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
Strategy compiler, SDK package scaffolds, and mission-control refinements
nirholas407ab2cd02a5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6ef8f852f..80f5abad8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -61,7 +61,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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]`- **See the agent economy move, live, on the home page** — The home page now carries a live readout of real value moving between agents — every tip, payment, trade, and token launch as it happens on-chain. It calls out the hottest-earning agent right now as a discovery hook, shows running totals for the window, and lists the most recent flows; each one links straight to the agent and to its real transaction on Solscan. Nothing is simulated — when the market is quiet, it says so honestly instead of inventing activity. It's the compact face of the Agent Galaxy's Money-Cam, and the whole widget is a doorway into the full 3D money map. (`/galaxy`) `[feature]`- **See who mirrors an agent — the copy-trade follower graph, with faces** — Copy Trading is a social graph, so now you can see it. Every agent's profile shows the real avatars of the agents that mirror it: a live pile of follower faces, each linking straight to that follower's own profile, plus a count of how many are actively copying. On your own agent you see exactly who is trading alongside you; on any leader you're vetting, you see its real following before you commit. Every face is a real three.ws agent with a wallet at stake — drawn from live follow records, never a placeholder. (`/mirror`) `[improvement]`-- **Signal Marketplace — verified traders sell paid alpha feeds; your agent pays per signal and auto-mirrors** — Copy-trading with real economics and real accountability. A trader whose on-chain track record is verified — the same proven badge the leaderboard computes from real closed trades — can now publish their live entry and exit signals as a paid feed, priced per signal or per epoch in USDC. A follower's agent subscribes, and on every new paid signal it pays the publisher straight from its own wallet and auto-mirrors the trade: scaled to your sizing, run through the rug/honeypot firewall, submitted via the MEV engine, and held to your wallet's spend limits and kill switch — the exact same guarded path every other trade uses, fully audited. Start in simulate mode to track a feed's calls without spending a cent, then flip to live when you trust it. Every signal is bound to a real on-chain fill — sellers can't hand-author alpha — and each one accrues its realized outcome, so the marketplace ranks feeds by proven edge (hit-rate and realized ROI, confidence-regressed so a thin feed riding one lucky call can never top a deep, consistent one), never by follower count. Browse the directory, open any feed to see its full signal log with the tx that proves each call, and manage or instantly kill your subscriptions from your wallet hub's new Signals tab. Verified traders publish from the same tab and earn real USDC. (`/signals`) `[feature, sdk]`+- **Signal Marketplace — verified traders sell paid alpha feeds; your agent pays per signal and auto-mirrors** — Copy-trading with real economics and real accountability. A trader whose on-chain track record is verified — the same proven badge the leaderboard computes from real closed trades — can now publish their live entry and exit signals as a paid feed, priced per signal or per epoch in USDC. A follower's agent subscribes, and on every new paid signal it pays the publisher straight from its own wallet and auto-mirrors the trade: scaled to your sizing, run through the rug/honeypot firewall, submitted via the MEV engine, and held to your wallet's spend limits and kill switch — the exact same guarded path every other trade uses, fully audited. Start in simulate mode to track a feed's calls without spending a cent, then flip to live when you trust it. Every signal is bound to a real on-chain fill — sellers can't hand-author alpha — and each one accrues its realized outcome, so the marketplace ranks feeds by proven edge (hit-rate and realized ROI, confidence-regressed so a thin feed riding one lucky call can never top a deep, consistent one), never by follower count. Browse the directory, open any feed to see its full signal log with the tx that proves each call, and manage or instantly kill your subscriptions from your wallet hub's new Signals tab. Verified traders publish from the same tab and earn real USDC. (`/signals`) `[feature]`- **Skill-sale earnings now show up in your agent's Earn tab** — The Earn tab's headline number — what your avatar has actually earned — now counts every skill sale, not just tips. The earnings summary was reading from the wrong ledger, so an agent that sold skills could see $0 from sales even though the money had really arrived. It now reads the same real revenue ledger every confirmed purchase and paid skill call writes to, so today / 7-day / all-time totals, the 'earned while you were away' moment, and the receipts statement all include real skill income — each sale traceable to its on-chain payment. Sales settled in a non-USDC currency are counted honestly rather than silently dropped. (`/agent`) `[fix]`- **Social recovery & inheritance — a funded agent that never dies with its owner** — Your agent's wallet is custodial and real-money funded, so "I lost access" or "the owner is gone" should never mean the funds are lost forever. You can now name guardians (real three.ws accounts you trust) and a beneficiary, and set how many guardians must agree. If you ever lose access, that threshold of guardians approving — plus a 48-hour safety window only you can cancel — hands control of the agent and its wallet back to you. An optional dead-man's switch passes the agent to your beneficiary if you go silent past a period you choose, but only after a generous, cancellable grace window and an explicit confirmation — and you abort the whole thing instantly just by showing up (a login, a trade, or tapping "I'm here"). Crucially, no private key is ever exported or exposed: recovery and inheritance only change who owns the agent, and the same encrypted, server-held key keeps signing for the new owner. Every step is time-locked, reversible until commit, and written to your custody trail; the wallet is frozen against autonomous spending during any contested process so it can never be drained out from under you. Guardians act from a new Guardian console — the agents you're trusted to protect, where you approve a recovery or confirm an inheritance without ever touching anyone's funds. (`/guardian`) `[feature, security]`- **Steadier 3D generation and token stats when free providers get busy** — Two backend reliability fixes. The free image step behind text→3D now shrugs off a brief blip from NVIDIA's gateway — if it answers with a fast, transient hiccup, we retry once before handing off, so fewer prompts have to fall through to a slower backup and fewer fail outright. (A real timeout still hands off immediately, so nothing waits twice.) Separately, live token stats lean on several market-data sources; when one hits its monthly quota we already pause it, but each fresh server instance used to re-discover that the hard way and waste another doomed call. That pause is now shared across the whole fleet, so the moment one instance sees a source is exhausted, none of the others retry it — quieter, faster, and no wasted quota. `[fix, infra]`diff --git a/api/_lib/strategy-compiler.js b/api/_lib/strategy-compiler.jsnew file mode 100644index 000000000..721dd7b0a--- /dev/null+++ b/api/_lib/strategy-compiler.js@@ -0,0 +1,355 @@+// Natural-language → validated sniper strategy compiler.+//+// A user describes a snipe strategy in plain English ("snipe creators who've+// graduated at least two, market cap under $30k, organic distribution, take+// profit at 3x, stop loss 40%, max 0.3 SOL per trade"). We compile it to a row+// shaped exactly like agent_sniper_strategies / the api/sniper/strategy.js POST+// body, HARD-validate it against the same ranges the arm endpoint enforces, and+// clamp every money/risk knob to the agent's runtime trade guards+// (agent-trade-guards.js) so a compiled strategy can NEVER bypass a spend cap or+// the price-impact breaker. The result carries a plain-language summary plus an+// explicit list of every value we assumed or clamped — so the owner sees the+// truth before arming, never a silent unsafe config.+//+// Prefers the platform LLM (free-first chain in llm.js); falls back to a real+// deterministic intent parser so the feature always compiles, model or not.++import { llmComplete, llmConfigured } from './llm.js';++const LAMPORTS_PER_SOL = 1_000_000_000;++// Canonical pump.fun intel categories the classifier emits (intel/classify.js).+const KNOWN_CATEGORIES = ['meme', 'tech', 'ai', 'culture', 'community', 'gaming', 'animal', 'political', 'finance'];++const COMPILE_SYSTEM = `You translate a plain-English pump.fun sniper strategy into ONE JSON object. Output ONLY the JSON — no prose, no markdown fence.++Schema (omit a field or use null when the user didn't specify it — do NOT invent values):+{+ "trigger": "new_mint" | "intel_confirmed", // "new_mint" snipes blind on launch; "intel_confirmed" waits for the Coin Intelligence read. Use intel_confirmed when the user mentions bundle/organic/concentration/quality/smart-money signals.+ "per_trade_sol": number|null, // SOL spent per snipe+ "daily_budget_sol": number|null, // total SOL/day budget+ "max_concurrent_positions": integer|null,+ "slippage_pct": number|null, // entry slippage tolerance, percent+ "max_price_impact_pct": number|null, // reject entry if quote impact exceeds this+ "min_market_cap_usd": number|null,+ "max_market_cap_usd": number|null,+ "min_creator_graduated": integer|null, // creator must have >= N graduated coins+ "max_creator_launches": integer|null, // reject serial ruggers with > N launches+ "require_socials": boolean|null, // demand twitter/telegram/website+ "require_sol_quote": boolean|null, // SOL-paired only (default true)+ "take_profit_pct": number|null, // "3x" => 200 (gain percent above entry)+ "stop_loss_pct": number|null, // MANDATORY for safety; percent loss+ "trailing_stop_pct": number|null,+ "max_hold_seconds": integer|null, // "hold 30 min" => 1800+ "min_quality_score": number|null, // 0-100 (intel_confirmed)+ "max_bundle_score": number|null, // 0-1, lower = cleaner launch (intel_confirmed)+ "max_concentration_top1": number|null, // 0-100, top holder share cap (intel_confirmed)+ "avoid_dev_dump": boolean|null, // skip coins where dev already sold+ "allowed_categories": [string]|null, // subset of: ${KNOWN_CATEGORIES.join(', ')}+ "summary": string, // one plain-language sentence describing what this strategy does+ "assumptions": [string] // anything you defaulted or could not parse+}+Conversions: "3x"/"triple" => take_profit_pct 200; "2x" => 100. "graduated at least two" => min_creator_graduated 2. "organic" / "no bundles" => trigger intel_confirmed with a low max_bundle_score (~0.3) and decent min_quality_score (~55). "smart money" => trigger intel_confirmed. Percentages stay percentages. Never reference any coin other than $THREE.`;++function num(v) {+ if (v === null || v === undefined || v === '') return null;+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+}+function intOrNull(v) {+ const n = num(v);+ return n == null ? null : Math.floor(n);+}+function str(v, max = 240) {+ if (typeof v !== 'string') return '';+ return v.trim().slice(0, max);+}+function clamp(n, min, max) {+ return Math.min(max, Math.max(min, n));+}++function safeJsonExtract(text) {+ if (typeof text !== 'string') return null;+ const t = text.trim().replace(/^```(?:json)?/i, '').replace(/```$/, '').trim();+ const start = t.indexOf('{');+ const end = t.lastIndexOf('}');+ if (start < 0 || end < start) return null;+ try {+ return JSON.parse(t.slice(start, end + 1));+ } catch {+ return null;+ }+}++/**+ * Compile NL → validated strategy.+ * @param {string} text the user's plain-English description+ * @param {object} [opts]+ * @param {object} [opts.tradeLimits] agent meta.trade_limits — runtime ceilings to clamp to+ * @param {string} [opts.network]+ * @param {object} [opts.track] llm spend attribution+ * @returns {Promise<{ok:boolean, error?:string, message?:string, via?:string,+ * source_text?:string, strategy?:object, summary?:string, assumptions?:string[],+ * clamped?:string[], warnings?:string[]}>}+ */+export async function compileStrategyFromText(text, { tradeLimits = null, network = 'mainnet', track = null } = {}) {+ const source = typeof text === 'string' ? text.trim().slice(0, 4000) : '';+ if (source.length < 3) {+ return { ok: false, error: 'empty', message: 'Describe your strategy in a sentence or two first.' };+ }++ let parsed = null;+ let via = 'heuristic';+ if (llmConfigured()) {+ try {+ const out = await llmComplete({+ system: COMPILE_SYSTEM,+ user: source,+ maxTokens: 700,+ timeoutMs: 25_000,+ track: track ? { ...track, tool: 'sniper-strategy-compile' } : { tool: 'sniper-strategy-compile' },+ });+ parsed = safeJsonExtract(out.text);+ if (parsed) via = 'model';+ } catch (e) {+ console.warn('[strategy-compiler] LLM compile failed, using heuristic:', e?.message);+ }+ }+ if (!parsed) parsed = heuristicCompile(source);++ const assumptions = Array.isArray(parsed.assumptions) ? parsed.assumptions.map((w) => str(w)).filter(Boolean) : [];+ const clamped = [];++ // ── raw field extraction ──────────────────────────────────────────────────+ let trigger = parsed.trigger === 'intel_confirmed' || parsed.trigger === 'first_claim' ? parsed.trigger : 'new_mint';++ let perTradeSol = num(parsed.per_trade_sol);+ let dailySol = num(parsed.daily_budget_sol);+ // A per-trade size with no daily budget: assume room for a few trades a day so+ // the owner can arm without re-typing. Never let per-trade exceed the daily cap.+ if (perTradeSol != null && perTradeSol > 0 && dailySol == null) {+ dailySol = perTradeSol * 5;+ assumptions.push(`No daily budget given — assumed ${dailySol} SOL/day (5× your per-trade size). Adjust before arming.`);+ }+ if (perTradeSol != null && dailySol != null && perTradeSol > dailySol) {+ dailySol = perTradeSol;+ clamped.push(`Daily budget raised to ${dailySol} SOL so it covers a single ${perTradeSol} SOL trade.`);+ }++ // Clamp money + risk knobs to the agent's runtime trade guards. These are the+ // SAME ceilings agent-trade-guards.js enforces on every live buy — a compiled+ // strategy must never be able to exceed them.+ const tl = tradeLimits || {};+ if (perTradeSol != null && tl.per_trade_sol != null && perTradeSol > tl.per_trade_sol) {+ perTradeSol = tl.per_trade_sol;+ clamped.push(`Per-trade size clamped to your ${tl.per_trade_sol} SOL trade cap.`);+ }+ if (dailySol != null && tl.daily_budget_sol != null && dailySol > tl.daily_budget_sol) {+ dailySol = tl.daily_budget_sol;+ clamped.push(`Daily budget clamped to your ${tl.daily_budget_sol} SOL/day cap.`);+ if (perTradeSol != null && perTradeSol > dailySol) perTradeSol = dailySol;+ }++ let slippageBps = parsed.slippage_pct != null ? Math.round(num(parsed.slippage_pct) * 100) : null;+ if (slippageBps != null) slippageBps = clamp(slippageBps, 0, 5000);+ if (slippageBps != null && tl.max_slippage_bps != null && slippageBps > tl.max_slippage_bps) {+ slippageBps = tl.max_slippage_bps;+ clamped.push(`Slippage clamped to your ${(tl.max_slippage_bps / 100).toFixed(2)}% ceiling.`);+ }++ let maxImpact = num(parsed.max_price_impact_pct);+ if (maxImpact != null) maxImpact = clamp(maxImpact, 0, 100);+ const impactCeil = tl.max_price_impact_pct != null ? tl.max_price_impact_pct : 15;+ if (maxImpact == null) maxImpact = Math.min(10, impactCeil);+ if (maxImpact > impactCeil) {+ maxImpact = impactCeil;+ clamped.push(`Max price impact clamped to the ${impactCeil}% safety breaker.`);+ }++ let maxConcurrent = intOrNull(parsed.max_concurrent_positions);+ if (maxConcurrent != null) maxConcurrent = clamp(maxConcurrent, 1, 50);+ if (maxConcurrent == null) maxConcurrent = 1;+ if (tl.max_concurrent != null && maxConcurrent > tl.max_concurrent) {+ maxConcurrent = tl.max_concurrent;+ clamped.push(`Max concurrent positions clamped to your ${tl.max_concurrent} cap.`);+ }++ // ── exits — stop-loss is mandatory and must be > 0 ─────────────────────────+ let stopLoss = num(parsed.stop_loss_pct);+ if (stopLoss == null || stopLoss <= 0) {+ stopLoss = 35;+ assumptions.push('No stop-loss specified — defaulted to 35%. A stop-loss is mandatory; raise or lower it, but it can never be removed.');+ }+ stopLoss = clamp(stopLoss, 1, 95);++ let takeProfit = num(parsed.take_profit_pct);+ if (takeProfit != null) takeProfit = takeProfit > 0 ? clamp(takeProfit, 1, 100000) : null;+ let trailing = num(parsed.trailing_stop_pct);+ if (trailing != null) trailing = trailing > 0 ? clamp(trailing, 1, 95) : null;++ let maxHold = intOrNull(parsed.max_hold_seconds);+ if (maxHold != null) maxHold = clamp(maxHold, 30, 86400);+ if (maxHold == null) maxHold = 1800;++ // ── entry filters ──────────────────────────────────────────────────────────+ const minMc = num(parsed.min_market_cap_usd);+ const maxMc = num(parsed.max_market_cap_usd);+ const minGrad = intOrNull(parsed.min_creator_graduated);+ const maxLaunches = intOrNull(parsed.max_creator_launches);+ const requireSocials = parsed.require_socials === true;+ const requireSolQuote = parsed.require_sol_quote !== false; // default true+ const avoidDevDump = parsed.avoid_dev_dump !== false; // default true++ let minQuality = num(parsed.min_quality_score);+ if (minQuality != null) minQuality = clamp(Math.round(minQuality), 0, 100);+ let maxBundle = num(parsed.max_bundle_score);+ if (maxBundle != null) maxBundle = clamp(maxBundle, 0, 1);+ let maxConc = num(parsed.max_concentration_top1);+ if (maxConc != null) maxConc = clamp(maxConc, 0, 100);++ let categories = Array.isArray(parsed.allowed_categories)+ ? [...new Set(parsed.allowed_categories.map((c) => str(c, 24).toLowerCase()).filter((c) => KNOWN_CATEGORIES.includes(c)))]+ : null;+ if (categories && categories.length === 0) categories = null;++ // Intel-only signals only bite when the trigger waits for the intel read.+ if (trigger !== 'intel_confirmed' && (minQuality != null || maxBundle != null || maxConc != null || categories)) {+ trigger = 'intel_confirmed';+ assumptions.push('Switched to "intel-confirmed" entry — your filters (quality / bundle / concentration / category) need the Coin Intelligence read, which the blind launch trigger can\'t see.');+ }++ const perTradeLamports = perTradeSol != null ? String(Math.max(0, Math.round(perTradeSol * LAMPORTS_PER_SOL))) : '0';+ const dailyLamports = dailySol != null ? String(Math.max(0, Math.round(dailySol * LAMPORTS_PER_SOL))) : '0';++ const strategy = {+ trigger,+ daily_budget_lamports: dailyLamports,+ per_trade_lamports: perTradeLamports,+ max_concurrent_positions: maxConcurrent,+ slippage_bps: slippageBps != null ? slippageBps : 500,+ max_price_impact_pct: Number(maxImpact.toFixed(2)),+ min_market_cap_usd: minMc,+ max_market_cap_usd: maxMc,+ min_creator_graduated: minGrad,+ max_creator_launches: maxLaunches,+ require_socials: requireSocials,+ require_sol_quote: requireSolQuote,+ take_profit_pct: takeProfit,+ stop_loss_pct: Number(stopLoss.toFixed(2)),+ trailing_stop_pct: trailing,+ max_hold_seconds: maxHold,+ min_quality_score: minQuality,+ max_bundle_score: maxBundle,+ max_concentration_top1: maxConc,+ avoid_dev_dump: avoidDevDump,+ allowed_categories: categories,+ };++ const warnings = [];+ if (BigInt(perTradeLamports) <= 0n || BigInt(dailyLamports) <= 0n) {+ warnings.push('Set a per-trade size and a daily budget before you can arm this — a live strategy needs real SOL to spend.');+ }++ const summary = str(parsed.summary, 400) || describeStrategy(strategy);++ return {+ ok: true,+ via,+ source_text: source,+ strategy,+ summary,+ assumptions: [...new Set(assumptions)],+ clamped: [...new Set(clamped)],+ warnings,+ };+}++// Plain-language fallback description, in case the model didn't return a summary.+function describeStrategy(s) {+ const parts = [];+ const perSol = Number(BigInt(s.per_trade_lamports)) / LAMPORTS_PER_SOL;+ const daySol = Number(BigInt(s.daily_budget_lamports)) / LAMPORTS_PER_SOL;+ parts.push(s.trigger === 'intel_confirmed'+ ? 'Waits for the Coin Intelligence read, then snipes coins that clear your filters'+ : 'Snipes brand-new pump.fun launches that clear your filters');+ if (perSol > 0) parts.push(`at ${perSol} SOL each (up to ${daySol} SOL/day)`);+ const exits = [];+ if (s.take_profit_pct) exits.push(`take profit +${s.take_profit_pct}%`);+ exits.push(`stop loss ${s.stop_loss_pct}%`);+ if (s.trailing_stop_pct) exits.push(`${s.trailing_stop_pct}% trailing stop`);+ parts.push(`Exits on ${exits.join(', ')}.`);+ return parts.join(', ').replace(', Exits', '. Exits');+}++// ── deterministic intent parser — real implementation, not a mock ──────────────+// Extracts the same fields from common phrasings so the feature always compiles+// even with no model configured.+function heuristicCompile(text) {+ const t = ` ${text.toLowerCase()} `;+ const out = { assumptions: [], allowed_categories: null };++ const moneyToNum = (m) => {+ if (!m) return null;+ let v = parseFloat(m.replace(/[$,\s]/g, ''));+ if (/k\b/i.test(m)) v *= 1_000;+ if (/m(?:m|illion)?\b/i.test(m)) v *= 1_000_000;+ return Number.isFinite(v) ? v : null;+ };++ // take profit: "3x" / "take profit at 3x" / "tp 200%"+ const mult = t.match(/(\d+(?:\.\d+)?)\s*x\b/);+ if (mult) out.take_profit_pct = (parseFloat(mult[1]) - 1) * 100;+ const tp = t.match(/(?:take[ -]?profit|tp)\D{0,12}?(\d+(?:\.\d+)?)\s*%/);+ if (tp) out.take_profit_pct = parseFloat(tp[1]);++ const sl = t.match(/(?:stop[ -]?loss|sl|stop)\D{0,12}?(\d+(?:\.\d+)?)\s*%/);+ if (sl) out.stop_loss_pct = parseFloat(sl[1]);+ const trail = t.match(/(?:trailing|trail)\D{0,14}?(\d+(?:\.\d+)?)\s*%/);+ if (trail) out.trailing_stop_pct = parseFloat(trail[1]);++ const perTrade = t.match(/(\d+(?:\.\d+)?)\s*sol\s*(?:per|\/|each|a)\s*(?:trade|snipe|buy|position)/);+ if (perTrade) out.per_trade_sol = parseFloat(perTrade[1]);+ const maxPer = t.match(/(?:max|up to)\s*(\d+(?:\.\d+)?)\s*sol/);+ if (maxPer && out.per_trade_sol == null) out.per_trade_sol = parseFloat(maxPer[1]);+ const daily = t.match(/(\d+(?:\.\d+)?)\s*sol\s*(?:a|per|\/)\s*day|daily\s*budget\D{0,8}(\d+(?:\.\d+)?)\s*sol/);+ if (daily) out.daily_budget_sol = parseFloat(daily[1] || daily[2]);++ const underMc = t.match(/(?:under|below|less than|max(?:imum)?(?:\s*market\s*cap)?(?:\s*of)?)\s*\$?\s*([\d.,]+\s*[km]?)/);+ if (underMc && /market\s*cap|mcap|mc\b|cap/.test(t)) out.max_market_cap_usd = moneyToNum(underMc[1]);+ const overMc = t.match(/(?:over|above|more than|min(?:imum)?(?:\s*market\s*cap)?(?:\s*of)?)\s*\$?\s*([\d.,]+\s*[km]?)/);+ if (overMc && /market\s*cap|mcap|mc\b|cap/.test(t)) out.min_market_cap_usd = moneyToNum(overMc[1]);++ const grad = t.match(/graduat\w*\s*(?:at least\s*|>=?\s*)?(\d+)|(\d+)\+?\s*graduat/);+ if (grad) out.min_creator_graduated = parseInt(grad[1] || grad[2], 10);++ const hold = t.match(/(?:hold|timeout|exit after)\D{0,10}?(\d+(?:\.\d+)?)\s*(min|minute|hour|hr|sec|second)/);+ if (hold) {+ let s = parseFloat(hold[1]);+ if (/min/.test(hold[2])) s *= 60; else if (/h/.test(hold[2])) s *= 3600;+ out.max_hold_seconds = Math.round(s);+ }++ const slip = t.match(/(\d+(?:\.\d+)?)\s*%?\s*slippage|slippage\D{0,8}(\d+(?:\.\d+)?)\s*%/);+ if (slip) out.slippage_pct = parseFloat(slip[1] || slip[2]);++ if (/\bsocials?\b|twitter|telegram|website/.test(t)) out.require_socials = true;+ if (/no dev (?:dump|sell)|dev (?:hasn'?t|didn'?t) (?:dump|sell)/.test(t)) out.avoid_dev_dump = true;++ // intel signals+ if (/organic|no bundle|not bundled|clean (?:launch|distribution)|distributed/.test(t)) {+ out.trigger = 'intel_confirmed';+ out.max_bundle_score = 0.3;+ if (out.min_quality_score == null) out.min_quality_score = 55;+ out.assumptions.push('Read "organic / clean distribution" as a low bundle-score ceiling (0.3) and a 55+ quality bar.');+ }+ const conc = t.match(/(?:concentration|top\s*holder|whale)\D{0,12}?(\d+(?:\.\d+)?)\s*%/);+ if (conc) { out.trigger = 'intel_confirmed'; out.max_concentration_top1 = parseFloat(conc[1]); }+ const q = t.match(/quality\D{0,10}?(\d+(?:\.\d+)?)/);+ if (q) { out.trigger = 'intel_confirmed'; out.min_quality_score = parseFloat(q[1]); }+ for (const cat of KNOWN_CATEGORIES) {+ if (new RegExp(`\\b${cat}\\b`).test(t)) out.allowed_categories = [...(out.allowed_categories || []), cat];+ }+ if (out.allowed_categories) out.trigger = 'intel_confirmed';++ return out;+}diff --git a/api/_lib/tournament-scoring.js b/api/_lib/tournament-scoring.jsindex 455fbfb87..074416d13 100644--- a/api/_lib/tournament-scoring.js+++ b/api/_lib/tournament-scoring.js@@ -155,7 +155,9 @@ export function computeStandings(tournament, pairs, { solUsd = null, now = Date.return {agent_id: entry.agent_id,agent_name: entry.agent_name || null,- image: entry.profile_image_url || entry.avatar_url || null,+ // Row thumbnails render as <img>, so only use a flat profile image here; the+ // glb (avatar_url) drives the 3D spotlight separately and isn't an image.+ image: entry.profile_image_url || null,glb_url: entry.avatar_url || null,wallet: entry.wallet || null,joined_at: entry.joined_at,diff --git a/data/changelog.json b/data/changelog.jsonindex 0bcef8ef1..590c203b7 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -6,8 +6,7 @@"title": "Signal Marketplace — verified traders sell paid alpha feeds; your agent pays per signal and auto-mirrors","summary": "Copy-trading with real economics and real accountability. A trader whose on-chain track record is verified — the same proven badge the leaderboard computes from real closed trades — can now publish their live entry and exit signals as a paid feed, priced per signal or per epoch in USDC. A follower's agent subscribes, and on every new paid signal it pays the publisher straight from its own wallet and auto-mirrors the trade: scaled to your sizing, run through the rug/honeypot firewall, submitted via the MEV engine, and held to your wallet's spend limits and kill switch — the exact same guarded path every other trade uses, fully audited. Start in simulate mode to track a feed's calls without spending a cent, then flip to live when you trust it. Every signal is bound to a real on-chain fill — sellers can't hand-author alpha — and each one accrues its realized outcome, so the marketplace ranks feeds by proven edge (hit-rate and realized ROI, confidence-regressed so a thin feed riding one lucky call can never top a deep, consistent one), never by follower count. Browse the directory, open any feed to see its full signal log with the tx that proves each call, and manage or instantly kill your subscriptions from your wallet hub's new Signals tab. Verified traders publish from the same tab and earn real USDC.","tags": [- "feature",- "sdk"+ "feature"],"link": "/signals"},diff --git a/packages/forge/README.md b/packages/forge/README.mdnew file mode 100644index 000000000..bc6e636e2--- /dev/null+++ b/packages/forge/README.md@@ -0,0 +1,265 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/forge</h1>++<p align="center"><strong>Text, image, or sketch → a textured, rig-ready 3D <code>.glb</code> in one call.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/forge"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/forge?logo=npm&color=cb3837"></a>+ <a href="https://www.npmjs.com/package/@three-ws/forge"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/forge?color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/forge?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/forge?color=339933&logo=node.js">+</p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#api">API</a> ·+ <a href="#how-it-works">How it works</a> ·+ <a href="#pricing">Pricing</a> ·+ <a href="https://three.ws/forge">three.ws</a>+</p>++---++> `@three-ws/forge` is the official client for the three.ws **Forge** — the+> generation engine behind [three.ws/forge](https://three.ws/forge). It turns a+> prompt, a photo, or a sketch into a watertight, textured GLB, and can+> auto-rig that GLB into an animation-ready humanoid. It wraps the public,+> auth-free `/api/forge` endpoint: a free [TRELLIS](https://github.com/microsoft/TRELLIS)+> lane on NVIDIA NIM, paid high-detail tiers billed in USDC over+> [x402](https://x402.org), and bring-your-own-key geometry backends+> (Meshy, Tripo). It pairs with [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar)+> — Forge *makes* the model, `@three-ws/avatar` *renders* it.++## Why++Every "text-to-3D" you find is either a closed playground with no API, or a raw+model endpoint that hands you an untextured mesh and leaves rigging, polygon+budgets, provider fallback, job polling, and billing to you. Forge is the whole+pipeline, done once:++- **One call, a real GLB.** `forge('a chrome robot')` resolves to a hosted,+ durable `.glb` URL plus a [three.ws viewer](https://three.ws/forge) link.+- **Free first.** Text prompts default to the free NVIDIA NIM / TRELLIS lane —+ no key, no wallet, no card.+- **Scales with the asset.** Three quality tiers (draft → standard → high) map+ to real polygon budgets and PBR texturing. Pay per call in USDC only when you+ reach for the paid tiers.+- **Rig-ready.** One flag chains generation into auto-rigging, so the output+ drops straight into the three.ws animation runtime — idle, walk, emotes.++This is the SDK twin of the [3D Studio MCP server](https://three.ws/mcp) — the+same engine, exposed as plain functions instead of MCP tools.++## Install++```bash+npm install @three-ws/forge+```++Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch`).+For rendering the result, add [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar).++## Quick start++The free lane needs no key:++```js+import { forge } from '@three-ws/forge';++const model = await forge('a chrome robot with neon trim');++console.log(model.glbUrl); // → https://cdn.three.ws/forge/….glb (durable)+console.log(model.viewerUrl); // → https://three.ws/forge?share=…+```++A fuller run — high tier, geometry-first, then auto-rig:++```js+import { forge, rig } from '@three-ws/forge';++const model = await forge('a stylized fox, full body, T-pose', {+ tier: 'high', // draft | standard | high+ path: 'geometry', // image | geometry | sketch+ providerKey: process.env.MESHY_KEY, // BYOK for the geometry path+});++const rigged = await rig(model.glbUrl); // animation-ready humanoid GLB+console.log(rigged.glbUrl);+```++From an image or a sketch:++```js+// Photo → 3D+await forge({ images: ['https://example.com/sneaker.png'], prompt: 'a sneaker' });++// Drawing + a name → geometry (no textures)+await forge({ images: ['data:image/png;base64,…'], prompt: 'a sword', path: 'sketch' });+```++## API++### `forge(promptOrInput, options?) → Promise<ForgeResult>`++Generate a GLB from text, image(s), or a sketch. Accepts a bare prompt string,+or an input object.++**Input**++| Field | Type | Notes |+|---|---|---|+| `prompt` | `string` | Text description. Required for text + sketch paths. |+| `images` | `string[]` | One or more image URLs / data URIs. Switches to image→3D. |+| `aspectRatio` | `string` | Reference-image aspect for the `image` path, e.g. `"1:1"`. |++**Options**++| Option | Type | Default | Notes |+|---|---|---|---|+| `path` | `'image' \| 'geometry' \| 'sketch'` | `'image'` | How geometry is produced — see [How it works](#how-it-works). |+| `tier` | `'draft' \| 'standard' \| 'high'` | `'standard'` | Polygon budget + texture richness. |+| `backend` | `string` | auto | Force a generation backend (`nvidia`, `huggingface`, `meshy`, `tripo`). |+| `providerKey` | `string` | — | BYOK key for the `geometry` path (Meshy/Tripo). |+| `payWith` | `'x402' \| 'credits'` | `'x402'` | Billing lane for paid tiers (see [Pricing](#pricing)). |+| `signal` | `AbortSignal` | — | Cancel an in-flight generation. |+| `onProgress` | `(job) => void` | — | Called on each poll tick with the latest job state. |++**Returns** `ForgeResult`++| Field | Type | Notes |+|---|---|---|+| `glbUrl` | `string` | Durable hosted GLB URL. |+| `viewerUrl` | `string` | Shareable three.ws viewer link. |+| `jobId` | `string \| null` | `null` when the backend returned synchronously. |+| `status` | `'done'` | Resolved jobs are always `done`; failures throw. |+| `path` / `tier` / `backend` | `string` | What actually produced the mesh. |+| `etaSeconds` | `number` | Backend ETA at submit time. |++`forge()` submits to `POST /api/forge`, then polls `GET /api/forge?job=<id>`+until the job is `done` (the free NVIDIA lane often returns synchronously, with+no polling). Failures reject with a typed [`ForgeError`](#errors--edge-cases).++### `rig(glbUrl, options?) → Promise<ForgeResult>`++Auto-rig an existing GLB into an animation-ready humanoid. Wraps+`POST /api/forge?action=rig { glb_url }`. Returns the same `ForgeResult` shape+with a rigged `glbUrl`.++### `catalog() → Promise<Catalog>`++Fetch the live tier / backend / cost matrix (`GET /api/forge?catalog`) — the+single source of truth for prices, ETAs, which backends are configured, and+which paths each serves. Use it to render a picker before the user commits.++## How it works++Two orthogonal axes describe every request — `path` (how geometry is produced)+and `tier` (how much budget to spend):++```+prompt / image / sketch+ │+ ▼+ ┌──────────┐ image ┌───────────────────────────────┐+ │ path = ├────────────▶ FLUX/Imagen → TRELLIS·Hunyuan3D │ fast default, free lane+ │ ├─ geometry ─▶ Meshy / Tripo native text→mesh │ BYOK, higher detail ceiling+ │ ├─ sketch ───▶ TripoSG-scribble │ drawing + name → raw geometry+ └──────────┘ └───────────────┬───────────────┘+ ▼+ textured / untextured GLB+ │ (action=rig)+ ▼+ rigged humanoid GLB+```++- **`image`** (default) — text is painted into a reference image, then+ reconstructed to a mesh. Fast, and the free lane lives here.+- **`geometry`** — a native 3D model emits mesh geometry directly, so detail+ isn't capped by a single synthesized view. Bring your own Meshy/Tripo key.+- **`sketch`** — a drawing plus a prompt naming it drives TripoSG-scribble to+ raw geometry (no textures).++Backends declare which paths they serve and whether they need a key. If a+selected backend isn't configured, Forge returns a clean error state — it never+fabricates a model.++## Pricing++The free lane is genuinely free. Paid tiers are flat per-call prices, quoted in+USDC (6-decimal atomics) and settled over [x402](https://x402.org) or from a+prepaid credit balance:++| Tier | Polygons (target) | PBR | Price | Lane |+|---|---|---|---|---|+| **draft** | ~12k | — | **free** on NVIDIA NIM (text) | TRELLIS |+| **standard** | ~30k | — | **$0.15** (free on the NIM text lane) | TRELLIS / paid |+| **high** | ~200k | yes | **$0.50** | paid |++Set `payWith: 'x402'` (default) to pay per call with USDC, or `payWith:+'credits'` to draw from a signed-in prepaid balance. Pair with+[`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) to+automate the 402 settlement. Prices are authoritative in `catalog()` — read+them at runtime rather than hardcoding.++## Errors & edge cases++`forge()` and `rig()` reject with a typed `ForgeError` carrying a `code`:++| `code` | HTTP | Meaning | Recovery |+|---|---|---|---|+| `needs_key` | 501 | The `geometry` path needs a BYOK Meshy/Tripo key. | Pass `providerKey`. |+| `backend_unavailable` | 503 | The selected backend isn't configured. | Omit `backend` to auto-route, or pick another. |+| `payment_required` | 402 | Paid tier with no payment. | Provide an x402 payer or top up credits. |+| `insufficient_credits` | 402 | `payWith: 'credits'` balance too low. | Top up at `/credits`. |+| `unauthorized` | 401 | Credit lane needs a signed-in account. | Authenticate, or use `payWith: 'x402'`. |+| `rate_limited` | 429 | Too many submissions. | Honour `retryAfter` on the error. |+| `generation_failed` | — | The backend produced no usable mesh. | Retry, or change `path`/`backend`. |++Every state is designed: a missing key returns `needs_key` (not a crash), an+unconfigured backend returns `503` (not a fake model). Mirror that in your UI.++## Examples++**Agent tool (free, zero-config)** — the same capability is exposed as the+`forge_free` MCP tool, so an agent can generate 3D with no wallet:++```js+const { glbUrl } = await forge('a low-poly treasure chest', { tier: 'draft' });+```++**Browser → render inline** with the sibling viewer:++```html+<script type="module">+ import { forge } from '@three-ws/forge';+ import '@three-ws/avatar/viewer';++ const { glbUrl } = await forge('a friendly robot');+ const el = document.createElement('three-ws-viewer');+ el.setAttribute('src', glbUrl);+ document.body.append(el);+</script>+```++**Generate → rig → animate** in one chain, ready for the walk companion:++```js+const base = await forge('a cartoon astronaut, full body', { tier: 'standard' });+const rigged = await rig(base.glbUrl);+// drop rigged.glbUrl into @three-ws/walk or @three-ws/avatar+```++## Related++- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render and animate the GLB Forge produces.+- [`@three-ws/walk`](https://www.npmjs.com/package/@three-ws/walk) — a rigged Forge model as a page companion.+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-pay the paid tiers.+- [`@three-ws/avatar-schema`](https://www.npmjs.com/package/@three-ws/avatar-schema) — validate on-chain avatar manifests.++---++<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>diff --git a/packages/forge/package.json b/packages/forge/package.jsonnew file mode 100644index 000000000..dee46818a--- /dev/null+++ b/packages/forge/package.json@@ -0,0 +1,28 @@+{+ "name": "@three-ws/forge",+ "version": "0.1.0",+ "description": "Text/image/sketch → textured, rig-ready 3D GLB in one call. The three.ws Forge generation SDK — free TRELLIS lane, paid high-detail tiers, and auto-rigging.",+ "keywords": [+ "3d",+ "text-to-3d",+ "image-to-3d",+ "gltf",+ "glb",+ "generative",+ "trellis",+ "avatar",+ "rigging",+ "three.ws"+ ],+ "license": "MIT",+ "private": true,+ "type": "module",+ "homepage": "https://three.ws/forge",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ }+}diff --git a/packages/intel/README.md b/packages/intel/README.mdnew file mode 100644index 000000000..32208cb9d--- /dev/null+++ b/packages/intel/README.md@@ -0,0 +1,328 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/intel</h1>++<p align="center"><strong>Token sentiment + market intelligence in one import — for agents and dashboards that need to read the market before they act.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/intel"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/intel?logo=npm&color=cb3837"></a>+ <a href="https://www.npmjs.com/package/@three-ws/intel"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/intel?color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/intel?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/intel?color=339933&logo=node.js">+</p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#api">API</a> ·+ <a href="#how-it-works">How it works</a> ·+ <a href="#pricing--payment">Pricing</a> ·+ <a href="https://three.ws">three.ws</a>+</p>++---++> `@three-ws/intel` is the official client for the three.ws **market intelligence**+> surface — four reads that tell you what a token is *worth*, what people are+> *saying* about it, and where attention is *flowing*. It wraps four live+> endpoints: a deterministic **sentiment pulse** over pump.fun commentary, the+> **aixbt narrative intel** feed, **momentum-ranked project scans**, and a+> real-time **Solana token snapshot** (price, volume, holders, metadata). The+> sentiment endpoint is public and key-free; the aixbt and snapshot lanes are+> exposed as paid MCP tools settled in USDC over [x402](https://x402.org). It+> pairs with [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) —+> Forge *makes* assets, Intel *reads* the market they trade into.++## Why++Reading a token means stitching together five providers — pump.fun comments,+Jupiter price, Dexscreener volume, Solana RPC holder distribution, and a+narrative source — then normalizing five different payload shapes, handling each+one's rate limits, and scoring sentiment yourself. Intel does that once:++- **One import, four reads.** `sentiment(mint)`, `intel(query)`, `projects()`,+ `snapshot(mint)` — each a single call returning a stable, normalized shape.+- **Real data, no fakes.** Every field comes from a live source. If a provider+ is unreachable, the field is `null` so you see the gap — never a fabricated+ number.+- **Sentiment that's reproducible.** The pulse uses a deterministic lexicon+ scorer, not an opaque model, so the same comments always yield the same score.+- **Narrative + momentum in one place.** The aixbt bridge surfaces what's being+ said (`intel`) and what's spiking (`projects`) without you holding an aixbt+ key — it stays server-side.++This is the SDK twin of the [3D Studio MCP server](https://three.ws/mcp) — the+same `sentiment_pulse`, `aixbt_intel`, `aixbt_projects`, and `pump_snapshot`+tools, exposed as plain functions instead of MCP calls.++## Install++```bash+npm install @three-ws/intel+```++Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch`). To+auto-pay the paid lanes (aixbt + snapshot), add+[`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch).++## Quick start++The sentiment lane is public — no key, no wallet:++```js+import { sentiment } from '@three-ws/intel';++const pulse = await sentiment('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump'); // $THREE++console.log(pulse.overall.score); // → 0.42 (range -1 … 1)+console.log(pulse.overall.posPct); // → 58+console.log(pulse.breakdown.pumpfun.count); // comments scored+```++A fuller read — narrative, momentum, and an on-chain snapshot together:++```js+import { intel, projects, snapshot } from '@three-ws/intel';++const narrative = await intel({ chain: 'solana', limit: 10 });+const hot = await projects({ chain: 'solana', limit: 10 });+const market = await snapshot('THREEsynthetic1111111111111111111111111111');++console.log(narrative.intel[0].description); // what's being said+console.log(hot.projects[0].scores.spiking); // momentum rank+console.log(market.priceUsd, market.holders.topHolderCount);+```++Fold your own signals (e.g. X cashtag posts you collected) into the pulse:++```js+const pulse = await sentiment('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', {+ limit: 150,+ extraTexts: ['$THREE volume ripping today', 'best 3D agent stack on Solana'],+});+console.log(pulse.breakdown.extra.score); // score of just your snippets+```++## API++### `sentiment(mint, options?) → Promise<SentimentPulse>`++Real-time sentiment pulse for a Solana token. Pulls recent pump.fun comments via+`frontend-api-v3`, optionally folds in caller-supplied snippets, and scores the+combined stream with the three.ws deterministic lexicon. Wraps+`POST /api/social/sentiment-pulse`. **Public — no key required.**++**Options**++| Option | Type | Default | Notes |+|---|---|---|---|+| `limit` | `number` | `100` | Max pump.fun comments to fetch + score (1–200). |+| `extraTexts` | `string[]` | `[]` | Up to 200 extra snippets (≤2000 chars each) to score alongside. |++**Returns** `SentimentPulse`++| Field | Type | Notes |+|---|---|---|+| `ok` | `true` | Present on success. |+| `token` | `string` | The mint you queried. |+| `overall` | `Score` | Combined score over comments + extras. |+| `breakdown.pumpfun` | `Score` | Just the pump.fun comments (or `{ error, count: 0 }` if the source failed). |+| `breakdown.extra` | `Score` | Just your `extraTexts`. |+| `sources` | `object` | `{ pumpfun, pumpfunCount, extraCount }`. |+| `fetchedAt` | `string` | ISO timestamp. |++A `Score` is `{ score, posPct, negPct, neuPct, count, examples }` — `score` runs+`-1 … 1`, the `*Pct` fields sum to 100, and `examples` carries `{ pos, neg }`+representative lines.++### `intel(query?) → Promise<IntelFeed>`++aixbt narrative intelligence feed — recent intel items detected across crypto.+Wraps `GET /api/aixbt/intel`. **Paid via the `aixbt_intel` MCP tool ($0.01).**++**Query**++| Field | Type | Default | Notes |+|---|---|---|---|+| `limit` | `number` | `20` | Items to return (1–100; the bridge caps the upstream call at 50). |+| `category` | `string` | — | Filter to one aixbt intel category. |+| `chain` | `string` | — | Filter to a chain, e.g. `solana`, `base`, `ethereum`. |++**Returns** `{ intel: IntelItem[], pagination }`, where each `IntelItem` is+`{ category, description, detected_at, reinforced_at, observations, official_source, project, ticker, source }`.++### `projects(query?) → Promise<ProjectScan>`++aixbt momentum scan — projects ranked by spiking / climbing / active scores, with+market metrics and recent intel per project. Wraps `GET /api/aixbt/projects`.+**Paid via the `aixbt_projects` MCP tool ($0.01).**++**Query**++| Field | Type | Default | Notes |+|---|---|---|---|+| `limit` | `number` | `20` | Projects to return (1–100; upstream capped at 50). |+| `page` | `number` | `1` | Page of the ranked list (1–100). |+| `names` | `string` | — | Comma-separated names/tickers to filter to. |+| `chain` | `string` | — | Filter to a chain. |++**Returns** `{ projects: Project[], pagination }`. Each `Project`:++| Field | Type | Notes |+|---|---|---|+| `id` / `name` / `ticker` | `string` | Identity. |+| `x_handle` | `string \| null` | Project X handle. |+| `address` / `chain` | `string \| null` | Primary token address + chain. |+| `scores` | `{ spiking, climbing, active }` | aixbt momentum scores. |+| `trajectory` | `string \| null` | Spiking/climbing trajectory note. |+| `market` | `{ price_usd, market_cap, volume_24h, change_24h }` | Live metrics (`null` where unavailable). |+| `intel` | `IntelItem[]` | Up to 10 recent intel items for the project. |+| `categories` | `string[]` | CoinGecko categories. |++### `snapshot(mint) → Promise<TokenSnapshot>`++Live market snapshot for any Solana SPL or pump.fun token. Generic plumbing — it+takes whatever mint you pass at runtime. Wraps the `pump_snapshot` MCP tool.+**Paid ($0.005).**++**Returns** `TokenSnapshot`++| Field | Type | Notes |+|---|---|---|+| `token` | `string` | The mint. |+| `priceUsd` | `number \| null` | USD price (Jupiter, falling back to Dexscreener). |+| `priceSource` | `'jupiter' \| 'dexscreener' \| null` | Which source priced it. |+| `price` | `object` | Jupiter detail: `{ usdPrice, priceChange24hPct, liquidityUsd, decimals, blockId }`. |+| `volume24h` | `object` | Dexscreener: `{ volume24hUsd, dex, pairAddress, url, marketCapUsd, … }`. |+| `meta` | `object` | pump.fun metadata: `{ name, symbol, imageUrl, creator, marketCapUsd, … }`. |+| `holders` | `object` | `{ topHolderCount, topHolders[] }` from Solana RPC `getTokenLargestAccounts`. |+| `helius` | `object \| null` | Supply/decimals/price from Helius DAS when `HELIUS_API_KEY` is set. |+| `image` | `string \| null` | Token image. |+| `sources` | `object` | The exact upstream URLs each field came from. |+| `fetchedAt` | `string` | ISO timestamp. |++## How it works++Four independent reads, each fronting a normalized aggregate. The aixbt key and+all provider keys live server-side — the SDK never holds them.++```+ sentiment(mint) ─▶ POST /api/social/sentiment-pulse+ └─ pump.fun frontend-api-v3 replies → lexicon scorer++ intel(query) ─▶ GET /api/aixbt/intel ─┐+ projects(query) ─▶ GET /api/aixbt/projects ┴─▶ aixbt REST v2 (key server-side)++ snapshot(mint) ─▶ pump_snapshot (x402) ─┬─ Jupiter Lite → price+ ├─ Dexscreener → volume + pair+ ├─ pump.fun api-v3 → name/image/mcap+ ├─ Solana RPC → top holders+ └─ Helius DAS (opt) → exact supply+```++- **Sentiment** is deterministic: the same comments always produce the same+ score. The pulse fetches the most recent batch from pump.fun and scores+ positive/negative term matches — no model, no randomness.+- **Narrative + momentum** ride the three.ws ⇄ aixbt bridge. aixbt wraps its+ reads as `{ status, data, pagination }`; the bridge unwraps and normalizes them+ into the lean shapes above so an upstream change never ripples into your code.+- **Snapshot** fans out to five sources in parallel and stitches the results.+ Price has a built-in fallback (Jupiter → Dexscreener) so the single most+ important field has two independent backers.++## Pricing & payment++The sentiment lane is genuinely free — it relies only on public pump.fun data+and an in-repo scorer. The aixbt and snapshot lanes are flat per-call prices,+quoted in USDC and settled `exact` on Solana mainnet over [x402](https://x402.org):++| Call | Tool | Price | Lane |+|---|---|---|---|+| `sentiment()` | `sentiment_pulse` | **free** over the public endpoint¹ | pump.fun + lexicon |+| `intel()` | `aixbt_intel` | **$0.01** USDC | aixbt bridge |+| `projects()` | `aixbt_projects` | **$0.01** USDC | aixbt bridge |+| `snapshot()` | `pump_snapshot` | **$0.005** USDC | multi-provider |++¹ The `sentiment_pulse` MCP tool is priced at **$0.003 USDC** for agent callers;+the underlying `POST /api/social/sentiment-pulse` HTTP endpoint this SDK targets+is public and key-free. Pair with+[`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) to+automate the 402 settlement on the paid calls.++## Errors & edge cases++Every state is designed — a missing key or an unreachable provider returns a+typed state, never a crash or a fake number.++| State | HTTP | Where | Meaning & recovery |+|---|---|---|---|+| `validation_error` | 400 | sentiment | `token` isn't a base58 mint, or body is malformed. Fix the input. |+| `aixbt_not_configured` | 503 | intel / projects | Deployment has no `AIXBT_API_KEY`. Response carries a `setup` hint pointing at the aixbt key pass. |+| `aixbt_unauthorized` | 401/403 | intel / projects | aixbt rejected the key. Rotate it. |+| `aixbt_rate_limited` | 429 | intel / projects | aixbt throttled the bridge. Back off and retry. |+| `aixbt_upstream_error` | 502/504 | intel / projects | aixbt was unreachable or errored. Retry. |+| `invalid_mint` | — | snapshot | `token` isn't a valid Solana pubkey. Fix it. |+| `payment_required` | 402 | intel / projects / snapshot | Paid lane with no x402 payment. Attach a payer (see [Pricing](#pricing--payment)). |+| field `= null` | 200 | snapshot | A provider was unreachable. The field is `null` and `sources` shows which one — partial data, never fabricated. |++In the sentiment pulse, a pump.fun failure doesn't fail the whole call:+`breakdown.pumpfun` becomes `{ error, count: 0 }` and the overall score reflects+whatever did resolve (e.g. just your `extraTexts`). Branch on it in your UI.++## Examples++**Agent decision gate** — read sentiment + momentum before acting:++```js+import { sentiment, projects } from '@three-ws/intel';++const mint = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump'; // $THREE+const [pulse, scan] = await Promise.all([+ sentiment(mint),+ projects({ chain: 'solana', limit: 5 }),+]);++const bullish = pulse.overall.score > 0.2 && pulse.overall.count >= 20;+const trending = scan.projects.some((p) => (p.scores.spiking ?? 0) > 0.8);+if (bullish && trending) console.log('signal: attention + positive chatter');+```++**Dashboard tile** — render a live token card in the browser:++```html+<script type="module">+ import { snapshot, sentiment } from '@three-ws/intel';++ const mint = 'THREEsynthetic1111111111111111111111111111';+ const [m, s] = await Promise.all([snapshot(mint), sentiment(mint)]);++ document.querySelector('#card').innerHTML = `+ <h3>${m.meta?.name ?? 'Token'} · ${m.meta?.symbol ?? '—'}</h3>+ <p>$${m.priceUsd ?? '—'} · vol $${m.volume24h?.volume24hUsd ?? '—'}</p>+ <p>sentiment ${Math.round(s.overall.posPct)}% positive+ (${s.overall.count} comments)</p>`;+</script>+```++**Narrative monitor** — poll the intel feed for a category:++```js+import { intel } from '@three-ws/intel';++const feed = await intel({ category: 'partnership', limit: 15 });+for (const item of feed.intel) {+ if (item.official_source) console.log(`[${item.ticker}] ${item.description}`);+}+```++## Related++- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate the 3D assets that trade into these markets.+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-pay the aixbt + snapshot lanes in USDC.+- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render an agent that acts on this intelligence.++---++<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>diff --git a/packages/intel/package.json b/packages/intel/package.jsonnew file mode 100644index 000000000..72407cc6f--- /dev/null+++ b/packages/intel/package.json@@ -0,0 +1,28 @@+{+ "name": "@three-ws/intel",+ "version": "0.1.0",+ "description": "Token sentiment + market intelligence in one import. Sentiment pulse, aixbt narrative intel, momentum-ranked project scans, and live Solana token snapshots — the three.ws intelligence SDK.",+ "keywords": [+ "sentiment",+ "market-intelligence",+ "solana",+ "token-snapshot",+ "aixbt",+ "narrative",+ "momentum",+ "pump.fun",+ "x402",+ "three.ws"+ ],+ "license": "MIT",+ "private": true,+ "type": "module",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ }+}diff --git a/packages/names/README.md b/packages/names/README.mdnew file mode 100644index 000000000..99ed49be8--- /dev/null+++ b/packages/names/README.md@@ -0,0 +1,345 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/names</h1>++<p align="center"><strong>ENS + SNS resolution, <code>*.threews.sol</code> subdomain minting, and pay-by-name — agent identity in one import.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/names"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/names?logo=npm&color=cb3837"></a>+ <a href="https://www.npmjs.com/package/@three-ws/names"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/names?color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/names?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/names?color=339933&logo=node.js">+</p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#api">API</a> ·+ <a href="#how-it-works">How it works</a> ·+ <a href="https://three.ws">three.ws</a>+</p>++---++> `@three-ws/names` is the official client for the three.ws **naming layer** —+> the identity plumbing behind every agent on the platform. It resolves+> human-readable names to on-chain addresses across **ENS** (Ethereum) and+> **SNS** (Solana), mints `<label>.threews.sol` subdomains under the+> platform-owned parent, and routes USDC payments to a recipient identified by+> *name* instead of a 44-character base58 key. It wraps the public+> `/api/sns`, `/api/sns-subdomain`, `/api/threews/subdomain`, and+> `/api/x402/pay-by-name` endpoints. If your agent has a wallet, this gives it a+> name people can read, type, and pay.++## Why++A wallet address is unusable as an identity. Nobody types+`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump` from memory, and nobody should+have to. The naming layer turns identity into a string:++- **Resolve in one call.** `resolve('vitalik.eth')` and `resolve('bonfida.sol')`+ hit the right registry automatically — ENS via an Ethereum RPC with failover,+ SNS via Bonfida — and a bare label is tried against both.+- **Mint a name your agent owns.** `mintSubdomain('alice')` registers+ `alice.threews.sol` on-chain, writes a Brave-resolvable URL record, and+ transfers ownership to the agent's wallet — all in one signed transaction.+ The platform absorbs the gas; the agent's wallet never signs.+- **Pay by name.** `payByName('alice.threews.sol', '5')` resolves the recipient+ and builds (or sends) a USDC transfer — handles, `.sol` domains, and raw+ addresses all route through the same call, with a recipient-poisoning guard.++Hand-rolling this means three different on-chain SDKs (Bonfida SNS, ethers, SPL+token), RPC failover, label validation, an availability denylist, and a+preview-then-send flow that survives a name being re-pointed mid-flight. This+package is that, done once.++This is the SDK twin of the [`ens_sns_resolve` MCP tool](https://three.ws/mcp) —+the same resolution engine, exposed as plain functions instead of an MCP tool.++## Install++```bash+npm install @three-ws/names+```++Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch`).+Minting and `mode: 'send'` payments require a signed-in three.ws session or a+bearer token. The browser `prep` lane needs no auth — it returns an unsigned+transaction for a wallet to sign.++## Quick start++Resolution needs no key:++```js+import { resolve } from '@three-ws/names';++const eth = await resolve('vitalik.eth');+console.log(eth.address); // → 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045++const sol = await resolve('bonfida.sol');+console.log(sol.address); // → owner base58 wallet+console.log(sol.allDomains); // → other .sol domains the owner holds+```++Mint a subdomain for an agent and pay it by name:++```js+import { mintSubdomain, payByName } from '@three-ws/names';++// Registers alice.threews.sol on-chain, transfers it to the agent's wallet.+const { full_name, signature } = await mintSubdomain({+ agentId: 'agt_7Yq…',+ label: 'alice', // optional — defaults to the agent's slugified name+ token: process.env.THREEWS_TOKEN,+});+console.log(full_name); // → alice.threews.sol++// Build an unsigned 5-USDC transfer to that name for a browser wallet to sign.+const { tx_base64, recipient } = await payByName('alice.threews.sol', '5', {+ payerWallet: myWallet.publicKey.toBase58(),+});+console.log(recipient.address, recipient.source); // resolved wallet + 'sns'+```++## API++### `resolve(name, options?) → Promise<ResolveResult>`++Resolve a name to an address. `.eth` goes to ENS, `.sol` to SNS, and a bare+label (`vitalik`) is tried against the `.sol` registry. Wraps+`GET /api/sns?name=<name>` for `.sol` and the ENS resolver for `.eth`.++**Returns** `ResolveResult`++| Field | Type | Notes |+|---|---|---|+| `name` | `string` | The resolved name, e.g. `alice.sol` or `vitalik.eth`. |+| `address` | `string \| null` | Owner wallet. `null` when `resolved` is `false`. |+| `network` | `'solana' \| 'ethereum'` | Which registry answered. |+| `resolved` | `boolean` | `false` is a routine "no such name", **not** an error. |+| `allDomains` | `string[]` | (SNS) other `.sol` domains the owner holds. |+| `favoriteDomain` | `string \| null` | (SNS) the owner's primary `.sol`, if set. |++A `.sol` miss returns `200` with `resolved: false` — the reverse-lookup that+runs on every page load makes "no domain" an expected answer, so it is never a+`404`. Malformed input is a `400`.++### `reverseLookup(address) → Promise<ResolveResult>`++Find the primary `.sol` for a wallet. Wraps `GET /api/sns?address=<base58>`.+Returns the same envelope with `name` populated (or `null` if the wallet has no+favorite domain).++### `checkSubdomain(label) → Promise<Availability>`++Check whether `<label>.threews.sol` is free. Wraps+`GET /api/sns-subdomain?label=<label>` (no auth).++| Field | Type | Notes |+|---|---|---|+| `label` | `string` | Normalized label. |+| `parent` | `string` | `threews.sol`. |+| `full_name` | `string` | `<label>.threews.sol`. |+| `available` | `boolean` | `true` if no on-chain owner. |+| `owner` | `string \| null` | Current on-chain owner, if any. |++### `mintSubdomain(input) → Promise<MintResult>`++Mint `<label>.threews.sol`, write its Brave URL record, and transfer ownership+to a wallet — atomically, in one platform-signed transaction. Wraps+`POST /api/sns-subdomain`. Requires auth.++**Input**++| Field | Type | Notes |+|---|---|---|+| `agentId` | `string` | **Required.** The agent the subdomain attaches to. |+| `label` | `string` | Optional. Defaults to the agent's slugified name. 1–63 chars `[a-z0-9-]`. |+| `ownerAddress` | `string` | Optional base58 wallet to receive ownership. Must be **linked to your account**. Defaults to the agent's own Solana wallet. |+| `space` | `number` | Optional, 1000–10000. Registry bytes reserved. Default `2000`. |+| `token` | `string` | Bearer token (or rely on a session cookie). |++**Returns** `MintResult`: `{ ok, agent_id, full_name, parent, owner, signature, explorer, url_record, agent_url }`. The new subdomain's URL record points at+`https://three.ws/a/<agentId>`, and the agent's `meta.sns_domain` is set so x402+manifests can show `recipient_name` without an extra round-trip.++> For a **user/username-claim** subdomain (showcased at `/u/<label>`, where the+> label must equal your username), use `claimSubdomain` instead.++### `claimSubdomain(input) → Promise<ClaimResult>`++Claim `<username>.threews.sol` for the signed-in user, with its URL record set+to `https://three.ws/u/<username>`. Wraps `POST /api/threews/subdomain`. The+`label` **must equal your account username** — divergent labels would let users+impersonate other handles. Pass `ownerWallet` (linked to your account) or fall+back to your default agent's Solana wallet. `releaseSubdomain(label)` wraps the+`DELETE` route to drop the local claim (on-chain ownership is unchanged).++### `payByName(name, amountUsdc, options?) → Promise<PayResult>`++Pay a recipient by name in USDC. Wraps `POST /api/x402/pay-by-name`. The name+resolves across three namespaces in order: **@username** → that user's default+agent wallet; **`.sol` domain** (including `foo.threews.sol`) → on-chain owner;+**raw base58** → pass-through.++**Options**++| Option | Type | Default | Notes |+|---|---|---|---|+| `mode` | `'prep' \| 'send'` | `'prep'` | `prep` returns an unsigned tx; `send` has the agent sign and broadcast. |+| `payerWallet` | `string` | — | **Required for `prep`.** Base58 fee-payer + source. |+| `agentId` | `string` | — | **Required for `send`.** The agent that signs (must be yours). |+| `expectedAddress` | `string` | — | (`send`) the address you previewed. If the name now resolves elsewhere, the call rejects with `recipient_changed` before signing. |+| `message` | `string` | — | Optional memo. |+| `token` | `string` | — | Bearer token for `send`. |++**Returns (`prep`)** `{ recipient, amount_usdc, tx_base64, blockhash, last_valid_block_height, mint }` — decode `tx_base64` into a `VersionedTransaction`, sign with the payer wallet, and submit. **Returns (`send`)** `{ recipient, payer, amount_usdc, signature, mode }`. `amount_usdc` accepts a string or number, must be `> 0` and `≤ 10000`.++### `resolvePayee(name) → Promise<Payee>`++Resolve-only, no payment. Wraps `GET /api/x402/pay-by-name?name=<name>`. Returns+`{ name, address, source, resolved, claim? }` where `source` is one of+`address`, `sns`, or `username`. A `404` means the name resolved nowhere.++## How it works++Three namespaces, one ergonomic surface. Each call routes by the shape of the+string you pass:++```+ resolve / payByName+ │+ ┌───────────┼─────────────────────────┐+ *.eth│ *.sol│ base58 / @handle+ ▼ ▼ ▼+ ENS resolver Bonfida SNS users.username+ (eth RPC, resolve() + reverse → default agent+ failover, domains + fav-domain Solana wallet+ 3s timeout) (.threews.sol also+ │ │ surfaces a DB claim)+ ▼ ▼ ▼+ 0x… address owner base58 recipient address+ │+ mintSubdomain ──▶ createSubdomain → URL record → transferSubdomain+ (one VersionedTransaction, signed by the platform parent-owner keypair)+```++- **ENS** resolves on Ethereum mainnet through a failover provider, bounded by+ a 3-second timeout. A reverse lookup of the owner's primary name is+ best-effort.+- **SNS** resolves through Bonfida — owner wallet, the owner's other `.sol`+ domains, and their favorite domain.+- **Subdomain minting** is a single on-chain transaction: `createSubdomain`+ (parent owner becomes owner) → `createRecordV2Instruction` writes the URL+ record while the platform still owns it (so `<label>.threews.sol` resolves in+ Brave) → `transferSubdomain` hands it to the agent's wallet. The platform's+ parent-owner keypair (`THREEWS_SOL_PARENT_SECRET_BASE58`) is the only signer+ and fee payer — gas is under 0.01 SOL and absorbed, so the agent's wallet+ never has to sign.+- **Pay-by-name** uses the USDC mint (`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,+ 6 decimals), creating the recipient's associated token account idempotently.+ `mode: 'send'` enforces the agent's per-transaction spend limit and rejects+ off-curve recipients.++### Environment++`THREEWS_SOL_PARENT_SECRET_BASE58` — the base58-encoded 64-byte ed25519 secret+for the wallet that owns the parent `.sol` (default `threews.sol`, overridable+with `THREEWS_SOL_PARENT_DOMAIN`). This is **server-side only**; it gates all+subdomain minting. When it is absent the mint endpoints answer `503`+`config_missing` rather than failing mid-transaction — the SDK surfaces that as+a clean error, never a fake success.++## Pricing / payment++| Action | Cost |+|---|---|+| `resolve`, `reverseLookup`, `checkSubdomain`, `resolvePayee` | **Free.** Public, rate-limited per IP. |+| `mintSubdomain`, `claimSubdomain` | **Free** to the caller — the platform absorbs the sub-0.01-SOL gas. Requires auth. |+| `payByName` | The transferred USDC amount, plus Solana network fees. |+| [`ens_sns_resolve` MCP tool](https://three.ws/mcp) | **$0.0005 USDC** over x402 — the metered equivalent of `resolve`. |++`.sol` reads are cached server-side (5 min positive, 60 s negative), and ENS+resolutions are cached 5 min in-memory, so repeated UX previews don't hammer the+RPC pools.++## Errors & edge cases++Every state is designed. Resolution failures return data, not exceptions; only+real faults reject.++| State | HTTP | Meaning | Recovery |+|---|---|---|---|+| `resolved: false` | 200 | Name has no owner. **Not an error.** | Show "unclaimed"; offer to mint. |+| `validation_error` | 400 | Malformed name, label, or amount. | Fix the input. Labels are 1–63 chars `[a-z0-9-]`. |+| `unauthorized` | 401 | Mint or `mode: 'send'` without auth. | Sign in or pass a bearer `token`. |+| `forbidden` | 403 | `ownerAddress` not linked to your account. | Link the wallet, or omit it. |+| `per_tx_exceeded` | 403 | Send over the agent's per-transaction limit. | Lower the amount or raise the agent's limit. |+| `not_found` | 404 | Agent missing, or payee resolved nowhere. | Check the agent ID / name. |+| `agent_missing_wallet` | 412 | Agent has no Solana wallet to attach to. | Provision one via `POST /api/agents/:id/solana`. |+| `conflict` | 409 | `<label>.threews.sol` already registered. | Pick another label. |+| `recipient_changed` | 409 | Name re-pointed since you previewed it. | Re-preview, then re-send. |+| `no_username` / `username_mismatch` | 409 | Claim label ≠ your username. | Set/match your username first. |+| `config_missing` | 503 | Platform parent-owner key not configured. | Server-side `THREEWS_SOL_PARENT_SECRET_BASE58` must be set. |+| `ens_timeout` | 503 | ENS RPC exceeded 3 s. | Retry; the failover provider rotates endpoints. |++## Examples++**Under the hood — resolve `.sol` with raw `fetch`** (what `resolve` wraps):++```js+const r = await fetch('https://three.ws/api/sns?name=bonfida.sol');+const { data } = await r.json();+// → { name: 'bonfida.sol', address: '…', network: 'solana', resolved: true }+```++**Agent identity, end to end** — give an agent a name, then receive a payment:++```js+import { mintSubdomain, resolvePayee } from '@three-ws/names';++const { full_name } = await mintSubdomain({ agentId, label: 'oracle', token });+// → oracle.threews.sol, owned by the agent's wallet, URL record → /a/<agentId>++const payee = await resolvePayee(full_name);+// → { name: 'oracle.threews.sol', address: '…', source: 'sns', claim: … }+```++**Browser pay-by-name** — build, sign in the wallet, submit:++```js+import { payByName } from '@three-ws/names';+import { VersionedTransaction } from '@solana/web3.js';++const { tx_base64 } = await payByName('alice.threews.sol', '2.5', {+ payerWallet: wallet.publicKey.toBase58(),+});+const tx = VersionedTransaction.deserialize(Buffer.from(tx_base64, 'base64'));+const signed = await wallet.signTransaction(tx);+const sig = await connection.sendRawTransaction(signed.serialize());+```++**Agent-signed send** — the agent's custodial wallet pays, with a poisoning guard:++```js+const preview = await resolvePayee('alice.threews.sol');+const { signature } = await payByName('alice.threews.sol', '5', {+ mode: 'send',+ agentId,+ expectedAddress: preview.address, // rejects if the name re-points before signing+ token,+});+```++## Related++- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-pay the `$0.0005` `ens_sns_resolve` MCP tool and other x402 lanes.+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate the agent's 3D avatar to pair with its name.+- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render the named agent's avatar in the browser.++---++<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>diff --git a/packages/names/package.json b/packages/names/package.jsonnew file mode 100644index 000000000..97103a1d3--- /dev/null+++ b/packages/names/package.json@@ -0,0 +1,29 @@+{+ "name": "@three-ws/names",+ "version": "0.1.0",+ "description": "ENS + SNS name resolution, *.threews.sol subdomain minting, and pay-by-name in one import. The three.ws agent-identity SDK.",+ "keywords": [+ "ens",+ "sns",+ "solana-name-service",+ "name-resolution",+ "subdomain",+ "threews.sol",+ "pay-by-name",+ "x402",+ "usdc",+ "agent-identity",+ "three.ws"+ ],+ "license": "MIT",+ "private": true,+ "type": "module",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ }+}diff --git a/packages/reputation/README.md b/packages/reputation/README.mdnew file mode 100644index 000000000..8fa7951a7--- /dev/null+++ b/packages/reputation/README.md@@ -0,0 +1,353 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/reputation</h1>++<p align="center"><strong>Read ERC-8004 agent trust scores and attest agent-to-agent feedback on-chain, in one import.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/reputation"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/reputation?logo=npm&color=cb3837"></a>+ <a href="https://www.npmjs.com/package/@three-ws/reputation"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/reputation?color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/reputation?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/reputation?color=339933&logo=node.js">+</p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#api">API</a> ·+ <a href="#how-it-works">How it works</a> ·+ <a href="#chains">Chains</a> ·+ <a href="https://three.ws">three.ws</a>+</p>++---++> `@three-ws/reputation` is the official client for [ERC-8004](https://eips.ethereum.org/EIPS/eip-8004)+> agent reputation as wired into [three.ws](https://three.ws). One import gives you+> two things: **read** an agent's aggregate trust score, vouch count, total stake,+> and recent feedback events straight from the canonical on-chain+> `ReputationRegistry`; and **resolve** an agent's identity (owner, wallet, URI)+> from the `IdentityRegistry` — by agentId, by EVM wallet, or by CAIP-10 ID. It+> wraps the live three.ws reputation endpoints and the same registries the+> `agent_reputation` MCP tool reads, so the score you get is the score every other+> surface shows. For agents that need to *write* feedback, it speaks the same+> on-chain attestation primitive the platform uses to record validations and+> vouches. Built for agent builders, marketplaces, and anyone who needs trust that+> is backed by money and time, not a follower count.++## Why++Agent reputation only means something if it is non-gameable and auditable.+ERC-8004 puts that on-chain — but reading it by hand means standing up an ethers+provider per chain, juggling failover RPCs, decoding the `getReputation`+`(int256 avgX100, uint256 count)` tuple correctly (the average is already ×100,+signed, and must *not* be divided by count again), resolving an agentId from a+wallet through the `IdentityRegistry`, and scanning logs for `FeedbackSubmitted`+/ `ReputationStaked` events across a sane block window. Get one of those wrong and+your trust score is silently incorrect.++This SDK does it once, correctly:++- **One call, a real score.** `reputation(agentId)` resolves to the aggregate+ average, count, total stake, and the latest vouches — read live from the+ canonical registry, no indexer, no cache, no fabricated fallback.+- **Resolve by anything.** Pass a uint agentId, a `0x` wallet, or a CAIP-10+ `eip155:<chainId>:<wallet>` ID. Wallet → agentId resolution goes through the+ `IdentityRegistry` for you.+- **Multi-chain by default.** Base is the default; 14 other mainnets and 7+ testnets carry the same CREATE2-deterministic registry addresses.+- **Attest, don't just read.** `attest({ agent, score, ... })` records+ agent-to-agent feedback on-chain through the platform's signed attestation+ lane, so an agent can build its own counterpart's track record.++This is the SDK twin of the [`agent_reputation` MCP tool](https://three.ws/mcp) —+the same registries, exposed as plain functions instead of a paid MCP call.++## Install++```bash+npm install @three-ws/reputation+```++Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch`).+Reads are auth-free and walletless. Writing an attestation requires a signed-in+three.ws account or an API token with the `avatars:write` scope.++## Quick start++Read an agent's trust score — no key, no wallet:++```js+import { reputation } from '@three-ws/reputation';++const rep = await reputation(1); // agentId 1 on Base (default chain)++console.log(rep.reputation.average); // → 4.2 (signed; null when count is 0)+console.log(rep.reputation.count); // → "6" (uint as string, transport-safe)+console.log(rep.reputation.totalStakeWei); // → "0"+console.log(rep.identity.owner); // → 0x… (from the IdentityRegistry)+```++Resolve from a wallet, on a chosen chain, and read the latest vouches:++```js+import { reputation } from '@three-ws/reputation';++const rep = await reputation('0xAbc…123', { chain: 'arbitrum' });+// wallet → agentId resolved via the IdentityRegistry++for (const e of rep.events) {+ // e.kind: 'submitted' | 'staked'+ console.log(e.kind, e.score, e.txHash);+}+```++Attest agent-to-agent feedback on-chain:++```js+import { attest } from '@three-ws/reputation';++const receipt = await attest({+ agent: 'THREEsynthetic1111111111111111111111111111',+ kind: 'feedback',+ score: 5,+ detail: 'completed the rig task, clean GLB',+});++console.log(receipt.signature); // → on-chain tx signature+console.log(receipt.status); // → 'minted' | 'deduped'+```++## API++### `reputation(agent, options?) → Promise<ReputationResult>`++Read an agent's on-chain reputation. `agent` accepts a uint `agentId`, an EVM+wallet (`0x…`), or a CAIP-10 `eip155:<chainId>:<wallet>` ID (which also selects+the chain). When you pass a wallet, the agentId is resolved through the+`IdentityRegistry` first.++**Options**++| Option | Type | Default | Notes |+|---|---|---|---|+| `chain` | `string \| number` | `'base'` | Chain name or numeric chainId. See [Chains](#chains). A CAIP-10 `agent` overrides this. |+| `signal` | `AbortSignal` | — | Cancel the in-flight read. |++**Returns** `ReputationResult`++| Field | Type | Notes |+|---|---|---|+| `chain` | `string` | Resolved chain name, e.g. `"Base"`. |+| `chainId` | `number` | Resolved numeric chainId. |+| `agentId` | `string` | The agent's uint id, as a string. |+| `agentRegistry` | `string` | CAIP-10 id of the `IdentityRegistry`, e.g. `eip155:8453:0x8004A1…`. |+| `reputationRegistry` | `string` | `ReputationRegistry` address. |+| `identity` | `object \| null` | `{ owner, agentWallet, uri }`. `null` when owner is the zero address. |+| `reputation` | `object` | `{ averageX100, average, count, totalStakeWei }` — see below. |+| `events` | `object[]` | Latest 25 `submitted` / `staked` events, newest first. |+| `fetchedAt` | `string` | ISO timestamp of the read. |++The `reputation` block is decoded straight from `getReputation` + `getTotalStake`:++| Field | Type | Notes |+|---|---|---|+| `averageX100` | `string` | Raw signed `int256` from the contract — the average already ×100. |+| `average` | `number \| null` | `averageX100 / 100`, sign preserved. `null` when `count` is 0. |+| `count` | `string` | Number of feedback entries (uint, as string). |+| `totalStakeWei` | `string` | Total wei staked on this agent's vouches. |++Each `events[i]` is one of:++| `kind` | Fields |+|---|---|+| `submitted` | `blockNumber`, `txHash`, `submitter`, `score`, `comment` (the feedback URI) |+| `staked` | `blockNumber`, `txHash`, `staker`, `score`, `valueWei` |++### `attest(input) → Promise<AttestReceipt>`++Record agent-to-agent feedback on-chain through the platform's signed+attestation lane (`threews.*` memo, exactly-once). Requires a signed-in account+or a `avatars:write`-scoped token.++**Input**++| Field | Type | Notes |+|---|---|---|+| `agent` | `string` | Target agent asset to attest about. |+| `kind` | `'feedback' \| 'validation' \| 'task'` | What is being attested. |+| `score` | `number` | Feedback score (for `kind: 'feedback'`). |+| `passed` | `boolean` | Pass/fail (for `kind: 'validation'`). |+| `detail` | `string` | Optional human-readable note. |+| `eventId` | `string` | Optional deterministic id — a retry with the same id is idempotent (deduped, never a second tx). |++**Returns** `AttestReceipt` — `{ status, signature, kind }`, where `status` is+`'minted'` (a new on-chain tx), `'deduped'` (a prior attestation for the same+`eventId` already landed), or `'in_progress'` (a concurrent attest is mid-flight).++### `leaderboard(options?) → Promise<Leaderboard>`++Fetch the platform's live ranking of trusted agents+(`GET /api/reputation/leaderboard`) — every rank is the same non-gameable+wallet-trust score the badge shows, computed from real ledger + chain activity.++**Options** — `{ limit?: number }` (1–50, default 20).++**Returns** — `{ generated_at, count, scored, agents }`, where each agent carries+`rank`, `id`, `name`, `score`, `tier`, `tier_label`, `totals`, `agent_url`, and a+`breakdown_url` linking to the auditable breakdown.++### Under the hood — raw HTTP / on-chain++`reputation()` reads directly from the canonical registries with an ethers+provider (the same path the [`agent_reputation` MCP tool](https://three.ws/mcp)+uses), so there is no HTTP read endpoint to call by hand — the registry *is* the+source of truth:++```js+import { Contract, JsonRpcProvider } from 'ethers';++const REPUTATION_REGISTRY = '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63'; // mainnet+const ABI = [+ 'function getReputation(uint256 agentId) view returns (int256 avgX100, uint256 count)',+ 'function getTotalStake(uint256 agentId) view returns (uint256)',+];++const provider = new JsonRpcProvider('https://mainnet.base.org');+const rep = new Contract(REPUTATION_REGISTRY, ABI, provider);+const [avgX100, count] = await rep.getReputation(1n);+const average = count > 0n ? Number(avgX100) / 100 : null; // never divide by count+```++`leaderboard()` is plain HTTP against the public, auth-free endpoint:++```js+const res = await fetch('https://three.ws/api/reputation/leaderboard?limit=20');+const { agents } = await res.json();+```++## How it works++Two canonical, CREATE2-deterministic registries back every read. The+`IdentityRegistry` maps wallets ↔ agentIds; the `ReputationRegistry` holds the+aggregate score, stake, and feedback events. The SDK resolves the identifier,+reads both, and decodes the score correctly:++```+agentId / wallet / eip155:<chain>:<wallet>+ │+ ▼+ ┌──────────────────┐ wallet ┌──────────────────────────┐+ │ resolve agentId ├─────────▶│ IdentityRegistry │ balanceOf → tokenOfOwnerByIndex+ │ │ │ 0x8004A169… (mainnet) │ ownerOf · getAgentWallet · tokenURI+ └────────┬─────────┘ └──────────────────────────┘+ │ agentId+ ▼+ ┌──────────────────────────────────────────────────────┐+ │ ReputationRegistry 0x8004BAa1… (mainnet) │+ │ getReputation → (int256 avgX100, uint256 count) │ average = avgX100 / 100 (signed)+ │ getTotalStake → uint256 wei │+ │ logs: FeedbackSubmitted · ReputationStaked (≤25) │+ └──────────────────────────────────────────────────────┘+```++The registry addresses are deterministic per **network class** — one mainnet+address shared across every mainnet, one testnet address shared across every+testnet:++| Registry | Mainnet | Testnet |+|---|---|---|+| Identity | `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432` | `0x8004A818BFB912233c491871b3d84c89A494BD9e` |+| Reputation | `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63` | — |+| Validation | _pending mainnet deploy_ | `0x8004Cb1BF31DAf7788923b405b754f57acEB4272` |++`attest()` records feedback through the platform's exactly-once memo+attestation: a deterministic `eventId` is the dedupe key, the on-chain memo tx is+the artifact, and a mirror row feeds the reputation reads. Retrying with the same+`eventId` never produces a second tx.++## Chains++Reads default to **Base**. The `IdentityRegistry` is deployed at the same+mainnet address on all of these:++**Mainnets** — Base (8453), Ethereum (1), Arbitrum One (42161), Optimism (10),+Polygon (137), BNB Chain (56), Avalanche (43114), Gnosis (100), Fantom (250),+Celo (42220), Linea (59144), Scroll (534352), Mantle (5000), zkSync Era (324),+Moonbeam (1284).++**Testnets** — Base Sepolia (84532), Arbitrum Sepolia (421614), Ethereum Sepolia+(11155111), Optimism Sepolia (11155420), Polygon Amoy (80002), Avalanche Fuji+(43113), BSC Testnet (97). The testnet `ValidationRegistry` is live; the mainnet+`ValidationRegistry` is pending deploy and is never read with a placeholder+address.++Select a chain by name (`'base'`, `'arbitrum'`, …) or numeric id. A CAIP-10+`agent` argument overrides the `chain` option.++## Errors & edge cases++Reads and writes surface real states, never a fabricated score:++| State | Cause | Recovery |+|---|---|---|+| `no_agent_registered_for_wallet` | The wallet owns no ERC-8004 agent on that chain. | Pass an agentId directly, or check the chain. |+| `unsupported_chain` | Unknown chain name / id. | Use a [supported chain](#chains). |+| `count === 0` → `average: null` | The agent has no feedback yet. | Surface "new agent / no track record", not a zero score. |+| `events: []` | No vouches in the scanned block window. | That's the truth, not a failure — render an empty state. |+| `unauthorized` (401) | `attest()` without a session or token. | Sign in, or use a `avatars:write` token. |+| `insufficient_scope` (403) | Token lacks `avatars:write`. | Mint a scoped token. |+| `rate_limited` (429) | Too many requests. | Honour `retryAfter`. |++A missing identity returns `identity: null` (zero-address owner), not a crash.+An empty registry returns a real empty result, not invented data.++## Examples++**Marketplace gate** — only list agents above a trust floor:++```js+import { reputation } from '@three-ws/reputation';++async function isTrusted(agentId, floor = 4.0) {+ const { reputation: r } = await reputation(agentId);+ return r.average != null && r.average >= floor && Number(r.count) >= 3;+}+```++**Agent-to-agent vouch after a completed task:**++```js+import { attest } from '@three-ws/reputation';++await attest({+ agent: counterpartyAsset,+ kind: 'feedback',+ score: 5,+ detail: `task ${taskId} delivered`,+ eventId: `vouch:${taskId}`, // idempotent — retries dedupe+});+```++**Render the live leaderboard** in the browser:++```js+import { leaderboard } from '@three-ws/reputation';++const { agents } = await leaderboard({ limit: 10 });+agents.forEach((a) =>+ console.log(`#${a.rank} ${a.name} — ${a.tier_label} (${a.score})`),+);+```++## Related++- [`@three-ws/avatar-schema`](https://www.npmjs.com/package/@three-ws/avatar-schema) — validate the on-chain agent manifests these scores attach to.+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate the rig-ready GLB an agent identity wears.+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-pay the `agent_reputation` MCP tool's $0.01 lane.++---++<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>diff --git a/packages/reputation/package.json b/packages/reputation/package.jsonnew file mode 100644index 000000000..c45a053b8--- /dev/null+++ b/packages/reputation/package.json@@ -0,0 +1,28 @@+{+ "name": "@three-ws/reputation",+ "version": "0.1.0",+ "description": "Read ERC-8004 agent trust scores and attest agent-to-agent feedback on-chain, in one import. The three.ws reputation SDK — canonical Identity + Reputation registries on Base and 14 other chains.",+ "keywords": [+ "erc-8004",+ "erc8004",+ "agent-reputation",+ "trust-score",+ "attestation",+ "identity-registry",+ "reputation-registry",+ "onchain",+ "agents",+ "three.ws"+ ],+ "license": "MIT",+ "private": true,+ "type": "module",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ }+}diff --git a/packages/vanity/README.md b/packages/vanity/README.mdnew file mode 100644index 000000000..95b211f8b--- /dev/null+++ b/packages/vanity/README.md@@ -0,0 +1,350 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/vanity</h1>++<p align="center"><strong>Mine Solana vanity addresses — custom prefix and/or suffix — fast, WASM-accelerated, in the browser or Node.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/vanity"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/vanity?logo=npm&color=cb3837"></a>+ <a href="https://www.npmjs.com/package/@three-ws/vanity"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/vanity?color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/vanity?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/vanity?color=339933&logo=node.js">+</p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#api">API</a> ·+ <a href="#how-it-works">How it works</a> ·+ <a href="#pricing">Pricing</a> ·+ <a href="https://three.ws/vanity">three.ws</a>+</p>++---++> `@three-ws/vanity` grinds Solana addresses whose Base58 form starts with a+> prefix and/or ends with a suffix of your choosing — `THREE…`, `…pump`, your+> ticker, your handle. The hot loop is a real Rust + `ed25519-dalek` + `bs58`+> grinder compiled to WebAssembly (it already ships in the three.ws repo at+> `src/solana/vanity/wasm`, ~25k keypairs/sec single-threaded). In the browser+> it fans that WASM module across every CPU core via a Web Worker pool; in Node+> it runs the same module on the request thread. Keys are generated entirely on+> your machine and **never leave it**. For agents that can't or won't run WASM,+> the same capability is exposed as a paid x402 HTTP endpoint and the+> `vanity_grinder` MCP tool.++## Why++Vanity grinding is embarrassingly parallel keypair generation: make an Ed25519+keypair, Base58-encode the public key, check the prefix/suffix, repeat until a+hit. The naïve version is twenty lines of JavaScript — and unusably slow,+because pure-JS Ed25519 manages a few thousand candidates per second. A 4-char+prefix expects ~11M attempts. You need native-speed crypto, real+parallelism, and an honest difficulty model so you don't kick off a grind that+finishes next century.++`@three-ws/vanity` is that, done once:++- **WASM-fast, not JS-slow.** The Rust grinder runs the keygen → encode → match+ loop in fixed-size batches inside WebAssembly. ~25k/sec per thread.+- **Every core, automatically.** The browser path races one worker per logical+ core (capped, configurable). First match wins; the rest are killed instantly.+- **Difficulty up front.** `expectedAttempts()` and a live ETA tell you whether+ a pattern is seconds or years *before* you commit a fan.+- **Keys stay local.** The grind happens client-side. No address, no secret key,+ no telemetry is sent anywhere. That is the entire security posture (see below).+- **A paid lane when you can't grind.** Short patterns (≤3 chars) are available+ over x402 — pay per call in USDC, get a fresh keypair, no toolchain.++This is the SDK twin of the [3D Studio MCP server](https://three.ws/mcp)'s+`vanity_grinder` tool and the [`/vanity`](https://three.ws/vanity) browser+grinder — the same engine, exposed as plain functions.++## Install++```bash+npm install @three-ws/vanity+```++Zero runtime dependencies — the WASM binary is bundled. Works in Node 18+ and+any browser with WebAssembly + Web Workers. To turn the 64-byte secret key into+a usable wallet, add [`@solana/web3.js`](https://www.npmjs.com/package/@solana/web3.js)+(peer, optional): `Keypair.fromSecretKey(result.secretKey)`.++## Quick start++Grind an address that starts with `THREE`, across every core:++```js+import { grind } from '@three-ws/vanity';++const { publicKey, secretKey, attempts, durationMs } = await grind({+ prefix: 'THREE',+});++console.log(publicKey); // → THREE… (Base58)+console.log(secretKey); // → Uint8Array(64), Solana's standard keypair layout+```++`secretKey` is the 64-byte Ed25519 layout (`[32-byte seed][32-byte pubkey]`),+ready for `Keypair.fromSecretKey()`:++```js+import { Keypair } from '@solana/web3.js';+const wallet = Keypair.fromSecretKey(secretKey);+```++A fuller run — suffix, case-insensitive, live progress + ETA, cancellable:++```js+import { grind, expectedAttempts } from '@three-ws/vanity';++const controller = new AbortController();+console.log('expected attempts:', expectedAttempts({ prefix: 'ag', suffix: 'nt' }));++const result = await grind({+ prefix: 'ag',+ suffix: 'nt',+ ignoreCase: true,+ maxWorkers: 6,+ signal: controller.signal,+ onProgress: ({ attempts, rate, eta }) => {+ console.log(`${attempts.toLocaleString()} tried · ${Math.round(rate)}/s · ETA ${eta}`);+ },+});+// later, to bail out: controller.abort();+```++Pick the **suffix** when you can: the leading characters of a Base58-encoded+32-byte key are not uniformly distributed, so a given prefix can be markedly+harder than `58^n` predicts. Suffix characters are uniform.++## API++### `grind(options) → Promise<GrindResult>`++Grind for a vanity address. In the browser it spawns a Web Worker pool driving+the WASM module; in Node it runs the WASM module on the calling thread. Rejects+with `AbortError` if `signal` aborts.++| Option | Type | Default | Notes |+|---|---|---|---|+| `prefix` | `string` | — | Base58 prefix the address must start with. |+| `suffix` | `string` | — | Base58 suffix the address must end with. |+| `ignoreCase` | `boolean` | `false` | Case-insensitive match (folds upper+lower Base58 chars). |+| `maxWorkers` | `number` | `min(cores, 8)` | Browser worker count, clamped to `hardwareConcurrency`. |+| `signal` | `AbortSignal` | — | Cancel the grind. |+| `controller` | `object` | — | Opt-in handle; `grind` attaches `pause()`, `resume()`, `stop()` once the pool is live. |+| `onProgress` | `(p) => void` | — | Called ~every 250ms with `{ attempts, rate, eta, paused? }`. |++At least one of `prefix` / `suffix` is required. Both are validated against the+Base58 alphabet (`0 O I l` excluded) and a 6-char-per-pattern ceiling before any+work starts — an invalid pattern rejects immediately with a specific message.++**Returns** `GrindResult`++| Field | Type | Notes |+|---|---|---|+| `publicKey` | `string` | Base58 address (matches your pattern). |+| `secretKey` | `Uint8Array(64)` | Ed25519 secret key — `Keypair.fromSecretKey()`-compatible. |+| `attempts` | `number` | Total keypairs tried across all workers. |+| `durationMs` | `number` | Wall-clock duration. |+| `workers` | `number` | Workers used (browser; `1` in Node). |++**`onProgress` payload**++| Field | Type | Notes |+|---|---|---|+| `attempts` | `number` | Running total across the pool. |+| `rate` | `number` | Combined keypairs/sec. |+| `eta` | `string` | Human estimate of remaining time — `"~12 seconds"`, `"~3 hours"`, `"paused"`, `"unknown"`. |+| `paused` | `boolean` | Present and `true` while paused. |++### `expectedAttempts({ prefix?, suffix?, ignoreCase? }) → number`++The mean of the geometric distribution — `58^n` adjusted for case-insensitivity+per character. Use it to gate a pattern before grinding (e.g. warn past a+threshold).++### `validatePattern(pattern) → { valid, errors }`++Validate a single prefix or suffix against the Base58 alphabet and length ceiling.+Returns specific, user-facing error strings (e.g. `invalid character 'O'+(uppercase o) — use other uppercase letters`).++### `grindViaApi(options) → Promise<ApiResult>` — the paid lane++For environments without WASM/Workers, grind a short pattern over the hosted+[x402](https://x402.org) endpoint instead of locally. Wraps+`GET /api/x402/vanity`. Combined pattern capped at 3 chars; pass an+x402-capable `fetch` to settle the 402 automatically.++| Option | Type | Notes |+|---|---|---|+| `prefix` / `suffix` | `string` | Combined ≤ 3 chars. |+| `ignoreCase` | `boolean` | Case-insensitive match. |+| `format` | `'keypair' \| 'mnemonic'` | `mnemonic` returns an importable BIP-39 phrase (≤ 2 chars, ~100× slower). |+| `strength` | `128 \| 256` | Mnemonic only: 12 or 24 words. |+| `sealTo` | `string` | Optional X25519 public key — the secret is ECIES-sealed to you and the plaintext is omitted from the response. |+| `fetch` | `typeof fetch` | An x402-wrapped fetch (see [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch)). |++Response fields: `address`, `secretKeyBase58`, `secretKey` (64-int array),+`attempts`, `durationMs`, `expectedAttempts`, `network`, `explorerUrl`, and —+for `format=mnemonic` — `mnemonic`, `wordCount`, `derivationPath`.++## How it works++Two backends, one `grind()` surface. Picked by environment.++```+ grind({ prefix, suffix })+ │+ ┌───────── browser ─┴─ Node ──────────┐+ ▼ ▼+ Web Worker pool (1/core, capped) WASM on the request thread+ │ start/pause/resume/stop │ batched, time-budgeted+ ▼ ▼+ ┌──────────────────────────────────────────────────────────┐+ │ Rust + ed25519-dalek + bs58 → WebAssembly │+ │ grind(prefix, suffix, ignoreCase, batchSize, seed) │+ │ → null | { publicKey: string, secretKey: Uint8Array(64) }│+ └──────────────────────────────────────────────────────────┘+ │ first match wins → pool terminated+ ▼+ { publicKey, secretKey, attempts, durationMs }+```++- **WASM core** — the hot loop (CSPRNG seed → Ed25519 keygen → Base58 encode →+ prefix/suffix compare) runs entirely inside WebAssembly in fixed-size batches.+ Built from `crates/vanity-grinder` via `npm run build:wasm`; the compiled+ artifact is checked into `src/solana/vanity/wasm/` so there's no Rust+ toolchain at install time.+- **Browser pool** — one worker per logical core (default `min(cores, 8)`).+ Each worker yields to its event loop between batches, so `pause`/`stop`+ messages land within one batch (≤~200ms). Pausing genuinely frees the cores;+ resume continues the attempt count.+- **Node path** — no Worker pool in a serverless function, so the same WASM+ module runs single-threaded under a wall-clock budget. The hosted endpoint+ caps patterns at 3 chars for this reason; anything longer belongs in the+ browser pool.++## Security++This is the part that matters for a secret-key tool.++- **Keys are generated locally and never transmitted.** In both the browser and+ Node SDK paths, the keypair is produced on your machine inside WASM. No+ address, no secret key, no prefix is sent to three.ws or anywhere else. There+ is no network call on the local `grind()` path.+- **The secret exists once, in memory.** `grind()` resolves with the+ `secretKey`; nothing persists it. Capture it (write the wallet, store it+ encrypted) before the value goes out of scope.+- **The paid lane is fresh-per-request and never stored.** The x402 endpoint+ grinds a brand-new keypair per call and returns it once over TLS; it is never+ written to disk and is stripped from the idempotency cache. Because that+ secret transits the network, prefer `sealTo` (ECIES-seal it to your X25519+ key so the plaintext never appears in the response or any proxy log) — or just+ grind locally.+- **MCP responses can be logged.** The `vanity_grinder` MCP tool returns a real,+ spendable secret in plaintext over the MCP channel, which the host (Claude+ Desktop, Cursor, any proxy) may log. Import it immediately and never reuse a+ secret that may have been logged. For the strongest guarantee, grind locally+ with this SDK.++## Pricing++The local `grind()` path is free and unlimited — it's your CPU. Pricing only+applies to the paid `grindViaApi()` HTTP lane, which is difficulty-tiered+(each Base58 character multiplies expected work by ~58):++| Combined chars | `keypair` | `mnemonic` |+|---|---|---|+| 1 | **$0.01** | **$0.05** |+| 2 | **$0.05** | **$0.50** |+| 3 | **$0.25** | — (capped at 2) |++A [provably-fair lane](https://three.ws/vanity/verify) (`GET+/api/x402/vanity-verifiable`, $0.02–$0.40) grinds under a commit–reveal protocol+and returns a signed receipt you can verify entirely client-side. Settlement+runs only **after** a successful grind, so an exhausted budget costs nothing and+can be retried. Pay per call in USDC on Base or Solana mainnet — no API keys, no+accounts. Pair with [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch)+to automate the 402.++## Errors & edge cases++The local `grind()` path rejects on:++| Condition | Surfaces as |+|---|---|+| No `prefix` and no `suffix` | `Error: prefix or suffix is required` |+| Non-Base58 char (`0 O I l`, etc.) | `Error: invalid prefix: invalid character 'O' …` |+| Pattern longer than 6 chars | `Error: length 7 exceeds maximum of 6` |+| `signal` aborted | `AbortError` (`DOMException`) |+| Worker crash (browser) | The worker's error, rejecting the promise |++The paid `grindViaApi()` path surfaces the endpoint's HTTP errors:++| `code` | HTTP | Meaning | Recovery |+|---|---|---|---|+| `validation_error` | 400 | Bad pattern, format, or strength. | Fix the input. |+| `pattern_too_long` | 400 | Combined pattern > server cap (3, or 2 for mnemonic). | Grind locally with `grind()`. |+| `grind_exhausted` | 504 | Time budget elapsed without a hit (rare, <1% at 3 chars). | Retry — you weren't charged. |+| `rate_limited` | 429 | Pre-payment probe rate limit. | Honour `retry-after`. |++Long patterns are designed, not crashed: the server tells you to move to the+browser pool, where there's no cap and every core is in play.++## Examples++**Node — grind, then write a Solana CLI keypair file:**++```js+import { grind } from '@three-ws/vanity';+import { writeFileSync } from 'node:fs';++const { publicKey, secretKey } = await grind({ suffix: 'pump' });+writeFileSync(`${publicKey}.json`, JSON.stringify(Array.from(secretKey)));+// → solana config set --keypair ./<address>.json+```++**Browser — pause/resume a long grind with a controller:**++```js+import { grind } from '@three-ws/vanity';++const controller = {};+const job = grind({ prefix: 'THREE', controller, onProgress: render });++document.querySelector('#pause').onclick = () => controller.pause();+document.querySelector('#resume').onclick = () => controller.resume();+document.querySelector('#stop').onclick = () => controller.stop();++const { publicKey, secretKey } = await job;+```++**Agent — the free MCP tool, no toolchain:**++```js+// The same capability ships as the `vanity_grinder` MCP tool on the+// three.ws MCP server. Or call the paid HTTP lane directly:+import { grindViaApi } from '@three-ws/vanity';+import { wrapFetchWithPayment } from '@three-ws/x402-fetch';++const { address, secretKeyBase58 } = await grindViaApi({+ prefix: 'ag',+ fetch: wrapFetchWithPayment(fetch, payer),+});+```++## Related++- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-pay the 402 on the hosted grinder.+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — text/image → rig-ready 3D GLB, the same SDK pattern.+- [`@three-ws/pumpfun-mcp`](https://www.npmjs.com/package/@three-ws/pumpfun-mcp) — launch a token to a vanity mint you ground here.++---++<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>diff --git a/packages/vanity/package.json b/packages/vanity/package.jsonnew file mode 100644index 000000000..1ce07ef9b--- /dev/null+++ b/packages/vanity/package.json@@ -0,0 +1,30 @@+{+ "name": "@three-ws/vanity",+ "version": "0.1.0",+ "description": "Mine Solana vanity addresses (custom prefix/suffix) fast — WASM-accelerated, in the browser or Node. Ergonomic grind() API over a real Rust/ed25519 grinder, with progress, difficulty/ETA, and a paid x402 fallback.",+ "keywords": [+ "solana",+ "vanity",+ "vanity-address",+ "keypair",+ "ed25519",+ "wasm",+ "bs58",+ "base58",+ "wallet",+ "mnemonic",+ "x402",+ "three.ws"+ ],+ "license": "MIT",+ "private": true,+ "type": "module",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ }+}diff --git a/packages/voice/README.md b/packages/voice/README.mdnew file mode 100644index 000000000..cb5f45d6b--- /dev/null+++ b/packages/voice/README.md@@ -0,0 +1,324 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/voice</h1>++<p align="center"><strong>Give your avatar a voice — speech in, speech out, and lips that move. ASR, TTS, and Audio2Face lipsync in one import.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/voice"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/voice?logo=npm&color=cb3837"></a>+ <a href="https://www.npmjs.com/package/@three-ws/voice"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/voice?color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/voice?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/voice?color=339933&logo=node.js">+</p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#api">API</a> ·+ <a href="#how-it-works">How it works</a> ·+ <a href="https://three.ws">three.ws</a>+</p>++---++> `@three-ws/voice` is the official client for the three.ws **voice loop** — the+> three endpoints that let an avatar hear, speak, and move its face in sync.+> `transcribe()` turns spoken audio into text (NVIDIA Riva ASR), `speak()` turns+> text into a voiced clip (NVIDIA Magpie TTS, ElevenLabs for cloned voices), and+> `lipsync()` turns that audio into a per-frame ARKit blendshape track (NVIDIA+> Audio2Face-3D) that drives the avatar's mouth and face. It wraps the live,+> auth-free `/api/asr`, `/api/tts/speak`, and `/api/a2f` endpoints. The visemes+> it produces are exactly what [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar)+> plays back on a loaded GLB — this is the voice half of a talking avatar.++## Why++A talking avatar needs three separate systems wired together: a recognizer to+hear the user, a synthesizer to give the avatar a voice, and a facial-animation+model so the mouth matches the words. Each is a different provider, a different+wire format, and a different failure mode. Hand-rolling that means juggling gRPC+audio encodings, WAV header parsing, sample-rate resampling, ARKit blendshape+ordering, and three sets of rate limits.++`@three-ws/voice` is that loop, done once:++- **One import, the whole loop.** `transcribe(audio)`, `speak(text)`,+ `lipsync(audio)` — hear, speak, and animate the face from three plain calls.+- **Free first.** All three lanes lead with NVIDIA NIM (Riva, Magpie,+ Audio2Face-3D) — no key, no wallet, no card on the free path.+- **Cross-browser by default.** Server-side Riva recognition replaces the+ Chrome/Edge-only `window.webkitSpeechRecognition`, so voice input works in+ Firefox and inside embeds too.+- **Lips that match the exact bytes.** `lipsync()` returns time-coded ARKit+ weights for the precise clip you'll play — drop them straight into+ [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar).++Every lane is purely additive on the platform: when a provider isn't configured,+the endpoint returns a clean `not_configured` state instead of crashing, and the+avatar falls back to in-browser recognition / amplitude lipsync.++## Install++```bash+npm install @three-ws/voice+```++Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch`).+To render the visemes on a GLB, add [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar).++## Quick start++Text to a voiced clip, no key:++```js+import { speak } from '@three-ws/voice';++const clip = await speak('Hi, I am your three.ws avatar.', { voice: 'nova' });+new Audio(clip.url).play(); // clip.url is an object URL for the synthesized audio+```++The full loop — hear the user, answer, animate the face:++```js+import { transcribe, speak, lipsync } from '@three-ws/voice';++// 1. Speech → text (record audio in the browser, send the bytes)+const { text } = await transcribe(audioBlob); // → "what's the weather like"++// 2. Text → speech (your agent decides the reply)+const reply = await speak(`You said: ${text}`, { voice: 'nova' });++// 3. Speech → ARKit visemes for the exact clip you'll play+const face = await lipsync(reply.blob);+// face.blendShapeNames → ["eyeBlinkLeft", "jawOpen", …] (ARKit-52)+// face.frames → [{ t: 0.0, w: [...] }, { t: 0.033, w: [...] }, …] at 30 fps+```++One-shot: synthesize **and** animate in a single call (server speaks the text+with Magpie, then animates that exact audio):++```js+const { audio, animation } = await say('Welcome back.', { voice: 'nova' });+// audio.url → play it · animation.frames → drive the face, perfectly aligned+```++## API++### `transcribe(audio, options?) → Promise<Transcript>`++Speech → text on the free NVIDIA Riva ASR lane. Wraps `POST /api/asr`. `audio`+is a `Blob`, `ArrayBuffer`, or `Uint8Array`; the SDK reads the encoding from the+blob's MIME type (or `options.format`).++**Options**++| Option | Type | Default | Notes |+|---|---|---|---|+| `format` | `'wav' \| 'pcm' \| 'flac' \| 'ogg'` | from MIME | Audio encoding. WebM/Opus must be decoded to PCM/WAV client-side first. |+| `language` | `string` | `'en-US'` | BCP-47 language code. |+| `sampleRate` | `number` | `16000` | Required for raw `pcm`; WAV carries its own rate in the header. |+| `words` | `boolean` | `false` | Return word-level timestamps. |+| `model` | `string` | — | Override the Riva model name. |+| `signal` | `AbortSignal` | — | Cancel an in-flight request. |++**Returns** `Transcript`++| Field | Type | Notes |+|---|---|---|+| `text` | `string` | The recognized utterance. |+| `confidence` | `number` | Mean confidence across results (0–1). |+| `language` | `string` | Detected language code. |+| `model` | `string` | Model that produced the transcript. |+| `durationSec` | `number` | Seconds of audio processed. |+| `words` | `{ word, startMs, endMs, confidence }[]` | Present only when `words: true`. |++### `speak(text, options?) → Promise<Clip>`++Text → a voiced audio clip. Wraps `POST /api/tts/speak` (NVIDIA Magpie free+lane; OpenAI is the paid backstop). Returns the complete audio as a `Blob` plus+a ready-to-play object `url`.++**Options**++| Option | Type | Default | Notes |+|---|---|---|---|+| `voice` | `string` | `'nova'` | One of the [voice catalog](#voices) ids. |+| `format` | `'mp3' \| 'wav' \| 'opus' \| 'aac' \| 'flac' \| 'pcm'` | `'mp3'` | Output container. Magpie emits PCM, so non-`pcm` requests are served as WAV. |+| `language` | `string` | `'en-US'` | BCP-47 language code. |+| `speed` | `number` | `1.0` | Clamped to 0.5–2.0 (paid backstop only). |+| `model` | `string` | — | `tts-1`, `tts-1-hd`, or `gpt-4o-mini-tts` (backstop). |+| `signal` | `AbortSignal` | — | Cancel an in-flight request. |++**Returns** `Clip`: `{ blob, url, contentType, voice, format, model }`. The+`x-tts-voice` / `x-tts-model` / `x-tts-format` response headers always describe+the bytes actually sent.++> `text` is capped at 4096 characters per call.++### `lipsync(audio, options?) → Promise<FaceTrack>`++Speech → a per-frame ARKit blendshape track. Wraps `POST /api/a2f` with audio+(NVIDIA Audio2Face-3D). `audio` is a `Blob` / `ArrayBuffer` of `wav` or `pcm`.+The track's time codes are in **seconds from clip start**, so play the original+audio and sample the track by the audio element's `currentTime`.++**Returns** `FaceTrack`++| Field | Type | Notes |+|---|---|---|+| `fps` | `number` | Frame cadence (30 fps native). |+| `blendShapeNames` | `string[]` | ARKit-52 names, the order `frames[i].w` follows. |+| `frames` | `{ t, w }[]` | `t` = seconds from start, `w` = weights (0–1) in `blendShapeNames` order. |+| `frameCount` | `number` | Number of frames. |+| `durationSec` | `number` | Clip length in seconds. |++### `say(text, options?) → Promise<{ audio, animation }>`++One-shot text → speech → face. Wraps `POST /api/a2f` with `{ text, voice,+language }`: the server synthesizes with Magpie, animates that exact clip, and+returns both. `audio` is `{ url, blob, contentType, format, voiceName }`;+`animation` is the same shape as `FaceTrack`. Use this when latency matters more+than picking your own TTS — one round trip instead of two.++### `voices() → Promise<VoiceCatalog>`++Fetch the live voice catalog (`GET /api/tts/voices`) — ids, names, descriptions,+which synthesis lanes are configured. Render a picker before the user commits.++### Capability probes++Each lane answers a `GET` probe so a UI can decide whether to use the server lane+or its in-browser fallback without sniffing the browser:++- `GET /api/asr` → `{ configured, encodings, sampleRate }`+- `GET /api/a2f` → `{ configured, canSynthesize, model, fps, blendshapeFormat: 'arkit', sampleRate, accepts }`++## Voices++`speak()` and `say()` accept these ids (full catalog is live at `voices()`):++| id | Voice | id | Voice |+|---|---|---|---|+| `nova` *(default)* | Bright, energetic | `echo` | Calm, measured |+| `alloy` | Neutral, balanced | `fable` | Expressive storyteller |+| `ash` | Warm, expressive | `onyx` | Deep, authoritative |+| `ballad` | Soft, lyrical | `sage` | Gentle, thoughtful |+| `coral` | Friendly, upbeat | `shimmer` | Light, airy |+| `verse` | Dynamic, conversational | | |++The same id renders on either lane: the free Magpie lane maps each to a persona,+the paid backstop uses the id directly.++## How it works++Three NVIDIA NIM models on one face, closing the loop user → avatar → user:++```+ user speaks avatar speaks+ │ ▲+ ▼ │+ ┌──────────┐ POST /api/asr POST /api/tts/speak ┌──────────┐+ │ microphone│ ───────────────▶ text ──────────────────▶ │ speaker │+ └──────────┘ Riva ASR (free) │ Magpie TTS (free) └──────────┘+ │ ElevenLabs (cloned) ▲+ ▼ │+ agent / app logic audio ───────────┘+ │+ POST /api/a2f (Audio2Face-3D, free)+ │+ ▼+ ARKit-52 blendshape track ──▶ @three-ws/avatar+ { fps, blendShapeNames, frames:[{t,w}] } (lips move)+```++- **ASR** — Riva offline `Recognize` over NVCF gRPC. Browsers can't all produce+ the same codec, so the cross-browser default is raw 16-bit PCM (or WAV, whose+ header is parsed to LINEAR_PCM). Needs `NVIDIA_API_KEY` + `NVIDIA_ASR_FUNCTION_ID`.+- **TTS** — Magpie leads (free, gRPC); OpenAI `/v1/audio/speech` is the paid+ last-resort backstop. The clip is fully buffered before a byte ships, so a+ Magpie failure fails over cleanly.+- **Lipsync** — Audio2Face-3D bidirectional streaming. Audio is downmixed to+ mono and resampled to 16 kHz, then streamed; the server streams back the+ ordered ARKit names followed by per-frame weights at 30 fps. Works out of the+ box with just `NVIDIA_API_KEY` (a stable published model id; override with+ `NVIDIA_A2F_FUNCTION_ID`).++A2F emits ARKit-52 names; [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar)+maps them onto whatever convention the loaded GLB exposes (ARKit / RPM / VRM /+Oculus), so the same track drives any avatar.++## Pricing++The three NVIDIA NIM lanes are **free** (credit-metered, no payment). The lanes+are metered to bound abuse: signed-in callers get a per-user budget, anonymous+callers a tighter per-IP one — exceeding it returns `429`. The OpenAI TTS+backstop and ElevenLabs cloned voices are paid provider lanes used only when+configured; the free Magpie lane covers the default voices end to end.++## Errors & edge cases++Each call rejects with a typed `VoiceError` carrying a `code` that mirrors the+endpoint's response:++| `code` | HTTP | Meaning | Recovery |+|---|---|---|---|+| `not_configured` | 503 | The lane's provider key isn't set on the server. | Fall back to in-browser recognition / amplitude lipsync. |+| `unsupported_media_type` | 415 | Audio Content-Type the lane can't accept (e.g. WebM/Opus). | Decode to PCM/WAV client-side first. |+| `bad_request` | 400 | Missing audio/text, or `text` over 4096 chars. | Fix the input. |+| `payload_too_large` | 413 | Audio exceeds the 8 MB limit. | Send a shorter clip. |+| `rate_limited` | 429 | Per-user / per-IP budget exceeded. | Honour `retryAfter`; sign in for a higher limit. |+| `invalid_argument` | 400 | Provider rejected the encoding / rate / language. | Check `format` + `sampleRate`. |+| `provider_error` / `upstream_error` | 502 | Upstream provider failed. | Retry. |+| `timeout` | 504 | Audio2Face exceeded its deadline. | Send a shorter clip and retry. |++Every state is designed: an unconfigured lane returns `not_configured` (not a+crash), so the client keeps its existing browser path. A2F's text path+additionally needs Magpie TTS — without it, `say()` returns `not_configured` and+you pass pre-synthesized audio to `lipsync()` instead.++## Examples++**Browser voice loop → animated avatar.** Record, transcribe, answer, and drive+the face on a loaded GLB:++```js+import { transcribe, say } from '@three-ws/voice';++const heard = await transcribe(recordedBlob); // user speech → text+const { audio, animation } = await say(reply(heard.text)); // reply → voice + face++const el = document.createElement('audio');+el.src = audio.url;+el.play();+// sample `animation.frames` by el.currentTime and apply to the avatar's+// morph targets — @three-ws/avatar does this mapping for you.+```++**Node — synthesize a narration clip to a file:**++```js+import { writeFile } from 'node:fs/promises';+import { speak } from '@three-ws/voice';++const clip = await speak('The only coin is $THREE.', { voice: 'onyx', format: 'wav' });+await writeFile('line.wav', Buffer.from(await clip.blob.arrayBuffer()));+```++**Agent — caption an audio clip (word-level timestamps):**++```js+const { text, words } = await transcribe(clip, { words: true });+for (const w of words) console.log(`${(w.startMs / 1000).toFixed(2)}s ${w.word}`);+```++## Related++- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render a GLB and play these visemes as real lipsync.+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate and auto-rig the GLB this voice loop speaks through.+- [`@three-ws/react`](https://www.npmjs.com/package/@three-ws/react) — React bindings for the three.ws avatar runtime.++---++<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>diff --git a/packages/voice/package.json b/packages/voice/package.jsonnew file mode 100644index 000000000..58f4bc4db--- /dev/null+++ b/packages/voice/package.json@@ -0,0 +1,29 @@+{+ "name": "@three-ws/voice",+ "version": "0.1.0",+ "description": "Speech for avatars — ASR (speech→text), TTS (text→speech), and Audio2Face-3D lipsync visemes in one import. The voice layer for three.ws avatars.",+ "keywords": [+ "asr",+ "tts",+ "speech-to-text",+ "text-to-speech",+ "lipsync",+ "visemes",+ "audio2face",+ "blendshapes",+ "arkit",+ "avatar",+ "three.ws"+ ],+ "license": "MIT",+ "private": true,+ "type": "module",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ }+}diff --git a/packages/x402-server/README.md b/packages/x402-server/README.mdnew file mode 100644index 000000000..2c2136248--- /dev/null+++ b/packages/x402-server/README.md@@ -0,0 +1,376 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/x402-server</h1>++<p align="center"><strong>The merchant side of <a href="https://x402.org">x402</a> — turn any HTTP endpoint into a paid one in a few lines. Issue the 402, price the work, verify and settle the payment, take your fee.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/x402-server"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/x402-server?logo=npm&color=cb3837"></a>+ <a href="https://www.npmjs.com/package/@three-ws/x402-server"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/x402-server?color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/x402-server?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/x402-server?color=339933&logo=node.js">+</p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#api">API</a> ·+ <a href="#how-it-works">How it works</a> ·+ <a href="#payment">Payment</a> ·+ <a href="https://three.ws">three.ws</a>+</p>++---++> `@three-ws/x402-server` is the **seller** half of x402: the middleware and+> primitives that make an endpoint demand payment. Wrap a route with `paid()`+> and it answers an unpaid request with a `402 Payment Required` challenge —+> listing what it `accepts` (asset · amount · network · pay-to) — then, on the+> retry that carries an `X-PAYMENT` header, it verifies the payment, runs your+> handler, settles on-chain, and returns the result with an `X-PAYMENT-RESPONSE`+> receipt. It speaks the two lanes the three.ws rails already run in production:+> **Solana** (facilitator-settled SPL `transferChecked`) and **EVM / Base**+> (gasless [EIP-3009](https://eips.ethereum.org/EIPS/eip-3009)+> `transferWithAuthorization`). It is the server twin of the buyer-side+> [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch)+> and [`@three-ws/x402-modal`](https://www.npmjs.com/package/@three-ws/x402-modal) —+> they pay; this charges.++## Why++x402 revives HTTP `402 Payment Required` as a real payment rail: a server+answers a request with a `402` whose body lists its `accepts[]`, the client+pays, and re-sends the request with an `X-PAYMENT` header. The buyer side is a+solved problem — drop in a fetch wrapper or the modal and it pays. **The seller+side is where everyone reinvents the same machinery:** build the challenge+envelope in the exact v2 shape, advertise the right asset/fee-payer per chain,+parse the `X-PAYMENT` header, call a facilitator's `/verify`, run the work+*only after* verification, settle *only after* the work succeeds, emit the+receipt, and skim a platform fee out of the price without double-charging the+buyer.++This package is that machinery, done once, the way the three.ws merchant rails+do it:++- **One wrapper, a paid route.** `paid({ price, asset, payTo })` emits the 402+ and gates your handler behind a verified payment.+- **Two lanes, one API.** Solana and Base/EVM accepts come from the same config;+ the challenge advertises both and the buyer picks.+- **Settle after the work, never before.** Verification gates the handler;+ settlement runs after it returns `200`. A failed call moves no funds, so a+ retry can't double-charge.+- **Fee without surprise-billing.** A platform fee is split out of the listed+ price — the buyer's total is never marked up, and the fee ships inert (rate+ `0`, no treasury) until you turn it on.++This is the same flow that powers paid MCP tools and hosted checkout SKUs on+[three.ws](https://three.ws); the package is its standalone, embeddable home.++## Install++```bash+npm install @three-ws/x402-server+```++Node 18+ (uses the global `fetch` and Web Crypto). Framework-agnostic: works as+Express/Connect middleware, a Fastify hook, or a bare `(req, res)` handler on+Vercel / Node `http`. For the buyer side of a test, pair with+[`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch).++## Quick start++### The one-liner — `paid()`++Wrap a handler. Unpaid requests get a `402`; paid ones run the handler:++```js+import { paid } from '@three-ws/x402-server';++export default paid(+ { price: '10000', asset: 'usdc', payTo: { solana: 'THREEsynthetic1111…' } },+ async (req, res) => {+ res.json({ summary: await summarize(req.body.text) });+ },+);+```++`price` is in **atomic units** of the asset — `'10000'` is `$0.01` of 6-decimal+USDC. The first unpaid `GET`/`POST` returns the challenge; the buyer pays and+re-sends with `X-PAYMENT`; your handler runs once, settlement lands, and the+response carries the on-chain receipt.++### A fuller route — both lanes, a fee, a receipt++```js+import { paid } from '@three-ws/x402-server';++export default paid(+ {+ price: '50000', // $0.05 USDC (6-decimal atomics)+ asset: 'usdc',+ payTo: {+ solana: 'THREEsynthetic1111…', // SPL pay-to+ base: '0xPlatformPayoutAddress…', // EVM pay-to+ },+ network: ['solana', 'base'], // advertise both accepts; buyer chooses+ feeBps: 250, // 2.5% platform fee, split out of the price+ feeTo: 'TREASURYsynthetic1111…',+ description: 'Document summarization',+ serviceName: 'Acme Summarize',+ },+ async (req, res, payment) => {+ // `payment` is the verified payer + accept — present only on a paid call.+ const out = await summarize(req.body.text);+ res.json({ summary: out, billedTo: payment.payer });+ },+);+```++### Under the hood — the raw 402 → sign → settle flow++`paid()` wraps four primitives you can drive directly when you don't want the+middleware:++```js+import {+ buildChallenge, // → the 402 envelope (x402Version, resource, accepts[], extensions)+ verifyPayment, // X-PAYMENT header → { ok, payer, accept } (calls the facilitator /verify)+ settlePayment, // verified payment → on-chain settlement + receipt+ feeSplit, // (price, bps) → { net, fee, recipient }+} from '@three-ws/x402-server';++export default async function handler(req, res) {+ const accepts = [+ { scheme: 'exact', network: 'solana:5eykt…', asset: 'EPjF…USDC', payTo, amount: '50000',+ maxTimeoutSeconds: 60, extra: { name: 'USDC', decimals: 6, feePayer } },+ ];++ const header = req.headers['x-payment'];+ if (!header) {+ // 1 — challenge. Body + base64 PAYMENT-REQUIRED header (Bazaar reads both).+ const body = buildChallenge({ resourceUrl: req.url, accepts });+ res.statusCode = 402;+ res.setHeader('PAYMENT-REQUIRED', Buffer.from(JSON.stringify(body)).toString('base64'));+ return res.end(JSON.stringify(body));+ }++ // 2 — verify the X-PAYMENT against the same accepts. No work runs if this fails.+ const v = await verifyPayment({ paymentHeader: header, requirements: accepts });+ if (!v.ok) { res.statusCode = 402; return res.end(JSON.stringify(v.body)); }++ // 3 — run the work, THEN settle (never before — a failed call moves no funds).+ const result = await summarize(req.body.text);+ const settled = await settlePayment({ verified: v });++ res.setHeader('X-PAYMENT-RESPONSE',+ Buffer.from(JSON.stringify(settled)).toString('base64'));+ res.json({ result, payer: v.payer, tx: settled.transaction });+}+```++This is exactly the order the three.ws rails enforce: **verify → dispatch →+settle**. Settlement is the last step, so a handler that throws never charges.++## API++### `paid(options, handler) → (req, res) => void`++Wrap a request handler so it requires payment. Returns a standard `(req, res)`+function — mount it as Express/Connect middleware, a Vercel function, or a Node+`http` handler.++**Options**++| Option | Type | Default | Notes |+|---|---|---|---|+| `price` | `string` | — (**required**) | Amount in **atomic units** of the asset (`'10000'` = `$0.01` of 6-decimal USDC). |+| `asset` | `'usdc' \| { solana?, base? }` | `'usdc'` | Settlement asset. A string resolves the canonical USDC mint/contract per chain; an object pins explicit addresses. |+| `payTo` | `{ solana?, base? }` | — (**required**) | Pay-to address per lane. At least one chain is required. |+| `network` | `('solana' \| 'base')[]` | from `payTo` | Which accepts to advertise. Solana leads when both are present. |+| `feeBps` | `number` | `0` | Platform fee in basis points, **split out of `price`** (≤ `1000` / 10%). `0` = no fee. |+| `feeTo` | `string` | — | Fee recipient. Required when `feeBps > 0` — no recipient, no fee. |+| `facilitator` | `string` | platform default | Override the x402 facilitator base URL used for `/verify` + `/settle`. |+| `maxTimeoutSeconds` | `number` | `60` | How long the buyer has to land the signed payment. |+| `description` | `string` | — | Human label for the `resource` in the challenge (shown in wallets/the modal). |+| `serviceName` / `tags` / `iconUrl` | `string` / `string[]` / `string` | — | Bazaar discovery metadata echoed into the challenge. |+| `onSettled` | `(receipt) => void` | — | Fired after a successful settlement — record the call, fire a webhook. |++**Handler** — `(req, res, payment) => unknown`. `payment` is present only on a+paid call: `{ payer, network, accept, amount }`. Throwing from the handler+returns its error to the buyer and **skips settlement** — no funds move.++### `buildChallenge(options) → Body`++Build the v2 `402` envelope. Returns `{ x402Version, error, resource, accepts,+extensions }`; the same object is what you base64 into the `PAYMENT-REQUIRED`+header. Accepts the canonical accept shape:++```ts+{ scheme: 'exact', network, asset, payTo, amount, maxTimeoutSeconds,+ extra: { name, decimals, feePayer? } } // feePayer required on Solana+```++### `verifyPayment({ paymentHeader, requirements }) → Promise<Verified>`++Decode the base64 `X-PAYMENT` header and verify it against `requirements` (your+`accepts[]`) via the facilitator's `/verify`. Returns `{ ok, payer, accept }` on+success, or `{ ok: false, body }` (a fresh `402` body) on a rejected/under-paid+payment. **Call your handler only when `ok`.**++### `settlePayment({ verified }) → Promise<Receipt>`++Broadcast/settle the verified payment and return the receipt+`{ network, payer, transaction }`. Run this **after** the work succeeds. The+returned object is what you base64 into the `X-PAYMENT-RESPONSE` header.++### `feeSplit(priceAtomics, bps, recipient) → { net, fee, recipient } | null`++Split a platform fee out of the listed price: `fee = floor(price × bps /+10_000)`, `net = price − fee`. Returns `null` when no fee applies (rate `0`, no+recipient, or a sub-atomic fee) so the buyer is charged the full price and the+creator receives all of it. `bps` is clamped to `[0, 1000]`.++## How it works++```+buyer request (no X-PAYMENT)+ │+ ▼+ ┌──────────────┐ 402 ┌──────────────────────────────────────────────┐+ │ buildChallenge├──────▶ accepts[]: Solana (exact, feePayer) │+ │ │ │ Base/EVM (EIP-3009 transferWith…) │+ └──────────────┘ └──────────────────────────────────────────────┘+ │ buyer signs (wallet) and retries with X-PAYMENT+ ▼+ verifyPayment ──▶ facilitator /verify ──▶ { ok, payer, accept }+ │ ok+ ▼+ your handler runs the work ◀── settlement has NOT happened yet+ │ returns 200+ ▼+ settlePayment ──▶ on-chain settle ──▶ X-PAYMENT-RESPONSE receipt+```++The buyer never signs an instruction your server can't verify. On **Solana** the+accept advertises a `feePayer` (the facilitator's sponsor account); the buyer's+wallet signs an SPL `transferChecked` of the named mint to `payTo`, the+facilitator co-signs as fee payer and lands it — the buyer pays no SOL gas. On+**Base/EVM** the buyer signs an EIP-3009 `transferWithAuthorization` typed-data+message locally (no on-chain tx, no gas) and the facilitator submits it;+settlement is verified by scanning the mined tx for a USDC `Transfer` to `payTo`+of at least the expected amount, with a confirmation floor against reorgs.++### Lanes++| Lane | Network id | Scheme | Buyer signs | Gas |+|---|---|---|---|---|+| **Solana** | `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` | `exact` | SPL `transferChecked` (facilitator co-signs) | facilitator pays |+| **Base** | `eip155:8453` | `exact` (EIP-3009) | `transferWithAuthorization` typed data | facilitator pays |+| Base Sepolia | `eip155:84532` | `exact` (EIP-3009) | same | facilitator pays |++Solana leads the `accepts[]` so first-accept clients settle there; advertise+`network: ['base']` (or both) to lead with EVM. The challenge also carries a+`bazaar` discovery extension so the endpoint is findable in the x402 bazaar.++## Payment++Prices are quoted and charged in **atomic units** of the settlement asset — USDC+is 6-decimal, so `1_000_000` = `$1.00`. The buyer's total is exactly `price`;+the platform fee is carved *out* of it:++| `feeBps` | On a `$1.00` (`1000000`) call | Creator nets | Fee |+|---|---|---|---|+| `0` (default) | buyer pays `$1.00` | `$1.00` | — |+| `250` (2.5%) | buyer pays `$1.00` | `$0.975` | `$0.025` |+| `1000` (10%, max) | buyer pays `$1.00` | `$0.90` | `$0.10` |++The fee applies **only** when both `feeBps > 0` **and** `feeTo` is set, so an+unconfigured server charges nothing — the fee feature ships inert and never+surprise-bills on deploy. On Solana the fee is an extra `transferChecked` in the+*same* transaction the buyer signs (one signature, no custody, atomic); the+buyer sees and signs it. The only coin this platform promotes is+[$THREE](https://three.ws) — settlement runs in USDC, and any mint your server+names is supplied by you at config time.++## Errors & edge cases++`verifyPayment` returns a structured result rather than throwing on a bad+payment, and `paid()` maps every state to the right HTTP status:++| Code | HTTP | Meaning | What the buyer sees / does |+|---|---|---|---|+| `payment_required` | 402 | No `X-PAYMENT`, or the header failed `/verify`. | A fresh challenge — pay and retry. |+| `invalid_payment` | 402 | The signed tx doesn't pay the declared amount/asset/recipient. | Re-sign against the advertised accept. |+| `missing_fee_payer` | 422 | A Solana accept omitted `extra.feePayer`. | Server misconfig — set `X402_FEE_PAYER_SOLANA`. |+| `unsupported_network` | 400 | Buyer paid a network the route doesn't advertise. | Pick an advertised accept. |+| `facilitator_unreachable` | 502 | The facilitator `/verify` or `/settle` is down. | **No funds moved** — safe to retry. |+| `settle_uncertain` | 502 | Verified + work ran, but settlement status is unknown. | Check on-chain before retrying to avoid double-pay. |+| `pending` | — | EVM tx not yet mined / below the confirmation floor. | Confirm again shortly. |++Two invariants make these safe: verification runs **before** your handler (a bad+payment never triggers the work), and settlement runs **after** it (a failed+handler never charges). A `429` from your upstream can be retried with the+*same* signed payment, because settlement only happens once the work succeeds.++## Examples++**Express — meter an existing API**++```js+import express from 'express';+import { paid } from '@three-ws/x402-server';++const app = express();+app.use(express.json());++app.post('/v1/embed', paid(+ { price: '2000', asset: 'usdc', payTo: { solana: 'THREEsynthetic1111…' } },+ async (req, res) => res.json({ vector: await embed(req.body.text) }),+));++app.listen(3000);+```++**Vercel / Node `http` — a paid serverless function**++```js+import { paid } from '@three-ws/x402-server';++export default paid(+ { price: '100000', asset: 'usdc', payTo: { base: '0xPayout…' }, network: ['base'] },+ async (req, res, payment) => {+ res.json({ report: await generate(req.body.topic), billedTo: payment.payer });+ },+);+```++**Agent economy — sell a tool, record every call**++```js+export default paid(+ {+ price: '5000', asset: 'usdc',+ payTo: { solana: 'THREEsynthetic1111…' },+ serviceName: 'Pose seeds', tags: ['3d', 'animation'],+ onSettled: (receipt) => recordCall(receipt), // feed your dashboard / webhook+ },+ async (req, res) => res.json({ seed: await poseSeed(req.body.prompt) }),+);+```++A buyer running [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch)+calls any of these with a plain `fetch` — the `402` is paid automatically and the+result comes back as if the endpoint were free.++## Related++- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — **buyer side.** A `fetch` wrapper that auto-pays the `402` your server here emits.+- [`@three-ws/x402-modal`](https://www.npmjs.com/package/@three-ws/x402-modal) — **buyer side.** A drop-in browser checkout modal for the same `402`.+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — a real paid endpoint built on these rails (text/image → 3D GLB).+- [three.ws merchant console](https://three.ws) — hosted SKUs, storefronts, and settlement dashboards over the same primitives.++---++<p align="center">Built by <a href="https://three.ws">three.ws</a> · The only coin is <a href="https://three.ws">$THREE</a></p>diff --git a/packages/x402-server/package.json b/packages/x402-server/package.jsonnew file mode 100644index 000000000..22b263c9c--- /dev/null+++ b/packages/x402-server/package.json@@ -0,0 +1,30 @@+{+ "name": "@three-ws/x402-server",+ "version": "0.1.0",+ "description": "The merchant side of x402 — turn any HTTP endpoint into a paid one. Issue 402 challenges, price SKUs, verify and settle the X-PAYMENT header on Solana and Base, and take a platform fee.",+ "keywords": [+ "x402",+ "402",+ "payment-required",+ "paywall",+ "usdc",+ "solana",+ "base",+ "eip-3009",+ "merchant",+ "middleware",+ "agent-payments",+ "three.ws"+ ],+ "license": "MIT",+ "private": true,+ "type": "module",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "https://github.com/nirholas/three.ws"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ }+}diff --git a/public/changelog.json b/public/changelog.jsonindex cdd95ceb9..2608c1cbf 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T07:40:33.570Z",+ "generated_at": "2026-06-23T07:50:01.651Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -543,8 +543,7 @@"summary": "Copy-trading with real economics and real accountability. A trader whose on-chain track record is verified — the same proven badge the leaderboard computes from real closed trades — can now publish their live entry and exit signals as a paid feed, priced per signal or per epoch in USDC. A follower's agent subscribes, and on every new paid signal it pays the publisher straight from its own wallet and auto-mirrors the trade: scaled to your sizing, run through the rug/honeypot firewall, submitted via the MEV engine, and held to your wallet's spend limits and kill switch — the exact same guarded path every other trade uses, fully audited. Start in simulate mode to track a feed's calls without spending a cent, then flip to live when you trust it. Every signal is bound to a real on-chain fill — sellers can't hand-author alpha — and each one accrues its realized outcome, so the marketplace ranks feeds by proven edge (hit-rate and realized ROI, confidence-regressed so a thin feed riding one lucky call can never top a deep, consistent one), never by follower count. Browse the directory, open any feed to see its full signal log with the tx that proves each call, and manage or instantly kill your subscriptions from your wallet hub's new Signals tab. Verified traders publish from the same tab and earn real USDC.","link": "/signals","tags": [- "feature",- "sdk"+ "feature"]},{diff --git a/public/features.json b/public/features.jsonindex c9e5fb517..99544c699 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T07:40:33.508Z",+ "generated_at": "2026-06-23T07:50:01.640Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agent-wallet-hub/tabs/portfolio.js b/src/agent-wallet-hub/tabs/portfolio.jsindex 8cce050eb..33b0c8e02 100644--- a/src/agent-wallet-hub/tabs/portfolio.js+++ b/src/agent-wallet-hub/tabs/portfolio.js@@ -37,6 +37,9 @@ const PORT_STYLE = `.awh-live::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--success,#4ade80); box-shadow: 0 0 0 0 color-mix(in srgb, var(--success,#4ade80) 60%, transparent); animation: awh-live-pulse 2s ease-out infinite; }@keyframes awh-live-pulse { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--success,#4ade80) 50%, transparent); } 70% { box-shadow: 0 0 0 6px transparent; } 100% { box-shadow: 0 0 0 0 transparent; } }@media (prefers-reduced-motion: reduce) { .awh-live::before { animation: none; } }+.awh-paused { appearance: none; font: inherit; font-size: var(--text-2xs,.6875rem); color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 12%, transparent); border: 1px solid color-mix(in srgb, var(--warn,#fbbf24) 35%, transparent); border-radius: var(--radius-pill,999px); padding: 1px 9px; cursor: pointer; transition: background var(--duration-fast,140ms); }+.awh-paused:hover { background: color-mix(in srgb, var(--warn,#fbbf24) 20%, transparent); }+.awh-paused:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 2px; }.awh-port-table { width: 100%; border-collapse: collapse; font-size: var(--text-sm,.764rem); }.awh-port-table th { text-align: right; font-weight: 500; color: var(--ink-dim,#888); font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .04em; padding: 0 0 8px; border-bottom: 1px solid var(--stroke, rgba(255,255,255,.08)); }@@ -207,7 +210,11 @@ registerWalletTab({return `<div class="awh-card"><div class="awh-port-nw"><div class="awh-port-nw-main">- <div class="awh-port-nw-label">Net worth ${state.live ? '<span class="awh-live">live</span>' : ''}</div>+ <div class="awh-port-nw-label">Net worth ${state.live+ ? '<span class="awh-live">live</span>'+ : state.streamDown+ ? '<button class="awh-paused" type="button" data-act="resume" title="Live updates paused — click to reconnect">updates paused ↻</button>'+ : ''}</div><div class="awh-port-nw-usd">${escapeHtml(usd)}</div><div class="awh-port-nw-sol">${escapeHtml(formatSol(nw.sol))} SOL${d.sol_usd ? ` · SOL ${escapeHtml(formatUsd(d.sol_usd) || '')}` : ''}</div></div>@@ -329,6 +336,11 @@ registerWalletTab({}function wire() {+ panel.querySelector('[data-act="resume"]')?.addEventListener('click', () => {+ state.streamDown = false;+ render();+ reload();+ });panel.querySelectorAll('[data-trade]').forEach((b) => {b.addEventListener('click', async () => {const mint = b.dataset.trade;@@ -387,12 +399,18 @@ registerWalletTab({state.data = { ...state.data, ...ev };pushSpark(ev?.net_worth?.usd);state.live = true;+ state.streamDown = false;render();});es.addEventListener('error', () => {state.live = false;- // EventSource auto-reconnects; if the server closed permanently, stop.- if (es && es.readyState === EventSource.CLOSED) closeStream();+ // EventSource auto-reconnects; if the server closed permanently, stop+ // and surface a "paused" affordance so the user knows data is frozen.+ if (es && es.readyState === EventSource.CLOSED) {+ closeStream();+ state.streamDown = true;+ render();+ }});}function closeStream() {diff --git a/src/arena/arena.js b/src/arena/arena.jsindex 73ee3b1ea..3c8b468bc 100644--- a/src/arena/arena.js+++ b/src/arena/arena.js@@ -443,11 +443,15 @@ function statCountdown(k, iso) {);}+const isModelUrl = (u) => typeof u === 'string' && /\.(glb|gltf)(\?|#|$)/i.test(u);+function leaderVisual(leader) {if (!leader) {return h('div', { class: 'spot-fallback' }, 'Awaiting the first ranked trade');}- const visual = leader.glb_url+ // Only mount the 3D viewer when the avatar is an actual model; agent_identities+ // .avatar_url can also hold a flat image, which <agent-3d body> can't render.+ const visual = isModelUrl(leader.glb_url)? h('agent-3d', { body: leader.glb_url, autorotate: 'true', 'camera-controls': 'true', 'aria-label': `${leader.agent_name} avatar` }): leader.image? h('div', { class: 'spot-fallback' }, h('img', { src: leader.image, alt: leader.agent_name, loading: 'lazy' }))diff --git a/src/mission-control/feed.js b/src/mission-control/feed.jsindex 6fde2e293..bbe46181e 100644--- a/src/mission-control/feed.js+++ b/src/mission-control/feed.js@@ -59,7 +59,8 @@ export function createFeedPane({ store, bus, enrich, mount }) {let source = store.getFilters().source || 'live';let sse = null;let signalsTimer = null;- let radarState = null; // null | 'loading' | 'degraded' | 'ok'+ let radarTimer = null;+ let radarState = null; // null | 'loading' | 'empty' | 'down' | 'ok'let connState = 'reconnecting'; // mirror of conn:feed so the body can show an honest down-statelet rafToken = 0;const rowEls = new Map(); // mint -> element (in current window)@@ -143,6 +144,7 @@ export function createFeedPane({ store, bus, enrich, mount }) {function stopStreams() {if (sse) { sse.stop(); sse = null; }if (signalsTimer) { clearInterval(signalsTimer); signalsTimer = null; }+ if (radarTimer) { clearInterval(radarTimer); radarTimer = null; }radarState = null;setConn('reconnecting');}@@ -230,37 +232,43 @@ export function createFeedPane({ store, bus, enrich, mount }) {signalsTimer = setInterval(tick, SIGNALS_REFRESH_MS);}- // Radar — pre-launch precursors (epic task 04). Honest degraded state when absent.+ // Radar — pre-launch precursors (epic task 04, GET /api/sniper/radar). The+ // precursor stream records `events`, some of which already carry a minted+ // `mint` — those are the tradeable rows. Polled (the endpoint is cached ~5s).+ // Honest states: down (unreachable), empty (watching, nothing minted yet), ok.async function startRadar() {- radarState = 'loading';- setConn('reconnecting');- scheduleRender();- try {- const r = await fetch(`/api/sniper/radar?network=${store.getNetwork()}`, {- headers: { accept: 'application/json' },- });- if (!r.ok) throw new Error(`HTTP ${r.status}`);- const data = await r.json();- const items = data?.precursors || data?.radar || data?.items || [];- if (!Array.isArray(items) || !items.length) {- radarState = 'degraded';+ if (radarState == null) radarState = 'loading';+ const tick = async () => {+ try {+ const r = await fetch(`/api/sniper/radar?network=${store.getNetwork()}`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const data = await r.json();+ const events = (Array.isArray(data?.events) ? data.events : []).filter((e) => e?.mint);+ if (data?.ok === false) { radarState = 'down'; setConn('down'); return; }+ if (!events.length) {+ radarState = 'empty';+ setConn('live'); // the source IS reachable; it just has no minted precursor yet+ return;+ }+ radarState = 'ok';+ setConn('live');+ for (const e of events) {+ const created = e.observed_ts || e.created_at;+ store.upsertRow({+ mint: e.mint,+ created_at: created ? Math.floor(new Date(created).getTime() / 1000) : Math.floor(Date.now() / 1000),+ radar: { reason: e.watch_reason || e.kind, confidence: e.confidence, score: e.watch_score, fired: e.fired },+ source: 'radar',+ });+ }+ } catch {+ // Unreachable (404 / network) — degrade honestly, no fabricated rows.+ radarState = 'down';setConn('down');- scheduleRender();- return;- }- radarState = 'ok';- setConn('live');- for (const it of items) {- if (!it?.mint) continue;- store.upsertRow({ ...it, source: 'radar' });}- scheduleRender();- } catch {- // Source not live (404 / network) — degrade honestly, no fabricated rows.- radarState = 'degraded';- setConn('down');- scheduleRender();- }+ };+ await tick();+ radarTimer = setInterval(tick, SIGNALS_REFRESH_MS);}// ── virtualized render ─────────────────────────────────────────────────────@@ -346,12 +354,20 @@ export function createFeedPane({ store, bus, enrich, mount }) {<span class="mc-row-age mc-num">${age}</span><span class="mc-row-meta"><span class="mc-row-mc mc-num">MC <b>${mc}</b></span>+ ${radarChip(row)}${intelChip(row)}${safetyChip(row)}${smartChip(row)}</span>`;}+ function radarChip(row) {+ if (!row.radar) return '';+ const conf = row.radar.confidence != null ? ` ${Math.round(Number(row.radar.confidence) * 100)}%` : '';+ const reason = row.radar.reason ? String(row.radar.reason).replace(/_/g, ' ') : 'precursor';+ return `<span class="mc-chip mc-chip--smart" title="Pre-launch radar signal">◬ ${escapeHtml(reason)}${conf}</span>`;+ }+function intelChip(row) {if (row.intel === undefined) return `<span class="mc-chip-skel"></span>`;const q = row.intel?.quality_score;@@ -373,13 +389,21 @@ export function createFeedPane({ store, bus, enrich, mount }) {// ── state panels (loading / empty / degraded) ──────────────────────────────function pickStatePanel(rows) {- if (source === 'radar' && radarState === 'degraded') {- return {- html: stateHtml('◎', 'Pre-launch radar is offline', 'The radar precursor stream isn’t live in this environment yet. Switch to <b>Live</b> for the new-launch firehose or <b>Signals</b> for scored launches.', 'Switch to Live'),- wire: (host) => host.querySelector('button')?.addEventListener('click', () => switchSource('live')),- };+ if (source === 'radar') {+ if (radarState === 'loading') return { html: skeletonHtml() };+ if (radarState === 'down') {+ return {+ html: stateHtml('⚠', 'Pre-launch radar is unreachable', 'We can’t reach the radar precursor stream right now and we’re retrying. Switch to <b>Live</b> for the new-launch firehose or <b>Signals</b> for scored launches.', 'Switch to Live'),+ wire: (host) => host.querySelector('button')?.addEventListener('click', () => switchSource('live')),+ };+ }+ if (radarState === 'empty' && !rows.length) {+ return {+ html: stateHtml('◎', 'Radar armed — watching', 'The pre-launch radar is tracking smart-money wallets, but none have minted a coin yet. New precursors that mint will appear here the moment they do.', 'See Live launches'),+ wire: (host) => host.querySelector('button')?.addEventListener('click', () => switchSource('live')),+ };+ }}- if (source === 'radar' && radarState === 'loading') return { html: skeletonHtml() };if (!rows.length) {if (store.allRowsCount() === 0) {// Source unreachable with nothing received yet — show an honest,diff --git a/src/mission-control/index.js b/src/mission-control/index.jsindex bc9593aa1..63a68a8e8 100644--- a/src/mission-control/index.js+++ b/src/mission-control/index.js@@ -164,13 +164,11 @@ export function mountMissionControl(root, opts = {}) {function wireMobileBar() {const buttons = [...rootEl.querySelectorAll('[data-mpane]')];- const main = rootEl.querySelector('[data-host="main"]');const setActive = (name) => {for (const b of buttons) b.setAttribute('aria-selected', String(b.dataset.mpane === name));for (const key of ['feed', 'focus', 'positions']) {rootEl.querySelector(`[data-host="${key}"]`)?.classList.toggle('is-active', key === name);}- main.classList.toggle('show-positions', name === 'positions');};for (const b of buttons) b.addEventListener('click', () => setActive(b.dataset.mpane));setActive('feed');diff --git a/src/mission-control/positions.js b/src/mission-control/positions.jsindex a112e8bf9..e0854e684 100644--- a/src/mission-control/positions.js+++ b/src/mission-control/positions.js@@ -50,6 +50,7 @@ export function createPositionsPane({ store, bus, mount }) {let holdingsTimer = null;let rafToken = 0;let agentId = store.getAgent()?.id || null;+ let connState = 'reconnecting';let summaryTween = { from: 0, to: 0, t0: 0, raf: 0 };const keyOf = (p) => (p.source === 'spot' ? `spot:${p.mint}` : `snipe:${p.id}`);@@ -155,7 +156,7 @@ export function createPositionsPane({ store, bus, mount }) {function startStream() {sse = createSseClient({url: `/api/sniper/stream?network=${store.getNetwork()}`,- onState: (s) => bus.emit('conn:positions', s),+ onState: (s) => { connState = s; bus.emit('conn:positions', s); scheduleRender(); },events: {open: () => {},buy: (d) => { if (d?.agent_id === agentId) { ingestSniper(d, 'open'); flash(d.mint, d.pnl_pct); scheduleRender(); } },@@ -226,6 +227,10 @@ export function createPositionsPane({ store, bus, mount }) {return;}if (!open.length && !closed.length) {+ if (connState === 'down') {+ body.innerHTML = stateHtml('⚠', 'Position stream unreachable', 'We can’t reach the live position stream right now and we’re retrying. Nothing stale is shown.');+ return;+ }body.innerHTML = stateHtml('▦', 'No open positions', 'Buy a coin from the feed to open your first position — its live PnL streams here.');return;}diff --git a/src/mission-control/styles.js b/src/mission-control/styles.jsindex c26ac47a2..527b34865 100644--- a/src/mission-control/styles.js+++ b/src/mission-control/styles.js@@ -184,10 +184,12 @@ const CSS = `/* ── responsive ──────────────────────────────────────────────────────────── */@media (max-width: 1100px) {- .mc-main { grid-template-columns: minmax(280px, 1fr) minmax(320px, 1.4fr); grid-template-rows: 1fr; }- .mc-pane--positions { grid-column: 1 / -1; display: none; } /* folded into focus column tab on tablet */- .mc-main.show-positions .mc-pane--focus { display: none; }- .mc-main.show-positions .mc-pane--positions { display: flex; grid-column: 2; }+ /* Two columns: the feed spans the full height on the left; focus + positions+ stack in the right column. Every pane stays reachable — no hidden tab. */+ .mc-main { grid-template-columns: minmax(260px, 1fr) minmax(320px, 1.45fr); grid-template-rows: 1.25fr 1fr; }+ .mc-pane--feed { grid-column: 1; grid-row: 1 / span 2; }+ .mc-pane--focus { grid-column: 2; grid-row: 1; }+ .mc-pane--positions { grid-column: 2; grid-row: 2; }}@media (max-width: 760px) {.mc-main { grid-template-columns: 1fr; }diff --git a/src/signals.js b/src/signals.jsindex 7f5ae4570..7cb05115a 100644--- a/src/signals.js+++ b/src/signals.js@@ -121,7 +121,7 @@ function card(f) {</div><div class="sm-card-foot"><div class="sm-price">${priceBlock(f.pricing)}</div>- ${thin || `<span class="sm-view">${s.subscribers} sub${s.subscribers === 1 ? '' : 's'} · View →</span>`}+ <div style="display:flex;align-items:center;gap:8px">${thin}<span class="sm-view">${s.subscribers} sub${s.subscribers === 1 ? '' : 's'} · View →</span></div></div></a>`;}diff --git a/tasks/next-gen-trading/06-signal-marketplace-x402.md b/tasks/next-gen-trading/06-signal-marketplace-x402.mddeleted file mode 100644index b661b6733..000000000--- a/tasks/next-gen-trading/06-signal-marketplace-x402.md+++ /dev/null@@ -1,99 +0,0 @@-# Task 06 — Reputation-Gated Signal Marketplace (x402 paid alpha feeds)--> **Operating bar (applies to the whole task).** Senior engineer + product thinker building-> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no-> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%-> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**-> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade-> plumbing are the only exception and are never promoted. After it works, self-review and ship-> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the-> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.->-> **Depends on task 03 (smart-money graph).** Reputation gating uses real track records.--## The invention--We have **verifiable on-chain track records** (`trader-stats.js` composite score + verification-badge) and **x402 agent-to-agent micropayments**. Combine them into the first **trust-gated-signal marketplace**: a trader whose track record is verified can publish their live entry/exit-signals as an x402-metered feed; a follower's *agent* pays per signal (or per epoch) and mirrors-the trade automatically from its own wallet, with the firewall + spend guards intact. Signals are-**performance-bonded and accountable** — every published signal's realized outcome is tracked, so-the marketplace ranks sellers by *proven* edge, not follower count. This is copy-trading with-real economics and real accountability, which no one in this space has.--## Context (real, verified)--- Track record + verification: `api/_lib/trader-stats.js` (`computeTraderMetrics`, `verified`- badge: 12+ closed, 5+ coins, ≤40% churn, >0 realized SOL). Leaderboard: `api/sniper/leaderboard.js`.-- x402 micropayments: `api/x402-pay.js` (per-agent USDC settlement, SSE, spend tracking via- `agent-trade-guards.js`); A2A scaffolding: `api/agents/a2a-*.js`, `agent_payments` ledger.-- Copy scaffolding already present: `copy_subscriptions` table + `activeCopierCounts` /- `copierCountForAgent` in `trader-stats.js`. Build the marketplace ON this — finish it.-- Live position events: `api/sniper/stream.js` (SSE open/buy/sell/close) — the raw signal source.-- Mirror execution reuses `api/agents/agent-trade.js`/`executor.js`, the firewall (01), MEV (02).--## Goal--A signal marketplace where verified traders publish x402-metered signal feeds and follower agents-subscribe + auto-mirror, with per-signal accountability and a ranked, real-performance directory.--## What to build--1. **Publisher side** — let a verified agent (gate on `trader-stats` `verified === true`) create a- **signal feed**: pricing (x402 per-signal USDC and/or per-epoch subscription), what it emits- (entries, exits, sizing %), and visibility. New `signal_feeds` + `signal_emissions` tables- (feed config; each emission: mint, side, size_pct, conviction, emitted_at, realized_outcome- filled in later). Emissions are generated **from the publisher's real trades** (hook the- position lifecycle / sniper fills) — never hand-authored, never fake.-2. **x402 metering** — gate feed reads behind `api/x402-pay.js`: a subscriber agent pays USDC from- its own wallet per signal or per epoch; settlement flows through the existing per-agent path- with custody audit (`agent_custody_events`, category `signal`) and spend guards. Idempotent;- respect daily caps + kill switch. Publisher earns real USDC.-3. **Subscriber auto-mirror** — `signal_subscriptions` (subscriber_agent_id, feed_id, mode- simulate|live, size_scaling, max_per_trade, slippage, firewall_level). On a new paid emission,- the subscriber agent mirrors the trade from its own wallet: scale size, run the firewall (01),- submit via MEV engine (02), record a position tagged with the source feed. All spend guards- apply. Simulate mode mirrors without spending for trust-building.-4. **Accountability + ranking** — when a mirrored/published signal closes, record realized outcome- on the emission and roll up per-feed stats (hit-rate, avg follower ROI, latency from emit→fill).- `GET /api/signals/marketplace` ranks feeds by **proven realized edge** (not follower count),- reusing `trader-stats` confidence regression so thin feeds don't top the board.-5. **API + UI** — `/api/signals/feeds` (CRUD, publisher), `/api/signals/marketplace` (public,- ranked), `/api/signals/subscribe` (subscriber), `/api/signals/stream` (paid SSE of emissions).- Build a **Signals** product surface: marketplace directory (each feed shows verified track- record + realized signal accuracy + price), a feed detail page, and a subscriber control panel- in the wallet hub (mode, sizing, kill). Designed empty/loading/error/populated; accessible;- responsive.--## Constraints--- Only **verified** track records can publish; the verification + score come from real closed- trades via `trader-stats.js`, never self-declared. Sellers cannot fake performance — emissions- bind to real on-chain fills and realized outcomes.-- Real x402 USDC settlement only — no simulated payments in live mode; simulate mode is clearly- labeled and spends nothing. Every payment audited and spend-guarded.-- Mirror trades obey the firewall + spend limits + kill switch with no exception; a subscriber can- always halt instantly and withdraw.-- $THREE-only rule; the marketplace ranks *traders/feeds*, never promotes a token. Mints shown are- runtime trade data only.--## Success criteria--- A verified agent publishes a feed; a subscriber agent pays real x402 USDC and auto-mirrors a- real trade through the firewall + MEV engine, fully audited.-- Emissions accrue realized outcomes; marketplace ranks by proven edge with confidence regression.-- Signals UI (marketplace, feed detail, subscriber panel) renders all states; instant kill works.-- Build/typecheck/test clean. Changelog entry (tags: feature, sdk). Completionist passes.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--```bash-git rm "tasks/next-gen-trading/06-signal-marketplace-x402.md"-```--A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/next-gen-trading/09-mission-control-terminal.md b/tasks/next-gen-trading/09-mission-control-terminal.mddeleted file mode 100644index 6da708a50..000000000--- a/tasks/next-gen-trading/09-mission-control-terminal.md+++ /dev/null@@ -1,96 +0,0 @@-# Task 09 — Mission Control: Real-Time Trading Terminal (the capstone UI)--> **Operating bar (applies to the whole task).** Senior engineer + product thinker building-> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no-> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%-> end-to-end with REAL APIs and real data. Every state designed. Only coin is **$THREE**-> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade-> plumbing are the only exception and are never promoted. After it works, self-review and ship-> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the-> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.->-> **Depends on tasks 01, 03, 04 (and consumes 02/05/06 data where present).**--## The invention--Pump.fun traders juggle ten tabs. We give them one screen that makes them feel like they have a-superpower: a **real-time trading terminal** that fuses everything three.ws computes — the live-launch feed with intel scores + firewall verdicts + smart-money flow + pre-launch radar-precursors, the user's live positions with streaming PnL, and one-click (or one-keystroke) snipe/-exit from the agent wallet. This is the surface people screenshot and share. Bloomberg-grade-density, Linear-grade polish, zero jank, fully keyboard-driven.--## Context (real, verified)--- Live data sources to fuse (all real, all existing or built by this epic):- - Launch feed: `api/_lib/pumpfun-ws-feed.js` (server) → expose via an SSE/stream endpoint.- - Intel scores: `pump_coin_intel`; oracle conviction: `oracle_conviction`.- - Firewall verdict: task 01 `GET /api/pump/safety`.- - Smart-money: task 03 `GET /api/intel/smart-money`.- - Pre-launch radar: task 04 `GET /api/sniper/radar` + SSE.- - Positions + PnL: `api/sniper/stream.js` (SSE), `api/_lib/trader-stats.js`.- - Execute: `api/agents/agent-trade.js` / `api/agents/solana-trade.js` (firewall + MEV-gated).-- UI conventions + design tokens: `src/agent-wallet-hub/index.js`, `src/agent-wallet-hub/tabs/trade.js`,- `src/game/coin-buy.js`. SSE client patterns already used in the sniper UI.-- Frontend: vanilla JS modules + Vite. Keep it performant — virtualize lists, debounce, rAF.--## Goal--A dedicated `/terminal` (or `/mission-control`) page + `src/mission-control/` module that streams-real data into a multi-pane, keyboard-driven trading cockpit, executing real trades from the agent-wallet through the firewall + MEV engine.--## What to build--1. **Layout** — a responsive multi-pane terminal: (a) **live launch feed** (new mints streaming- in, each row showing intel score, firewall verdict chip, smart-money count, age, market cap),- (b) **radar** precursors (task 04), (c) **your positions** with live streaming PnL + quick exit,- (d) a **focus/detail** pane for the selected coin (chart, intel breakdown, safety panel, smart-- money graph, buy/sell). Collapses gracefully to a stacked mobile layout at 320/768/1440.-2. **Real-time plumbing** — consume all SSE/stream endpoints with robust reconnect/backoff, a- shared event bus, and virtualized rendering so a fast feed never janks. No polling where SSE- exists; no fake `setTimeout` ticks. Show connection state honestly (live / reconnecting / down).-3. **One-keystroke trading** — keyboard-first: arrow/jk to move the selection, `b` to buy preset- size, `s` to sell, number keys for size presets, `/` to filter, `?` for a shortcut overlay.- Every execution runs through the firewall (block disables the action) and the MEV engine, from- the agent wallet, spend-guarded + audited. Confirm-on-first-use, then express mode.-4. **Filters + saved views** — filter the feed by intel score, firewall verdict, smart-money,- creator pedigree, market-cap band; persist named views per user. Empty/loading/error states for- every pane (skeletons, not spinners).-5. **Polish that makes it screenshot-worthy** — micro-interactions on new-row entry, smooth PnL- number transitions, color-coded verdicts, a tasteful "alpha" density without clutter, focus- rings, ARIA live regions for the streaming feed, reduced-motion support. Navigable from main nav- and from the wallet hub. Add it to `data/pages.json` so the changelog records the new page.--## Constraints--- Every datum is real and streaming from real endpoints — no seeded rows, no demo coins, no fake- feed. If a source is down, that pane shows an honest degraded state, not stale or fake data.-- Trades execute only through the existing guarded paths (firewall + spend guards + MEV + custody- audit); the terminal is a fast UI over real execution, never a bypass.-- Performance is a feature: 60fps feed, virtualized lists, lazy-loaded heavy panes, debounced- input. No memory leaks on long-lived SSE (clean up on unmount/route change).-- $THREE-only rule. The feed shows arbitrary runtime mints as market data; it promotes no token- and never names any coin other than $THREE in chrome/copy.--## Success criteria--- `/terminal` streams real launches, intel, firewall verdicts, smart-money, radar, and live- positions simultaneously, reconnecting cleanly; reachable from main navigation.-- Keyboard-driven buy/sell executes real firewall+MEV-gated trades from the agent wallet, audited.-- Filters + saved views work; every pane has designed loading/empty/error/populated states;- responsive 320/768/1440; accessible; console-clean; no jank under a fast feed.-- New page added to `data/pages.json`. Build/typecheck/test clean. Changelog entry (tags: feature).- Completionist passes.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--```bash-git rm "tasks/next-gen-trading/09-mission-control-terminal.md"-```--A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/next-gen-trading/10-trading-arena-tournaments.md b/tasks/next-gen-trading/10-trading-arena-tournaments.mddeleted file mode 100644index 7de83c0a4..000000000--- a/tasks/next-gen-trading/10-trading-arena-tournaments.md+++ /dev/null@@ -1,100 +0,0 @@-# Task 10 — Social Trading Arena: On-Chain PvP Tournaments ($THREE prizes)--> **Operating bar (applies to the whole task).** Senior engineer + product thinker building-> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no-> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%-> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**-> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade-> plumbing are the only exception and are never promoted. After it works, self-review and ship-> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the-> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.--## The invention--We have **verifiable, tamper-evident track records** (`trader-stats.js`, on-chain attestations).-Turn trading into a spectator sport: **time-boxed PvP tournaments** where agents compete on-*real, verified* PnL over a window, ranked live, with results settled and attested on-chain and-**$THREE prizes** for winners. Entry can be gated or open; performance can't be faked because it's-computed from real closed positions. This converts the leaderboard from a static table into a-recurring, social, competitive product loop that drives engagement and showcases the platform's-real edge — a trading esport for AI agents.--## Context (real, verified)--- Canonical metrics: `api/_lib/trader-stats.js` (`computeTraderMetrics`, composite score,- verification, ROI, drawdown, Sharpe). Leaderboard + SSE: `api/sniper/{leaderboard,trader,- stream}.js`. Positions: `agent_sniper_positions`.-- On-chain attestation for tamper-evident results: Solana attestations- (`solana_attestations`, kinds like `threews.*`), `contracts/src/ReputationRegistry.sol`, and the- attestation helpers in `@three-ws/sdk` (`attestValidation`, `listAttestations`).-- $THREE is the only coin (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — prizes are $THREE.- Use the existing platform launch records / $THREE plumbing for prize accounting; never reference- any other token.-- Identity + reputation: `agent_identities`, ERC-8004 (`erc8004_agents_index`). Real-time:- `api/sniper/stream.js` SSE pattern.--## Goal--A tournament engine: create/join time-boxed competitions scored on real verified PnL, a live-leaderboard with anti-cheat, on-chain attestation of final standings, and $THREE prize settlement-— surfaced as an Arena product with live spectating.--## What to build--1. **Tournament model** — `tournaments` (id, name, network, scoring [roi_pct|realized_pnl|score],- starts_at, ends_at, entry_rules jsonb, prize_pool_three, status) and `tournament_entries`- (tournament_id, agent_id, joined_at, starting_snapshot jsonb, status). Scoring uses only trades- **opened within the window** to be fair; snapshot each entrant's baseline at join.-2. **Live scoring engine** — compute each entrant's window-scoped metrics from real- `agent_sniper_positions` via `trader-stats.js`, ranked live. Anti-cheat: reuse the verification- gates (min trades, min unique coins, churn cap) + a wash/self-trade check (reject coins traded- only against the entrant's own related wallets — leverage task 03 clustering if present). No- simulated/paper trades count toward prizes (separate "practice" bracket allowed, clearly- labeled).-3. **On-chain attestation** — at tournament close, write the final standings as a Solana- attestation (`threews.tournament.v1` kind) so results are tamper-evident and independently- verifiable; link the attestation from the results page. Use the existing attestation path; no- new signing key handling.-4. **Prize settlement** — distribute the $THREE prize pool to winners per the published structure,- recorded with a real tx + an entry in the relevant ledger, audited. Honest accounting; if prize- funding is unavailable in an environment, the tournament still runs and ranks, and settlement- reports BLOCKED(reason) rather than faking a payout.-5. **API + UI — the Arena** — `/api/tournaments` (CRUD, join), `/api/tournaments/:id` (state,- live standings, prize, attestation link), `/api/tournaments/:id/stream` (SSE live rank changes).- Build an **Arena** page: list of upcoming/live/finished tournaments, a live competition view- (animated ranking, each agent's 3D avatar + verified badge + live PnL, recent trades ticker),- join flow, and a results page with the on-chain attestation + prize distribution. Make it feel- alive and competitive — this is a showcase surface. Add to `data/pages.json`. All states- designed; accessible; responsive; reduced-motion friendly.--## Constraints--- Rankings derive only from **real verified closed trades** — never fabricate PnL, never count- unverifiable or wash trades toward prizes. The integrity is the entire point.-- Prizes are **$THREE only**. Never introduce, name, or reference any other token anywhere in the- arena (copy, schema, fixtures). Mints shown are runtime trade data, not promotions.-- On-chain attestation must be real (real Solana tx) or honestly reported as unavailable — no fake- proof links.-- Settlement is real and audited; BLOCKED is a first-class honest outcome when funding is absent.--## Success criteria--- A tournament can be created and joined; live standings compute from real `trader-stats` metrics- over the window with anti-cheat enforced.-- Final standings are attested on-chain (real tx) and linked from results; $THREE prizes settle- (or report BLOCKED honestly with the unblock step).-- Arena UI (list, live competition, results) renders all states, is responsive + accessible, and- is reachable from main navigation; new page in `data/pages.json`.-- Build/typecheck/test clean. Changelog entry (tags: feature). Completionist passes.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--```bash-git rm "tasks/next-gen-trading/10-trading-arena-tournaments.md"-```--A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/trading-frontier/03-portfolio-intelligence-command.md b/tasks/trading-frontier/03-portfolio-intelligence-command.mddeleted file mode 100644index cde2ffab9..000000000--- a/tasks/trading-frontier/03-portfolio-intelligence-command.md+++ /dev/null@@ -1,85 +0,0 @@-# Task 03 — Portfolio Intelligence & Risk Command (unified cross-wallet)--> **Operating bar.** Senior engineer + product thinker building three.ws to beat the best.-> Genuinely innovative, not a clone. No mocks/fake data/placeholders/TODO/stubs/`setTimeout`-> fake-loading. Wire 100% with REAL APIs + on-chain data. Only coin is **$THREE**-> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime mints in generic plumbing are the only-> exception, never promoted.--## ⛓ Chain protocol — STEP 0, before building--Node in a self-extending chain (see `tasks/trading-frontier/README.md`). Before building:-read all `tasks/` + `BACKLOG.md`; invent **10 genuinely new, non-duplicate, real-codebase-grounded-feature ideas**; write each as a full prompt in `tasks/trading-frontier/next/<slug>.md` matching-this file's structure (including this Chain protocol section); append each to `BACKLOG.md` after a-dedup check. Only then build YOUR feature to the production-ready bar (epic README) and `git rm`-this file in the completion commit.--## The invention--A trader on three.ws has SOL, SPL holdings, open sniper positions, discretionary positions, and-(soon) orders/swarms — scattered. Build a **Portfolio Command**: one real-time, unified view of-everything the agent wallet holds and has done, with honest **PnL attribution** (which strategy /-signal / source made or lost money), live **risk metrics** (exposure, concentration, drawdown,-correlation to the broad pump.fun tape), and a cost-basis / realized-vs-unrealized breakdown.-Bloomberg-grade portfolio analytics for an AI agent's wallet — nothing like it exists for memecoins.--## Context (real, verified)--- Balances: `api/agents/solana-wallet.js` (SOL + SPL holdings, USDC). Live SOL price: feed util in- `api/_lib/pumpfun-ws-feed.js#getSolPrice` / `agent-trade-guards.js#lamportsToUsd`.-- Trade truth: `agent_sniper_positions`, `agent_custody_events` (spend/withdraw/trade/snipe/x402),- discretionary trades via `api/agents/solana-trade.js` history.-- Metrics engine to reuse/extend: `api/_lib/trader-stats.js` (`computeTraderMetrics`: PnL, ROI,- drawdown, Sharpe, profit factor, churn). Live position updates: `api/sniper/stream.js`.-- Token valuation: curve/AMM quotes `api/_lib/pump.js` (`getAmmPoolState`).--## Goal--A portfolio service (`api/_lib/portfolio.js` + `/api/agents/:id/portfolio`) that values all-holdings live, attributes PnL by source, computes risk, and a Portfolio Command UI — all from real-on-chain + ledger data.--## What to build--1. **Valuation + holdings** — enumerate the agent wallet's SOL + every SPL holding, value each via- live curve/AMM quotes (graceful for illiquid/dead tokens — mark unpriceable, don't crash), sum- to a real total in SOL + USD. Cache briefly; never fabricate a price.-2. **PnL attribution** — reconcile `agent_custody_events` + positions into realized vs unrealized- PnL, attributed by source: discretionary, each sniper strategy, signal feed (task 06 of- next-gen), swarm, MM. Cost-basis per holding (FIFO lots) for accurate realized PnL.-3. **Risk metrics** — live exposure (% of net worth at risk), concentration (largest position- share + a Herfindahl-style score), max drawdown, realized volatility, and correlation of the- portfolio's moves to the broad pump.fun tape (from intel/feed aggregates). Surface plain-language- risk flags ("78% concentrated in one illiquid position").-4. **API + UI** — `/api/agents/:id/portfolio` (holdings, valuation, attribution, risk) + SSE for- live updates. Build a **Portfolio Command** surface in the wallet hub: net-worth header with- live sparkline, holdings table (value, cost basis, unrealized PnL, liquidity warning), an- attribution breakdown (what's making/losing money), a risk panel, and one-click jump to- trade/exit any holding. All states designed (incl. a helpful empty state for a fresh wallet);- accessible; responsive.--## Constraints--- Every value is real and live; unpriceable/illiquid holdings are honestly flagged, never guessed.-- Read-only analytics + jump-to-action; all actual trades go through existing guarded paths.-- Performance: value holdings concurrently, cache, virtualize long tables. $THREE-only rule.--## Success criteria--- Portfolio values all real holdings live in SOL + USD with cost basis and realized/unrealized PnL,- attributed by source, with live risk metrics and honest illiquidity flags.-- Portfolio Command UI renders all states, updates live, is responsive + accessible.-- Production-ready bar met; chain extended. Build/typecheck/test clean. Changelog (tags: feature,- improvement). Completionist passes.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file (after authoring + registering 10 chained prompts)--```bash-git rm "tasks/trading-frontier/03-portfolio-intelligence-command.md"-```-A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tests/portfolio.test.js b/tests/portfolio.test.jsindex 015d3f488..361afa890 100644--- a/tests/portfolio.test.js+++ b/tests/portfolio.test.js@@ -130,7 +130,7 @@ describe('buildAttribution — buckets, realized + unrealized, outflows', () =>{ category: 'withdraw', amount_lamports: Number(SOL), status: 'confirmed' },{ category: 'trade', amount_lamports: 999, status: 'failed' }, // ignored (failed)];- const attr = buildAttribution({ realizedBySource, unrealizedBySource, custodyRows, solUsd: 200, hasStrategy: true });+ const attr = buildAttribution({ realizedBySource, unrealizedBySource, custodyRows, solUsd: 200 });const sniper = attr.find((a) => a.source === 'sniper');expect(sniper.realized_sol).toBe(2);@@ -159,7 +159,6 @@ describe('buildAttribution — buckets, realized + unrealized, outflows', () =>unrealizedBySource: new Map(),custodyRows: [],solUsd: null,- hasStrategy: false,});expect(attr[0].realized_sol).toBe(1);expect(attr[0].realized_usd).toBe(null);diff --git a/vercel.json b/vercel.jsonindex 550330aae..500650401 100644--- a/vercel.json+++ b/vercel.json@@ -844,6 +844,10 @@"src": "/play/arena/?","dest": "/play/arena.html"},+ {+ "src": "/arena/?",+ "dest": "/arena.html"+ },{"src": "/play/?","dest": "/play.html"diff --git a/workers/agent-sniper/exit-logic.js b/workers/agent-sniper/exit-logic.jsnew file mode 100644index 000000000..5c610b284--- /dev/null+++ b/workers/agent-sniper/exit-logic.js@@ -0,0 +1,43 @@+// agent-sniper — pure exit decision. No I/O, no time source of its own.+//+// The single source of truth for "should this position exit, and why". The live+// position loop (positions.js) calls it every tick with a freshly re-quoted SOL+// value + high-water mark; the historical backtester (api/_lib/strategy-backtest.js)+// calls it at the recorded peak and terminal price points so a projected strategy+// is evaluated with the EXACT stop-loss / trailing-stop / take-profit / timeout+// priority that governs real money. Keeping it here means the two can never drift.++/** Coerce to a finite number, or null. */+export function pct(n) {+ const x = Number(n);+ return Number.isFinite(x) ? x : null;+}++/**+ * Decide the exit reason for a position, or null to hold. Evaluated in priority+ * order: stop-loss → trailing-stop → take-profit → timeout.+ *+ * @param {object} pos position-like: { entry_quote_lamports, stop_loss_pct,+ * trailing_stop_pct, take_profit_pct, max_hold_seconds, opened_at }+ * @param {number} value current SOL value of the position (lamports)+ * @param {number} peak high-water mark of `value` since entry (lamports)+ * @param {number} [now] epoch ms for the timeout clock (defaults to Date.now()).+ * Pass an explicit clock from a replay to keep it pure.+ * @returns {'stop_loss'|'trailing_stop'|'take_profit'|'timeout'|null}+ */+export function decideExit(pos, value, peak, now = Date.now()) {+ const entry = BigInt(pos.entry_quote_lamports || '0');+ if (entry <= 0n) return null;+ const ev = Number(entry);+ const sl = pct(pos.stop_loss_pct);+ const ts = pct(pos.trailing_stop_pct);+ const tp = pct(pos.take_profit_pct);++ if (sl != null && value <= ev * (1 - sl / 100)) return 'stop_loss';+ if (ts != null && peak > 0 && value <= peak * (1 - ts / 100)) return 'trailing_stop';+ if (tp != null && value >= ev * (1 + tp / 100)) return 'take_profit';++ const heldS = (now - new Date(pos.opened_at).getTime()) / 1000;+ if (pos.max_hold_seconds != null && heldS >= pos.max_hold_seconds) return 'timeout';+ return null;+}diff --git a/workers/agent-sniper/positions.js b/workers/agent-sniper/positions.jsindex 417db3b7e..cd56da132 100644--- a/workers/agent-sniper/positions.js+++ b/workers/agent-sniper/positions.js@@ -11,29 +11,7 @@ import { getTradeCtx } from './trade-client.js';import { getOpenPositions } from './strategy-store.js';import { executeSell } from './executor.js';import { quoteAmmSell } from './amm-exit.js';--function pct(n) {- const x = Number(n);- return Number.isFinite(x) ? x : null;-}--/** Decide the exit reason for a position, or null to hold. */-function decideExit(pos, value, peak) {- const entry = BigInt(pos.entry_quote_lamports || '0');- if (entry <= 0n) return null;- const ev = Number(entry);- const sl = pct(pos.stop_loss_pct);- const ts = pct(pos.trailing_stop_pct);- const tp = pct(pos.take_profit_pct);-- if (sl != null && value <= ev * (1 - sl / 100)) return 'stop_loss';- if (ts != null && peak > 0 && value <= peak * (1 - ts / 100)) return 'trailing_stop';- if (tp != null && value >= ev * (1 + tp / 100)) return 'take_profit';-- const heldS = (Date.now() - new Date(pos.opened_at).getTime()) / 1000;- if (pos.max_hold_seconds != null && heldS >= pos.max_hold_seconds) return 'timeout';- return null;-}+import { decideExit } from './exit-logic.js';async function tickPosition(cfg, pos) {// Kill-switch flipped while holding → exit at market now.