Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
x402 server payer, agent wallet trade tab, Solana wallet handlers, club crowd, changelog
nirholasc1b09db601a9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 502e4dd8e..1962a3cab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Connect a wallet and your $THREE tier is recognized — no account needed** — You no longer need a three.ws account to be seen as a $THREE holder. Connect your Solana wallet and the site reads your tier straight from your on-chain holdings: the holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) and holder features like High-quality generation on Forge unlock from the connected wallet alone. When a feature needs proof the wallet is yours, you approve a single free signature that moves no funds. Switch or disconnect a wallet and your tier updates instantly, no reload. Signed-in accounts keep working exactly as before. (`/forge`) `[improvement]`- **Embedded 3D agents animate on any site, not just three.ws** — When you drop the <agent-3d> tag onto a page hosted somewhere other than three.ws, the avatar's gestures — waving, celebrating, thinking — silently failed to load: the animation clips were being requested from the host page's own domain instead of from three.ws, so each one came back as a 404. The component now resolves its animation library against three.ws no matter where it's embedded, so an agent reacts and emotes correctly on partner pages, live demos, and any third-party site. `[fix, sdk]`- **Faster marketplace — agent pages load skill prices from cache** — Agent and marketplace pages now feel snappier. A creator's skill prices are cached for an hour and shared across our servers instead of being re-read from the database on every single page view, so opening an agent, browsing the marketplace, or checking what a skill costs returns faster — especially for popular agents. The cache stays honest: the moment a creator changes a price the old value is cleared everywhere, so you always see the current price, and a purchase is still quoted against the exact price at checkout time. `[improvement, infra]`+- **Floor placement now works on iPhone — and holds up in the real world** — Placing your agent on the floor in AR got a big reach-and-reliability upgrade. It now works on iPhone too, through Apple's AR Quick Look, so you're no longer Android-only. Your agent is correctly hidden when something real — a couch, a wall, a person — passes in front of it, so it reads as actually being in the room. It reloads facing the exact direction you placed it, not rounded to the nearest few degrees, so you and anyone nearby see it the same way. And it now holds up to real life: if a call comes in, you lock your phone, or tracking briefly drops in low light, the session pauses and recovers cleanly, your agent stays anchored where you tapped, and your saved spot is written exactly once — never lost, never duplicated. On devices that can't lock a hardware anchor, we tell you honestly that it may drift rather than pretending it's rock-solid. (`/irl`) `[feature, improvement]`- **Forge always reaches for a free 3D engine first** — Text-to-3D and image-to-3D generation now exhaust the free engines before any paid one. A prompt is rendered on the free NVIDIA lane; if that's busy, the reference image is reconstructed into a mesh on a free engine too — the platform only reaches for a paid engine as a genuine last resort. And if every engine is briefly out of reach, you now get an honest "temporarily unavailable, try again shortly" instead of a confusing technical billing message. Same Forge, fewer dead ends, no surprise costs. (`/forge`) `[improvement, fix]`- **Forge checkout no longer dead-ends when generation is briefly busy** — When the 3D generator was momentarily rate-limited mid-checkout, Forge could show a raw technical error and look like the payment had failed for good. Now a brief upstream slowdown shows a clear message — your payment was not taken, and the generation retries in a few seconds — and the checkout auto-retries on its own before ever asking you to try again. Your payment only settles once the model is actually produced, so a busy moment never costs you anything. (`/forge`) `[fix]`- **Gasless checkout — buy skills and assets with no SOL in your wallet** — Buying a skill, time-pass, or whole asset no longer requires you to hold SOL for the network fee. When your Solana wallet is connected, three.ws now sponsors the transaction fee: the platform builds and pre-signs the payment, and your wallet only adds your own approval. You still pay the USDC price (and sellers still receive their split), but the tiny gas fee is on us — one fewer thing to top up before you check out. If sponsorship is ever unavailable, checkout falls back to the normal pay-your-own-gas flow automatically, so a purchase never gets blocked. `[feature, improvement]`@@ -40,6 +41,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The animated 3D bot in the site footer renders again** — The little animated 3D robot that sits in the footer across the site — and on the sign-in page — had gone missing, leaving an empty space. The model files it loads are compressed, but the footer loader wasn't set up to unpack that format, so it failed before the bot could appear. The decoder is now wired in, so the bot loads and spins as intended everywhere the footer shows. `[fix]`- **The disco dance floor in coin worlds works again** — Every coin world has a disco pad beside the totem that pulses to a shared beat and crossfades dancers in lockstep. A wiring gap meant the world tried to listen for a beat the connection didn't know about, which threw an error the moment you entered and left the pad dark. The beat is now delivered properly: step onto the pad, hit Dance, and you and everyone else standing on it move to the same animation on the same beat, with the floor and lights pulsing in time. (`/play`) `[fix]`- **The homepage avatar now prays, then walks** — Tap “🙏 Pray” on the homepage hero and the avatar finishes the prayer and rises straight into a walk — one smooth motion instead of snapping back to a standing idle at the end of the clip. After the walk plays out, the avatar eases back into its gentle idle-and-stroll rhythm. The other one-tap emotes (wave, dance, jump, and the rest) also return to that ambient motion now instead of freezing on their last frame. `[improvement]`+- **The Pole Club walk-in is full of people now** — Walking up to the Pole Club, you used to move through the alley, the gallery, and the clubhouse completely alone. Now every room is full: each one is populated with a live crowd built from our avatars — the bundled looks plus public avatars from the gallery — grounded on the floor and moving for real. Near the entrance they lean, chill, and idle; deeper in, more of them are dancing, so the energy builds as you get closer to the stage. The crowd lines your route instead of blocking it, and the head-count scales to your device so it stays smooth on phones and goes big on desktop. (`/club`) `[feature, improvement]`- **Tip a dancer for a Pole Twerk and she works the pole** — The Club stage has a new headline move: Pole Twerk, now the default style on every pole. Tip a dancer for it and instead of facing the crowd like the other styles, she turns into the pole and works it with her back to the room — a real pole-dancer twerk, not a free-floor one — set to its own track. Pick it (or any other style) from the dropdown on each pole before you tip; all the existing dances are still there. (`/club`) `[feature]`- **Tipping a dancer goes straight to the wallet now** — Tapping Tip in the Pole Club used to open a three-step “Before you go on-chain” explainer first, and dismissing it cancelled the tip entirely — so first-time visitors couldn't pay without sitting through the wizard. That gate is gone. Tip now opens the wallet-and-amount checkout directly, where you pick Phantom or a browser wallet, see the exact USDC amount, and approve with one signature. The checkout already shows everything the explainer did, so there's no reason to stack a lecture in front of a fraction-of-a-cent tip. (`/club`) `[improvement]`- **Tipping a dancer in the Club is now one tap** — In the Pole Club, paying a dancer used to pop an extra step that made you pick your wallet before anything happened — annoying when you just want to tip and watch her dance, and worse when tipping pole after pole. Now, when a single wallet is detected, hitting Tip goes straight to the signature: approve the $0.001 USDC and she takes the pole. The same shortcut applies to the cover charge at the door. If you have more than one wallet installed you still get to choose, and the free re-entry option for returning guests is untouched. (`/club`) `[improvement]`diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.jsindex 9b79af6b2..48f627be7 100644--- a/api/_lib/agent-trade-guards.js+++ b/api/_lib/agent-trade-guards.js@@ -546,7 +546,10 @@ export async function recordSpend(e) {* Read the agent's recent custody events for the owner-facing audit feed.* Cursor is the `id` of the last row seen (descending, so strictly-less-than).*/-export async function listCustodyEvents(agentId, { limit = 50, beforeId = null, network = null } = {}) {+export async function listCustodyEvents(+ agentId,+ { limit = 50, beforeId = null, network = null, category = null } = {},+) {const lim = Math.min(200, Math.max(1, Number(limit) || 50));const rows = await sql`SELECT id, event_type, category, network, asset, amount_lamports, amount_raw,@@ -554,6 +557,7 @@ export async function listCustodyEvents(agentId, { limit = 50, beforeId = null,FROM agent_custody_eventsWHERE agent_id = ${agentId}AND (${network}::text IS NULL OR network = ${network})+ AND (${category}::text IS NULL OR category = ${category})AND (${beforeId}::bigint IS NULL OR id < ${beforeId})ORDER BY id DESCLIMIT ${lim}diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.jsindex 0ed281177..d4cc42618 100644--- a/api/agents/solana-wallet.js+++ b/api/agents/solana-wallet.js@@ -842,11 +842,17 @@ async function handleHoldings(req, res, id) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;- const owned = await loadOwnedWallet(req, res, id);- if (owned.error) return;- const { auth, address } = owned;+ // Token balances are public on-chain data, so the holdings list is readable by+ // owner and visitor alike (the wallet hub's Trade tab shows a read-only holdings+ // view to visitors). Only the owner ever gets management actions, which live on+ // other endpoints. The owner path is unchanged; visitors get an IP-keyed read.+ const auth = await resolveAuth(req);+ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;+ if (!row) return error(res, 404, 'not_found', 'agent not found');+ const isOwner = !!(auth && row.user_id === auth.userId);+ const address = row.meta?.solana_address || null;- const rl = await limits.walletRead(auth.userId);+ const rl = await limits.walletRead(isOwner ? auth.userId : clientIp(req));if (!rl.success) return rateLimited(res, rl);if (!address) return error(res, 404, 'not_found', 'agent has no solana wallet');@@ -888,7 +894,7 @@ async function handleHoldings(req, res, id) {}tokens.sort((a, b) => Number(b.ui_amount) - Number(a.ui_amount));- return json(res, 200, { data: { address, network, sol, tokens } });+ return json(res, 200, { data: { address, network, sol, tokens, is_owner: isOwner } });}// ── custody audit trail ───────────────────────────────────────────────────────@@ -910,8 +916,12 @@ async function handleCustody(req, res, id) {const beforeRaw = url.searchParams.get('before');const beforeId = beforeRaw && /^\d+$/.test(beforeRaw) ? beforeRaw : null;const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : url.searchParams.get('network') === 'mainnet' ? 'mainnet' : null;+ // Optional category filter (e.g. 'x402') so a caller can read just the spends+ // of one kind — the Pay tab reads its own x402 payment activity this way.+ const categoryRaw = url.searchParams.get('category');+ const category = categoryRaw && /^[a-z0-9_]{1,32}$/i.test(categoryRaw) ? categoryRaw : null;- const events = await listCustodyEvents(id, { limit, beforeId, network });+ const events = await listCustodyEvents(id, { limit, beforeId, network, category });const items = events.map((e) => ({id: String(e.id),event_type: e.event_type,@@ -927,6 +937,9 @@ async function handleCustody(req, res, id) {reason: e.reason,status: e.status,created_at: e.created_at,+ // meta carries the x402 service/url + resource for the payment activity+ // row; this endpoint is ownership-gated so it's owner-only data already.+ meta: e.meta && typeof e.meta === 'object' ? e.meta : null,}));const nextCursor = items.length === limit ? items[items.length - 1].id : null;return json(res, 200, { data: { items, next_cursor: nextCursor } });@@ -987,6 +1000,14 @@ export default async function handler(req, res, id, action) {if (action === 'holdings') return handleHoldings(req, res, id);if (action === 'custody') return handleCustody(req, res, id);if (action === 'limits') return handleLimits(req, res, id);+ if (action === 'trade') {+ const mod = await import('./solana-trade.js');+ return mod.handleTrade(req, res, id);+ }+ if (action === 'trade-history') {+ const mod = await import('./solana-trade.js');+ return mod.handleTradeHistory(req, res, id);+ }return handleWallet(req, res, id);}diff --git a/api/x402-pay.js b/api/x402-pay.jsindex 1ab2fe4b2..540b06f3f 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -48,6 +48,8 @@ import { logger } from './_lib/usage.js';import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';import { recoverSolanaAgentKeypair } from './_lib/agent-wallet.js';import { enforceSpendLimit, SpendLimitError, recordSpend } from './_lib/agent-trade-guards.js';+import { validatePublicUrl, resolvePublicHost, pinnedAgent, SsrfError } from './_lib/ssrf.js';+import { BUILDER_CODE } from './_lib/x402-builder-code.js';const log = logger('x402-pay');@@ -177,6 +179,19 @@ async function requireAuth(req) {return null;}+// Decide which wallet signs an x402 payment. An agent context — an `agentId`+// on the request, which the wallet hub always sends and any authenticated owner+// call carries — ALWAYS pays from that agent's own custodial wallet. The shared+// platform wallet (X402_AGENT_SOLANA_SECRET_BASE58) is an explicit fallback for+// platform-level/demo calls that carry no agent context. The handler logs that+// fallback so a regression where an agent call drops its agentId is visible in+// the logs instead of silently spending the shared wallet on the agent's behalf.+export function resolvePayerRouting(input) {+ const agentId = input && input.agentId ? String(input.agentId) : '';+ if (agentId) return { mode: 'agent', agentId };+ return { mode: 'platform' };+}+async function loadAgentKeypairForUser(agentId, userId) {const [row] = await sql`SELECT id, meta FROM agent_identities@@ -374,6 +389,278 @@ async function buildSolanaPaymentPayload({ accept, buyer, conn, resourceUrl }) {};}+// ── External x402 endpoint pay (wallet hub "Pay" tab) ─────────────────────+// Pays an ARBITRARY x402 endpoint discovered via the bazaar from the agent's+// own Solana wallet. Distinct from runFlow (which pays the platform's own MCP):+// here the 402 challenge, payTo, asset and feePayer all come from the external+// resource server, and that server — not us — verifies + settles. We only build+// and sign the SPL transfer with the agent key and present it as X-PAYMENT.++const EXTERNAL_FETCH_TIMEOUT_MS = 30_000;++// SSRF-guarded one-shot fetch of an untrusted URL: https-only (http in dev),+// DNS resolved + checked against the private-range blocklist, the socket pinned+// to the validated addresses (closes the DNS-rebinding TOCTOU), redirects never+// followed into an internal target. Returns { status, ok, headers, text }.+// Throws SsrfError on a blocked target.+async function guardedFetch(rawUrl, { method = 'GET', headers = {}, body } = {}) {+ const url = validatePublicUrl(rawUrl);+ const addrs = await resolvePublicHost(url.hostname);+ const agent = pinnedAgent(url.hostname, addrs);+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), EXTERNAL_FETCH_TIMEOUT_MS);+ try {+ const res = await fetch(url, {+ method,+ redirect: 'manual',+ signal: controller.signal,+ dispatcher: agent,+ headers: {+ 'user-agent': '3d-agent-x402/1.0 (+https://three.ws/)',+ accept: 'application/json, text/plain;q=0.8, */*;q=0.5',+ ...(body != null ? { 'content-type': 'application/json' } : {}),+ ...headers,+ },+ ...(body != null+ ? { body: typeof body === 'string' ? body : JSON.stringify(body) }+ : {}),+ });+ const text = await res.text();+ return { status: res.status, ok: res.ok, headers: res.headers, text };+ } finally {+ clearTimeout(timer);+ await agent.close().catch(() => {});+ }+}++function safeJsonParse(text) {+ if (typeof text !== 'string' || !text) return null;+ try {+ return JSON.parse(text);+ } catch {+ return null;+ }+}++function b64decodeJson(s) {+ if (!s) return null;+ try {+ return JSON.parse(Buffer.from(String(s), 'base64').toString('utf8'));+ } catch {+ return null;+ }+}++// Probe an external x402 endpoint for its payment requirements WITHOUT paying.+// Returns the parsed 402 challenge + the Solana accept (the only network an+// agent wallet can pay), { free: true } when the endpoint served a result+// without a 402, or { unsupported: true, networks } when it has no Solana accept.+async function probeExternalRequirements({ url, method, body }) {+ let res;+ try {+ res = await guardedFetch(url, { method, body });+ } catch (err) {+ if (err instanceof SsrfError) {+ throw Object.assign(new Error('that endpoint is not a reachable public https URL'), {+ status: 400,+ code: 'blocked_url',+ });+ }+ throw Object.assign(+ new Error(`could not reach the service: ${err?.message || 'network error'}`),+ { status: 502, code: 'endpoint_unreachable' },+ );+ }+ if (res.status !== 402) {+ // The endpoint returned without challenging for payment — nothing to pay.+ return { free: true, status: res.status, result: safeJsonParse(res.text) ?? res.text };+ }+ const challenge = safeJsonParse(res.text) || b64decodeJson(res.headers.get('payment-required'));+ if (!challenge || !Array.isArray(challenge.accepts)) {+ throw Object.assign(new Error('the service returned an unreadable payment challenge'), {+ status: 502,+ code: 'invalid_challenge',+ });+ }+ const solAccept = challenge.accepts.find(+ (a) => typeof a?.network === 'string' && a.network.startsWith('solana'),+ );+ if (!solAccept) {+ const networks = [...new Set(challenge.accepts.map((a) => a?.network).filter(Boolean))];+ return { unsupported: true, networks, challenge };+ }+ const resource =+ challenge.resource && typeof challenge.resource === 'object'+ ? challenge.resource+ : { url: typeof challenge.resource === 'string' ? challenge.resource : url };+ return { challenge, accept: solAccept, resource };+}++// Echo the builder-code app tag the challenge declared so the external server's+// on-chain attribution is honoured (mirrors x402-buyer-fetch.ensureBuilderCodeEcho).+function echoBuilderCode(challenge, paymentPayload) {+ const declaredA = challenge?.extensions?.[BUILDER_CODE]?.info?.a;+ if (!declaredA) return paymentPayload;+ const existing = paymentPayload.extensions || {};+ const block = { ...(existing[BUILDER_CODE] || {}), a: declaredA };+ if (env.X402_BUILDER_CODE_WALLET && !block.w) block.w = env.X402_BUILDER_CODE_WALLET;+ paymentPayload.extensions = { ...existing, [BUILDER_CODE]: block };+ return paymentPayload;+}++// Summarize the resource a probe surfaced for the SSE 'challenge'/'result' events+// and the spend ledger — never trust raw fields into innerHTML on the client.+function resourceSummary(probe, fallbackUrl) {+ const r = probe.resource || {};+ return {+ url: r.url || fallbackUrl,+ description: typeof r.description === 'string' ? r.description : null,+ serviceName: typeof r.serviceName === 'string' ? r.serviceName : null,+ };+}++// Run the full external-endpoint pay flow, emitting the same SSE event vocabulary+// the internal flow uses (challenge → built → settled → result) so the client can+// render one progress timeline. `buyer` is the agent's recovered keypair.+async function runExternalFlow({ url, method, body, emit, buyer, spendGuard, serviceLabel }) {+ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });++ const probe = await probeExternalRequirements({ url, method, body });+ if (probe.free) {+ emit('result', { ok: true, free: true, result: probe.result, payment: null });+ return;+ }+ if (probe.unsupported) {+ throw Object.assign(+ new Error('this service does not accept Solana USDC — agent wallets pay in Solana USDC'),+ { status: 422, code: 'no_solana_accept', detail: { networks: probe.networks } },+ );+ }+ const accept = probe.accept;+ if (!accept.extra?.feePayer) {+ throw Object.assign(+ new Error('the service did not advertise a Solana fee payer, so it cannot be paid from here'),+ { status: 422, code: 'missing_fee_payer' },+ );+ }+ const resource = resourceSummary(probe, url);+ const spendUsd = Number(accept.amount) / 1e6;+ const t0 = Date.now();+ emit('challenge', {+ network: accept.network,+ amount: accept.amount,+ asset: accept.asset,+ payTo: accept.payTo,+ price_usdc: spendUsd,+ resource,+ });++ // Per-agent spend policy — enforced BEFORE the payment is built/signed so a+ // breach moves no funds.+ if (spendGuard) {+ try {+ await enforceSpendLimit({+ agentId: spendGuard.agentId,+ meta: spendGuard.meta,+ category: 'x402',+ usdValue: spendUsd,+ destination: accept.payTo,+ network: 'mainnet',+ });+ } catch (e) {+ if (e instanceof SpendLimitError) {+ throw Object.assign(new Error(e.message), { status: e.status, code: e.code, detail: e.detail });+ }+ throw e;+ }+ }++ const paymentPayload = await buildSolanaPaymentPayload({+ accept,+ buyer,+ conn,+ resourceUrl: resource.url,+ });+ echoBuilderCode(probe.challenge, paymentPayload);+ const tBuilt = Date.now();+ emit('built', { build_ms: tBuilt - t0 });++ const xPayment = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');+ let paid;+ try {+ paid = await guardedFetch(url, { method, body, headers: { 'X-PAYMENT': xPayment } });+ } catch (err) {+ // The signed payment went out but we never saw the response — the chain+ // state is unknown, so do NOT promise the wallet was untouched.+ throw Object.assign(+ new Error('the payment was submitted but its status could not be confirmed — check the wallet activity before retrying'),+ { status: 502, code: 'settle_uncertain', cause: err },+ );+ }+ const paidJson = safeJsonParse(paid.text) ?? paid.text;+ if (!paid.ok) {+ if (paid.status === 402) {+ throw Object.assign(+ new Error('the service rejected the payment before settlement; no funds were transferred'),+ { status: 402, code: 'payment_required', detail: typeof paidJson === 'object' ? paidJson : null },+ );+ }+ throw Object.assign(+ new Error(`the service returned an error after payment (HTTP ${paid.status}); check the wallet activity before retrying`),+ { status: 502, code: 'settle_uncertain', detail: typeof paidJson === 'object' ? paidJson : null },+ );+ }+ const settled = b64decodeJson(paid.headers.get('x-payment-response'));+ const tx = settled?.transaction || null;+ const payer = settled?.payer || buyer.publicKey.toBase58();+ const tSettled = Date.now();+ emit('settled', {+ settle_ms: tSettled - tBuilt,+ tx,+ network: settled?.network || accept.network,+ payer,+ explorer: tx ? `https://solscan.io/tx/${tx}` : null,+ });++ // Record the agent's x402 spend into the shared custody ledger so it counts+ // toward the per-agent daily ceiling and shows in the wallet's payment activity.+ if (spendGuard) {+ void recordSpend({+ agentId: spendGuard.agentId,+ userId: spendGuard.userId,+ category: 'x402',+ network: 'mainnet',+ asset: 'USDC',+ usd: spendUsd,+ destination: accept.payTo,+ signature: tx,+ status: tx ? 'confirmed' : 'ok',+ meta: {+ url,+ service: serviceLabel || resource.serviceName || null,+ resource: resource.url,+ },+ }).catch((err) => log.warn('x402_external_spend_record_failed', { message: err?.message }));+ }++ emit('result', {+ ok: true,+ result: paidJson,+ payment: {+ network: settled?.network || accept.network,+ payer,+ payTo: accept.payTo,+ asset: accept.asset,+ amount: accept.amount,+ tx,+ explorer: tx ? `https://solscan.io/tx/${tx}` : null,+ },+ receipt: settled,+ resource,+ durations: { build_ms: tBuilt - t0, settle_ms: tSettled - tBuilt, total_ms: tSettled - t0 },+ });+}+async function getAgentBalance() {const buyer = loadAgentKeypair();const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });@@ -562,8 +849,10 @@ function payErrorEnvelope(err) {let error_description;if (code === 'facilitator_unreachable' || code === 'facilitator_error' || code === 'settle_failed') {error_description = 'Payment could not be completed and no funds were transferred from the agent wallet. Please try again.';- } else if (code === 'facilitator_bad_response') {- error_description = 'Payment status could not be confirmed. Check the payment feed before retrying to avoid paying twice.';+ } else if (code === 'facilitator_bad_response' || code === 'settle_uncertain') {+ error_description = 'Payment status could not be confirmed. Check the payment activity before retrying to avoid paying twice.';+ } else if (code === 'no_solana_accept' || code === 'missing_fee_payer' || code === 'endpoint_unreachable' || code === 'invalid_challenge' || code === 'blocked_url') {+ error_description = 'No payment was attempted, so no funds were transferred from the agent wallet.';} else if (code === 'invalid_payment' || code === 'payment_required' || code === 'builder_code_tampered') {error_description = 'The payment was rejected before settlement; no funds were transferred.';}@@ -586,6 +875,117 @@ function payErrorStatus(err) {return 500;}+// Pay an arbitrary external x402 endpoint from the owner's agent wallet. This is+// the money core behind the wallet hub Pay tab. Owner-authenticated + ownership-+// gated; the agent key is decrypted server-side via recoverSolanaAgentKeypair+// (audit-logged) and never leaves the server. Two modes:+// { preview: true } — probe requirements only (no funds moved, no key signs).+// default — full pay; SSE-streams progress when the client asks.+async function handleExternalPay(req, res, input, ip) {+ const auth = await requireAuth(req);+ if (!auth) return json(res, 401, { error: 'authentication_required' });+ const agentId = input.agentId ? String(input.agentId) : '';+ if (!agentId) {+ // An external pay with no agent context would have no wallet to pay from —+ // never silently reach for the shared platform wallet here.+ log.warn('external_pay_missing_agent', { ip });+ return json(res, 400, {+ error: 'agent_required',+ error_description: 'paying a service requires an agent context',+ });+ }++ const loaded = await loadAgentKeypairForUser(agentId, auth.userId);+ if (!loaded) return json(res, 403, { error: 'agent_not_found_or_no_solana_wallet' });++ const method =+ typeof input.method === 'string' && /^(GET|POST|PUT|PATCH|DELETE)$/i.test(input.method)+ ? input.method.toUpperCase()+ : 'GET';+ const body = input.body != null ? input.body : undefined;++ // Preview: surface the live price + what's being bought before the owner+ // confirms. Moves no funds.+ if (input.preview === true) {+ try {+ const probe = await probeExternalRequirements({ url: input.url, method, body });+ if (probe.free) {+ return json(res, 200, { ok: true, requires_payment: false, status: probe.status });+ }+ if (probe.unsupported) {+ return json(res, 200, {+ ok: true,+ requires_payment: true,+ payable: false,+ code: 'no_solana_accept',+ networks: probe.networks,+ });+ }+ const accept = probe.accept;+ const resource = resourceSummary(probe, input.url);+ return json(res, 200, {+ ok: true,+ requires_payment: true,+ payable: !!accept.extra?.feePayer,+ ...(accept.extra?.feePayer ? {} : { code: 'missing_fee_payer' }),+ network: accept.network,+ amount: accept.amount,+ asset: accept.asset,+ payTo: accept.payTo,+ price_usdc: Number(accept.amount) / 1e6,+ resource,+ method,+ });+ } catch (err) {+ return json(res, payErrorStatus(err), payErrorEnvelope(err));+ }+ }++ const spendGuard = { agentId, userId: auth.userId, meta: loaded.meta, network: 'mainnet' };+ const wantsStream =+ (req.headers.accept || '').includes('text/event-stream') || input.stream === true;++ if (wantsStream) {+ sseInit(res);+ const emit = (ev, data) => sseSend(res, ev, data);+ try {+ await runExternalFlow({+ url: input.url,+ method,+ body,+ emit,+ buyer: loaded.keypair,+ spendGuard,+ serviceLabel: typeof input.service_label === 'string' ? input.service_label : null,+ });+ } catch (err) {+ emit('error', payErrorEnvelope(err));+ } finally {+ res.end();+ }+ return;+ }++ let final = null;+ const emit = (ev, data) => {+ if (ev === 'result') final = data;+ };+ try {+ await runExternalFlow({+ url: input.url,+ method,+ body,+ emit,+ buyer: loaded.keypair,+ spendGuard,+ serviceLabel: typeof input.service_label === 'string' ? input.service_label : null,+ });+ } catch (err) {+ return json(res, payErrorStatus(err), payErrorEnvelope(err));+ }+ return json(res, 200, final);+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;@@ -642,24 +1042,38 @@ export default wrap(async (req, res) => {}const input = await readJson(req, 50_000);++ // External x402 endpoint pay (wallet hub Pay tab): a target `url` means an+ // arbitrary bazaar service paid from the agent's OWN wallet — never the shared+ // platform wallet. Owner-authenticated, per-agent spend policy enforced.+ if (typeof input.url === 'string' && input.url) {+ return handleExternalPay(req, res, input, ip);+ }+const tool = String(input.tool || '');const args = input.args && typeof input.args === 'object' ? input.args : {};if (!ALLOWED_TOOLS.has(tool)) {return json(res, 400, { error: 'invalid_tool', allowed: [...ALLOWED_TOOLS] });}- // Resolve payer: agent wallet (agentId + authed) or shared showcase wallet.+ // Resolve payer. An agent context (agentId) ALWAYS pays from that agent's own+ // wallet; the shared showcase wallet is the explicit, logged fallback for+ // platform/demo calls with no agent context (see resolvePayerRouting).+ const routing = resolvePayerRouting(input);let buyer;let spendGuard = null;- if (input.agentId) {+ if (routing.mode === 'agent') {const auth = await requireAuth(req);if (!auth) return json(res, 401, { error: 'authentication_required' });- const loaded = await loadAgentKeypairForUser(String(input.agentId), auth.userId);+ const loaded = await loadAgentKeypairForUser(routing.agentId, auth.userId);if (!loaded) return json(res, 403, { error: 'agent_not_found_or_no_solana_wallet' });buyer = loaded.keypair;// Per-agent spend policy applies to x402 just like trade/snipe/withdraw.- spendGuard = { agentId: String(input.agentId), userId: auth.userId, meta: loaded.meta, network: 'mainnet' };+ spendGuard = { agentId: routing.agentId, userId: auth.userId, meta: loaded.meta, network: 'mainnet' };} else {+ // No agent context — fall back to the shared platform wallet, but log it so+ // a regression that drops agentId off an agent call is visible, not silent.+ log.warn('platform_wallet_fallback', { tool, reason: 'no_agent_context', ip });try {buyer = loadAgentKeypair();} catch (err) {diff --git a/data/changelog.json b/data/changelog.jsonindex ca7db8b6c..87d894771 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$comment": "Curated changelog entries for three.ws \u2014 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-18",+ "title": "The Pole Club walk-in is full of people now",+ "summary": "Walking up to the Pole Club, you used to move through the alley, the gallery, and the clubhouse completely alone. Now every room is full: each one is populated with a live crowd built from our avatars — the bundled looks plus public avatars from the gallery — grounded on the floor and moving for real. Near the entrance they lean, chill, and idle; deeper in, more of them are dancing, so the energy builds as you get closer to the stage. The crowd lines your route instead of blocking it, and the head-count scales to your device so it stays smooth on phones and goes big on desktop.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/club"+ },+ {+ "date": "2026-06-18",+ "title": "Floor placement now works on iPhone — and holds up in the real world",+ "summary": "Placing your agent on the floor in AR got a big reach-and-reliability upgrade. It now works on iPhone too, through Apple's AR Quick Look, so you're no longer Android-only. Your agent is correctly hidden when something real — a couch, a wall, a person — passes in front of it, so it reads as actually being in the room. It reloads facing the exact direction you placed it, not rounded to the nearest few degrees, so you and anyone nearby see it the same way. And it now holds up to real life: if a call comes in, you lock your phone, or tracking briefly drops in low light, the session pauses and recovers cleanly, your agent stays anchored where you tapped, and your saved spot is written exactly once — never lost, never duplicated. On devices that can't lock a hardware anchor, we tell you honestly that it may drift rather than pretending it's rock-solid.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/irl"+ },{"date": "2026-06-18","title": "Placing an agent on the floor feels solid now",diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.htmlindex 5a9a84688..4e4203fe7 100644--- a/pages/ibm/x402-demo.html+++ b/pages/ibm/x402-demo.html@@ -245,6 +245,7 @@ a:focus-visible{outline-offset:3px}.note svg{flex:0 0 auto;width:20px;height:20px;color:var(--ibm-blue);margin-top:1px}.note p{font-size:13px;color:var(--ibm-muted);line-height:1.6;font-weight:300}.note p b{color:var(--ibm-ink);font-weight:600}+.note-aside{display:block;margin-top:8px;padding-top:8px;border-top:1px solid var(--ibm-border);color:var(--ibm-subtle);font-size:12px}/* ── Forge demo (Demo 03): tier selector, model viewer, result actions ── */.tier-row{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px}@@ -594,7 +595,7 @@ agent-3d:defined ~ .agent-skel{display:none}<!-- requirements --><div class="note"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>- <p>You'll need a browser wallet — <b>MetaMask</b> (Base) or <b>Phantom</b> (Solana) — holding at least <b>$0.001 USDC</b> on mainnet. This spends <b>real USDC</b> — one tenth of a cent — from your own wallet. The payment itself is a gasless signature: the network fee is sponsored by the x402 facilitator, so it isn't added to your cost (it isn't zero, just not yours to pay). No wallet? You can still watch the live 402 challenge above and read the <a href="https://three.ws/docs/x402" target="_blank" rel="noopener">protocol docs</a>.</p>+ <p>You'll need a browser wallet — <b>MetaMask</b> (Base) or <b>Phantom</b> (Solana) — holding at least <b>$0.001 USDC</b> on mainnet. This spends <b>real USDC</b> — one tenth of a cent — from your own wallet. The payment itself is a gasless signature: the network fee is sponsored by the x402 facilitator, so it isn't added to your cost (it isn't zero, just not yours to pay). No wallet? You can still watch the live 402 challenge above and read the <a href="https://three.ws/docs/x402" target="_blank" rel="noopener">protocol docs</a>. <span class="note-aside">Paying with <b>MetaMask</b> on Base is fully self-contained — it talks only to three.ws. Paying with <b>Phantom</b> on Solana additionally loads a small library from <span class="mono">esm.sh</span>; if a strict host security policy blocks it, the Solana button reports it clearly and the Base path keeps working.</span></p></div></div></div>@@ -869,8 +870,10 @@ agent-3d:defined ~ .agent-skel{display:none}var iframe = document.createElement('iframe');iframe.title = embed.getAttribute('data-label') || 'three.ws demo';iframe.loading = 'lazy';+ // `data-allow` already carries `fullscreen`, which is the modern Permissions-Policy+ // way to grant it; adding the legacy `allowfullscreen` attribute too just makes the+ // browser warn that `allow` takes precedence, so we rely on `allow` alone.iframe.setAttribute('allow', embed.getAttribute('data-allow') || '');- iframe.setAttribute('allowfullscreen', '');iframe.setAttribute('referrerpolicy', 'no-referrer-when-downgrade');var timer = setTimeout(function () {if (!embed.classList.contains('loaded')) embed.classList.add('failed');@@ -1221,6 +1224,28 @@ agent-3d:defined ~ .agent-skel{display:none}// Networks the live 402 challenge is quoting, for specific error guidance.var quotedNetworks = '';+ // model-viewer is heavy (~955 KB, bundles its own Three.js) and only needed once+ // a model has actually been forged. Load it lazily, self-hosted from ./vendor/, so+ // a page view that never forges pays nothing for it and its Three.js never co-exists+ // with the agent's at idle. Injected <model-viewer> elements upgrade automatically+ // once the module defines the custom element; a blocked/failed load never wedges the+ // result UI (the GLB download link still works).+ var _mvLoading = null;+ function ensureModelViewer() {+ if (_mvLoading) return _mvLoading;+ _mvLoading = new Promise(function (resolve) {+ if (window.customElements && customElements.get('model-viewer')) { resolve(); return; }+ var s = document.createElement('script');+ s.type = 'module';+ s.src = './vendor/model-viewer.min.js';+ s.addEventListener('error', resolve);+ document.head.appendChild(s);+ if (window.customElements) customElements.whenDefined('model-viewer').then(resolve, resolve);+ else resolve();+ });+ return _mvLoading;+ }+function escapeHtml(s) {return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];@@ -1398,6 +1423,7 @@ agent-3d:defined ~ .agent-skel{display:none}announce('Error: ' + text + (tip ? ' ' + tip : ''));}function setResultGenerating(payment, etaSec, startTs) {+ ensureModelViewer(); // warm the viewer during the generation wait so the result paints instantlyvar el = $('fgResult'); el.className = 'result is-loading';el.innerHTML ='<div class="r-status"><span class="spin" aria-hidden="true"></span><span id="fgGenText">Payment settled — forging your model…</span></div>' +@@ -1413,6 +1439,7 @@ agent-3d:defined ~ .agent-skel{display:none}}function setResultDone(glbUrl, payment, meta) {clearInterval(genTimer);+ ensureModelViewer(); // covers the synchronous-finish path where generation never streamedvar el = $('fgResult'); el.className = 'result is-done';var explorer = explorerUrl(payment.network, payment.transaction);var safeGlb = escapeHtml(glbUrl);diff --git a/public/changelog.json b/public/changelog.jsonindex 32102c86c..c43d02ae2 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T09:21:16.302Z",+ "generated_at": "2026-06-18T09:26:45.826Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -59,6 +59,17 @@"infra"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Floor placement now works on iPhone — and holds up in the real world",+ "summary": "Placing your agent on the floor in AR got a big reach-and-reliability upgrade. It now works on iPhone too, through Apple's AR Quick Look, so you're no longer Android-only. Your agent is correctly hidden when something real — a couch, a wall, a person — passes in front of it, so it reads as actually being in the room. It reloads facing the exact direction you placed it, not rounded to the nearest few degrees, so you and anyone nearby see it the same way. And it now holds up to real life: if a call comes in, you lock your phone, or tracking briefly drops in low light, the session pauses and recovers cleanly, your agent stays anchored where you tapped, and your saved spot is written exactly once — never lost, never duplicated. On devices that can't lock a hardware anchor, we tell you honestly that it may drift rather than pretending it's rock-solid.",+ "link": "/irl",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-18","type": "update",@@ -358,6 +369,17 @@"improvement"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "The Pole Club walk-in is full of people now",+ "summary": "Walking up to the Pole Club, you used to move through the alley, the gallery, and the clubhouse completely alone. Now every room is full: each one is populated with a live crowd built from our avatars — the bundled looks plus public avatars from the gallery — grounded on the floor and moving for real. Near the entrance they lean, chill, and idle; deeper in, more of them are dancing, so the energy builds as you get closer to the stage. The crowd lines your route instead of blocking it, and the head-count scales to your device so it stays smooth on phones and goes big on desktop.",+ "link": "/club",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-18","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex cac3ba0d5..bbaf69c46 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -46,6 +46,14 @@<category>improvement</category><description>Agent and marketplace pages now feel snappier. A creator's skill prices are cached for an hour and shared across our servers instead of being re-read from the database on every single page view, so opening an agent, browsing the marketplace, or checking what a skill costs returns faster — especially for popular agents. The cache stays honest: the moment a creator changes a price the old value is cleared everywhere, so you always see the current price, and a purchase is still quoted against the exact price at checkout time.</description></item>+ <item>+ <title>Floor placement now works on iPhone — and holds up in the real world</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-18:Floor placement now works on iPhone — and holds up in the real world</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Placing your agent on the floor in AR got a big reach-and-reliability upgrade. It now works on iPhone too, through Apple's AR Quick Look, so you're no longer Android-only. Your agent is correctly hidden when something real — a couch, a wall, a person — passes in front of it, so it reads as actually being in the room. It reloads facing the exact direction you placed it, not rounded to the nearest few degrees, so you and anyone nearby see it the same way. And it now holds up to real life: if a call comes in, you lock your phone, or tracking briefly drops in low light, the session pauses and recovers cleanly, your agent stays anchored where you tapped, and your saved spot is written exactly once — never lost, never duplicated. On devices that can't lock a hardware anchor, we tell you honestly that it may drift rather than pretending it's rock-solid.</description>+ </item><item><title>Forge always reaches for a free 3D engine first</title><link>https://three.ws/forge</link>@@ -278,6 +286,14 @@<category>improvement</category><description>Tap “🙏 Pray” on the homepage hero and the avatar finishes the prayer and rises straight into a walk — one smooth motion instead of snapping back to a standing idle at the end of the clip. After the walk plays out, the avatar eases back into its gentle idle-and-stroll rhythm. The other one-tap emotes (wave, dance, jump, and the rest) also return to that ambient motion now instead of freezing on their last frame.</description></item>+ <item>+ <title>The Pole Club walk-in is full of people now</title>+ <link>https://three.ws/club</link>+ <guid isPermaLink="false">2026-06-18:The Pole Club walk-in is full of people now</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Walking up to the Pole Club, you used to move through the alley, the gallery, and the clubhouse completely alone. Now every room is full: each one is populated with a live crowd built from our avatars — the bundled looks plus public avatars from the gallery — grounded on the floor and moving for real. Near the entrance they lean, chill, and idle; deeper in, more of them are dancing, so the energy builds as you get closer to the stage. The crowd lines your route instead of blocking it, and the head-count scales to your device so it stays smooth on phones and goes big on desktop.</description>+ </item><item><title>Tip a dancer for a Pole Twerk and she works the pole</title><link>https://three.ws/club</link>diff --git a/public/features.json b/public/features.jsonindex 3b6a4d57d..6119ac8de 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T09:21:16.269Z",+ "generated_at": "2026-06-18T09:26:45.801Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/x402.js b/public/x402.jsindex f136ed60b..48709ea23 100644--- a/public/x402.js+++ b/public/x402.js@@ -1380,6 +1380,13 @@ function friendlyError(err) {if (/throttl|rate.?limit|too many requests|less than \$|in credit|\b429\b/i.test(msg)) {return 'The service is briefly busy and your payment was not taken — retry in a few seconds.';}+ // The Solana and EVM-sign-in paths dynamic-import a library from esm.sh. A strict+ // host Content-Security-Policy (or esm.sh being unreachable) blocks that import and+ // the raw "Failed to fetch dynamically imported module" is opaque. The Base/EIP-3009+ // payment path has no such dependency, so steer the buyer there.+ if (/dynamically imported module|esm\.sh|module script failed/i.test(msg)) {+ return 'A component this wallet path needs (loaded from esm.sh) was blocked — often by a strict host security policy. Pay with MetaMask on Base instead; it needs no third-party code.';+ }return msg.slice(0, 240);}diff --git a/scripts/ibm-csp-test.mjs b/scripts/ibm-csp-test.mjsindex f6a19fbe7..4cbdb5d0e 100644--- a/scripts/ibm-csp-test.mjs+++ b/scripts/ibm-csp-test.mjs@@ -34,12 +34,11 @@ const TIER1 = oneLine(`const TIER2 = oneLine(`default-src 'none';- script-src 'self' https://three.ws https://esm.sh 'unsafe-inline';- connect-src https://three.ws https://assets.three.ws https://esm.sh;+ script-src 'self' https://three.ws https://esm.sh 'unsafe-inline' 'wasm-unsafe-eval';+ connect-src 'self' blob: https://three.ws https://esm.sh;style-src 'self' 'unsafe-inline';font-src 'self';- img-src 'self' data: blob: https://three.ws https://assets.three.ws;- media-src 'self' blob: https://three.ws https://assets.three.ws;+ img-src 'self' data: blob: https://three.ws;worker-src 'self' blob:;frame-src https://three.ws;base-uri 'self';@@ -128,14 +127,18 @@ async function scrollThrough(page) {}function report(name, rec, { expectClean = true } = {}) {- const errs = rec.console.filter((c) => c.type === 'error').map((c) => c.text);+ const allErrs = rec.console.filter((c) => c.type === 'error').map((c) => c.text);+ // The demo INTENTIONALLY fetch()es the live 402/401 challenge to render it; Chromium+ // logs every non-2xx fetch to the console. These are expected protocol reads, not faults.+ const expected = allErrs.filter((e) => /the server responded with a status of 40[12]\b/.test(e));+ const errs = allErrs.filter((e) => !expected.includes(e));const warns = rec.console.filter((c) => c.type === 'warning').map((c) => c.text);// Network failures to three.ws RPC endpoints the agent probes are not page bugs// unless they are CSP-blocked; flag only blocked/refused ones distinctly.const cspCount = rec.csp.length;console.log(`\n──────── ${name} ────────`);console.log(`origins touched: ${[...rec.origins].sort().join(' ')}`);- console.log(`console errors: ${errs.length} | warnings: ${warns.length} | CSP violations: ${cspCount} | pageerrors: ${rec.errors.length}`);+ console.log(`real console errors: ${errs.length} | expected 402/401 reads: ${expected.length} | warnings: ${warns.length} | CSP violations: ${cspCount} | pageerrors: ${rec.errors.length}`);if (cspCount) { console.log(' CSP VIOLATIONS:'); rec.csp.slice(0, 40).forEach((c) => console.log(' • ' + c.slice(0, 200))); }if (errs.length) { console.log(' ERRORS:'); errs.slice(0, 30).forEach((e) => console.log(' • ' + e.slice(0, 200))); }if (rec.errors.length) { console.log(' PAGEERRORS:'); rec.errors.slice(0, 20).forEach((e) => console.log(' • ' + e.slice(0, 200))); }@@ -212,10 +215,13 @@ async function main() {await run('2. Tier 2 (full) / full page / top-level', {url: `http://127.0.0.1:${PORT_HOST}/x402-demo.html`, csp: TIER2,postCheck: async (page, rec) => {+ // model-viewer is lazy now — it is NOT expected to be defined until a model is+ // forged (validated standalone in scenario 6). Here we confirm the rest is clean.const mvDefined = await page.evaluate(() => !!customElements.get('model-viewer'));const fontReq = rec.requests.some((u) => /\/fonts\/IBMPlex/.test(u));+ const wmOk = !rec.console.some((c) => /watermark/i.test(c.text));const x402 = await page.evaluate(() => !!(window.X402 && typeof window.X402.pay === 'function'));- console.log(` checks: model-viewer defined=${mvDefined} | self-host font fetched=${fontReq} | window.X402.pay=${x402}`);+ console.log(` checks: model-viewer lazy(undef at idle)=${!mvDefined} | self-host font fetched=${fontReq} | no watermark error=${wmOk} | window.X402.pay=${x402}`);},});diff --git a/src/agent-solana-wallet.js b/src/agent-solana-wallet.jsindex eaf423918..8bd00b0f5 100644--- a/src/agent-solana-wallet.js+++ b/src/agent-solana-wallet.js@@ -120,6 +120,103 @@ export async function requestAgentSolanaAirdrop(agentId) {return json.data;}+// ── discretionary trading (agent-wallet pump.fun buy/sell) ────────────────────++/** Structured trade error: carries the endpoint's machine code + recovery detail. */+export class TradeError extends Error {+ constructor(message, { code = 'error', status = 0, detail = null } = {}) {+ super(message);+ this.name = 'TradeError';+ this.code = code;+ this.status = status;+ this.detail = detail;+ }+}++async function postTrade(agentId, body) {+ const url = `/api/agents/${encodeURIComponent(agentId)}/solana/trade`;+ let resp;+ try {+ resp = await fetch(url, {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ } catch {+ throw new TradeError('Network unreachable — check your connection and try again.', { code: 'network_error' });+ }+ const json = await resp.json().catch(() => ({}));+ // The API error envelope is { error: <code>, error_description: <message>, ...detail }.+ // A 202 "submitted but unconfirmed" is a 2xx that still carries that envelope, so+ // treat any payload with no `data` and an `error` code as a non-final outcome.+ const hasError = !resp.ok || (json && json.error != null && json.data == null);+ if (hasError) {+ const code = typeof json.error === 'string' ? json.error : json?.error?.code || 'error';+ const message =+ json?.error_description ||+ (typeof json.error === 'object' ? json.error?.message : null) ||+ `Trade failed (${resp.status})`;+ const detail = { ...json };+ delete detail.error;+ delete detail.error_description;+ throw new TradeError(message, { code, status: resp.status, detail });+ }+ return json.data;+}++/**+ * Live, non-binding quote for a discretionary trade. Returns expected output,+ * price impact, minimum received, fee context, the wallet's SOL balance, and any+ * guard/funds warning the confirm step should surface BEFORE the owner submits.+ *+ * @param {object} p+ * @param {string} p.agentId+ * @param {'buy'|'sell'} p.side+ * @param {string} p.mint+ * @param {number} [p.solAmount] SOL to spend (buy)+ * @param {string} [p.tokenAmountRaw] token base units to sell (sell)+ * @param {number} p.slippageBps+ * @param {string} p.network+ */+export function previewAgentTrade({ agentId, side, mint, solAmount, tokenAmountRaw, slippageBps, network }) {+ return postTrade(agentId, {+ preview: true, side, mint, network, slippage_bps: slippageBps,+ ...(side === 'buy' ? { sol_amount: solAmount } : { token_amount_raw: tokenAmountRaw }),+ });+}++/**+ * Execute a discretionary trade from the agent's own wallet. Idempotent: pass a+ * stable `idempotencyKey` so a retry of the same intent never double-spends.+ * Resolves with { signature, explorer, new_balance_sol, … } once confirmed.+ */+export function executeAgentTrade({ agentId, side, mint, solAmount, tokenAmountRaw, slippageBps, network, idempotencyKey }) {+ return postTrade(agentId, {+ side, mint, network, slippage_bps: slippageBps, idempotency_key: idempotencyKey,+ ...(side === 'buy' ? { sol_amount: solAmount } : { token_amount_raw: tokenAmountRaw }),+ });+}++/** Token holdings for the agent wallet (owner or visitor — balances are public). */+export async function fetchAgentHoldings(agentId, network = 'mainnet') {+ const url = `/api/agents/${encodeURIComponent(agentId)}/solana/holdings?network=${encodeURIComponent(network)}`;+ const resp = await fetch(url, { credentials: 'include' });+ const json = await resp.json().catch(() => ({}));+ if (!resp.ok) throw new Error(json?.error?.message || `holdings fetch failed (${resp.status})`);+ return json.data;+}++/** Unified trade history (discretionary + sniper), newest first. Owner-only. */+export async function fetchAgentTradeHistory(agentId, network = 'mainnet', limit = 40) {+ const url = `/api/agents/${encodeURIComponent(agentId)}/solana/trade-history?network=${encodeURIComponent(network)}&limit=${limit}`;+ const resp = await fetch(url, { credentials: 'include' });+ if (resp.status === 401 || resp.status === 403) return { items: [], forbidden: true };+ const json = await resp.json().catch(() => ({}));+ if (!resp.ok) throw new Error(json?.error?.message || `history fetch failed (${resp.status})`);+ return json.data;+}+// ── UI card ─────────────────────────────────────────────────────────────────const STYLE = `diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.jsindex e7d440633..74ffcc5d3 100644--- a/src/agent-wallet-hub/index.js+++ b/src/agent-wallet-hub/index.js@@ -132,6 +132,8 @@ export function mountAgentWalletHub({ mount, agent, initialTab, onNetworkChangeif (typeof fn === 'function') networkListeners.add(fn);return () => networkListeners.delete(fn);},+ // Lets a tab hand off to another (e.g. Trade → Deposit on insufficient funds).+ openTab: (id) => openTab(id),escapeHtml,shortAddress,copyToClipboard,diff --git a/src/agent-wallet-hub/tabs/trade.js b/src/agent-wallet-hub/tabs/trade.jsindex 9fdf73662..cfb614aa6 100644--- a/src/agent-wallet-hub/tabs/trade.js+++ b/src/agent-wallet-hub/tabs/trade.js@@ -1,18 +1,894 @@/**- * Agent Wallet hub — Trade tab (placeholder; replaced by epic task 04).+ * Agent Wallet hub — Trade tab (epic task 04).*- * Owner-only: discretionary trading moves the agent's own custodial funds.- * Task 04 ships the pump.fun buy/sell widget that signs from the agent wallet.+ * Discretionary pump.fun buy/sell FROM the agent's own funded custodial wallet.+ * The owner picks a coin (paste a mint or tap a holding), sizes the trade in SOL+ * (buy) or tokens (sell), sees a live quote — expected output, price impact,+ * minimum received, slippage, fees — then confirms. Execution is real and+ * on-chain via POST /api/agents/:id/solana/trade (server-signed; the browser+ * never holds or sends a key). Balances and holdings update only after the tx+ * confirms.+ *+ * Owner sees the full trade controls; visitors get a read-only holdings + history+ * view. Every state is designed: wallet-preparing, idle, resolving-coin, quoting,+ * confirming, submitting, success, and every guard/error (over budget, price+ * impact too high, insufficient SOL → routes to the Deposit tab).+ *+ * Coin-agnostic: trades whatever mint the owner supplies at runtime. $THREE is the+ * only coin three.ws promotes — nothing here names or recommends any other token;+ * the placeholder is a synthetic example, not a real mint.*/-import { registerPlaceholderTab } from './_placeholder.js';+import { registerWalletTab } from '../registry.js';+import {+ previewAgentTrade, executeAgentTrade, fetchAgentHoldings, fetchAgentTradeHistory, TradeError,+} from '../../agent-solana-wallet.js';+import { solToUsd } from '../../shared/usd-price.js';+import { formatSol, timeAgo, explorerTxUrl } from '../util.js';++const QUOTE_DEBOUNCE_MS = 450;+const BUY_HEADROOM_SOL = 0.003; // keep fee+rent headroom out of "Max"+const SLIPPAGE_PRESETS = [100, 300, 500]; // 1% / 3% / 5%+const IMPACT_WARN = 5; // amber+const IMPACT_DANGER = 15; // red+// A clearly-synthetic placeholder mint — never a real coin (CLAUDE.md: $THREE is+// the only coin three.ws references; this is illustrative input only).+const MINT_PLACEHOLDER = 'Paste a coin mint address…';+const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const STYLE_ID = 'awh-trade-style';+const STYLE = `+.awh-tr { display: flex; flex-direction: column; gap: var(--awh-gap, 16px); }+.awh-tr-banner { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; border-radius: var(--radius-md,10px); font-size: var(--text-sm,.764rem); line-height: 1.45; border: 1px solid transparent; }+.awh-tr-banner--info { color: var(--ink-dim,#888); background: var(--surface-1, rgba(255,255,255,.03)); border-color: var(--stroke, rgba(255,255,255,.08)); }+.awh-tr-banner--warn { color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 10%, transparent); border-color: color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); }++.awh-tr-side { display: inline-flex; padding: 3px; gap: 3px; background: var(--surface-2, rgba(255,255,255,.05)); border-radius: var(--radius-md,10px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); }+.awh-tr-side button { appearance: none; font: inherit; font-size: var(--text-md,.8125rem); font-weight: 600; color: var(--ink-dim,#888); background: transparent; border: none; padding: 7px 18px; border-radius: var(--radius-sm,6px); cursor: pointer; transition: color var(--duration-fast,140ms), background var(--duration-fast,140ms); }+.awh-tr-side button:hover:not([aria-pressed="true"]) { color: var(--ink,#e8e8e8); }+.awh-tr-side button[aria-pressed="true"][data-side="buy"] { color: #0a0a0a; background: var(--success,#4ade80); }+.awh-tr-side button[aria-pressed="true"][data-side="sell"] { color: #0a0a0a; background: var(--danger,#f87171); }+.awh-tr-side button:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 2px; }++.awh-tr-field { display: flex; flex-direction: column; gap: 7px; }+.awh-tr-label { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim,#888); display: flex; justify-content: space-between; align-items: center; gap: 8px; }+.awh-tr-label a, .awh-tr-label button.awh-tr-link { color: var(--accent,#fff); background: none; border: none; font: inherit; cursor: pointer; padding: 0; text-decoration: none; }+.awh-tr-label button.awh-tr-link:hover { text-decoration: underline; }++.awh-tr-mintrow { display: flex; gap: 8px; align-items: stretch; }+.awh-tr-input { flex: 1 1 auto; min-width: 0; font: inherit; font-size: var(--text-md,.8125rem); color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding: 9px 12px; transition: border-color var(--duration-fast,140ms); }+.awh-tr-input::placeholder { color: var(--ink-faint, #666); }+.awh-tr-input:focus-visible { outline: none; border-color: var(--accent,#fff); }+.awh-tr-input.is-mono { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-sm,.764rem); }++.awh-tr-coin { display: flex; align-items: center; gap: 10px; padding: 9px 11px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.03)); }+.awh-tr-coin img, .awh-tr-coin .awh-tr-coin-ph { width: 30px; height: 30px; border-radius: 50%; flex: none; object-fit: cover; background: var(--surface-3, rgba(255,255,255,.08)); }+.awh-tr-coin-name { font-weight: 600; color: var(--ink-bright,#fff); font-size: var(--text-md,.8125rem); }+.awh-tr-coin-sym { color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); }+.awh-tr-badge { font-size: var(--text-2xs,.6875rem); font-weight: 600; padding: 2px 7px; border-radius: var(--radius-pill,999px); border: 1px solid var(--stroke,rgba(255,255,255,.12)); color: var(--ink-dim,#888); margin-left: auto; }++.awh-tr-amt { position: relative; }+.awh-tr-amt .awh-tr-input { padding-right: 64px; font-size: var(--text-lg,1.236rem); font-weight: 600; }+.awh-tr-denom { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: var(--ink-dim,#888); font-size: var(--text-sm,.764rem); font-weight: 600; pointer-events: none; }+.awh-tr-amt-usd { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); min-height: 1em; }+.awh-tr-chips { display: flex; gap: 6px; flex-wrap: wrap; }+.awh-tr-chip { appearance: none; font: inherit; font-size: var(--text-sm,.764rem); color: var(--ink,#e8e8e8); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-pill,999px); padding: 4px 12px; cursor: pointer; transition: background var(--duration-fast,140ms), border-color var(--duration-fast,140ms); }+.awh-tr-chip:hover:not(:disabled) { background: var(--surface-3, rgba(255,255,255,.08)); border-color: var(--stroke-strong, rgba(255,255,255,.14)); }+.awh-tr-chip:disabled { opacity: .4; cursor: not-allowed; }+.awh-tr-chip:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 2px; }++.awh-tr-slip { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }+.awh-tr-slip .awh-tr-chip[aria-pressed="true"] { background: var(--accent,#fff); color: #0a0a0a; border-color: var(--accent,#fff); }+.awh-tr-slip input { width: 64px; }++.awh-tr-quote { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.03)); padding: 12px 14px; display: flex; flex-direction: column; gap: 8px; }+.awh-tr-qrow { display: flex; justify-content: space-between; gap: 12px; font-size: var(--text-sm,.764rem); }+.awh-tr-qrow dt { color: var(--ink-dim,#888); margin: 0; }+.awh-tr-qrow dd { margin: 0; color: var(--ink,#e8e8e8); font-variant-numeric: tabular-nums; text-align: right; }+.awh-tr-qrow dd.is-strong { color: var(--ink-bright,#fff); font-weight: 600; }+.awh-tr-qrow dd.impact-warn { color: var(--warn,#fbbf24); }+.awh-tr-qrow dd.impact-danger { color: var(--danger,#f87171); }+.awh-tr-quote-skel { height: 14px; border-radius: 5px; background: var(--surface-2, rgba(255,255,255,.05)); animation: awh-skel 1.4s ease-in-out infinite; }+.awh-tr-quote-skel:nth-child(2) { width: 70%; } .awh-tr-quote-skel:nth-child(3) { width: 85%; }+.awh-tr-quote-note { font-size: var(--text-sm,.764rem); }+.awh-tr-quote-note.is-err { color: var(--danger,#f87171); }+.awh-tr-quote-note.is-warn { color: var(--warn,#fbbf24); }++.awh-tr-actions { display: flex; flex-direction: column; gap: 8px; }+.awh-tr-submit { width: 100%; justify-content: center; padding: 11px 16px; font-size: var(--text-md,.8125rem); font-weight: 600; }+.awh-tr-submit[data-side="buy"]:not(:disabled) { background: var(--success,#4ade80); color: #0a0a0a; border-color: var(--success,#4ade80); }+.awh-tr-submit[data-side="sell"]:not(:disabled) { background: var(--danger,#f87171); color: #0a0a0a; border-color: var(--danger,#f87171); }+.awh-tr-submit[data-side="buy"]:hover:not(:disabled) { background: color-mix(in srgb, var(--success,#4ade80) 88%, #000); }+.awh-tr-submit[data-side="sell"]:hover:not(:disabled) { background: color-mix(in srgb, var(--danger,#f87171) 88%, #000); }+.awh-tr-deposit-cta { width: 100%; justify-content: center; }++.awh-tr-confirm { border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: var(--radius-md,10px); background: var(--surface-2, rgba(255,255,255,.05)); padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; animation: awh-fade var(--duration-base,220ms) var(--ease-out,ease); }+.awh-tr-confirm-h { font-size: var(--text-md,.8125rem); font-weight: 600; color: var(--ink-bright,#fff); }+.awh-tr-confirm-actions { display: flex; gap: 8px; }+.awh-tr-confirm-actions .awh-btn { flex: 1; justify-content: center; }++.awh-tr-result { display: flex; gap: 10px; align-items: flex-start; padding: 11px 13px; border-radius: var(--radius-md,10px); font-size: var(--text-sm,.764rem); line-height: 1.5; }+.awh-tr-result--ok { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 10%, transparent); border: 1px solid color-mix(in srgb, var(--success,#4ade80) 30%, transparent); }+.awh-tr-result--err { color: var(--danger,#f87171); background: color-mix(in srgb, var(--danger,#f87171) 10%, transparent); border: 1px solid color-mix(in srgb, var(--danger,#f87171) 30%, transparent); }+.awh-tr-result a { color: inherit; font-weight: 600; }++.awh-tr-hold-list, .awh-tr-hist-list { list-style: none; margin: 0; padding: 0; }+.awh-tr-hold { display: flex; align-items: center; gap: 10px; width: 100%; text-align: left; padding: 9px 6px; border: none; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.06)); background: none; cursor: pointer; font: inherit; border-radius: 6px; transition: background var(--duration-fast,140ms); }+.awh-tr-hold:last-child { border-bottom: none; }+.awh-tr-hold:hover { background: var(--surface-1, rgba(255,255,255,.03)); }+.awh-tr-hold:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: -2px; }+.awh-tr-hold[disabled] { cursor: default; }+.awh-tr-hold-sym { font-weight: 600; color: var(--ink-bright,#fff); font-size: var(--text-md,.8125rem); }+.awh-tr-hold-mint { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }+.awh-tr-hold-amt { margin-left: auto; text-align: right; font-variant-numeric: tabular-nums; color: var(--ink,#e8e8e8); font-size: var(--text-sm,.764rem); }+.awh-tr-hold-cta { margin-left: 8px; flex: none; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }-registerPlaceholderTab({+.awh-tr-hist { display: flex; align-items: center; gap: 10px; padding: 9px 0; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.06)); font-size: var(--text-sm,.764rem); }+.awh-tr-hist:last-child { border-bottom: none; }+.awh-tr-hist-side { font-size: var(--text-2xs,.6875rem); font-weight: 700; text-transform: uppercase; letter-spacing: .04em; padding: 2px 7px; border-radius: var(--radius-pill,999px); flex: none; }+.awh-tr-hist-side.is-buy { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 14%, transparent); }+.awh-tr-hist-side.is-sell { color: var(--danger,#f87171); background: color-mix(in srgb, var(--danger,#f87171) 14%, transparent); }+.awh-tr-hist-side.is-snipe { color: var(--accent,#9b8cff); background: color-mix(in srgb, var(--accent,#9b8cff) 16%, transparent); }+.awh-tr-hist-main { flex: 1 1 auto; min-width: 0; overflow: hidden; }+.awh-tr-hist-mint { font-family: var(--font-mono, ui-monospace, monospace); color: var(--ink,#e8e8e8); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.awh-tr-hist-sub { color: var(--ink-dim,#888); font-size: var(--text-2xs,.6875rem); }+.awh-tr-hist-val { flex: none; text-align: right; font-variant-numeric: tabular-nums; }+.awh-tr-hist-val a { color: var(--ink,#e8e8e8); text-decoration: none; }+.awh-tr-hist-val a:hover { text-decoration: underline; }+.awh-tr-pnl-pos { color: var(--success,#4ade80); } .awh-tr-pnl-neg { color: var(--danger,#f87171); }++.awh-tr-skel-row { height: 16px; border-radius: 5px; background: var(--surface-2, rgba(255,255,255,.05)); animation: awh-skel 1.4s ease-in-out infinite; margin: 8px 0; }+@keyframes awh-skel { 0%,100% { opacity: .5; } 50% { opacity: 1; } }+@media (prefers-reduced-motion: reduce) { .awh-tr-quote-skel, .awh-tr-skel-row, .awh-tr-confirm { animation: none; } }+@media (max-width: 520px) { .awh-tr-side button { padding: 7px 14px; } }+`;++function injectStyle() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = STYLE_ID;+ tag.textContent = STYLE;+ document.head.appendChild(tag);+}++// ── small formatting helpers ──────────────────────────────────────────────────+function fmtUsd(n) {+ if (n == null || !Number.isFinite(n)) return '';+ if (n === 0) return '$0.00';+ if (n < 0.01) return `$${n.toFixed(4)}`;+ if (n < 1000) return `$${n.toFixed(2)}`;+ return `$${Math.round(n).toLocaleString('en-US')}`;+}+function fmtTokens(n) {+ if (n == null || !Number.isFinite(n)) return '—';+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;+ if (n >= 1000) return n.toLocaleString('en-US', { maximumFractionDigits: 2 });+ if (n >= 1) return n.toLocaleString('en-US', { maximumFractionDigits: 4 });+ return n.toPrecision(4).replace(/\.?0+$/, '');+}+function short(s, h = 4, t = 4) {+ return !s || s.length <= h + t + 1 ? s || '' : `${s.slice(0, h)}…${s.slice(-t)}`;+}+function rawToUi(rawStr, decimals) {+ try { return Number(BigInt(rawStr)) / 10 ** decimals; } catch { return 0; }+}+function pctOfRaw(rawStr, pct) {+ try { return ((BigInt(rawStr) * BigInt(Math.round(pct))) / 100n).toString(); } catch { return '0'; }+}+function uiToRaw(ui, decimals) {+ if (!(Number(ui) > 0)) return '0';+ // Avoid float drift for the integer base-unit amount.+ const [whole, frac = ''] = String(ui).split('.');+ const fracPad = (frac + '0'.repeat(decimals)).slice(0, decimals);+ try { return (BigInt(whole || '0') * 10n ** BigInt(decimals) + BigInt(fracPad || '0')).toString(); }+ catch { return '0'; }+}++let _uid = 0;+const newIdempotencyKey = () => {+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID();+ _uid += 1;+ return `trade-${Date.now()}-${_uid}-${Math.floor(Math.random() * 1e9)}`;+};++registerWalletTab({id: 'trade',label: 'Trade',order: 30,- ownerOnly: true,- icon: '⇄',- title: 'Trade from this wallet',- body: 'Buy and sell pump.fun tokens directly from the agent’s own funded wallet, with live quotes, slippage controls, and price-impact guardrails. This panel is being wired up now.',+ ownerOnly: false, // visitors get a read-only holdings + history view+ mount({ panel, ctx }) {+ injectStyle();+ const { escapeHtml, toast } = ctx;+ const esc = escapeHtml;+ let destroyed = false;+ let detachNet = null;+ let quoteTimer = null;+ let quoteSeq = 0;++ const state = {+ isOwner: ctx.isOwner,+ walletReady: !!(ctx.agent.walletReady ?? ctx.agent.wallet_ready),+ side: 'buy',+ mintInput: '',+ coin: null, // { mint, name, symbol, image, graduated, loading, error }+ slippageBps: 300,+ buySol: '', // string in the SOL field+ sellRaw: '0', // base units (source of truth for sell)+ sellDecimals: 6,+ quote: null, // last successful preview payload+ quoting: false,+ quoteError: null, // TradeError+ confirming: false,+ submitting: false,+ result: null, // { ok, message, explorer } | { ok:false, ... }+ solBalance: null,+ holdings: null, // [{ mint, ui_amount, amount_raw, decimals, ... }]+ holdingsError: null,+ holdingsLoaded: false,+ history: null,+ historyError: null,+ historyLoaded: false,+ solPrice: null,+ };++ // ── data loads ────────────────────────────────────────────────────────+ async function loadHoldings() {+ try {+ const data = await fetchAgentHoldings(ctx.agentId, ctx.getNetwork());+ state.solBalance = data?.sol ?? null;+ state.holdings = (data?.tokens || []).filter((t) => !t.is_usdc);+ state.holdingsError = null;+ } catch (e) {+ state.holdingsError = e?.message || 'holdings_error';+ } finally {+ state.holdingsLoaded = true;+ }+ }++ async function loadHistory() {+ if (!state.isOwner) { state.historyLoaded = true; return; }+ try {+ const data = await fetchAgentTradeHistory(ctx.agentId, ctx.getNetwork(), 40);+ state.history = data?.items || [];+ state.historyError = null;+ } catch (e) {+ state.historyError = e?.message || 'history_error';+ } finally {+ state.historyLoaded = true;+ }+ }++ async function loadSolPrice() {+ try { state.solPrice = await solToUsd(1); } catch { state.solPrice = null; }+ }++ async function resolveCoin(mint) {+ state.coin = { mint, loading: true, error: null, name: null, symbol: null, image: null, graduated: null };+ renderAll();+ let meta = null;+ try {+ const r = await fetch(`/api/pump/coin?mint=${encodeURIComponent(mint)}`, { headers: { accept: 'application/json' } });+ if (r.ok) meta = await r.json();+ } catch { /* metadata is best-effort — the mint still trades */ }+ if (destroyed || state.coin?.mint !== mint) return;+ state.coin = {+ mint,+ loading: false,+ error: null,+ name: meta?.name || null,+ symbol: meta?.symbol || null,+ image: meta?.image_uri || meta?.image || null,+ graduated: meta?.complete ?? null,+ };+ // Pre-fill sell decimals/amount from a matching holding when selling.+ syncSellDecimals();+ renderAll();+ scheduleQuote();+ }++ function syncSellDecimals() {+ const h = (state.holdings || []).find((t) => t.mint === state.coin?.mint);+ if (h) state.sellDecimals = h.decimals ?? 6;+ }++ // ── quote (debounced) ───────────────────────────────────────────────────+ function tradeArgs() {+ const mint = state.coin?.mint;+ if (!mint) return null;+ if (state.side === 'buy') {+ const sol = Number(state.buySol);+ if (!(sol > 0)) return null;+ return { agentId: ctx.agentId, side: 'buy', mint, solAmount: sol, slippageBps: state.slippageBps, network: ctx.getNetwork() };+ }+ if (!(BigInt(state.sellRaw || '0') > 0n)) return null;+ return { agentId: ctx.agentId, side: 'sell', mint, tokenAmountRaw: state.sellRaw, slippageBps: state.slippageBps, network: ctx.getNetwork() };+ }++ function scheduleQuote() {+ clearTimeout(quoteTimer);+ state.result = null;+ const args = tradeArgs();+ if (!args) {+ state.quote = null;+ state.quoteError = null;+ state.quoting = false;+ renderQuote();+ renderActions();+ return;+ }+ state.quoting = true;+ state.quoteError = null;+ renderQuote();+ renderActions();+ const seq = ++quoteSeq;+ quoteTimer = setTimeout(async () => {+ try {+ const data = await previewAgentTrade(args);+ if (destroyed || seq !== quoteSeq) return;+ state.quote = data;+ state.quoteError = null;+ } catch (e) {+ if (destroyed || seq !== quoteSeq) return;+ state.quote = null;+ state.quoteError = e instanceof TradeError ? e : new TradeError(e?.message || 'Could not price this trade.');+ } finally {+ if (!destroyed && seq === quoteSeq) {+ state.quoting = false;+ renderQuote();+ renderActions();+ }+ }+ }, QUOTE_DEBOUNCE_MS);+ }++ // ── execute ─────────────────────────────────────────────────────────────+ async function submit() {+ const args = tradeArgs();+ if (!args || state.submitting) return;+ state.submitting = true;+ state.confirming = false;+ state.result = null;+ renderActions();+ try {+ const data = await executeAgentTrade({ ...args, idempotencyKey: newIdempotencyKey() });+ if (destroyed) return;+ const net = ctx.getNetwork();+ const outAsset = state.side === 'buy' ? (state.coin?.symbol || 'tokens') : 'SOL';+ const outAmt = state.side === 'buy'+ ? fmtTokens(data?.out?.amount)+ : `◎${formatSol(data?.out?.amount)}`;+ state.result = {+ ok: true,+ message: data?.replayed+ ? `Already executed — ${state.side === 'buy' ? 'bought' : 'sold'} ${esc(outAmt)} ${esc(outAsset)}.`+ : `${state.side === 'buy' ? 'Bought' : 'Sold'} ${esc(outAmt)} ${esc(outAsset)}.`,+ explorer: data?.explorer || (data?.signature ? explorerTxUrl(data.signature, net) : null),+ };+ toast(state.side === 'buy' ? 'Buy confirmed' : 'Sell confirmed');+ // Reset the amount; refresh real on-chain balances + history.+ if (state.side === 'buy') state.buySol = '';+ else state.sellRaw = '0';+ state.quote = null;+ await Promise.all([loadHoldings(), loadHistory(), refreshBalanceCacheBust()]);+ } catch (e) {+ if (destroyed) return;+ state.result = buildErrorResult(e);+ } finally {+ if (!destroyed) {+ state.submitting = false;+ renderAll();+ }+ }+ }++ async function refreshBalanceCacheBust() {+ // Holdings already re-read SOL; nothing else to bust client-side.+ }++ function buildErrorResult(e) {+ const code = e instanceof TradeError ? e.code : 'error';+ const msg = e?.message || 'The trade could not be completed.';+ // Insufficient funds → offer the deposit route.+ const insufficient = code === 'insufficient_sol' || code === 'insufficient_sol_for_fees';+ return { ok: false, code, message: msg, insufficient, explorer: e?.detail?.explorer || null };+ }++ // ── renderers ───────────────────────────────────────────────────────────+ function renderAll() {+ if (destroyed) return;+ if (!state.walletReady) {+ panel.innerHTML = `+ <div class="awh-card">+ <div class="awh-tr-banner awh-tr-banner--warn" role="status">+ <span aria-hidden="true">⏳</span>+ <span>This agent’s wallet is still being prepared. Trading opens automatically the moment it’s ready — refresh in a few seconds.</span>+ </div>+ </div>`;+ return;+ }+ panel.innerHTML = `+ <div class="awh-tr">+ ${state.isOwner ? tradeCardHtml() : visitorBannerHtml()}+ ${holdingsCardHtml()}+ ${historyCardHtml()}+ </div>`;+ wireEvents();+ }++ function visitorBannerHtml() {+ return `<div class="awh-card">+ <div class="awh-tr-banner awh-tr-banner--info" role="note">+ <span aria-hidden="true">👁️</span>+ <span>You’re viewing <strong>${esc(ctx.agent.name || 'this agent')}</strong>’s wallet. Holdings and trade history are public; only the owner can trade from it.</span>+ </div>+ </div>`;+ }++ function tradeCardHtml() {+ return `+ <div class="awh-card">+ <div class="awh-tr">+ <div class="awh-tr-field">+ <div class="awh-tr-label" id="awh-tr-coin-l">Coin</div>+ <div class="awh-tr-mintrow">+ <input class="awh-tr-input is-mono" data-tr="mint" type="text" inputmode="text" spellcheck="false"+ autocomplete="off" aria-labelledby="awh-tr-coin-l"+ placeholder="${esc(MINT_PLACEHOLDER)}" value="${esc(state.mintInput)}" />+ </div>+ ${coinPreviewHtml()}+ </div>++ <div class="awh-tr-side" role="group" aria-label="Trade side">+ <button type="button" data-side="buy" aria-pressed="${state.side === 'buy'}">Buy</button>+ <button type="button" data-side="sell" aria-pressed="${state.side === 'sell'}">Sell</button>+ </div>++ ${amountFieldHtml()}+ ${slippageHtml()}++ <div class="awh-tr-field">+ <div class="awh-tr-label">Quote</div>+ <div data-host="quote">${quoteInnerHtml()}</div>+ </div>++ <div class="awh-tr-actions" data-host="actions">${actionsInnerHtml()}</div>+ <div data-host="result">${resultInnerHtml()}</div>+ </div>+ </div>`;+ }++ function coinPreviewHtml() {+ const c = state.coin;+ if (!c) return '';+ if (c.loading) return `<div class="awh-tr-coin"><div class="awh-tr-coin-ph" aria-hidden="true"></div><span class="awh-tr-coin-sym">Resolving coin…</span></div>`;+ const sym = c.symbol ? esc(c.symbol) : short(c.mint, 4, 4);+ const name = c.name ? esc(c.name) : 'Unknown coin';+ const badge = c.graduated === true ? 'Graduated · AMM' : c.graduated === false ? 'Bonding curve' : '';+ return `<div class="awh-tr-coin">+ ${c.image ? `<img src="${esc(c.image)}" alt="" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'awh-tr-coin-ph'}))" />` : '<div class="awh-tr-coin-ph" aria-hidden="true"></div>'}+ <div>+ <div class="awh-tr-coin-name">${name}</div>+ <div class="awh-tr-coin-sym">${sym} · <span class="awh-mono">${short(c.mint, 4, 4)}</span></div>+ </div>+ ${badge ? `<span class="awh-tr-badge">${badge}</span>` : ''}+ </div>`;+ }++ function amountFieldHtml() {+ if (state.side === 'buy') {+ const usd = state.solPrice && Number(state.buySol) > 0 ? fmtUsd(Number(state.buySol) * state.solPrice) : '';+ return `<div class="awh-tr-field">+ <div class="awh-tr-label"><span>You pay</span><span>${state.solBalance != null ? `Balance: ◎${formatSol(state.solBalance)}` : ''}</span></div>+ <div class="awh-tr-amt">+ <input class="awh-tr-input" data-tr="buySol" type="text" inputmode="decimal" autocomplete="off"+ placeholder="0.0" value="${esc(state.buySol)}" aria-label="SOL amount to spend" />+ <span class="awh-tr-denom">SOL</span>+ </div>+ <div class="awh-tr-amt-usd">${usd ? `≈ ${usd}` : ''}</div>+ <div class="awh-tr-chips" data-host="chips">${buyChipsHtml()}</div>+ </div>`;+ }+ const h = (state.holdings || []).find((t) => t.mint === state.coin?.mint);+ const ui = rawToUi(state.sellRaw, state.sellDecimals);+ const sym = state.coin?.symbol || 'tokens';+ const held = h ? `Holding: ${fmtTokens(Number(h.ui_amount))}` : 'Not held';+ return `<div class="awh-tr-field">+ <div class="awh-tr-label"><span>You sell</span><span>${esc(held)}</span></div>+ <div class="awh-tr-amt">+ <input class="awh-tr-input" data-tr="sellUi" type="text" inputmode="decimal" autocomplete="off"+ placeholder="0.0" value="${ui > 0 ? esc(fmtTokens(ui)) : ''}" aria-label="Token amount to sell" />+ <span class="awh-tr-denom">${esc(sym).slice(0, 6)}</span>+ </div>+ <div class="awh-tr-amt-usd"></div>+ <div class="awh-tr-chips" data-host="chips">${sellChipsHtml()}</div>+ </div>`;+ }++ function buyChipsHtml() {+ const bal = Number(state.solBalance);+ const ok = Number.isFinite(bal) && bal > BUY_HEADROOM_SOL;+ const maxSpendable = ok ? Math.max(0, bal - BUY_HEADROOM_SOL) : 0;+ return [25, 50, 75, 100].map((p) => {+ const v = (maxSpendable * p) / 100;+ const label = p === 100 ? 'Max' : `${p}%`;+ return `<button type="button" class="awh-tr-chip" data-buychip="${v.toFixed(6)}" ${ok ? '' : 'disabled'}>${label}</button>`;+ }).join('');+ }++ function sellChipsHtml() {+ const h = (state.holdings || []).find((t) => t.mint === state.coin?.mint);+ const ok = !!h && BigInt(h.amount_raw || '0') > 0n;+ return [25, 50, 75, 100].map((p) => {+ const label = p === 100 ? 'Max' : `${p}%`;+ return `<button type="button" class="awh-tr-chip" data-sellchip="${p}" ${ok ? '' : 'disabled'}>${label}</button>`;+ }).join('');+ }++ function slippageHtml() {+ const isPreset = SLIPPAGE_PRESETS.includes(state.slippageBps);+ return `<div class="awh-tr-field">+ <div class="awh-tr-label">Max slippage</div>+ <div class="awh-tr-slip" role="group" aria-label="Max slippage">+ ${SLIPPAGE_PRESETS.map((b) => `<button type="button" class="awh-tr-chip" data-slip="${b}" aria-pressed="${state.slippageBps === b}">${(b / 100).toFixed(b % 100 ? 1 : 0)}%</button>`).join('')}+ <input class="awh-tr-input awh-tr-chip" data-tr="slipBps" type="number" min="0" max="5000" step="10"+ value="${isPreset ? '' : state.slippageBps}" placeholder="bps" aria-label="Custom slippage in basis points" style="padding:4px 10px" />+ </div>+ </div>`;+ }++ function quoteInnerHtml() { return quoteBodyHtml(); }+ function renderQuote() {+ const host = panel.querySelector('[data-host="quote"]');+ if (host) host.innerHTML = quoteBodyHtml();+ }+ function quoteBodyHtml() {+ if (!state.coin) return `<div class="awh-tr-quote-note" style="color:var(--ink-dim,#888)">Enter a coin and amount to see a live quote.</div>`;+ if (state.quoting) {+ return `<div class="awh-tr-quote" aria-busy="true" aria-label="Fetching quote"><div class="awh-tr-quote-skel"></div><div class="awh-tr-quote-skel"></div><div class="awh-tr-quote-skel"></div></div>`;+ }+ if (state.quoteError) {+ const code = state.quoteError.code;+ const friendly = code === 'no_market'+ ? 'No bonding curve or pool found for this mint on this network. Double-check the address.'+ : code === 'amount_too_small'+ ? 'That amount is too small to trade. Try a larger size.'+ : state.quoteError.message;+ return `<div class="awh-tr-quote"><div class="awh-tr-quote-note is-err">${esc(friendly)}</div></div>`;+ }+ const q = state.quote;+ if (!q) return `<div class="awh-tr-quote-note" style="color:var(--ink-dim,#888)">Enter an amount to see a live quote.</div>`;+ const impact = Number(q.price_impact_pct) || 0;+ const impactCls = impact >= IMPACT_DANGER ? 'impact-danger' : impact >= IMPACT_WARN ? 'impact-warn' : '';+ const outAsset = q.out?.asset === 'SOL' ? 'SOL' : (state.coin?.symbol || 'tokens');+ const outStr = q.out?.asset === 'SOL' ? `◎${formatSol(q.out?.amount)}` : fmtTokens(q.out?.amount);+ const minStr = q.min_received?.amount != null+ ? (q.out?.asset === 'SOL' ? `◎${formatSol(q.min_received.amount)}` : `${fmtTokens(q.min_received.amount)} ${esc(outAsset)}`)+ : '—';+ const feeBps = Number(q.platform_fee_bps) || 0;+ const guard = q.guard;+ const funds = q.funds;+ return `<dl class="awh-tr-quote">+ <div class="awh-tr-qrow"><dt>Expected ${state.side === 'buy' ? 'output' : 'proceeds'}</dt><dd class="is-strong">${esc(outStr)}${q.out?.asset === 'SOL' ? '' : ` ${esc(outAsset)}`}</dd></div>+ <div class="awh-tr-qrow"><dt>Minimum received</dt><dd>${esc(minStr)}</dd></div>+ <div class="awh-tr-qrow"><dt>Price impact</dt><dd class="${impactCls}">${impact.toFixed(2)}%</dd></div>+ <div class="awh-tr-qrow"><dt>Max slippage</dt><dd>${(state.slippageBps / 100).toFixed(state.slippageBps % 100 ? 1 : 0)}%</dd></div>+ <div class="awh-tr-qrow"><dt>Route</dt><dd>${q.venue === 'amm' ? 'AMM pool' : 'Bonding curve'}${feeBps > 0 ? ` · ${(feeBps / 100).toFixed(2)}% fee` : ''}</dd></div>+ ${impact >= IMPACT_WARN ? `<div class="awh-tr-quote-note is-warn">⚠ High price impact (${impact.toFixed(1)}%). You may receive significantly less than the market rate.</div>` : ''}+ ${guard ? `<div class="awh-tr-quote-note is-err">⚠ ${esc(guard.message)}</div>` : ''}+ ${funds ? `<div class="awh-tr-quote-note is-err">⚠ ${esc(funds.message)}</div>` : ''}+ </dl>`;+ }++ function actionsInnerHtml() {+ const args = tradeArgs();+ const q = state.quote;+ const blocked = q && (q.guard || q.funds);+ const fundsInsufficient = q?.funds;+ const ready = !!args && !!q && !state.quoting && !blocked;+ const sym = state.coin?.symbol || 'coin';+ if (state.submitting) {+ return `<button class="awh-btn awh-btn--primary awh-tr-submit" type="button" disabled data-side="${state.side}">Submitting…</button>`;+ }+ if (state.confirming && ready) {+ const q2 = state.quote;+ const outAsset = q2.out?.asset === 'SOL' ? 'SOL' : (state.coin?.symbol || 'tokens');+ const outStr = q2.out?.asset === 'SOL' ? `◎${formatSol(q2.out?.amount)}` : `${fmtTokens(q2.out?.amount)} ${esc(outAsset)}`;+ const payStr = state.side === 'buy' ? `◎${formatSol(Number(state.buySol))} SOL` : `${fmtTokens(rawToUi(state.sellRaw, state.sellDecimals))} ${esc(state.coin?.symbol || 'tokens')}`;+ return `<div class="awh-tr-confirm" role="group" aria-label="Confirm trade">+ <div class="awh-tr-confirm-h">Confirm ${state.side === 'buy' ? 'buy' : 'sell'}</div>+ <dl class="awh-tr-quote" style="border:none;padding:0;background:none">+ <div class="awh-tr-qrow"><dt>You ${state.side === 'buy' ? 'pay' : 'sell'}</dt><dd class="is-strong">${esc(payStr)}</dd></div>+ <div class="awh-tr-qrow"><dt>You receive ≈</dt><dd class="is-strong">${esc(outStr)}</dd></div>+ <div class="awh-tr-qrow"><dt>Minimum</dt><dd>${q2.out?.asset === 'SOL' ? `◎${formatSol(q2.min_received?.amount)}` : `${fmtTokens(q2.min_received?.amount)} ${esc(outAsset)}`}</dd></div>+ </dl>+ <div class="awh-tr-confirm-actions">+ <button class="awh-btn" type="button" data-tr="cancel">Cancel</button>+ <button class="awh-btn awh-btn--primary awh-tr-submit" type="button" data-tr="confirm" data-side="${state.side}">Confirm ${state.side}</button>+ </div>+ </div>`;+ }+ if (fundsInsufficient) {+ return `<button class="awh-btn awh-btn--primary awh-tr-deposit-cta" type="button" data-tr="deposit">Add funds to ${esc(ctx.agent.name || 'this wallet')}</button>`;+ }+ return `<button class="awh-btn awh-btn--primary awh-tr-submit" type="button" data-tr="review" data-side="${state.side}" ${ready ? '' : 'disabled'}>+ ${state.side === 'buy' ? `Buy ${esc(sym)}` : `Sell ${esc(sym)}`}+ </button>`;+ }+ function renderActions() {+ const host = panel.querySelector('[data-host="actions"]');+ if (host) { host.innerHTML = actionsInnerHtml(); wireActionEvents(); }+ }++ function resultInnerHtml() {+ const r = state.result;+ if (!r) return '';+ if (r.ok) {+ return `<div class="awh-tr-result awh-tr-result--ok" role="status">+ <span aria-hidden="true">✓</span>+ <span>${r.message}${r.explorer ? ` <a href="${esc(r.explorer)}" target="_blank" rel="noopener">View on explorer ↗</a>` : ''}</span>+ </div>`;+ }+ return `<div class="awh-tr-result awh-tr-result--err" role="alert">+ <span aria-hidden="true">⚠</span>+ <span>${esc(r.message)}${r.insufficient ? ` <button class="awh-tr-link" type="button" data-tr="deposit" style="color:inherit;font-weight:600;text-decoration:underline">Add funds →</button>` : ''}${r.explorer ? ` <a href="${esc(r.explorer)}" target="_blank" rel="noopener">Check explorer ↗</a>` : ''}</span>+ </div>`;+ }++ // ── holdings card ────────────────────────────────────────────────────────+ function holdingsCardHtml() {+ let inner;+ if (!state.holdingsLoaded) {+ inner = `<div class="awh-tr-skel-row"></div><div class="awh-tr-skel-row" style="width:70%"></div>`;+ } else if (state.holdingsError) {+ inner = `<div class="awh-empty">Couldn’t load holdings. <button class="awh-btn awh-bal-mini" type="button" data-tr="retry-holdings">Retry</button></div>`;+ } else if (!state.holdings || !state.holdings.length) {+ inner = `<div class="awh-empty">No token holdings yet.${state.isOwner ? ' Buy a coin above and it’ll appear here.' : ''}</div>`;+ } else {+ inner = `<ul class="awh-tr-hold-list">${state.holdings.map(holdingRowHtml).join('')}</ul>`;+ }+ return `<div class="awh-card">+ <h2 class="awh-card-h">Holdings${state.solBalance != null ? ` · ◎${formatSol(state.solBalance)} SOL` : ''}</h2>+ <div data-host="holdings">${inner}</div>+ </div>`;+ }+ function holdingRowHtml(t) {+ const sym = t.mint === state.coin?.mint && state.coin?.symbol ? state.coin.symbol : short(t.mint, 4, 4);+ const sellable = state.isOwner;+ return `<li><button class="awh-tr-hold" type="button" ${sellable ? `data-sell-mint="${esc(t.mint)}" data-sell-dec="${t.decimals ?? 6}"` : 'disabled'}>+ <div>+ <div class="awh-tr-hold-sym">${esc(sym)}</div>+ <div class="awh-tr-hold-mint">${short(t.mint, 6, 6)}</div>+ </div>+ <span class="awh-tr-hold-amt">${fmtTokens(Number(t.ui_amount))}</span>+ ${sellable ? '<span class="awh-tr-hold-cta">Sell →</span>' : ''}+ </button></li>`;+ }++ // ── history card ──────────────────────────────────────────────────────────+ function historyCardHtml() {+ if (!state.isOwner) return '';+ let inner;+ if (!state.historyLoaded) {+ inner = `<div class="awh-tr-skel-row"></div><div class="awh-tr-skel-row" style="width:80%"></div><div class="awh-tr-skel-row" style="width:60%"></div>`;+ } else if (state.historyError) {+ inner = `<div class="awh-empty">Couldn’t load trade history. <button class="awh-btn awh-bal-mini" type="button" data-tr="retry-history">Retry</button></div>`;+ } else if (!state.history || !state.history.length) {+ inner = `<div class="awh-empty">No trades yet. Your buys, sells, and sniper exits show up here.</div>`;+ } else {+ inner = `<ul class="awh-tr-hist-list">${state.history.map(historyRowHtml).join('')}</ul>`;+ }+ return `<div class="awh-card">+ <h2 class="awh-card-h">Trade history</h2>+ <div data-host="history">${inner}</div>+ </div>`;+ }+ function historyRowHtml(it) {+ const net = ctx.getNetwork();+ if (it.source === 'sniper') {+ const pnl = it.pnl_sol;+ const cls = pnl == null ? '' : pnl >= 0 ? 'awh-tr-pnl-pos' : 'awh-tr-pnl-neg';+ const pnlStr = pnl == null ? '' : `${pnl >= 0 ? '+' : ''}◎${formatSol(pnl)}${it.pnl_pct != null ? ` (${it.pnl_pct >= 0 ? '+' : ''}${it.pnl_pct.toFixed(1)}%)` : ''}`;+ return `<li class="awh-tr-hist">+ <span class="awh-tr-hist-side is-snipe">Snipe</span>+ <div class="awh-tr-hist-main"><div class="awh-tr-hist-mint">${esc(it.symbol || short(it.mint, 5, 5))}</div><div class="awh-tr-hist-sub">${esc(it.exit_reason || 'closed')} · ${esc(timeAgo(Math.floor(new Date(it.at).getTime() / 1000)))}</div></div>+ <span class="awh-tr-hist-val ${cls}">${it.sell_url ? `<a href="${esc(it.sell_url)}" target="_blank" rel="noopener">${esc(pnlStr)}</a>` : esc(pnlStr)}</span>+ </li>`;+ }+ const isBuy = it.side === 'buy';+ const val = it.sol_amount != null ? `${isBuy ? '−' : '+'}◎${formatSol(it.sol_amount)}` : (it.token_amount_raw ? `${fmtTokens(rawToUi(it.token_amount_raw, 6))}` : '');+ const statusNote = it.status && it.status !== 'confirmed' ? ` · ${esc(it.status)}` : '';+ return `<li class="awh-tr-hist">+ <span class="awh-tr-hist-side ${isBuy ? 'is-buy' : 'is-sell'}">${isBuy ? 'Buy' : 'Sell'}</span>+ <div class="awh-tr-hist-main"><div class="awh-tr-hist-mint">${esc(it.mint ? short(it.mint, 5, 5) : 'trade')}</div><div class="awh-tr-hist-sub">${esc(it.venue === 'amm' ? 'AMM' : 'curve')}${statusNote} · ${esc(timeAgo(Math.floor(new Date(it.at).getTime() / 1000)))}</div></div>+ <span class="awh-tr-hist-val">${it.explorer ? `<a href="${esc(it.explorer)}" target="_blank" rel="noopener">${esc(val)}</a>` : esc(val)}</span>+ </li>`;+ }++ // ── event wiring ──────────────────────────────────────────────────────────+ function wireEvents() {+ const mintEl = panel.querySelector('[data-tr="mint"]');+ if (mintEl) {+ mintEl.addEventListener('input', () => {+ const v = mintEl.value.trim();+ state.mintInput = v;+ if (MINT_RE.test(v)) {+ if (state.coin?.mint !== v) resolveCoin(v);+ } else {+ state.coin = null;+ state.quote = null;+ state.quoteError = null;+ renderQuote();+ renderActions();+ const cp = panel.querySelector('.awh-tr-coin');+ if (cp) cp.remove();+ }+ });+ }+ panel.querySelectorAll('.awh-tr-side [data-side]').forEach((b) => {+ b.addEventListener('click', () => {+ if (state.side === b.dataset.side) return;+ state.side = b.dataset.side;+ if (state.side === 'sell') syncSellDecimals();+ state.confirming = false;+ state.result = null;+ renderAll();+ scheduleQuote();+ });+ });++ const buySolEl = panel.querySelector('[data-tr="buySol"]');+ if (buySolEl) buySolEl.addEventListener('input', () => {+ state.buySol = buySolEl.value.replace(/[^0-9.]/g, '');+ state.confirming = false;+ const usdEl = panel.querySelector('.awh-tr-amt-usd');+ if (usdEl) usdEl.textContent = state.solPrice && Number(state.buySol) > 0 ? `≈ ${fmtUsd(Number(state.buySol) * state.solPrice)}` : '';+ scheduleQuote();+ });+ const sellUiEl = panel.querySelector('[data-tr="sellUi"]');+ if (sellUiEl) sellUiEl.addEventListener('input', () => {+ const v = sellUiEl.value.replace(/[^0-9.]/g, '');+ state.sellRaw = uiToRaw(v, state.sellDecimals);+ state.confirming = false;+ scheduleQuote();+ });++ panel.querySelectorAll('[data-buychip]').forEach((b) => b.addEventListener('click', () => {+ state.buySol = String(Number(b.dataset.buychip));+ state.confirming = false;+ renderAmount();+ scheduleQuote();+ }));+ panel.querySelectorAll('[data-sellchip]').forEach((b) => b.addEventListener('click', () => {+ const h = (state.holdings || []).find((t) => t.mint === state.coin?.mint);+ if (!h) return;+ state.sellRaw = pctOfRaw(h.amount_raw, Number(b.dataset.sellchip));+ state.sellDecimals = h.decimals ?? 6;+ state.confirming = false;+ renderAmount();+ scheduleQuote();+ }));++ panel.querySelectorAll('[data-slip]').forEach((b) => b.addEventListener('click', () => {+ state.slippageBps = Number(b.dataset.slip);+ renderSlippage();+ scheduleQuote();+ }));+ const slipEl = panel.querySelector('[data-tr="slipBps"]');+ if (slipEl) slipEl.addEventListener('input', () => {+ const n = Math.max(0, Math.min(5000, Math.round(Number(slipEl.value) || 0)));+ state.slippageBps = n || 300;+ panel.querySelectorAll('[data-slip]').forEach((x) => x.setAttribute('aria-pressed', String(state.slippageBps === Number(x.dataset.slip))));+ scheduleQuote();+ });++ panel.querySelector('[data-tr="retry-holdings"]')?.addEventListener('click', async () => {+ state.holdingsLoaded = false; renderAll(); await loadHoldings(); renderAll();+ });+ panel.querySelector('[data-tr="retry-history"]')?.addEventListener('click', async () => {+ state.historyLoaded = false; renderAll(); await loadHistory(); renderAll();+ });+ panel.querySelectorAll('[data-sell-mint]').forEach((b) => b.addEventListener('click', () => {+ const mint = b.dataset.sellMint;+ state.side = 'sell';+ state.mintInput = mint;+ state.sellDecimals = Number(b.dataset.sellDec) || 6;+ const h = (state.holdings || []).find((t) => t.mint === mint);+ state.sellRaw = h ? h.amount_raw : '0';+ state.result = null;+ state.confirming = false;+ renderAll();+ resolveCoin(mint);+ panel.scrollIntoView?.({ behavior: 'smooth', block: 'start' });+ }));++ wireActionEvents();+ }++ function wireActionEvents() {+ panel.querySelector('[data-tr="review"]')?.addEventListener('click', () => {+ state.confirming = true; renderActions();+ });+ panel.querySelector('[data-tr="cancel"]')?.addEventListener('click', () => {+ state.confirming = false; renderActions();+ });+ panel.querySelector('[data-tr="confirm"]')?.addEventListener('click', submit);+ panel.querySelectorAll('[data-tr="deposit"]').forEach((b) => b.addEventListener('click', () => {+ ctx.openTab?.('deposit');+ }));+ }++ // Partial re-renders to keep focus/caret stable while typing.+ function renderAmount() {+ const host = panel.querySelector('.awh-tr-amt')?.closest('.awh-tr-field');+ if (!host) { renderAll(); return; }+ host.outerHTML = amountFieldHtml();+ // Re-wire just the amount controls.+ const buySolEl = panel.querySelector('[data-tr="buySol"]');+ if (buySolEl) buySolEl.addEventListener('input', () => {+ state.buySol = buySolEl.value.replace(/[^0-9.]/g, '');+ state.confirming = false;+ const usdEl = panel.querySelector('.awh-tr-amt-usd');+ if (usdEl) usdEl.textContent = state.solPrice && Number(state.buySol) > 0 ? `≈ ${fmtUsd(Number(state.buySol) * state.solPrice)}` : '';+ scheduleQuote();+ });+ const sellUiEl = panel.querySelector('[data-tr="sellUi"]');+ if (sellUiEl) sellUiEl.addEventListener('input', () => {+ state.sellRaw = uiToRaw(sellUiEl.value.replace(/[^0-9.]/g, ''), state.sellDecimals);+ state.confirming = false;+ scheduleQuote();+ });+ panel.querySelectorAll('[data-buychip]').forEach((b) => b.addEventListener('click', () => {+ state.buySol = String(Number(b.dataset.buychip)); state.confirming = false; renderAmount(); scheduleQuote();+ }));+ panel.querySelectorAll('[data-sellchip]').forEach((b) => b.addEventListener('click', () => {+ const h = (state.holdings || []).find((t) => t.mint === state.coin?.mint);+ if (!h) return;+ state.sellRaw = pctOfRaw(h.amount_raw, Number(b.dataset.sellchip));+ state.confirming = false; renderAmount(); scheduleQuote();+ }));+ }+ function renderSlippage() {+ const host = panel.querySelector('.awh-tr-slip')?.closest('.awh-tr-field');+ if (!host) return;+ host.outerHTML = slippageHtml();+ panel.querySelectorAll('[data-slip]').forEach((b) => b.addEventListener('click', () => {+ state.slippageBps = Number(b.dataset.slip); renderSlippage(); scheduleQuote();+ }));+ const slipEl = panel.querySelector('[data-tr="slipBps"]');+ if (slipEl) slipEl.addEventListener('input', () => {+ const n = Math.max(0, Math.min(5000, Math.round(Number(slipEl.value) || 0)));+ state.slippageBps = n || 300;+ panel.querySelectorAll('[data-slip]').forEach((x) => x.setAttribute('aria-pressed', String(state.slippageBps === Number(x.dataset.slip))));+ scheduleQuote();+ });+ }++ // ── lifecycle ─────────────────────────────────────────────────────────────+ let firstShow = true;+ detachNet = ctx.onNetworkChange(() => {+ state.holdingsLoaded = false; state.historyLoaded = false;+ state.coin = null; state.quote = null; state.result = null; state.mintInput = '';+ renderAll();+ Promise.all([loadHoldings(), loadHistory()]).then(() => renderAll());+ });++ renderAll();++ return {+ async onShow() {+ if (firstShow) {+ firstShow = false;+ loadSolPrice();+ await Promise.all([loadHoldings(), loadHistory()]);+ if (!destroyed) renderAll();+ }+ },+ onHide() { clearTimeout(quoteTimer); state.confirming = false; },+ destroy() {+ destroyed = true;+ clearTimeout(quoteTimer);+ detachNet?.();+ },+ };+ },});diff --git a/src/agent-x402-pay.js b/src/agent-x402-pay.jsnew file mode 100644index 000000000..a66a6f193--- /dev/null+++ b/src/agent-x402-pay.js@@ -0,0 +1,158 @@+/**+ * Agent x402 pay — client for the wallet hub Pay tab.+ *+ * Thin fetch layer over the real endpoints — no mocks, no sample data:+ * - searchBazaarServices → GET /api/bazaar/search (Solana-payable x402 services)+ * - previewX402 → POST /api/x402-pay { preview } (live price + what's bought)+ * - payX402Stream → POST /api/x402-pay (SSE) (build → settle from agent wallet)+ * - fetchAgentUsdc → GET /api/agents/:id/solana/holdings (USDC balance, funding-aware)+ * - fetchX402Activity → GET /api/agents/:id/solana/custody?category=x402+ *+ * Every payment is signed + settled server-side from the agent's OWN custodial+ * Solana wallet (api/x402-pay.js). The shared platform wallet is never used here.+ */++// Browse / search the x402 bazaar, scoped to services payable in Solana USDC+// (the only network an agent's Solana wallet can settle). Returns normalized+// resources from api/_lib/x402/bazaar-client.js.+export async function searchBazaarServices(query = '', { maxPrice = null, limit = 24 } = {}) {+ const params = new URLSearchParams({ type: 'http', network: 'solana:*', limit: String(limit) });+ if (query) params.set('query', query);+ if (maxPrice != null) params.set('maxPrice', String(maxPrice));+ const resp = await fetch(`/api/bazaar/search?${params}`, { credentials: 'include' });+ const json = await resp.json().catch(() => ({}));+ if (!resp.ok) {+ throw new Error(json?.error?.message || json?.message || `search failed (${resp.status})`);+ }+ return {+ resources: Array.isArray(json.resources) ? json.resources : [],+ count: json.count || 0,+ errors: Array.isArray(json.errors) ? json.errors : [],+ };+}++// Fetch the live payment requirements for one endpoint without moving funds.+// Resolves to the server's preview envelope:+// { ok, requires_payment, payable?, price_usdc?, asset?, payTo?, network?, resource?, code? }+export async function previewX402({ agentId, url, method = 'GET', body = undefined }) {+ const resp = await fetch('/api/x402-pay', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agentId, url, method, body, preview: true }),+ });+ const json = await resp.json().catch(() => ({}));+ if (!resp.ok) {+ const e = new Error(json?.error_description || json?.error || `preview failed (${resp.status})`);+ e.code = json?.code || json?.error;+ e.status = resp.status;+ throw e;+ }+ return json;+}++// Pay an endpoint from the agent wallet, streaming the lifecycle as SSE.+// `on(event, data)` is called for each event ('challenge'|'built'|'settled'|+// 'result'|'error'). Resolves with the final result envelope, or rejects with an+// Error carrying `.code`/`.envelope` from the 'error' event.+export async function payX402Stream({ agentId, url, method = 'GET', body = undefined, serviceLabel = null }, on = () => {}) {+ const resp = await fetch('/api/x402-pay', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },+ body: JSON.stringify({ agentId, url, method, body, service_label: serviceLabel, stream: true }),+ });++ // A non-stream error (auth, rate limit, validation) comes back as JSON, not SSE.+ const ctype = resp.headers.get('content-type') || '';+ if (!resp.ok && !ctype.includes('text/event-stream')) {+ const json = await resp.json().catch(() => ({}));+ const e = new Error(json?.error_description || json?.error || `payment failed (${resp.status})`);+ e.code = json?.code || json?.error;+ e.status = resp.status;+ throw e;+ }+ if (!resp.body) throw new Error('payment stream unavailable');++ const reader = resp.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ let result = null;+ let failure = null;++ const dispatch = (event, dataRaw) => {+ let data = null;+ try {+ data = dataRaw ? JSON.parse(dataRaw) : null;+ } catch {+ data = null;+ }+ if (event === 'result') result = data;+ if (event === 'error') failure = data;+ try {+ on(event, data);+ } catch {+ /* a UI handler throwing must not break the stream pump */+ }+ };++ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let sep;+ while ((sep = buffer.indexOf('\n\n')) >= 0) {+ const frame = buffer.slice(0, sep);+ buffer = buffer.slice(sep + 2);+ let event = 'message';+ let data = '';+ for (const line of frame.split('\n')) {+ if (line.startsWith('event:')) event = line.slice(6).trim();+ else if (line.startsWith('data:')) data += line.slice(5).trim();+ }+ if (data || event !== 'message') dispatch(event, data);+ }+ }++ if (failure) {+ const e = new Error(failure.error_description || failure.error || 'payment failed');+ e.code = failure.code;+ e.envelope = failure;+ throw e;+ }+ if (!result) throw new Error('payment ended without a result');+ return result;+}++// The agent wallet's USDC balance (+ SOL), read from real holdings. Returns+// { address, usdc, sol } — usdc is 0 when the agent holds none yet.+export async function fetchAgentUsdc(agentId, network = 'mainnet') {+ const resp = await fetch(+ `/api/agents/${encodeURIComponent(agentId)}/solana/holdings?network=${encodeURIComponent(network)}`,+ { credentials: 'include' },+ );+ const json = await resp.json().catch(() => ({}));+ if (!resp.ok) {+ throw new Error(json?.error?.message || json?.error || `holdings failed (${resp.status})`);+ }+ const data = json.data || {};+ const usdcToken = Array.isArray(data.tokens) ? data.tokens.find((t) => t.is_usdc) : null;+ return {+ address: data.address || null,+ sol: typeof data.sol === 'number' ? data.sol : null,+ usdc: usdcToken ? Number(usdcToken.ui_amount) || 0 : 0,+ };+}++// The agent's x402 payment history from the custody ledger (category=x402).+export async function fetchX402Activity(agentId, network = 'mainnet', limit = 25) {+ const resp = await fetch(+ `/api/agents/${encodeURIComponent(agentId)}/solana/custody?network=${encodeURIComponent(network)}&category=x402&limit=${limit}`,+ { credentials: 'include' },+ );+ const json = await resp.json().catch(() => ({}));+ if (!resp.ok) {+ throw new Error(json?.error?.message || json?.error || `activity failed (${resp.status})`);+ }+ return Array.isArray(json.data?.items) ? json.data.items : [];+}diff --git a/src/club-crowd.js b/src/club-crowd.jsnew file mode 100644index 000000000..0287becf1--- /dev/null+++ b/src/club-crowd.js@@ -0,0 +1,376 @@+// /club crowd — fills every walk-in environment with three.ws avatars.+//+// As you walk the alley → gallery → clubhouse (src/club-entrance.js) you're no+// longer alone: each room is populated with a living crowd built from the full+// platform avatar roster — the bundled known-good rigs plus every public 3D+// avatar in the gallery (/api/explore). Each member is grounded on the room's+// floor, scaled to human height, and driven by a varied loop (idle/lean/chill+// near the entrance, dancing deeper in) so the rooms feel like a real club, not+// an empty set.+//+// Performance is the whole game here. We:+// • retarget each clip ONCE per unique avatar GLB (via AnimationManager), then+// reuse the resulting bound clips across every clone of that rig with a bare+// AnimationMixer — so a room of 80 dancers costs ~N cheap mixers, not N+// retargets;+// • cap the head-count to the device's `crowdInstances` budget (src/club-perf.js)+// and log when the roster is larger than the cap (no silent truncation);+// • clone once per instance (SkeletonUtils), leave frustum culling on, cast no+// shadows, and stagger instantiation so a swap never stalls the walk.+//+// Any failure degrades silently to a smaller (or empty) crowd — the walk-in and+// the pole stage always work without it. A rig the canonical clip library can't+// drive is skipped rather than left standing in a bind/T-pose.++import { AnimationMixer, Box3, Group, Raycaster, Vector3 } from 'three';+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';+import { gltfLoader } from './loaders/gltf.js';+import { AnimationManager } from './animation-manager.js';+import { log } from './shared/log.js';++// Clip pools, by mood. Names must exist in /animations/manifest.json; URLs are+// resolved from the manifest passed to the constructor. A missing clip is just+// dropped — the crowd falls back to whatever else retargeted on that rig.+const IDLE_CLIPS = ['idle', 'av-idle-breath', 'av-waiting', 'av-chilling', 'av-leaning-wall', 'av-listening-music', 'av-smoking'];+const DANCE_CLIPS = ['twerk', 'dance', 'rumba', 'av-dance-shuffle', 'av-rap-dance', 'av-headbang', 'av-banging-tunes', 'av-cheering', 'av-boxer-dance'];+const ALL_CROWD_CLIPS = [...new Set([...IDLE_CLIPS, ...DANCE_CLIPS])];++// Public 3D avatars to pull for the crowd. Larger page than the entrance's agent+// switcher (limit=24) so a populated room shows real variety; deduped by GLB URL+// against the bundled rigs.+const CROWD_GALLERY_URL = '/api/explore?source=avatar&category=avatar&only3d=1&limit=60';++const MIN_HEIGHT = 1.6;+const MAX_HEIGHT = 1.82;+// Keep the central walk lane (spawn → door) clear so the crowd lines the route+// rather than blocking it, and don't spawn anyone on top of the player.+const CORRIDOR_HALF_WIDTH = 1.35;+const SPAWN_CLEAR = 1.7;+const MIN_SPACING = 0.85;+const WALL_INSET = 0.6; // extra margin inside the walkable bounds+// Fraction of the crowd that dances rather than idles, per room index. The+// energy ramps up as you get closer to the stage.+const DANCE_RATIO = [0.18, 0.32, 0.6];+// Don't leave a room feeling dead when the gallery is unreachable — cycle the+// bundled rigs up to this floor (still capped by the device budget).+const LIVELY_FLOOR = 9;++const DOWN = new Vector3(0, -1, 0);+const _box = new Box3();+const _origin = new Vector3();++function scaleToHeight(obj, h) {+ _box.setFromObject(obj, true);+ const cur = _box.max.y - _box.min.y || 1;+ obj.scale.multiplyScalar(h / cur);+}+function groundFeet(obj) {+ _box.setFromObject(obj, true);+ if (Number.isFinite(_box.min.y)) obj.position.y -= _box.min.y;+}++function shuffle(arr) {+ const a = arr.slice();+ for (let i = a.length - 1; i > 0; i--) {+ const j = Math.floor(Math.random() * (i + 1));+ [a[i], a[j]] = [a[j], a[i]];+ }+ return a;+}++// Distance from point (px,pz) to the segment a→b in the XZ plane.+function distToSegmentXZ(px, pz, ax, az, bx, bz) {+ const dx = bx - ax, dz = bz - az;+ const len2 = dx * dx + dz * dz;+ let t = len2 > 1e-6 ? ((px - ax) * dx + (pz - az) * dz) / len2 : 0;+ t = Math.max(0, Math.min(1, t));+ const cx = ax + dx * t, cz = az + dz * t;+ return Math.hypot(px - cx, pz - cz);+}++function dedupeRoster(list) {+ const seen = new Set();+ const out = [];+ for (const a of list) {+ if (!a?.url || seen.has(a.url)) continue;+ seen.add(a.url);+ out.push({ name: a.name || 'Avatar', url: a.url });+ }+ return out;+}++export class ClubCrowd {+ /**+ * @param {object} opts+ * @param {import('three').WebGLRenderer} opts.renderer+ * @param {import('three').Scene} opts.scene+ * @param {Array} opts.manifest animation manifest (name→url defs)+ * @param {number} opts.max per-room instance cap (crowdInstances)+ * @param {Array<{name:string,url:string}>} [opts.bundled] guaranteed offline rigs+ */+ constructor({ renderer, scene, manifest, max, bundled = [] }) {+ this.scene = scene;+ this.loader = gltfLoader(renderer);+ this.max = Math.max(0, Math.floor(max) || 0);+ this.raycaster = new Raycaster();++ // name → clip URL, for the pools we actually use.+ this._clipUrls = new Map();+ const defs = Array.isArray(manifest) ? manifest : [];+ for (const name of ALL_CROWD_CLIPS) {+ const def = defs.find((d) => d?.name === name);+ if (def?.url) this._clipUrls.set(name, def.url);+ }++ // Parsed clip JSON, fetched once and shared across every template.+ this._clipJson = new Map(); // name → parsed AnimationClip JSON+ this._clipJsonReady = null; // Promise++ // url → Promise<{ scene, clips: Map<name, retargetedClip>, drivable }>+ this._templates = new Map();++ this._roster = dedupeRoster(bundled);+ this._rosterLoaded = false;++ // Current room: a fresh Group per mount, tracked so a swap disposes the+ // previous crowd. `_gen` cancels an in-flight async populate when the room+ // changes underneath it.+ this._root = null;+ this._instances = [];+ this._placed = []; // {x,z} of placed members, for spacing checks+ this._gen = 0;+ this._disposed = false;+ }++ /** Kick off the gallery roster + clip fetches. Safe to call repeatedly. */+ async load() {+ this._ensureClips();+ if (this._rosterLoaded) return;+ this._rosterLoaded = true;+ try {+ const res = await fetch(CROWD_GALLERY_URL, { headers: { accept: 'application/json' } });+ if (res.ok) {+ const data = await res.json();+ const items = Array.isArray(data?.items) ? data.items : [];+ const extra = items+ .filter((it) => it?.glbUrl && it.has3d !== false && it.kind === 'avatar')+ .map((it) => ({ name: it.name || 'Avatar', url: it.glbUrl }));+ this._roster = dedupeRoster([...this._roster, ...extra]);+ }+ } catch (err) {+ log.warn('[club-crowd] gallery roster fetch failed', err);+ }+ }++ _ensureClips() {+ if (this._clipJsonReady) return this._clipJsonReady;+ const entries = [...this._clipUrls.entries()];+ this._clipJsonReady = Promise.all(entries.map(async ([name, url]) => {+ try {+ const r = await fetch(url, { cache: 'force-cache' });+ if (r.ok) this._clipJson.set(name, await r.json());+ } catch (err) {+ log.warn(`[club-crowd] clip "${name}" fetch failed`, err);+ }+ })).then(() => this._clipJson);+ return this._clipJsonReady;+ }++ /**+ * Load a unique avatar GLB once and produce its reusable, retargeted clips.+ * Returns { scene, clips, drivable }. `clips` maps each crowd clip name to a+ * bound AnimationClip whose tracks are keyed by this rig's node names — those+ * names are identical on every SkeletonUtils.clone, so the clips drive any+ * clone via a plain AnimationMixer (no per-instance retarget).+ */+ _template(url) {+ if (this._templates.has(url)) return this._templates.get(url);+ const p = (async () => {+ await this._ensureClips();+ const gltf = await this.loader.loadAsync(url);+ const root = gltf.scene;+ root.traverse((n) => {+ if (!n.isMesh) return;+ n.castShadow = false;+ n.receiveShadow = false;+ });+ // Retarget against a throwaway clone so the shared template stays pristine.+ const ref = cloneSkinnedScene(root);+ const mgr = new AnimationManager();+ mgr.attach(ref, { avatarUrl: url });+ const clips = new Map();+ if (mgr.supportsCanonicalClips()) {+ for (const [name, json] of this._clipJson) {+ mgr.injectClip(name, json, { loop: true });+ const clip = mgr.actions.get(name)?.getClip?.();+ if (clip) clips.set(name, clip);+ }+ }+ mgr.detach();+ return { scene: root, clips, drivable: clips.size > 0 };+ })().catch((err) => {+ log.warn('[club-crowd] template load failed', url, err);+ return { scene: null, clips: new Map(), drivable: false };+ });+ this._templates.set(url, p);+ return p;+ }++ /**+ * Populate a freshly-mounted environment. Clears the previous room's crowd,+ * then scatters up to `max` avatars across the floor, clear of the walk lane.+ *+ * @param {object} ctx+ * @param {import('three').Object3D} ctx.envRoot the mounted environment group (for floor rays)+ * @param {{minX:number,maxX:number,minZ:number,maxZ:number}} ctx.bounds walkable bounds+ * @param {{spawn:import('three').Vector3, door:import('three').Vector3}} ctx.path+ * @param {number} ctx.roomIndex+ */+ mount({ envRoot, bounds, path, roomIndex = 0 }) {+ if (this._disposed || this.max <= 0) return;+ this.clear();+ const gen = ++this._gen;+ const root = new Group();+ root.name = 'club-crowd';+ this.scene.add(root);+ this._root = root;+ this._populate({ gen, root, envRoot, bounds, path, roomIndex })+ .catch((err) => log.warn('[club-crowd] populate failed', err));+ }++ async _populate({ gen, root, envRoot, bounds, path, roomIndex }) {+ await this.load();+ if (gen !== this._gen) return; // room swapped while we were fetching++ // Build the target roster: as many distinct avatars as the budget allows,+ // shuffled so each room differs. If the live roster is thin (gallery down),+ // cycle the bundled rigs up to a lively floor so the room never feels dead.+ const distinct = shuffle(this._roster);+ const targets = distinct.slice(0, this.max);+ const floor = Math.min(this.max, LIVELY_FLOOR);+ for (let i = 0; targets.length < floor && distinct.length; i++) {+ targets.push(distinct[i % distinct.length]);+ }+ if (this._roster.length > this.max) {+ log.info(`[club-crowd] roster ${this._roster.length} exceeds budget ${this.max} — showing ${this.max} this room`);+ }++ const danceRatio = DANCE_RATIO[Math.min(roomIndex, DANCE_RATIO.length - 1)] ?? 0.3;++ for (let i = 0; i < targets.length; i++) {+ if (gen !== this._gen) return;+ const spot = this._pickSpot(envRoot, bounds, path);+ if (!spot) break; // room is full / no clear floor left+ const tpl = await this._template(targets[i].url);+ if (gen !== this._gen) return;+ if (!tpl?.scene || !tpl.drivable) continue; // skip undrivable rigs (no T-pose crowd)++ const wantDance = Math.random() < danceRatio;+ this._spawn(root, tpl, spot, path, wantDance);+ this._placed.push({ x: spot.x, z: spot.z });++ // Yield between members so a large room fills progressively instead of+ // stalling the walk on one heavy frame.+ if ((i & 3) === 3) await new Promise((r) => setTimeout(r, 0));+ }+ }++ // Find a clear floor point: inside the bounds, off the walk lane, away from+ // the spawn, and not on top of another crowd member. Null when none found.+ _pickSpot(envRoot, bounds, path) {+ const minX = bounds.minX + WALL_INSET, maxX = bounds.maxX - WALL_INSET;+ const minZ = bounds.minZ + WALL_INSET, maxZ = bounds.maxZ - WALL_INSET;+ if (maxX <= minX || maxZ <= minZ) return null;+ for (let tries = 0; tries < 48; tries++) {+ const x = minX + Math.random() * (maxX - minX);+ const z = minZ + Math.random() * (maxZ - minZ);+ if (distToSegmentXZ(x, z, path.spawn.x, path.spawn.z, path.door.x, path.door.z) < CORRIDOR_HALF_WIDTH) continue;+ if (Math.hypot(x - path.spawn.x, z - path.spawn.z) < SPAWN_CLEAR) continue;+ let tooClose = false;+ for (const p of this._placed) {+ if (Math.hypot(x - p.x, z - p.z) < MIN_SPACING) { tooClose = true; break; }+ }+ if (tooClose) continue;+ const y = this._sampleFloor(envRoot, x, z);+ return { x, z, y };+ }+ return null;+ }++ // Cast straight down from waist height through the floor band — the same+ // strategy the player floor tracker uses — so sculpture/arch tops aren't hit.+ _sampleFloor(envRoot, x, z) {+ this.raycaster.set(_origin.set(x, 1.2, z), DOWN);+ this.raycaster.far = 1.6;+ const hit = this.raycaster.intersectObject(envRoot, true)[0];+ return hit ? Math.max(0, hit.point.y) : 0;+ }++ _spawn(root, tpl, spot, path, wantDance) {+ const clip = this._pickClip(tpl, wantDance);+ const model = cloneSkinnedScene(tpl.scene);+ model.traverse((n) => { if (n.isMesh) n.castShadow = false; });+ scaleToHeight(model, MIN_HEIGHT + Math.random() * (MAX_HEIGHT - MIN_HEIGHT));+ groundFeet(model);++ const group = new Group();+ group.add(model);+ group.position.set(spot.x, spot.y, spot.z);+ // Face roughly toward the walk lane (a crowd watching the route) with jitter;+ // dancers spin off in any direction.+ const cx = (path.spawn.x + path.door.x) / 2;+ const cz = (path.spawn.z + path.door.z) / 2;+ const faceYaw = Math.atan2(cx - spot.x, cz - spot.z);+ group.rotation.y = wantDance+ ? Math.random() * Math.PI * 2+ : faceYaw + (Math.random() - 0.5) * 1.1;+ root.add(group);++ let mixer = null;+ if (clip) {+ mixer = new AnimationMixer(model);+ const action = mixer.clipAction(clip);+ action.time = Math.random() * (clip.duration || 1); // desync the loop+ action.play();+ }+ this._instances.push({ group, mixer, model });+ }++ _pickClip(tpl, wantDance) {+ const pool = wantDance ? DANCE_CLIPS : IDLE_CLIPS;+ const avail = pool.filter((n) => tpl.clips.has(n));+ const pick = avail.length ? avail[Math.floor(Math.random() * avail.length)] : null;+ // Always fall back to a held clip so the member is never a static T-pose.+ const name = pick || (tpl.clips.has('idle') ? 'idle' : [...tpl.clips.keys()][0]);+ return name ? tpl.clips.get(name) : null;+ }++ /** Advance every crowd member's loop. Cheap — one mixer.update per member. */+ update(dt) {+ for (const inst of this._instances) inst.mixer?.update(dt);+ }++ /** Tear down the current room's crowd (called on every venue swap). */+ clear() {+ this._gen++; // cancel any in-flight populate+ for (const inst of this._instances) {+ inst.mixer?.stopAllAction();+ // Clones share geometry + materials with the cached template+ // (SkeletonUtils.clone) — disposing them would corrupt every other+ // clone and the template, so we only unparent.+ inst.group.parent?.remove(inst.group);+ }+ this._instances = [];+ this._placed = [];+ if (this._root) {+ this.scene.remove(this._root);+ this._root = null;+ }+ }++ dispose() {+ this._disposed = true;+ this.clear();+ this._templates.clear();+ }+}diff --git a/src/club-entrance.js b/src/club-entrance.jsindex c811c955b..671dd8694 100644--- a/src/club-entrance.js+++ b/src/club-entrance.js@@ -53,6 +53,8 @@ import {} from 'postprocessing';import { gltfLoader } from './loaders/gltf.js';import { AnimationManager } from './animation-manager.js';+import { ClubCrowd } from './club-crowd.js';+import { detectProfile, PROFILES } from './club-perf.js';import { log } from './shared/log.js';const TOUR_URL = '/club/venue/tour.glb';@@ -288,6 +290,25 @@ async function start(canvasEl) {anim.injectClip('walk', walkClipJson, { loop: true });await anim.play('idle');+ // ── Crowd — populate every environment with our avatars ──+ // You don't walk an empty set: each room fills with the full platform roster+ // (bundled rigs + public gallery), grounded and dancing/idling clear of your+ // path. Sized to the device's crowd budget; degrades to nothing if it can't+ // load. Re-populated on every venue swap via refreshCrowd().+ const crowdProfile = PROFILES[detectProfile()] || PROFILES.medium;+ const crowd = new ClubCrowd({+ renderer,+ scene,+ manifest,+ max: crowdProfile.crowdInstances,+ bundled: BUNDLED_AGENTS,+ });+ crowd.load(); // background fetch of roster + clip data; mount() awaits it+ const refreshCrowd = () => {+ if (!env) return;+ crowd.mount({ envRoot: env.root, bounds: env.bounds, path, roomIndex: venueIndex });+ };+// ── Door marker — a neon frame at the end of the alley you walk up to ────const doorMarker = buildDoorMarker();scene.add(doorMarker.group);@@ -311,6 +332,7 @@ async function start(canvasEl) {const camRay = new Raycaster();placeSpawn();+ refreshCrowd(); // populate the opening room (alley)// Cast straight down from waist height to find the walkable floor.// Starting from ROOM_HEIGHT * 0.6 wrongly hit sculpture tops / arch geometry@@ -688,6 +710,7 @@ async function start(canvasEl) {stepAvatar(ix, iz, dt);trackFloor(dt);anim.update(dt);+ crowd.update(dt);updateCamera(dt);if (phase === 'walk') minimap.update(rig.position, rig.rotation.y, nearDoor, now / 1000, prefersReducedMotion);@@ -720,6 +743,7 @@ async function start(canvasEl) {if (next && next !== 'error') {mountVenue(venueIndex + 1);placeSpawn();+ refreshCrowd(); // fill the next room with the rostersetHint();setPhase('swapIn');} else if (next === 'error') {@@ -872,6 +896,7 @@ async function start(canvasEl) {agentBrowseBtn?.removeEventListener('click', onBrowseAgents);onAdmit = null;try { anim.dispose?.(); } catch {}+ try { crowd.dispose(); } catch {}disposeObject(scene);composer.dispose();renderer.dispose();diff --git a/tasks/ibm-x402-demo/08-copy-brand-compliance.md b/tasks/ibm-x402-demo/08-copy-brand-compliance.mddeleted file mode 100644index 60fdf7a26..000000000--- a/tasks/ibm-x402-demo/08-copy-brand-compliance.md+++ /dev/null@@ -1,69 +0,0 @@-# Task 08 — Copy, brand & $THREE-compliance review--## Context--three.ws workspace at `/workspaces/three.ws`. Deliverable + verified facts:-[00-PLAN.md](00-PLAN.md). The page is [`pages/ibm/x402-demo.html`](../../pages/ibm/x402-demo.html).--This page represents both three.ws and IBM. Every word must be accurate, enterprise-clear, and-compliant. Mind the repo's public-copy rule: professional and literal ("3D AI agents", "pay-per-call-API"), never sci-fi metaphor.--## Do this--1. **Technical accuracy.** Verify the x402 explanation is correct and crisp: HTTP `402` →- machine-readable payment terms → signed stablecoin authorization → retry with `X-PAYMENT` →- on-chain settlement. No overclaiming ("instant", "free", "no fees" — the network fee is- sponsored, not nonexistent; say so precisely).-2. **Honesty about real money.** The page must be unambiguous that this spends **real USDC on- mainnet** (a tenth of a cent) and needs a funded wallet. No dark patterns. The existing note- is a good start — tighten it.-3. **IBM brand correctness.** The inline IBM mark is a placeholder `<rect>+text` SVG. Replace it- with a correct treatment (the proper 8-bar IBM logo, or a clean wordmark) and confirm- "IBM Business Partner" usage matches IBM's brand guidelines (lockup, spacing, the relationship- wording). If unsure of exact rights, use a neutral, defensible treatment and flag it for the- user to confirm with IBM. Use IBM Plex + Carbon blue `#0f62fe` (already in place).-4. **$THREE compliance (hard rule).** `$THREE` must be the **only** coin referenced anywhere on- the page — copy, examples, metadata, comments. The footer line is present; keep it.- - The default ticker `GRANITE` is IBM's model family, **not a coin** — fine.- - The `symbol-availability` endpoint can surface real launched tickers at runtime in- `similar[]` (the allowed launch-directory exception). Decide whether arbitrary- user-launched tickers appearing on an IBM page is desirable. If not, prefer ticker inputs- (like `GRANITE`) that return clean/empty results, and ensure nothing in **static** copy- names another coin.-5. **Endpoint-narrative decision.** `symbol-availability` is pump.fun-flavored. Evaluate whether- to keep it or swap to a cleaner enterprise data call (e.g. `/api/x402/skill-marketplace`,- also $0.001 — "query the agent-skill marketplace"). **If you swap:** the price tag + 402- preview are endpoint-agnostic, but the result-body renderer is symbol-availability-shaped, so- update the renderer to the new response schema and re-verify with task 01's flow. Record the- decision and rationale in the completion report. (Default: keep `symbol-availability` unless- the enterprise narrative clearly improves — don't churn without reason.)-6. **Plain-language & scannability.** Headlines, the 3-step strip, button label, empty/idle copy,- error copy (coordinate with task 03). Read it as a first-time enterprise visitor who has never- heard of x402 — does each section land in seconds?-7. **Links & metadata.** Every link resolves (docs, bazaar, changelog). `<title>`,- `meta description`, and any OG tags are accurate and partnership-appropriate.--## Definition of done--- Copy is accurate, professional, literal, and honest about real-money spend; no overclaiming,- no metaphor.-- IBM brand treatment is correct (or a defensible neutral treatment flagged for IBM sign-off).-- `$THREE` is the only coin anywhere on the page; static copy names no other coin.-- The endpoint-narrative decision is made and recorded; if swapped, the renderer is updated and- re-verified.-- All links resolve; title/description/OG accurate. No console errors. Run the **completionist**- subagent.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--```bash-git rm "tasks/ibm-x402-demo/08-copy-brand-compliance.md"-```--Stage the deletion in the same commit as the implementation. A file that still exists is-unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/irl-floor-anchor/SIGN-OFF.md b/tasks/irl-floor-anchor/SIGN-OFF.mdnew file mode 100644index 000000000..5a706df7e--- /dev/null+++ b/tasks/irl-floor-anchor/SIGN-OFF.md@@ -0,0 +1,108 @@+# IRL floor-anchor — verification sign-off (task 07)++> Closes the epic. Records what the fake-XR harness proves in CI vs. what only a+> real device can confirm, the one bug verification surfaced, and the DoD walk.++## What ships provable without a phone++WebXR `immersive-ar` can't be driven by a headless browser — no camera, no IMU,+no compositor — so before this task the floor-anchor session was only ever+exercised on one Android phone, and any regression in its session lifecycle or+pose math would have shipped invisibly. The harness closes that gap.++- **`tests/helpers/fake-xr.js`** — stand-ins for `navigator.xr`, `XRSession`,+ `XRFrame`, `XRHitTestResult`, `XRReferenceSpace` and `XRAnchor`. A test feeds a+ scripted sequence of frames (no-hit → hit at a known matrix → anchored), fires+ `select` / `visibilitychange` / `end`, and steps the render loop by hand. Three.js+ stays **real** (the reticle group, scene, content, XR camera, matrix math); only+ the GPU renderer and the XR device are faked.+- **`tests/ar-webxr-session.test.js`** — 14 lifecycle tests, green in CI with no+ hardware:+ - session bring-up wires `hit-test` (required), `anchors`/`local-floor`/`dom-overlay`+ (optional, the last only when a root is supplied);+ - `onHit` fires only on the searching↔found transition; the reticle Group and+ content track the hit pose; tap retires the reticle and emits `onAnchored` with+ the **tap-moment** pose and `{ degraded: false }`; the live anchor then drives+ content frame-to-frame;+ - **degraded path (task 05):** `createAnchor` rejecting *or* being absent still+ anchors, flagged `{ degraded: true }`, frozen at the tap pose — never broken;+ a second tap is ignored (anchor exactly once);+ - **OS-initiated end** restores the viewer (XR disabled, loop torn down, hit-test+ source cancelled, reticle/shadow/pulse disposed, controls re-enabled, content+ transform restored, visibilitychange unsubscribed) and runs **exactly once** —+ a redundant `end()` is a no-op;+ - **tracking loss** declares lost only after the sustained miss threshold, fires+ once, recovers on the first pose, and hides the reticle so no stale target is+ tappable; **visibility** changes fire per transition and pause per-frame work+ while hidden;+ - **write-path round-trip:** a known hit matrix → `_readAnchorPose` →+ `anchorPoseToPin` reloads to the exact east/north/height/heading we tapped+ (`source: 'webxr'`), end-to-end through the real session.++Pure layers already had their own suites and still pass: `ar-anchor-lifecycle`+(tracking machine, visibility enum, persist-gate save-exactly-once),+`irl-floor-anchor` (pose→pin math incl. sub-degree facing), `irl-room-anchor`.+Combined: **71/71 green.** `npm run typecheck` clean.++## Bug found and fixed during verification++The harness caught a real conflict the on-device testing never would have: on+tracking loss `_setTracking` hid the reticle, but later in the **same** `_tick`+the hit-block's dropout-tolerance branch re-showed it (`reticle.visible = _hadHit`),+leaving exactly the stale reticle the code comment promises is hidden. Fixed in+[src/ar/webxr.js](../../src/ar/webxr.js) by gating the re-show on+`!this._trackingState.lost`, so brief dropouts still hold a calm dim reticle while+genuine tracking loss keeps it hidden. Covered by the "hides the reticle on+tracking loss" test.++## Console audit (`/irl` AR flow)++The AR device layer — `src/ar/webxr.js`, `src/ar/depth-occlusion.js`,+`src/ar/anchor-lifecycle.js` — emits **no** console output on any path (the paused+tick is deliberately silent). The only AR-flow logs live in `src/irl.js`:++- `log.error('[irl] WebXR start failed:', err)` — fires only on a genuine session+ rejection (camera/motion denied, or a device that can't hold AR) and is paired+ with the actionable error UI (Retry / Use Pin instead). Intentional; `error` is+ un-gated by design (`src/shared/log.js`).+- `log.info('[irl] simulated location cleared …')` — dev-only simulated-GPS path;+ `info` is silenced in production unless `?debug` is set.++No other console lines originate in the AR flow. A full Playwright route audit+(`npm run audit:web`) cannot enter `immersive-ar` headlessly — which is the whole+reason this harness exists — so the in-session console is audited by source review+plus the harness; the surrounding `/irl` page is covered by the standard audit.++## Confirmed on real hardware vs. harness++| Behavior | Harness (CI) | Real device |+| --- | --- | --- |+| Session start / feature negotiation | ✅ asserted | ⬜ pending hardware pass |+| Hit-test reticle + content follow | ✅ asserted | ⬜ |+| Tap → anchor → live anchor follow | ✅ asserted | ⬜ |+| Degraded (no/failed `createAnchor`) fallback | ✅ asserted | ⬜ |+| Tracking-loss / recovery + reticle hide | ✅ asserted | ⬜ |+| Backgrounding pause / resume (call, lock) | ✅ asserted | ⬜ |+| OS-end restoration, idempotent | ✅ asserted | ⬜ |+| Pose → GPS pin numeric round-trip | ✅ asserted | ⬜ |+| Real-world occlusion (depth-sensing) | ⬜ device-only | ⬜ Android w/ depth |+| iOS AR Quick Look placement parity (task 06) | ⬜ device-only | ⬜ iPhone |+| Cross-user reload at the same spot/angle | ✅ math asserted | ⬜ two devices |++**Manual pass to record before final ship:** one Android WebXR device (anchor+hold, occlusion behind real geometry, recovery after a phone call) and one iPhone+(Quick Look entry/exit, placement parity). The harness's claims above should match+what those two devices show; note any divergence here.++## Definition of Done++- [x] Harness + lifecycle suite exercise hit/tap/anchor/degrade/visibility/end with+ no hardware; `npm test` suites green (71/71 across the AR/IRL pure + session+ tests), `typecheck` clean.+- [x] Write-path pose round-trip asserted numerically end-to-end.+- [x] Console audit clean; the two intentional `/irl` log lines documented benign.+- [x] One real bug surfaced by verification, fixed, and covered by a test.+- [x] Changelog entry added (`data/changelog.json`) and validated by+ `npm run build:pages`. `npm run changelog:push` left for post-deploy.+- [x] No mocks/fake data in shipped code; the harness lives under `tests/` only.+- [ ] Real-device pass (Android + iPhone) — pending physical hardware; table above.diff --git a/tests/agent-trade-endpoint.test.js b/tests/agent-trade-endpoint.test.jsnew file mode 100644index 000000000..43548970b--- /dev/null+++ b/tests/agent-trade-endpoint.test.js@@ -0,0 +1,450 @@+// Tests for the discretionary agent-wallet trade endpoint + its shared guardrails.+//+// Two layers:+// 1. The pure guard predicates + trade-limit normalization + the guard→HTTP+// mapping in api/_lib/agent-trade-guards.js — the single source of truth the+// sniper and the endpoint both call.+// 2. POST /api/agents/:id/trade end-to-end with the RPC, DB, custodial key, and+// SOL price all mocked: auth + ownership gating, every guard rejection as a+// structured 4xx, idempotent replay, paper-mode simulate, and a live buy that+// signs + confirms — asserting no secret ever appears in the response.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';+import { Keypair, PublicKey } from '@solana/web3.js';++// ── mocks ──────────────────────────────────────────────────────────────────────++const AGENT_KP = Keypair.generate();+const AGENT_ADDR = AGENT_KP.publicKey.toBase58();+const ENCRYPTED_SECRET = 'ENCRYPTED::do-not-leak::ZW5jcnlwdGVk';++const sqlState = {+ agent: null,+ existingCustody: null,+ claim: [{ id: 1 }],+ dailyLamports: '0',+ dailyUsd: 0,+ openTrades: 0,+ calls: [],+};++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ const q = (typeof strings === 'string' ? strings : strings.join('?')).toLowerCase();+ sqlState.calls.push({ q, values });+ if (/from agent_identities/.test(q) && /select/.test(q)) {+ return sqlState.agent ? [sqlState.agent] : [];+ }+ if (/from agent_custody_events/.test(q) && /idempotency_key =/.test(q) && /select/.test(q)) {+ return sqlState.existingCustody ? [sqlState.existingCustody] : [];+ }+ if (/insert into agent_custody_events/.test(q)) return sqlState.claim;+ if (/sum\(amount_lamports\)/.test(q)) return [{ lamports: sqlState.dailyLamports }];+ if (/sum\(usd\)/.test(q)) return [{ usd: sqlState.dailyUsd }];+ if (/count\(\*\)/.test(q)) return [{ n: sqlState.openTrades }];+ return [];+ }),+}));++vi.mock('../api/_lib/avatar-wallet.js', () => ({+ solUsdPrice: vi.fn(async () => 200),+ explorerTxUrl: (sig, net) => `https://explorer.example/tx/${sig}?cluster=${net}`,+}));++vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));++const authState = { session: { id: 'owner-1' }, bearer: null };+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => authState.session),+ authenticateBearer: vi.fn(async () => authState.bearer),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ tradePerUser: vi.fn(async () => ({ success: true })),+ authIp: vi.fn(async () => ({ success: true })),+ walletRead: vi.fn(async () => ({ success: true })),+ },+ clientIp: () => '127.0.0.1',+}));++vi.mock('../api/_lib/agent-wallet.js', () => ({+ ensureAgentWallet: vi.fn(async () => ({ address: AGENT_ADDR, created: false })),+ recoverSolanaAgentKeypair: vi.fn(async () => AGENT_KP),+}));++vi.mock('../workers/agent-sniper/amm-exit.js', () => ({+ buildAmmSellInstructions: vi.fn(async () => ({ instructions: [], expectedQuoteOut: 50_000_000n })),+ quoteAmmSell: vi.fn(async () => ({ expectedQuoteOut: 50_000_000n, minQuoteOut: 47_000_000n, priceImpactPct: 2 })),+}));++class FakeBN {+ constructor(v) { this.v = BigInt(v); }+ toString() { return this.v.toString(); }+}++const clientState = {+ buyImpact: 1,+ expectedBaseTokens: '1000000',+ sellImpact: 1,+ expectedQuoteOut: '50000000',+ buyThrows: null,+ sellThrows: null,+};++const connState = {+ balance: 5_000_000_000n, // 5 SOL+ sendSig: 'SIG_LIVE_123',+ confirmErr: null,+};++function fakeCtx() {+ const wsol = new PublicKey('So11111111111111111111111111111111111111112');+ return {+ BN: FakeBN,+ web3: { PublicKey },+ connection: {+ getBalance: vi.fn(async () => Number(connState.balance)),+ getLatestBlockhash: vi.fn(async () => ({ blockhash: PublicKey.default.toBase58(), lastValidBlockHeight: 100 })),+ sendRawTransaction: vi.fn(async () => connState.sendSig),+ confirmTransaction: vi.fn(async () => ({ value: { err: connState.confirmErr } })),+ simulateTransaction: vi.fn(async () => ({ value: { err: null, unitsConsumed: 1234 } })),+ getSignatureStatus: vi.fn(async () => ({ value: { err: null, confirmationStatus: 'confirmed' } })),+ },+ client: {+ quoteForBuy: vi.fn(async () => {+ if (clientState.buyThrows) throw clientState.buyThrows;+ return { expectedBaseTokens: { toString: () => clientState.expectedBaseTokens }, quoteMint: wsol, priceImpactPct: clientState.buyImpact };+ }),+ buildBuyInstructions: vi.fn(async () => ({ instructions: [], expectedBaseTokens: { toString: () => clientState.expectedBaseTokens } })),+ quoteForSell: vi.fn(async () => {+ if (clientState.sellThrows) throw clientState.sellThrows;+ return { expectedQuoteOut: { toString: () => clientState.expectedQuoteOut }, quoteMint: wsol, priceImpactPct: clientState.sellImpact };+ }),+ buildSellInstructions: vi.fn(async () => ({ instructions: [], expectedQuoteOut: { toString: () => clientState.expectedQuoteOut } })),+ },+ };+}++vi.mock('../api/_lib/pump.js', () => ({+ getPumpTradeClient: vi.fn(async () => fakeCtx()),+ getConnection: vi.fn(() => fakeCtx().connection),+}));++// Keep the real ATA derivation + program ids; stub only the on-chain mint read.+vi.mock('@solana/spl-token', async (orig) => ({+ ...(await orig()),+ getMint: vi.fn(async () => ({ decimals: 6 })),+}));++const guards = await import('../api/_lib/agent-trade-guards.js');+const { default: handler } = await import('../api/agents/agent-trade.js');++const AGENT_ID = '11111111-1111-4111-8111-111111111111';+const MINT = Keypair.generate().publicKey.toBase58();++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++function mockReq({ method = 'POST', url = '/', body = null } = {}) {+ const chunks = body != null ? [Buffer.from(JSON.stringify(body))] : [];+ const r = Readable.from(chunks);+ r.method = method;+ r.url = url;+ r.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json' };+ return r;+}++function setAgent(meta = {}) {+ sqlState.agent = { id: AGENT_ID, user_id: 'owner-1', meta: { solana_address: AGENT_ADDR, encrypted_solana_secret: ENCRYPTED_SECRET, ...meta } };+}++async function execTrade(body) {+ const req = mockReq({ method: 'POST', url: `/api/agents/${AGENT_ID}/trade`, body });+ const res = mockRes();+ await handler(req, res, AGENT_ID, undefined);+ return res;+}++beforeEach(() => {+ sqlState.agent = null;+ sqlState.existingCustody = null;+ sqlState.claim = [{ id: 1 }];+ sqlState.dailyLamports = '0';+ sqlState.dailyUsd = 0;+ sqlState.openTrades = 0;+ sqlState.calls = [];+ authState.session = { id: 'owner-1' };+ authState.bearer = null;+ clientState.buyImpact = 1;+ clientState.expectedBaseTokens = '1000000';+ clientState.sellImpact = 1;+ clientState.expectedQuoteOut = '50000000';+ clientState.buyThrows = null;+ clientState.sellThrows = null;+ connState.balance = 5_000_000_000n;+ connState.sendSig = 'SIG_LIVE_123';+ connState.confirmErr = null;+ delete process.env.SNIPER_MODE;+ setAgent();+});++// ── pure guard predicates ────────────────────────────────────────────────────++describe('trade guard predicates', () => {+ it('checkPerTradeCap blocks an over-cap buy, passes at the cap', () => {+ expect(guards.checkPerTradeCap(100_000_000n, 50_000_000n)).toMatchObject({ reason: 'per_trade_cap' });+ expect(guards.checkPerTradeCap(50_000_000n, 50_000_000n)).toBeNull();+ expect(guards.checkPerTradeCap(100n, null)).toBeNull(); // no cap set+ });++ it('checkDailyBudgetLamports blocks when spent + amount exceeds budget', () => {+ expect(guards.checkDailyBudgetLamports(30n, 25n, 50n)).toMatchObject({ reason: 'daily_budget' });+ expect(guards.checkDailyBudgetLamports(25n, 25n, 50n)).toBeNull();+ expect(guards.checkDailyBudgetLamports(999n, 999n, null)).toBeNull();+ });++ it('checkConcurrency blocks at/over the cap', () => {+ expect(guards.checkConcurrency(3, 3)).toMatchObject({ reason: 'max_positions' });+ expect(guards.checkConcurrency(2, 3)).toBeNull();+ expect(guards.checkConcurrency(99, null)).toBeNull();+ });++ it('checkSolHeadroom blocks when the wallet cannot cover spend + fees', () => {+ expect(guards.checkSolHeadroom(1_000_000n, 0n, 3_000_000n)).toMatchObject({ reason: 'insufficient_sol' });+ expect(guards.checkSolHeadroom(10_000_000n, 5_000_000n, 3_000_000n)).toBeNull();+ });++ it('checkPriceImpact trips strictly above the max', () => {+ expect(guards.checkPriceImpact(16, 15)).toMatchObject({ reason: 'price_impact' });+ expect(guards.checkPriceImpact(15, 15)).toBeNull();+ expect(guards.checkPriceImpact(99, null)).toBeNull();+ });++ it('checkKillSwitch trips only when paused', () => {+ expect(guards.checkKillSwitch(true)).toMatchObject({ reason: 'kill_switch' });+ expect(guards.checkKillSwitch(false)).toBeNull();+ });++ it('tradeGuardResponse maps each reason to a 4xx with an actionable message', () => {+ const r = guards.tradeGuardResponse({ reason: 'per_tx_cap', detail: {} }); // unknown → generic 422+ expect(r.status).toBe(422);+ const cap = guards.tradeGuardResponse({ reason: 'per_trade_cap', detail: { amount_lamports: '100000000', cap_lamports: '50000000' } });+ expect(cap.status).toBe(422);+ expect(cap.code).toBe('per_trade_cap');+ expect(cap.message).toMatch(/per-trade cap/i);+ expect(guards.tradeGuardResponse({ reason: 'kill_switch', detail: {} }).status).toBe(403);+ expect(guards.tradeGuardResponse({ reason: 'insufficient_sol', detail: { wallet_lamports: '0', required_lamports: '3000000' } }).status).toBe(400);+ });+});++describe('normalizeTradeLimits', () => {+ it('applies sane defaults and clamps out-of-range knobs', () => {+ const n = guards.normalizeTradeLimits(undefined);+ expect(n.per_trade_sol).toBeNull();+ expect(n.daily_budget_sol).toBeNull();+ expect(n.max_price_impact_pct).toBe(15);+ expect(n.max_slippage_bps).toBe(1000);+ expect(n.kill_switch).toBe(false);++ const clamped = guards.normalizeTradeLimits({ max_price_impact_pct: 999, max_slippage_bps: 99999, per_trade_sol: -1, kill_switch: true });+ expect(clamped.max_price_impact_pct).toBe(100);+ expect(clamped.max_slippage_bps).toBe(10000);+ expect(clamped.per_trade_sol).toBeNull();+ expect(clamped.kill_switch).toBe(true);+ });++ it('getTradeLimits reads off meta.trade_limits', () => {+ const lim = guards.getTradeLimits({ trade_limits: { per_trade_sol: 0.25, kill_switch: true } });+ expect(lim.per_trade_sol).toBe(0.25);+ expect(lim.kill_switch).toBe(true);+ });+});++// ── endpoint: auth + ownership ───────────────────────────────────────────────++describe('POST /api/agents/:id/trade — auth & ownership', () => {+ it('rejects an unauthenticated caller with 401', async () => {+ authState.session = null;+ authState.bearer = null;+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });+ expect(res.statusCode).toBe(401);+ expect(res.json.error).toBe('unauthorized');+ });++ it('rejects a non-owner with 403', async () => {+ sqlState.agent.user_id = 'someone-else';+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });+ expect(res.statusCode).toBe(403);+ expect(res.json.error).toBe('forbidden');+ });++ it('404s an unknown agent', async () => {+ sqlState.agent = null;+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });+ expect(res.statusCode).toBe(404);+ });+});++// ── endpoint: input validation ───────────────────────────────────────────────++describe('POST /api/agents/:id/trade — input', () => {+ it('rejects a bad side', async () => {+ const res = await execTrade({ side: 'hodl', mint: MINT, amount: 0.1 });+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('invalid_side');+ });++ it('rejects an invalid mint', async () => {+ const res = await execTrade({ side: 'buy', mint: 'not-a-mint!', amount: 0.1 });+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('invalid_mint');+ });++ it('rejects a non-positive amount', async () => {+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0 });+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('invalid_amount');+ });+});++// ── endpoint: guard rejections (each a structured 4xx, never a 500) ──────────++describe('POST /api/agents/:id/trade — guard rejections', () => {+ it('kill switch → 403 kill_switch', async () => {+ setAgent({ trade_limits: { kill_switch: true } });+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });+ expect(res.statusCode).toBe(403);+ expect(res.json.error).toBe('kill_switch');+ });++ it('over per-trade cap → 422 per_trade_cap', async () => {+ setAgent({ trade_limits: { per_trade_sol: 0.05 } });+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });+ expect(res.statusCode).toBe(422);+ expect(res.json.error).toBe('per_trade_cap');+ expect(res.json.detail).toBeTruthy();+ });++ it('over daily budget → 422 daily_budget', async () => {+ setAgent({ trade_limits: { daily_budget_sol: 0.1 } });+ sqlState.dailyLamports = String(90_000_000n); // 0.09 SOL already today+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.05 });+ expect(res.statusCode).toBe(422);+ expect(res.json.error).toBe('daily_budget');+ });++ it('price impact over the breaker → 422 price_impact', async () => {+ clientState.buyImpact = 40;+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });+ expect(res.statusCode).toBe(422);+ expect(res.json.error).toBe('price_impact');+ });++ it('insufficient SOL → 400 insufficient_sol', async () => {+ connState.balance = 0n;+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('insufficient_sol');+ });++ it('over-cap concurrency → 409 max_positions', async () => {+ setAgent({ trade_limits: { max_concurrent: 1 } });+ sqlState.openTrades = 1;+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });+ expect(res.statusCode).toBe(409);+ expect(res.json.error).toBe('max_positions');+ });+});++// ── endpoint: idempotency ────────────────────────────────────────────────────++describe('POST /api/agents/:id/trade — idempotency', () => {+ it('replays a confirmed trade for the same key without re-executing', async () => {+ sqlState.existingCustody = { id: 9, status: 'confirmed', signature: 'PRIOR_SIG', meta: { side: 'buy' } };+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1, idempotency_key: 'k-1' });+ expect(res.statusCode).toBe(200);+ expect(res.json.data.replayed).toBe(true);+ expect(res.json.data.signature).toBe('PRIOR_SIG');+ });++ it('409s a same-key trade still in flight', async () => {+ sqlState.existingCustody = { id: 9, status: 'pending', signature: null, meta: {} };+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1, idempotency_key: 'k-2' });+ expect(res.statusCode).toBe(409);+ expect(res.json.error).toBe('trade_in_progress');+ });++ it('409s when the idempotency INSERT loses the race (ON CONFLICT → no row)', async () => {+ sqlState.claim = []; // conflict: another request already claimed+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1, idempotency_key: 'k-3' });+ expect(res.statusCode).toBe(409);+ expect(res.json.error).toBe('trade_in_progress');+ });+});++// ── endpoint: paper mode + live execution ────────────────────────────────────++describe('POST /api/agents/:id/trade — execution', () => {+ it('simulate buy runs the real quote path but never signs or records', async () => {+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1, simulate: true });+ expect(res.statusCode).toBe(200);+ expect(res.json.data.simulated).toBe(true);+ expect(res.json.data.expected_tokens_out || res.json.data.expected_out).toBeTruthy();+ // No idempotency INSERT in simulate mode.+ expect(sqlState.calls.some((c) => /insert into agent_custody_events/.test(c.q))).toBe(false);+ });++ it('honors SNIPER_MODE=simulate as the paper toggle', async () => {+ process.env.SNIPER_MODE = 'simulate';+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1 });+ expect(res.json.data.simulated).toBe(true);+ });++ it('live buy signs, confirms, records, and never leaks the secret', async () => {+ const res = await execTrade({ side: 'buy', mint: MINT, amount: 0.1, idempotency_key: 'live-1' });+ expect(res.statusCode).toBe(200);+ expect(res.json.data.replayed).toBe(false);+ expect(res.json.data.signature).toBe('SIG_LIVE_123');+ expect(res.json.data.tokens_received).toBe('1000000');+ expect(res.json.data.side).toBe('buy');+ // The decrypted secret must never surface in the response.+ expect(res._body).not.toContain(ENCRYPTED_SECRET);+ expect(res._body).not.toMatch(/encrypted_solana_secret/);+ // It did claim + confirm the ledger row.+ expect(sqlState.calls.some((c) => /insert into agent_custody_events/.test(c.q))).toBe(true);+ expect(sqlState.calls.some((c) => /update agent_custody_events/.test(c.q))).toBe(true);+ });++ it('a sell from a graduated curve routes through the AMM path', async () => {+ const grad = Object.assign(new Error('graduated'), { name: 'CoinGraduatedError' });+ clientState.sellThrows = grad;+ const ammExit = await import('../workers/agent-sniper/amm-exit.js');+ // Sell 100 tokens; resolveHolding reads the on-chain balance via the ctx+ // connection — give it a balance by stubbing getTokenAccountBalance.+ const { getPumpTradeClient } = await import('../api/_lib/pump.js');+ getPumpTradeClient.mockImplementationOnce(async () => {+ const ctx = fakeCtx();+ ctx.connection.getAccountInfo = vi.fn(async () => ({ owner: new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA') }));+ ctx.connection.getTokenAccountBalance = vi.fn(async () => ({ value: { amount: '1000000000' } }));+ return ctx;+ });+ const res = await execTrade({ side: 'sell', mint: MINT, amount: 'max', idempotency_key: 'sell-1' });+ expect(res.statusCode).toBe(200);+ expect(res.json.data.venue).toBe('amm');+ expect(ammExit.buildAmmSellInstructions).toHaveBeenCalled();+ });+});diff --git a/tests/agent-wallet-trade.test.js b/tests/agent-wallet-trade.test.jsnew file mode 100644index 000000000..d8f8b2f94--- /dev/null+++ b/tests/agent-wallet-trade.test.js@@ -0,0 +1,267 @@+// Integration tests for the discretionary agent-wallet trade endpoint+// (api/agents/solana-trade.js handleTrade, POST /api/agents/:id/solana/trade).+//+// Proves at the handler layer:+// 1. validation (bad side / bad mint) → 400, key never recovered+// 2. preview → live quote, never signs/sends+// 3. execute without idempotency_key → 400, key never recovered+// 4. spend-limit breach (per-tx ceiling) → 403 with the reason, key safe+// 5. insufficient SOL for a buy → 402 with deposit-able detail+// 6. idempotency replay of a confirmed trade → 200 replayed, never re-sends+// 7. live buy on the bonding curve → 200 confirmed signature+//+// All Solana RPC, the agent key recovery, the pump SDK builders, and the SOL price+// feed are mocked so the orchestration is deterministic. The shared spend policy+// itself is exercised for real (its own units live in agent-custody-guards.test.js).++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Keypair, PublicKey } from '@solana/web3.js';++process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-secret-for-agent-trade';++const TOKEN_2022 = new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');+const AGENT_ID = '11111111-1111-4111-8111-111111111111';+const MINT = Keypair.generate().publicKey.toBase58();++// ── auth ────────────────────────────────────────────────────────────────────+const authState = { session: { id: 'owner-1' } };+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => authState.session),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++// ── db ──────────────────────────────────────────────────────────────────────+const sqlState = { queue: [], calls: [] };+vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: strings.join('?'), values });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ }),+}));++// ── rate limit / cache / audit ────────────────────────────────────────────────+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authIp: vi.fn(async () => ({ success: true })), walletRead: vi.fn(async () => ({ success: true })) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));+vi.mock('../api/_lib/cache.js', () => ({ cacheGet: vi.fn(async () => null), cacheSet: vi.fn(async () => {}) }));+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));++// ── price feed (used by the shared guards' lamportsToUsd) ──────────────────────+vi.mock('../api/_lib/avatar-wallet.js', () => ({+ solUsdPrice: vi.fn(async () => 200), // $200 / SOL+ explorerTxUrl: (sig, net) => `https://explorer/${sig}?n=${net}`,+}));++// ── agent key recovery (spied so we can assert it is NEVER called on a reject) ──+const recoverSpy = vi.fn(async () => Keypair.generate());+vi.mock('../api/_lib/agent-wallet.js', () => ({ recoverSolanaAgentKeypair: recoverSpy }));++// ── Solana RPC (fake connection) ──────────────────────────────────────────────+const connState = {+ balance: 5_000_000_000, // 5 SOL+ blockhash: Keypair.generate().publicKey.toBase58(),+ sig: 'TRADESIG111111111111111111111111111111111111',+ confirmErr: null,+ sent: 0,+};+const fakeConn = {+ getBalance: vi.fn(async () => connState.balance),+ getParsedAccountInfo: vi.fn(async () => ({ value: { data: { parsed: { info: { decimals: 6 } } } } })),+ getAccountInfo: vi.fn(async () => ({ owner: TOKEN_2022 })),+ getLatestBlockhash: vi.fn(async () => ({ blockhash: connState.blockhash, lastValidBlockHeight: 1000 })),+ sendRawTransaction: vi.fn(async () => { connState.sent += 1; return connState.sig; }),+ confirmTransaction: vi.fn(async () => ({ value: { err: connState.confirmErr } })),+ getSignatureStatus: vi.fn(async () => ({ value: { err: null, confirmationStatus: 'confirmed' } })),+};+vi.mock('../api/_lib/agent-pumpfun.js', () => ({+ solanaConnection: vi.fn(() => fakeConn),+ solanaPublicConnection: vi.fn(() => fakeConn),+}));++// ── pump quote bridge ──────────────────────────────────────────────────────────+const quoteState = { buy: { tokens: '1000000000', priceImpact: 1.2 }, sell: { sol: '480000000', priceImpact: 0.8 } };+vi.mock('../api/_lib/solana/sdk-bridge.js', () => ({+ getBuyQuote: vi.fn(async () => (quoteState.buy ? { tokens: quoteState.buy.tokens, priceImpact: quoteState.buy.priceImpact } : null)),+ getSellQuote: vi.fn(async () => (quoteState.sell ? { sol: quoteState.sell.sol, priceImpact: quoteState.sell.priceImpact } : null)),+}));+vi.mock('../api/_lib/pump.js', () => ({+ getAmmPoolState: vi.fn(async () => { const e = new Error('no pool'); e.code = 'pool_not_found'; throw e; }),+}));++// ── pump SDK instruction builders (return no-op instructions for the v0 tx) ─────+vi.mock('@pump-fun/pump-sdk', () => {+ class OnlinePumpSdk {+ async fetchGlobal() { return {}; }+ async fetchFeeConfig() { return null; }+ async fetchBuyState() { return { bondingCurve: { quoteMint: PublicKey.default, tokenTotalSupply: 1 }, bondingCurveAccountInfo: {}, associatedUserAccountInfo: null }; }+ async fetchSellState() { return { bondingCurve: { quoteMint: PublicKey.default, tokenTotalSupply: 1 }, bondingCurveAccountInfo: {} }; }+ }+ class PumpSdk {+ async buyV2Instructions() { return []; }+ async sellV2Instructions() { return []; }+ }+ return {+ OnlinePumpSdk, PumpSdk,+ getBuyTokenAmountFromSolAmount: () => ({ gt: () => true, toString: () => '1000000000' }),+ getSellSolAmountFromTokenAmount: () => ({ toString: () => '480000000' }),+ };+});++const { handleTrade } = await import('../api/agents/solana-trade.js');++// ── fake req/res ──────────────────────────────────────────────────────────────+function makeReq(body, { method = 'POST', query = '' } = {}) {+ return {+ method,+ url: `/api/agents/${AGENT_ID}/solana/trade${query}`,+ headers: { host: 'x', 'content-type': 'application/json' },+ body,+ on() {}, // readJson tolerates a pre-parsed .body+ };+}+function makeRes() {+ return {+ statusCode: 200, headers: {}, body: null, ended: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ status(c) { this.statusCode = c; return this; },+ json(o) { this.body = o; this.ended = true; return this; },+ end(d) { if (d && !this.body) { try { this.body = JSON.parse(d); } catch { this.body = d; } } this.ended = true; return this; },+ };+}++function agentRow(extraMeta = {}) {+ return [{ id: AGENT_ID, user_id: 'owner-1', meta: { solana_address: Keypair.generate().publicKey.toBase58(), encrypted_solana_secret: 'enc', ...extraMeta } }];+}++beforeEach(() => {+ sqlState.queue = []; sqlState.calls = [];+ recoverSpy.mockClear();+ connState.balance = 5_000_000_000; connState.sent = 0; connState.confirmErr = null;+ quoteState.buy = { tokens: '1000000000', priceImpact: 1.2 };+ quoteState.sell = { sol: '480000000', priceImpact: 0.8 };+ authState.session = { id: 'owner-1' };+});++describe('handleTrade — validation', () => {+ it('rejects an invalid side without recovering the key', async () => {+ sqlState.queue = [agentRow()];+ const res = makeRes();+ await handleTrade(makeReq({ side: 'hodl', mint: MINT, sol_amount: 0.5 }), res, AGENT_ID);+ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('validation_error');+ expect(recoverSpy).not.toHaveBeenCalled();+ });++ it('rejects a malformed mint', async () => {+ sqlState.queue = [agentRow()];+ const res = makeRes();+ await handleTrade(makeReq({ side: 'buy', mint: 'not-a-mint', sol_amount: 0.5 }), res, AGENT_ID);+ expect(res.statusCode).toBe(400);+ expect(recoverSpy).not.toHaveBeenCalled();+ });++ it('rejects a non-owner', async () => {+ sqlState.queue = [[{ id: AGENT_ID, user_id: 'someone-else', meta: {} }]];+ const res = makeRes();+ await handleTrade(makeReq({ side: 'buy', mint: MINT, sol_amount: 0.5 }), res, AGENT_ID);+ expect(res.statusCode).toBe(403);+ expect(recoverSpy).not.toHaveBeenCalled();+ });+});++describe('handleTrade — preview', () => {+ it('returns a live buy quote and never signs', async () => {+ sqlState.queue = [agentRow()];+ const res = makeRes();+ await handleTrade(makeReq({ preview: true, side: 'buy', mint: MINT, sol_amount: 0.5, slippage_bps: 300 }), res, AGENT_ID);+ expect(res.statusCode).toBe(200);+ expect(res.body.data.preview).toBe(true);+ expect(res.body.data.out.asset).toBe('TOKEN');+ expect(Number(res.body.data.out.amount)).toBeGreaterThan(0);+ expect(res.body.data.price_impact_pct).toBeCloseTo(1.2, 3);+ // minimum received = expected * (1 - 3%)+ expect(Number(res.body.data.min_received.amount)).toBeLessThan(Number(res.body.data.out.amount));+ expect(connState.sent).toBe(0);+ expect(recoverSpy).not.toHaveBeenCalled();+ });++ it('returns a sell quote priced in SOL', async () => {+ sqlState.queue = [agentRow()];+ const res = makeRes();+ await handleTrade(makeReq({ preview: true, side: 'sell', mint: MINT, token_amount_raw: '1000000000', slippage_bps: 500 }), res, AGENT_ID);+ expect(res.statusCode).toBe(200);+ expect(res.body.data.out.asset).toBe('SOL');+ expect(Number(res.body.data.out.amount)).toBeGreaterThan(0);+ expect(recoverSpy).not.toHaveBeenCalled();+ });+});++describe('handleTrade — guards', () => {+ it('requires an idempotency key to execute', async () => {+ sqlState.queue = [agentRow()];+ const res = makeRes();+ await handleTrade(makeReq({ side: 'buy', mint: MINT, sol_amount: 0.5 }), res, AGENT_ID);+ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('validation_error');+ expect(recoverSpy).not.toHaveBeenCalled();+ });++ it('blocks a buy over the per-transaction USD ceiling (403, key safe)', async () => {+ // 0.5 SOL × $200 = $100, over a $10 per-tx cap.+ sqlState.queue = [agentRow({ spend_limits: { per_tx_usd: 10, daily_usd: null, withdraw_allowlist: [] } })];+ const res = makeRes();+ await handleTrade(makeReq({ side: 'buy', mint: MINT, sol_amount: 0.5, slippage_bps: 300, idempotency_key: 'k-1' }), res, AGENT_ID);+ expect(res.statusCode).toBe(403);+ expect(res.body.error).toBe('per_tx_exceeded');+ expect(recoverSpy).not.toHaveBeenCalled();+ expect(connState.sent).toBe(0);+ });++ it('blocks a buy that exceeds the wallet balance (402, key safe)', async () => {+ connState.balance = 100_000; // 0.0001 SOL — far below a 0.5 SOL buy+ sqlState.queue = [agentRow()];+ const res = makeRes();+ await handleTrade(makeReq({ side: 'buy', mint: MINT, sol_amount: 0.5, slippage_bps: 300, idempotency_key: 'k-2' }), res, AGENT_ID);+ expect(res.statusCode).toBe(402);+ expect(res.body.error).toBe('insufficient_sol');+ expect(res.body.balance_lamports).toBeDefined();+ expect(recoverSpy).not.toHaveBeenCalled();+ });+});++describe('handleTrade — idempotency + execution', () => {+ it('replays a confirmed trade with the same key without re-sending', async () => {+ sqlState.queue = [+ agentRow(),+ [{ status: 'confirmed', signature: connState.sig, meta: {} }], // prior row+ ];+ const res = makeRes();+ await handleTrade(makeReq({ side: 'buy', mint: MINT, sol_amount: 0.5, slippage_bps: 300, idempotency_key: 'k-dup' }), res, AGENT_ID);+ expect(res.statusCode).toBe(200);+ expect(res.body.data.replayed).toBe(true);+ expect(res.body.data.signature).toBe(connState.sig);+ expect(connState.sent).toBe(0);+ expect(recoverSpy).not.toHaveBeenCalled();+ });++ it('executes a live bonding-curve buy and returns a confirmed signature', async () => {+ sqlState.queue = [+ agentRow(), // loadOwnedWallet+ [], // prior idempotency check → none+ [{ id: 'evt-1' }], // claim INSERT+ [], // updateCustodyEvent (confirmed)+ [], // indexTrade: pump_agent_mints lookup → none+ ];+ const res = makeRes();+ await handleTrade(makeReq({ side: 'buy', mint: MINT, sol_amount: 0.5, slippage_bps: 300, idempotency_key: 'k-live' }), res, AGENT_ID);+ expect(res.statusCode).toBe(200);+ expect(res.body.data.replayed).toBe(false);+ expect(res.body.data.signature).toBe(connState.sig);+ expect(res.body.data.explorer).toContain(connState.sig);+ expect(connState.sent).toBe(1);+ expect(recoverSpy).toHaveBeenCalledTimes(1);+ });+});