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
Mirror copy-trading, wallet reputation, conversational wallet intent, and galaxy money-cam
nirholas0a8840274e06
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bed82ef9a..d32a56c56 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,6 +26,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **New: your avatar comes alive in iOS AR — it breathes and idles in your room** — Placing an avatar in AR on iPhone or iPad used to drop a frozen mannequin into your space. Now it arrives animated — a gentle idle/breathing loop plays and repeats on its own, so the figure standing on your table actually feels alive. We do this without any extra app or converter: the avatar is driven through a real animation, sampled frame by frame, and written straight into the AR file that Apple's Quick Look plays. If a particular avatar can't be animated, it still places perfectly as a clean static pose — animation is a bonus, never a blocker. `[feature, improvement]`- **Prompt-to-avatar: a live progress bar you can cancel, plus motion and screen-reader polish** — Building an avatar from a text prompt now shows a progress bar that actually moves second-to-second (tied to real elapsed time) instead of sitting frozen between stages, a real elapsed clock, and a Cancel button (or Escape) so you're never stuck watching a spinner. Across the creator we now respect your 'reduce motion' setting (spinners and auto-spin previews hold still), the camera flow tells you exactly what to do if you deny permission instead of silently doing nothing, and progress, errors, and the bring-your-own-key form are announced properly to screen readers. Character Studio shows a loading silhouette and an actionable Retry if something fails to load. (`/create/prompt`) `[improvement]`- **Security: CSRF protection extended to sniper arming and trade limits** — Arming an autonomous sniper strategy and changing an agent's discretionary trade limits both commit or unlock real custodial funds, so both writes now require the same one-time CSRF token every other money-moving action already enforced (withdraw, vanity grind, spend limits, trade execution). Ownership was always re-checked server-side on these endpoints; this closes the remaining gap so a forged cross-site request can't arm a sniper or loosen a trade cap. No change to how you use them — the dashboard already sends the token. `[security]`+- **Talk to your agent and it trades — the Conversational Wallet** — Your avatar's wallet now takes voice and text commands. Tell your agent "tip 0.1 SOL to vault.sol", "snipe that mint with half a SOL", "sell half my $THREE", or "withdraw 2 SOL to my Phantom" — it parses your intent with Claude, shows you exactly what it will do next to your own words (real quote, USD value, fees, network), and waits for an explicit "yes" or a tap before anything moves. Confirmed trades come back with a real on-chain signature and explorer link, and the avatar celebrates the moment it lands. Every action runs the same owner-only, spend-limit-gated, audited path as the rest of the wallet — visitors can chat but can never move funds, by any phrasing. A wrong hearing is caught at the read-back, "cancel" is always one word away, and there's a full keyboard path with no mic required. `[feature]`- **The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time** — The payment card that appears when you unlock a paid skill inside an embedded agent got a polish-and-correctness pass. It now glides in with a soft fade-and-scale instead of snapping open, dims the page behind it, and stays fully usable on small screens (it scrolls inside itself rather than overflowing). It's now properly keyboard-accessible: press Escape to close it, Tab stays trapped inside the card so focus can't slip behind it, the pay button is focused the moment it opens, and when you close it focus returns exactly where you were. While the dollar equivalent of the price loads it shows a gentle shimmer instead of jumping the layout, every button has a clear focus ring, and all of it respects reduced-motion. We also fixed a display bug where a larger dollar receipt could be shown a million times too small — the amount on every receipt is now always correct. (`/marketplace`) `[improvement, fix]`- **The walking companion, page narrator, and 3D tour are smoother, kinder to your battery, and never start on a blank canvas** — The three avatars that walk and talk over a page got a polish pass focused on the moments before and around them. The corner companion now greets you with a soft loading shimmer instead of an empty box while its 3D body streams in, and the guided tour opens with an honest 'waking your guide' loader — a real readiness cue, never a fake bar — instead of a frozen page. All four 3D surfaces (the corner companion, the full-page walk playground, the drop-in page narrator, and the feature tour) now pause their animation the instant you switch to another tab, and the page narrator also pauses when it scrolls out of view — so a living avatar never quietly burns your laptop battery in a background tab. The narrator's mute button now shows the correct state from the very first frame, the tour's loader always clears cleanly when you exit, and several small resource leaks (timers and drag handlers left running after a companion or narrator was dismissed) are fixed. Reduced-motion preferences are honored throughout. (`/walk`) `[improvement, fix]`- **Your agent's wallet is now a living identity on every surface** — The little wallet badge under every agent and avatar grew up. Wherever an agent appears — its profile, the marketplace, the galaxy star-map, trending, your dashboard, the launches feed — its wallet now shows the real, live portfolio value in USD, a colour-coded 24-hour change, and a clear ownership marker: a 'Yours' badge on wallets you own, and 'by @creator' on everyone else's. Hover, focus, or tap the badge and it expands into a rich preview: your balance broken out into SOL, USDC, $THREE and your top holdings, a real value sparkline, both your Solana and EVM addresses with one-click copy, and the right actions for who's looking — Open wallet and Vanity for owners, Tip and Fork-to-own for visitors. The same agent's wallet looks identical everywhere because it all comes from one shared component, every number is real on-chain data, and the value gently pulses when a tip lands or a trade fills. Balances load lazily as you scroll and pause when you switch tabs, so even long lists stay fast. (`/marketplace`) `[feature, improvement]`diff --git a/api/_lib/agent-mirror.js b/api/_lib/agent-mirror.jsnew file mode 100644index 000000000..9732f5eb7--- /dev/null+++ b/api/_lib/agent-mirror.js@@ -0,0 +1,443 @@+// Custodial mirror executor — turns a leader agent's REAL on-chain trade into a+// follower agent's REAL, server-signed mirror trade, within the follower's spend+// policy and fully audited.+//+// Safe by construction: every mirrored buy runs through the SAME shared spend+// guardrails (api/_lib/agent-trade-guards.js) the discretionary trade endpoint+// and the sniper use, the SAME pump quote + instruction builders+// (api/agents/solana-trade.js), the SAME MEV-aware execution engine, and lands+// in the SAME custody ledger (agent_custody_events, category 'trade', reason+// 'mirror', meta.mirror = { leader… }). It can NEVER bypass a limit:+// • the mirror kill switch (agent meta.mirror_killed) and the per-follow+// `enabled` flag both halt it before any tx;+// • the per-trade cap, rolling daily budget, USD ceiling, price-impact breaker,+// rug/honeypot firewall, and SOL headroom all gate the buy;+// • a retried (follow, leader-trade) never double-spends — the custody+// idempotency key and the agent_mirror_fills unique index both dedupe it.+//+// Detection source: the leader's confirmed custody trade rows — real signatures,+// real amounts, real mints. A leader is itself an ownable three.ws agent, so its+// trades are captured here with full fidelity (side/mint/size) the moment they+// confirm on-chain.++import { PublicKey } from '@solana/web3.js';+import { sql } from './db.js';+import { planMirror } from './mirror-engine.js';+import { quoteTrade, buildTradeInstructions } from '../agents/solana-trade.js';+import { recoverSolanaAgentKeypair } from './agent-wallet.js';+import { solanaConnection, solanaPublicConnection } from './agent-pumpfun.js';+import { submitProtected } from './execution-engine.js';+import { assessTradeSafety, recordFirewallDecision } from './trade-firewall.js';+import { logAudit } from './audit.js';+import { cacheSet } from './cache.js';+import { WSOL_MINT } from './pump-trade-args.js';+import {+ getSpendLimits, getTradeLimits, enforceSpendLimit, SpendLimitError, lamportsToUsd,+ getDailySpendLamports, updateCustodyEvent,+ checkPerTradeCap, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,+ SOL_FEE_HEADROOM_LAMPORTS,+} from './agent-trade-guards.js';++const LAMPORTS_PER_SOL = 1_000_000_000;+const DEFAULT_MIRROR_SLIPPAGE_BPS = 300;+const lamToSol = (l) => Number(BigInt(l)) / LAMPORTS_PER_SOL;++function netOf(v) { return v === 'devnet' ? 'devnet' : 'mainnet'; }++// ── detection ────────────────────────────────────────────────────────────────+// A leader's real trades from the confirmed custody ledger. `sinceId` is the+// follow's cursor so we never reprocess. Buys carry the SOL spend in+// amount_lamports; sells carry the token side (we mirror the exit, not the size).+export async function detectLeaderTrades(leaderId, network, sinceId = 0, limit = 50) {+ const rows = await sql`+ select id, asset, amount_lamports, amount_raw, usd, signature, created_at, meta+ from agent_custody_events+ where agent_id = ${leaderId}+ and network = ${network}+ and category = 'trade'+ and status = 'confirmed'+ and id > ${sinceId}+ order by id asc+ limit ${limit}+ `;+ return rows.map((e) => {+ const side = e.meta?.side || (e.asset === 'SOL' ? 'buy' : 'sell');+ return {+ eventId: Number(e.id),+ side: side === 'sell' ? 'sell' : 'buy',+ mint: e.meta?.mint || (e.asset !== 'SOL' ? e.asset : null),+ leaderSol: side === 'buy' && e.amount_lamports != null ? lamToSol(e.amount_lamports) : null,+ leaderUsd: e.usd != null ? Number(e.usd) : null,+ signature: e.signature || null,+ createdAt: e.created_at,+ };+ }).filter((t) => t.mint);+}++// Spendable SOL of the follower wallet (best-effort; null when RPC is down so the+// engine can still size fixed/proportional buys and the on-chain headroom check+// remains the hard backstop).+async function readSol(conn, ownerPk, network) {+ try { return lamToSol(BigInt(await conn.getBalance(ownerPk, 'confirmed'))); }+ catch {+ try { return lamToSol(BigInt(await solanaPublicConnection(network).getBalance(ownerPk, 'confirmed'))); }+ catch { return null; }+ }+}++// The follower's full token balance for a mint (used to size the mirrored EXIT —+// when the leader sells, the follower sells everything it holds of that coin).+async function readTokenBalance(conn, ownerPk, mintPk) {+ try {+ const res = await conn.getParsedTokenAccountsByOwner(ownerPk, { mint: mintPk });+ let raw = 0n;+ let decimals = 6;+ for (const acc of res?.value || []) {+ const info = acc.account?.data?.parsed?.info?.tokenAmount;+ if (info?.amount) raw += BigInt(info.amount);+ if (Number.isInteger(info?.decimals)) decimals = info.decimals;+ }+ return { raw, decimals };+ } catch {+ return { raw: 0n, decimals: 6 };+ }+}++// ── follower agent loader ─────────────────────────────────────────────────────+async function loadFollower(followerId) {+ const [row] = await sql`+ SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${followerId} AND deleted_at IS NULL+ `;+ if (!row) return null;+ const meta = { ...(row.meta || {}) };+ return {+ id: row.id,+ ownerId: row.user_id,+ name: row.name,+ meta,+ address: meta.solana_address || null,+ encryptedSecret: meta.encrypted_solana_secret || null,+ killed: meta.mirror_killed === true,+ };+}++// ── the guarded follower trade ────────────────────────────────────────────────+// The SAME guard sequence as handleTrade (api/agents/solana-trade.js), composed+// for a server-initiated mirror. Returns a structured result — never throws past+// the boundary. `leaderRef` labels the custody trail + audit ("mirrored from X").+async function runFollowerTrade({+ follower, side, mint, network, solAmount, tokenAmountRaw, slippageBps, idempotencyKey, leaderRef,+}) {+ const { id, ownerId, meta, address, encryptedSecret } = follower;+ if (!address || !encryptedSecret) return { status: 'failed', code: 'wallet_preparing' };++ let mintPk; let ownerPk;+ try { mintPk = new PublicKey(mint); ownerPk = new PublicKey(address); }+ catch { return { status: 'failed', code: 'bad_address' }; }+ if (mint === WSOL_MINT) return { status: 'skipped', code: 'wsol' };++ const conn = solanaConnection(network);++ // 1. Quote (real pump curve / AMM pricing).+ let quote;+ try {+ quote = await quoteTrade({ conn, side, mintPk, mintStr: mint, network, solAmount, tokenAmountRaw, slippageBps });+ } catch (e) {+ if (e?.code === 'pool_not_found') return { status: 'skipped', code: 'no_market' };+ return { status: 'failed', code: e?.code || 'quote_failed', message: (e?.message || '').slice(0, 200) };+ }++ let usdValue = null;+ try {+ const lamports = side === 'buy' ? BigInt(quote.inAtomics) : BigInt(quote.outAtomics);+ usdValue = await lamportsToUsd(lamports);+ } catch { usdValue = null; }++ const limitsCfg = getSpendLimits(meta);+ const tradeLimits = getTradeLimits(meta);++ // 2. Guards — identical predicates to the discretionary path.+ if (tradeLimits.kill_switch) return { status: 'skipped', code: 'kill_switch' };++ if (side === 'buy') {+ const lamportsIn = BigInt(quote.inAtomics);+ const capLamports = tradeLimits.per_trade_sol == null ? null : BigInt(Math.floor(tradeLimits.per_trade_sol * LAMPORTS_PER_SOL));+ if (checkPerTradeCap(lamportsIn, capLamports)) return { status: 'skipped', code: 'per_trade_cap' };++ if (tradeLimits.daily_budget_sol != null) {+ const budgetLamports = BigInt(Math.floor(tradeLimits.daily_budget_sol * LAMPORTS_PER_SOL));+ const spent = await getDailySpendLamports(id, network);+ if (checkDailyBudgetLamports(spent, lamportsIn, budgetLamports)) return { status: 'skipped', code: 'daily_budget' };+ }+ try {+ await enforceSpendLimit({ agentId: id, limits: limitsCfg, category: 'trade', usdValue, network });+ } catch (e) {+ if (e instanceof SpendLimitError) return { status: 'skipped', code: e.code };+ throw e;+ }+ }++ if (checkPriceImpact(quote.priceImpactPct, tradeLimits.max_price_impact_pct)) {+ return { status: 'skipped', code: 'price_impact' };+ }++ // 3. Rug/honeypot firewall — buys only, the unsafe direction. A 'block' verdict+ // refuses the mirror (degrades to allow when a source is down, never stalls).+ if (side === 'buy') {+ const assessment = await assessTradeSafety({+ network, mint: mintPk, side: 'buy', payer: ownerPk,+ quoteAmount: BigInt(quote.inAtomics), priceImpactPct: quote.priceImpactPct,+ }).catch(() => null);+ if (assessment) {+ recordFirewallDecision({+ mint, network, side: 'buy', verdict: assessment.verdict, score: assessment.score,+ simulated: assessment.simulated, checks: assessment.checks, reasons: assessment.reasons,+ source: 'mirror', agentId: id, userId: ownerId,+ quoteLamports: BigInt(quote.inAtomics), enforced: assessment.verdict === 'block',+ }).catch(() => {});+ if (assessment.verdict === 'block') return { status: 'skipped', code: 'firewall_blocked' };+ }+ }++ // 4. SOL fee/headroom against the real on-chain balance.+ let walletLamports = null;+ try { walletLamports = BigInt(await conn.getBalance(ownerPk, 'confirmed')); }+ catch { walletLamports = null; }+ if (walletLamports != null) {+ const spendLamports = side === 'buy' ? BigInt(quote.inAtomics) : 0n;+ if (checkSolHeadroom(walletLamports, spendLamports, SOL_FEE_HEADROOM_LAMPORTS)) {+ return { status: 'skipped', code: 'insufficient_sol' };+ }+ }++ // 5. Idempotency claim in the custody ledger (also the spend row). A retry with+ // the same key replays instead of double-spending.+ const [prior] = await sql`+ SELECT status, signature, id FROM agent_custody_events+ WHERE agent_id = ${id} AND idempotency_key = ${idempotencyKey} LIMIT 1+ `;+ if (prior) {+ if (prior.status === 'confirmed' && prior.signature) {+ return { status: 'executed', signature: prior.signature, custodyEventId: Number(prior.id), usd: usdValue, priceImpact: quote.priceImpactPct, replayed: true };+ }+ if (prior.status === 'pending') return { status: 'failed', code: 'in_flight' };+ return { status: 'failed', code: 'prior_failed' };+ }++ const mirrorMeta = {+ side, mint, venue: quote.venue, reason: 'mirror',+ expected_out_atomics: quote.outAtomics, min_out_atomics: quote.minOutAtomics,+ slippage_bps: slippageBps, price_impact_pct: quote.priceImpactPct,+ mirror: leaderRef,+ };+ const claim = await sql`+ INSERT INTO agent_custody_events+ (agent_id, user_id, event_type, category, network, asset,+ amount_lamports, amount_raw, usd, status, reason, idempotency_key, meta)+ VALUES (+ ${id}, ${ownerId}, 'spend', 'trade', ${network},+ ${side === 'buy' ? 'SOL' : mint},+ ${side === 'buy' ? quote.inAtomics : null},+ ${side === 'sell' ? quote.inAtomics : null},+ ${side === 'buy' ? usdValue ?? null : null},+ 'pending', 'mirror', ${idempotencyKey},+ ${JSON.stringify(mirrorMeta)}::jsonb+ )+ ON CONFLICT (agent_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING+ RETURNING id+ `;+ if (!claim.length) return { status: 'failed', code: 'in_flight' };+ const claimId = Number(claim[0].id);++ // 6. Recover the key (audit-logged), build, broadcast, confirm.+ let keypair;+ try {+ keypair = await recoverSolanaAgentKeypair(encryptedSecret, {+ agentId: id, userId: ownerId, reason: `mirror_${side}`,+ meta: { mint, network, custody_event_id: claimId, leader_agent_id: leaderRef?.leader_agent_id || null },+ });+ } catch (e) {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } }).catch(() => {});+ return { status: 'failed', code: 'key_recover_failed' };+ }++ let instructions;+ try {+ instructions = await buildTradeInstructions({ side, conn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps, solAmount, tokenAmountRaw });+ } catch (e) {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'build_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});+ return { status: 'failed', code: 'build_failed' };+ }++ let signature;+ let confirmed = true;+ let execTelemetry = null;+ try {+ const result = await submitProtected({+ network, connection: solanaConnection(network), payer: keypair, instructions,+ opts: { tipMode: 'off', confirmTimeoutMs: 45_000 },+ });+ signature = result.signature;+ execTelemetry = { route: result.route, priority_fee_microlamports: result.priorityFeeMicroLamports, landed_ms: result.landedMs, attempts: result.attempts };+ } catch (e) {+ if (e?.code === 'TX_ERR') { signature = e.signature || null; confirmed = false; }+ else {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'send_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});+ logAudit({ userId: ownerId, action: 'custody.trade_failed', resourceId: id, meta: { side, mint, reason: 'mirror_send_failed', leader: leaderRef } });+ return { status: 'failed', code: 'send_failed' };+ }+ }++ if (!confirmed) {+ await updateCustodyEvent(claimId, { signature, meta: { confirm: 'unconfirmed' } }).catch(() => {});+ logAudit({ userId: ownerId, action: 'custody.trade_unconfirmed', resourceId: id, meta: { side, mint, signature, reason: 'mirror', leader: leaderRef } });+ return { status: 'unconfirmed', signature, custodyEventId: claimId, usd: usdValue, priceImpact: quote.priceImpactPct };+ }++ await updateCustodyEvent(claimId, { status: 'confirmed', signature, usd: side === 'buy' ? usdValue ?? null : null, meta: execTelemetry ? { exec: execTelemetry } : undefined }).catch(() => {});+ logAudit({ userId: ownerId, action: 'custody.trade', resourceId: id, meta: { side, mint, venue: quote.venue, usd: usdValue, signature, network, reason: 'mirror', leader: leaderRef, exec_route: execTelemetry?.route } });+ await cacheSet(`sol:bal:${address}:${network}`, null, 1).catch(() => {});++ return { status: 'executed', signature, custodyEventId: claimId, usd: usdValue, priceImpact: quote.priceImpactPct };+}++// ── public: mirror one leader trade onto one follow ───────────────────────────+// Idempotent via the agent_mirror_fills unique (follow_id, leader_event_id, side).+// Records exactly one fill row (executed / skipped / failed / unconfirmed) with a+// human-readable reason, and advances the follow cursor. Never throws.+export async function mirrorOne({ follow, leaderEvent, follower }) {+ const network = netOf(follow.network);+ // Claim the idempotency slot first so a concurrent fanout can't double-process.+ const [claimed] = await sql`+ INSERT INTO agent_mirror_fills+ (follow_id, follower_agent_id, leader_agent_id, owner_user_id, network,+ leader_event_id, leader_signature, side, mint, leader_sol, status)+ VALUES (+ ${follow.id}, ${follow.follower_agent_id}, ${follow.leader_agent_id}, ${follow.owner_user_id}, ${network},+ ${leaderEvent.eventId}, ${leaderEvent.signature}, ${leaderEvent.side}, ${leaderEvent.mint},+ ${leaderEvent.leaderSol}, 'pending'+ )+ ON CONFLICT (follow_id, leader_event_id, side) DO NOTHING+ RETURNING id+ `;+ if (!claimed) return { status: 'duplicate' };+ const fillId = Number(claimed.id);++ const finalize = async (patch) => {+ await sql`+ UPDATE agent_mirror_fills SET+ status = ${patch.status},+ skip_reason = ${patch.skip_reason ?? null},+ planned_sol = ${patch.planned_sol ?? null},+ custody_event_id = ${patch.custody_event_id ?? null},+ signature = ${patch.signature ?? null},+ usd = ${patch.usd ?? null},+ price_impact_pct = ${patch.price_impact_pct ?? null}+ WHERE id = ${fillId}+ `.catch(() => {});+ return { fillId, ...patch };+ };++ follower = follower || await loadFollower(follow.follower_agent_id);+ if (!follower) return finalize({ status: 'failed', skip_reason: 'follower_missing' });++ const conn = solanaConnection(network);+ let ownerPk = null;+ try { ownerPk = new PublicKey(follower.address); } catch { /* wallet not ready */ }+ const followerBalanceSol = ownerPk ? await readSol(conn, ownerPk, network) : null;++ // Per-follow daily spend already mirrored today (for the follow-level budget).+ let spentTodaySol = 0;+ if (follow.daily_budget_sol != null) {+ const [r] = await sql`+ SELECT COALESCE(SUM(planned_sol), 0)::float8 AS s FROM agent_mirror_fills+ WHERE follow_id = ${follow.id} AND side = 'buy' AND status = 'executed'+ AND created_at > now() - interval '24 hours'+ `.catch(() => [{ s: 0 }]);+ spentTodaySol = Number(r?.s || 0);+ }++ const decision = planMirror({+ follow,+ leaderTrade: { side: leaderEvent.side, mint: leaderEvent.mint, leaderSol: leaderEvent.leaderSol },+ followerBalanceSol,+ spentTodaySol,+ killed: follower.killed,+ });++ if (decision.action === 'skip') {+ return finalize({ status: 'skipped', skip_reason: decision.reason });+ }++ const slippageBps = Math.max(0, Math.min(getTradeLimits(follower.meta).max_slippage_bps ?? DEFAULT_MIRROR_SLIPPAGE_BPS, DEFAULT_MIRROR_SLIPPAGE_BPS));+ const leaderRef = {+ leader_agent_id: follow.leader_agent_id,+ leader_name: follow.leader_name || null,+ leader_event_id: leaderEvent.eventId,+ leader_signature: leaderEvent.signature,+ };+ const idem = `mirror:${follow.id}:${leaderEvent.eventId}:${decision.side}`;++ if (decision.side === 'buy') {+ const result = await runFollowerTrade({+ follower, side: 'buy', mint: leaderEvent.mint, network,+ solAmount: decision.order_sol, tokenAmountRaw: null,+ slippageBps, idempotencyKey: idem, leaderRef,+ });+ return finalize({+ status: result.status === 'executed' ? 'executed' : result.status === 'unconfirmed' ? 'unconfirmed' : result.status === 'skipped' ? 'skipped' : 'failed',+ skip_reason: result.code || null,+ planned_sol: decision.order_sol,+ custody_event_id: result.custodyEventId || null,+ signature: result.signature || null,+ usd: result.usd ?? null,+ price_impact_pct: result.priceImpact ?? null,+ });+ }++ // SELL — mirror the exit: sell the follower's FULL balance of the mint.+ if (!ownerPk) return finalize({ status: 'skipped', skip_reason: 'wallet_preparing' });+ const mintPk = new PublicKey(leaderEvent.mint);+ const { raw } = await readTokenBalance(conn, ownerPk, mintPk);+ if (raw <= 0n) return finalize({ status: 'skipped', skip_reason: 'no_holding' });++ const result = await runFollowerTrade({+ follower, side: 'sell', mint: leaderEvent.mint, network,+ solAmount: null, tokenAmountRaw: raw.toString(),+ slippageBps, idempotencyKey: idem, leaderRef,+ });+ return finalize({+ status: result.status === 'executed' ? 'executed' : result.status === 'unconfirmed' ? 'unconfirmed' : result.status === 'skipped' ? 'skipped' : 'failed',+ skip_reason: result.code || null,+ custody_event_id: result.custodyEventId || null,+ signature: result.signature || null,+ usd: result.usd ?? null,+ price_impact_pct: result.priceImpact ?? null,+ });+}++// ── public: process every pending leader trade for one follow ─────────────────+// Used by both the cron fanout and the owner's "Sync now". Advances the cursor+// to the newest processed leader event so the next pass starts fresh.+export async function syncFollow(follow, { maxEvents = 25 } = {}) {+ const network = netOf(follow.network);+ const trades = await detectLeaderTrades(follow.leader_agent_id, network, Number(follow.last_leader_event_id || 0), maxEvents);+ if (!trades.length) return { processed: 0, results: [] };++ const follower = await loadFollower(follow.follower_agent_id);+ const results = [];+ let cursor = Number(follow.last_leader_event_id || 0);+ for (const ev of trades) {+ try {+ const r = await mirrorOne({ follow, leaderEvent: ev, follower });+ results.push({ eventId: ev.eventId, side: ev.side, ...r });+ } catch (e) {+ results.push({ eventId: ev.eventId, side: ev.side, status: 'failed', skip_reason: (e?.message || 'error').slice(0, 120) });+ }+ cursor = Math.max(cursor, ev.eventId);+ }+ if (cursor > Number(follow.last_leader_event_id || 0)) {+ await sql`UPDATE agent_mirror_follows SET last_leader_event_id = ${cursor}, updated_at = now() WHERE id = ${follow.id}`.catch(() => {});+ }+ return { processed: trades.length, results };+}diff --git a/api/_lib/agent-recovery.js b/api/_lib/agent-recovery.jsnew file mode 100644index 000000000..1cae0f95f--- /dev/null+++ b/api/_lib/agent-recovery.js@@ -0,0 +1,827 @@+// Social recovery & inheritance for custodial agent wallets.+//+// Agent wallets are custodial and funded — so "I lost access" or "the owner is+// gone" must not mean the funds die with the key. This module implements a real,+// auditable, threshold-approved, time-locked process that transfers WHO OWNS an+// agent (agent_identities.user_id) to a new account. The AES-GCM-encrypted secret+// is NEVER exported, copied, or decrypted here: only the owner row changes, and+// the same server-held key keeps signing for the new owner.+//+// Safe by construction:+// - Only the current owner configures guardians/beneficiary/threshold/dead-man.+// - A recovery needs `threshold` approvals from CURRENT active guardians AND a+// time-lock window to elapse — a single impostor or compromised guardian+// cannot take over, and the owner can cancel the whole thing instantly by+// being active.+// - At most one active process per agent (DB partial-unique index): contested /+// duplicate requests are serialized, not raced.+// - The wallet is frozen for autonomous spend during a contested process, so a+// wallet with funds is never drained mid-recovery; the owner's own withdraw+// stays open (the freeze never traps the owner).+// - Every step is written to the custody trail (agent_custody_events) and the+// platform audit log.+// - Ownership transfer is atomic and idempotent: the agent_identities.user_id+// update is guarded by the previous owner id, so it applies exactly once and a+// re-run is a safe no-op.++import { sql } from './db.js';+import { logAudit } from './audit.js';+import { insertNotification } from './notify.js';+import { recordCustodyEvent } from './agent-trade-guards.js';++// ── tunables ────────────────────────────────────────────────────────────────+// A recovery's anti-takeover time-lock: even after enough guardians approve, the+// transfer waits this long so a present owner always has a window to cancel.+export const RECOVERY_TIMELOCK_MS = 48 * 60 * 60 * 1000; // 48h+// A recovery request that never reaches its approval threshold expires (so a+// stale impostor attempt doesn't keep the wallet frozen forever).+export const RECOVERY_REQUEST_TTL_MS = 14 * 24 * 60 * 60 * 1000; // 14 days++export const DEAD_MAN_MIN_DAYS = 7;+export const DEAD_MAN_MAX_DAYS = 365;+export const DEAD_MAN_GRACE_MIN_DAYS = 1;+export const DEAD_MAN_GRACE_MAX_DAYS = 90;+export const DEAD_MAN_DEFAULT_INACTIVITY_DAYS = 90;+export const DEAD_MAN_DEFAULT_GRACE_DAYS = 14;++export const MAX_GUARDIANS = 10;+const DAY_MS = 24 * 60 * 60 * 1000;++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+export const isUuid = (v) => typeof v === 'string' && UUID_RE.test(v);++// ── config (meta.recovery) ────────────────────────────────────────────────────++function clampInt(v, lo, hi, def) {+ const n = Math.round(Number(v));+ if (!Number.isFinite(n)) return def;+ return Math.min(hi, Math.max(lo, n));+}++/**+ * Read + normalize the recovery config off an agent's meta blob. The guardian /+ * beneficiary roster itself lives in agent_recovery_guardians — meta only holds+ * the threshold + dead-man settings + bookkeeping.+ */+export function getRecoveryConfig(meta) {+ const r = meta?.recovery && typeof meta.recovery === 'object' ? meta.recovery : {};+ const dm = r.dead_man && typeof r.dead_man === 'object' ? r.dead_man : {};+ return {+ threshold: r.threshold == null ? null : clampInt(r.threshold, 1, MAX_GUARDIANS, null),+ dead_man: {+ enabled: dm.enabled === true,+ inactivity_days: clampInt(dm.inactivity_days, DEAD_MAN_MIN_DAYS, DEAD_MAN_MAX_DAYS, DEAD_MAN_DEFAULT_INACTIVITY_DAYS),+ grace_days: clampInt(dm.grace_days, DEAD_MAN_GRACE_MIN_DAYS, DEAD_MAN_GRACE_MAX_DAYS, DEAD_MAN_DEFAULT_GRACE_DAYS),+ last_check_in: typeof dm.last_check_in === 'string' ? dm.last_check_in : null,+ },+ // reqId that froz-the wallet during a process, so we only auto-unfreeze a+ // freeze WE applied (never override an owner's own pre-existing freeze).+ frozen_by_request: typeof r.frozen_by_request === 'string' ? r.frozen_by_request : null,+ updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,+ };+}++/**+ * Effective approval threshold for a roster. Defaults to a sensible 2-of-N+ * (or all guardians when fewer than 2 exist) until the owner sets an explicit+ * value, and is always clamped to [1, guardianCount].+ */+export function effectiveThreshold(config, guardianCount) {+ if (guardianCount <= 0) return 0;+ const want = config?.threshold ?? Math.min(2, guardianCount);+ return Math.min(guardianCount, Math.max(1, want));+}++// ── pure state machine ──────────────────────────────────────────────────────++/**+ * Compute a request's live phase from its stored fields + the freshly-counted+ * current-guardian approvals. Pure: the caller fetches the numbers, this decides.+ *+ * Returns { phase, approved, approvalsCount, approvalsRequired, timelockUntil,+ * msUntilUnlock, msUntilExpiry }.+ */+export function computeRequestPhase({ status, approvalsRequired, approvalsCount, timelockUntil, createdAt, now = Date.now() }) {+ const terminal = ['completed', 'cancelled', 'rejected', 'expired'];+ if (terminal.includes(status)) {+ return { phase: status, approved: status === 'completed', approvalsCount, approvalsRequired, timelockUntil, msUntilUnlock: 0, msUntilExpiry: 0 };+ }+ const approved = approvalsCount >= approvalsRequired;+ const createdMs = createdAt ? new Date(createdAt).getTime() : now;+ const expiryMs = createdMs + RECOVERY_REQUEST_TTL_MS;+ const msUntilExpiry = expiryMs - now;++ if (!approved) {+ // Not yet enough approvals. Expire if the window has fully elapsed.+ if (msUntilExpiry <= 0) {+ return { phase: 'expired', approved: false, approvalsCount, approvalsRequired, timelockUntil, msUntilUnlock: 0, msUntilExpiry: 0 };+ }+ return { phase: 'pending_approvals', approved: false, approvalsCount, approvalsRequired, timelockUntil, msUntilUnlock: 0, msUntilExpiry };+ }++ // Approved — the time-lock governs from here.+ const unlockMs = timelockUntil ? new Date(timelockUntil).getTime() : now;+ const msUntilUnlock = unlockMs - now;+ if (msUntilUnlock > 0) {+ return { phase: 'time_locked', approved: true, approvalsCount, approvalsRequired, timelockUntil, msUntilUnlock, msUntilExpiry };+ }+ return { phase: 'ready', approved: true, approvalsCount, approvalsRequired, timelockUntil, msUntilUnlock: 0, msUntilExpiry };+}++// ── user resolution ───────────────────────────────────────────────────────────++/** Resolve a guardian handle (username, @username, email, or uuid) → a user row. */+export async function resolveUserHandle(handle) {+ const raw = typeof handle === 'string' ? handle.trim() : '';+ if (!raw) return null;+ if (isUuid(raw)) {+ const [u] = await sql`SELECT id, username, display_name, email FROM users WHERE id = ${raw} AND deleted_at IS NULL LIMIT 1`;+ return u || null;+ }+ const handleNorm = raw.replace(/^@/, '').toLowerCase();+ const isEmail = raw.includes('@') && !raw.startsWith('@');+ if (isEmail) {+ const [u] = await sql`SELECT id, username, display_name, email FROM users WHERE lower(email) = ${raw.toLowerCase()} AND deleted_at IS NULL LIMIT 1`;+ return u || null;+ }+ const [u] = await sql`SELECT id, username, display_name, email FROM users WHERE lower(username) = ${handleNorm} AND deleted_at IS NULL LIMIT 1`;+ return u || null;+}++/** Public-safe label for a user (never leaks email unless it's the only id). */+export function userLabel(u) {+ if (!u) return 'Unknown';+ return u.display_name || (u.username ? `@${u.username}` : null) || u.email_masked || 'a three.ws account';+}++function maskEmail(email) {+ if (!email || typeof email !== 'string' || !email.includes('@')) return null;+ const [name, domain] = email.split('@');+ const head = name.slice(0, 2);+ return `${head}${'•'.repeat(Math.max(1, name.length - 2))}@${domain}`;+}++// ── guardian roster ─────────────────────────────────────────────────────────++/** All active guardians/beneficiaries of an agent, decorated with account labels. */+export async function listGuardians(agentId) {+ const rows = await sql`+ SELECT g.id, g.guardian_user_id, g.role, g.status, g.created_at,+ u.username, u.display_name, u.email, u.avatar_url+ FROM agent_recovery_guardians g+ JOIN users u ON u.id = g.guardian_user_id AND u.deleted_at IS NULL+ WHERE g.agent_id = ${agentId} AND g.status = 'active'+ ORDER BY g.role, g.created_at ASC+ `;+ return rows.map((r) => ({+ id: String(r.id),+ user_id: r.guardian_user_id,+ role: r.role,+ username: r.username || null,+ display_name: r.display_name || null,+ email_masked: maskEmail(r.email),+ avatar_url: r.avatar_url || null,+ label: r.display_name || (r.username ? `@${r.username}` : maskEmail(r.email)) || 'a three.ws account',+ since: r.created_at,+ }));+}++/**+ * Replace an agent's guardian/beneficiary roster + threshold + dead-man config in+ * one owner-authorized, audited operation. `guardians` and `beneficiary` are+ * already-resolved user ids (resolution + validation happen in the route so a bad+ * handle returns a clean 400). Idempotent: re-adding flips 'removed' → 'active',+ * dropping flips 'active' → 'removed'.+ *+ * @returns {Promise<{ guardians: object[], config: object }>}+ */+export async function setGuardiansAndConfig({ agentId, ownerId, guardianIds, beneficiaryId, threshold, deadMan, meta, req = null }) {+ const desired = new Map(); // user_id -> Set(roles)+ for (const gid of guardianIds || []) {+ if (!desired.has(gid)) desired.set(gid, new Set());+ desired.get(gid).add('guardian');+ }+ if (beneficiaryId) {+ if (!desired.has(beneficiaryId)) desired.set(beneficiaryId, new Set());+ desired.get(beneficiaryId).add('beneficiary');+ }++ const existing = await sql`+ SELECT guardian_user_id, role, status FROM agent_recovery_guardians WHERE agent_id = ${agentId}+ `;+ const existingKey = new Set(existing.filter((e) => e.status === 'active').map((e) => `${e.guardian_user_id}:${e.role}`));+ const desiredKey = new Set();+ for (const [uid, roles] of desired) for (const role of roles) desiredKey.add(`${uid}:${role}`);++ const added = [];+ // Upsert every desired (user, role) to active.+ for (const [uid, roles] of desired) {+ for (const role of roles) {+ await sql`+ INSERT INTO agent_recovery_guardians (agent_id, guardian_user_id, role, status, added_by)+ VALUES (${agentId}, ${uid}, ${role}, 'active', ${ownerId})+ ON CONFLICT (agent_id, guardian_user_id, role)+ DO UPDATE SET status = 'active', added_by = ${ownerId}, updated_at = now()+ `;+ if (!existingKey.has(`${uid}:${role}`)) added.push({ uid, role });+ }+ }+ // Soft-remove anything previously active that's no longer desired.+ const removed = [];+ for (const key of existingKey) {+ if (!desiredKey.has(key)) {+ const [uid, role] = key.split(':');+ await sql`+ UPDATE agent_recovery_guardians SET status = 'removed', updated_at = now()+ WHERE agent_id = ${agentId} AND guardian_user_id = ${uid} AND role = ${role}+ `;+ removed.push({ uid, role });+ }+ }++ // Persist threshold + dead-man config into meta.recovery.+ const prev = getRecoveryConfig(meta);+ const guardianCount = [...desired].filter(([, roles]) => roles.has('guardian')).length;+ const nextConfig = {+ threshold: threshold == null ? prev.threshold : clampInt(threshold, 1, Math.max(1, guardianCount || 1), null),+ dead_man: deadMan+ ? {+ enabled: deadMan.enabled === true,+ inactivity_days: clampInt(deadMan.inactivity_days, DEAD_MAN_MIN_DAYS, DEAD_MAN_MAX_DAYS, prev.dead_man.inactivity_days),+ grace_days: clampInt(deadMan.grace_days, DEAD_MAN_GRACE_MIN_DAYS, DEAD_MAN_GRACE_MAX_DAYS, prev.dead_man.grace_days),+ last_check_in: prev.dead_man.last_check_in,+ }+ : prev.dead_man,+ frozen_by_request: prev.frozen_by_request,+ updated_at: new Date().toISOString(),+ };+ const nextMeta = { ...(meta || {}), recovery: nextConfig };+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(nextMeta)}::jsonb WHERE id = ${agentId}`;++ await recordCustodyEvent({+ agentId, userId: ownerId, eventType: 'guardian_change', reason: 'recovery_config_updated',+ meta: { added: added.length, removed: removed.length, guardian_count: guardianCount, threshold: nextConfig.threshold, dead_man: nextConfig.dead_man },+ }).catch(() => {});+ logAudit({ userId: ownerId, action: 'recovery.config_change', resourceId: agentId, meta: { added, removed, threshold: nextConfig.threshold, dead_man_enabled: nextConfig.dead_man.enabled }, req });++ // Notify the newly designated guardians/beneficiaries.+ for (const { uid, role } of added) {+ insertNotification(uid, role === 'beneficiary' ? 'recovery_beneficiary_added' : 'recovery_guardian_added', {+ agent_id: agentId, role, by_user_id: ownerId,+ });+ }++ return { guardians: await listGuardians(agentId), config: nextConfig };+}++// ── owner-activity / dead-man ──────────────────────────────────────────────────++/**+ * The most recent moment the owner was demonstrably "alive" for this agent —+ * the dead-man's switch measures inactivity against this. We take the latest of+ * several REAL signals so a quiet-but-active owner is never falsely declared gone:+ * - any of the owner's browser sessions seen recently,+ * - any custody event on this agent (a withdraw, trade, limit change…),+ * - any usage/telemetry event attributed to this agent,+ * - the agent row's own updated_at,+ * - an explicit "I'm here" check-in (meta.recovery.dead_man.last_check_in).+ *+ * @returns {Promise<{ lastActiveAt: Date, signals: object }>}+ */+export async function getOwnerActivity(agentId, ownerId, meta) {+ const cfg = getRecoveryConfig(meta);+ const [sessionRow] = await sql`SELECT max(last_seen_at) AS t FROM sessions WHERE user_id = ${ownerId}`;+ const [custodyRow] = await sql`SELECT max(created_at) AS t FROM agent_custody_events WHERE agent_id = ${agentId}`;+ const [usageRow] = await sql`SELECT max(created_at) AS t FROM usage_events WHERE agent_id = ${agentId}`;+ const [agentRow] = await sql`SELECT updated_at FROM agent_identities WHERE id = ${agentId}`;++ const signals = {+ session: sessionRow?.t || null,+ custody: custodyRow?.t || null,+ usage: usageRow?.t || null,+ agent_updated: agentRow?.updated_at || null,+ check_in: cfg.dead_man.last_check_in || null,+ };+ let lastActiveMs = 0;+ for (const v of Object.values(signals)) {+ if (v) lastActiveMs = Math.max(lastActiveMs, new Date(v).getTime());+ }+ if (!lastActiveMs) lastActiveMs = Date.now();+ return { lastActiveAt: new Date(lastActiveMs), signals };+}++/**+ * Dead-man status for display + cron evaluation. Returns inactivity days, whether+ * the inactivity threshold is crossed (eligible to arm), and the next check-in+ * deadline. Pure once you've fetched lastActiveAt.+ */+export function deadManStatus(config, lastActiveAt, now = Date.now()) {+ const dm = config.dead_man;+ const lastMs = lastActiveAt instanceof Date ? lastActiveAt.getTime() : new Date(lastActiveAt).getTime();+ const inactiveMs = Math.max(0, now - lastMs);+ const inactiveDays = inactiveMs / DAY_MS;+ const armAtMs = lastMs + dm.inactivity_days * DAY_MS;+ return {+ enabled: dm.enabled,+ inactivity_days: dm.inactivity_days,+ grace_days: dm.grace_days,+ inactive_days: Math.floor(inactiveDays),+ last_active_at: new Date(lastMs).toISOString(),+ arm_at: new Date(armAtMs).toISOString(),+ ms_until_arm: armAtMs - now,+ eligible_to_arm: dm.enabled && now >= armAtMs,+ };+}++// ── request reads ──────────────────────────────────────────────────────────────++/** Count current-guardian approve/decline votes for a request (stale votes from+ * removed/deleted guardians excluded by the JOIN). */+export async function countApprovals(requestId, agentId) {+ const [row] = await sql`+ SELECT+ count(*) FILTER (WHERE a.decision = 'approve')::int AS approvals,+ count(*) FILTER (WHERE a.decision = 'decline')::int AS declines+ FROM agent_recovery_approvals a+ JOIN agent_recovery_guardians g+ ON g.agent_id = ${agentId} AND g.guardian_user_id = a.guardian_user_id+ AND g.role = 'guardian' AND g.status = 'active'+ WHERE a.request_id = ${requestId}+ `;+ return { approvals: row?.approvals || 0, declines: row?.declines || 0 };+}++/** The single active request for an agent (or null). */+export async function getActiveRequest(agentId) {+ const [row] = await sql`+ SELECT * FROM agent_recovery_requests+ WHERE agent_id = ${agentId} AND status IN ('pending_approvals', 'time_locked', 'ready')+ ORDER BY created_at DESC LIMIT 1+ `;+ return row || null;+}++/** Decorate a request row with its live phase + voter detail for the UI. */+export async function decorateRequest(row, agentId) {+ if (!row) return null;+ const { approvals, declines } = await countApprovals(row.id, agentId);+ const phase = computeRequestPhase({+ status: row.status,+ approvalsRequired: row.approvals_required,+ approvalsCount: approvals,+ timelockUntil: row.timelock_until,+ createdAt: row.created_at,+ });+ const votes = await sql`+ SELECT a.guardian_user_id, a.decision, a.updated_at,+ u.username, u.display_name+ FROM agent_recovery_approvals a+ JOIN users u ON u.id = a.guardian_user_id+ WHERE a.request_id = ${row.id}+ ORDER BY a.updated_at DESC+ `;+ // No-guardian inheritance can't be "ready" until the beneficiary confirms.+ const needsBeneficiary = row.kind === 'inheritance' && row.approvals_required === 0 && row.meta?.beneficiary_confirmed !== true;+ let displayStatus = phase.phase;+ if (needsBeneficiary && displayStatus === 'ready') displayStatus = 'time_locked';+ return {+ id: row.id,+ agent_id: row.agent_id,+ kind: row.kind,+ status: displayStatus,+ needs_beneficiary_confirmation: needsBeneficiary,+ stored_status: row.status,+ requester_id: row.requester_id,+ prev_owner_id: row.prev_owner_id,+ new_owner_id: row.new_owner_id,+ approvals: phase.approvalsCount,+ approvals_required: phase.approvalsRequired,+ declines,+ approved: phase.approved,+ timelock_until: row.timelock_until,+ ms_until_unlock: phase.msUntilUnlock,+ ms_until_expiry: phase.msUntilExpiry,+ reason: row.reason,+ created_at: row.created_at,+ completed_at: row.completed_at,+ votes: votes.map((v) => ({+ user_id: v.guardian_user_id,+ decision: v.decision,+ at: v.updated_at,+ label: v.display_name || (v.username ? `@${v.username}` : 'guardian'),+ })),+ };+}++/** Recent request history for an agent (for the owner's audit view). */+export async function listRequests(agentId, { limit = 20 } = {}) {+ const lim = Math.min(50, Math.max(1, Number(limit) || 20));+ const rows = await sql`+ SELECT * FROM agent_recovery_requests+ WHERE agent_id = ${agentId}+ ORDER BY created_at DESC LIMIT ${lim}+ `;+ return Promise.all(rows.map((r) => decorateRequest(r, agentId)));+}++// ── freeze helpers ─────────────────────────────────────────────────────────────+// Freeze autonomous spend for the duration of a contested process so a funded+// wallet can't be drained out from under a recovery. We only auto-unfreeze a+// freeze WE applied (tracked by request id), never an owner's own freeze.++async function freezeForRequest(agentId, requestId, ownerId) {+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`;+ const meta = { ...(row?.meta || {}) };+ const spend = { ...(meta.spend_limits || {}) };+ const alreadyFrozen = spend.frozen === true;+ spend.frozen = true;+ spend.updated_at = new Date().toISOString();+ const recovery = { ...getRecoveryConfig(meta), frozen_by_request: alreadyFrozen ? (meta.recovery?.frozen_by_request || null) : requestId };+ meta.spend_limits = spend;+ meta.recovery = recovery;+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${agentId}`;+ await recordCustodyEvent({ agentId, userId: ownerId, eventType: 'limit_change', reason: 'recovery_freeze', meta: { request_id: requestId, auto: true } }).catch(() => {});+}++async function unfreezeForRequest(agentId, requestId, actorId) {+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`;+ const meta = { ...(row?.meta || {}) };+ const frozenBy = meta.recovery?.frozen_by_request || null;+ if (frozenBy !== requestId) return; // we didn't freeze it (or owner's own freeze) — leave it+ const spend = { ...(meta.spend_limits || {}) };+ spend.frozen = false;+ spend.updated_at = new Date().toISOString();+ meta.spend_limits = spend;+ meta.recovery = { ...meta.recovery, frozen_by_request: null };+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${agentId}`;+ await recordCustodyEvent({ agentId, userId: actorId ?? null, eventType: 'limit_change', reason: 'recovery_unfreeze', meta: { request_id: requestId, auto: true } }).catch(() => {});+}++// ── notifications fan-out ──────────────────────────────────────────────────────++async function notifyParties(agentId, type, payload, { includeOwner = true } = {}) {+ const [agent] = await sql`SELECT user_id FROM agent_identities WHERE id = ${agentId}`;+ const roster = await sql`SELECT DISTINCT guardian_user_id FROM agent_recovery_guardians WHERE agent_id = ${agentId} AND status = 'active'`;+ const recipients = new Set();+ if (includeOwner && agent?.user_id) recipients.add(agent.user_id);+ for (const r of roster) recipients.add(r.guardian_user_id);+ for (const uid of recipients) insertNotification(uid, type, { agent_id: agentId, ...payload });+}++// ── recovery request lifecycle ─────────────────────────────────────────────────++/**+ * Open a recovery request. The requester must be a current active guardian or the+ * beneficiary; they nominate a new owner (themselves, or — if a beneficiary is+ * set — the beneficiary). Freezes the wallet, notifies every party, and starts+ * the approval clock. Throws { status, code, message } on any guard failure.+ */+export async function createRecoveryRequest({ agentId, requesterId, reason, req = null }) {+ const [agent] = await sql`SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;+ if (!agent) throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });+ if (agent.user_id === requesterId) {+ throw Object.assign(new Error('you already own this agent'), { status: 409, code: 'already_owner' });+ }++ // The requester must hold a real role in this agent's recovery graph.+ const roles = await sql`+ SELECT role FROM agent_recovery_guardians+ WHERE agent_id = ${agentId} AND guardian_user_id = ${requesterId} AND status = 'active'+ `;+ const roleSet = new Set(roles.map((r) => r.role));+ if (roleSet.size === 0) {+ throw Object.assign(new Error('you are not a guardian or beneficiary of this agent'), { status: 403, code: 'not_a_guardian' });+ }++ // Nominee: the beneficiary if one is set, else the requesting guardian.+ const [beneficiary] = await sql`+ SELECT guardian_user_id FROM agent_recovery_guardians+ WHERE agent_id = ${agentId} AND role = 'beneficiary' AND status = 'active' LIMIT 1+ `;+ const newOwnerId = beneficiary?.guardian_user_id || requesterId;++ const guardians = await sql`SELECT count(*)::int AS n FROM agent_recovery_guardians WHERE agent_id = ${agentId} AND role = 'guardian' AND status = 'active'`;+ const guardianCount = guardians[0]?.n || 0;+ const config = getRecoveryConfig(agent.meta);+ // Threshold counts OTHER guardians' approvals — the requester can never approve+ // their own takeover. A manual recovery therefore needs at least one guardian+ // other than the requester; a beneficiary-only setup recovers via the dead-man+ // inheritance path instead, not this one.+ const otherGuardians = guardianCount - (roleSet.has('guardian') ? 1 : 0);+ if (otherGuardians < 1) {+ throw Object.assign(new Error('recovery needs at least one guardian (other than you) to approve — ask the owner to add guardians, or use the inheritance path'), { status: 422, code: 'not_enough_guardians' });+ }+ const required = Math.max(1, Math.min(effectiveThreshold(config, guardianCount), otherGuardians));++ let row;+ try {+ [row] = await sql`+ INSERT INTO agent_recovery_requests+ (agent_id, kind, status, requester_id, prev_owner_id, new_owner_id, approvals_required, reason)+ VALUES (${agentId}, 'recovery', 'pending_approvals', ${requesterId}, ${agent.user_id}, ${newOwnerId}, ${required}, ${reason ? String(reason).slice(0, 500) : null})+ RETURNING *+ `;+ } catch (e) {+ // Hit the one-active-request-per-agent partial unique index.+ if (String(e?.message || '').includes('agent_recovery_requests_one_active') || e?.code === '23505') {+ throw Object.assign(new Error('a recovery or inheritance process is already in progress for this agent'), { status: 409, code: 'process_in_progress' });+ }+ throw e;+ }++ await freezeForRequest(agentId, row.id, agent.user_id);+ await recordCustodyEvent({+ agentId, userId: requesterId, eventType: 'recovery_request', reason: 'recovery_opened',+ meta: { request_id: row.id, new_owner_id: newOwnerId, approvals_required: required, kind: 'recovery' },+ }).catch(() => {});+ logAudit({ userId: requesterId, action: 'recovery.request', resourceId: agentId, meta: { request_id: row.id, new_owner_id: newOwnerId }, req });++ // Notify the owner (their agent is under recovery — they can cancel) and all+ // guardians (their approval is needed).+ await notifyParties(agentId, 'recovery_requested', { request_id: row.id, requester_id: requesterId, agent_name: agent.name });++ return decorateRequest(row, agentId);+}++/**+ * Record a guardian's vote (approve/decline) on the active request. When the+ * approval threshold is first reached, arm the time-lock. Returns the live+ * decorated request.+ */+export async function recordVote({ agentId, requestId, guardianId, decision, req = null }) {+ if (decision !== 'approve' && decision !== 'decline') {+ throw Object.assign(new Error('decision must be approve or decline'), { status: 400, code: 'bad_decision' });+ }+ const [row] = await sql`SELECT * FROM agent_recovery_requests WHERE id = ${requestId} AND agent_id = ${agentId}`;+ if (!row) throw Object.assign(new Error('recovery request not found'), { status: 404, code: 'not_found' });+ if (!['pending_approvals', 'time_locked', 'ready'].includes(row.status)) {+ throw Object.assign(new Error('this request is no longer open'), { status: 409, code: 'not_open' });+ }+ // Voter must be a current active GUARDIAN (beneficiary doesn't vote).+ const [g] = await sql`+ SELECT 1 FROM agent_recovery_guardians+ WHERE agent_id = ${agentId} AND guardian_user_id = ${guardianId} AND role = 'guardian' AND status = 'active'+ `;+ if (!g) throw Object.assign(new Error('only an active guardian can vote'), { status: 403, code: 'not_a_guardian' });+ if (guardianId === row.requester_id) {+ throw Object.assign(new Error('the requester cannot approve their own recovery'), { status: 403, code: 'no_self_approve' });+ }++ await sql`+ INSERT INTO agent_recovery_approvals (request_id, guardian_user_id, decision)+ VALUES (${requestId}, ${guardianId}, ${decision})+ ON CONFLICT (request_id, guardian_user_id)+ DO UPDATE SET decision = ${decision}, updated_at = now()+ `;+ await recordCustodyEvent({ agentId, userId: guardianId, eventType: 'recovery_approval', reason: decision, meta: { request_id: requestId } }).catch(() => {});+ logAudit({ userId: guardianId, action: `recovery.${decision}`, resourceId: agentId, meta: { request_id: requestId }, req });++ // Re-evaluate: arm the time-lock the moment the threshold is first reached.+ const { approvals } = await countApprovals(requestId, agentId);+ if (approvals >= row.approvals_required && !row.timelock_until && row.status === 'pending_approvals') {+ const until = new Date(Date.now() + RECOVERY_TIMELOCK_MS).toISOString();+ await sql`UPDATE agent_recovery_requests SET status = 'time_locked', timelock_until = ${until}, updated_at = now() WHERE id = ${requestId} AND status = 'pending_approvals'`;+ await notifyParties(agentId, 'recovery_timelock_started', { request_id: requestId, unlock_at: until });+ } else if (decision === 'approve') {+ insertNotification(row.requester_id, 'recovery_approval_received', { agent_id: agentId, request_id: requestId, by_user_id: guardianId });+ }++ const [fresh] = await sql`SELECT * FROM agent_recovery_requests WHERE id = ${requestId}`;+ return decorateRequest(fresh, agentId);+}++/**+ * Cancel an active request. Allowed for the current owner (the canonical abort:+ * "I'm here") or the original requester (withdrawing their attempt). Unfreezes the+ * wallet if we froze it.+ */+export async function cancelRequest({ agentId, requestId, actorId, byOwner, reason, req = null }) {+ const [row] = await sql`SELECT * FROM agent_recovery_requests WHERE id = ${requestId} AND agent_id = ${agentId}`;+ if (!row) throw Object.assign(new Error('recovery request not found'), { status: 404, code: 'not_found' });+ if (!['pending_approvals', 'time_locked', 'ready'].includes(row.status)) {+ throw Object.assign(new Error('this request is no longer open'), { status: 409, code: 'not_open' });+ }+ const status = byOwner ? 'rejected' : 'cancelled';+ await sql`UPDATE agent_recovery_requests SET status = ${status}, updated_at = now(), completed_at = now(), meta = meta || ${JSON.stringify({ cancelled_by: actorId, reason: reason ? String(reason).slice(0, 300) : null })}::jsonb WHERE id = ${requestId}`;+ await unfreezeForRequest(agentId, requestId, actorId);+ await recordCustodyEvent({ agentId, userId: actorId, eventType: 'recovery_cancel', reason: byOwner ? 'owner_rejected' : 'requester_withdrew', meta: { request_id: requestId } }).catch(() => {});+ logAudit({ userId: actorId, action: 'recovery.cancel', resourceId: agentId, meta: { request_id: requestId, by_owner: !!byOwner }, req });+ await notifyParties(agentId, byOwner ? 'recovery_rejected_by_owner' : 'recovery_withdrawn', { request_id: requestId });+ const [fresh] = await sql`SELECT * FROM agent_recovery_requests WHERE id = ${requestId}`;+ return decorateRequest(fresh, agentId);+}++/**+ * Atomic, idempotent ownership transfer. Changes ONLY agent_identities.user_id+ * (guarded by the previous owner id) and the linked avatar's owner_id — the+ * encrypted secret is untouched and never exported. Re-running after a partial+ * crash is a safe no-op. Records an ownership_transfer custody event and lifts the+ * recovery freeze.+ */+export async function transferAgentOwnership({ agentId, requestId, prevOwnerId, newOwnerId, kind, actorId = null, req = null }) {+ const [agent] = await sql`SELECT id, user_id, avatar_id, name, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;+ if (!agent) throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });++ // Idempotent: already transferred to the nominee.+ if (agent.user_id === newOwnerId) {+ await sql`UPDATE agent_recovery_requests SET status = 'completed', completed_at = coalesce(completed_at, now()), updated_at = now() WHERE id = ${requestId} AND status NOT IN ('completed')`;+ return { transferred: false, alreadyOwned: true };+ }+ // The owner changed out from under us (e.g. owner returned and took action) —+ // refuse: never transfer away from an owner who is no longer `prevOwnerId`.+ if (agent.user_id !== prevOwnerId) {+ await sql`UPDATE agent_recovery_requests SET status = 'rejected', completed_at = now(), updated_at = now(), meta = meta || ${JSON.stringify({ aborted: 'owner_changed' })}::jsonb WHERE id = ${requestId}`;+ await unfreezeForRequest(agentId, requestId, actorId);+ throw Object.assign(new Error('ownership changed during recovery — transfer aborted'), { status: 409, code: 'owner_changed' });+ }++ // Guarded transfer: applies exactly once.+ const moved = await sql`+ UPDATE agent_identities SET user_id = ${newOwnerId}, updated_at = now()+ WHERE id = ${agentId} AND user_id = ${prevOwnerId}+ RETURNING id+ `;+ if (!moved.length) {+ throw Object.assign(new Error('ownership transfer did not apply — retry'), { status: 409, code: 'transfer_noop' });+ }+ // Move the linked avatar too, if this agent owns one and it's still the prev+ // owner's (best-effort: the wallet authority is the agent row above).+ if (agent.avatar_id) {+ await sql`UPDATE avatars SET owner_id = ${newOwnerId} WHERE id = ${agent.avatar_id} AND owner_id = ${prevOwnerId}`.catch(() => {});+ }++ await sql`UPDATE agent_recovery_requests SET status = 'completed', completed_at = now(), updated_at = now() WHERE id = ${requestId}`;+ await unfreezeForRequest(agentId, requestId, newOwnerId);++ await recordCustodyEvent({+ agentId, userId: newOwnerId, eventType: 'ownership_transfer', reason: kind === 'inheritance' ? 'inheritance_completed' : 'recovery_completed',+ meta: { request_id: requestId, prev_owner_id: prevOwnerId, new_owner_id: newOwnerId, kind },+ }).catch(() => {});+ logAudit({ userId: actorId ?? newOwnerId, action: 'recovery.ownership_transfer', resourceId: agentId, meta: { request_id: requestId, prev_owner_id: prevOwnerId, new_owner_id: newOwnerId, kind }, req });++ // Notify everyone: the former owner (their agent moved), the new owner (they+ // now control it), and the guardians.+ insertNotification(prevOwnerId, 'agent_ownership_transferred_out', { agent_id: agentId, agent_name: agent.name, new_owner_id: newOwnerId, kind });+ insertNotification(newOwnerId, 'agent_ownership_transferred_in', { agent_id: agentId, agent_name: agent.name, prev_owner_id: prevOwnerId, kind });+ await notifyParties(agentId, 'recovery_completed', { request_id: requestId, kind, new_owner_id: newOwnerId }, { includeOwner: false });++ return { transferred: true };+}++/**+ * Complete a request whose time-lock has elapsed and approvals still hold. Used by+ * the explicit "complete" route (recovery) and by the cron (inheritance). Re-runs+ * the live phase so we never transfer a request that isn't truly ready.+ */+export async function completeIfReady({ agentId, requestId, actorId = null, req = null }) {+ const [row] = await sql`SELECT * FROM agent_recovery_requests WHERE id = ${requestId} AND agent_id = ${agentId}`;+ if (!row) throw Object.assign(new Error('recovery request not found'), { status: 404, code: 'not_found' });+ if (row.status === 'completed') return { transferred: false, alreadyOwned: true };+ if (!['time_locked', 'ready'].includes(row.status)) {+ throw Object.assign(new Error('this request is not ready to complete'), { status: 409, code: 'not_ready' });+ }+ const { approvals } = await countApprovals(requestId, agentId);+ const phase = computeRequestPhase({+ status: row.status, approvalsRequired: row.approvals_required, approvalsCount: approvals,+ timelockUntil: row.timelock_until, createdAt: row.created_at,+ });+ if (phase.phase !== 'ready') {+ throw Object.assign(new Error('the safety window has not elapsed or approvals fell below threshold'), { status: 409, code: 'not_ready', detail: { phase: phase.phase, ms_until_unlock: phase.msUntilUnlock, approvals, required: row.approvals_required } });+ }+ // Inheritance with no guardians: the beneficiary's explicit confirmation is the+ // required human gate (never transfer purely on a timer).+ if (row.kind === 'inheritance' && row.approvals_required === 0 && row.meta?.beneficiary_confirmed !== true) {+ throw Object.assign(new Error('awaiting the beneficiary’s confirmation before control can pass'), { status: 409, code: 'awaiting_beneficiary', detail: { phase: 'awaiting_beneficiary' } });+ }+ if (row.status !== 'ready') {+ await sql`UPDATE agent_recovery_requests SET status = 'ready', updated_at = now() WHERE id = ${requestId}`;+ }+ return transferAgentOwnership({ agentId, requestId, prevOwnerId: row.prev_owner_id, newOwnerId: row.new_owner_id, kind: row.kind, actorId, req });+}++// ── check-in (cancel a looming dead-man) ───────────────────────────────────────++/**+ * The owner stamps "I'm here". Records the check-in (resetting the dead-man clock)+ * and aborts any in-flight INHERITANCE process — the dead-man's switch must always+ * be defeatable by the owner simply being present.+ */+export async function ownerCheckIn({ agentId, ownerId, req = null }) {+ const [agent] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`;+ const meta = { ...(agent?.meta || {}) };+ const cfg = getRecoveryConfig(meta);+ cfg.dead_man.last_check_in = new Date().toISOString();+ cfg.updated_at = new Date().toISOString();+ meta.recovery = cfg;+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb, updated_at = now() WHERE id = ${agentId}`;++ // Abort any active inheritance (recovery requests are NOT auto-cancelled by a+ // check-in — those are explicit owner-driven flows; only the dead-man path is).+ const active = await getActiveRequest(agentId);+ let cancelled = null;+ if (active && active.kind === 'inheritance') {+ cancelled = await cancelRequest({ agentId, requestId: active.id, actorId: ownerId, byOwner: true, reason: 'owner_checked_in', req });+ }+ await recordCustodyEvent({ agentId, userId: ownerId, eventType: 'dead_man_checkin', reason: 'owner_present', meta: { aborted_inheritance: cancelled?.id || null } }).catch(() => {});+ logAudit({ userId: ownerId, action: 'recovery.checkin', resourceId: agentId, meta: { aborted_inheritance: cancelled?.id || null }, req });+ return { checked_in_at: cfg.dead_man.last_check_in, aborted_inheritance: cancelled };+}++/**+ * Arm the dead-man's switch: open an INHERITANCE request to the beneficiary after+ * the owner's inactivity has crossed the configured threshold. Never auto-completes+ * — it needs guardian/beneficiary confirmation AND the grace window, and the owner+ * can cancel it just by being active. Used by the cron and the beneficiary's+ * manual "arm" action. Returns null if not eligible / already armed.+ */+export async function armInheritance({ agentId, actorId = null, req = null }) {+ const [agent] = await sql`SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`;+ if (!agent) return null;+ const cfg = getRecoveryConfig(agent.meta);+ if (!cfg.dead_man.enabled) return null;++ // Must have a beneficiary to inherit to.+ const [beneficiary] = await sql`SELECT guardian_user_id FROM agent_recovery_guardians WHERE agent_id = ${agentId} AND role = 'beneficiary' AND status = 'active' LIMIT 1`;+ if (!beneficiary) return null;++ // Already an active process? Don't double-arm.+ if (await getActiveRequest(agentId)) return null;++ // Eligibility: inactivity threshold crossed.+ const { lastActiveAt } = await getOwnerActivity(agentId, agent.user_id, agent.meta);+ const dm = deadManStatus(cfg, lastActiveAt);+ if (!dm.eligible_to_arm) return null;++ // Confirmation threshold: at least one guardian (if any exist) must confirm,+ // otherwise the beneficiary's own confirmation suffices.+ const guardians = await sql`SELECT count(*)::int AS n FROM agent_recovery_guardians WHERE agent_id = ${agentId} AND role = 'guardian' AND status = 'active'`;+ const guardianCount = guardians[0]?.n || 0;+ // With guardians, inheritance still needs threshold guardian confirmations.+ // With no guardians, the beneficiary's own confirmation is the only human gate+ // (required = 0 guardian votes) — readiness then also checks beneficiary_confirmed.+ const required = guardianCount > 0 ? Math.min(effectiveThreshold(cfg, guardianCount), guardianCount) : 0;++ // Grace window doubles as the time-lock: control passes only after grace_days+ // of continued inactivity AND confirmation.+ const until = new Date(Date.now() + cfg.dead_man.grace_days * DAY_MS).toISOString();++ let row;+ try {+ [row] = await sql`+ INSERT INTO agent_recovery_requests+ (agent_id, kind, status, requester_id, prev_owner_id, new_owner_id, approvals_required, timelock_until, reason, meta)+ VALUES (${agentId}, 'inheritance', 'pending_approvals', ${actorId}, ${agent.user_id}, ${beneficiary.guardian_user_id},+ ${required}, ${until}, 'dead_man_switch', ${JSON.stringify({ grace_days: cfg.dead_man.grace_days, inactivity_days: cfg.dead_man.inactivity_days, last_active_at: dm.last_active_at })}::jsonb)+ RETURNING *+ `;+ } catch (e) {+ if (e?.code === '23505') return null; // lost the race to another armer+ throw e;+ }++ // If no guardians exist, the beneficiary's confirmation is the only gate — but+ // we still require the grace window. Pre-seed nothing; the beneficiary confirms.+ await freezeForRequest(agentId, row.id, agent.user_id);+ await recordCustodyEvent({ agentId, userId: actorId ?? null, eventType: 'dead_man_arm', reason: 'inactivity_threshold_crossed', meta: { request_id: row.id, beneficiary_id: beneficiary.guardian_user_id, grace_until: until, last_active_at: dm.last_active_at } }).catch(() => {});+ logAudit({ userId: actorId ?? null, action: 'recovery.inheritance_armed', resourceId: agentId, meta: { request_id: row.id, beneficiary_id: beneficiary.guardian_user_id }, req });++ // Loud, early notification — the owner gets a prominent "we think you're gone,+ // tap I'm here to cancel" and the grace window starts.+ insertNotification(agent.user_id, 'dead_man_armed_owner', { agent_id: agentId, agent_name: agent.name, request_id: row.id, grace_until: until });+ await notifyParties(agentId, 'inheritance_armed', { request_id: row.id, agent_name: agent.name, beneficiary_id: beneficiary.guardian_user_id, grace_until: until }, { includeOwner: false });++ return decorateRequest(row, agentId);+}++/**+ * Confirm an inheritance (guardian or beneficiary). For inheritance, a beneficiary+ * confirmation also counts toward the threshold when there are no guardians.+ * Delegates to recordVote for guardians; beneficiary-only confirmation arms the+ * time-lock directly.+ */+export async function confirmInheritance({ agentId, requestId, actorId, req = null }) {+ const [row] = await sql`SELECT * FROM agent_recovery_requests WHERE id = ${requestId} AND agent_id = ${agentId} AND kind = 'inheritance'`;+ if (!row) throw Object.assign(new Error('inheritance request not found'), { status: 404, code: 'not_found' });+ if (!['pending_approvals', 'time_locked', 'ready'].includes(row.status)) {+ throw Object.assign(new Error('this request is no longer open'), { status: 409, code: 'not_open' });+ }+ const roles = await sql`SELECT role FROM agent_recovery_guardians WHERE agent_id = ${agentId} AND guardian_user_id = ${actorId} AND status = 'active'`;+ const roleSet = new Set(roles.map((r) => r.role));+ if (roleSet.size === 0) throw Object.assign(new Error('only a guardian or the beneficiary can confirm'), { status: 403, code: 'not_a_party' });++ // A guardian votes through the normal path.+ if (roleSet.has('guardian')) {+ return recordVote({ agentId, requestId, guardianId: actorId, decision: 'approve', req });+ }+ // Beneficiary-only (no guardian role): their confirmation satisfies the gate+ // when there are no guardians. Arm the time-lock if not already.+ await recordCustodyEvent({ agentId, userId: actorId, eventType: 'recovery_approval', reason: 'beneficiary_confirm', meta: { request_id: requestId } }).catch(() => {});+ if (row.status === 'pending_approvals') {+ const until = row.timelock_until || new Date(Date.now() + 0).toISOString(); // grace already set at arm time+ await sql`UPDATE agent_recovery_requests SET status = 'time_locked', timelock_until = coalesce(timelock_until, ${until}), meta = meta || ${JSON.stringify({ beneficiary_confirmed: true })}::jsonb, updated_at = now() WHERE id = ${requestId}`;+ } else {+ await sql`UPDATE agent_recovery_requests SET meta = meta || ${JSON.stringify({ beneficiary_confirmed: true })}::jsonb, updated_at = now() WHERE id = ${requestId}`;+ }+ const [fresh] = await sql`SELECT * FROM agent_recovery_requests WHERE id = ${requestId}`;+ return decorateRequest(fresh, agentId);+}diff --git a/api/_lib/agent-trade-exec.js b/api/_lib/agent-trade-exec.jsnew file mode 100644index 000000000..28b52494f--- /dev/null+++ b/api/_lib/agent-trade-exec.js@@ -0,0 +1,508 @@+// Reusable custodial trade executor — the server-side engine behind autonomous+// trade paths (the Mirror / Copy-Trade social graph, task 09).+//+// api/agents/solana-trade.js is the OWNER-DRIVEN, HTTP-coupled discretionary path+// (preview + rich response shaping + req/res). It cannot be called server-to-server+// by a cron fanout. This module is its autonomous sibling: the SAME shared spend+// guardrails (api/_lib/agent-trade-guards.js), the SAME rug/honeypot firewall, the+// SAME idempotent custody ledger, the SAME MEV-aware execution engine — exposed as+// a plain async function that returns a structured result instead of writing HTTP.+//+// executeCustodialTrade({ agentId, userId, meta, side, mint, solAmount,+// tokenAmountRaw, slippageBps, network, source,+// idempotencyKey, extraMeta })+// → { ok, code, message, detail, skip, signature, explorer, usd, ... }+//+// The pump.fun instruction builders + live-quote logic intentionally mirror+// solana-trade.js (which itself mirrors api/agents/pumpfun/[action].js) so the+// "how do we price + build a trade" convention has a consistent shape across paths;+// the "is this trade allowed" math has exactly ONE home in agent-trade-guards.js+// and is imported, never re-implemented.+//+// Hard rules honoured: the key is decrypted only via recoverSolanaAgentKeypair,+// only after the guard gauntlet passes, always audit-logged; guard rejections are+// structured (never thrown 500s) so the caller can record an honest skip reason; a+// retried idempotency key never double-spends. $THREE is the only coin three.ws+// promotes — this is coin-agnostic plumbing that trades whatever mint it's given.++import { sql } from './db.js';+import { recoverSolanaAgentKeypair } from './agent-wallet.js';+import { solanaConnection, solanaPublicConnection } from './agent-pumpfun.js';+import { PublicKey } from '@solana/web3.js';+import { cacheSet } from './cache.js';+import { logAudit } from './audit.js';+import { explorerTxUrl } from './avatar-wallet.js';+import {+ enforceSpendLimit, SpendLimitError, getSpendLimits, updateCustodyEvent, lamportsToUsd,+ getTradeLimits, getDailySpendLamports,+ checkKillSwitch, checkPerTradeCap, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,+ SOL_FEE_HEADROOM_LAMPORTS,+} from './agent-trade-guards.js';+import {+ slippagePercentFromBps, resolveCustodialQuote, resolveTokenProgramForMintOwner, WSOL_MINT,+} from './pump-trade-args.js';+import { getBuyQuote, getSellQuote } from './solana/sdk-bridge.js';+import { getAmmPoolState } from './pump.js';+import { assessTradeSafety, recordFirewallDecision } from './trade-firewall.js';+import { submitProtected } from './execution-engine.js';++const LAMPORTS_PER_SOL = 1_000_000_000;+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++function netOf(v) { return v === 'devnet' ? 'devnet' : 'mainnet'; }+function lamportsToSol(l) { return Number(BigInt(l)) / LAMPORTS_PER_SOL; }++function applySlippageFloor(amountBase, slippageBps) {+ const a = BigInt(amountBase);+ const bps = BigInt(Math.max(0, Math.min(10_000, slippageBps)));+ return (a * (10_000n - bps)) / 10_000n;+}++async function resolveMintDecimals(conn, mintPk) {+ try {+ const info = await conn.getParsedAccountInfo(mintPk);+ const dec = info?.value?.data?.parsed?.info?.decimals;+ if (Number.isInteger(dec)) return dec;+ } catch { /* fall through */ }+ return 6;+}++// Sum the owner's full SPL balance for a mint, across both token programs, in base+// units. Used to mirror a leader's EXIT: when the leader sells, the follower sells+// its entire position in that mint (a conservative, honest "leader out → you out").+async function resolveTokenBalanceRaw(conn, ownerPk, mintPk) {+ let total = 0n;+ for (const programId of [+ new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'),+ new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'),+ ]) {+ try {+ const res = await conn.getParsedTokenAccountsByOwner(ownerPk, { mint: mintPk, programId });+ for (const { account } of res.value) {+ const amt = account?.data?.parsed?.info?.tokenAmount?.amount;+ if (amt) total += BigInt(amt);+ }+ } catch { /* program may not own any account; ignore */ }+ }+ return total;+}++function typed(status, code, message) {+ const e = new Error(message);+ e.status = status; e.code = code;+ return e;+}++function clampImpact(v) {+ const n = Number(v);+ return Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : 0;+}++function derivePriceImpact(inReserve, outReserve, inAmt, out) {+ const ir = Number(inReserve?.toString?.() ?? inReserve ?? 0);+ const or = Number(outReserve?.toString?.() ?? outReserve ?? 0);+ const a = Number(inAmt?.toString?.() ?? inAmt ?? 0);+ const o = Number(out ?? 0);+ if (!(ir > 0) || !(or > 0) || !(a > 0)) return 0;+ const spotOut = (a * or) / ir;+ if (!(spotOut > 0)) return 0;+ const impact = ((spotOut - o) / spotOut) * 100;+ return Number.isFinite(impact) ? Math.max(0, Math.min(100, impact)) : 0;+}++async function loadAmm(network, mintPk) {+ const amm = await getAmmPoolState({ network, mint: mintPk });+ const resolvedQuote = amm.pool.quoteMint?.toString?.() ?? WSOL_MINT;+ if (resolvedQuote !== WSOL_MINT) {+ throw typed(409, 'unsupported_quote', 'this coin trades against a non-SOL asset');+ }+ return amm;+}++// Live quote — bonding curve first, AMM pool for graduated coins. Pure read.+export async function quoteTrade({ conn, side, mintPk, mintStr, network, solAmount, tokenAmountRaw, slippageBps }) {+ if (side === 'buy') {+ const lamportsIn = BigInt(Math.floor(Number(solAmount) * LAMPORTS_PER_SOL));+ if (lamportsIn <= 0n) throw typed(400, 'amount_too_small', 'enter a SOL amount greater than zero');++ const curve = await getBuyQuote(conn, mintStr, lamportsIn.toString());+ if (curve && curve.tokens) {+ const decimals = await resolveMintDecimals(conn, mintPk);+ const tokensOut = BigInt(curve.tokens.toString());+ if (tokensOut <= 0n) throw typed(400, 'amount_too_small', 'that SOL amount is too small to buy any tokens');+ return {+ venue: 'bonding_curve', graduated: false, quoteAsset: 'SOL',+ inAsset: 'SOL', inAmount: Number(solAmount), inAtomics: lamportsIn.toString(),+ outAsset: 'TOKEN', outAtomics: tokensOut.toString(), outUi: Number(tokensOut) / 10 ** decimals,+ minOutAtomics: applySlippageFloor(tokensOut, slippageBps).toString(),+ minOutUi: Number(applySlippageFloor(tokensOut, slippageBps)) / 10 ** decimals,+ decimals, priceImpactPct: clampImpact(curve.priceImpact),+ };+ }++ const amm = await loadAmm(network, mintPk);+ const sdk = await import('@pump-fun/pump-swap-sdk');+ const r = sdk.buyQuoteInput({+ quote: new amm.BN(lamportsIn.toString()), slippage: slippagePercentFromBps(slippageBps),+ baseReserve: amm.baseReserve, quoteReserve: amm.quoteReserve, globalConfig: amm.globalConfig,+ baseMintAccount: amm.baseMintAccount, baseMint: amm.pool.baseMint,+ coinCreator: amm.pool.coinCreator, creator: amm.pool.creator, feeConfig: amm.feeConfig,+ });+ const decimals = await resolveMintDecimals(conn, mintPk);+ const tokensOut = BigInt((r.base ?? 0).toString());+ if (tokensOut <= 0n) throw typed(400, 'amount_too_small', 'that SOL amount is too small to buy any tokens');+ return {+ venue: 'amm', graduated: true, quoteAsset: 'SOL', poolKey: amm.poolKey.toString(),+ inAsset: 'SOL', inAmount: Number(solAmount), inAtomics: lamportsIn.toString(),+ outAsset: 'TOKEN', outAtomics: tokensOut.toString(), outUi: Number(tokensOut) / 10 ** decimals,+ minOutAtomics: applySlippageFloor(tokensOut, slippageBps).toString(),+ minOutUi: Number(applySlippageFloor(tokensOut, slippageBps)) / 10 ** decimals,+ decimals, priceImpactPct: derivePriceImpact(amm.quoteReserve, amm.baseReserve, lamportsIn, tokensOut),+ };+ }++ // SELL — amount is token base units.+ const baseUnits = BigInt(tokenAmountRaw);+ if (baseUnits <= 0n) throw typed(400, 'amount_too_small', 'enter a token amount greater than zero');+ const decimals = await resolveMintDecimals(conn, mintPk);++ const curve = await getSellQuote(conn, mintStr, baseUnits.toString());+ if (curve && curve.sol) {+ const lamportsOut = BigInt(curve.sol.toString());+ return {+ venue: 'bonding_curve', graduated: false, quoteAsset: 'SOL',+ inAsset: 'TOKEN', inAtomics: baseUnits.toString(), inUi: Number(baseUnits) / 10 ** decimals,+ outAsset: 'SOL', outAtomics: lamportsOut.toString(), outUi: lamportsToSol(lamportsOut),+ minOutAtomics: applySlippageFloor(lamportsOut, slippageBps).toString(),+ minOutUi: lamportsToSol(applySlippageFloor(lamportsOut, slippageBps)),+ decimals, priceImpactPct: clampImpact(curve.priceImpact),+ };+ }++ const amm = await loadAmm(network, mintPk);+ const sdk = await import('@pump-fun/pump-swap-sdk');+ const r = sdk.sellBaseInput({+ base: new amm.BN(baseUnits.toString()), slippage: slippagePercentFromBps(slippageBps),+ baseReserve: amm.baseReserve, quoteReserve: amm.quoteReserve, globalConfig: amm.globalConfig,+ baseMintAccount: amm.baseMintAccount, baseMint: amm.pool.baseMint,+ coinCreator: amm.pool.coinCreator, creator: amm.pool.creator, feeConfig: amm.feeConfig,+ });+ const lamportsOut = BigInt((r.uiQuote ?? r.minQuote ?? 0).toString());+ const minLamportsOut = BigInt((r.minQuote ?? r.uiQuote ?? 0).toString());+ return {+ venue: 'amm', graduated: true, quoteAsset: 'SOL', poolKey: amm.poolKey.toString(),+ inAsset: 'TOKEN', inAtomics: baseUnits.toString(), inUi: Number(baseUnits) / 10 ** decimals,+ outAsset: 'SOL', outAtomics: lamportsOut.toString(), outUi: lamportsToSol(lamportsOut),+ minOutAtomics: minLamportsOut.toString(), minOutUi: lamportsToSol(minLamportsOut),+ decimals, priceImpactPct: derivePriceImpact(amm.baseReserve, amm.quoteReserve, baseUnits, lamportsOut),+ };+}++// Build the on-chain instructions for the resolved venue + side. Curve trades use+// the pump-sdk v2 builders; graduated trades use the pump-swap AMM SDK.+async function buildTradeInstructions({ side, conn, network, mintPk, ownerPk, quote, slippageBps, solAmount, tokenAmountRaw }) {+ const BNmod = (await import('bn.js')).default;++ if (quote.venue === 'bonding_curve') {+ const { PumpSdk, OnlinePumpSdk, getBuyTokenAmountFromSolAmount, getSellSolAmountFromTokenAmount } =+ await import('@pump-fun/pump-sdk');+ const online = new OnlinePumpSdk(conn);+ const sdk = new PumpSdk();+ const mintInfo = await conn.getAccountInfo(mintPk);+ if (!mintInfo) throw typed(404, 'mint_not_found', 'mint not found on this network');+ const tokenProgram = resolveTokenProgramForMintOwner(mintInfo.owner);++ if (side === 'buy') {+ const [global, feeConfig, state] = await Promise.all([+ online.fetchGlobal(), online.fetchFeeConfig().catch(() => null),+ online.fetchBuyState(mintPk, ownerPk, tokenProgram),+ ]);+ const qa = resolveCustodialQuote(state.bondingCurve?.quoteMint, network);+ if (!qa.isSol) throw typed(409, 'unsupported_quote', 'this coin trades against a non-SOL asset');+ const quoteAtomics = new BNmod(Math.floor(Number(solAmount) * LAMPORTS_PER_SOL));+ const expected = getBuyTokenAmountFromSolAmount({ global, feeConfig, mintSupply: state.bondingCurve.tokenTotalSupply, bondingCurve: state.bondingCurve, amount: quoteAtomics });+ if (!expected.gt(new BNmod(0))) throw typed(400, 'amount_too_small', 'that SOL amount is too small to buy any tokens');+ return sdk.buyV2Instructions({+ global, bondingCurveAccountInfo: state.bondingCurveAccountInfo, bondingCurve: state.bondingCurve,+ associatedUserAccountInfo: state.associatedUserAccountInfo, mint: mintPk, user: ownerPk,+ amount: expected, quoteAmount: quoteAtomics, slippage: slippagePercentFromBps(slippageBps), tokenProgram,+ });+ }+ const [global, feeConfig, state] = await Promise.all([+ online.fetchGlobal(), online.fetchFeeConfig().catch(() => null),+ online.fetchSellState(mintPk, ownerPk, tokenProgram),+ ]);+ const qa = resolveCustodialQuote(state.bondingCurve?.quoteMint, network);+ if (!qa.isSol) throw typed(409, 'unsupported_quote', 'this coin trades against a non-SOL asset');+ const tokens = new BNmod(tokenAmountRaw);+ const expectedQuote = getSellSolAmountFromTokenAmount({ global, feeConfig, mintSupply: state.bondingCurve.tokenTotalSupply, bondingCurve: state.bondingCurve, amount: tokens });+ return sdk.sellV2Instructions({+ global, bondingCurveAccountInfo: state.bondingCurveAccountInfo, bondingCurve: state.bondingCurve,+ mint: mintPk, user: ownerPk, amount: tokens, quoteAmount: expectedQuote,+ slippage: slippagePercentFromBps(slippageBps), tokenProgram,+ });+ }++ const { PumpAmmSdk, OnlinePumpAmmSdk, canonicalPumpPoolPda } = await import('@pump-fun/pump-swap-sdk');+ const amm = new PumpAmmSdk();+ const online = new OnlinePumpAmmSdk(conn);+ const poolKey = canonicalPumpPoolPda(mintPk);+ const swapState = await online.swapSolanaState(poolKey, ownerPk).catch(() => online.swapSolanaStateNoPool(poolKey, ownerPk));+ const slippage = slippagePercentFromBps(slippageBps);+ if (side === 'buy') {+ return amm.buyQuoteInput(swapState, new BNmod(BigInt(quote.inAtomics).toString()), slippage);+ }+ return amm.sellBaseInput(swapState, new BNmod(tokenAmountRaw), slippage);+}++function fail(code, message, { skip = false, detail = null } = {}) {+ return { ok: false, skip, code, message, detail };+}++/**+ * Execute a real custodial trade for an agent, server-side, fully guarded.+ *+ * Returns a structured result — never throws for an expected rejection (a guard+ * breach, insufficient funds, a firewall block, a missing position). Those come+ * back as { ok:false, skip:true, code, message } so an autonomous caller can log+ * an honest skip reason and keep its subscription alive. Only genuinely+ * unexpected internal failures bubble up.+ *+ * @param {object} p+ * @param {string} p.agentId follower agent id+ * @param {string} p.userId owner user id (for custody/audit attribution)+ * @param {object} p.meta agent_identities.meta (wallet keys + spend policy)+ * @param {'buy'|'sell'} p.side+ * @param {string} p.mint base58 mint+ * @param {number} [p.solAmount] buy: SOL to spend+ * @param {string} [p.tokenAmountRaw] sell: token base units, or 'max' for full position+ * @param {number} [p.slippageBps]+ * @param {string} [p.network]+ * @param {string} [p.source] recorded in custody meta + audit (e.g. 'mirror')+ * @param {string} p.idempotencyKey required — dedupes retries+ * @param {object} [p.extraMeta] merged into the custody event meta + audit meta+ */+export async function executeCustodialTrade({+ agentId, userId, meta, side, mint, solAmount, tokenAmountRaw,+ slippageBps = 300, network = 'mainnet', source = 'auto', idempotencyKey, extraMeta = {},+}) {+ network = netOf(network);+ side = side === 'sell' ? 'sell' : 'buy';+ if (!idempotencyKey) return fail('validation_error', 'idempotency_key is required');+ if (typeof mint !== 'string' || !BASE58_RE.test(mint)) return fail('validation_error', 'mint must be a base58 Solana address');+ if (mint === WSOL_MINT) return fail('validation_error', 'cannot trade wrapped SOL as a token');++ let mintPk, ownerPk;+ try { mintPk = new PublicKey(mint); } catch { return fail('validation_error', 'mint is not a valid Solana address'); }++ const address = meta?.solana_address || null;+ const encryptedSecret = meta?.encrypted_solana_secret || null;+ if (!address || !encryptedSecret) return fail('wallet_preparing', 'the agent wallet is still being prepared', { skip: true });+ try { ownerPk = new PublicKey(address); } catch { return fail('wallet_preparing', 'the agent wallet is still being prepared', { skip: true }); }++ const idem = String(idempotencyKey).slice(0, 128);+ const readConn = solanaConnection(network);++ // Resolve a 'max' sell to the full on-chain position now (mirroring a leader exit).+ if (side === 'sell') {+ if (tokenAmountRaw === 'max' || tokenAmountRaw == null) {+ const bal = await resolveTokenBalanceRaw(readConn, ownerPk, mintPk).catch(() => 0n);+ if (bal <= 0n) return fail('no_position', 'the follower holds none of this token to mirror the exit', { skip: true });+ tokenAmountRaw = bal.toString();+ } else if (!/^\d+$/.test(String(tokenAmountRaw)) || BigInt(String(tokenAmountRaw)) <= 0n) {+ return fail('validation_error', 'token_amount_raw must be a positive base-unit integer');+ }+ } else if (!(Number(solAmount) > 0)) {+ return fail('amount_too_small', 'sol amount must be greater than zero', { skip: true });+ }++ const bps = Math.max(0, Math.min(5_000, Math.round(Number(slippageBps) || 300)));++ // 1. Quote.+ let quote;+ try {+ quote = await quoteTrade({ conn: readConn, side, mintPk, mintStr: mint, network, solAmount, tokenAmountRaw, slippageBps: bps });+ } catch (e) {+ if (e?.code === 'pool_not_found') return fail('no_market', 'no bonding curve or AMM pool found for this mint', { skip: true });+ if (e?.status) return fail(e.code || 'quote_failed', e.message, { skip: true });+ return fail('quote_failed', 'could not price this trade right now', { skip: true });+ }++ // USD value of the SOL leg (best-effort).+ let usdValue = null;+ try {+ const lamports = side === 'buy' ? BigInt(quote.inAtomics) : BigInt(quote.outAtomics);+ usdValue = await lamportsToUsd(lamports);+ } catch { usdValue = null; }++ const limitsCfg = getSpendLimits(meta);+ const tradeLimits = getTradeLimits(meta);++ // 2. Guards — identical predicates to the owner-driven path. The kill switch ++ // price-impact breaker apply both directions; SOL caps gate only a buy.+ const killed = checkKillSwitch(tradeLimits.kill_switch);+ if (killed) return fail('trading_paused', 'trading is paused for this agent', { skip: true, detail: {} });++ if (side === 'buy') {+ const lamportsIn = BigInt(quote.inAtomics);++ const capLamports = tradeLimits.per_trade_sol == null ? null : BigInt(Math.floor(tradeLimits.per_trade_sol * LAMPORTS_PER_SOL));+ const cap = checkPerTradeCap(lamportsIn, capLamports);+ if (cap) return fail('per_trade_cap', `over the per-trade cap of ◎${tradeLimits.per_trade_sol}`, { skip: true, detail: cap.detail });++ if (tradeLimits.daily_budget_sol != null) {+ const budgetLamports = BigInt(Math.floor(tradeLimits.daily_budget_sol * LAMPORTS_PER_SOL));+ const spent = await getDailySpendLamports(agentId, network);+ const budget = checkDailyBudgetLamports(spent, lamportsIn, budgetLamports);+ if (budget) return fail('daily_budget', `over the ◎${tradeLimits.daily_budget_sol} daily budget`, { skip: true, detail: budget.detail });+ }++ try {+ await enforceSpendLimit({ agentId, limits: limitsCfg, category: 'trade', usdValue, network });+ } catch (e) {+ if (e instanceof SpendLimitError) return fail(e.code, e.message, { skip: true, detail: e.detail });+ throw e;+ }+ }++ // Price-impact circuit breaker — both directions.+ {+ const impact = checkPriceImpact(quote.priceImpactPct, tradeLimits.max_price_impact_pct);+ if (impact) return fail('price_impact_too_high', `price impact ${quote.priceImpactPct.toFixed(1)}% over the ${tradeLimits.max_price_impact_pct}% limit`, { skip: true, detail: impact.detail });+ }++ // 3. Rug/honeypot firewall — a REAL on-chain simulated round-trip, buys only.+ if (side === 'buy') {+ const assessment = await assessTradeSafety({+ network, mint: mintPk, side: 'buy', payer: ownerPk,+ quoteAmount: BigInt(quote.inAtomics), priceImpactPct: quote.priceImpactPct,+ }).catch(() => null);+ if (assessment) {+ recordFirewallDecision({+ mint, network, side: 'buy', verdict: assessment.verdict, score: assessment.score,+ simulated: assessment.simulated, checks: assessment.checks, reasons: assessment.reasons,+ source, agentId, userId, quoteLamports: BigInt(quote.inAtomics), enforced: assessment.verdict === 'block',+ }).catch(() => {});+ if (assessment.verdict === 'block') {+ return fail('firewall_blocked', assessment.reasons?.[0] || 'blocked by the safety firewall', { skip: true, detail: { score: assessment.score, reasons: assessment.reasons } });+ }+ }+ }++ // 4. SOL headroom / balance check (real on-chain balance).+ let walletLamports = null;+ try { walletLamports = BigInt(await readConn.getBalance(ownerPk, 'confirmed')); }+ catch {+ try { walletLamports = BigInt(await solanaPublicConnection(network).getBalance(ownerPk, 'confirmed')); }+ catch { walletLamports = null; }+ }+ if (walletLamports != null) {+ const spendLamports = side === 'buy' ? BigInt(quote.inAtomics) : 0n;+ const head = checkSolHeadroom(walletLamports, spendLamports, SOL_FEE_HEADROOM_LAMPORTS);+ if (head) return fail(side === 'buy' ? 'insufficient_sol' : 'insufficient_sol_for_fees', 'the wallet lacks SOL for this trade plus fees', { skip: true, detail: head.detail });+ }++ // 5. Idempotency fast-path.+ const [prior] = await sql`+ SELECT status, signature FROM agent_custody_events+ WHERE agent_id = ${agentId} AND idempotency_key = ${idem} LIMIT 1+ `;+ if (prior) {+ if (prior.status === 'confirmed' && prior.signature) {+ return { ok: true, replayed: true, signature: prior.signature, explorer: explorerTxUrl(prior.signature, network), side, mint, network, venue: quote.venue, usd: usdValue };+ }+ if (prior.status === 'pending') return fail('trade_in_progress', 'a trade with this id is already in flight');+ return fail('trade_failed', 'this trade id already failed');+ }++ // 6. Claim the idempotency slot (also the spend-ledger row). A buy counts toward+ // the daily ceiling (usd set); a sell records usd=null so it never inflates spend.+ const claimMeta = {+ side, mint, venue: quote.venue, source,+ expected_out_atomics: quote.outAtomics, min_out_atomics: quote.minOutAtomics,+ slippage_bps: bps, price_impact_pct: quote.priceImpactPct, ...extraMeta,+ };+ const claim = await sql`+ INSERT INTO agent_custody_events+ (agent_id, user_id, event_type, category, network, asset,+ amount_lamports, amount_raw, usd, status, idempotency_key, meta)+ VALUES (+ ${agentId}, ${userId}, 'spend', 'trade', ${network},+ ${side === 'buy' ? 'SOL' : mint},+ ${side === 'buy' ? quote.inAtomics : null},+ ${side === 'sell' ? quote.inAtomics : null},+ ${side === 'buy' ? usdValue ?? null : null},+ 'pending', ${idem},+ ${JSON.stringify(claimMeta)}::jsonb+ )+ ON CONFLICT (agent_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING+ RETURNING id+ `;+ if (!claim.length) return fail('trade_in_progress', 'a trade with this id is already in flight');+ const claimId = claim[0].id;++ // 7. Recover the signing key (audit-logged) and build the instructions.+ let keypair;+ try {+ keypair = await recoverSolanaAgentKeypair(encryptedSecret, {+ agentId, userId, reason: `${source}_trade_${side}`,+ meta: { mint, network, custody_event_id: claimId, venue: quote.venue, source },+ });+ } catch (e) {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } }).catch(() => {});+ return fail('key_recover_failed', 'could not access the agent wallet key — no funds were moved');+ }++ let instructions;+ try {+ instructions = await buildTradeInstructions({ side, conn: readConn, network, mintPk, ownerPk: keypair.publicKey, quote, slippageBps: bps, solAmount, tokenAmountRaw });+ } catch (e) {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'build_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});+ return fail(e?.code || 'build_failed', e?.message || 'could not build this trade — the market may have moved', { skip: true });+ }++ // 8. Broadcast + confirm through the MEV-aware execution engine (protected single-tx,+ // no Jito tip — autonomous mirrors don't run a per-strategy tip policy).+ const signConn = solanaConnection(network);+ let signature, confirmed = true, execTelemetry = null;+ try {+ const result = await submitProtected({+ network, connection: signConn, payer: keypair, instructions,+ opts: { tipMode: 'off', confirmTimeoutMs: 45_000 },+ });+ signature = result.signature;+ execTelemetry = { route: result.route, priority_fee_microlamports: result.priorityFeeMicroLamports, landed_ms: result.landedMs, attempts: result.attempts };+ } catch (e) {+ if (e?.code === 'TX_ERR') { signature = e.signature || null; confirmed = false; }+ else {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'send_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});+ logAudit({ userId, action: 'custody.trade_failed', resourceId: agentId, meta: { side, mint, reason: 'send_failed', source, ...extraMeta } });+ return fail('send_failed', 'the trade could not be submitted and no funds were moved');+ }+ }++ if (!confirmed) {+ await updateCustodyEvent(claimId, { signature, meta: { confirm: 'unconfirmed' } }).catch(() => {});+ logAudit({ userId, action: 'custody.trade_unconfirmed', resourceId: agentId, meta: { side, mint, signature, source, ...extraMeta } });+ return fail('trade_unconfirmed', 'the trade was submitted but not yet confirmed', { detail: { signature, explorer: explorerTxUrl(signature, network) } });+ }++ await updateCustodyEvent(claimId, {+ status: 'confirmed', signature, usd: side === 'buy' ? usdValue ?? null : null,+ meta: execTelemetry ? { exec: execTelemetry } : undefined,+ }).catch(() => {});+ logAudit({ userId, action: 'custody.trade', resourceId: agentId, meta: { side, mint, venue: quote.venue, usd: usdValue, signature, network, exec_route: execTelemetry?.route, source, ...extraMeta } });++ await cacheSet(`sol:bal:${address}:${network}`, null, 1).catch(() => {});++ return {+ ok: true, replayed: false, signature, explorer: explorerTxUrl(signature, network),+ side, mint, network, venue: quote.venue, usd: usdValue,+ custodyEventId: claimId,+ sol_spent: side === 'buy' ? lamportsToSol(quote.inAtomics) : null,+ sol_received: side === 'sell' ? lamportsToSol(quote.outAtomics) : null,+ tokens_received: side === 'buy' ? quote.outAtomics : null,+ tokens_sold: side === 'sell' ? quote.inAtomics : null,+ price_impact_pct: quote.priceImpactPct,+ };+}diff --git a/api/_lib/galaxy-flows.js b/api/_lib/galaxy-flows.jsnew file mode 100644index 000000000..db8e4c3c2--- /dev/null+++ b/api/_lib/galaxy-flows.js@@ -0,0 +1,140 @@+// Pure shaping + cursor helpers for the Galaxy Money-Cam flow feed+// (GET /api/galaxy/flows). Kept dependency-free so they are unit-testable without+// a database or RPC — the endpoint (api/galaxy/flows.js) owns all I/O and calls+// into these to turn a DB row into the public flow event the 3D map renders.+//+// A "flow" is one real, on-chain, explorer-verifiable money movement that touches+// at least one public platform agent. Every flow has a real signature (or a real+// launch mint). There are NO synthetic flows — if the platform is quiet, the feed+// is honestly empty and the galaxy stays calm.++// Custody categories that are safe to surface publicly. Everything else+// (withdraw, vanity_swap, limit_change, key_recover) is owner-private and is+// excluded by the endpoint's WHERE clause — never add those here.+export const PUBLIC_SPEND_CATEGORIES = ['trade', 'snipe', 'x402'];++// type= query param → the set of `kind`s it admits (mirrors /api/pulse).+export const TYPE_KINDS = {+ all: ['tip', 'trade', 'snipe', 'payment', 'launch'],+ tips: ['tip'],+ trades: ['trade', 'snipe'],+ payments: ['payment'],+ launches: ['launch'],+};++// Keyset cursor = base64url("<epoch_ms>|<row_id>"). row_id is the unified id of+// the boundary row; comparing (ts, row_id) gives a stable total order across the+// UNION so pagination/delta-polling never skips or duplicates a flow. Identical+// scheme to /api/pulse so the two feeds stay interchangeable.+export function encodeCursor(tsIso, rowId) {+ const ms = new Date(tsIso).getTime();+ return Buffer.from(`${ms}|${rowId}`, 'utf8').toString('base64url');+}++export function decodeCursor(raw) {+ if (!raw || typeof raw !== 'string') return null;+ try {+ const [ms, rowId] = Buffer.from(raw, 'base64url').toString('utf8').split('|');+ const n = Number(ms);+ if (!Number.isFinite(n) || !rowId) return null;+ return { ts: new Date(n).toISOString(), rowId };+ } catch {+ return null;+ }+}++// Solscan URLs — inlined (not imported from avatar-wallet.js) so this module+// stays free of Solana deps and trivially testable. Matches avatar-wallet.js.+export function txExplorerUrl(signature, network) {+ if (!signature) return null;+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';+ return `https://solscan.io/tx/${signature}${cluster}`;+}+export function accountExplorerUrl(address, network) {+ if (!address) return null;+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';+ return `https://solscan.io/account/${address}${cluster}`;+}++// Shape one DB row into the public flow event the Money-Cam renders. Pure.+//+// Direction is truthful by construction:+// · tip → 'in' money ARRIVES at the actor (sender = meta.from)+// · spend → 'out' money LEAVES the actor (recipient = destination)+// · launch→ 'launch' the actor minted a coin (no counterparty)+// from/to are then derived from direction so the client can animate a pulse in+// the real direction value moved. The counterparty agent is resolved server-side+// only when its wallet maps to another PUBLIC platform agent — otherwise it stays+// a bare wallet (or null) and the client flares the single node instead of+// fabricating a second star.+export function shapeFlow(r) {+ const network = r.network;+ const amountLamports = r.amount_lamports != null ? String(r.amount_lamports) : null;+ const amountRaw = r.amount_raw != null ? String(r.amount_raw) : null;+ const sol = amountLamports != null ? Number(amountLamports) / 1e9 : null;+ const usd = r.usd != null ? Number(r.usd) : null;+ const sig = r.signature || null;++ const actor = {+ id: r.actor_id,+ name: r.actor_name || 'Agent',+ wallet: r.actor_addr || null,+ vanity_prefix: r.actor_vp || null,+ vanity_suffix: r.actor_vs || null,+ };+ const counterparty = r.counterparty_addr+ ? { id: r.counterparty_id || null, name: r.counterparty_name || null, wallet: r.counterparty_addr }+ : null;++ // from → to in real money-flow direction.+ let from = null;+ let to = null;+ if (r.direction === 'in') {+ from = counterparty;+ to = actor;+ } else if (r.direction === 'out') {+ from = actor;+ to = counterparty;+ } else {+ from = actor; // launch: the actor acts on itself+ to = null;+ }++ return {+ id: r.row_id,+ kind: r.kind, // tip | trade | snipe | payment | launch+ direction: r.direction, // in | out | launch+ ts: r.ts instanceof Date ? r.ts.toISOString() : r.ts,+ network,+ asset: r.asset || null,+ amount_lamports: amountLamports,+ amount_raw: amountRaw,+ sol,+ usd,+ signature: sig,+ explorer: txExplorerUrl(sig, network),+ actor,+ counterparty,+ from,+ to,+ // launch-only+ mint: r.mint || null,+ symbol: r.symbol || null,+ coin_name: r.coin_name || null,+ mint_explorer: accountExplorerUrl(r.mint, network),+ };+}++// A flow is an agent↔agent EDGE only when both endpoints are real platform agents+// (the counterparty wallet resolved to another public agent and it is not the+// actor itself). Otherwise it is a single-node event (a flare). Pure predicate,+// used by both the endpoint summary and the client.+export function isAgentEdge(flow) {+ return Boolean(+ flow &&+ flow.counterparty &&+ flow.counterparty.id &&+ flow.actor &&+ flow.counterparty.id !== flow.actor.id,+ );+}diff --git a/api/_lib/migrations/20260623100000_mirror_social.sql b/api/_lib/migrations/20260623100000_mirror_social.sqlnew file mode 100644index 000000000..4b7941b8e--- /dev/null+++ b/api/_lib/migrations/20260623100000_mirror_social.sql@@ -0,0 +1,129 @@+-- Migration: the Mirror / Copy-Trade Social Graph (task 09, invention layer).+--+-- This is the CUSTODIAL agent-to-agent mirror layer — distinct from the existing+-- non-custodial copy_* tables (which only record intents a human acts on from any+-- wallet). Here, an owner subscribes ONE of THEIR agents (a custodial wallet) to+-- mirror ANOTHER public agent's real on-chain trades. When the leader trades, the+-- follower's agent executes the proportional move automatically — real tx, signed+-- with the follower's custodial key, clamped to the follower's spend policy.+--+-- Two tables:+-- mirror_subscriptions — the relationship + the follower's mirror policy. The+-- policy is bounded by, and can never exceed, the agent's+-- existing spend policy (meta.spend_limits / trade_limits);+-- it is the follower's own, narrower risk dial.+-- mirror_fills — the audit trail: every mirrored execution (filled,+-- skipped, or failed) with the leader reference + trigger,+-- traceable end to end alongside the custody ledger.+--+-- A leader's opt-out of being copyable lives in agent_identities.meta.copyable+-- (default copyable), so no schema change is needed for that — the engine reads it.+begin;++-- ── mirror_subscriptions ─────────────────────────────────────────────────────+-- follower_agent_id (the owner's custodial agent) mirrors leader_agent_id (any+-- public agent). One subscription per (follower_agent, leader_agent, network).+-- follower_user_id is denormalized for the owner-only ownership check on every+-- read/write without a join back to agent_identities.+create table if not exists mirror_subscriptions (+ id uuid primary key default gen_random_uuid(),+ follower_agent_id uuid not null references agent_identities(id) on delete cascade,+ follower_user_id uuid not null references users(id) on delete cascade,+ leader_agent_id uuid not null references agent_identities(id) on delete cascade,+ network text not null default 'mainnet', -- mainnet | devnet+ status text not null default 'active', -- active | paused | stopped++ -- Allocation: how the follower's order is sized from the leader's move.+ -- proportional : leader's SOL spend × proportion (e.g. 0.5 = half the leader)+ -- fixed : a flat fixed_sol per copied buy+ -- pct_balance : pct_balance % of the follower's own SOL balance+ allocation_mode text not null default 'proportional',+ proportion numeric not null default 1.0, -- multiplier vs leader (proportional)+ fixed_sol numeric, -- fixed mode+ pct_balance numeric, -- pct_balance mode (0–100)++ -- The follower's own caps. Hard ceilings, re-clamped to the agent's spend+ -- policy server-side at execution time (the spend policy always wins).+ max_per_trade_sol numeric not null default 0.25,+ max_per_day_sol numeric not null default 1.0,+ min_order_sol numeric not null default 0.001, -- skip dust below this+ slippage_bps int not null default 300, -- clamped to trade_limits.max_slippage_bps++ -- Asset gating. allow_mints non-empty ⇒ only those mints are mirrored.+ -- deny_mints always blocks. $THREE is never special-cased here — this is+ -- coin-agnostic plumbing keyed on whatever mint the leader actually traded.+ allow_mints text[] not null default '{}'::text[],+ deny_mints text[] not null default '{}'::text[],+ copy_sells boolean not null default true, -- mirror leader exits++ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),++ constraint mirror_sub_uniq unique (follower_agent_id, leader_agent_id, network),+ constraint mirror_no_self check (follower_agent_id <> leader_agent_id),+ constraint mirror_alloc_mode check (allocation_mode in ('proportional','fixed','pct_balance')),+ constraint mirror_status_ck check (status in ('active','paused','stopped'))+);++-- "Who does this agent follow" (follower lens) and "who follows this agent"+-- (leader/discovery lens) are both hot reads; index each direction.+create index if not exists mirror_sub_follower+ on mirror_subscriptions (follower_agent_id, status);+create index if not exists mirror_sub_leader+ on mirror_subscriptions (leader_agent_id, network, status);+create index if not exists mirror_sub_user+ on mirror_subscriptions (follower_user_id, status);++-- ── mirror_fills ─────────────────────────────────────────────────────────────+-- One row per (subscription, leader trade, direction). The partial unique index+-- makes the fanout idempotent: a re-run over the same leader trade can't fire a+-- second mirrored order. leader_custody_event_id is the discretionary-trade+-- trigger; leader_position_id is the sniper trigger (mutually exclusive).+create table if not exists mirror_fills (+ id uuid primary key default gen_random_uuid(),+ subscription_id uuid not null references mirror_subscriptions(id) on delete cascade,+ follower_agent_id uuid not null,+ follower_user_id uuid not null,+ leader_agent_id uuid not null,+ network text not null default 'mainnet',++ -- Trigger references (exactly one set).+ leader_custody_event_id bigint, -- agent_custody_events.id (discretionary)+ leader_position_id uuid, -- agent_sniper_positions.id (sniper)+ leader_signature text, -- leader's on-chain tx (attribution)++ mint text not null,+ symbol text,+ direction text not null, -- buy | sell+ planned_sol numeric, -- sized order (null when skipped pre-size)++ status text not null, -- filled | skipped | failed+ skip_reason text, -- why a copy/sell was not executed+ follower_signature text, -- the mirrored tx signature+ follower_custody_event_id bigint, -- agent_custody_events.id of the mirror+ usd numeric,+ detail jsonb not null default '{}'::jsonb,++ created_at timestamptz not null default now(),++ constraint mirror_fill_dir check (direction in ('buy','sell')),+ constraint mirror_fill_status check (status in ('filled','skipped','failed'))+);++-- Idempotency: one fill per (subscription, leader trigger, direction). Two partial+-- indexes because the trigger source is either a custody event or a sniper position.+create unique index if not exists mirror_fill_custody_uniq+ on mirror_fills (subscription_id, leader_custody_event_id, direction)+ where leader_custody_event_id is not null;+create unique index if not exists mirror_fill_position_uniq+ on mirror_fills (subscription_id, leader_position_id, direction)+ where leader_position_id is not null;++-- Owner-facing audit feed: a follower's mirror history, newest first.+create index if not exists mirror_fills_follower_time+ on mirror_fills (follower_agent_id, created_at desc);+-- Leaderboard / leader social proof: a leader's downstream mirror activity.+create index if not exists mirror_fills_leader_time+ on mirror_fills (leader_agent_id, created_at desc);++commit;diff --git a/api/_lib/migrations/20260623100000_social_recovery.sql b/api/_lib/migrations/20260623100000_social_recovery.sqlnew file mode 100644index 000000000..9edfa392f--- /dev/null+++ b/api/_lib/migrations/20260623100000_social_recovery.sql@@ -0,0 +1,113 @@+begin;++-- Social recovery & inheritance for custodial agent wallets.+--+-- Agent Solana/EVM wallets are custodial: the platform holds the AES-GCM+-- encrypted secret and signs server-side, and the single owner is+-- agent_identities.user_id. That makes "I lost access" or "the owner is gone"+-- survivable WITHOUT ever exporting a key — recovery/inheritance change *who the+-- owner is* (the user_id), never the encrypted secret, which keeps signing for+-- the new owner exactly as before.+--+-- Three tables model the social graph + the threshold-approved, time-locked+-- process. The owner-set threshold and dead-man's-switch config live on+-- agent_identities.meta.recovery (jsonb) — same convention as meta.spend_limits —+-- so this migration is purely the relational/audit side.++-- ── guardians + beneficiary roster ─────────────────────────────────────────────+-- Who can help recover (guardians) and who inherits (beneficiary). Both reference+-- REAL accounts (users.id). A user may be both a guardian and the beneficiary+-- (two rows, distinct role). Reverse lookup (guardian_user_id, status) powers the+-- guardian inbox: "the agents I'm trusted to recover".+create table if not exists agent_recovery_guardians (+ id bigserial primary key,+ agent_id uuid not null,+ guardian_user_id uuid not null references users(id) on delete cascade,+ role text not null default 'guardian', -- guardian | beneficiary+ status text not null default 'active', -- active | removed+ added_by uuid, -- owner who set it (audit)+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- One active row per (agent, user, role): re-adding a removed guardian flips the+-- existing row back to active rather than duplicating.+create unique index if not exists agent_recovery_guardians_unq+ on agent_recovery_guardians (agent_id, guardian_user_id, role);++create index if not exists agent_recovery_guardians_inbox+ on agent_recovery_guardians (guardian_user_id, status)+ where status = 'active';++create index if not exists agent_recovery_guardians_agent+ on agent_recovery_guardians (agent_id, status);++-- ── recovery / inheritance requests ────────────────────────────────────────────+-- One ongoing process to hand control of an agent to a new owner. `kind`+-- distinguishes an owner-driven recovery from a dead-man's-switch inheritance.+-- The process is threshold-approved (approvals_required) AND time-locked+-- (timelock_until) so a single impostor — or a single compromised guardian —+-- can never take over: the real owner has the whole window to cancel by simply+-- being active.+create table if not exists agent_recovery_requests (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null,+ kind text not null, -- recovery | inheritance+ status text not null default 'pending_approvals',+ -- pending_approvals | time_locked | ready | completed | cancelled | rejected | expired+ requester_id uuid, -- initiator (null = system/cron)+ prev_owner_id uuid not null, -- owner at request time+ new_owner_id uuid not null, -- nominee who gains control+ approvals_required int not null default 1,+ timelock_until timestamptz, -- set once threshold is met+ reason text,+ meta jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ completed_at timestamptz+);++-- Serialize: at most ONE active process per agent. A second recovery attempt+-- (an impostor racing the owner, or a duplicate click) is refused at the DB+-- level rather than racing two transfers.+create unique index if not exists agent_recovery_requests_one_active+ on agent_recovery_requests (agent_id)+ where status in ('pending_approvals', 'time_locked', 'ready');++create index if not exists agent_recovery_requests_agent_time+ on agent_recovery_requests (agent_id, created_at desc);++create index if not exists agent_recovery_requests_active+ on agent_recovery_requests (status)+ where status in ('pending_approvals', 'time_locked', 'ready');++-- ── guardian votes ─────────────────────────────────────────────────────────────+-- One vote per guardian per request; a re-vote overwrites the prior decision.+-- Counted at evaluation time by JOINing against the CURRENT active guardian+-- roster, so a guardian removed (or whose account was deleted) mid-process no+-- longer counts — no stale approvals can push a takeover over the threshold.+create table if not exists agent_recovery_approvals (+ id bigserial primary key,+ request_id uuid not null references agent_recovery_requests(id) on delete cascade,+ guardian_user_id uuid not null references users(id) on delete cascade,+ decision text not null, -- approve | decline+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create unique index if not exists agent_recovery_approvals_unq+ on agent_recovery_approvals (request_id, guardian_user_id);++comment on table agent_recovery_guardians is+ 'Per-agent guardian + beneficiary roster for social recovery / inheritance of '+ 'custodial agent wallets. role = guardian|beneficiary. Owner-managed; reverse '+ 'lookup (guardian_user_id) powers the guardian inbox. Threshold + dead-man '+ 'config live in agent_identities.meta.recovery.';++comment on table agent_recovery_requests is+ 'Threshold-approved, time-locked process to transfer agent ownership '+ '(agent_identities.user_id) to a new owner — no key is ever exported. '+ 'One active row per agent (partial unique index). Completion is atomic and '+ 'audited in agent_custody_events as an ownership_transfer.';++commit;diff --git a/api/_lib/migrations/20260624000000_agent_mirror.sql b/api/_lib/migrations/20260624000000_agent_mirror.sqlnew file mode 100644index 000000000..c0ac2b520--- /dev/null+++ b/api/_lib/migrations/20260624000000_agent_mirror.sql@@ -0,0 +1,126 @@+-- Migration: custodial mirror / copy-trade social graph (task 09).+--+-- Distinct from the NON-custodial copy_subscriptions/copy_executions system+-- (api/copy/*, api/cron/copy-fanout.js), which only records INTENTS the copier+-- acts on from their own wallet. This layer is CUSTODIAL: a follower agent's own+-- server-signed wallet auto-mirrors a leader agent's real on-chain trades through+-- the same task-05 trade engine + the same shared spend guardrails+-- (api/_lib/agent-trade-guards.js). Every mirrored trade is a real tx within real+-- limits, fully audited in agent_custody_events (category 'trade', reason+-- 'mirror'), and the owner can pause one edge or kill all mirroring at once.+--+-- apply-migrations.mjs only runs api/_lib/migrations/*.sql, so the schema lives+-- here. Everything is `if not exists`, safe to re-apply.+begin;++-- ── agent_mirror_follows — the directed copy-trade graph ─────────────────────+-- One row = "follower_agent_id mirrors leader_agent_id, under owner_user_id's+-- spend policy." Owner-only to create/edit (owner_user_id is the follower's+-- owner, snapshotted for the cron's authz + audit). `enabled` pauses one edge;+-- the agent-wide kill switch lives at agent_identities.meta.mirror_killed and+-- halts every edge for the follower at once. last_leader_event_id is the cursor+-- into agent_custody_events.id so the fanout never reprocesses an old trade.+create table if not exists agent_mirror_follows (+ id bigserial primary key,+ follower_agent_id uuid not null references agent_identities(id) on delete cascade,+ leader_agent_id uuid not null references agent_identities(id) on delete cascade,+ owner_user_id uuid not null references users(id) on delete cascade,+ network text not null default 'mainnet',+ enabled boolean not null default true,++ -- Sizing rule: how a leader buy of N SOL becomes the follower's order.+ -- 'fixed' → always order fixed_sol+ -- 'proportional' → leader_sol * (proportion_pct / 100)+ -- 'pct_balance' → follower_spendable_sol * (pct_balance / 100)+ sizing_mode text not null default 'proportional',+ fixed_sol double precision,+ proportion_pct double precision default 100,+ pct_balance double precision,++ -- Per-follow leash. max_per_trade_sol hard-caps any single mirrored buy;+ -- daily_budget_sol is an optional extra ceiling on top of the follower's+ -- agent-level trade_limits (null = governed solely by the agent policy).+ max_per_trade_sol double precision,+ daily_budget_sol double precision,+ min_leader_sol double precision default 0, -- ignore leader buys smaller than this++ copy_sells boolean not null default true,+ mint_allowlist text[] not null default '{}'::text[], -- if non-empty, only mirror these mints+ mint_denylist text[] not null default '{}'::text[], -- never mirror these mints++ last_leader_event_id bigint not null default 0,+ paused_reason text, -- set when auto-paused (e.g. repeated failures)+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),++ check (follower_agent_id <> leader_agent_id)+);++-- One follow edge per (follower, leader). The toggle/upsert keys on this.+create unique index if not exists agent_mirror_follows_edge+ on agent_mirror_follows (follower_agent_id, leader_agent_id);++-- Hot read: "who does this agent follow" (owner management view).+create index if not exists agent_mirror_follows_by_follower+ on agent_mirror_follows (follower_agent_id, created_at desc);++-- Hot read: "who follows this agent" (leader's follower count + discovery).+create index if not exists agent_mirror_follows_by_leader+ on agent_mirror_follows (leader_agent_id);++-- Fanout scan: active edges per leader+network whose cursor may be behind.+create index if not exists agent_mirror_follows_active+ on agent_mirror_follows (leader_agent_id, network)+ where enabled = true;++comment on table agent_mirror_follows is+ 'Custodial copy-trade graph: follower_agent_id auto-mirrors leader_agent_id''s '+ 'real trades through the task-05 engine, within the follower owner''s spend policy.';++-- ── agent_mirror_fills — the per-mirror execution log ────────────────────────+-- One row per (follow, leader trade) the fanout considered: executed, skipped+-- (with a human reason), failed, or unconfirmed. The unique key makes mirroring+-- idempotent — a leader trade can never be mirrored twice for the same follow.+-- custody_event_id links to the real agent_custody_events row (signature, USD,+-- audit) that the trade engine wrote; this table is the social/track-record view.+create table if not exists agent_mirror_fills (+ id bigserial primary key,+ follow_id bigint not null references agent_mirror_follows(id) on delete cascade,+ follower_agent_id uuid not null,+ leader_agent_id uuid not null,+ owner_user_id uuid,+ network text not null default 'mainnet',++ leader_event_id bigint not null, -- agent_custody_events.id of the leader trade+ leader_signature text,+ side text not null, -- 'buy' | 'sell'+ mint text not null,+ leader_sol double precision, -- leader's SOL leg size+ planned_sol double precision, -- sized for the follower (buys)++ status text not null, -- 'executed' | 'skipped' | 'failed' | 'unconfirmed'+ skip_reason text,+ custody_event_id bigint, -- follower's agent_custody_events row+ signature text,+ usd double precision,+ price_impact_pct double precision,+ created_at timestamptz not null default now()+);++-- Idempotency: one mirror outcome per (follow, leader trade, side).+create unique index if not exists agent_mirror_fills_idem+ on agent_mirror_fills (follow_id, leader_event_id, side);++-- Owner feed: this follower's recent mirror activity, newest first.+create index if not exists agent_mirror_fills_by_follower+ on agent_mirror_fills (follower_agent_id, created_at desc);++-- Leader view: trades this leader generated for its followers.+create index if not exists agent_mirror_fills_by_leader+ on agent_mirror_fills (leader_agent_id, created_at desc);++comment on table agent_mirror_fills is+ 'Per-mirror execution log linking a leader trade to the follower''s real fill '+ '(or the reason it was skipped). Unique (follow,leader_event,side) = no double-mirror.';++commit;diff --git a/api/_lib/migrations/20260624120000_treasury_autopilot.sql b/api/_lib/migrations/20260624120000_treasury_autopilot.sqlnew file mode 100644index 000000000..19f4be9f5--- /dev/null+++ b/api/_lib/migrations/20260624120000_treasury_autopilot.sql@@ -0,0 +1,94 @@+begin;++-- Treasury Autopilot (prompts/agent-wallets/14) — the agent that funds its own+-- existence.+--+-- An agent's custodial wallet both EARNS (tips, its coin's creator fees, trading)+-- and COSTS money to run (the metered LLM/voice compute that makes it think and+-- talk). Treasury Autopilot lets the owner arm a natural-language treasury policy+-- the agent executes on its OWN wallet, autonomously and bounded: settle its own+-- compute, hold a safety buffer, dollar-cost-average a slice of income into+-- $THREE, compound its coin fees into buybacks, and sweep profit to the owner on+-- a schedule. Every action is a real, spend-policy-gated on-chain transaction.+--+-- Two tables:+-- agent_treasury_autopilot the per-agent policy: the owner's NL text, the+-- compiled+approved rules, and the arm/kill flags.+-- Config side — the source of truth for "what is armed".+-- agent_autopilot_runs the run ledger: one row per (agent, rule, period)+-- attempt, idempotent by design so an overlapping+-- cron tick can never double-execute. Powers the+-- runway view and the activity trail. The custodial+-- spend itself is ALSO written to agent_custody_events+-- (the shared audit trail) — this table is the+-- autopilot-specific scheduling + analytics side.++-- ── policy (config) ──────────────────────────────────────────────────────────+create table if not exists agent_treasury_autopilot (+ agent_id uuid primary key references agent_identities(id) on delete cascade,+ user_id uuid not null, -- owner who armed it (immutable owner of the agent)+ network text not null default 'mainnet',+ -- Arm state. `armed` = the owner approved the compiled rules and turned it on.+ -- `killed` = the prominent kill switch. A killed policy halts ALL execution+ -- instantly regardless of `armed`, and is the safe resting state.+ armed boolean not null default false,+ killed boolean not null default false,+ -- The owner's natural-language policy, verbatim — shown back so they always+ -- see what they wrote.+ policy_text text,+ -- The compiled, validated, owner-APPROVED rules (the structured form the+ -- executor runs). Null until the owner approves a compile.+ rules jsonb not null default '{}'::jsonb,+ -- Hash of the approved rules. If a later compile differs, the UI requires a+ -- fresh approval before arming — the owner always re-consents to changes.+ rules_hash text,+ approved_at timestamptz,+ -- Per-rule pause map: { "<rule_kind>": true } pauses just that rule without+ -- disarming the whole policy.+ paused jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- The cron scans armed, un-killed policies on mainnet ordered by last touch.+create index if not exists agent_treasury_autopilot_active+ on agent_treasury_autopilot (network, updated_at desc)+ where armed = true and killed = false;++-- ── run ledger (idempotent execution log + analytics) ────────────────────────+create table if not exists agent_autopilot_runs (+ id bigserial primary key,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ user_id uuid,+ network text not null default 'mainnet',+ -- settle_compute | buffer | dca | buyback | sweep+ rule_kind text not null,+ -- The period bucket this run satisfies (e.g. 'dca:2026-W26', 'sweep:2026-06-26').+ -- The unique index below makes (agent, kind, period) execute at most once.+ period_key text not null,+ -- planned | executing | confirmed | skipped | failed+ status text not null default 'planned',+ -- Why it skipped/failed (e.g. 'below_buffer', 'no_income', 'no_liquidity',+ -- 'price_feed_down', 'killed') — surfaced honestly in the activity trail.+ reason text,+ -- The on-chain tx (buy/sweep/settle). Null for skips.+ signature text,+ amount_lamports bigint,+ amount_usd numeric,+ -- Free-form: { mint, route, expected_out, explorer, trigger, ... }.+ meta jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- Idempotency: at most one run per (agent, rule_kind, period_key). The executor+-- INSERTs this row BEFORE moving funds; a duplicate insert loses the race and the+-- second runner backs off — no double-spend on overlapping ticks or retries.+create unique index if not exists agent_autopilot_runs_idem+ on agent_autopilot_runs (agent_id, rule_kind, period_key);++-- Activity trail + runway analytics: newest-first per agent.+create index if not exists agent_autopilot_runs_agent_time+ on agent_autopilot_runs (agent_id, created_at desc);++commit;diff --git a/api/_lib/mirror-engine.js b/api/_lib/mirror-engine.jsnew file mode 100644index 000000000..88fcbdf32--- /dev/null+++ b/api/_lib/mirror-engine.js@@ -0,0 +1,170 @@+/**+ * Custodial mirror-trade decision engine — PURE, deterministic, no DB / no network.+ *+ * Given a follow edge, the leader's detected trade, and the follower's live+ * spendable balance + remaining daily budget, it decides whether to mirror and at+ * what size. This is the money-adjacent core of task 09, so it is isolated and+ * unit-tested (tests/mirror-engine.test.js). Every "skip" carries a machine ++ * human reason so the owner can see exactly why a mirror didn't fire.+ *+ * It NEVER signs or moves funds — it only sizes the order. The actual execution+ * (api/_lib/agent-mirror.js) runs the sized order through the SAME shared spend+ * guardrails (api/_lib/agent-trade-guards.js) the discretionary trade endpoint+ * and the sniper use, so a runaway leader can never drain a follower: this engine+ * is the first clamp, the spend policy is the hard backstop.+ */++const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));+const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);+const round6 = (x) => Math.round(x * 1e6) / 1e6;++// A buy sized below this is dust — not worth a tx fee, and pump curves reject it.+export const MIN_MIRROR_BUY_SOL = 0.0005;++/**+ * Validate + normalize a follow edge's tunables coming from owner input.+ * Returns { ok, value, error }. Never throws.+ */+export function normalizeFollowInput(raw = {}) {+ const sizing = ['fixed', 'proportional', 'pct_balance'].includes(raw.sizing_mode) ? raw.sizing_mode : 'proportional';+ const fixed = n(raw.fixed_sol);+ // Proportional defaults to 1:1 (100%) when the owner doesn't specify a ratio.+ const proportion = raw.proportion_pct == null || raw.proportion_pct === '' ? 100 : n(raw.proportion_pct);+ const pct = n(raw.pct_balance);+ const maxPerTrade = raw.max_per_trade_sol == null || raw.max_per_trade_sol === '' ? null : n(raw.max_per_trade_sol);+ const dailyBudget = raw.daily_budget_sol == null || raw.daily_budget_sol === '' ? null : n(raw.daily_budget_sol);+ const minLeader = n(raw.min_leader_sol);++ if (sizing === 'fixed' && fixed <= 0) return { ok: false, error: 'fixed_sol must be greater than 0' };+ if (sizing === 'proportional' && !(proportion > 0)) return { ok: false, error: 'proportion_pct must be greater than 0' };+ if (sizing === 'pct_balance' && !(pct > 0 && pct <= 100)) return { ok: false, error: 'pct_balance must be between 0 and 100' };+ if (maxPerTrade != null && maxPerTrade <= 0) return { ok: false, error: 'max_per_trade_sol must be greater than 0' };+ if (dailyBudget != null && dailyBudget <= 0) return { ok: false, error: 'daily_budget_sol must be greater than 0' };+ if (minLeader < 0) return { ok: false, error: 'min_leader_sol cannot be negative' };++ const cleanMints = (arr) => (Array.isArray(arr) ? arr : [])+ .map((m) => (typeof m === 'string' ? m.trim() : ''))+ .filter((m) => /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(m))+ .slice(0, 100);++ return {+ ok: true,+ value: {+ sizing_mode: sizing,+ fixed_sol: fixed,+ proportion_pct: sizing === 'proportional' ? proportion : 100,+ pct_balance: pct,+ max_per_trade_sol: maxPerTrade,+ daily_budget_sol: dailyBudget,+ min_leader_sol: minLeader,+ copy_sells: raw.copy_sells !== false,+ mint_allowlist: cleanMints(raw.mint_allowlist),+ mint_denylist: cleanMints(raw.mint_denylist),+ },+ };+}++/** Raw order size (SOL) from the sizing rule, before any clamping. */+export function rawMirrorSol(follow, { leaderSol = 0, followerBalanceSol = null } = {}) {+ switch (follow.sizing_mode) {+ case 'fixed': return n(follow.fixed_sol);+ case 'proportional': return n(leaderSol) * (n(follow.proportion_pct) / 100);+ case 'pct_balance':+ return followerBalanceSol == null ? NaN : n(followerBalanceSol) * (n(follow.pct_balance) / 100);+ default: return 0;+ }+}++/**+ * Decide whether — and at what size — to mirror one leader trade onto one follow.+ *+ * @param {object} p+ * @param {object} p.follow the follow edge (sizing rule + leashes).+ * @param {object} p.leaderTrade { side:'buy'|'sell', mint, leaderSol }.+ * @param {number|null} p.followerBalanceSol follower's spendable SOL (needed for pct_balance + headroom).+ * @param {number} [p.spentTodaySol] SOL already mirrored under this follow's daily budget today.+ * @param {boolean} [p.killed] the follower agent's mirror kill switch.+ * @returns {{ action:'mirror'|'skip', side:'buy'|'sell', order_sol?:number, reason:string, detail?:string }}+ */+export function planMirror({ follow, leaderTrade, followerBalanceSol = null, spentTodaySol = 0, killed = false }) {+ const side = leaderTrade.side === 'sell' ? 'sell' : 'buy';+ const mint = leaderTrade.mint;++ if (killed) return skip(side, 'mirror_killed', 'Mirroring is paused by the kill switch.');+ if (!follow.enabled) return skip(side, 'follow_disabled', 'This follow is paused.');++ // Allow/deny lists apply to both directions — an owner who blocked a mint never+ // wants to hold OR be forced to keep it.+ const deny = Array.isArray(follow.mint_denylist) ? follow.mint_denylist : [];+ const allow = Array.isArray(follow.mint_allowlist) ? follow.mint_allowlist : [];+ if (deny.includes(mint)) return skip(side, 'mint_denylisted', 'This token is on your skip list.');+ if (allow.length > 0 && !allow.includes(mint)) return skip(side, 'mint_not_allowlisted', 'This token is not on your allow list.');++ // SELL — mirror the exit: sell the follower's full remaining balance of the+ // mint (the safe direction — selling brings SOL in). Sizing happens at execution+ // from the real on-chain token balance, so the engine only gates here.+ if (side === 'sell') {+ if (!follow.copy_sells) return skip('sell', 'sells_disabled', 'This follow does not mirror sells.');+ return { action: 'mirror', side: 'sell', reason: 'mirror_exit' };+ }++ // BUY — size + leash.+ const leaderSol = n(leaderTrade.leaderSol);+ if (follow.min_leader_sol > 0 && leaderSol > 0 && leaderSol < follow.min_leader_sol) {+ return skip('buy', 'below_min_leader', `Leader's ${leaderSol.toFixed(4)} SOL buy is below your ${follow.min_leader_sol} SOL floor.`);+ }++ let order = rawMirrorSol(follow, { leaderSol, followerBalanceSol });+ if (!Number.isFinite(order) || order <= 0) {+ return skip('buy', 'sizing_unavailable', 'Could not size this order (missing balance for % sizing).');+ }++ // Per-follow per-trade cap (the agent-level per_trade_sol cap is enforced again+ // at execution as the hard backstop).+ if (follow.max_per_trade_sol != null) {+ order = Math.min(order, follow.max_per_trade_sol);+ }++ // Per-follow daily budget (optional, stacks under the agent's own daily budget).+ if (follow.daily_budget_sol != null) {+ const remaining = follow.daily_budget_sol - n(spentTodaySol);+ if (remaining <= 0) return skip('buy', 'follow_daily_spent', 'This follow’s daily budget is already used up.');+ order = Math.min(order, remaining);+ }++ // Don't spend more than the wallet can cover (a fee/rent headroom is re-checked+ // on-chain at execution; this is the early, friendly clamp).+ if (followerBalanceSol != null) {+ order = Math.min(order, Math.max(0, followerBalanceSol - 0.004));+ }++ if (order < MIN_MIRROR_BUY_SOL) {+ return skip('buy', 'below_dust', `Sized order ${order.toFixed(5)} SOL is below the ${MIN_MIRROR_BUY_SOL} SOL minimum.`);+ }++ return { action: 'mirror', side: 'buy', order_sol: round6(order), reason: 'sized' };+}++function skip(side, reason, detail) {+ return { action: 'skip', side, reason, detail };+}++// Human-friendly labels for skip reasons, surfaced in the owner's mirror feed.+export const SKIP_LABELS = {+ mirror_killed: 'Kill switch on',+ follow_disabled: 'Follow paused',+ mint_denylisted: 'Token on skip list',+ mint_not_allowlisted: 'Not on allow list',+ sells_disabled: 'Sells not mirrored',+ below_min_leader: 'Leader buy too small',+ sizing_unavailable: 'Could not size order',+ follow_daily_spent: 'Daily budget used up',+ below_dust: 'Order too small',+ insufficient_sol: 'Wallet underfunded',+ per_trade_cap: 'Over per-trade cap',+ daily_budget: 'Over daily budget',+ price_impact: 'Price impact too high',+ wallet_frozen: 'Wallet frozen',+ firewall_blocked: 'Blocked by safety firewall',+ no_holding: 'Nothing to sell',+};diff --git a/api/_lib/mirror-stats.js b/api/_lib/mirror-stats.jsnew file mode 100644index 000000000..50fa83b09--- /dev/null+++ b/api/_lib/mirror-stats.js@@ -0,0 +1,131 @@+/**+ * Leader track records — REAL, on-chain-derived stats only.+ *+ * The trust surface of copy-trading: before you let your agent mirror a leader,+ * you see that leader's honest numbers — realized P&L, win rate, drawdown,+ * volume — every one computed from real persisted fills, never inflated, never+ * backfilled, losers included.+ *+ * Two real sources, both confirmed chain data:+ * • agent_sniper_positions (closed) — entry/exit lamports + realized P&L per+ * round-trip. This is where win rate / P&L / drawdown come from.+ * • agent_custody_events (category 'trade', confirmed) — every discretionary+ * buy/sell the leader signed, for trade count + SOL/USD volume.+ *+ * A leader with zero history returns total === 0 (an honest "no track record+ * yet"), never a fabricated number.+ */++import { sql } from './db.js';++const lamToSol = (l) => (l == null ? 0 : Number(BigInt(l)) / 1e9);++/**+ * Compute a leader agent's real track record on a network.+ * @returns {Promise<object>} honest summary (all numbers from real fills).+ */+export async function leaderTrackRecord(agentId, network = 'mainnet') {+ const [closed, activity, followers] = await Promise.all([+ sql`+ select realized_pnl_lamports, realized_pnl_pct, entry_quote_lamports,+ exit_quote_lamports, closed_at+ from agent_sniper_positions+ where agent_id = ${agentId} and network = ${network} and status = 'closed'+ order by closed_at asc+ `.catch(() => []),+ sql`+ select+ count(*)::int as trades,+ count(*) filter (where status = 'confirmed')::int as confirmed,+ coalesce(sum(amount_lamports) filter (where asset = 'SOL'), 0)::text as buy_lamports,+ coalesce(sum(usd) filter (where usd is not null), 0)::float8 as usd_volume,+ max(created_at) as last_trade_at+ from agent_custody_events+ where agent_id = ${agentId} and network = ${network}+ and category = 'trade' and status in ('confirmed', 'ok')+ `.catch(() => [{}]),+ sql`+ select count(*)::int as total,+ count(*) filter (where enabled = true)::int as active+ from agent_mirror_follows+ where leader_agent_id = ${agentId} and network = ${network}+ `.catch(() => [{ total: 0, active: 0 }]),+ ]);++ // Realized stats from closed round-trips (the honest P&L surface).+ let wins = 0;+ let losses = 0;+ let pnlSol = 0;+ let grossEntrySol = 0;+ let best = null;+ let worst = null;+ // Max drawdown over the cumulative realized-P&L equity curve (peak-to-trough).+ let equity = 0;+ let peak = 0;+ let maxDrawdownSol = 0;+ for (const p of closed) {+ const pnl = lamToSol(p.realized_pnl_lamports);+ pnlSol += pnl;+ grossEntrySol += lamToSol(p.entry_quote_lamports);+ if (pnl > 0) wins++; else if (pnl < 0) losses++;+ const pct = p.realized_pnl_pct != null ? Number(p.realized_pnl_pct) : null;+ if (pct != null) {+ if (best == null || pct > best) best = pct;+ if (worst == null || pct < worst) worst = pct;+ }+ equity += pnl;+ if (equity > peak) peak = equity;+ const dd = peak - equity;+ if (dd > maxDrawdownSol) maxDrawdownSol = dd;+ }+ const settled = wins + losses;+ const a = activity[0] || {};+ const f = followers[0] || { total: 0, active: 0 };++ const tradeCount = Number(a.trades || 0);+ const buyVolumeSol = lamToSol(a.buy_lamports || 0);+ const roiPct = grossEntrySol > 0 ? (pnlSol / grossEntrySol) * 100 : null;++ return {+ network,+ // "Does this leader have anything to show?" — total spans both real sources.+ total: closed.length + tradeCount,+ closed_positions: closed.length,+ discretionary_trades: tradeCount,+ realized: {+ pnl_sol: round4(pnlSol),+ roi_pct: roiPct == null ? null : round2(roiPct),+ win_rate: settled > 0 ? round2((wins / settled) * 100) : null,+ wins,+ losses,+ settled,+ best_pct: best == null ? null : round2(best),+ worst_pct: worst == null ? null : round2(worst),+ max_drawdown_sol: round4(maxDrawdownSol),+ },+ volume: {+ buy_sol: round4(buyVolumeSol),+ usd: a.usd_volume != null ? round2(Number(a.usd_volume)) : 0,+ },+ followers: { total: Number(f.total || 0), active: Number(f.active || 0) },+ last_trade_at: a.last_trade_at || (closed.length ? closed[closed.length - 1].closed_at : null),+ };+}++/** Batch follower/following counts for a set of agents (for cards/leaderboards). */+export async function followCounts(agentIds, network = 'mainnet') {+ if (!Array.isArray(agentIds) || agentIds.length === 0) return new Map();+ const rows = await sql`+ select leader_agent_id as id, count(*)::int as followers,+ count(*) filter (where enabled = true)::int as active_followers+ from agent_mirror_follows+ where leader_agent_id = any(${agentIds}) and network = ${network}+ group by leader_agent_id+ `.catch(() => []);+ const m = new Map();+ for (const r of rows) m.set(r.id, { followers: Number(r.followers), active: Number(r.active_followers) });+ return m;+}++function round2(x) { return Math.round(x * 100) / 100; }+function round4(x) { return Math.round(x * 1e4) / 1e4; }diff --git a/api/_lib/networth-model.js b/api/_lib/networth-model.jsindex 19777b32e..e999522f6 100644--- a/api/_lib/networth-model.js+++ b/api/_lib/networth-model.js@@ -4,9 +4,9 @@// presence: the wealth/reputation tier, the aura intensity/colour, the idle// confidence, and the legible "regalia" marks. The server computes the canonical// look from real reads (api/agents/solana-wallet.js → handleNetWorth) and the-// browser renders it; src/shared/agent-networth.js imports the same constants for-// the offline/hold-last-state fallback so the galaxy star, the profile hero, and-// the AR body always agree.+// browser renders it (src/shared/agent-networth.js fetches it for the presence+// panel; src/shared/wallet-aura.js + the galaxy shader share this tier vocabulary)+// so the galaxy star, the profile hero, and the AR body always agree.//// Every output traces to a real number. Nothing here invents a balance — callers// pass real portfolio USD, real $THREE holdings, real fork counts, and real@@ -20,13 +20,18 @@ export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';// Presence tiers, keyed off real portfolio USD value. Names follow the aura// metaphor (light, not money) so a well-funded agent reads as *present*, never// gaudy. `min` is the real USD threshold that unlocks the tier.+//+// These thresholds, keys and labels are the CANONICAL set, kept in lockstep with+// src/shared/wallet-networth.js (NETWORTH_TIERS) so the galaxy star, the aura on+// every surface, and the presence panel all name the same wallet the same tier.+// Change one, change both. Accents stay in the wallet-violet family.export const PRESENCE_TIERS = Object.freeze([- { key: 'latent', label: 'Latent', min: 0, accent: '#8b8b9a' },+ { key: 'dormant', label: 'Dormant', min: 0, accent: '#8b8b9a' },{ key: 'spark', label: 'Spark', min: 1, accent: '#8b5cf6' },- { key: 'glow', label: 'Glow', min: 50, accent: '#a78bfa' },- { key: 'radiant', label: 'Radiant', min: 500, accent: '#c4b5fd' },- { key: 'luminous', label: 'Luminous', min: 5_000, accent: '#ddd6fe' },- { key: 'beacon', label: 'Beacon', min: 50_000, accent: '#f5f3ff' },+ { key: 'ember', label: 'Ember', min: 25, accent: '#9b7cf6' },+ { key: 'glow', label: 'Glow', min: 250, accent: '#a78bfa' },+ { key: 'radiant', label: 'Radiant', min: 2_500, accent: '#c4b5fd' },+ { key: 'luminous', label: 'Luminous', min: 25_000, accent: '#ddd6fe' },]);export const REACTIVITY_LEVELS = Object.freeze(['off', 'subtle', 'balanced', 'expressive']);@@ -64,6 +69,7 @@ export function tierForUsd(usd) {* @param {number} state.usd real total portfolio USD* @param {number} [state.threeUsd] real $THREE holding value (extra warmth)* @param {number} [state.forkCount] real forks-of-this-agent+ * @param {number} [state.tipUsd] real lifetime tip volume in USD (optional)* @param {number} [state.repScore] real reputation score 0..100 (optional)* @param {number} [state.attesters] real unique attesters (optional)*/@@ -81,11 +87,14 @@ export function computeLook(state = {}) {const auraIntensity = clamp(wealth + threeBoost, 0, 1);// Reputation lifts the idle posture (stands taller / steadier) without touching- // the aura, so a brand-new but well-attested agent still reads as trusted.+ // the aura, so a brand-new but well-tipped/forked agent still reads as trusted.+ // Forks, lifetime tip volume, and attestation are all real earned signals.const repScore = clamp(state.repScore, 0, 100) / 100;const forks = Math.max(0, Number(state.forkCount) || 0);const forkBoost = clamp(Math.log10(forks + 1) / 3, 0, 0.25); // 9 forks ~0.33→capped .25- const confidence = clamp(tier.index / 5 * 0.6 + repScore * 0.25 + forkBoost, 0, 1);+ const tipUsd = Math.max(0, Number(state.tipUsd) || 0);+ const tipBoost = tipUsd > 0 ? clamp(Math.log10(tipUsd + 1) / 4, 0, 0.2) : 0;+ const confidence = clamp(tier.index / 5 * 0.5 + repScore * 0.2 + forkBoost + tipBoost, 0, 1);// Emissive/material rim steps every two tiers → 0,0,1,1,2,2.const materialTier = Math.floor(tier.index / 2);@@ -140,6 +149,34 @@ export function computeMarks(state = {}, { hubUrl = null } = {}) {href: hubUrl,});}+ // Lifetime tips received — a real trust signal. Counts come from confirmed+ // on-chain tip rows (agent_custody_events, event_type='tip'); the mark+ // deep-links to the wallet hub where each tip is itemised in the activity trail.+ const tipCount = Math.max(0, Number(state.tipCount) || 0);+ const tipUsd = Math.max(0, Number(state.tipUsd) || 0);+ if (tipCount > 0) {+ marks.push({+ key: 'tips',+ label: tipUsd > 0 ? `Tipped ${fmtUsd(tipUsd)}` : (tipCount === 1 ? 'Tipped once' : `Tipped ${tipCount}×`),+ value: tipUsd > 0 ? fmtUsd(tipUsd) : tipCount,+ detail: `${tipCount} lifetime tip${tipCount === 1 ? '' : 's'}${tipUsd > 0 ? ` worth ${fmtUsd(tipUsd)}` : ''}`,+ href: hubUrl,+ });+ }+ // Realized trading P&L — only surfaced when net-positive, so the mark reads as+ // an earned badge, never a scarlet letter. From closed sniper positions+ // (agent_sniper_positions.realized_pnl_lamports), a real on-chain settlement.+ const realizedPnlSol = Number(state.realizedPnlSol) || 0;+ if (realizedPnlSol > 0.0001) {+ const wins = Math.max(0, Number(state.realizedWins) || 0);+ marks.push({+ key: 'pnl',+ label: `+${realizedPnlSol.toFixed(realizedPnlSol < 1 ? 3 : 2)} SOL P&L`,+ value: `+${realizedPnlSol.toFixed(realizedPnlSol < 1 ? 3 : 2)}`,+ detail: `Realized +${realizedPnlSol.toFixed(3)} SOL across ${wins} closed trade${wins === 1 ? '' : 's'}`,+ href: hubUrl,+ });+ }const attesters = Math.max(0, Number(state.attesters) || 0);if (attesters > 0) {marks.push({diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 65087dd63..9db48ec76 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -563,6 +563,12 @@ export const limits = {walletLink: (userId) => getLimiter('wallet:link', { limit: 10, window: '10 m' }).limit(userId),// Agent wallet read endpoints (GET balance, activity). Per authenticated user.walletRead: (userId) => getLimiter('wallet:read', { limit: 60, window: '1 m' }).limit(userId),+ // Public cross-origin wallet embed card (GET /api/agents/wallet-embed). Served+ // CORS:* so a stranger's blog can mount the wallet chip — keyed per IP and+ // generous (a page with several embeds hydrates them all on load) but bounded+ // so the open endpoint can't be turned into a free balance-scraping relay. Reads+ // are short-TTL cached, so this only gates cache-miss origin hits.+ walletEmbedIp: (ip) => getLimiter('wallet:embed:ip', { limit: 120, window: '1 m' }).limit(ip),agentSuggest: (ip) => getLimiter('agents:suggest', { limit: 120, window: '1 m' }).limit(ip),// On-chain agent registration (register_agent MCP tool). Each call may mint a// Core asset + Agent Identity PDA — real SOL spend — so this is deliberatelydiff --git a/api/_lib/trust/wallet-reputation.js b/api/_lib/trust/wallet-reputation.jsnew file mode 100644index 000000000..ac9da25fc--- /dev/null+++ b/api/_lib/trust/wallet-reputation.js@@ -0,0 +1,547 @@+// Wallet Reputation — a real, non-gameable trust score for an agent's wallet.+//+// In a world of infinite forkable avatars, trust is the scarce asset. A wallet's+// real history — how much it has earned, how long it has been active, how+// reliably it settles, how many distinct funded wallets tipped it, how often it+// was forked, whether it carries a verified on-chain identity — is the most+// honest reputation signal three.ws has. This module turns those real, already-+// settled facts into ONE explainable 0–100 score.+//+// Design principles (read before touching the weights):+//+// 1. Every input is a real, verifiable fact pulled from the ledger+// (agent_custody_events), the on-chain payment index (pump_agent_*), signed+// Solana attestations, the EVM ERC-8004 reputation registry, fork lineage+// (avatars.parent_avatar_id), and the agent's own age. No invented numbers.+//+// 2. Costly, provable signals outweigh cheap ones. Real USD volume, wallet age,+// on-chain verification, and tips from DISTINCT funded wallets are weighted+// heavily; anything a single actor can manufacture for free (self-tips, a+// pile of payments from one wallet) is discounted or ignored in the+// computation — not flagged after the fact.+//+// 3. The formula is fully explainable. computeReputation() is a pure function+// that returns, for every pillar, the raw inputs, the points awarded, the+// max, and human-readable detail. The UI renders that breakdown verbatim:+// transparency is the trust.+//+// 4. A brand-new agent reads honestly as "new" — near-zero score, `new` tier —+// never a fake high or a fake low. Time and money are the two things you+// cannot fast-forward.+//+// The pillars and their maxima sum to 100:+//+// tenure 15 wallet/agent age (log-scaled) + recent activity cadence+// volume 25 real settled USD that flowed through the wallet (earnings + tips)+// tips 15 count of DISTINCT external funded wallets that tipped it+// reliability 15 on-chain settlement success rate (only once there's volume)+// lineage 10 how many times the avatar was forked (others valued it)+// identity 20 verified ERC-8004 identity + registry feedback + attestations+//+// computeReputation is pure and unit-tested (tests/wallet-reputation.test.js).+// loadReputationInputs / getAgentReputation do the real I/O.++import { sql } from '../db.js';+import { loadAgentReputation } from './solana-bouncer.js';++export const REPUTATION_VERSION = 1;++// Pillar definitions — label + max points. Order is the display order.+export const PILLARS = [+ { key: 'tenure', label: 'Tenure & consistency', max: 15 },+ { key: 'volume', label: 'Earnings & volume', max: 25 },+ { key: 'tips', label: 'Tips from distinct wallets', max: 15 },+ { key: 'reliability', label: 'Payment reliability', max: 15 },+ { key: 'lineage', label: 'Fork lineage', max: 10 },+ { key: 'identity', label: 'On-chain identity', max: 20 },+];++export const MAX_SCORE = PILLARS.reduce((s, p) => s + p.max, 0); // 100++// Tier ladder. Tiers reflect REAL thresholds, not just the raw score — `trusted`+// and above additionally require genuine counterparty diversity so age + identity+// alone can never manufacture trust.+export const TIERS = {+ new: { label: 'New', rank: 0, accent: '#9ca3af' },+ emerging: { label: 'Emerging', rank: 1, accent: '#c4b5fd' },+ established: { label: 'Established', rank: 2, accent: '#a78bfa' },+ trusted: { label: 'Trusted', rank: 3, accent: '#4ade80' },+ elite: { label: 'Elite', rank: 4, accent: '#fbbf24' },+};++const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));+const round1 = (n) => Math.round(n * 10) / 10;+const log2 = (n) => Math.log(n) / Math.LN2;++/**+ * Pure scoring function. Takes a fully-resolved, real `inputs` object (no I/O)+ * and returns an explainable reputation result. Kept pure so the formula is+ * unit-testable and identical on server and (if ever) client.+ *+ * @param {object} inputs+ * @param {number} inputs.ageDays agent/wallet age in days+ * @param {number} inputs.activeDays90 distinct days with ledger activity in last 90d+ * @param {number} inputs.externalTipUsd real USD tipped by NON-self wallets+ * @param {number} inputs.settledUsd real USD that settled through the wallet (earnings)+ * @param {number} inputs.tipCount total recorded tips+ * @param {number} inputs.distinctTippers distinct EXTERNAL funded tipper wallets+ * @param {number} inputs.selfTipCount tips whose sender == the wallet itself (ignored)+ * @param {number} inputs.confirmedPayments confirmed on-chain payments accepted+ * @param {number} inputs.failedPayments failed on-chain payments+ * @param {number} inputs.distinctPayers distinct confirmed payers+ * @param {number} inputs.distributionSuccess success rate of distribute/buyback runs (0..1)+ * @param {number} inputs.forkCount times this avatar was forked+ * @param {boolean} inputs.hasOnchainIdentity verified ERC-8004 identity present+ * @param {number} inputs.registryAverage ERC-8004 reputation registry average (0..5 or 0..100)+ * @param {number} inputs.registryCount ERC-8004 registry feedback count+ * @param {number} inputs.validationCount signed Solana validation attestations+ * @param {number} inputs.feedbackCount signed Solana feedback attestations+ * @param {boolean} inputs.hasSkillCollection on-chain skill-license collection minted+ * @returns {object} { version, score, tier, tierLabel, accent, isNew, pillars, discounted, totals }+ */+export function computeReputation(inputs = {}) {+ const i = normalizeInputs(inputs);+ const pillars = [];+ const discounted = [];++ // Counterparty concentration — the core anti-gaming guard. Real trust comes+ // from MANY distinct funded wallets choosing to pay/tip. If volume is high but+ // it all came from a single counterparty (a classic wash / self-deal pattern),+ // the money-weighted pillars are heavily discounted: that volume is not+ // evidence the wider world trusts this agent.+ const tipDiversity = i.distinctTippers;+ const concentrated = i.tipCount > 1 && tipDiversity <= 1;+ const diversityMultiplier = concentrated ? 0.35 : 1;++ // ── Tenure & consistency (max 15) ──────────────────────────────────────────+ // Age is the single most non-gameable signal: you cannot fast-forward time.+ const agePts = clamp(3.4 * Math.log10(i.ageDays + 1), 0, 10);+ const consistencyPts = clamp((i.activeDays90 / 30) * 5, 0, 5);+ pushPillar(pillars, 'tenure', agePts + consistencyPts, {+ detail:+ i.ageDays < 1+ ? 'Brand-new wallet — no track record yet.'+ : `${fmtAge(i.ageDays)} old · active ${i.activeDays90} of the last 90 days.`,+ facts: { age_days: Math.round(i.ageDays), active_days_90: i.activeDays90 },+ });++ // ── Earnings & volume (max 25) ─────────────────────────────────────────────+ // Real USD that flowed through the wallet. Money moved is costly to fake.+ const rawVolume = i.settledUsd + i.externalTipUsd;+ const volumePtsRaw = clamp(6.5 * Math.log10(rawVolume + 1), 0, 25);+ const volumePts = volumePtsRaw * diversityMultiplier;+ pushPillar(pillars, 'volume', volumePts, {+ detail:+ rawVolume <= 0+ ? 'No settled volume yet.'+ : `$${fmtUsd(rawVolume)} in real settled volume${concentrated ? ' (discounted — single counterparty)' : ''}.`,+ facts: { settled_usd: round1(i.settledUsd), tip_usd: round1(i.externalTipUsd) },+ });++ // ── Tips from distinct wallets (max 15) ────────────────────────────────────+ // Each DISTINCT funded tipper is a real Sybil cost. Self-tips are excluded+ // entirely from the count below.+ const tipsPtsRaw = clamp(5 * log2(tipDiversity + 1), 0, 15);+ const tipsPts = tipsPtsRaw * diversityMultiplier;+ pushPillar(pillars, 'tips', tipsPts, {+ detail:+ tipDiversity === 0+ ? 'No tips from external wallets yet.'+ : `${tipDiversity} distinct funded wallet${tipDiversity === 1 ? '' : 's'} tipped this agent.`,+ facts: { distinct_tippers: tipDiversity, total_tips: i.tipCount },+ });++ // ── Payment reliability (max 15) ───────────────────────────────────────────+ // Only meaningful once there's real settlement volume. A new agent honestly+ // scores 0 here (no history) rather than an unearned full mark.+ const settled = i.confirmedPayments + i.failedPayments;+ let reliabilityPts = 0;+ let reliabilityDetail = 'No settled payments yet — reliability is unproven.';+ if (settled >= 5) {+ const successRate = i.confirmedPayments / settled;+ reliabilityPts = successRate * 12 + clamp(i.distributionSuccess * 3, 0, 3);+ reliabilityDetail = `${(successRate * 100).toFixed(0)}% of ${settled} settlements succeeded${+ i.distributionSuccess > 0 ? `, ${(i.distributionSuccess * 100).toFixed(0)}% distribution success` : ''+ }.`;+ }+ pushPillar(pillars, 'reliability', reliabilityPts, {+ detail: reliabilityDetail,+ facts: { confirmed_payments: i.confirmedPayments, failed_payments: i.failedPayments },+ });++ // ── Fork lineage (max 10) ──────────────────────────────────────────────────+ // Being forked a lot is a real, costly-to-fake signal that others valued this+ // agent enough to copy it.+ const lineagePts = clamp(3.3 * log2(i.forkCount + 1), 0, 10);+ pushPillar(pillars, 'lineage', lineagePts, {+ detail:+ i.forkCount === 0+ ? 'Not forked yet.'+ : `Forked ${i.forkCount} time${i.forkCount === 1 ? '' : 's'} by other creators.`,+ facts: { fork_count: i.forkCount },+ });++ // ── On-chain identity & verification (max 20) ──────────────────────────────+ let identityPts = 0;+ const idBits = [];+ if (i.hasOnchainIdentity) {+ identityPts += 8;+ idBits.push('verified ERC-8004 identity');+ }+ if (i.registryCount > 0) {+ // Registry average may arrive on a 0–5 star scale or a 0–100 scale.+ const norm = i.registryAverage > 5 ? i.registryAverage / 100 : i.registryAverage / 5;+ const regPts = clamp(norm * 4 + clamp(log2(i.registryCount + 1), 0, 2), 0, 6);+ identityPts += regPts;+ idBits.push(`${i.registryCount} on-chain review${i.registryCount === 1 ? '' : 's'}`);+ }+ const attPts = clamp(i.validationCount * 2 + i.feedbackCount * 0.5, 0, 4);+ if (attPts > 0) {+ identityPts += attPts;+ idBits.push(`${i.validationCount + i.feedbackCount} signed attestation${i.validationCount + i.feedbackCount === 1 ? '' : 's'}`);+ }+ if (i.hasSkillCollection) {+ identityPts += 2;+ idBits.push('on-chain skill licenses');+ }+ identityPts = clamp(identityPts, 0, 20);+ pushPillar(pillars, 'identity', identityPts, {+ detail: idBits.length ? `Carries ${idBits.join(', ')}.` : 'No on-chain identity or attestations yet.',+ facts: { verified: i.hasOnchainIdentity, registry_count: i.registryCount, attestations: i.validationCount + i.feedbackCount },+ });++ // ── Anti-gaming transparency ───────────────────────────────────────────────+ // Surface what did NOT count so the score reads as credible.+ if (i.selfTipCount > 0) {+ discounted.push({+ kind: 'self_tips',+ label: `${i.selfTipCount} self-tip${i.selfTipCount === 1 ? '' : 's'} ignored`,+ detail: 'Tips sent from the wallet to itself carry no trust and are excluded from the score.',+ });+ }+ if (concentrated) {+ discounted.push({+ kind: 'concentration',+ label: 'Single-counterparty volume discounted',+ detail:+ 'Most volume came from one wallet. Trust requires many distinct funded counterparties, so this volume is weighted down.',+ });+ }++ const score = round1(clamp(pillars.reduce((s, p) => s + p.points, 0), 0, MAX_SCORE));++ // Real activity floor for the "new" verdict — independent of the raw score,+ // which is never exactly 0 once an agent has any age.+ const realActivity =+ i.tipCount ++ i.confirmedPayments ++ i.forkCount ++ i.validationCount ++ i.feedbackCount ++ i.registryCount ++ (i.hasOnchainIdentity ? 1 : 0) ++ (rawVolume > 0 ? 1 : 0);+ const isNew = realActivity === 0;++ const tier = tierFor({ score, isNew, distinctTippers: tipDiversity, confirmedPayments: i.confirmedPayments });++ return {+ version: REPUTATION_VERSION,+ score,+ max: MAX_SCORE,+ tier,+ tierLabel: TIERS[tier].label,+ accent: TIERS[tier].accent,+ isNew,+ pillars,+ discounted,+ totals: {+ settled_usd: round1(rawVolume),+ distinct_tippers: tipDiversity,+ confirmed_payments: i.confirmedPayments,+ fork_count: i.forkCount,+ verified: i.hasOnchainIdentity,+ },+ };+}++/**+ * Tier from the real score + real counterparty thresholds. `trusted`/`elite`+ * require genuine counterparty diversity (≥3 distinct tippers OR ≥10 confirmed+ * payments) so that score earned purely from age + identity can never be sold as+ * peer trust.+ */+export function tierFor({ score, isNew, distinctTippers = 0, confirmedPayments = 0 }) {+ if (isNew) return 'new';+ const hasPeerTrust = distinctTippers >= 3 || confirmedPayments >= 10;+ if (score >= 75 && hasPeerTrust) return 'elite';+ if (score >= 55 && hasPeerTrust) return 'trusted';+ if (score >= 30) return 'established';+ return 'emerging';+}++function pushPillar(arr, key, points, extra) {+ const def = PILLARS.find((p) => p.key === key);+ arr.push({+ key,+ label: def.label,+ points: round1(clamp(points, 0, def.max)),+ max: def.max,+ ...extra,+ });+}++function normalizeInputs(raw) {+ const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);+ return {+ ageDays: Math.max(0, num(raw.ageDays)),+ activeDays90: Math.max(0, num(raw.activeDays90)),+ externalTipUsd: Math.max(0, num(raw.externalTipUsd)),+ settledUsd: Math.max(0, num(raw.settledUsd)),+ tipCount: Math.max(0, num(raw.tipCount)),+ distinctTippers: Math.max(0, num(raw.distinctTippers)),+ selfTipCount: Math.max(0, num(raw.selfTipCount)),+ confirmedPayments: Math.max(0, num(raw.confirmedPayments)),+ failedPayments: Math.max(0, num(raw.failedPayments)),+ distinctPayers: Math.max(0, num(raw.distinctPayers)),+ distributionSuccess: clamp(num(raw.distributionSuccess), 0, 1),+ forkCount: Math.max(0, num(raw.forkCount)),+ hasOnchainIdentity: Boolean(raw.hasOnchainIdentity),+ registryAverage: Math.max(0, num(raw.registryAverage)),+ registryCount: Math.max(0, num(raw.registryCount)),+ validationCount: Math.max(0, num(raw.validationCount)),+ feedbackCount: Math.max(0, num(raw.feedbackCount)),+ hasSkillCollection: Boolean(raw.hasSkillCollection),+ };+}++function fmtAge(days) {+ if (days >= 365) return `${(days / 365).toFixed(1)}y`;+ if (days >= 30) return `${Math.round(days / 30)}mo`;+ if (days >= 1) return `${Math.round(days)}d`;+ return '<1d';+}+function fmtUsd(n) {+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;+ return n.toFixed(n < 10 ? 2 : 0);+}++// ── Real I/O ────────────────────────────────────────────────────────────────++/**+ * Gather every REAL reputation input for an agent from the ledger, the on-chain+ * payment index, fork lineage, attestations, and (best-effort) the EVM ERC-8004+ * reputation registry. Never fabricates: a source that errors degrades to its+ * zero/neutral value and is reflected as `partial` by the caller.+ *+ * @param {string} agentId+ * @param {object} [opts]+ * @param {boolean} [opts.lite=false] Skip the best-effort EVM ERC-8004 registry+ * RPC read — used for batch list rendering where dozens of agents are+ * scored at once. The registry contributes ≤6 of 100 and the full+ * per-agent endpoint always includes it, so a lite score stays honest.+ * @returns {Promise<{ inputs: object, agent: object, evidence: object, partial: boolean }>}+ */+export async function loadReputationInputs(agentId, opts = {}) {+ const lite = opts.lite === true;+ let partial = false;+ const soft = async (p, fallback) => {+ try {+ return await p;+ } catch {+ partial = true;+ return fallback;+ }+ };++ const [agent] = await sql`+ select+ id, name, created_at, avatar_id, chain_id, erc8004_agent_id,+ skill_collection_mint,+ meta->>'solana_address' as solana_address,+ wallet_address+ from agent_identities+ where id = ${agentId} and deleted_at is null+ limit 1+ `;+ if (!agent) {+ const err = new Error('agent not found');+ err.status = 404;+ err.code = 'not_found';+ throw err;+ }++ const ownWallet = agent.solana_address || '__none__';+ const ageDays = agent.created_at ? (Date.now() - new Date(agent.created_at).getTime()) / 86_400_000 : 0;++ // Ledger: tips, volume, cadence — all from agent_custody_events.+ const [ledger] = await soft(+ sql`+ select+ count(*) filter (where event_type = 'tip' and status in ('confirmed','ok'))::int+ as tip_count,+ count(distinct case+ when event_type = 'tip' and status in ('confirmed','ok')+ and meta->>'from' is not null and meta->>'from' <> ${ownWallet}+ then meta->>'from' end)::int+ as distinct_tippers,+ count(*) filter (+ where event_type = 'tip' and meta->>'from' = ${ownWallet}+ )::int as self_tip_count,+ coalesce(sum(case+ when event_type = 'tip' and status in ('confirmed','ok')+ and (meta->>'from') is distinct from ${ownWallet}+ then usd else 0 end), 0)::float8 as external_tip_usd,+ coalesce(sum(case+ when status in ('confirmed','ok') and usd is not null then usd else 0 end), 0)::float8+ as settled_usd,+ count(distinct date_trunc('day', created_at)) filter (+ where created_at >= now() - interval '90 days'+ )::int as active_days_90+ from agent_custody_events+ where agent_id = ${agentId}+ `,+ [{}],+ );++ // Fork lineage: how many avatars were forked from this agent's avatar.+ const [forks] = agent.avatar_id+ ? await soft(+ sql`+ select count(*)::int as fork_count+ from avatars+ where parent_avatar_id = ${agent.avatar_id} and deleted_at is null+ `,+ [{ fork_count: 0 }],+ )+ : [{ fork_count: 0 }];++ // On-chain payment / distribution / attestation record (already-real index).+ const solRep = await soft(loadAgentReputation(agentId), null);++ // Best-effort EVM ERC-8004 reputation registry read (skipped in lite mode).+ const registry = lite+ ? { average: 0, count: 0 }+ : await soft(readErc8004Registry(agent), { average: 0, count: 0 });++ const inputs = {+ ageDays,+ activeDays90: ledger?.active_days_90 || 0,+ externalTipUsd: ledger?.external_tip_usd || 0,+ settledUsd: ledger?.settled_usd || 0,+ tipCount: ledger?.tip_count || 0,+ distinctTippers: ledger?.distinct_tippers || 0,+ selfTipCount: ledger?.self_tip_count || 0,+ confirmedPayments: solRep?.payments?.confirmed_count || 0,+ failedPayments: solRep?.payments?.failed_count || 0,+ distinctPayers: solRep?.payments?.distinct_payers || 0,+ distributionSuccess: solRep?.distributions?.success_rate || 0,+ forkCount: forks?.fork_count || 0,+ hasOnchainIdentity: Boolean(agent.erc8004_agent_id),+ registryAverage: registry?.average || 0,+ registryCount: registry?.count || 0,+ validationCount: solRep?.attestations?.validation_count || 0,+ feedbackCount: solRep?.attestations?.feedback_count || 0,+ hasSkillCollection: Boolean(agent.skill_collection_mint),+ };++ const evidence = buildEvidence(agent, { solRep, registry });+ return { inputs, agent, evidence, partial };+}++/**+ * Full reputation result for one agent: real inputs → pure score → evidence ++ * owner guidance. This is what the HTTP endpoint and discovery ranking call.+ */+export async function getAgentReputation(agentId, opts = {}) {+ const { inputs, agent, evidence, partial } = await loadReputationInputs(agentId, opts);+ const result = computeReputation(inputs);+ return {+ agent_id: agent.id,+ name: agent.name,+ ...result,+ evidence,+ guidance: buildGuidance(result, inputs, agent),+ partial,+ computed_at: new Date().toISOString(),+ };+}++async function readErc8004Registry(agent) {+ if (!agent.erc8004_agent_id || !agent.chain_id) return { average: 0, count: 0 };+ const RPC = {+ 1: 'https://eth.llamarpc.com',+ 10: 'https://optimism.llamarpc.com',+ 8453: 'https://base.llamarpc.com',+ 42161: 'https://arbitrum.llamarpc.com',+ 137: 'https://polygon.llamarpc.com',+ };+ const rpcUrl = RPC[agent.chain_id];+ if (!rpcUrl) return { average: 0, count: 0 };+ const { JsonRpcProvider, Contract } = await import('ethers');+ const { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI } = await import('../../../src/erc8004/abi.js');+ const deployment = REGISTRY_DEPLOYMENTS[agent.chain_id];+ if (!deployment?.reputationRegistry) return { average: 0, count: 0 };+ const provider = new JsonRpcProvider(rpcUrl, agent.chain_id, { staticNetwork: true });+ const contract = new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider);+ const [avgX100, count] = await contract.getReputation(BigInt(agent.erc8004_agent_id));+ const n = Number(count);+ return { average: n === 0 ? 0 : Number(avgX100) / 100, count: n };+}++function buildEvidence(agent, { solRep, registry }) {+ const ev = {};+ if (agent.solana_address) {+ ev.wallet = {+ label: 'Wallet activity',+ href: `https://solscan.io/account/${agent.solana_address}`,+ };+ ev.ledger = { label: 'Custody ledger', href: `/agent/${agent.id}/wallet` };+ }+ if (agent.avatar_id) {+ ev.lineage = { label: 'Fork lineage', href: `/avatars/${agent.avatar_id}` };+ }+ if (agent.erc8004_agent_id) {+ ev.identity = { label: 'On-chain identity', href: `/agent/${agent.id}/onchain` };+ }+ if (registry?.count > 0) {+ ev.registry = { label: 'On-chain reviews', href: '/reputation' };+ }+ const mint = solRep?.mints?.[0]?.mint;+ if (mint) {+ ev.mint = { label: 'Launched coin', href: `https://solscan.io/token/${mint}` };+ }+ return ev;+}++// Owner-facing, actionable guidance tied to real available actions. Visitors do+// not see this — only the owner can act on it.+function buildGuidance(result, inputs, agent) {+ const tips = [];+ if (!inputs.hasOnchainIdentity) {+ tips.push({+ action: 'verify_identity',+ label: 'Verify your on-chain identity',+ detail: 'Register an ERC-8004 identity to add up to 8 points of provable trust.',+ href: `/agent/${agent.id}/onchain`,+ });+ }+ if (inputs.distinctTippers < 3) {+ tips.push({+ action: 'grow_tips',+ label: 'Earn tips from real wallets',+ detail: 'Trust grows fastest from many distinct funded wallets choosing to tip you.',+ href: `/agent/${agent.id}/wallet`,+ });+ }+ if (inputs.confirmedPayments < 10) {+ tips.push({+ action: 'transact',+ label: 'Build a settlement history',+ detail: 'Reliable, confirmed on-chain payments raise your reliability score over time.',+ href: `/agent/${agent.id}/wallet`,+ });+ }+ return tips.slice(0, 3);+}diff --git a/api/agents/_id/reputation.js b/api/agents/_id/reputation.jsindex 20c6b488d..b54df4045 100644--- a/api/agents/_id/reputation.js+++ b/api/agents/_id/reputation.js@@ -1,90 +1,82 @@-import { sql } from '../../_lib/db.js';+// GET /api/agents/:id/reputation+//+// The agent's unified wallet trust score — a real, non-gameable 0–100 credibility+// signal derived entirely from real ledger + on-chain activity. The score, its+// per-pillar breakdown, the evidence links, and (for the owner) actionable+// guidance are computed by api/_lib/trust/wallet-reputation.js. Public read: the+// score is a trust signal others rely on, so owner and visitor see the same+// number; only the owner additionally receives the `guidance` block.+import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { getRedis } from '../../_lib/redis.js';--const CACHE_TTL_S = 300; // 5 minutes--// Minimal public RPC map-const RPC = {- 1: 'https://eth.llamarpc.com',- 10: 'https://optimism.llamarpc.com',- 8453: 'https://base.llamarpc.com',- 42161: 'https://arbitrum.llamarpc.com',- 137: 'https://polygon.llamarpc.com',- 11155111: 'https://ethereum-sepolia.publicnode.com',- 84532: 'https://base-sepolia.publicnode.com',-};+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { sql } from '../../_lib/db.js';+import { getAgentReputation } from '../../_lib/trust/wallet-reputation.js';++const CACHE_TTL_S = 180; // 3 minutes — score is derived, not real-time critical.++async function resolveUserId(req) {+ try {+ const session = await getSessionUser(req);+ if (session) return session.id;+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return bearer.userId;+ } catch {+ /* anonymous */+ }+ return null;+}export const handleReputation = wrap(async (req, res, agentId) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const [agent] = await sql`- SELECT erc8004_agent_id, chain_id- FROM agent_identities- WHERE id = ${agentId} AND deleted_at IS NULL- LIMIT 1- `;- if (!agent) return error(res, 404, 'not_found', 'agent not found');-- const url = new URL(req.url, 'http://x');- const chainId = Number(url.searchParams.get('chain_id')) || agent.chain_id;-- if (!chainId || !agent.erc8004_agent_id) {- return json(res, 200, { average: 0, count: 0, total_stake_wei: '0', chain_id: chainId });- }-- const cacheKey = `rep:${agentId}:${chainId}`;+ const cacheKey = `walletrep:v1:${agentId}`;const redis = await getRedis();+ let result = null;if (redis) {try {const cached = await redis.get(cacheKey);if (cached) {+ result = cached;res.setHeader('X-Cache', 'HIT');- return json(res, 200, cached);}- } catch { /* cache miss */ }+ } catch {+ /* cache miss */+ }}- const rpcUrl = RPC[chainId];- if (!rpcUrl) {- return json(res, 200, { average: 0, count: 0, total_stake_wei: '0', chain_id: chainId });+ if (!result) {+ try {+ result = await getAgentReputation(agentId);+ } catch (err) {+ if (err.status === 404) return error(res, 404, 'not_found', 'agent not found');+ throw err;+ }+ // Only cache a complete result — never persist a degraded/partial score.+ if (redis && !result.partial) {+ redis.set(cacheKey, result, { ex: CACHE_TTL_S }).catch(() => {});+ }+ res.setHeader('X-Cache', 'MISS');}- const { JsonRpcProvider, Contract } = await import('ethers');- const { REGISTRY_DEPLOYMENTS, REPUTATION_REGISTRY_ABI } = await import('../../../src/erc8004/abi.js');-- const deployment = REGISTRY_DEPLOYMENTS[chainId];- if (!deployment?.reputationRegistry) {- return json(res, 200, { average: 0, count: 0, total_stake_wei: '0', chain_id: chainId });+ // Owner-only guidance: strip it for everyone else.+ const userId = await resolveUserId(req);+ let isOwner = false;+ if (userId) {+ const [own] = await sql`+ select 1 from agent_identities where id = ${agentId} and user_id = ${userId} and deleted_at is null limit 1+ `.catch(() => []);+ isOwner = Boolean(own);}- const provider = new JsonRpcProvider(rpcUrl, chainId, { staticNetwork: true });- const contract = new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider);-- const erc8004Id = BigInt(agent.erc8004_agent_id);- const [[avgX100, count], totalStakeWei] = await Promise.all([- contract.getReputation(erc8004Id),- contract.getTotalStake(erc8004Id).catch(() => 0n),- ]);-- const n = Number(count);- const result = {- average: n === 0 ? 0 : Number(avgX100) / 100,- count: n,- total_stake_wei: totalStakeWei.toString(),- chain_id: chainId,- };-- if (redis) {- redis.set(cacheKey, result, { ex: CACHE_TTL_S }).catch(() => {});- }+ const payload = { ...result, is_owner: isOwner };+ if (!isOwner) delete payload.guidance;- res.setHeader('X-Cache', 'MISS');- return json(res, 200, result);+ return json(res, 200, payload, { 'cache-control': 'public, max-age=60, stale-while-revalidate=300' });});diff --git a/api/agents/reputation-batch.js b/api/agents/reputation-batch.jsnew file mode 100644index 000000000..75b5b9b08--- /dev/null+++ b/api/agents/reputation-batch.js@@ -0,0 +1,87 @@+// GET|POST /api/agents/reputation-batch?ids=a,b,c+//+// Compact wallet-trust scores for a list of agents, so discovery surfaces+// (trending, marketplace cards, the galaxy) can render a reputation badge on+// every agent without N round-trips. Returns only the public, list-relevant+// fields per agent — never the owner-only guidance block. Each score is the same+// real computation as the per-agent endpoint, in `lite` mode (skips the optional+// EVM registry RPC) so a page of cards stays fast while every number stays real.++import { cors, json, error, method, wrap, rateLimited, readBody } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getRedis } from '../_lib/redis.js';+import { getAgentReputation } from '../_lib/trust/wallet-reputation.js';++const MAX_IDS = 60;+const CACHE_TTL_S = 180;++function compact(rep) {+ return {+ agent_id: rep.agent_id,+ score: rep.score,+ max: rep.max,+ tier: rep.tier,+ tierLabel: rep.tierLabel,+ accent: rep.accent,+ isNew: rep.isNew,+ totals: rep.totals,+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let ids = [];+ if (req.method === 'POST') {+ const body = await readBody(req, 8192).catch(() => null);+ let parsed = null;+ try {+ parsed = body ? JSON.parse(body) : null;+ } catch {+ return error(res, 400, 'validation_error', 'invalid JSON body');+ }+ ids = Array.isArray(parsed?.ids) ? parsed.ids : [];+ } else {+ const url = new URL(req.url, 'http://x');+ ids = (url.searchParams.get('ids') || '').split(',');+ }++ ids = [...new Set(ids.map((s) => String(s || '').trim()).filter(Boolean))].slice(0, MAX_IDS);+ if (!ids.length) return json(res, 200, { data: {} });++ const redis = await getRedis();++ const settled = await Promise.allSettled(+ ids.map(async (id) => {+ const cacheKey = `walletrep:lite:v1:${id}`;+ if (redis) {+ try {+ const cached = await redis.get(cacheKey);+ if (cached) return [id, cached];+ } catch {+ /* miss */+ }+ }+ const rep = await getAgentReputation(id, { lite: true });+ const small = compact(rep);+ if (redis && !rep.partial) {+ redis.set(cacheKey, small, { ex: CACHE_TTL_S }).catch(() => {});+ }+ return [id, small];+ }),+ );++ const data = {};+ for (const r of settled) {+ if (r.status === 'fulfilled' && r.value) {+ const [id, val] = r.value;+ data[id] = val;+ }+ }++ return json(res, 200, { data }, { 'cache-control': 'public, max-age=60, stale-while-revalidate=300' });+});diff --git a/api/agents/solana-intent.js b/api/agents/solana-intent.jsnew file mode 100644index 000000000..f2f2b7135--- /dev/null+++ b/api/agents/solana-intent.js@@ -0,0 +1,415 @@+// /api/agents/:id/solana/intent — the Conversational Wallet's parser.+//+// POST /api/agents/:id/solana/intent { utterance, history?, network?, context? }+//+// Turns a natural-language instruction ("tip 0.1 SOL to vault.sol", "snipe that+// mint with half a SOL", "withdraw 2 SOL to my Phantom") into a STRICT, validated+// intent object via Claude tool use — never free-text-to-transaction. This handler+// ONLY parses and grounds the intent; it never signs, quotes, or moves funds. The+// client takes the returned intent, previews it through the real task-05 trade /+// withdraw engine, shows an explicit read-back, and on the owner's confirm calls+// those owner-only, CSRF-protected, spend-policy-gated, audited endpoints.+//+// Owner-only by construction: a visitor (or logged-out caller) gets a 403 here, and+// even if they fabricated an intent the execution endpoints reject them server-side.+// The LLM has no privileged route around the spend guard — it produces structured+// text, nothing more.+//+// $THREE is the only coin three.ws promotes. The parser resolves "$THREE"/"three"+// to its canonical mint; any other mint is runtime data the owner supplied+// (a snipe target), never hardcoded or recommended.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { loadUserProviderKeys } from '../_lib/provider-keys.js';+import { resolveSolanaRecipient } from '../../src/solana/sns.js';+import { THREE_MINT } from '../_lib/networth-model.js';+import { getSpendLimits, getTradeLimits } from '../_lib/agent-trade-guards.js';++const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';+const ANTHROPIC_MODEL = 'claude-opus-4-8';+const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';+// GPT-OSS 120B exposes OpenAI-style tool calling on OpenRouter — the free-tier+// fallback when the Anthropic key is absent so voice trading still parses.+const OPENROUTER_MODEL = 'openai/gpt-oss-120b';+const CALL_TIMEOUT_MS = 15_000;+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const ACTIONS = ['buy', 'swap', 'snipe', 'sell', 'tip', 'withdraw', 'none', 'clarify'];+const UNITS = ['SOL', 'USDC', 'USD', 'token', 'percent', 'max'];++// The single tool Claude must call. We force the call (tool_choice) and validate+// the result server-side, so a missing/odd field degrades to a clarify, never a+// bad transaction.+const INTENT_TOOL = {+ name: 'record_wallet_intent',+ description:+ 'Record the single wallet action the owner asked their agent to take, as a strict structured intent. ' ++ 'Map the latest message to exactly one action. NEVER guess an amount or a destination — if either is ' ++ 'missing or ambiguous, set action to "clarify" and put a short, in-character question in ' ++ 'clarifying_question. The only coin the platform promotes is $THREE; treat "$THREE"/"three" as that ' ++ 'coin. A mint the user names for a snipe/buy is their own runtime input.',+ input_schema: {+ type: 'object',+ properties: {+ action: {+ type: 'string',+ enum: ACTIONS,+ description:+ 'buy/swap: spend SOL to buy a token. snipe: buy a freshly-launched mint. sell: sell a held ' ++ 'token for SOL. tip: send SOL/USDC to someone as a tip. withdraw: move SOL/token to an ' ++ 'address the owner controls. none: not a wallet command. clarify: need more info.',+ },+ amount: {+ type: 'number',+ description: 'The numeric amount the user named (e.g. 0.1, 2, 50). Omit if they named none.',+ },+ amount_unit: {+ type: 'string',+ enum: UNITS,+ description:+ 'SOL/USDC/USD = a currency amount; percent = a share (e.g. "half" → 50); max = all of it; ' ++ 'token = a raw token count for a sell.',+ },+ asset: {+ type: 'string',+ description:+ 'The asset being spent or sold: "SOL", "USDC", "$THREE", a token symbol, or a base58 mint.',+ },+ destination_or_mint: {+ type: 'string',+ description:+ 'For withdraw/tip: the recipient address or .sol name. For buy/swap/snipe: the mint or ' ++ 'symbol to acquire ("$THREE" or a base58 mint).',+ },+ slippage_pct: { type: 'number', description: 'Slippage tolerance percent if the user stated one.' },+ confidence: { type: 'number', description: 'Your confidence 0..1 that this parse is correct.' },+ clarifying_question: {+ type: 'string',+ description: 'When action is "clarify", the single in-character question to ask the owner.',+ },+ readback: {+ type: 'string',+ description:+ 'One plain-language sentence stating exactly what will happen, e.g. ' ++ '"Withdraw 2 SOL to 7xKX…Ab12." Phrase it for the owner to confirm aloud.',+ },+ },+ required: ['action', 'confidence', 'readback'],+ },+};++const OPENAI_TOOL = {+ type: 'function',+ function: { name: INTENT_TOOL.name, description: INTENT_TOOL.description, parameters: INTENT_TOOL.input_schema },+};++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++// ── pure helpers (exported for tests) ───────────────────────────────────────────++// Map a free-text asset reference to a canonical Solana asset. $THREE is the only+// coin we resolve by name; everything else is SOL, USDC, a raw mint, or unknown.+export function resolveAssetToken(raw, { threeMint = THREE_MINT } = {}) {+ const s = String(raw || '').trim();+ if (!s) return { kind: 'none', mint: null, symbol: null };+ const lower = s.toLowerCase().replace(/^\$/, '');+ if (lower === 'sol' || lower === 'solana') return { kind: 'sol', mint: null, symbol: 'SOL' };+ if (lower === 'usdc') return { kind: 'usdc', mint: null, symbol: 'USDC' };+ if (lower === 'three') return { kind: 'three', mint: threeMint, symbol: '$THREE' };+ if (BASE58_RE.test(s)) {+ return { kind: s === threeMint ? 'three' : 'mint', mint: s, symbol: s === threeMint ? '$THREE' : null };+ }+ return { kind: 'unknown', mint: null, symbol: s };+}++// Validate + clamp the raw tool output into the canonical intent the client+// executes. Anything malformed collapses to a clarify so money never moves on a+// guess. Pure + synchronous; destination/mint resolution happens in the handler.+export function normalizeWalletIntent(raw, { threeMint = THREE_MINT } = {}) {+ const r = raw && typeof raw === 'object' ? raw : {};+ let action = String(r.action || '').toLowerCase();+ if (!ACTIONS.includes(action)) action = 'none';+ if (action === 'swap') action = 'buy';++ const confidence = clamp01(Number(r.confidence));+ const readback = typeof r.readback === 'string' ? r.readback.slice(0, 400) : '';+ const clarifying =+ typeof r.clarifying_question === 'string' && r.clarifying_question.trim()+ ? r.clarifying_question.trim().slice(0, 400)+ : null;++ if (action === 'none') {+ return { action: 'none', confidence, readback, clarifying_question: clarifying };+ }+ if (action === 'clarify') {+ return {+ action: 'clarify',+ confidence,+ readback,+ clarifying_question: clarifying || 'Could you say that again with the amount and destination?',+ };+ }++ const amountRaw = Number(r.amount);+ const amount = Number.isFinite(amountRaw) && amountRaw > 0 ? amountRaw : null;+ let unit = typeof r.amount_unit === 'string' ? r.amount_unit : null;+ if (unit && !UNITS.includes(unit)) unit = null;++ let slippage = Number(r.slippage_pct);+ slippage = Number.isFinite(slippage) ? Math.max(0, Math.min(50, slippage)) : null;++ const out = { action, confidence, readback, clarifying_question: clarifying, slippage_pct: slippage };++ if (action === 'buy' || action === 'snipe') {+ // Acquire a mint by spending SOL. The thing being acquired is in+ // destination_or_mint (the mint/symbol); the spend is amount+unit.+ const target = resolveAssetToken(r.destination_or_mint || r.asset, { threeMint });+ out.target = target;+ out.amount = amount;+ out.amount_unit = unit;+ return out;+ }+ if (action === 'sell') {+ const target = resolveAssetToken(r.asset || r.destination_or_mint, { threeMint });+ out.target = target;+ out.amount = amount;+ out.amount_unit = unit;+ return out;+ }+ // tip / withdraw — move an asset to a destination.+ out.asset = resolveAssetToken(r.asset, { threeMint });+ out.amount = amount;+ out.amount_unit = unit;+ out.destination = typeof r.destination_or_mint === 'string' ? r.destination_or_mint.trim() : '';+ return out;+}++function clamp01(n) {+ return Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : 0.5;+}++// ── LLM calls ───────────────────────────────────────────────────────────────────++function buildSystemPrompt({ agentName, network, balanceSol, holdings, limits: lim, tradeLimits }) {+ const heldLines = (holdings || [])+ .slice(0, 8)+ .map((h) => ` - ${h.symbol || h.mint}: ${h.ui_amount} (mint ${h.mint})`)+ .join('\n');+ const lines = [+ `You are the wallet brain of "${agentName || 'this agent'}", a 3D AI agent on three.ws that holds its own real Solana wallet. The agent's OWNER is speaking to you and can move real funds.`,+ 'Your only job: translate the owner\'s latest message into exactly one structured wallet intent by calling the record_wallet_intent tool. Output nothing else.',+ '',+ 'Rules:',+ '- NEVER guess an amount or a destination. If the message is missing the amount, the destination, or the token, set action="clarify" and ask one short, in-character question.',+ '- If the message is small talk or not about moving money, set action="none".',+ '- The ONLY coin this platform promotes is $THREE. Treat "$THREE"/"three" as that coin. A mint address the owner pastes for a snipe/buy is their own input — pass it through, never invent one.',+ '- "buy/swap" spends SOL to acquire a token. "snipe" buys a freshly-launched mint. "sell" sells a held token for SOL. "tip" and "withdraw" send funds to an address.',+ '- "half a SOL" → amount 0.5, unit SOL. "half my SOL" / "half" of a holding → amount 50, unit percent. "everything"/"all" → unit max.',+ '- Trades on this engine are quoted in SOL. If the owner asks to swap a non-SOL balance (e.g. USDC) into a token without saying how much SOL to spend, clarify how much SOL to use.',+ '- Keep readback to one sentence the owner can confirm aloud, naming the real amount and destination/token.',+ '',+ `Live context — network: ${network}; spendable SOL: ${balanceSol == null ? 'unknown' : balanceSol}.`,+ heldLines ? `Tokens held:\n${heldLines}` : 'Tokens held: none detected.',+ `Owner spend policy: per-tx $${fmtLim(lim?.per_tx_usd)}, daily $${fmtLim(lim?.daily_usd)}. Trade caps: per-trade ◎${fmtLim(tradeLimits?.per_trade_sol)}, daily ◎${fmtLim(tradeLimits?.daily_budget_sol)}${tradeLimits?.kill_switch ? '; trading is PAUSED' : ''}.`,+ 'These limits are enforced by the server at execution — you do not need to enforce them, but you may mention them if the owner asks for more than allowed.',+ ];+ return lines.join('\n');+}++function fmtLim(v) {+ return v == null ? '∞' : v;+}++function buildMessages({ utterance, history }) {+ const msgs = [];+ for (const h of (history || []).slice(-6)) {+ if (h && (h.role === 'user' || h.role === 'assistant') && typeof h.content === 'string') {+ msgs.push({ role: h.role, content: h.content.slice(0, 1000) });+ }+ }+ msgs.push({ role: 'user', content: String(utterance).slice(0, 1000) });+ // Anthropic requires the first message to be a user turn.+ if (msgs[0].role !== 'user') msgs.shift();+ return msgs;+}++async function fetchWithTimeout(url, opts) {+ const ctrl = new AbortController();+ const t = setTimeout(() => ctrl.abort(), CALL_TIMEOUT_MS);+ try {+ return await fetch(url, { ...opts, signal: ctrl.signal });+ } finally {+ clearTimeout(t);+ }+}++async function callAnthropic({ apiKey, system, messages }) {+ const resp = await fetchWithTimeout(ANTHROPIC_URL, {+ method: 'POST',+ headers: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' },+ body: JSON.stringify({+ model: ANTHROPIC_MODEL,+ max_tokens: 600,+ system,+ messages,+ tools: [INTENT_TOOL],+ tool_choice: { type: 'tool', name: INTENT_TOOL.name },+ }),+ });+ if (!resp.ok) throw new Error(`anthropic ${resp.status}`);+ const j = await resp.json();+ const block = (j.content || []).find((b) => b.type === 'tool_use' && b.name === INTENT_TOOL.name);+ if (!block) throw new Error('anthropic: no tool_use');+ return block.input;+}++async function callOpenRouter({ apiKey, system, messages }) {+ const resp = await fetchWithTimeout(OPENROUTER_URL, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${apiKey}`,+ 'content-type': 'application/json',+ 'HTTP-Referer': 'https://three.ws',+ 'X-Title': 'three.ws conversational wallet',+ },+ body: JSON.stringify({+ model: OPENROUTER_MODEL,+ max_tokens: 600,+ messages: [{ role: 'system', content: system }, ...messages],+ tools: [OPENAI_TOOL],+ tool_choice: { type: 'function', function: { name: INTENT_TOOL.name } },+ }),+ });+ if (!resp.ok) throw new Error(`openrouter ${resp.status}`);+ const j = await resp.json();+ const call = j.choices?.[0]?.message?.tool_calls?.[0];+ if (!call?.function?.arguments) throw new Error('openrouter: no tool_call');+ return JSON.parse(call.function.arguments);+}++// ── handler ──────────────────────────────────────────────────────────────────────++export async function handleIntent(req, res, id) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to talk-to-trade from this wallet');++ const [row] = await sql`SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;+ if (!row) return error(res, 404, 'not_found', 'agent not found');+ // Owner-only: visitors can converse but can never trigger a fund action, by any+ // phrasing. The parser itself is gated so the LLM is never even consulted for a+ // non-owner.+ if (row.user_id !== auth.userId) {+ return error(res, 403, 'forbidden', 'only the owner can give this wallet voice commands');+ }++ const rl = await limits.chatUser(auth.userId || `ip:${clientIp(req)}`);+ if (!rl.success) return rateLimited(res, rl, 'too many wallet commands, slow down');++ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');+ }++ const utterance = typeof body.utterance === 'string' ? body.utterance.trim() : '';+ if (!utterance) return error(res, 400, 'validation_error', 'utterance is required');+ if (utterance.length > 1000) return error(res, 400, 'validation_error', 'utterance is too long');+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';++ const meta = { ...(row.meta || {}) };+ const ctx = body.context && typeof body.context === 'object' ? body.context : {};+ const system = buildSystemPrompt({+ agentName: row.name,+ network,+ balanceSol: typeof ctx.balance_sol === 'number' ? ctx.balance_sol : null,+ holdings: Array.isArray(ctx.holdings) ? ctx.holdings : [],+ limits: getSpendLimits(meta),+ tradeLimits: getTradeLimits(meta),+ });+ const messages = buildMessages({ utterance, history: body.history });++ // Provider ladder: Anthropic (claude-opus-4-8, native tool use) first; an+ // OpenRouter free-tier model with OpenAI-style tool calling as the fallback so a+ // missing Anthropic key never takes voice trading down silently. Both produce the+ // same tool schema; the server normalizes the result either way.+ let userKeys = {};+ try {+ const [urow] = await sql`SELECT provider_keys FROM users WHERE id = ${auth.userId}`;+ userKeys = await loadUserProviderKeys(urow?.provider_keys);+ } catch {+ userKeys = {};+ }+ const anthropicKey = userKeys.anthropic || process.env.ANTHROPIC_API_KEY;+ const openrouterKey = userKeys.openrouter || process.env.OPENROUTER_API_KEY;++ let rawIntent = null;+ let provider = null;+ const tried = [];+ if (anthropicKey) {+ try {+ rawIntent = await callAnthropic({ apiKey: anthropicKey, system, messages });+ provider = 'anthropic';+ } catch (e) {+ tried.push(`anthropic:${e.message}`);+ }+ }+ if (!rawIntent && openrouterKey) {+ try {+ rawIntent = await callOpenRouter({ apiKey: openrouterKey, system, messages });+ provider = 'openrouter';+ } catch (e) {+ tried.push(`openrouter:${e.message}`);+ }+ }++ if (!rawIntent) {+ if (!anthropicKey && !openrouterKey) {+ // Honest signal so the client can fall back to the manual HUD form rather+ // than fake a parse.+ return error(res, 503, 'intent_unavailable', 'voice trading is not configured on this deployment — use the wallet form');+ }+ console.warn('[solana/intent] all providers failed:', tried.join(' | '));+ return error(res, 502, 'parse_failed', 'could not understand that right now — try again or use the wallet form');+ }++ const intent = normalizeWalletIntent(rawIntent, { threeMint: THREE_MINT });++ // Resolve a withdraw/tip destination (.sol → address) server-side so the client+ // shows the real recipient in the read-back. An unresolved name becomes a clarify.+ if ((intent.action === 'tip' || intent.action === 'withdraw') && intent.destination) {+ const resolved = await resolveSolanaRecipient(intent.destination).catch(() => ({ address: null }));+ if (resolved.address) {+ intent.destination = resolved.address;+ intent.destination_label = resolved.resolved_from || null;+ } else if (!BASE58_RE.test(intent.destination)) {+ return json(res, 200, {+ data: {+ provider,+ intent: {+ action: 'clarify',+ confidence: intent.confidence,+ readback: '',+ clarifying_question: `I couldn't resolve "${intent.destination}" to a Solana address. What address or .sol name should I send to?`,+ },+ },+ });+ }+ }++ return json(res, 200, { data: { provider, intent } });+}++export default handleIntent;diff --git a/api/agents/solana-trade.js b/api/agents/solana-trade.jsindex 2fa272f15..81fc66f08 100644--- a/api/agents/solana-trade.js+++ b/api/agents/solana-trade.js@@ -108,7 +108,7 @@ async function resolveMintDecimals(conn, mintPk) {// the bonding curve first (getBuy/SellQuote → price impact); on a graduated coin// (no curve) it prices off the canonical AMM pool. Throws a typed error the// handler maps to a clean 4xx.-async function quoteTrade({ conn, side, mintPk, mintStr, network, solAmount, tokenAmountRaw, slippageBps }) {+export async function quoteTrade({ conn, side, mintPk, mintStr, network, solAmount, tokenAmountRaw, slippageBps }) {if (side === 'buy') {const lamportsIn = BigInt(Math.floor(Number(solAmount) * LAMPORTS_PER_SOL));if (lamportsIn <= 0n) throw typed(400, 'amount_too_small', 'enter a SOL amount greater than zero');@@ -589,7 +589,7 @@ export async function handleTrade(req, res, id) {// Build the on-chain instructions for the resolved venue + side. Curve trades use// the pump-sdk v2 builders; graduated trades use the pump-swap AMM SDK. Mirrors// api/agents/pumpfun/[action].js so there is one instruction-building convention.-async function buildTradeInstructions({ side, conn, network, mintPk, ownerPk, quote, slippageBps, solAmount, tokenAmountRaw }) {+export async function buildTradeInstructions({ side, conn, network, mintPk, ownerPk, quote, slippageBps, solAmount, tokenAmountRaw }) {const BNmod = (await import('bn.js')).default;if (quote.venue === 'bonding_curve') {diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.jsindex 9ec16ce43..c6f921db9 100644--- a/api/agents/solana-wallet.js+++ b/api/agents/solana-wallet.js@@ -1357,6 +1357,49 @@ async function forkCountFor(id) {}}+// Lifetime tips received by this agent — confirmed on-chain tip rows only, so the+// count can never be fabricated. Powers the "Tipped Nx / $X" reputation mark.+async function lifetimeTipsFor(id) {+ try {+ const [r] = await sql`+ SELECT count(*)::int AS n, COALESCE(sum(usd), 0)::float8 AS usd+ FROM agent_custody_events+ WHERE agent_id = ${id} AND event_type = 'tip' AND status IN ('ok', 'confirmed')+ `;+ return { count: r?.n || 0, usd: Number(r?.usd) || 0 };+ } catch {+ return { count: 0, usd: 0 };+ }+}++// Realized trading P&L from CLOSED sniper positions (a real on-chain settlement).+// Net SOL and the count of profitable closes; defensive when the table is absent.+async function realizedPnlFor(id) {+ try {+ const [r] = await sql`+ SELECT+ COALESCE(sum(realized_pnl_lamports), 0)::float8 AS lamports,+ count(*) FILTER (WHERE realized_pnl_lamports > 0)::int AS wins+ FROM agent_sniper_positions+ WHERE agent_id = ${id} AND status = 'closed' AND realized_pnl_lamports IS NOT NULL+ `;+ return { sol: (Number(r?.lamports) || 0) / 1e9, wins: r?.wins || 0 };+ } catch {+ // Table may not exist on this deployment — P&L mark simply doesn't appear.+ return { sol: 0, wins: 0 };+ }+}++// One real read of every reputation signal the look + regalia use.+async function reputationFor(id) {+ const [forkCount, tips, pnl] = await Promise.all([+ forkCountFor(id),+ lifetimeTipsFor(id),+ realizedPnlFor(id),+ ]);+ return { forkCount, tips, pnl };+}+// GET /api/agents/:id/solana/networth — public read: the agent's net-worth "look"// (presence tier, aura, confidence, regalia marks) derived entirely from real// chain reads + real DB counts, plus the owner's reactivity preferences.@@ -1401,18 +1444,29 @@ async function handleNetWorth(req, res, id) {if (!rl.success) return rateLimited(res, rl);const prefs = normalizePrefs(row.meta?.networth_look);- const forkCount = await forkCountFor(id);+ const { forkCount, tips, pnl } = await reputationFor(id);+ const repState = {+ forkCount,+ tipCount: tips.count, tipUsd: tips.usd,+ realizedPnlSol: pnl.sol, realizedWins: pnl.wins,+ };+ const reputation = {+ fork_count: forkCount,+ tips: { count: tips.count, usd: tips.usd },+ realized_pnl_sol: pnl.sol, realized_wins: pnl.wins,+ };// No wallet yet (provisioning): calm baseline look, honest about state. The- // agent still reads as itself — never poor-shamed, never faked.+ // agent still reads as itself — never poor-shamed, never faked. Reputation it+ // has already earned (forks, tips) still shows.if (!address) {- const look = computeLook({ usd: 0, forkCount });+ const look = computeLook({ usd: 0, ...repState });return json(res, 200, {data: {agent_id: id, address: null, network: 'mainnet', provisioning: true,portfolio: { usd: 0, sol: 0, three: null, usdc: 0, token_count: 0, top: [] },- reputation: { fork_count: forkCount },- tier: look.tier, look, marks: computeMarks({ usd: 0, forkCount }, { hubUrl }),+ reputation,+ tier: look.tier, look, marks: computeMarks({ usd: 0, ...repState }, { hubUrl }),prefs, is_owner: isOwner, hub_url: hubUrl,},});@@ -1440,7 +1494,7 @@ async function handleNetWorth(req, res, id) {usd,threeUsd: threeTok?.usd || 0,threeAmount: threeTok?.amount || 0,- forkCount,+ ...repState,};const look = computeLook(state);const marks = computeMarks(state, { hubUrl });@@ -1459,7 +1513,7 @@ async function handleNetWorth(req, res, id) {token_count: tokens.length,top,},- reputation: { fork_count: forkCount },+ reputation,tier: look.tier,look,marks,@@ -1685,6 +1739,10 @@ export default async function handler(req, res, id, action) {if (action === 'limits') return handleLimits(req, res, id);if (action === 'tip') return handleTip(req, res, id);if (action === 'pulse-visibility') return handlePulseVisibility(req, res, id);+ if (action === 'intent') {+ const mod = await import('./solana-intent.js');+ return mod.handleIntent(req, res, id);+ }if (action === 'trade') {const mod = await import('./solana-trade.js');return mod.handleTrade(req, res, id);diff --git a/api/agents/wallet-embed.js b/api/agents/wallet-embed.jsnew file mode 100644index 000000000..8155719d8--- /dev/null+++ b/api/agents/wallet-embed.js@@ -0,0 +1,149 @@+/**+ * GET /api/agents/wallet-embed?id=<agentId>[&network=mainnet]+ *+ * The public, cross-origin wallet card that powers the agent's wallet wherever+ * its avatar appears OFF three.ws — the `<agent-3d wallet>` web component on a+ * stranger's blog, the avatar SDK viewer, an IRL/AR card, the walk world, the+ * chat app. It is served `Access-Control-Allow-Origin: *` (no credentials) so+ * any embedding origin can read it, and it exposes ONLY public data:+ *+ * • the agent's public custodial Solana receive address (+ vanity pattern)+ * • its live balance: total USD, native SOL, and the $THREE / USDC breakdown+ * • lifetime tips received (count + USD) — the real, screenshot-worthy headline+ * • name, avatar thumbnail, and the canonical three.ws deep links (open / tip)+ *+ * It never returns a secret key, an owner-only field, or anything that could+ * move funds — an embed is the visitor view by construction. Role (owner vs+ * visitor) is NEVER asserted by the embedding host; it is derived only from a+ * real three.ws session on three.ws itself, so this endpoint has no concept of+ * ownership at all.+ *+ * Rate-limited per IP (`walletEmbedIp`) and short-TTL cached so the open+ * endpoint can't be turned into a balance-scraping relay. The Solana balance+ * read reuses the same cached `getBalances` path the in-app chip uses, so an+ * embed and the profile page never disagree on a number.+ */++import { sql } from '../_lib/db.js';+import { cors, wrap, json, method, error, rateLimited } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { isUuid } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getBalances, walletUsdTotal } from '../_lib/balances.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+// CDN-readable for embed crawlers; short browser cache, longer at the edge.+const CACHE = 'public, max-age=30, s-maxage=120, stale-while-revalidate=60';++function thumbnailUrl(thumbKey, visibility) {+ if (!thumbKey) return null;+ if (visibility !== 'public' && visibility !== 'unlisted') return null;+ const base = env.S3_PUBLIC_DOMAIN || 'https://three.ws/cdn';+ return `${base}/${thumbKey}`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.walletEmbedIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const id = (url.searchParams.get('id') || '').trim();+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';+ if (!isUuid(id)) return error(res, 400, 'bad_request', 'id must be an agent UUID');++ let row;+ try {+ [row] = await sql`+ SELECT i.id, i.name, i.meta,+ a.thumbnail_key, a.visibility+ FROM agent_identities i+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL+ WHERE i.id = ${id} AND i.deleted_at IS NULL+ LIMIT 1+ `;+ } catch {+ return error(res, 503, 'unavailable', 'could not read the agent right now — try again');+ }+ if (!row) return error(res, 404, 'not_found', 'agent not found');++ const meta = row.meta || {};+ const address = meta.solana_address || null;+ const origin = env.APP_ORIGIN || 'https://three.ws';++ // No wallet yet — still a real, honest response so the embed can render a+ // clean "wallet provisioning" identity rather than a broken widget.+ if (!address || !BASE58_RE.test(String(address))) {+ res.setHeader('cache-control', CACHE);+ return json(res, 200, {+ data: {+ agentId: id,+ name: row.name || null,+ avatar: thumbnailUrl(row.thumbnail_key, row.visibility),+ address: null,+ network,+ openUrl: `${origin}/agent/${id}`,+ },+ });+ }++ // Live balance via the shared cached path (Helius DAS → public RPC fallback),+ // plus lifetime tips from the durable custody ledger. Both tolerate failure:+ // a balance read error yields nulls (the embed shows the address without a+ // value) rather than a 5xx, honoring "no broken widget".+ let balanceUsd = null, sol = null, three = null, usdc = null;+ try {+ const balances = await getBalances({ chain: 'solana', address });+ if (balances) {+ balanceUsd = walletUsdTotal(balances);+ sol = balances.native?.amount ?? null;+ for (const t of balances.tokens || []) {+ if (t.mint === THREE_MINT) three = t.amount;+ else if (t.mint === USDC_MINT) usdc = t.amount;+ }+ }+ } catch {+ /* balance unavailable — render identity-only, never a 5xx */+ }++ let tipsCount = 0, tipsUsd = 0;+ try {+ const [agg] = await sql`+ SELECT COUNT(*)::int AS n, COALESCE(SUM(usd), 0)::float8 AS usd+ FROM agent_custody_events+ WHERE agent_id = ${id} AND event_type = 'tip' AND status = 'confirmed'+ `;+ tipsCount = agg?.n ?? 0;+ tipsUsd = agg?.usd ?? 0;+ } catch {+ /* tip ledger unavailable — omit the headline stat, keep the card */+ }++ const prefix = meta.solana_vanity_prefix || null;+ const suffix = meta.solana_vanity_suffix || null;++ res.setHeader('cache-control', CACHE);+ return json(res, 200, {+ data: {+ agentId: id,+ name: row.name || null,+ avatar: thumbnailUrl(row.thumbnail_key, row.visibility),+ address: String(address),+ vanity: prefix || suffix ? { prefix, suffix } : null,+ network,+ balanceUsd,+ sol,+ three,+ usdc,+ tips: { count: tipsCount, usd: tipsUsd },+ explorerUrl: `https://solscan.io/account/${address}`,+ openUrl: `${origin}/agent/${id}`,+ walletUrl: `${origin}/agent/${id}/wallet`,+ tipUrl: `${origin}/agent/${id}/wallet#tip`,+ },+ });+});diff --git a/api/galaxy/flows.js b/api/galaxy/flows.jsnew file mode 100644index 000000000..7bd544225--- /dev/null+++ b/api/galaxy/flows.js@@ -0,0 +1,232 @@+// GET /api/galaxy/flows — the Galaxy Money-Cam feed.+//+// A real, platform-wide stream of money MOVING between agent wallets, shaped for+// the 3D star-map: every row is one on-chain, explorer-verifiable transfer that+// touches at least one PUBLIC three.ws agent, with the counterparty resolved to a+// second agent whenever its wallet belongs to one. The galaxy renders an+// agent↔agent transfer as a pulse of light travelling star→star, and a one-sided+// flow (a community tip, a DEX trade) as a flare on the single agent's star.+//+// EVERY flow is real. There are NO synthetic edges — when the platform is quiet+// the feed is honestly empty and the galaxy stays calm. This is the visual layer+// over the same public ledger as /api/pulse (Money Pulse), so the two never+// disagree; this endpoint adds the counterparty→agent resolution the map needs to+// draw an edge between two stars.+//+// Sources (all real, all public):+// · agent_custody_events — tips received (event_type='tip', sender = meta.from),+// and outbound spends (event_type='spend', category in trade/snipe/x402,+// recipient = destination). Withdraws / vanity-swaps / limit-changes /+// key-recovery are OWNER-PRIVATE and never appear.+// · pump_agent_mints — coins an agent launched.+//+// Privacy is load-bearing: a private (is_public=false) or pulse-opted-out agent+// never appears — as the actor OR as a resolved counterparty.+//+// GET /api/galaxy/flows — most-recent window (keyset paginated)+// GET /api/galaxy/flows?since=<cursor> — delta poll: only flows newer than cursor+// GET /api/galaxy/flows?cursor=<cursor> — load older history (scrubber backfill)+// GET /api/galaxy/flows?type=tips|trades|payments|launches|all+// GET /api/galaxy/flows?network=mainnet|devnet&limit=<n>++import { sql } from '../_lib/db.js';+import { cors, json, method, serverError, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { cacheGet, cacheSet } from '../_lib/cache.js';+import {+ PUBLIC_SPEND_CATEGORIES,+ TYPE_KINDS,+ encodeCursor,+ decodeCursor,+ shapeFlow,+ isAgentEdge,+} from '../_lib/galaxy-flows.js';++const FEED_TTL_S = 8; // first-page cache — it's a live feed, keep it short+const DEFAULT_LIMIT = 80;+const MAX_LIMIT = 200;++// A flow is only worth animating if it touches a star the viewer can actually+// see, but that gating happens client-side against the loaded snapshot — here we+// return the full public window so the scrubber has real history to replay.+async function handleFeed({ network, type, limit, cursor, since }) {+ const kinds = TYPE_KINDS[type] || TYPE_KINDS.all;++ // Public-map privacy gate — a private or pulse-opted-out agent never appears,+ // as the actor OR as a resolved counterparty. Written out per-alias (not+ // parameterized) to match the proven /api/pulse composition exactly.+ const actorGate = sql`ai.deleted_at IS NULL AND ai.is_public = true+ AND COALESCE((ai.meta->>'pulse_opt_out')::boolean, false) = false`;+ const cpGate = sql`cp.deleted_at IS NULL AND cp.is_public = true+ AND COALESCE((cp.meta->>'pulse_opt_out')::boolean, false) = false`;++ // The counterparty wallet depends on direction: a tip's counterparty is the+ // sender (meta.from); a spend's counterparty is the recipient (destination).+ const counterpartyAddr = sql`+ (CASE WHEN ce.event_type = 'tip'+ THEN NULLIF(ce.meta->>'from', '')+ ELSE ce.destination END)+ `;++ const feedCte = sql`+ SELECT+ ce.created_at AS ts,+ (CASE+ WHEN ce.event_type = 'tip' THEN 'tip'+ WHEN ce.category = 'x402' THEN 'payment'+ WHEN ce.category = 'snipe' THEN 'snipe'+ ELSE 'trade'+ END) AS kind,+ (CASE WHEN ce.event_type = 'tip' THEN 'in' ELSE 'out' END) AS direction,+ 'c' || ce.id::text AS row_id,+ ce.network AS network,+ ai.id AS actor_id,+ ai.name AS actor_name,+ ai.meta->>'solana_address' AS actor_addr,+ ai.meta->>'solana_vanity_prefix' AS actor_vp,+ ai.meta->>'solana_vanity_suffix' AS actor_vs,+ ce.asset AS asset,+ ce.amount_lamports AS amount_lamports,+ ce.amount_raw AS amount_raw,+ ce.usd AS usd,+ ce.signature AS signature,+ ${counterpartyAddr} AS counterparty_addr,+ cp.id AS counterparty_id,+ cp.name AS counterparty_name,+ NULL::text AS mint,+ NULL::text AS symbol,+ NULL::text AS coin_name+ FROM agent_custody_events ce+ JOIN agent_identities ai ON ai.id = ce.agent_id AND ${actorGate}+ LEFT JOIN agent_identities cp+ ON cp.meta->>'solana_address' = ${counterpartyAddr}+ AND ${cpGate}+ WHERE ce.network = ${network}+ AND ce.status IN ('ok', 'confirmed')+ AND (+ ce.event_type = 'tip'+ OR (ce.event_type = 'spend' AND ce.category = ANY(${PUBLIC_SPEND_CATEGORIES}))+ )++ UNION ALL++ SELECT+ pam.created_at AS ts,+ 'launch' AS kind,+ 'launch' AS direction,+ 'l' || pam.id::text AS row_id,+ pam.network AS network,+ ai.id AS actor_id,+ ai.name AS actor_name,+ ai.meta->>'solana_address' AS actor_addr,+ ai.meta->>'solana_vanity_prefix' AS actor_vp,+ ai.meta->>'solana_vanity_suffix' AS actor_vs,+ NULL::text AS asset,+ NULL::bigint AS amount_lamports,+ NULL::numeric AS amount_raw,+ NULL::numeric AS usd,+ NULL::text AS signature,+ NULL::text AS counterparty_addr,+ NULL::uuid AS counterparty_id,+ NULL::text AS counterparty_name,+ pam.mint AS mint,+ pam.symbol AS symbol,+ pam.name AS coin_name+ FROM pump_agent_mints pam+ JOIN agent_identities ai ON ai.id = pam.agent_id AND ${actorGate}+ WHERE pam.network = ${network}+ `;++ const cur = decodeCursor(cursor);+ const sinceCur = decodeCursor(since);+ const olderBound = cur+ ? sql`AND (feed.ts < ${cur.ts} OR (feed.ts = ${cur.ts} AND feed.row_id < ${cur.rowId}))`+ : sql``;+ const newerBound = sinceCur+ ? sql`AND (feed.ts > ${sinceCur.ts} OR (feed.ts = ${sinceCur.ts} AND feed.row_id > ${sinceCur.rowId}))`+ : sql``;++ const rows = await sql`+ WITH feed AS (${feedCte})+ SELECT * FROM feed+ WHERE feed.kind = ANY(${kinds})+ ${olderBound}+ ${newerBound}+ ORDER BY feed.ts DESC, feed.row_id DESC+ LIMIT ${limit + 1}+ `;++ const hasMore = rows.length > limit;+ const flows = rows.slice(0, limit).map(shapeFlow);+ const last = flows[flows.length - 1];+ const head = flows[0];+ const nextCursor = hasMore && last ? encodeCursor(last.ts, last.id) : null;+ const headCursor = head ? encodeCursor(head.ts, head.id) : (sinceCur ? since : null);++ // Honest window summary computed over exactly what we returned.+ let edges = 0;+ let usdTotal = 0;+ const byKind = { tip: 0, trade: 0, snipe: 0, payment: 0, launch: 0 };+ for (const f of flows) {+ if (isAgentEdge(f)) edges++;+ if (f.usd) usdTotal += f.usd;+ if (byKind[f.kind] != null) byKind[f.kind]++;+ }++ return {+ flows,+ has_more: hasMore,+ next_cursor: nextCursor,+ head_cursor: headCursor,+ network,+ type,+ summary: {+ count: flows.length,+ edges, // agent↔agent transfers (two stars)+ flares: flows.length - edges, // one-sided flows (one star)+ usd_total: usdTotal,+ by_kind: byKind,+ window_start: last ? last.ts : null, // oldest in page+ window_end: head ? head.ts : null, // newest in page+ },+ server_time: new Date().toISOString(),+ };+}++export default async function handler(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';+ const typeRaw = url.searchParams.get('type') || 'all';+ const type = TYPE_KINDS[typeRaw] ? typeRaw : 'all';+ const limit = Math.min(MAX_LIMIT, Math.max(1, Number(url.searchParams.get('limit')) || DEFAULT_LIMIT));+ const cursor = url.searchParams.get('cursor');+ const since = url.searchParams.get('since');++ try {+ // A first page (no cursor/since) is cached briefly to shield the DB from a+ // herd of pollers. A delta poll (`since`) is never cached — it must be live.+ const isFirstPage = !cursor && !since;+ if (isFirstPage) {+ const cacheKey = `galaxy:flows:${network}:${type}:${limit}`;+ let body = await cacheGet(cacheKey);+ if (body === null) {+ body = await handleFeed({ network, type, limit, cursor, since });+ await cacheSet(cacheKey, body, FEED_TTL_S);+ }+ res.setHeader('cache-control', 'public, max-age=6');+ return json(res, 200, { data: body });+ }++ const body = await handleFeed({ network, type, limit, cursor, since });+ return json(res, 200, { data: body });+ } catch (e) {+ console.error('[api/galaxy/flows] failed', e?.message, e?.stack);+ return serverError(res, 502, 'galaxy_flows_failed', e);+ }+}diff --git a/data/changelog.json b/data/changelog.jsonindex b41e791a5..5a3e1b7e9 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,14 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-23",+ "title": "Talk to your agent and it trades — the Conversational Wallet",+ "summary": "Your avatar's wallet now takes voice and text commands. Tell your agent \"tip 0.1 SOL to vault.sol\", \"snipe that mint with half a SOL\", \"sell half my $THREE\", or \"withdraw 2 SOL to my Phantom\" — it parses your intent with Claude, shows you exactly what it will do next to your own words (real quote, USD value, fees, network), and waits for an explicit \"yes\" or a tap before anything moves. Confirmed trades come back with a real on-chain signature and explorer link, and the avatar celebrates the moment it lands. Every action runs the same owner-only, spend-limit-gated, audited path as the rest of the wallet — visitors can chat but can never move funds, by any phrasing. A wrong hearing is caught at the read-back, \"cancel\" is always one word away, and there's a full keyboard path with no mic required.",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","title": "More uploaded avatars animate out of the box — no more accidental T-poses",diff --git a/public/changelog.json b/public/changelog.jsonindex 1e33e19b3..aede61e35 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T03:17:02.870Z",+ "generated_at": "2026-06-23T03:38:53.398Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -214,6 +214,16 @@"security"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Talk to your agent and it trades — the Conversational Wallet",+ "summary": "Your avatar's wallet now takes voice and text commands. Tell your agent \"tip 0.1 SOL to vault.sol\", \"snipe that mint with half a SOL\", \"sell half my $THREE\", or \"withdraw 2 SOL to my Phantom\" — it parses your intent with Claude, shows you exactly what it will do next to your own words (real quote, USD value, fees, network), and waits for an explicit \"yes\" or a tap before anything moves. Confirmed trades come back with a real on-chain signature and explorer link, and the avatar celebrates the moment it lands. Every action runs the same owner-only, spend-limit-gated, audited path as the rest of the wallet — visitors can chat but can never move funds, by any phrasing. A wrong hearing is caught at the read-back, \"cancel\" is always one word away, and there's a full keyboard path with no mic required.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 2fc2b5da1..a3c440263 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -166,6 +166,14 @@<category>security</category><description>Arming an autonomous sniper strategy and changing an agent's discretionary trade limits both commit or unlock real custodial funds, so both writes now require the same one-time CSRF token every other money-moving action already enforced (withdraw, vanity grind, spend limits, trade execution). Ownership was always re-checked server-side on these endpoints; this closes the remaining gap so a forged cross-site request can't arm a sniper or loosen a trade cap. No change to how you use them — the dashboard already sends the token.</description></item>+ <item>+ <title>Talk to your agent and it trades — the Conversational Wallet</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Talk to your agent and it trades — the Conversational Wallet</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your avatar's wallet now takes voice and text commands. Tell your agent "tip 0.1 SOL to vault.sol", "snipe that mint with half a SOL", "sell half my $THREE", or "withdraw 2 SOL to my Phantom" — it parses your intent with Claude, shows you exactly what it will do next to your own words (real quote, USD value, fees, network), and waits for an explicit "yes" or a tap before anything moves. Confirmed trades come back with a real on-chain signature and explorer link, and the avatar celebrates the moment it lands. Every action runs the same owner-only, spend-limit-gated, audited path as the rest of the wallet — visitors can chat but can never move funds, by any phrasing. A wrong hearing is caught at the read-back, "cancel" is always one word away, and there's a full keyboard path with no mic required.</description>+ </item><item><title>The in-chat skill purchase card is smoother, fully keyboard-friendly, and shows the right price every time</title><link>https://three.ws/marketplace</link>diff --git a/public/features.json b/public/features.jsonindex 5fbbc68b5..86ee76f85 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T03:17:02.820Z",+ "generated_at": "2026-06-23T03:38:53.303Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agent-detail.js b/src/agent-detail.jsindex 2f12ec38c..bb8ead446 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -14,6 +14,7 @@ import { mountMoneyPulse } from './shared/money-pulse.js';import { mountValidationBadge } from './shared/validation-badge.js';import { seeInWorldHref, agentAvatarGlb } from './shared/agent-3d.js';import { hydrateAvatarWallet } from './shared/wallet-aura.js';+import { mountPresence } from './shared/networth-presence.js';import { renderError as renderAsyncError } from './shared/async-state.js';import { skeletonHTML } from './shared/state-kit.js';import { openCoinLaunch } from './shared/agent-coin.js';@@ -36,17 +37,33 @@ let _pulseHandle = null;// The hero's wallet aura controller — torn down on re-render/unload so its live// poll + rAF never leak.let adNetWorthAura = null;+let adNetWorthPanel = null;function mountAgentDetailAura(agent) {const wrap = document.getElementById('ad-avatar-wrap');if (!wrap || !agent?.id) return;adNetWorthAura?.destroy?.();adNetWorthAura = null;+ adNetWorthPanel?.destroy?.();+ adNetWorthPanel = null;hydrateAvatarWallet(wrap, agent, { lod: 'full', live: true, network: 'mainnet' })- .then((c) => { adNetWorthAura = c; })+ .then((c) => {+ adNetWorthAura = c;+ // Mount the presence panel (tier + reputation regalia + owner reactivity+ // dial) at the top of the main column, kept in lockstep with the aura.+ const main = document.querySelector('.ad-main');+ if (c && main) {+ mountPresence({ agentId: agent.id, container: main, aura: c, position: 'prepend' })+ .then((panel) => { adNetWorthPanel = panel || null; })+ .catch(() => { /* read failed — aura still shows the look */ });+ }+ }).catch(() => { /* dormant baseline already shown */ });}if (typeof window !== 'undefined') {- window.addEventListener('pagehide', () => { adNetWorthAura?.destroy?.(); adNetWorthAura = null; }, { once: true });+ window.addEventListener('pagehide', () => {+ adNetWorthAura?.destroy?.(); adNetWorthAura = null;+ adNetWorthPanel?.destroy?.(); adNetWorthPanel = null;+ }, { once: true });}function destroyCoinStatus() {diff --git a/src/agent-wallet-hub/tabs/deposit.js b/src/agent-wallet-hub/tabs/deposit.jsindex c9790aadb..64f45a00f 100644--- a/src/agent-wallet-hub/tabs/deposit.js+++ b/src/agent-wallet-hub/tabs/deposit.js@@ -29,6 +29,7 @@import { registerWalletTab } from '../registry.js';import { fetchAgentSolanaWallet, fetchAgentSolanaActivity } from '../../agent-solana-wallet.js';import { renderQRToSVG } from '../../erc8004/qr.js';+import { buildSolanaPayUri } from '../../shared/solana-pay.js';import { formatSol, timeAgo, explorerAddressUrl, explorerTxUrl } from '../util.js';// Balance is server-cached for 60s, so a faster poll just re-reads the cache.@@ -109,24 +110,6 @@ function injectDepositStyle() {document.head.appendChild(tag);}-/**- * Build a Solana-Pay transfer-request URI: `solana:<recipient>[?amount=…][&label=…]`.- * Per the Solana Pay spec the recipient is a base58 address and `amount` is a- * decimal in SOL. Returns null without a valid-looking address.- */-export function buildSolanaPayUri(address, { amount, label } = {}) {- if (!address || typeof address !== 'string') return null;- const params = new URLSearchParams();- const amt = Number(amount);- if (Number.isFinite(amt) && amt > 0) {- // Trim to a sane lamport precision (9 dp) and drop trailing zeros.- params.set('amount', String(amt).slice(0, 24));- }- if (label) params.set('label', label);- const qs = params.toString();- return `solana:${address}${qs ? `?${qs}` : ''}`;-}-registerWalletTab({id: 'deposit',label: 'Deposit',diff --git a/src/avatar-page.js b/src/avatar-page.jsindex 9bf2feb61..313ad1420 100644--- a/src/avatar-page.js+++ b/src/avatar-page.js@@ -19,6 +19,7 @@ import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';import { mountAgentSolanaWalletCard } from './agent-solana-wallet.js';import { mountAgentVanityGrinderCard } from './agent-vanity-grinder.js';import { hydrateAvatarWallet, walletTierBadge } from './shared/wallet-aura.js';+import { mountPresence } from './shared/networth-presence.js';const ATTACHED_KEY_PREFIX = 'avatar_attached_v1:';@@ -56,12 +57,16 @@ if (!avatarId) {}// Stop the wallet-aura live poll and free its rAF when the page unloads.-window.addEventListener('pagehide', () => { netWorthAura?.destroy?.(); netWorthAura = null; }, { once: true });+window.addEventListener('pagehide', () => {+ netWorthAura?.destroy?.(); netWorthAura = null;+ netWorthPanel?.destroy?.(); netWorthPanel = null;+}, { once: true });// ── State ─────────────────────────────────────────────────────────────let avatar = null;let netWorthAura = null;+let netWorthPanel = null;let attachedSkills = new Set();let attachedPlugins = new Set();let chatHistory = [];@@ -575,6 +580,17 @@ function mountNetWorthAura() {.then((controller) => {if (!controller) return;netWorthAura = controller;+ // The presence panel: the legible, ownable face of the aura — the tier, the+ // reputation regalia (each a real number), and, for the owner, the+ // reactivity dial that drives the glow above. Lives at the top of Overview.+ if (!netWorthPanel) {+ const overview = $('av-overview');+ if (overview) {+ mountPresence({ agentId, container: overview, aura: controller, position: 'prepend' })+ .then((panel) => { if (panel) netWorthPanel = panel; else netWorthPanel = null; })+ .catch(() => { /* read failed — aura still shows the look */ });+ }+ }// Surface the honest net-worth tier + USD in the meta strip so the// presence has a readable label, not just a glow.const strip = $('av-meta-strip');diff --git a/src/shared/agent-networth.js b/src/shared/agent-networth.jsindex 55080d0f4..9a177fcc0 100644--- a/src/shared/agent-networth.js+++ b/src/shared/agent-networth.js@@ -1,71 +1,24 @@/**- * Net-Worth-Reactive Avatar — the single client source of truth.+ * Net-Worth-Reactive Avatar — the client data/prefs layer.** The agent wears its wallet: holdings, $THREE, fork lineage and reputation become- * the 3D body's aura, material, idle confidence and regalia. Every number here is- * REAL — it comes from GET /api/agents/:id/solana/networth, which aggregates real- * Solana balances (via api/_lib/balances.js), real $THREE holdings, and real fork- * counts, and returns the canonical "look" so the galaxy star, the profile hero,- * and the AR body always agree (one normalizer, one truth).+ * the 3D body's aura and the legible regalia of the presence panel. Every number+ * here is REAL — it comes from GET /api/agents/:id/solana/networth, which aggregates+ * real Solana balances (via api/_lib/balances.js), real $THREE holdings, and real+ * fork counts, and returns the canonical look/tier/marks so the galaxy star, the+ * profile hero, and the AR body always agree (one server truth, fetched once here).*- * The server computes the canonical look/tier/marks; this module fetches it,- * persists owner reactivity prefs (CSRF-gated), and carries a small local mirror of- * the tier model (kept in lockstep with api/_lib/networth-model.js) for the- * hold-last-state / offline path so a brief RPC hiccup never blanks an avatar.+ * The server (api/_lib/networth-model.js) computes the canonical look/tier/marks;+ * this module fetches it and persists the owner's reactivity prefs (CSRF-gated).+ * The visual mapping itself lives in src/shared/wallet-networth.js (the aura) and+ * the shader (the galaxy); both share the server's tier vocabulary.*/-// Mirror of api/_lib/networth-model.js — keep the thresholds in lockstep. Used-// only for the offline/hold-last fallback; the server result is authoritative.-export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';--export const PRESENCE_TIERS = [- { key: 'latent', label: 'Latent', min: 0, accent: '#8b8b9a' },- { key: 'spark', label: 'Spark', min: 1, accent: '#8b5cf6' },- { key: 'glow', label: 'Glow', min: 50, accent: '#a78bfa' },- { key: 'radiant', label: 'Radiant', min: 500, accent: '#c4b5fd' },- { key: 'luminous', label: 'Luminous', min: 5_000, accent: '#ddd6fe' },- { key: 'beacon', label: 'Beacon', min: 50_000, accent: '#f5f3ff' },-];+import { formatWalletUsdSafe } from './wallet-format.js';export const REACTIVITY_LEVELS = ['off', 'subtle', 'balanced', 'expressive'];export const DEFAULT_PREFS = { reactivity: 'balanced', signals: { aura: true, events: true, reputation: true } };-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, Number(n) || 0));--export function tierForUsd(usd) {- const v = Math.max(0, Number(usd) || 0);- let index = 0;- for (let i = 0; i < PRESENCE_TIERS.length; i++) if (v >= PRESENCE_TIERS[i].min) index = i;- const t = PRESENCE_TIERS[index];- const nx = PRESENCE_TIERS[index + 1] || null;- return {- key: t.key, label: t.label, index, accent: t.accent,- next: nx ? { key: nx.key, label: nx.label, usd_to_next: Math.max(0, nx.min - v) } : null,- };-}--/** Local mirror of the server look computation (offline / hold-last fallback). */-export function computeLook(state = {}) {- const usd = Math.max(0, Number(state.usd) || 0);- const tier = tierForUsd(usd);- const wealth = clamp(Math.log10(usd + 1) / 5, 0, 1);- const threeUsd = Math.max(0, Number(state.threeUsd) || 0);- const threeBoost = threeUsd > 0 ? clamp(Math.log10(threeUsd + 1) / 5, 0, 0.18) : 0;- const auraIntensity = clamp(wealth + threeBoost, 0, 1);- const repScore = clamp(state.repScore, 0, 100) / 100;- const forks = Math.max(0, Number(state.forkCount) || 0);- const forkBoost = clamp(Math.log10(forks + 1) / 3, 0, 0.25);- const confidence = clamp(tier.index / 5 * 0.6 + repScore * 0.25 + forkBoost, 0, 1);- return {- tier,- auraIntensity,- auraColor: tier.accent,- materialTier: Math.floor(tier.index / 2),- confidence,- glow: clamp(0.12 + auraIntensity * 0.88, 0, 1),- };-}-export function normalizePrefs(raw) {const r = raw && typeof raw === 'object' ? raw : {};const reactivity = REACTIVITY_LEVELS.includes(r.reactivity) ? r.reactivity : DEFAULT_PREFS.reactivity;@@ -131,14 +84,10 @@ export async function saveNetWorthPrefs(agentId, prefs) {// ── Formatting ───────────────────────────────────────────────────────────────+// Compact USD comes from the wallet program's one formatter so the inline+// net-worth figure reads identically to the wallet chip ($1.2K, not $1k).export function fmtUsd(n) {- const v = Number(n) || 0;- if (v === 0) return '$0';- if (v < 0.01) return '<$0.01';- if (v < 1) return `$${v.toFixed(2)}`;- if (v < 1000) return `$${v.toFixed(v < 100 ? 1 : 0)}`;- if (v < 1_000_000) return `$${(v / 1000).toFixed(v < 10_000 ? 1 : 0)}k`;- return `$${(v / 1_000_000).toFixed(1)}M`;+ return formatWalletUsdSafe(n);}export function fmtAmount(n) {@@ -148,12 +97,3 @@ export function fmtAmount(n) {if (v < 1_000_000_000) return `${(v / 1_000_000).toFixed(1)}M`;return `${(v / 1_000_000_000).toFixed(1)}B`;}--/** Parse a hex accent (#rgb / #rrggbb) to a normalized [r,g,b] triple for WebGL. */-export function hexToRgb(hex) {- let h = String(hex || '#8b5cf6').replace('#', '');- if (h.length === 3) h = h.split('').map((c) => c + c).join('');- const int = parseInt(h, 16);- if (Number.isNaN(int)) return [0.55, 0.36, 0.96];- return [((int >> 16) & 255) / 255, ((int >> 8) & 255) / 255, (int & 255) / 255];-}diff --git a/src/shared/agent-wallet-chip.js b/src/shared/agent-wallet-chip.jsindex ef7b29444..009c99530 100644--- a/src/shared/agent-wallet-chip.js+++ b/src/shared/agent-wallet-chip.js@@ -41,6 +41,7 @@*/import { computeRarity } from '../solana/vanity/rarity.js';+import { formatWalletUsd, shortAddress } from './wallet-format.js';const STYLE_ID = 'tws-agent-wallet-chip-styles';const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -152,18 +153,10 @@ export function hasWallet(agent) {}// ── value formatting ──────────────────────────────────────────────────────────--/** Compact USD label: $0, <$0.01, $9.40, $950, $1.2K, $3.4M, $1.1B. */-export function formatWalletUsd(n) {- if (n == null || !Number.isFinite(n)) return null;- if (n <= 0) return '$0';- if (n < 0.01) return '<$0.01';- if (n < 10) return `$${n.toFixed(2)}`;- if (n < 1000) return `$${Math.round(n)}`;- if (n < 1e6) return `$${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}K`;- if (n < 1e9) return `$${(n / 1e6).toFixed(1)}M`;- return `$${(n / 1e9).toFixed(1)}B`;-}+// Compact USD + address shortening live in ./wallet-format.js (the single source+// of truth for the whole wallet program). Re-exported here so the many surfaces+// that already import { formatWalletUsd } from the chip keep working unchanged.+export { formatWalletUsd };function formatPct(p) {if (p == null || !Number.isFinite(p)) return null;@@ -897,7 +890,7 @@ function renderPopoverBody(el, entry, meta) {`<a class="twc-act twc-link" href="${esc(meta.explorerUrl)}" target="_blank" rel="noopener noreferrer" title="Solscan" aria-label="View on Solscan">${LINK_SVG}</a></div>` +(meta.evm? `<div class="twc-pop-addr"><span class="twc-chain" data-chain="evm">EVM</span>` +- `<span class="twc-amono">${esc(meta.evm.slice(0, 6))}…${esc(meta.evm.slice(-4))}</span>` ++ `<span class="twc-amono">${esc(shortAddress(meta.evm, 6, 4))}</span>` +`<button type="button" class="twc-act" data-twc-copy="${esc(meta.evm)}" title="Copy EVM address" aria-label="Copy EVM address">${COPY_SVG}</button>` +(meta.evmExplorerUrl ? `<a class="twc-act twc-link" href="${esc(meta.evmExplorerUrl)}" target="_blank" rel="noopener noreferrer" title="Basescan" aria-label="View on Basescan">${LINK_SVG}</a>` : '') +`</div>`diff --git a/src/shared/networth-aura.js b/src/shared/networth-aura.jsdeleted file mode 100644index b06714f31..000000000--- a/src/shared/networth-aura.js+++ /dev/null@@ -1,147 +0,0 @@-/**- * Net-Worth Aura — the tasteful, performance-cheap glow that embodies an agent's- * real wealth/reputation tier around its 3D body.- *- * Two additive sprites: a floor halo (a pool of light at the feet) and a soft- * back-glow behind the figure. Both read as *presence*, never a slot-machine.- * Intensity/colour come straight from the net-worth look descriptor- * (src/shared/agent-networth.js → computeLook), which is derived from real chain- * reads. A zero-value wallet gets a calm, near-invisible floor; a Beacon-tier- * agent gets a confident violet halo.- *- * Reduced-motion safe: the glow holds a static intensity (no pulse) when motion is- * off, so the tier still reads. Cheap by construction: one shared radial texture,- * two sprites, no per-frame allocation; the host stops calling update() when the- * avatar is offscreen.- */--import * as THREE from 'three';--// One soft radial-alpha texture, shared by every aura instance on the page.-let _spriteTex = null;-function radialTexture() {- if (_spriteTex) return _spriteTex;- const s = 128;- const c = document.createElement('canvas');- c.width = c.height = s;- const ctx = c.getContext('2d');- const g = ctx.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2);- g.addColorStop(0, 'rgba(255,255,255,1)');- g.addColorStop(0.35, 'rgba(255,255,255,0.55)');- g.addColorStop(0.7, 'rgba(255,255,255,0.12)');- g.addColorStop(1, 'rgba(255,255,255,0)');- ctx.fillStyle = g;- ctx.fillRect(0, 0, s, s);- _spriteTex = new THREE.CanvasTexture(c);- _spriteTex.colorSpace = THREE.SRGBColorSpace;- return _spriteTex;-}--const REDUCED_MOTION =- typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;--const lerp = (a, b, t) => a + (b - a) * Math.min(1, Math.max(0, t));--export class NetWorthAura {- constructor() {- this.object3D = new THREE.Group();- this.object3D.name = 'networth-aura';- this.object3D.renderOrder = -1; // draw behind the avatar-- const tex = radialTexture();- this._floorMat = new THREE.SpriteMaterial({ map: tex, color: 0x8b5cf6, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, opacity: 0 });- this._backMat = new THREE.SpriteMaterial({ map: tex, color: 0x8b5cf6, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, opacity: 0 });-- this._floor = new THREE.Sprite(this._floorMat);- this._floor.center.set(0.5, 0.5);- this._back = new THREE.Sprite(this._backMat);- this._back.center.set(0.5, 0.5);-- this.object3D.add(this._floor, this._back);-- this._radius = 1;- this._height = 1.7;- this._intensity = 0; // target glow 0..1- this._cur = 0; // smoothed glow- this._color = new THREE.Color(0x8b5cf6);- this._pulse = 0; // transient additive boost, decays- this._pulseSign = 1; // +1 celebratory, -1 subdued- this._t = 0;- this.visible = true;- }-- /** Fit the aura to the avatar's real bounds (call once after the model loads). */- setBounds({ radius, height, centerY = 0, baseY = 0 } = {}) {- if (radius > 0) this._radius = radius;- if (height > 0) this._height = height;- // Floor halo: flat pool at the feet, ~2.6× footprint.- const fr = this._radius * 2.6;- this._floor.scale.set(fr, fr, 1);- this._floor.position.set(0, baseY + 0.02, 0);- this._floor.material.rotation = 0;- // Back-glow: a tall soft column centered on the torso.- this._back.scale.set(this._radius * 3.2, this._height * 1.25, 1);- this._back.position.set(0, centerY, -this._radius * 0.4);- return this;- }-- /**- * Apply a net-worth look. `auraColor` may be a hex string or an [r,g,b] triple;- * `glow` (0..1) sets the steady intensity.- */- setLook(look = {}) {- const glow = Math.max(0, Math.min(1, Number(look.glow ?? look.auraIntensity) || 0));- this._intensity = glow;- const c = look.auraColor;- if (Array.isArray(c)) this._color.setRGB(c[0], c[1], c[2]);- else if (typeof c === 'string') this._color.set(c);- this._floorMat.color.copy(this._color);- this._backMat.color.copy(this._color);- return this;- }-- /** Fire a transient pulse on a real event. kind: 'positive' | 'subdued'. */- pulse(kind = 'positive') {- if (REDUCED_MOTION) return; // static look only — never flash with motion off- this._pulseSign = kind === 'subdued' ? -1 : 1;- this._pulse = kind === 'subdued' ? 0.5 : 1;- }-- /** Per-frame. Skips work when hidden. dt in seconds. */- update(dt) {- if (!this.visible) return;- this._t += dt;- // Smoothly chase the target intensity (so tier changes ease in).- this._cur = lerp(this._cur, this._intensity, dt * 2.5);- // Decay the transient pulse.- if (this._pulse > 0.001) this._pulse = Math.max(0, this._pulse - dt * (this._pulseSign > 0 ? 1.1 : 0.7));- else this._pulse = 0;-- // Gentle breathing on the steady glow (suppressed under reduced motion).- const breathe = REDUCED_MOTION ? 1 : 1 + 0.06 * Math.sin(this._t * 1.1);- const pulseBoost = this._pulse * this._pulseSign * 0.6;-- const floorBase = 0.10 + this._cur * 0.42;- const backBase = 0.04 + this._cur * 0.26;- this._floorMat.opacity = Math.max(0, (floorBase + pulseBoost) * breathe);- this._backMat.opacity = Math.max(0, (backBase + pulseBoost * 0.7) * breathe);- // Pulse also briefly widens the floor pool.- if (this._pulse > 0) {- const k = 1 + this._pulse * this._pulseSign * 0.18;- const fr = this._radius * 2.6 * k;- this._floor.scale.set(fr, fr, 1);- }- }-- setVisible(v) {- this.visible = !!v;- this.object3D.visible = !!v;- }-- dispose() {- this._floorMat.dispose();- this._backMat.dispose();- this.object3D.parent?.remove(this.object3D);- // The shared texture is intentionally NOT disposed (other auras may use it).- }-}diff --git a/src/shared/networth-presence.js b/src/shared/networth-presence.jsindex 0680ef15b..f7755bd29 100644--- a/src/shared/networth-presence.js+++ b/src/shared/networth-presence.js@@ -7,12 +7,14 @@* (off ↔ expressive) plus per-signal opt-outs, persisted on the agent record so a* visitor sees the agent exactly as the owner configured it.*- * Pairs with src/shared/reactive-avatar.js: the controller fetches the real data- * and renders the 3D aura; this panel renders the same data as UI and lets the- * owner tune it. One normalizer (agent-networth.js) feeds both.+ * Pairs with src/shared/wallet-aura.js: that controller renders the live 3D aura+ * on the model; this panel renders the same real data as UI and lets the owner+ * tune it. The owner's reactivity dial here drives that aura in lockstep (see+ * mountPresence), and one fetch (agent-networth.js → the canonical server look)+ * feeds both, so the panel and the glow can never disagree.*/-import { saveNetWorthPrefs, normalizePrefs, fmtUsd, fmtAmount, REACTIVITY_LEVELS } from './agent-networth.js';+import { fetchNetWorth, saveNetWorthPrefs, normalizePrefs, fmtUsd, fmtAmount, REACTIVITY_LEVELS } from './agent-networth.js';const STYLE_ID = 'tws-networth-presence-styles';@@ -32,7 +34,9 @@ function ensureStyles() {const s = document.createElement('style');s.id = STYLE_ID;s.textContent = `-.nwp{--nw-accent:#a78bfa;font-family:var(--font-body,Inter,system-ui,sans-serif);color:var(--ink,#e7e7ea);+.nwp{--nw-accent:var(--wallet-accent-strong,#a78bfa);--nw-accent-ink:var(--wallet-accent,#c4b5fd);+ --nw-accent-soft:var(--wallet-accent-soft,rgba(139,92,246,.12));--nw-accent-line:var(--wallet-accent-fill,rgba(139,92,246,.28));+ font-family:var(--font-body,Inter,system-ui,sans-serif);color:var(--ink,#e7e7ea);background:var(--surface-1,rgba(255,255,255,.03));border:1px solid var(--stroke,rgba(255,255,255,.08));border-radius:var(--radius-lg,16px);padding:var(--space-md,16px);display:flex;flex-direction:column;gap:14px;}.nwp-head{display:flex;align-items:center;gap:12px;}@@ -47,13 +51,13 @@ function ensureStyles() {.nwp-sub a{color:var(--nw-accent);text-decoration:none;}.nwp-sub a:hover{text-decoration:underline;}.nwp-next{height:5px;border-radius:999px;background:rgba(255,255,255,.07);overflow:hidden;}-.nwp-next i{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,#8b5cf6,var(--nw-accent));transition:width .6s var(--ease-standard,cubic-bezier(.4,0,.2,1));}+.nwp-next i{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,var(--nw-accent),var(--nw-accent-ink));transition:width .6s var(--ease-standard,cubic-bezier(.4,0,.2,1));}.nwp-marks{display:flex;flex-wrap:wrap;gap:6px;}.nwp-mark{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:600;padding:4px 9px;border-radius:999px;- background:rgba(139,92,246,.12);border:1px solid rgba(139,92,246,.28);color:#c4b5fd;text-decoration:none;+ background:var(--nw-accent-soft);border:1px solid var(--nw-accent-line);color:var(--nw-accent-ink);text-decoration:none;transition:transform .12s ease,filter .15s ease,background .15s ease;}-a.nwp-mark:hover{transform:translateY(-1px);background:rgba(139,92,246,.2);}-a.nwp-mark:focus-visible{outline:2px solid rgba(139,92,246,.7);outline-offset:2px;}+a.nwp-mark:hover{transform:translateY(-1px);background:var(--nw-accent-line);}+a.nwp-mark:focus-visible{outline:2px solid var(--nw-accent);outline-offset:2px;}.nwp-mark b{color:#fff;font-weight:700;}.nwp-controls{display:flex;flex-direction:column;gap:10px;border-top:1px solid var(--stroke,rgba(255,255,255,.08));padding-top:12px;}.nwp-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-dim,#9a9aa3);}@@ -63,7 +67,7 @@ a.nwp-mark:focus-visible{outline:2px solid rgba(139,92,246,.7);outline-offset:2ptransition:background .15s ease,color .15s ease;}.nwp-seg button:hover{color:#fff;}.nwp-seg button[aria-pressed="true"]{background:var(--nw-accent);color:#0a0a0a;}-.nwp-seg button:focus-visible{outline:2px solid rgba(139,92,246,.7);outline-offset:2px;}+.nwp-seg button:focus-visible{outline:2px solid var(--nw-accent);outline-offset:2px;}.nwp-hint{font-size:11px;color:var(--ink-dim,#9a9aa3);min-height:14px;}.nwp-sigs{display:flex;flex-wrap:wrap;gap:8px;}.nwp-sig{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--ink,#e7e7ea);cursor:pointer;user-select:none;}@@ -217,3 +221,40 @@ export function createPresencePanel({ agentId, onPrefsSaved } = {}) {destroy() { el.remove(); },};}++/**+ * One-call mount: fetch the agent's REAL net-worth look (the canonical server+ * endpoint — tier, reputation marks, owner prefs), render the presence panel into+ * `container`, and keep the live 3D aura in lockstep with the owner's prefs. The+ * panel and the aura read from the same truth, so the dial the owner turns here+ * immediately changes the glow on the model — and a visitor sees that same look.+ *+ * @param {object} opts+ * @param {string} opts.agentId+ * @param {HTMLElement} opts.container where to mount the panel+ * @param {{setPrefs?:(p:object)=>void}|null} [opts.aura] the wallet-aura controller to keep in sync+ * @param {'append'|'prepend'} [opts.position='append']+ * @returns {Promise<{el:HTMLElement, update:Function, destroy:Function}|null>}+ * the panel handle, or null when there is no presence to show (read failed).+ */+export async function mountPresence({ agentId, container, aura = null, position = 'append' } = {}) {+ if (!agentId || !container || typeof document === 'undefined') return null;+ const panel = createPresencePanel({+ agentId,+ onPrefsSaved: (prefs) => { try { aura?.setPrefs?.(prefs); } catch { /* aura gone */ } },+ });+ if (position === 'prepend' && container.firstChild) container.insertBefore(panel.el, container.firstChild);+ else container.appendChild(panel.el);++ let data = null;+ try { data = await fetchNetWorth(agentId); } catch { data = null; }+ if (!data) {+ // Read genuinely failed (not provisioning — that comes back 200). Don't leave+ // a stuck skeleton; remove the panel so the page degrades cleanly.+ panel.destroy();+ return null;+ }+ panel.update(data);+ try { aura?.setPrefs?.(data.prefs); } catch { /* aura gone */ }+ return panel;+}diff --git a/src/shared/reactive-avatar.js b/src/shared/reactive-avatar.jsdeleted file mode 100644index 082aad81a..000000000--- a/src/shared/reactive-avatar.js+++ /dev/null@@ -1,230 +0,0 @@-/**- * Reactive Avatar Controller — drives a 3D agent's embodiment from its REAL- * on-chain net worth.- *- * Given a live viewer (and, when present, the AgentAvatar empathy layer + the- * protocol bus), this:- * 1. fetches the agent's real net-worth look (one normalizer — agent-networth.js)- * and applies it as a persistent aura + idle confidence;- * 2. watches the real chain for change — a positive USD/$THREE delta between two- * real reads means funds actually landed (a tip, a fill, a pump), so the- * avatar performs a short celebratory reaction; a real drawdown reads as- * subdued, never punishing. No reaction ever fires without a real delta.- * 3. respects the owner's reactivity preference (off ↔ expressive) and per-signal- * opt-outs, `prefers-reduced-motion`, and visibility — it stops entirely when- * the avatar is offscreen or the tab is hidden, holding the last real state.- *- * Every visual traces to a real read. The poll cadence is just how often we read- * the chain; the *reaction* is event-driven off real deltas, not a timer.- */--import { Box3, Vector3 } from 'three';-import { fetchNetWorth, normalizePrefs, fmtUsd } from './agent-networth.js';-import { NetWorthAura } from './networth-aura.js';-import { ACTION_TYPES } from '../agent-protocol.js';--const REDUCED_MOTION =- typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;--// How often we read the chain while visible. The balances API caches ~60s, so a-// 30s cadence costs almost nothing yet catches a tip within one cache window.-const POLL_MS = 30_000;-// A USD move smaller than this is price noise, not an event.-const usdEventFloor = (usd) => Math.max(0.5, usd * 0.01);--export class ReactiveAvatarController {- /**- * @param {object} ctx- * @param {string} ctx.agentId- * @param {object} ctx.viewer the 3D Viewer (has .scene, .content, ._afterAnimateHooks, .el)- * @param {object} [ctx.protocol] the agent-protocol bus (for emotion/gesture reactions)- * @param {object} [ctx.avatar] the AgentAvatar empathy layer (optional)- * @param {boolean} [ctx.isOwner]- * @param {(data:object)=>void} [ctx.onUpdate] called with each fresh net-worth payload- * @param {(ev:object)=>void} [ctx.onReaction] called when a real event fires- */- constructor(ctx) {- this.agentId = ctx.agentId;- this.viewer = ctx.viewer;- this.protocol = ctx.protocol || null;- this.avatar = ctx.avatar || null;- this.isOwner = !!ctx.isOwner;- this.onUpdate = ctx.onUpdate || null;- this.onReaction = ctx.onReaction || null;-- this.aura = new NetWorthAura();- this.prefs = normalizePrefs(null);- this.data = null; // last real net-worth payload- this._last = null; // last snapshot used for delta detection- this._timer = null;- this._inflight = null;- this._disposed = false;- this._onFrame = (dt) => this.aura.update(dt);- this._io = null;- this._intersecting = true;- this._boundsFitted = false;-- this._onVisibility = () => this._reschedule();- }-- /** Boot: attach the aura, hook the frame loop, do the first real read. */- async start() {- if (this._disposed) return;- const scene = this.viewer?.scene;- if (scene) scene.add(this.aura.object3D);- this._fitBounds();-- if (this.viewer && Array.isArray(this.viewer._afterAnimateHooks)) {- this.viewer._afterAnimateHooks.push(this._onFrame);- }-- // Pause cleanly when offscreen.- if (typeof IntersectionObserver === 'function' && this.viewer?.el) {- this._io = new IntersectionObserver((entries) => {- this._intersecting = entries.some((e) => e.isIntersecting);- this.aura.setVisible(this._intersecting);- this._reschedule();- }, { threshold: 0.01 });- this._io.observe(this.viewer.el);- }- document.addEventListener('visibilitychange', this._onVisibility);-- await this.refresh();- this._reschedule();- }-- /** Re-fit the aura to the avatar's real bounds (call after a model swap). */- _fitBounds() {- const content = this.viewer?.content;- if (!content) return;- try {- const box = new Box3().setFromObject(content);- if (box.isEmpty()) return;- const size = box.getSize(new Vector3());- const center = box.getCenter(new Vector3());- const radius = Math.max(0.25, Math.max(size.x, size.z) / 2);- this.aura.setBounds({ radius, height: Math.max(0.5, size.y), centerY: center.y, baseY: box.min.y });- this.aura.object3D.position.set(content.position.x, 0, content.position.z);- this._boundsFitted = true;- } catch {- /* bounds unavailable yet — the look still applies, halo sits at origin */- }- }-- /** One real chain read → apply look, detect events. */- async refresh() {- if (this._disposed || this._inflight) return;- const ctrl = new AbortController();- this._inflight = ctrl;- let data;- try {- data = await fetchNetWorth(this.agentId, { signal: ctrl.signal });- } finally {- this._inflight = null;- }- if (this._disposed) return;- // Null = read failed: hold the last real state, never invent one.- if (!data) return;-- if (!this._boundsFitted) this._fitBounds();- this.prefs = normalizePrefs(data.prefs);- this.data = data;- this._applyLook(data.look);- this._detectEvents(data);- this.onUpdate?.(data);- }-- /** Apply the persistent net-worth look (respecting the owner's aura opt-out). */- _applyLook(look) {- if (!look) return;- const auraOn = this.prefs.reactivity !== 'off' && this.prefs.signals.aura !== false;- if (auraOn) {- this.aura.setLook(look);- } else {- // Owner muted the balance aura → keep a flat, minimal presence floor.- this.aura.setLook({ glow: 0.12, auraColor: look.auraColor });- }- }-- /**- * Compare the new real snapshot to the last and fire a reaction on a genuine- * delta. The first read only seeds the baseline — no reaction without history.- */- _detectEvents(data) {- const usd = Number(data?.portfolio?.usd) || 0;- const three = Number(data?.portfolio?.three?.amount) || 0;- const prev = this._last;- this._last = { usd, three };- if (!prev) return; // baseline only-- if (this.prefs.reactivity === 'off' || this.prefs.signals.events === false) return;-- const dUsd = usd - prev.usd;- const dThree = three - prev.three;-- if (dUsd > usdEventFloor(prev.usd) || dThree > 0) {- this._react('positive', {- kind: dThree > 0 ? 'three_in' : 'funds_in',- deltaUsd: dUsd,- deltaThree: dThree,- label: dThree > 0 ? `+${data.portfolio.three ? three - prev.three : ''} $THREE` : `+${fmtUsd(dUsd)}`,- });- } else if (dUsd < -Math.max(1, prev.usd * 0.02)) {- this._react('subdued', { kind: 'drawdown', deltaUsd: dUsd, label: fmtUsd(dUsd) });- }- }-- /** Perform a reaction, scaled to the owner's reactivity level. */- _react(tone, ev) {- const level = this.prefs.reactivity; // 'subtle' | 'balanced' | 'expressive'- // Aura pulse on every level (it self-suppresses under reduced motion).- this.aura.pulse(tone);-- // Emotion + gesture only on richer levels, and never under reduced motion.- if (!REDUCED_MOTION && this.protocol && level !== 'subtle') {- if (tone === 'positive') {- this.protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'celebration', weight: level === 'expressive' ? 0.95 : 0.65 } });- if (level === 'expressive') this.protocol.emit({ type: ACTION_TYPES.GESTURE, payload: { name: 'celebrate', duration: 1800 } });- this.protocol.emit({ type: ACTION_TYPES.LOOK_AT, payload: { target: 'up' } });- } else {- // Drawdown: subdued, not punished — a quiet downward glance.- this.protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'empathy', weight: 0.4 } });- this.protocol.emit({ type: ACTION_TYPES.LOOK_AT, payload: { target: 'down' } });- }- }- this.onReaction?.({ tone, ...ev });- }-- /** Owner changed reactivity prefs in the UI — apply immediately (already saved). */- applyPrefs(prefs) {- this.prefs = normalizePrefs(prefs);- if (this.data?.look) this._applyLook(this.data.look);- this._reschedule();- }-- /** Start/stop the poll based on visibility + reactivity. */- _reschedule() {- clearTimeout(this._timer);- this._timer = null;- if (this._disposed) return;- const active = !document.hidden && this._intersecting && this.prefs.reactivity !== 'off';- if (!active) return;- this._timer = setTimeout(async () => {- await this.refresh();- this._reschedule();- }, POLL_MS);- }-- dispose() {- this._disposed = true;- clearTimeout(this._timer);- this._inflight?.abort();- document.removeEventListener('visibilitychange', this._onVisibility);- this._io?.disconnect();- if (this.viewer && Array.isArray(this.viewer._afterAnimateHooks)) {- const i = this.viewer._afterAnimateHooks.indexOf(this._onFrame);- if (i !== -1) this.viewer._afterAnimateHooks.splice(i, 1);- }- this.aura.dispose();- }-}diff --git a/src/shared/solana-pay.js b/src/shared/solana-pay.jsnew file mode 100644index 000000000..8772936d6--- /dev/null+++ b/src/shared/solana-pay.js@@ -0,0 +1,25 @@+/**+ * Solana Pay transfer-request URIs — the one builder every surface shares.+ *+ * A `solana:<recipient>[?amount=…][&label=…]` deep link opens Phantom /+ * Solflare / Backpack pre-filled with the agent's public receive address. It is+ * what the wallet-hub Deposit tab renders as a QR, what IRL/AR encodes for+ * tap-to-tip in the real world, and what the portable embed wallet hands to a+ * phone. Keeping it here means the address/label/amount encoding is identical+ * everywhere and there is no per-surface copy to drift.+ *+ * Public data only: the recipient is the agent's PUBLIC solana_address, so this+ * never touches a secret. Per the Solana Pay spec `amount` is a decimal in SOL.+ */+export function buildSolanaPayUri(address, { amount, label } = {}) {+ if (!address || typeof address !== 'string') return null;+ const params = new URLSearchParams();+ const amt = Number(amount);+ if (Number.isFinite(amt) && amt > 0) {+ // Trim to a sane lamport precision (9 dp) and drop trailing zeros.+ params.set('amount', String(amt).slice(0, 24));+ }+ if (label) params.set('label', label);+ const qs = params.toString();+ return `solana:${address}${qs ? `?${qs}` : ''}`;+}diff --git a/src/shared/wallet-aura.js b/src/shared/wallet-aura.jsindex 54db1d6e6..a38899abf 100644--- a/src/shared/wallet-aura.js+++ b/src/shared/wallet-aura.js@@ -126,6 +126,16 @@ export function mountWalletAura(container, opts = {}) {const particles = new ParticleField(canvas);let visual = null;let visible = true;+ // The owner's reactivity preference (persisted server-side, fetched by the+ // presence panel and pushed in via setPrefs). Until known, the aura renders at+ // full strength; once known, a muted aura or 'off' reactivity dampens it to a+ // quiet presence floor, and 'events: false' suppresses the live flourish — so a+ // visitor always sees the agent exactly as its owner configured it. null = not+ // yet known → full default.+ let prefs = null;++ const auraMuted = () => !!prefs && (prefs.reactivity === 'off' || prefs.signals?.aura === false);+ const eventsMuted = () => !!prefs && (prefs.reactivity === 'off' || prefs.signals?.events === false);// Pause the particle rAF when the avatar scrolls off-screen — dense lists and// the galaxy must not pay for auras nobody is looking at.@@ -140,20 +150,36 @@ export function mountWalletAura(container, opts = {}) {function applyVisual(v) {visual = v;+ // When the owner has muted the wealth aura (or turned reactivity off), keep a+ // flat minimal presence floor — the agent still reads as itself, just calm.+ const muted = auraMuted();+ const intensity = muted ? 0.04 : v.intensity;layer.style.setProperty('--wa-accent', v.accent);layer.style.setProperty('--wa-glow', v.glow);- layer.style.setProperty('--wa-i', v.intensity.toFixed(3));- layer.dataset.level = String(v.level);- layer.dataset.levelHi = v.level >= 3 ? 'true' : 'false';+ layer.style.setProperty('--wa-i', intensity.toFixed(3));+ layer.dataset.level = String(muted ? 0 : v.level);+ layer.dataset.levelHi = !muted && v.level >= 3 ? 'true' : 'false';layer.dataset.tier = v.tier;+ layer.dataset.muted = muted ? 'true' : 'false';// The layer is always present (it fades in on ready); a dormant wallet just// renders a whisper-quiet baseline, never absent and never broken.layer.dataset.ready = 'true';- if (v.dormant) layer.style.setProperty('--wa-i', '0.04');- particles.configure(v);+ if (v.dormant && !muted) layer.style.setProperty('--wa-i', '0.04');+ // A muted aura runs no particle field — it's a still presence, not a glow.+ particles.configure(muted ? { ...v, dormant: true, particleDensity: 0 } : v);if (visible) particles.start();}+ /**+ * Apply the owner's saved reactivity prefs. Re-renders the current visual gated+ * by the new prefs so the change is immediate (the presence panel calls this on+ * the owner's first read and after every toggle). Safe to call before any data.+ */+ function setPrefs(p) {+ prefs = p && typeof p === 'object' ? p : null;+ if (visual) applyVisual(visual);+ }+async function update(stateOrAgent) {const state = stateOrAgent && stateOrAgent.usdTotal !== undefined? stateOrAgent@@ -165,6 +191,8 @@ export function mountWalletAura(container, opts = {}) {function flourish(kind = 'inflow') {if (REDUCED_MOTION) return;+ // The owner can mute live reactions while keeping the steady aura.+ if (eventsMuted()) return;if (kind === 'drawdown') {layer.classList.add('wa-draw');setTimeout(() => layer.classList.remove('wa-draw'), 900);@@ -186,7 +214,7 @@ export function mountWalletAura(container, opts = {}) {layer.remove();}- return { applyVisual, update, flourish, destroy, el: layer, get state() { return layer.__state; } };+ return { applyVisual, update, flourish, setPrefs, destroy, el: layer, get state() { return layer.__state; } };}/**@@ -382,6 +410,9 @@ export async function hydrateAvatarWallet(container, agent, opts = {}) {? agent: (agent?.agent_id || agent?.agentId || agent?.id || null);let stopLive = () => {};+ // An owner reactivity pref known up front (e.g. passed by the page) gates the+ // look before the first paint so a muted agent never flashes a full aura first.+ if (opts.prefs) controller.setPrefs(opts.prefs);try {await controller.update(agent);if (opts.live !== false && agentId) {diff --git a/src/shared/wallet-format.js b/src/shared/wallet-format.jsnew file mode 100644index 000000000..06a615d5c--- /dev/null+++ b/src/shared/wallet-format.js@@ -0,0 +1,46 @@+/**+ * Wallet-layer formatting — the single source of truth for how the wallet program+ * renders money and addresses. Every wallet surface (chip, HUD, net-worth presence,+ * tip modal) routes through these so the SAME value reads identically everywhere:+ * a compact USD figure in the chip matches the compact figure in the presence bar,+ * and an address is shortened the same way on every card.+ *+ * Two USD tiers exist by design:+ * - `formatWalletUsd` (here) — compact, for dense chrome (chips, inline rows).+ * - `formatNetWorth` (wallet-networth.js) — precise, for the hero net-worth number+ * ($1,500 / $2.00M). Do not collapse the two; they serve different densities.+ */++/**+ * Compact USD label: $0, <$0.01, $9.40, $950, $1.2K, $3.4M, $1.1B.+ * Returns null for non-finite input so callers can omit the figure entirely.+ */+export function formatWalletUsd(n) {+ if (n == null || !Number.isFinite(n)) return null;+ if (n <= 0) return '$0';+ if (n < 0.01) return '<$0.01';+ if (n < 10) return `$${n.toFixed(2)}`;+ if (n < 1000) return `$${Math.round(n)}`;+ if (n < 1e6) return `$${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}K`;+ if (n < 1e9) return `$${(n / 1e6).toFixed(1)}M`;+ return `$${(n / 1e9).toFixed(1)}B`;+}++/**+ * Same compact USD tier as `formatWalletUsd`, but never null — coerces a+ * missing/NaN value to `$0`. Use where the UI must always show a figure.+ */+export function formatWalletUsdSafe(n) {+ const v = Number(n);+ return formatWalletUsd(Number.isFinite(v) ? v : 0) ?? '$0';+}++/**+ * Shorten an address / mint / id for display: head + ellipsis + tail.+ * Returns the input unchanged when it is already short enough to show in full.+ */+export function shortAddress(value, head = 4, tail = 4) {+ const s = String(value || '');+ if (s.length <= head + tail + 1) return s;+ return `${s.slice(0, head)}…${s.slice(-tail)}`;+}diff --git a/src/voice/talk-controller.js b/src/voice/talk-controller.jsindex e6b7587bc..8686ae9b0 100644--- a/src/voice/talk-controller.js+++ b/src/voice/talk-controller.js@@ -47,7 +47,7 @@ export class TalkController {* @param {(err: Error) => void} [opts.onError]* @param {{ attach: Function, setMouthShape: Function }} opts.mouthTarget*/- constructor({ avatar, systemPromptFn, onMessage, onStateChange, onError, mouthTarget }) {+ constructor({ avatar, systemPromptFn, onMessage, onStateChange, onError, mouthTarget, commandInterceptor }) {if (!avatar?.id) throw new Error('TalkController: avatar.id required');if (!mouthTarget) throw new Error('TalkController: mouthTarget required');this.avatar = avatar;@@ -56,6 +56,10 @@ export class TalkController {this.onStateChange = onStateChange || (() => {});this.onError = onError || ((e) => log.warn('[talk]', e?.message));this.mouthTarget = mouthTarget;+ // Optional async hook: gets first crack at a final transcript. If it returns+ // true, the utterance was handled out-of-band (e.g. a wallet command) and the+ // normal chat round-trip is skipped. Used by the Conversational Wallet.+ this.commandInterceptor = commandInterceptor || null;this._state = 'idle';this._history = [];@@ -160,11 +164,49 @@ export class TalkController {this._voicePromise = null;}+ /** Recent conversation turns (for grounding an out-of-band command parse). */+ get history() {+ return this._history.slice();+ }++ /**+ * Voice a line through the avatar WITHOUT a chat round-trip — same TTS + lipsync+ * path as a reply. Used by the Conversational Wallet to speak read-backs,+ * clarifying questions, and confirmations in character.+ */+ async speakText(text) {+ const trimmed = String(text || '').trim();+ if (!trimmed) return;+ try {+ await this._speak(trimmed);+ } catch (err) {+ this.onError(err);+ }+ }+// ── pipeline ─────────────────────────────────────────────────────────async _handleTranscript(transcript) {this.onMessage({ role: 'user', content: transcript });this._history.push({ role: 'user', content: transcript });++ // Wallet commands (and any other registered interceptor) get first crack at+ // the utterance. A handled command never reaches the chat model — the+ // interceptor owns the read-back, confirm, and execution path.+ if (this.commandInterceptor) {+ this._setState('thinking');+ let handled = false;+ try {+ handled = await this.commandInterceptor(transcript);+ } catch (err) {+ this.onError(err);+ }+ if (handled) {+ this._setState('idle');+ return;+ }+ }+this._setState('thinking');let replyText = '';diff --git a/src/voice/talk-mode.js b/src/voice/talk-mode.jsindex 53b4f69bc..07076655c 100644--- a/src/voice/talk-mode.js+++ b/src/voice/talk-mode.js@@ -20,6 +20,7 @@ import { AvatarMouthTarget } from './avatar-morph-target.js';import { TalkController } from './talk-controller.js';import { openVoiceCloneModal } from './voice-clone-modal.js';import { nextPreset, PRESET_LABELS } from './camera-presets.js';+import { WalletIntentController } from './wallet-intent.js';import { log } from '../shared/log.js';let activeSession = null;@@ -62,6 +63,9 @@ export function openTalkMode({ avatar, systemPromptFn }) {const frameLabel = frameBtn?.querySelector('.tws-talk-frame-label');const emoteBar = overlay.querySelector('.tws-talk-emotes');const lipsyncNotice = overlay.querySelector('.tws-talk-lipsync-notice');+ const textbar = overlay.querySelector('.tws-talk-textbar');+ const textInput = overlay.querySelector('.tws-talk-input');+ const walletHintBtn = overlay.querySelector('.tws-talk-wallet-hint');nameEl.textContent = avatar.name || 'Avatar';// Owner-only affordance: `owner_id` is stripped from the API response for@@ -113,6 +117,60 @@ export function openTalkMode({ avatar, systemPromptFn }) {onError: (e) => showError(errEl, e.message),});+ // ── Conversational Wallet (owner-only) ──────────────────────────────+ // Only the owner can move funds — `owner_id` survives in the API response only+ // for the owner (stripped for visitors). With an agent_id we can talk-to-trade.+ let walletCtl = null;+ if (isOwner && avatar.agent_id) {+ const network = avatar.wallet_network === 'devnet' ? 'devnet' : 'mainnet';+ let walletBalance = null;+ refreshWalletBalance(avatar.agent_id, network).then((b) => { walletBalance = b; });++ walletCtl = new WalletIntentController({+ agentId: avatar.agent_id,+ network,+ mountEl: overlay,+ getState: () => ({+ balanceSol: walletBalance,+ history: controller.history.slice(-6),+ }),+ speak: (text) => controller.speakText(text),+ appendTranscript: (role, content) => appendTranscript(transcriptEl, { role, content }),+ onFlourish: () => {+ scene.getEmoteController?.()?.play('celebrate').catch(() => {});+ // Funds just moved — re-read the balance so the next command is grounded.+ refreshWalletBalance(avatar.agent_id, network).then((b) => { walletBalance = b; });+ },+ onManualFallback: () =>+ showError(errEl, 'Voice trading is offline — open the wallet card on this agent to trade manually.'),+ });+ controller.commandInterceptor = (transcript) => walletCtl.handle(transcript);++ // Discoverable affordance: a one-tap example that drops a starter command into+ // the text box so owners learn the capability exists.+ if (walletHintBtn) {+ walletHintBtn.textContent = '💸 Try: “sell half my $THREE” · “tip 0.1 SOL to …”';+ walletHintBtn.hidden = false;+ walletHintBtn.addEventListener('click', () => {+ textInput.value = 'tip 0.05 SOL to ';+ textInput.focus();+ });+ }+ }++ // ── Text input (mic-free path — works for chat and wallet commands) ──+ if (textbar) {+ textbar.addEventListener('submit', (e) => {+ e.preventDefault();+ const text = textInput.value.trim();+ if (!text) return;+ if (controller.state !== 'idle' && controller.state !== 'speaking') return;+ controller.stop();+ textInput.value = '';+ controller.say(text).catch((err) => showError(errEl, err.message));+ });+ }+// ── Hold-to-talk ───────────────────────────────────────────────────const startHold = (ev) => {ev.preventDefault();@@ -175,6 +233,9 @@ export function openTalkMode({ avatar, systemPromptFn }) {function close() {if (unloading) return;unloading = true;+ try {+ walletCtl?.dispose();+ } catch {}try {controller?.stop();} catch {}@@ -221,10 +282,16 @@ const TEMPLATE = `<div class="tws-talk-emotes" hidden role="toolbar" aria-label="Emote shortcuts"></div><div class="tws-talk-transcript" aria-live="polite"></div><div class="tws-talk-controls">+ <button class="tws-talk-wallet-hint" type="button" hidden></button><button class="tws-talk-hold" type="button" aria-label="Hold to talk"><span class="tws-talk-hold-dot"></span><span class="tws-talk-hold-label">Hold to talk</span></button>+ <form class="tws-talk-textbar" autocomplete="off">+ <input class="tws-talk-input" type="text" inputmode="text"+ placeholder="Type a message…" aria-label="Type a message or wallet command" />+ <button class="tws-talk-send" type="submit" aria-label="Send message">↑</button>+ </form><div class="tws-talk-status" data-state="idle">Ready</div></div><div class="tws-talk-error" role="alert" hidden></div>@@ -243,6 +310,22 @@ function setStatus(el, state) {el.textContent = STATUS_LABEL[state] || state;}+// Best-effort SOL balance read to ground the wallet parser ("half my SOL", "max").+// Returns null on any failure — the parser then asks for an explicit amount.+async function refreshWalletBalance(agentId, network) {+ try {+ const r = await fetch(+ `/api/agents/${encodeURIComponent(agentId)}/solana?network=${encodeURIComponent(network)}`,+ { credentials: 'include' },+ );+ if (!r.ok) return null;+ const j = await r.json();+ return typeof j?.data?.sol === 'number' ? j.data.sol : null;+ } catch {+ return null;+ }+}+function renderEmoteBar(barEl, emotes, errEl) {if (!barEl || !emotes) return;const defs = emotes.getBarDefs();@@ -477,6 +560,39 @@ const TALK_CSS = `0%, 100% { opacity: 1; }50% { opacity: 0.4; }}+.tws-talk-wallet-hint {+ background: rgba(139,92,246,0.1);+ border: 1px solid rgba(139,92,246,0.28);+ color: rgba(196,181,253,0.95);+ font-family: inherit; font-size: 11.5px; font-weight: 600;+ padding: 6px 13px; border-radius: 999px; cursor: pointer;+ max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ transition: background 0.15s, border-color 0.15s, transform 0.1s;+}+.tws-talk-wallet-hint:hover { background: rgba(139,92,246,0.18); border-color: rgba(139,92,246,0.45); transform: translateY(-1px); }+.tws-talk-wallet-hint:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+.tws-talk-textbar {+ display: flex; align-items: center; gap: 8px;+ width: min(440px, 100%);+}+.tws-talk-input {+ flex: 1; min-width: 0;+ background: rgba(255,255,255,0.05);+ border: 1px solid rgba(255,255,255,0.14);+ color: #fafafa; font-family: inherit; font-size: 14px;+ padding: 10px 14px; border-radius: 999px;+ transition: border-color 0.15s, background 0.15s;+}+.tws-talk-input::placeholder { color: #71717a; }+.tws-talk-input:focus { outline: none; border-color: rgba(139,92,246,0.5); background: rgba(255,255,255,0.08); }+.tws-talk-send {+ flex-shrink: 0; width: 40px; height: 40px; border-radius: 50%;+ background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.14);+ color: #fafafa; font-size: 17px; line-height: 1; cursor: pointer;+ transition: background 0.15s, border-color 0.15s, transform 0.1s;+}+.tws-talk-send:hover { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.28); transform: translateY(-1px); }+.tws-talk-send:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }.tws-talk-status {font-size: 11px;letter-spacing: 0.08em; text-transform: uppercase;diff --git a/src/voice/wallet-intent.js b/src/voice/wallet-intent.jsnew file mode 100644index 000000000..de44eda69--- /dev/null+++ b/src/voice/wallet-intent.js@@ -0,0 +1,668 @@+/**+ * Conversational Wallet — the talk-to-trade layer for an owner's agent.+ *+ * owner speaks/types ─▶ heuristic gate ─▶ /api/agents/:id/solana/intent+ * │ (Claude tool use → strict intent)+ * ▼+ * resolve amounts vs REAL balances/holdings+ * │+ * ▼+ * REAL preview (trade quote) / simulate (withdraw)+ * │+ * ▼+ * read-back card ── explicit confirm (tap or "yes") ──▶+ * │+ * ▼+ * REAL task-05 trade / withdraw endpoint (owner-only, CSRF,+ * spend-policy gated, audited) ─▶ signature + explorer link+ *+ * Nothing here signs or moves funds on its own path — it calls the same endpoints+ * the wallet HUD uses. Misunderstanding is treated as a safety event: the parsed+ * intent is shown next to the raw words, "cancel" is always one tap/word away, and+ * a confirm times out untouched after 30s. The only coin promoted is $THREE; any+ * other mint is a runtime snipe target the owner supplied.+ */++import {+ previewAgentTrade,+ executeAgentTrade,+ fetchAgentHoldings,+} from '../agent-solana-wallet.js';+import { getSolPriceUsd } from '../shared/usd-price.js';+import { consumeCsrfToken } from '../api.js';+import { log } from '../shared/log.js';++const DEFAULT_SLIPPAGE_BPS = 300; // 3% — matches the trade engine default+const CONFIRM_TIMEOUT_MS = 30_000;+const SOL_FEE_HEADROOM = 0.01; // leave room for fees/rent on a percent/max buy+const CONFIRM_WORDS = /\b(yes|yep|yeah|confirm|do it|send it|go|approve|proceed)\b/i;+const CANCEL_WORDS = /\b(no|nope|cancel|stop|abort|nevermind|never mind|wait)\b/i;++// Heuristic gate: does this utterance even look like a money command? Only matches+// route to the (paid) intent parser; everything else stays normal chat. A false+// positive is harmless — the parser returns action:"none" and we hand back to chat.+const MONEY_VERBS = /\b(tip|send|pay|swap|snipe|buy|sell|trade|withdraw|deposit|cash\s?out|convert)\b/i;+const MONEY_NOUNS = /(\bSOL\b|\bUSDC\b|\$?THREE\b|\bsolana\b|◎|\$\d|\bdollars?\b|\bcoins?\b|\btokens?\b|\bwallet\b)/i;++export function isWalletCommand(text) {+ const s = String(text || '');+ if (!MONEY_VERBS.test(s)) return false;+ // A bare verb ("buy") with no money noun/number is too weak — require a hint of+ // an asset or amount so ordinary chat ("sell me on this idea") doesn't trip it.+ return MONEY_NOUNS.test(s) || /\b\d+(\.\d+)?\b/.test(s) || /\b(half|all|everything|max)\b/i.test(s);+}++export class WalletIntentController {+ /**+ * @param {object} o+ * @param {string} o.agentId+ * @param {string} o.network 'mainnet' | 'devnet'+ * @param {HTMLElement} o.mountEl overlay element to render the confirm card into+ * @param {() => {balanceSol:number|null, history:Array}} o.getState+ * @param {(text:string)=>Promise<void>} o.speak voice a line through the avatar+ * @param {(role:'user'|'assistant', text:string)=>void} o.appendTranscript+ * @param {() => void} [o.onFlourish] fire the avatar's celebrate emote on a real tx+ * @param {() => void} [o.onManualFallback] open the wallet HUD form+ */+ constructor({ agentId, network, mountEl, getState, speak, appendTranscript, onFlourish, onManualFallback }) {+ this.agentId = agentId;+ this.network = network || 'mainnet';+ this.mountEl = mountEl;+ this.getState = getState || (() => ({ balanceSol: null, history: [] }));+ this.speak = speak || (async () => {});+ this.appendTranscript = appendTranscript || (() => {});+ this.onFlourish = onFlourish || (() => {});+ this.onManualFallback = onManualFallback || null;+ this._pending = null; // { plan } awaiting confirm+ this._card = null;+ this._timer = null;+ this._holdings = null; // cache within a session+ injectStylesOnce();+ }++ /**+ * Interceptor entry. Returns true when this layer handled the utterance (chat is+ * skipped), false to let normal conversation proceed.+ */+ async handle(utterance) {+ const text = String(utterance || '').trim();+ if (!text) return false;++ // A confirm is on the table — interpret yes / no first, before anything else.+ if (this._pending) {+ if (CANCEL_WORDS.test(text)) {+ this._cancel('You said cancel — nothing was sent.');+ return true;+ }+ if (CONFIRM_WORDS.test(text)) {+ await this._execute();+ return true;+ }+ await this.speak('Say "yes" to confirm, or "cancel" to call it off.');+ return true;+ }++ if (!isWalletCommand(text)) return false;++ let parsed;+ try {+ parsed = await this._parse(text);+ } catch (err) {+ if (err.code === 'intent_unavailable') {+ await this._fail('Voice trading isn\'t set up here — opening the wallet form instead.');+ this.onManualFallback?.();+ return true;+ }+ await this._fail(err.message || 'I couldn\'t understand that — try again or use the wallet form.');+ return true;+ }++ const intent = parsed.intent;+ if (!intent || intent.action === 'none') return false; // hand back to chat+ if (intent.action === 'clarify' || intent.confidence < 0.45) {+ const q = intent.clarifying_question || 'Could you say that again with the amount and destination?';+ this.appendTranscript('assistant', q);+ await this.speak(q);+ return true;+ }++ // Resolve the intent against REAL balances/holdings, then quote it for real.+ let plan;+ try {+ plan = await this._buildPlan(intent);+ } catch (err) {+ if (err.clarify) {+ this.appendTranscript('assistant', err.message);+ await this.speak(err.message);+ return true;+ }+ await this._fail(err.message || 'I couldn\'t prepare that trade.');+ return true;+ }++ this._pending = { plan, rawWords: text };+ this._renderConfirm(plan, text);+ this.appendTranscript('assistant', plan.readback);+ await this.speak(`${plan.readback} Confirm?`);+ return true;+ }++ /** Hard-abort any in-flight confirm (overlay closing, "stop" mid-flow). */+ dispose() {+ this._clearCard();+ this._pending = null;+ }++ // ── parse ──────────────────────────────────────────────────────────────────++ async _parse(utterance) {+ const { balanceSol, history } = this.getState();+ const holdings = await this._getHoldings();+ const resp = await fetch(`/api/agents/${encodeURIComponent(this.agentId)}/solana/intent`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ utterance,+ network: this.network,+ history: (history || []).slice(-6),+ context: {+ balance_sol: typeof balanceSol === 'number' ? balanceSol : null,+ holdings: holdings.map((h) => ({ mint: h.mint, symbol: h.symbol || null, ui_amount: h.ui_amount })),+ },+ }),+ });+ const j = await resp.json().catch(() => ({}));+ if (!resp.ok) {+ const e = new Error(j.error_description || j.error?.message || `parse failed (${resp.status})`);+ e.code = typeof j.error === 'string' ? j.error : j.error?.code;+ throw e;+ }+ return j.data;+ }++ async _getHoldings() {+ if (this._holdings) return this._holdings;+ try {+ const data = await fetchAgentHoldings(this.agentId, this.network);+ this._holdings = Array.isArray(data?.tokens) ? data.tokens : [];+ } catch {+ this._holdings = [];+ }+ return this._holdings;+ }++ // ── plan (resolve amounts + real quote) ──────────────────────────────────────++ async _buildPlan(intent) {+ const slippageBps = intent.slippage_pct != null ? Math.round(intent.slippage_pct * 100) : DEFAULT_SLIPPAGE_BPS;+ if (intent.action === 'buy' || intent.action === 'snipe') {+ return this._planBuy(intent, slippageBps);+ }+ if (intent.action === 'sell') {+ return this._planSell(intent, slippageBps);+ }+ if (intent.action === 'tip' || intent.action === 'withdraw') {+ return this._planTransfer(intent);+ }+ throw clarifyErr('I\'m not sure what to do with that — try "buy", "sell", "tip", or "withdraw".');+ }++ async _planBuy(intent, slippageBps) {+ const mint = intent.target?.mint;+ if (!mint) throw clarifyErr('Which token should I buy? Paste its mint address or say "$THREE".');+ const solAmount = await this._resolveSolSpend(intent);+ const quote = await previewAgentTrade({+ agentId: this.agentId, side: 'buy', mint, solAmount, slippageBps, network: this.network,+ });+ return this._tradePlan({+ kind: intent.action === 'snipe' ? 'snipe' : 'buy',+ side: 'buy', mint, solAmount, slippageBps, quote, intent,+ });+ }++ async _planSell(intent, slippageBps) {+ const mint = intent.target?.mint;+ if (!mint) throw clarifyErr('Which token should I sell? Name it or paste its mint.');+ const holdings = await this._getHoldings();+ const held = holdings.find((h) => h.mint === mint);+ if (!held || !(Number(held.ui_amount) > 0)) {+ throw clarifyErr('You don\'t hold any of that token, so there\'s nothing to sell.');+ }+ const rawTotal = BigInt(held.amount_raw);+ let raw;+ if (intent.amount_unit === 'max' || (intent.amount == null && /all|everything/i.test(intent.readback))) {+ raw = rawTotal;+ } else if (intent.amount_unit === 'percent' && intent.amount != null) {+ raw = (rawTotal * BigInt(Math.round(Math.min(100, intent.amount) * 100))) / 10000n;+ } else if (intent.amount_unit === 'token' && intent.amount != null) {+ raw = BigInt(Math.floor(intent.amount * 10 ** held.decimals));+ } else {+ throw clarifyErr('How much should I sell — a number of tokens, a percentage, or all of it?');+ }+ if (raw <= 0n) throw clarifyErr('That sell amount rounds to zero — try a larger amount.');+ if (raw > rawTotal) raw = rawTotal;+ const quote = await previewAgentTrade({+ agentId: this.agentId, side: 'sell', mint, tokenAmountRaw: raw.toString(), slippageBps, network: this.network,+ });+ return this._tradePlan({+ kind: 'sell', side: 'sell', mint, tokenAmountRaw: raw.toString(),+ sellUi: Number(raw) / 10 ** held.decimals, symbol: held.symbol || shortMint(mint),+ slippageBps, quote, intent,+ });+ }++ _tradePlan({ kind, side, mint, solAmount, tokenAmountRaw, sellUi, symbol, slippageBps, quote, intent }) {+ const tokenSymbol = symbol || (intent.target?.symbol) || shortMint(mint);+ const rows = [];+ if (side === 'buy') {+ rows.push(['Spend', `◎${fmt(solAmount, 4)} SOL`]);+ rows.push(['Receive (est.)', `${fmt(quote.out?.amount, 4)} ${tokenSymbol}`]);+ } else {+ rows.push(['Sell', `${fmt(sellUi, 4)} ${tokenSymbol}`]);+ rows.push(['Receive (est.)', `◎${fmt(quote.out?.amount, 4)} SOL`]);+ }+ if (quote.usd != null) rows.push(['Value', `≈ $${fmt(quote.usd, 2)}`]);+ if (quote.price_impact_pct != null) rows.push(['Price impact', `${fmt(quote.price_impact_pct, 2)}%`]);+ rows.push(['Slippage', `${(slippageBps / 100).toFixed(1)}%`]);+ rows.push(['Network', this.network]);++ const block = quote.guard || quote.funds || (quote.firewall?.verdict === 'block' ? quote.firewall : null);+ return {+ kind,+ title: kind === 'snipe' ? `Snipe ${tokenSymbol}` : side === 'buy' ? `Buy ${tokenSymbol}` : `Sell ${tokenSymbol}`,+ readback: intent.readback || (side === 'buy'+ ? `Buy ${tokenSymbol} with ${fmt(solAmount, 4)} SOL.`+ : `Sell ${fmt(sellUi, 4)} ${tokenSymbol} for SOL.`),+ rows,+ blocked: block ? (block.message || 'This trade is blocked by your safety policy.') : null,+ execute: () =>+ executeAgentTrade({+ agentId: this.agentId, side, mint, solAmount, tokenAmountRaw, slippageBps,+ network: this.network, idempotencyKey: cryptoRandom(),+ }),+ };+ }++ async _planTransfer(intent) {+ const dest = intent.destination;+ if (!dest) throw clarifyErr('Where should I send it? Give me a Solana address or a .sol name.');+ const asset = intent.asset || { kind: 'sol' };+ const isSol = asset.kind === 'sol' || asset.kind === 'none';+ const assetField = isSol ? 'SOL' : asset.mint || (asset.kind === 'usdc' ? USDC_MINT[this.network] : null);+ if (!assetField) throw clarifyErr('Which asset should I send — SOL, USDC, or a specific token?');++ let amountField;+ if (intent.amount_unit === 'max') {+ amountField = 'max';+ } else if (intent.amount != null) {+ amountField = intent.amount_unit === 'USD' && isSol ? await this._usdToSol(intent.amount) : intent.amount;+ } else {+ throw clarifyErr('How much should I send?');+ }++ // Real simulate — never touches the key; returns the true amount + USD + any+ // spend-policy rejection before the owner ever confirms.+ const sim = await this._simulateWithdraw({ asset: assetField, amount: amountField, destination: dest });+ const human = sim.amount != null ? sim.amount : amountField;+ const symbol = isSol ? 'SOL' : asset.kind === 'usdc' ? 'USDC' : shortMint(assetField);+ const verb = intent.action === 'tip' ? 'Tip' : 'Withdraw';+ const destShown = intent.destination_label ? `${intent.destination_label} (${shortMint(dest)})` : shortMint(dest);+ const rows = [+ ['Send', `${isSol ? '◎' : ''}${fmt(human, isSol ? 4 : 4)} ${symbol}`],+ ['To', destShown],+ ];+ if (sim.usd != null) rows.push(['Value', `≈ $${fmt(sim.usd, 2)}`]);+ rows.push(['Network', this.network]);++ return {+ kind: intent.action,+ title: `${verb} ${symbol}`,+ readback: intent.readback || `${verb} ${fmt(human, 4)} ${symbol} to ${destShown}.`,+ rows,+ blocked: sim.blocked || null,+ execute: () =>+ this._executeWithdraw({ asset: assetField, amount: amountField, destination: dest }),+ };+ }++ // ── amount resolution ────────────────────────────────────────────────────────++ async _resolveSolSpend(intent) {+ const { balanceSol } = this.getState();+ const unit = intent.amount_unit;+ const amt = intent.amount;+ if (unit === 'SOL' && amt != null) return amt;+ if (unit === 'USD' && amt != null) return this._usdToSol(amt);+ if ((unit === 'percent' || unit === 'max') && balanceSol != null) {+ const spendable = Math.max(0, balanceSol - SOL_FEE_HEADROOM);+ const sol = unit === 'max' ? spendable : spendable * (Math.min(100, amt ?? 0) / 100);+ if (!(sol > 0)) throw clarifyErr('There isn\'t enough SOL in the wallet to cover that and fees.');+ return round(sol, 4);+ }+ if (unit === 'USDC') {+ throw clarifyErr('Trades here are priced in SOL — how much SOL should I spend?');+ }+ throw clarifyErr('How much SOL should I spend?');+ }++ async _usdToSol(usd) {+ const price = await getSolPriceUsd().catch(() => null);+ if (!price) throw clarifyErr('I can\'t fetch the SOL price right now — tell me the amount in SOL instead.');+ return round(usd / price, 4);+ }++ // ── withdraw plumbing ────────────────────────────────────────────────────────++ async _simulateWithdraw({ asset, amount, destination }) {+ const resp = await fetch(`/api/agents/${encodeURIComponent(this.agentId)}/solana/withdraw`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ asset, amount, destination, network: this.network, simulate: true }),+ });+ const j = await resp.json().catch(() => ({}));+ if (!resp.ok) {+ // A spend-policy / balance rejection on simulate is the real, honest answer —+ // surface it as a blocked plan rather than throwing.+ return { blocked: j.error_description || j.error?.message || `That transfer was rejected (${resp.status}).` };+ }+ return { amount: j.data?.amount ?? null, usd: j.data?.usd ?? null, blocked: j.data?.err ? 'Simulation reverted on-chain.' : null };+ }++ async _executeWithdraw({ asset, amount, destination }) {+ const headers = { 'content-type': 'application/json' };+ const token = await consumeCsrfToken();+ if (token) headers['x-csrf-token'] = token;+ const resp = await fetch(`/api/agents/${encodeURIComponent(this.agentId)}/solana/withdraw`, {+ method: 'POST',+ credentials: 'include',+ headers,+ body: JSON.stringify({ asset, amount, destination, network: this.network, idempotency_key: cryptoRandom() }),+ });+ const j = await resp.json().catch(() => ({}));+ if (!resp.ok || (j.error != null && j.data == null)) {+ const e = new Error(j.error_description || j.error?.message || `Withdrawal failed (${resp.status})`);+ e.signature = j.signature || j.data?.signature || null;+ e.explorer = j.explorer || j.data?.explorer || null;+ throw e;+ }+ return j.data;+ }++ // ── execute (shared) ─────────────────────────────────────────────────────────++ async _execute() {+ if (!this._pending) return;+ const { plan } = this._pending;+ this._pending = null;+ this._setCardBusy(plan);+ try {+ const result = await plan.execute();+ this._clearCard();+ const sig = result.signature;+ const explorer = result.explorer;+ const line = `Done — ${plan.title.toLowerCase()} confirmed.`;+ this.appendTranscript('assistant', explorer ? `${line} ${explorer}` : line);+ if (explorer) this._renderReceipt(plan, sig, explorer);+ await this.speak(`${line} The signature's in the chat.`);+ this.onFlourish();+ } catch (err) {+ this._clearCard();+ const extra = err.explorer ? ` You can check it here: ${err.explorer}` : '';+ await this._fail(`${err.message}${extra}`);+ }+ }++ _cancel(line) {+ this._pending = null;+ this._clearCard();+ this.appendTranscript('assistant', line);+ this.speak(line).catch(() => {});+ }++ async _fail(message) {+ this.appendTranscript('assistant', message);+ await this.speak(message).catch(() => {});+ }++ // ── confirm card UI ──────────────────────────────────────────────────────────++ _renderConfirm(plan, rawWords) {+ this._clearCard();+ const card = document.createElement('div');+ card.className = 'tws-wic';+ card.setAttribute('role', 'dialog');+ card.setAttribute('aria-modal', 'true');+ card.setAttribute('aria-label', `Confirm: ${plan.title}`);+ const rowsHtml = plan.rows+ .map(+ ([k, v]) =>+ `<div class="tws-wic-row"><span class="tws-wic-k">${esc(k)}</span><span class="tws-wic-v">${esc(v)}</span></div>`,+ )+ .join('');+ card.innerHTML = `+ <div class="tws-wic-head">+ <span class="tws-wic-badge" aria-hidden="true">◎</span>+ <span class="tws-wic-title">${esc(plan.title)}</span>+ </div>+ <div class="tws-wic-said">“${esc(rawWords)}”</div>+ <div class="tws-wic-rows">${rowsHtml}</div>+ ${plan.blocked ? `<div class="tws-wic-blocked" role="alert">${esc(plan.blocked)}</div>` : ''}+ <div class="tws-wic-actions">+ <button class="tws-wic-cancel" type="button">Cancel</button>+ <button class="tws-wic-confirm" type="button"${plan.blocked ? ' disabled' : ''}>+ Confirm <span class="tws-wic-count" aria-hidden="true">30</span>+ </button>+ </div>+ <div class="tws-wic-hint">Or say “yes” to confirm, “cancel” to stop.</div>+ `;+ this.mountEl.appendChild(card);+ this._card = card;++ const confirmBtn = card.querySelector('.tws-wic-confirm');+ const cancelBtn = card.querySelector('.tws-wic-cancel');+ cancelBtn.addEventListener('click', () => this._cancel('Cancelled — nothing was sent.'));+ if (!plan.blocked) {+ confirmBtn.addEventListener('click', () => this._execute());+ confirmBtn.focus();+ } else {+ cancelBtn.focus();+ }++ card._onKey = (e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ this._cancel('Cancelled — nothing was sent.');+ }+ };+ card.addEventListener('keydown', card._onKey);++ // 30-second auto-cancel — funds stay untouched if the owner walks away.+ if (!plan.blocked) {+ let left = 30;+ const countEl = card.querySelector('.tws-wic-count');+ this._timer = setInterval(() => {+ left -= 1;+ if (countEl) countEl.textContent = String(Math.max(0, left));+ if (left <= 0) this._cancel('Confirmation timed out — nothing was sent.');+ }, 1000);+ }+ }++ _setCardBusy(plan) {+ if (!this._card) return;+ this._stopTimer();+ this._card.classList.add('tws-wic-busy');+ const actions = this._card.querySelector('.tws-wic-actions');+ if (actions) actions.innerHTML = `<div class="tws-wic-sending">Sending… <span class="tws-wic-spin" aria-hidden="true"></span></div>`;+ }++ _renderReceipt(plan, sig, explorer) {+ const card = document.createElement('div');+ card.className = 'tws-wic tws-wic-done';+ card.setAttribute('role', 'status');+ card.innerHTML = `+ <div class="tws-wic-head">+ <span class="tws-wic-badge tws-wic-ok" aria-hidden="true">✓</span>+ <span class="tws-wic-title">${esc(plan.title)} confirmed</span>+ </div>+ ${sig ? `<div class="tws-wic-said tws-wic-sig">${esc(shortMint(sig))}</div>` : ''}+ <div class="tws-wic-actions">+ <a class="tws-wic-explorer" href="${esc(explorer)}" target="_blank" rel="noopener noreferrer">View on explorer ↗</a>+ <button class="tws-wic-cancel" type="button">Done</button>+ </div>+ `;+ this.mountEl.appendChild(card);+ this._card = card;+ const doneBtn = card.querySelector('.tws-wic-cancel');+ doneBtn.addEventListener('click', () => this._clearCard());+ doneBtn.focus();+ setTimeout(() => { if (this._card === card) this._clearCard(); }, 12_000);+ }++ _clearCard() {+ this._stopTimer();+ if (this._card) {+ try { this._card.remove(); } catch {}+ this._card = null;+ }+ }++ _stopTimer() {+ if (this._timer) {+ clearInterval(this._timer);+ this._timer = null;+ }+ }+}++// ── helpers ──────────────────────────────────────────────────────────────────────++const USDC_MINT = {+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',+};++function clarifyErr(message) {+ const e = new Error(message);+ e.clarify = true;+ return e;+}++function cryptoRandom() {+ try {+ return crypto.randomUUID();+ } catch {+ return `wic-${Date.now()}-${Math.floor(Math.random() * 1e9)}`;+ }+}++function fmt(n, dp = 2) {+ const x = Number(n);+ if (!Number.isFinite(x)) return '—';+ return x.toLocaleString('en-US', { maximumFractionDigits: dp });+}++function round(n, dp) {+ const f = 10 ** dp;+ return Math.round(n * f) / f;+}++function shortMint(s) {+ const str = String(s || '');+ return str.length > 12 ? `${str.slice(0, 4)}…${str.slice(-4)}` : str;+}++function esc(s) {+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++function injectStylesOnce() {+ if (typeof document === 'undefined' || document.getElementById('tws-wic-css')) return;+ const el = document.createElement('style');+ el.id = 'tws-wic-css';+ el.textContent = WIC_CSS;+ document.head.appendChild(el);+}++const WALLET_ACCENT = 'rgba(196,181,253,0.9)';+const WIC_CSS = `+.tws-wic {+ position: absolute; left: 50%; bottom: 120px; transform: translateX(-50%);+ width: min(420px, calc(100vw - 32px)); z-index: 30;+ background: rgba(12,12,16,0.92);+ border: 1px solid rgba(139,92,246,0.35);+ border-radius: 16px;+ box-shadow: 0 18px 48px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.03) inset;+ backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px);+ padding: 16px 18px;+ font-family: 'Inter', system-ui, sans-serif; color: #fafafa;+ animation: tws-wic-in 180ms cubic-bezier(0.2,0.8,0.2,1);+}+@keyframes tws-wic-in { from { opacity: 0; transform: translateX(-50%) translateY(8px); } to { opacity: 1; transform: translateX(-50%) translateY(0); } }+.tws-wic-head { display: flex; align-items: center; gap: 9px; margin-bottom: 10px; }+.tws-wic-badge {+ width: 26px; height: 26px; border-radius: 50%; flex-shrink: 0;+ display: inline-flex; align-items: center; justify-content: center;+ font-size: 13px; color: ${WALLET_ACCENT};+ background: rgba(139,92,246,0.14); border: 1px solid rgba(139,92,246,0.3);+}+.tws-wic-ok { color: #4ade80; background: rgba(74,222,128,0.14); border-color: rgba(74,222,128,0.35); }+.tws-wic-title { font-family: 'Space Grotesk', sans-serif; font-weight: 700; font-size: 15px; letter-spacing: -0.01em; }+.tws-wic-said {+ font-size: 12.5px; color: #a1a1aa; font-style: italic;+ margin-bottom: 12px; line-height: 1.4;+ border-left: 2px solid rgba(139,92,246,0.4); padding-left: 9px;+}+.tws-wic-sig { font-family: 'JetBrains Mono', monospace; font-style: normal; }+.tws-wic-rows { display: flex; flex-direction: column; gap: 6px; margin-bottom: 12px; }+.tws-wic-row { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; font-size: 13px; }+.tws-wic-k { color: #71717a; }+.tws-wic-v { font-family: 'JetBrains Mono', monospace; color: #fafafa; text-align: right; word-break: break-word; }+.tws-wic-blocked {+ font-size: 12.5px; line-height: 1.45; color: #fda4af;+ background: rgba(244,63,94,0.1); border: 1px solid rgba(244,63,94,0.32);+ border-radius: 10px; padding: 8px 11px; margin-bottom: 12px;+}+.tws-wic-actions { display: flex; gap: 8px; align-items: center; }+.tws-wic-actions button { flex: 1; }+.tws-wic-confirm {+ background: ${WALLET_ACCENT}; color: #14101f; border: 0;+ font-family: inherit; font-weight: 700; font-size: 14px;+ padding: 11px 14px; border-radius: 10px; cursor: pointer;+ display: inline-flex; align-items: center; justify-content: center; gap: 7px;+ transition: transform 0.1s, box-shadow 0.15s, opacity 0.15s;+}+.tws-wic-confirm:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 6px 18px rgba(139,92,246,0.35); }+.tws-wic-confirm:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+.tws-wic-confirm:disabled { opacity: 0.4; cursor: not-allowed; }+.tws-wic-count {+ font-family: 'JetBrains Mono', monospace; font-size: 11px;+ background: rgba(0,0,0,0.18); border-radius: 6px; padding: 1px 6px; min-width: 22px;+}+.tws-wic-cancel {+ background: rgba(255,255,255,0.06); color: #fafafa;+ border: 1px solid rgba(255,255,255,0.14); font-family: inherit; font-weight: 600;+ font-size: 14px; padding: 11px 14px; border-radius: 10px; cursor: pointer;+ transition: background 0.15s, border-color 0.15s;+}+.tws-wic-cancel:hover { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.25); }+.tws-wic-cancel:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+.tws-wic-explorer {+ flex: 1; text-align: center; text-decoration: none;+ background: rgba(139,92,246,0.14); color: ${WALLET_ACCENT};+ border: 1px solid rgba(139,92,246,0.3); font-weight: 600; font-size: 13px;+ padding: 11px 14px; border-radius: 10px; transition: background 0.15s;+}+.tws-wic-explorer:hover { background: rgba(139,92,246,0.24); }+.tws-wic-hint { font-size: 11px; color: #52525b; text-align: center; margin-top: 9px; }+.tws-wic-sending { display: flex; align-items: center; justify-content: center; gap: 9px; font-size: 13px; color: #d4d4d8; padding: 9px; width: 100%; }+.tws-wic-spin { width: 13px; height: 13px; border: 2px solid rgba(255,255,255,0.2); border-top-color: ${WALLET_ACCENT}; border-radius: 50%; animation: tws-wic-spin 0.7s linear infinite; }+@keyframes tws-wic-spin { to { transform: rotate(360deg); } }+.tws-wic-busy { opacity: 0.92; }+@media (max-width: 600px) { .tws-wic { bottom: 96px; padding: 14px; } }+@media (prefers-reduced-motion: reduce) { .tws-wic { animation: none; } .tws-wic-spin { animation-duration: 1.4s; } }+`;++export const __test = { isWalletCommand };diff --git a/tests/conversational-wallet-intent.test.js b/tests/conversational-wallet-intent.test.jsnew file mode 100644index 000000000..e6ed4deac--- /dev/null+++ b/tests/conversational-wallet-intent.test.js@@ -0,0 +1,129 @@+// Unit tests for the Conversational Wallet parser's safety-critical pure logic:+// api/agents/solana-intent.js → resolveAssetToken + normalizeWalletIntent.+//+// These functions are the boundary between a fuzzy LLM tool output and a real,+// executable wallet intent. The rules they must never break: $THREE is the only+// coin resolved by name; a malformed/ambiguous parse collapses to a clarify (money+// never moves on a guess); amounts and slippage are clamped. The LLM HTTP path and+// DB/auth are not exercised here — only the deterministic normalization.++import { describe, it, expect, vi } from 'vitest';++const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// Stub the heavy server-only imports so importing the handler module is cheap and+// side-effect-free. The pure functions under test don't call any of them.+vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(), authenticateBearer: vi.fn(), extractBearer: vi.fn(),+}));+vi.mock('../api/_lib/http.js', () => ({+ cors: vi.fn(), json: vi.fn(), method: vi.fn(), error: vi.fn(), readJson: vi.fn(), rateLimited: vi.fn(),+}));+vi.mock('../api/_lib/rate-limit.js', () => ({ limits: { chatUser: vi.fn() }, clientIp: vi.fn() }));+vi.mock('../api/_lib/provider-keys.js', () => ({ loadUserProviderKeys: vi.fn(async () => ({})) }));+vi.mock('../src/solana/sns.js', () => ({ resolveSolanaRecipient: vi.fn(async () => ({ address: null })) }));+vi.mock('../api/_lib/networth-model.js', () => ({ THREE_MINT: THREE }));+vi.mock('../api/_lib/agent-trade-guards.js', () => ({+ getSpendLimits: vi.fn(() => ({})), getTradeLimits: vi.fn(() => ({})),+}));++const { resolveAssetToken, normalizeWalletIntent } = await import('../api/agents/solana-intent.js');++describe('resolveAssetToken', () => {+ it('resolves $THREE / three by name to the canonical mint', () => {+ expect(resolveAssetToken('$THREE')).toMatchObject({ kind: 'three', mint: THREE, symbol: '$THREE' });+ expect(resolveAssetToken('three')).toMatchObject({ kind: 'three', mint: THREE });+ expect(resolveAssetToken('THREE')).toMatchObject({ kind: 'three', mint: THREE });+ });++ it('recognises SOL and USDC', () => {+ expect(resolveAssetToken('SOL').kind).toBe('sol');+ expect(resolveAssetToken('solana').kind).toBe('sol');+ expect(resolveAssetToken('usdc').kind).toBe('usdc');+ });++ it('passes a base58 mint through as a runtime target', () => {+ const mint = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';+ expect(resolveAssetToken(mint)).toMatchObject({ kind: 'mint', mint });+ });++ it('flags the canonical mint string as $THREE even when pasted raw', () => {+ expect(resolveAssetToken(THREE)).toMatchObject({ kind: 'three', symbol: '$THREE' });+ });++ it('returns unknown for an unrecognised symbol', () => {+ expect(resolveAssetToken('DOGE').kind).toBe('unknown');+ expect(resolveAssetToken('').kind).toBe('none');+ });+});++describe('normalizeWalletIntent', () => {+ it('maps swap → buy and resolves the $THREE target', () => {+ const out = normalizeWalletIntent({+ action: 'swap', amount: 0.5, amount_unit: 'SOL', destination_or_mint: '$THREE',+ confidence: 0.9, readback: 'Buy $THREE with 0.5 SOL.',+ });+ expect(out.action).toBe('buy');+ expect(out.target).toMatchObject({ kind: 'three', mint: THREE });+ expect(out.amount).toBe(0.5);+ expect(out.amount_unit).toBe('SOL');+ });++ it('keeps snipe distinct and carries the runtime mint', () => {+ const mint = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';+ const out = normalizeWalletIntent({+ action: 'snipe', amount: 0.5, amount_unit: 'SOL', destination_or_mint: mint,+ confidence: 0.8, readback: 'Snipe with 0.5 SOL.',+ });+ expect(out.action).toBe('snipe');+ expect(out.target.mint).toBe(mint);+ });++ it('normalises a withdraw with destination + asset', () => {+ const out = normalizeWalletIntent({+ action: 'withdraw', amount: 2, amount_unit: 'SOL', asset: 'SOL',+ destination_or_mint: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU',+ confidence: 0.95, readback: 'Withdraw 2 SOL.',+ });+ expect(out.action).toBe('withdraw');+ expect(out.asset.kind).toBe('sol');+ expect(out.destination).toBe('7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU');+ expect(out.amount).toBe(2);+ });++ it('collapses an unknown action to none', () => {+ const out = normalizeWalletIntent({ action: 'launch', confidence: 0.9, readback: '' });+ expect(out.action).toBe('none');+ });++ it('preserves a clarify with its question', () => {+ const out = normalizeWalletIntent({+ action: 'clarify', confidence: 0.3, readback: '',+ clarifying_question: 'Which token?',+ });+ expect(out.action).toBe('clarify');+ expect(out.clarifying_question).toBe('Which token?');+ });++ it('supplies a default clarify question when the model omits one', () => {+ const out = normalizeWalletIntent({ action: 'clarify', confidence: 0.3, readback: '' });+ expect(out.clarifying_question).toBeTruthy();+ });++ it('clamps slippage to [0,50] and drops non-positive amounts', () => {+ const out = normalizeWalletIntent({+ action: 'buy', amount: -5, amount_unit: 'SOL', destination_or_mint: '$THREE',+ slippage_pct: 999, confidence: 1.2, readback: 'x',+ });+ expect(out.amount).toBeNull();+ expect(out.slippage_pct).toBe(50);+ expect(out.confidence).toBe(1); // clamped to [0,1]+ });++ it('never throws on garbage input — degrades to none', () => {+ expect(normalizeWalletIntent(null).action).toBe('none');+ expect(normalizeWalletIntent({}).action).toBe('none');+ expect(normalizeWalletIntent('nope').action).toBe('none');+ });+});diff --git a/tests/mirror-engine.test.js b/tests/mirror-engine.test.jsnew file mode 100644index 000000000..e8847632d--- /dev/null+++ b/tests/mirror-engine.test.js@@ -0,0 +1,123 @@+/**+ * Custodial mirror-trade decision engine — pure logic tests.+ * Money-adjacent: every sizing path, leash, list, and skip reason is pinned so a+ * runaway leader can never drain a follower past the first clamp.+ */++import { describe, it, expect } from 'vitest';+import {+ planMirror, normalizeFollowInput, rawMirrorSol, MIN_MIRROR_BUY_SOL,+} from '../api/_lib/mirror-engine.js';++const base = {+ enabled: true,+ sizing_mode: 'proportional',+ fixed_sol: 0.2,+ proportion_pct: 100,+ pct_balance: 10,+ max_per_trade_sol: null,+ daily_budget_sol: null,+ min_leader_sol: 0,+ copy_sells: true,+ mint_allowlist: [],+ mint_denylist: [],+};+const follow = (over = {}) => ({ ...base, ...over });+const buy = (leaderSol = 1, mint = 'MintAAA') => ({ side: 'buy', mint, leaderSol });+const sell = (mint = 'MintAAA') => ({ side: 'sell', mint });++describe('rawMirrorSol', () => {+ it('fixed → the fixed amount regardless of leader size', () => {+ expect(rawMirrorSol(follow({ sizing_mode: 'fixed' }), { leaderSol: 5 })).toBe(0.2);+ });+ it('proportional → leader size × proportion', () => {+ expect(rawMirrorSol(follow({ proportion_pct: 50 }), { leaderSol: 2 })).toBe(1);+ expect(rawMirrorSol(follow({ proportion_pct: 100 }), { leaderSol: 0.5 })).toBe(0.5);+ });+ it('pct_balance → percent of the follower balance, NaN without a balance', () => {+ expect(rawMirrorSol(follow({ sizing_mode: 'pct_balance', pct_balance: 10 }), { followerBalanceSol: 4 })).toBe(0.4);+ expect(Number.isNaN(rawMirrorSol(follow({ sizing_mode: 'pct_balance' }), {}))).toBe(true);+ });+});++describe('planMirror — gates', () => {+ it('kill switch blocks everything', () => {+ expect(planMirror({ follow: follow(), leaderTrade: buy(), killed: true }).reason).toBe('mirror_killed');+ });+ it('disabled follow is skipped', () => {+ expect(planMirror({ follow: follow({ enabled: false }), leaderTrade: buy() }).reason).toBe('follow_disabled');+ });+ it('denylisted mint is skipped (both directions)', () => {+ const f = follow({ mint_denylist: ['MintAAA'] });+ expect(planMirror({ follow: f, leaderTrade: buy(1, 'MintAAA') }).reason).toBe('mint_denylisted');+ expect(planMirror({ follow: f, leaderTrade: sell('MintAAA') }).reason).toBe('mint_denylisted');+ });+ it('allowlist excludes everything not on it', () => {+ const f = follow({ mint_allowlist: ['Other'] });+ expect(planMirror({ follow: f, leaderTrade: buy(1, 'MintAAA') }).reason).toBe('mint_not_allowlisted');+ expect(planMirror({ follow: f, leaderTrade: buy(1, 'Other'), followerBalanceSol: 10 }).action).toBe('mirror');+ });+});++describe('planMirror — sells', () => {+ it('mirrors an exit when copy_sells is on', () => {+ const d = planMirror({ follow: follow(), leaderTrade: sell() });+ expect(d).toMatchObject({ action: 'mirror', side: 'sell', reason: 'mirror_exit' });+ });+ it('skips an exit when copy_sells is off', () => {+ expect(planMirror({ follow: follow({ copy_sells: false }), leaderTrade: sell() }).reason).toBe('sells_disabled');+ });+});++describe('planMirror — buy sizing + leashes', () => {+ it('proportional sizing, fully funded → mirror at the sized amount', () => {+ const d = planMirror({ follow: follow({ proportion_pct: 50 }), leaderTrade: buy(2), followerBalanceSol: 10 });+ expect(d).toMatchObject({ action: 'mirror', side: 'buy', order_sol: 1 });+ });+ it('per-trade cap clamps the order down', () => {+ const d = planMirror({ follow: follow({ max_per_trade_sol: 0.3 }), leaderTrade: buy(2), followerBalanceSol: 10 });+ expect(d.order_sol).toBe(0.3);+ });+ it('leader buy below the floor is skipped', () => {+ const d = planMirror({ follow: follow({ min_leader_sol: 1 }), leaderTrade: buy(0.5), followerBalanceSol: 10 });+ expect(d.reason).toBe('below_min_leader');+ });+ it('daily budget remaining clamps and can exhaust', () => {+ const f = follow({ sizing_mode: 'fixed', fixed_sol: 1, daily_budget_sol: 1.2 });+ expect(planMirror({ follow: f, leaderTrade: buy(), followerBalanceSol: 10, spentTodaySol: 0.5 }).order_sol).toBeCloseTo(0.7, 6);+ expect(planMirror({ follow: f, leaderTrade: buy(), followerBalanceSol: 10, spentTodaySol: 1.2 }).reason).toBe('follow_daily_spent');+ });+ it('wallet balance clamps the order (keeps fee headroom)', () => {+ const d = planMirror({ follow: follow({ sizing_mode: 'fixed', fixed_sol: 5 }), leaderTrade: buy(), followerBalanceSol: 1 });+ expect(d.order_sol).toBeCloseTo(0.996, 3);+ });+ it('dust order is skipped', () => {+ const d = planMirror({ follow: follow({ sizing_mode: 'fixed', fixed_sol: 0.0001 }), leaderTrade: buy(), followerBalanceSol: 10 });+ expect(d.reason).toBe('below_dust');+ expect(0.0001).toBeLessThan(MIN_MIRROR_BUY_SOL);+ });+ it('pct_balance without a balance cannot be sized', () => {+ const d = planMirror({ follow: follow({ sizing_mode: 'pct_balance', pct_balance: 10 }), leaderTrade: buy(), followerBalanceSol: null });+ expect(d.reason).toBe('sizing_unavailable');+ });+});++describe('normalizeFollowInput', () => {+ it('defaults to proportional 100%', () => {+ const r = normalizeFollowInput({});+ expect(r.ok).toBe(true);+ expect(r.value).toMatchObject({ sizing_mode: 'proportional', proportion_pct: 100, copy_sells: true });+ });+ it('rejects a non-positive fixed size', () => {+ expect(normalizeFollowInput({ sizing_mode: 'fixed', fixed_sol: 0 }).ok).toBe(false);+ });+ it('rejects pct_balance outside (0,100]', () => {+ expect(normalizeFollowInput({ sizing_mode: 'pct_balance', pct_balance: 0 }).ok).toBe(false);+ expect(normalizeFollowInput({ sizing_mode: 'pct_balance', pct_balance: 150 }).ok).toBe(false);+ expect(normalizeFollowInput({ sizing_mode: 'pct_balance', pct_balance: 25 }).ok).toBe(true);+ });+ it('filters mint lists to valid base58 and caps length', () => {+ const r = normalizeFollowInput({ mint_denylist: ['bad!', 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', 123] });+ expect(r.value.mint_denylist).toEqual(['FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump']);+ });+});diff --git a/tests/wallet-reputation.test.js b/tests/wallet-reputation.test.jsnew file mode 100644index 000000000..116392326--- /dev/null+++ b/tests/wallet-reputation.test.js@@ -0,0 +1,152 @@+// Unit tests for the wallet reputation scoring engine.+//+// The pure computeReputation() function is the trust primitive — these tests pin+// the properties the score must hold to be credible: a new agent reads as new,+// costly signals dominate cheap ones, self-tips and single-counterparty volume+// are discounted, and the tier ladder requires real counterparty diversity.++import { describe, it, expect } from 'vitest';+import { computeReputation, tierFor, MAX_SCORE, PILLARS } from '../api/_lib/trust/wallet-reputation.js';++const NEW_AGENT = {+ ageDays: 0,+ activeDays90: 0,+ externalTipUsd: 0,+ settledUsd: 0,+ tipCount: 0,+ distinctTippers: 0,+ selfTipCount: 0,+ confirmedPayments: 0,+ failedPayments: 0,+ distinctPayers: 0,+ distributionSuccess: 0,+ forkCount: 0,+ hasOnchainIdentity: false,+ registryAverage: 0,+ registryCount: 0,+ validationCount: 0,+ feedbackCount: 0,+ hasSkillCollection: false,+};++const ESTABLISHED = {+ ...NEW_AGENT,+ ageDays: 220,+ activeDays90: 40,+ externalTipUsd: 1200,+ settledUsd: 3500,+ tipCount: 18,+ distinctTippers: 9,+ confirmedPayments: 24,+ failedPayments: 1,+ distinctPayers: 11,+ distributionSuccess: 1,+ forkCount: 5,+ hasOnchainIdentity: true,+ registryAverage: 4.6,+ registryCount: 7,+ validationCount: 2,+ feedbackCount: 5,+ hasSkillCollection: true,+};++describe('computeReputation — pillar maxima', () => {+ it('pillar maxima sum to 100', () => {+ expect(MAX_SCORE).toBe(100);+ expect(PILLARS.reduce((s, p) => s + p.max, 0)).toBe(100);+ });++ it('no pillar can exceed its max even with absurd inputs', () => {+ const r = computeReputation({+ ...ESTABLISHED,+ ageDays: 1e9,+ settledUsd: 1e12,+ externalTipUsd: 1e12,+ distinctTippers: 1e6,+ forkCount: 1e6,+ registryAverage: 100,+ registryCount: 1e6,+ validationCount: 1e6,+ });+ for (const p of r.pillars) expect(p.points).toBeLessThanOrEqual(p.max);+ expect(r.score).toBeLessThanOrEqual(100);+ });+});++describe('new-agent honesty', () => {+ it('a brand-new agent reads as "new" with a near-zero score', () => {+ const r = computeReputation(NEW_AGENT);+ expect(r.isNew).toBe(true);+ expect(r.tier).toBe('new');+ expect(r.score).toBeLessThan(2);+ });++ it('age alone does not manufacture peer trust', () => {+ // An old, verified wallet with NO counterparties cannot reach "trusted".+ const r = computeReputation({+ ...NEW_AGENT,+ ageDays: 900,+ activeDays90: 30,+ hasOnchainIdentity: true,+ registryAverage: 5,+ registryCount: 3,+ });+ expect(['emerging', 'established']).toContain(r.tier);+ expect(r.tier).not.toBe('trusted');+ expect(r.tier).not.toBe('elite');+ });+});++describe('anti-gaming', () => {+ it('self-tips are ignored and surfaced as discounted', () => {+ const withSelf = computeReputation({ ...NEW_AGENT, ageDays: 100, selfTipCount: 50, tipCount: 50, distinctTippers: 0 });+ const without = computeReputation({ ...NEW_AGENT, ageDays: 100 });+ // Self-tips contribute nothing to the score.+ expect(withSelf.score).toBeCloseTo(without.score, 1);+ expect(withSelf.discounted.some((d) => d.kind === 'self_tips')).toBe(true);+ });++ it('single-counterparty volume is discounted vs many distinct tippers', () => {+ const concentrated = computeReputation({+ ...NEW_AGENT,+ ageDays: 100,+ tipCount: 40,+ distinctTippers: 1,+ externalTipUsd: 5000,+ settledUsd: 5000,+ });+ const diverse = computeReputation({+ ...NEW_AGENT,+ ageDays: 100,+ tipCount: 40,+ distinctTippers: 20,+ externalTipUsd: 5000,+ settledUsd: 5000,+ });+ expect(diverse.score).toBeGreaterThan(concentrated.score);+ expect(concentrated.discounted.some((d) => d.kind === 'concentration')).toBe(true);+ });+});++describe('costly signals dominate', () => {+ it('an established, diverse, verified agent scores well and earns a real tier', () => {+ const r = computeReputation(ESTABLISHED);+ expect(r.score).toBeGreaterThan(55);+ expect(['trusted', 'elite']).toContain(r.tier);+ expect(r.isNew).toBe(false);+ });++ it('reliability is zero until there is real settlement volume', () => {+ const r = computeReputation({ ...NEW_AGENT, ageDays: 100, confirmedPayments: 2, failedPayments: 0 });+ const rel = r.pillars.find((p) => p.key === 'reliability');+ expect(rel.points).toBe(0);+ });+});++describe('tierFor gating', () => {+ it('requires counterparty diversity for trusted/elite', () => {+ expect(tierFor({ score: 80, isNew: false, distinctTippers: 0, confirmedPayments: 0 })).toBe('established');+ expect(tierFor({ score: 80, isNew: false, distinctTippers: 5, confirmedPayments: 0 })).toBe('elite');+ expect(tierFor({ score: 60, isNew: false, distinctTippers: 0, confirmedPayments: 12 })).toBe('trusted');+ });+});diff --git a/vercel.json b/vercel.jsonindex 15158bf21..c7ed2bca5 100644--- a/vercel.json+++ b/vercel.json@@ -482,6 +482,10 @@"src": "/api/agents/solana-validation","dest": "/api/agents/solana/[action]?action=validation"},+ {+ "src": "/api/agents/([^/]+)/economy",+ "dest": "/api/agents/[id]/economy?id=$1"+ },{"src": "/api/agents/([^/]+)/skills-pricing","dest": "/api/agents/[id]/skills-pricing?id=$1"@@ -1747,6 +1751,10 @@"src": "/api/agents/balances","dest": "/api/agents/balances"},+ {+ "src": "/api/agents/wallet-embed",+ "dest": "/api/agents/wallet-embed"+ },{"src": "/api/agents/by-address/([^/]+)","dest": "/api/agents/by-address/[addr]?addr=$1"@@ -1842,6 +1850,10 @@"src": "/api/agents/([^/]+)/pricing/([^/]+)","dest": "/api/agents/[id]"},+ {+ "src": "/api/agents/reputation-batch",+ "dest": "/api/agents/reputation-batch"+ },{"src": "/api/agents/([^/]+)/reputation","dest": "/api/agents/[id]"