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
Add wallet anomaly engine, vanity pool protocol, and capability migrations
nirholas69c1eb234b00
diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 11d92df15..711982248 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -173,6 +173,17 @@ export const env = {return opt('WALLET_ENCRYPTION_KEY');},+ // HMAC key that makes scoped session-key (capability) grants tamper-evident+ // (api/_lib/wallet-capabilities.js). Each capability stores an HMAC over its+ // immutable scope keyed by this secret; the spend path re-verifies on every+ // use, so a DB-write attacker who forges or edits a grant produces one that no+ // longer verifies and is rejected (fail safe). Decoupled from the encryption+ // key by preference; falls back to WALLET_ENCRYPTION_KEY then JWT_SECRET so the+ // feature works in every environment. NEVER log this value.+ get WALLET_CAPABILITY_SECRET() {+ return opt('WALLET_CAPABILITY_SECRET') || opt('WALLET_ENCRYPTION_KEY') || this.JWT_SECRET;+ },+// Long-lived Ed25519 signing seed for the provably-fair vanity grinder// (api/_lib/vanity-service-key.js). Stored as a secret-box ciphertext (v2:…)// or a raw 32-byte seed in hex/Base58. Signs every verifiable-grind receipt;diff --git a/api/_lib/migrations/20260628150000_agent_anomaly.sql b/api/_lib/migrations/20260628150000_agent_anomaly.sqlnew file mode 100644index 000000000..9f712da50--- /dev/null+++ b/api/_lib/migrations/20260628150000_agent_anomaly.sql@@ -0,0 +1,57 @@+begin;++-- Behavioral anomaly timeline for custodial agent wallets — the audit + UI side+-- of the wallet's immune system (api/_lib/wallet-anomaly.js scores every outbound+-- action; this table records each scored decision so the owner can see WHY).+--+-- One row per scored outbound action (allow OR freeze). It is intentionally+-- separate from agent_custody_events (the money ledger): that table is the+-- accounting record, this one is the explainability + adjudication record. A row+-- links back to its custody event via custody_event_id when one exists.+--+-- Lifecycle:+-- status = 'allowed' scored below threshold, action permitted+-- status = 'flagged' scored at/above threshold → wallet auto-frozen, action held+-- status = 'approved' owner confirmed "this was me" → unfrozen + baseline taught+-- status = 'denied' owner confirmed bad → wallet stays frozen+create table if not exists agent_anomaly_events (+ id bigserial primary key,+ agent_id uuid not null,+ user_id uuid, -- wallet owner+ network text not null default 'mainnet',+ category text, -- trade | snipe | x402 | withdraw+ asset text,+ usd numeric, -- USD value of the scored action (null when unpriceable)+ destination text, -- counterparty (base58) when present+ score numeric not null default 0, -- 0..1 anomaly score+ decision text not null, -- allow | freeze+ critical boolean not null default false, -- a catastrophic factor fired+ sensitivity text, -- preset in force at decision time+ factors jsonb not null default '[]'::jsonb, -- named contributing factors+ summary text, -- one-line plain-language explanation+ status text not null default 'allowed', -- allowed | flagged | approved | denied+ hour_utc smallint, -- decision hour (for "teach the baseline")+ custody_event_id bigint, -- the spend row this scored, if any+ adjudicated_by uuid,+ adjudicated_at timestamptz,+ swept boolean not null default false, -- owner used one-tap "sweep to safety"+ meta jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+);++-- Owner-facing timeline reads newest-first per agent.+create index if not exists agent_anomaly_events_agent_time+ on agent_anomaly_events (agent_id, id desc);++-- The hub badges/polls open flags (a freeze awaiting the owner's one-tap call).+create index if not exists agent_anomaly_events_open+ on agent_anomaly_events (agent_id, created_at desc)+ where status = 'flagged';++comment on table agent_anomaly_events is+ 'Per-agent behavioral anomaly timeline for custodial wallets. One row per '+ 'scored outbound action (allow/freeze) with named factors + plain-language '+ 'summary. Owner-viewable via GET /api/agents/:id/solana/guard. Scoring lives '+ 'in api/_lib/wallet-anomaly.js; config in agent_identities.meta.anomaly.';++commit;diff --git a/api/_lib/migrations/20260629000000_wallet_capabilities.sql b/api/_lib/migrations/20260629000000_wallet_capabilities.sqlnew file mode 100644index 000000000..a2d573e58--- /dev/null+++ b/api/_lib/migrations/20260629000000_wallet_capabilities.sql@@ -0,0 +1,77 @@+begin;++-- Scoped session keys — capability-based security for autonomous agent spending.+--+-- Today every skill / strategy / integration an agent runs wields the FULL+-- authority of the custodial wallet: any of them can spend up to the wallet-wide+-- caps, anywhere policy allows. A capability narrows that to a least-privilege+-- slice: "this sniper strategy may spend up to 2 SOL on these mints for the next+-- 24h, and nothing else." Capabilities strictly SUBTRACT authority — both the+-- capability ceiling and the wallet-wide policy (meta.spend_limits) must pass on+-- every autonomous spend. They never widen what the wallet policy already allows.+--+-- A grant is tamper-evident: `grant_sig` is an HMAC over the immutable scope keyed+-- by a server-held secret, verified server-side on every use. A DB-write attacker+-- who forges or edits a row produces a grant whose HMAC no longer verifies, so the+-- spend path rejects it (fail safe). Expiry and revocation are also enforced+-- server-side on every use, never client-trusted.+--+-- Enforcement lives in api/_lib/wallet-capabilities.js (pure predicates + atomic,+-- advisory-locked aggregate accounting) and is composed into the shared guards in+-- api/_lib/agent-trade-guards.js. Aggregate spend per capability is summed from+-- agent_custody_events rows tagged with capability_id (added below), the same way+-- the wallet daily ceiling is summed — one ledger, two ceilings.+create table if not exists agent_wallet_capabilities (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null,+ user_id uuid not null, -- owner who minted the grant+ label text not null, -- holder display ("Sniper · BONK strategy")+ holder_kind text not null default 'manual', -- skill | strategy | integration | manual+ holder_ref text, -- stable id of the holder (strategy id / service host / skill key)+ actions text[] not null, -- allowed action types: trade | snipe | x402+ per_use_usd numeric, -- max USD per single use (null = no per-use cap)+ aggregate_usd numeric, -- lifetime USD ceiling (null = none)+ target_kind text not null default 'any', -- mint | service | destination | any+ targets text[] not null default '{}', -- allowlist; empty = any target within `actions`+ expires_at timestamptz not null, -- hard expiry; a capability is always time-boxed+ revoked_at timestamptz, -- set on revoke; checked on every use+ revoked_reason text,+ grant_sig text not null, -- HMAC tag over the immutable scope (tamper-evidence)+ use_count integer not null default 0,+ last_used_at timestamptz,+ meta jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- The owner-facing Access surface lists a wallet's capabilities newest-first.+create index if not exists agent_wallet_capabilities_agent+ on agent_wallet_capabilities (agent_id, created_at desc);++-- The hot path resolves "is there a live capability for this holder + action?"+-- by (agent, holder_ref) among the not-yet-revoked rows.+create index if not exists agent_wallet_capabilities_holder+ on agent_wallet_capabilities (agent_id, holder_ref)+ where revoked_at is null;++comment on table agent_wallet_capabilities is+ 'Scoped, time-boxed, independently-revocable session keys (capabilities) for '+ 'autonomous agent wallet spending. Each grant narrows authority to a specific '+ 'actor + action(s) + target allowlist + per-use/aggregate USD ceiling + expiry. '+ 'Enforced server-side in api/_lib/wallet-capabilities.js, composed with the '+ 'wallet-wide policy in api/_lib/agent-trade-guards.js. Owner-managed via the '+ 'wallet hub Access tab (/api/agents/:id/solana/capabilities).';++-- Tag custody/spend rows with the capability that authorized them, so the+-- per-capability aggregate ceiling is summed from the SAME ledger that backs the+-- wallet daily ceiling. Additive nullable column — existing rows (and every spend+-- that carried no capability) stay capability_id = NULL and are unaffected.+alter table agent_custody_events+ add column if not exists capability_id uuid;++-- The aggregate-ceiling query sums recent spend rows per capability.+create index if not exists agent_custody_events_capability+ on agent_custody_events (capability_id, created_at)+ where capability_id is not null;++commit;diff --git a/api/_lib/wallet-anomaly.js b/api/_lib/wallet-anomaly.jsnew file mode 100644index 000000000..fab0318a0--- /dev/null+++ b/api/_lib/wallet-anomaly.js@@ -0,0 +1,414 @@+// Behavioral anomaly engine for custodial agent wallets — the wallet's immune+// system. Pure, synchronous, deterministic, unit-testable. No I/O, no clock, no+// randomness: every function takes its live numbers as arguments so the same+// inputs always produce the same verdict (the orchestrator in+// api/_lib/anomaly-events.js feeds it real custody history + live counts).+//+// The model has three pieces:+// 1. computeBaseline(events, nowMs) — learns an agent's "normal" from its real+// custody spend history (size, velocity, counterparties, active hours, assets).+// 2. scoreOutbound({ baseline, config, action, recent }) — scores one pending+// outbound action against the baseline into an interpretable signal: a 0..1+// score plus NAMED factors ("3.2× your largest-ever trade", "first payment to+// this address", "12 spends in the last minute — far above your usual pace").+// 3. applyApproval(config, evt) — when an owner approves a flagged action, folds+// that pattern into the config so the same action never re-trips (the wallet+// gets smarter, not naggier).+//+// Combination is noisy-OR (1 − Π(1 − wᵢ)): independent weak signals compound but+// stay bounded in [0,1), and any single catastrophic signal dominates. Catastrophic+// factors (a brand-new high-value destination, a hard velocity spike) carry a+// `critical` severity that forces a freeze regardless of sensitivity — we accept a+// rare false positive there to never miss the drain-the-wallet case.++// ── tunables ──────────────────────────────────────────────────────────────────++// Below this many priced events an agent has too little history to trust tight+// baselines; we widen tolerances and only the most extreme signals can flag.+export const MIN_HISTORY = 5;++// Distinct destinations kept on the baseline (a hard cap so meta can't bloat).+const MAX_COUNTERPARTIES = 200;+// USD samples kept for the size distribution.+const MAX_USD_SAMPLES = 500;++// Absolute USD floors. A spend under the "ignorable" floor is never worth+// flagging on size/counterparty alone (dust); a spend over the "large" floor is+// material even when an agent has thin history.+const USD_DUST = 1;+const USD_LARGE_ABS = 250;++// Velocity: a hard burst (this many spends inside 60s) is treated as a critical+// signal on its own — this is the signature of a leaked-session drain that stays+// under the daily USD cap by making many small payments fast.+const BURST_1MIN_ABS = 8;+const BURST_10MIN_ABS = 20;++export const SENSITIVITY_PRESETS = Object.freeze({+ // freeze when score ≥ threshold. Lower threshold = more protective = more alerts.+ relaxed: { key: 'relaxed', label: 'Relaxed', threshold: 0.85, description: 'Only freezes on the clearest threats. Fewest alerts.' },+ balanced: { key: 'balanced', label: 'Balanced', threshold: 0.7, description: 'Recommended. Freezes on strong anomalies, lets normal behavior through.' },+ strict: { key: 'strict', label: 'Strict', threshold: 0.5, description: 'Freezes on the first sign of unusual activity. Most alerts.' },+});++export const DEFAULT_SENSITIVITY = 'balanced';++export function sensitivityPreset(key) {+ return SENSITIVITY_PRESETS[key] || SENSITIVITY_PRESETS[DEFAULT_SENSITIVITY];+}++// Human noun for a spend category, used in factor copy.+const CATEGORY_NOUN = { trade: 'trade', snipe: 'snipe', x402: 'payment', withdraw: 'withdrawal' };+function noun(category) {+ return CATEGORY_NOUN[category] || 'spend';+}++// ── config (owner-tunable, stored at agent_identities.meta.anomaly) ─────────────++export const ANOMALY_CONFIG_DEFAULTS = Object.freeze({+ enabled: true,+ sensitivity: DEFAULT_SENSITIVITY,+ // Patterns the owner has approved — folded into scoring so an approved action+ // never re-trips. Approving TEACHES these.+ allow_destinations: [], // base58 destinations the owner blessed+ size_ceiling_usd: null, // owner-approved largest-normal spend+ extra_hours: [], // UTC hours (0–23) the owner marked normal+ // One-tap "sweep to safety" target. When set, a flagged owner can evacuate the+ // wallet to this address in a single tap (a normal audited withdraw).+ safe_address: null,+ updated_at: null,+});++function clampHour(h) {+ const n = Math.floor(Number(h));+ return Number.isFinite(n) && n >= 0 && n <= 23 ? n : null;+}++/** Coerce arbitrary input (DB meta or an API patch) into a clean config object. */+export function normalizeAnomalyConfig(raw) {+ const r = raw && typeof raw === 'object' ? raw : {};+ const sens = SENSITIVITY_PRESETS[r.sensitivity] ? r.sensitivity : DEFAULT_SENSITIVITY;+ const dests = Array.isArray(r.allow_destinations) ? r.allow_destinations : [];+ const seen = new Set();+ const allow = [];+ for (const d of dests) {+ const s = typeof d === 'string' ? d.trim() : '';+ if (s && !seen.has(s)) { seen.add(s); allow.push(s); }+ if (allow.length >= MAX_COUNTERPARTIES) break;+ }+ const hoursRaw = Array.isArray(r.extra_hours) ? r.extra_hours : [];+ const hours = [...new Set(hoursRaw.map(clampHour).filter((h) => h !== null))].sort((a, b) => a - b);+ const ceil = r.size_ceiling_usd;+ const safe = typeof r.safe_address === 'string' && r.safe_address.trim() ? r.safe_address.trim() : null;+ return {+ enabled: r.enabled !== false,+ sensitivity: sens,+ allow_destinations: allow,+ size_ceiling_usd: Number.isFinite(Number(ceil)) && Number(ceil) > 0 ? Number(ceil) : null,+ extra_hours: hours,+ safe_address: safe,+ updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,+ };+}++export function getAnomalyConfig(meta) {+ return normalizeAnomalyConfig(meta?.anomaly);+}++// ── baseline ────────────────────────────────────────────────────────────────++function percentile(sortedAsc, p) {+ if (!sortedAsc.length) return 0;+ const idx = Math.min(sortedAsc.length - 1, Math.max(0, Math.ceil((p / 100) * sortedAsc.length) - 1));+ return sortedAsc[idx];+}++function toMs(v) {+ if (v == null) return null;+ if (typeof v === 'number') return Number.isFinite(v) ? v : null;+ const t = Date.parse(v);+ return Number.isFinite(t) ? t : null;+}++/**+ * Learn an agent's normal spending behavior from its real custody spend events.+ * @param {Array<{usd:?number, destination:?string, asset:?string, category:?string, created_at:(string|number|Date)}>} events+ * @param {number} nowMs+ * @returns {object} baseline profile (JSON-serializable; cached in meta.anomaly_baseline)+ */+export function computeBaseline(events, nowMs = 0) {+ const rows = Array.isArray(events) ? events : [];+ const usd = [];+ const dests = new Map(); // destination -> count+ const assets = new Set();+ const hourCounts = new Array(24).fill(0);+ const hourBuckets = new Map(); // floor(ts/3600000) -> count (for velocity)+ let firstAt = null;+ let lastAt = null;++ for (const e of rows) {+ const ms = toMs(e?.created_at);+ const v = e?.usd;+ if (typeof v === 'number' && Number.isFinite(v) && v >= 0) {+ if (usd.length < MAX_USD_SAMPLES) usd.push(v);+ }+ const dest = typeof e?.destination === 'string' && e.destination.trim() ? e.destination.trim() : null;+ if (dest) dests.set(dest, (dests.get(dest) || 0) + 1);+ const asset = typeof e?.asset === 'string' && e.asset.trim() ? e.asset.trim() : null;+ if (asset) assets.add(asset);+ if (ms != null) {+ const h = new Date(ms).getUTCHours();+ hourCounts[h] += 1;+ const b = Math.floor(ms / 3_600_000);+ hourBuckets.set(b, (hourBuckets.get(b) || 0) + 1);+ if (firstAt == null || ms < firstAt) firstAt = ms;+ if (lastAt == null || ms > lastAt) lastAt = ms;+ }+ }++ const usdSorted = usd.slice().sort((a, b) => a - b);+ const usdSum = usdSorted.reduce((s, x) => s + x, 0);+ const perHour = [...hourBuckets.values()].sort((a, b) => a - b);+ // Most-active counterparties first, capped.+ const counterparties = [...dests.entries()]+ .sort((a, b) => b[1] - a[1])+ .slice(0, MAX_COUNTERPARTIES)+ .map(([d]) => d);+ const activeHours = hourCounts.map((c, h) => (c > 0 ? h : -1)).filter((h) => h >= 0);++ return {+ version: 1,+ n: usdSorted.length,+ total_events: rows.length,+ usd: {+ max: usdSorted.length ? usdSorted[usdSorted.length - 1] : 0,+ p95: percentile(usdSorted, 95),+ mean: usdSorted.length ? usdSum / usdSorted.length : 0,+ samples: usdSorted.length,+ },+ velocity: {+ per_hour_p95: percentile(perHour, 95),+ per_hour_max: perHour.length ? perHour[perHour.length - 1] : 0,+ active_hour_buckets: perHour.length,+ },+ counterparties,+ counterparty_count: dests.size,+ active_hours: activeHours,+ assets: [...assets],+ first_at: firstAt ? new Date(firstAt).toISOString() : null,+ last_at: lastAt ? new Date(lastAt).toISOString() : null,+ computed_at: nowMs ? new Date(nowMs).toISOString() : null,+ };+}++/** A fresh, empty baseline (no history yet). */+export function emptyBaseline() {+ return computeBaseline([], 0);+}++// ── scoring ───────────────────────────────────────────────────────────────────++// noisy-OR over independent factor weights.+function combine(weights) {+ let keep = 1;+ for (const w of weights) keep *= (1 - Math.min(0.999, Math.max(0, w)));+ return 1 - keep;+}++function round2(n) { return Math.round(n * 100) / 100; }++/**+ * Score one pending outbound action against the agent's baseline.+ *+ * Pure + total: never throws, never reads the clock. The orchestrator supplies+ * `action.atMs` (decision time) and `recent` (live velocity counts from a cheap+ * indexed query). Returns an interpretable verdict; the caller decides what to do+ * with `decision`.+ *+ * @param {object} o+ * @param {object} o.baseline from computeBaseline()+ * @param {object} o.config normalized anomaly config (owner-tuned + learned)+ * @param {object} o.action { usdValue:?number, destination:?string, asset:?string, category:string, atMs:number }+ * @param {object} o.recent { count_1min:number, count_10min:number } live counts incl. this action+ * @returns {{ score:number, decision:'allow'|'freeze', threshold:number, sensitivity:string,+ * lowHistory:boolean, critical:boolean, factors:Array<{key,label,weight,severity}> }}+ */+export function scoreOutbound({ baseline, config, action, recent } = {}) {+ const b = baseline && typeof baseline === 'object' ? baseline : emptyBaseline();+ const cfg = normalizeAnomalyConfig(config);+ const a = action || {};+ const r = recent || {};+ const preset = sensitivityPreset(cfg.sensitivity);++ const usd = typeof a.usdValue === 'number' && Number.isFinite(a.usdValue) && a.usdValue >= 0 ? a.usdValue : null;+ const dest = typeof a.destination === 'string' && a.destination.trim() ? a.destination.trim() : null;+ const asset = typeof a.asset === 'string' && a.asset.trim() ? a.asset.trim() : null;+ const category = typeof a.category === 'string' ? a.category : '';+ const atMs = Number.isFinite(a.atMs) ? a.atMs : 0;+ const hour = atMs ? new Date(atMs).getUTCHours() : null;+ const lowHistory = (b.n || 0) < MIN_HISTORY;++ const allowDest = new Set(cfg.allow_destinations || []);+ const extraHours = new Set(cfg.extra_hours || []);+ const count1 = Number(r.count_1min) || 0;+ const count10 = Number(r.count_10min) || 0;++ const factors = [];++ // 1 — transaction size vs the largest the agent has ever spent.+ const ceiling = Math.max(Number(b.usd?.max) || 0, cfg.size_ceiling_usd || 0);+ if (usd != null && usd > USD_DUST && ceiling > 0) {+ const ratio = usd / ceiling;+ if (ratio > 1.15) {+ let w;+ if (ratio > 6) w = 0.9;+ else if (ratio > 3) w = 0.7;+ else if (ratio > 1.5) w = 0.45;+ else w = 0.18;+ if (lowHistory) w *= 0.5; // thin history → size baseline is unreliable+ const critical = ratio > 3 && usd >= USD_LARGE_ABS && !lowHistory;+ factors.push({+ key: 'size',+ label: `${round2(ratio).toFixed(1)}× your largest-ever ${noun(category)} ($${usd.toFixed(2)} vs $${ceiling.toFixed(2)})`,+ weight: round2(w),+ severity: critical ? 'critical' : w >= 0.45 ? 'high' : 'medium',+ });+ }+ } else if (usd != null && usd >= USD_LARGE_ABS && ceiling <= 0) {+ // No priced history at all but a materially large first spend.+ factors.push({+ key: 'size',+ label: `A $${usd.toFixed(2)} ${noun(category)} with no prior spending history to compare against`,+ weight: 0.4,+ severity: 'high',+ });+ }++ // 2 — destination never seen before. Weighted HARD when it's also high-value:+ // a brand-new high-value counterparty is the catastrophic case.+ if (dest && !allowDest.has(dest) && !(b.counterparties || []).includes(dest)) {+ const knownCount = b.counterparty_count || 0;+ const material = usd == null ? false : usd >= USD_LARGE_ABS || (ceiling > 0 && usd >= 0.5 * ceiling);+ const overCeiling = usd != null && ceiling > 0 && usd > ceiling;+ let w;+ let severity;+ if (lowHistory && knownCount < 2) {+ // Almost everything is "new" early on — only flag if materially large.+ w = material ? 0.6 : 0.2;+ severity = material ? 'high' : 'low';+ } else {+ w = overCeiling ? 0.85 : material ? 0.72 : 0.5;+ severity = overCeiling || (material && !lowHistory) ? 'critical' : 'high';+ }+ const verb = category === 'withdraw' ? 'withdrawal to' : 'payment to';+ factors.push({+ key: 'new_counterparty',+ label: `First ${verb} this address — never used before${material && usd != null ? `, and it’s ${usd >= USD_LARGE_ABS ? 'a large amount' : 'above half your usual ceiling'}` : ''}`,+ weight: round2(w),+ severity,+ });+ }++ // 3 — velocity spike. Evaluated even with no USD (covers unpriceable spends and+ // the drain-under-the-cap attack: many small payments in a tight window).+ if (count1 >= BURST_1MIN_ABS || count10 >= BURST_10MIN_ABS) {+ factors.push({+ key: 'velocity',+ label: count1 >= BURST_1MIN_ABS+ ? `${count1} spends in the last minute — far above your normal pace`+ : `${count10} spends in 10 minutes — far above your normal pace`,+ weight: 0.9,+ severity: 'critical',+ });+ } else if (count10 >= 5) {+ // Relative spike vs the agent's busiest historical 10-minute-ish rate.+ // Approximate a normal 10-min ceiling from the busiest hour bucket.+ const normal10 = Math.max(2, Math.ceil((Number(b.velocity?.per_hour_max) || 0) / 6) + 1);+ const ratio = count10 / normal10;+ if (ratio >= 3) {+ factors.push({+ key: 'velocity',+ label: `${count10} spends in 10 minutes — about ${Math.round(ratio)}× your normal pace`,+ weight: round2(Math.min(0.7, 0.35 + 0.1 * ratio)),+ severity: 'high',+ });+ }+ }++ // 4 — off-hours. Only meaningful once the agent has a clear daily rhythm.+ if (hour != null && (b.active_hours || []).length > 0 && (b.active_hours || []).length <= 18 && (b.total_events || 0) >= 8) {+ if (!(b.active_hours || []).includes(hour) && !extraHours.has(hour)) {+ factors.push({+ key: 'off_hours',+ label: `First activity at this hour (${String(hour).padStart(2, '0')}:00 UTC) — outside your agent’s usual hours`,+ weight: 0.3,+ severity: 'medium',+ });+ }+ }++ // 5 — new asset (minor).+ if (asset && (b.assets || []).length > 0 && !(b.assets || []).includes(asset)) {+ factors.push({+ key: 'new_asset',+ label: `First time moving ${asset}`,+ weight: 0.2,+ severity: 'low',+ });+ }++ factors.sort((x, y) => y.weight - x.weight);+ const score = round2(combine(factors.map((f) => f.weight)));+ const critical = factors.some((f) => f.severity === 'critical');+ const decision = (critical || score >= preset.threshold) && cfg.enabled ? 'freeze' : 'allow';++ return {+ score,+ decision,+ threshold: preset.threshold,+ sensitivity: cfg.sensitivity,+ lowHistory,+ critical,+ factors,+ };+}++/** One-line plain-language summary of a verdict for notifications / the timeline. */+export function summarize(verdict) {+ const f = verdict?.factors?.[0];+ if (!f) return 'Nothing unusual.';+ if (verdict.factors.length === 1) return f.label;+ return `${f.label} (+${verdict.factors.length - 1} more signal${verdict.factors.length - 1 === 1 ? '' : 's'})`;+}++// ── learning (approve teaches the baseline) ─────────────────────────────────────++/**+ * Fold an approved flagged action into the config so the same pattern won't+ * re-trip. Returns a NEW normalized config (does not mutate). The owner approving+ * "yes this was me" is the highest-quality training signal we get.+ *+ * @param {object} config current normalized config+ * @param {object} evt the flagged anomaly event: { destination, usd, hour_utc }+ */+export function applyApproval(config, evt = {}) {+ const cfg = normalizeAnomalyConfig(config);+ const dest = typeof evt.destination === 'string' && evt.destination.trim() ? evt.destination.trim() : null;+ const allow = dest && !cfg.allow_destinations.includes(dest)+ ? [...cfg.allow_destinations, dest].slice(-MAX_COUNTERPARTIES)+ : cfg.allow_destinations;+ const usd = Number(evt.usd);+ const ceiling = Number.isFinite(usd) && usd > 0+ ? Math.max(cfg.size_ceiling_usd || 0, usd)+ : cfg.size_ceiling_usd;+ const hour = clampHour(evt.hour_utc);+ const hours = hour != null && !cfg.extra_hours.includes(hour)+ ? [...cfg.extra_hours, hour].sort((a, b) => a - b)+ : cfg.extra_hours;+ return normalizeAnomalyConfig({+ ...cfg,+ allow_destinations: allow,+ size_ceiling_usd: ceiling,+ extra_hours: hours,+ });+}diff --git a/api/wk.js b/api/wk.jsindex 81e0adc80..e15e60317 100644--- a/api/wk.js+++ b/api/wk.js@@ -2234,25 +2234,44 @@ async function handleThreeVanity(req, res) {200,{protocol: 'three-vanity/v1',+ protocols: ['three-vanity/v1', 'three-pog/v1'],description:- 'Provably-fair Solana vanity grinding. Each key is ground under a commit–reveal ' +- 'seed-mixing protocol and delivered with a receipt signed by the service key below. ' +- 'Verify a receipt entirely client-side — nothing here is trusted, everything is recomputed.',+ 'Provably-fair Solana vanity grinding. Keys are ground under a commit–reveal ' ++ 'seed-mixing protocol (three-vanity/v1) and/or attested with a proof-of-grind ' ++ 'certificate (three-pog/v1). Both are signed by the attestation key below and ' ++ 'verified entirely client-side — nothing here is trusted, everything is recomputed.',serviceKey: {curve: 'ed25519',+ keyId: identity.keyId,publicKeyBase58: identity.publicKeyBase58,publicKeyHex: identity.publicKeyHex,- use: 'receipt-signing',+ use: 'receipt-signing, proof-of-grind-attestation',},+ // Rotation-aware verifier keyring: the set of attestation keys a verifier+ // should accept. On rotation, the retiring key stays here (with a+ // `retired` flag/date) until all in-flight certs age out, so historical+ // proofs keep verifying. Today there is one active key.+ keyring: [+ {+ keyId: identity.keyId,+ curve: 'ed25519',+ publicKeyBase58: identity.publicKeyBase58,+ status: 'active',+ },+ ],schemes: {commitment: 'sha256(domain‖serverSeed)',seedMix: 'hkdf-sha256(serverSeed‖clientSeed‖requestNonce)',candidate: 'hmac-sha256(masterSeed, domain‖uint64_be(index)) → ed25519 seed',signature: 'ed25519',sealedEnvelope: 'x25519-hkdf-sha256-aes256gcm/v1',+ proofOfGrind: 'ed25519 over canonical(three-pog/cert/v1 ‖ sorted-json(core))',+ splitKeyNonCustody: 'P1 + a2·B == address (recomputed from public points)',},endpoints: {- grind: `${origin}/api/x402/vanity-verifiable`,+ grind: `${origin}/api/x402/vanity`,+ verifiableGrind: `${origin}/api/x402/vanity-verifiable`,+ certRegistry: `${origin}/api/vanity/cert`,verifyPage: `${origin}/vanity/verify`,},documentation: `${origin}/vanity/verify`,diff --git a/api/x402/vanity.js b/api/x402/vanity.jsindex 1b6a9b5ec..23c77573c 100644--- a/api/x402/vanity.js+++ b/api/x402/vanity.js@@ -265,6 +265,16 @@ const DISCOVERY_OUTPUT_SCHEMA = {},network: { type: 'string' },explorerUrl: { type: 'string', format: 'uri' },+ certificate: {+ type: 'object',+ description:+ 'Proof-of-grind certificate (three-pog/v1): a public, signed attestation of the ' ++ 'pattern, address, difficulty, rarity, and a freshness nonce — verifiable offline ' ++ 'with verifyProofOfGrind() or at /vanity/verify. Contains no secret. The attestation ' ++ 'public key is published at /.well-known/three-vanity.json.',+ },+ verifyUrl: { type: 'string', format: 'uri', description: 'Public verifier page for the certificate.' },+ serviceKeyUrl: { type: 'string', format: 'uri', description: 'Published attestation key (.well-known).' },},};@@ -416,6 +426,60 @@ async function sealSecret(result, sealTo) {};}+const PUBLIC_ORIGIN = env.APP_ORIGIN || 'https://three.ws';++// Attach a public, offline-verifiable proof-of-grind certificate to a grind+// result. The certificate attests the pattern, address, difficulty, rarity,+// freshness nonce, and (when sealed) the delivery envelope — signed by the+// long-lived three.ws attestation key. It contains NO secret, so it is safe in+// the response, the idempotency cache, and at rest. The certificate is also+// registered (first-write-wins) so a buyer/marketplace can later confirm this is+// the single canonical "freshly ground" proof for the address. Registry/signing+// failures must never break delivery — the buyer paid for a key, and the+// certificate is additive — so issuance degrades gracefully on error.+async function attachCertificate(result, pattern) {+ let identity;+ try {+ identity = await getServiceIdentity();+ } catch (err) {+ console.error('[vanity/cert] attestation key unavailable; delivering without certificate', err?.message || err);+ return result;+ }+ const delivery = result.sealed+ ? { sealed: true, sealedScheme: result.sealedScheme || SEALED_ENVELOPE_SCHEME, sealedRecipient: result.sealedSecret?.recipient || null }+ : { sealed: false };+ let certificate;+ try {+ const core = buildCertificateCore({+ address: result.address,+ pattern: { prefix: pattern.prefix || null, suffix: pattern.suffix || null, ignoreCase: !!pattern.ignoreCase },+ format: result.format,+ attempts: result.attempts,+ delivery,+ network: 'solana',+ keyId: identity.keyId,+ });+ certificate = signCertificate({ core, signingSeed: identity.seed, keyId: identity.keyId });+ } catch (err) {+ console.error('[vanity/cert] failed to sign certificate; delivering without it', err?.message || err);+ return result;+ }+ try {+ await registerCert(certificate);+ } catch (err) {+ // A registry outage degrades to "offline-verifiable only" — the certificate+ // still verifies cryptographically; only the single-issuance check is skipped.+ console.warn('[vanity/cert] registry unavailable; certificate is offline-verifiable only', err?.message || err);+ }+ return {+ ...result,+ certificate,+ verifyUrl: `${PUBLIC_ORIGIN}/vanity/verify`,+ certVerifyUrl: `${PUBLIC_ORIGIN}/vanity/verify?cert=${encodeURIComponent(certificate.certId)}`,+ serviceKeyUrl: `${PUBLIC_ORIGIN}/.well-known/three-vanity.json`,+ };+}+async function grindAndShape({ prefix, suffix, ignoreCase, format, strength, sealTo }) {let shaped;if (format === FORMAT_MNEMONIC) {@@ -469,7 +533,8 @@ async function grindAndShape({ prefix, suffix, ignoreCase, format, strength, sea};}- return sealTo ? sealSecret(shaped, sealTo) : shaped;+ const delivered = sealTo ? await sealSecret(shaped, sealTo) : shaped;+ return attachCertificate(delivered, { prefix, suffix, ignoreCase });}export default wrap(async (req, res) => {diff --git a/prompts/phase-4-virality/00-README.md b/prompts/phase-4-virality/00-README.mddeleted file mode 100644index d7664137d..000000000--- a/prompts/phase-4-virality/00-README.md+++ /dev/null@@ -1,131 +0,0 @@-# Phase 4 — Virality Engine (Index — DO NOT DELETE)--> This file is the index and shared context for **Phase 4** of the pump.fun-> social-trading roadmap. It is NOT a task. Do not delete it. Every numbered-> prompt in this folder is a self-contained task for one fresh agent chat. When-> an agent finishes a numbered task (and its self-review pass), it deletes-> **only its own** numbered prompt file — never this README, never another's.--Roadmap source of truth: `docs/roadmap/pumpfun-social-trading.md` (Prompt E,-"Phase 4: Social loop & growth") and `docs/roadmap/pumpfun-trading.md`-(§8, "Phase 4 — Virality engine").-------## The vision--Phases 0–3 built the truth: a provable, on-chain track record (the leaderboard +-trader profiles), a non-custodial copy engine, and performance-fee settlement.-The product is **correct and trustworthy** — but trust alone doesn't grow it.--**Phase 4 makes wins spread.** Every profitable close should be a screenshot worth-sharing, every shared card should carry a referral link, every follow should feed a-live activity stream, and every week the platform should hand each trader a recap-worth posting. The loop we are wiring:--> a trader wins → the win renders as a beautiful, provable card → the card spreads-> (in-app feed, Telegram, X) with a referral link → a new user lands on a profile-> that *proves* the track record → they copy or deploy → they win → repeat.--The north star for this phase: a new user can arrive from a shared card, see-irrefutable proof, and start copying within one session — and the trader who earned-that follow can *see* their reach (copiers gained, $THREE earned, reputation rising).--This is not growth-hacking spam. Every recommendation is computed from **real copy-data**, every badge is gated on **attested on-chain metrics**, every card shows-**real numbers**. Proof, not promises. If a number can't be verified, it doesn't ship.-------## What already exists (build ON this — do not rebuild it)--Proof / track-record layer (Phases 0–1):-- `api/sniper/leaderboard.js` — public leaderboard ranked by composite TraderScore- over a window; superset rows (`win_rate`, `score`, `verified`, `roi_pct`,- `drawdown`, recent closed trades, open positions). The shared trader-stats truth- layer feeds this and the profile so they can never disagree.-- `api/sniper/trader.js` — single-trader stats; `api/sniper/history.js` — trade log.-- `pages/leaderboard.html`, `pages/trader.html`, `pages/arena.html` — the front door.-- `api/trader-og.js` — `GET /api/trader-og?agent_id=<uuid>`: dynamic 1200×630 SVG- OG card (score gauge, win rate, realized P&L, trades closed, best trade) for- `/trader/<id>/share`. The PnL-card work extends this language.-- Sibling OG generators to match style: `api/og-leaderboard.js`, `api/agent-og.js`.--Copy engine + fees (Phases 2–3):-- `api/cron/copy-fanout.js`, `api/cron/mirror-fanout.js` — copy/mirror execution.-- `api/cron/trader-score-attest.js` — on-chain attestation of TraderScore.-- `pages/vaults.html` + vault APIs — Back-an-Agent copy vaults (the money loop).-- `pages/feed.html` — "Your Feed" page ("Recent activity from the people and agents- you follow"). Currently thin — Phase 4 fills it.--Referrals:-- `api/_lib/referrals.js` — code generation/normalization/availability/claim- (`generateReferralCode`, `setReferralCode`, `getReferralCodeAvailability`, …).-- `api/_lib/referral-rewards.js`, `api/_lib/activation.js` — reward/activation logic.-- `api/_lib/migrations/20260628120000_referral_activation.sql`.--Notifications & distribution:-- `api/_lib/notify.js` — `insertNotification(userId, type, payload)`,- `recordEvent(...)`, `emailAllowedForType(...)`.-- `api/_lib/notify-prefs.js`, `api/notifications/*` (index, preferences, read-all,- track, `[id]`), `api/_lib/email.js`.-- Telegram delivery: `src/pump/telegram-delivery.js`, `api/pump/deliver-telegram.js`,- `scripts/changelog-telegram.mjs`, migrations `*_sniper_telegram_notify.sql`,- `*_copy_telegram.sql`, `*_oracle_watch_telegram.sql`.-- Cron pattern to copy: `api/cron/rewards-distribute.js` (scheduled, idempotent).--KOL pre-seed:-- `api/kol/[action].js` (Birdeye/GMGN proxy), `api/kol/trades.js`,- `src/kol/leaderboard.js`, `src/kol/wallet-pnl.js`, `src/kol/wallets.js`,- `src/kol/wallets.json`, `src/kol/gmgn-parser.js`, `src/kol/kolscan-live.js`.--Schema & infra:-- `api/_lib/schema.sql` + `api/_lib/migrations/` — add new tables here (timestamped).-- `vercel.json` — register any new cron + route.-- `api/_lib/db.js` (`sql`), `api/_lib/http.js` (`cors`, `wrap`), `api/_lib/validate.js`.-------## The prompts--| # | Prompt | Builds on |-|---|---|---|-| 01 | PnL & trade share cards | `api/trader-og.js`, OG siblings, history |-| 02 | The Feed (follow-graph activity + recommendations) | `pages/feed.html`, copy data |-| 03 | Referral wiring everywhere | `api/_lib/referrals.js`, share cards |-| 04 | Trader Wrapped — weekly recap (cron) | `rewards-distribute.js`, notify, Telegram |-| 05 | Proven-track-record verification badge | `trader-score-attest.js`, leaderboard |-| 06 | KOL pre-seed + "claim this profile" | `api/kol/*`, `src/kol/*`, leaderboard |-| 07 | Telegram / X distribution bots | telegram-delivery, share cards |-| 08 | Integration QA & polish (run last) | all of the above |--Run 01 first (cards are the unit of virality everything else carries). 02–07 can run-in parallel chats once 01 lands. Run 08 last, after the others merge.-------## Global operating rules (every prompt repeats these — non-negotiable)--- Read `CLAUDE.md` and `STRUCTURE.md` first; **CLAUDE.md overrides defaults.**-- **No mocks / fake data / placeholders / TODOs / stubs.** Real APIs, real on-chain- data, real implementations. Every number on a card or in the feed is verifiable.-- **$THREE is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).- Never reference any other token anywhere — code, copy, fixtures, cards, bot posts.- The two runtime-data-only exceptions in CLAUDE.md still apply (user-supplied mints- in the launcher; platform launch directories rendering real launch records).-- **Every state is designed** — loading (skeletons), empty (tells the user what to- do next), error (actionable + recoverable), populated, overflow. Mobile-first.-- **No errors without solutions.** Ship working fallbacks and failsafes.-- Concurrent agents share this worktree — **stage explicit paths only** (never- `git add -A`/`.`); re-check `git status` and `git diff --staged` before committing.-- **esbuild trap:** never commit `api/*.js` starting with `__defProp`/`createRequire`;- recover with `git restore -- api/ public/`.-- Every user-visible change → an entry in `data/changelog.json`, then- `npm run build:pages`. New page → the `added` date in `data/pages.json` feeds it.-- DB changes go in a **new timestamped migration** under `api/_lib/migrations/` and- are reflected in `api/_lib/schema.sql`. New crons/routes → `vercel.json`.-- Tests: `npm test` (vitest + playwright) and `npm run typecheck` must pass. Add- tests for new logic (truth-layer math, dedup, gating, idempotency).-- Push to BOTH remotes when asked (`git push threeD main && git push threews main`);- never pull/fetch/merge from `threeD`.-- **Definition of done = CLAUDE.md's checklist.** If you can't verify a step, say so.diff --git a/prompts/phase-4-virality/01-pnl-share-cards.md b/prompts/phase-4-virality/01-pnl-share-cards.mddeleted file mode 100644index d5b285ab6..000000000--- a/prompts/phase-4-virality/01-pnl-share-cards.md+++ /dev/null@@ -1,64 +0,0 @@-# Phase 4 · 01 — PnL & trade share cards--Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, the-existing files, and the non-negotiable operating rules live there. This task assumes-them.--## Goal--Make every win shareable. A profitable closed trade — and a trader's overall track-record — must render as a beautiful, **provable** card that previews perfectly when-pasted into X, Telegram, Discord, or iMessage, and that carries a referral link back-to a page that proves the numbers. Cards are the atomic unit of virality; everything-else in Phase 4 carries them.--## Build on (do not rebuild)--- `api/trader-og.js` — the existing `/api/trader-og?agent_id=` 1200×630 SVG card- (score gauge, win rate, realized P&L, trades closed, best trade) for- `/trader/<id>/share`. Extend this visual language; do not fork a new style.-- OG siblings for consistent typography/gradients: `api/og-leaderboard.js`,- `api/agent-og.js`.-- `api/sniper/history.js` / `api/sniper/trader.js` — the real closed-trade + stats- source. The shared trader-stats truth layer is the only number source.-- `pages/trader.html` — where the share affordance lives.--## Deliver--1. **Per-trade PnL card.** A new dynamic OG endpoint (e.g. `api/trade-og.js`,- `GET /api/trade-og?trade=<id>`) rendering a single closed trade: coin (ticker +- thumbnail if available), entry/exit, ROI %, realized P&L in SOL and USD, hold- time, the trader's name/avatar, and a small "verified on-chain — view the tx"- proof line. Same dark card anatomy as `trader-og.js`. Must 404 cleanly for- unknown/open trades and degrade gracefully if the thumbnail is missing.-2. **Share routes + meta.** `/trade/<id>/share` and the existing `/trader/<id>/share`- serve HTML with correct `og:image`, `twitter:card=summary_large_image`,- `og:title`/`og:description` populated from real data, plus a visible- human-facing card and a prominent CTA ("Copy this trader" / "See full track- record"). The referral link (see prompt 03) is embedded in every share URL.-3. **One-tap share UI.** On `pages/trader.html` and anywhere a closed trade renders- (history rows, the feed from prompt 02), a share control that: copies the share- URL, opens native share sheet on mobile (`navigator.share` with graceful- fallback), and offers "share to X" / "copy for Telegram" intents. Hover/active/- focus states, keyboard-operable, ARIA-labeled.-4. **Caching & cost.** OG endpoints set sensible cache headers (match `trader-og.js`- `s-maxage`/`stale-while-revalidate`), and never trigger an expensive recompute on- every crawler hit. SVG only — no headless browser.--## Acceptance--- Pasting a `/trade/<id>/share` or `/trader/<id>/share` link into a link-preview- validator shows the card with **real** numbers; no placeholder values.-- The card's numbers match the trader profile exactly (same truth layer).-- Unknown trade id, open (unclosed) trade, and missing-avatar cases all render a- clean state — never a broken image or a 500.-- Share control works on mobile (native sheet) and desktop (copy + intents), with- full hover/active/focus states.-- `npm test` + `npm run typecheck` green; a test asserts the OG endpoint's numbers- equal the trader-stats truth layer for a fixture trade.-- `data/changelog.json` entry added (`feature`), `npm run build:pages` run.--## When done--Run the self-review protocol in `/CLAUDE.md`, then delete **only this file**-(`01-pnl-share-cards.md`). Leave `00-README.md` and all other prompts intact.diff --git a/prompts/phase-4-virality/02-the-feed.md b/prompts/phase-4-virality/02-the-feed.mddeleted file mode 100644index 3fa9961dd..000000000--- a/prompts/phase-4-virality/02-the-feed.md+++ /dev/null@@ -1,60 +0,0 @@-# Phase 4 · 02 — The Feed (follow-graph activity + recommendations)--Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing-files, and non-negotiable operating rules. This task assumes them.--## Goal--Turn `pages/feed.html` from a thin shell into the platform's living activity stream:-a real-time, mobile-first feed of what the traders and agents you follow (and copy)-are doing — scoped to **your** follow graph — plus recommendations computed from-**real copy data**, not influencer noise. The feed is where shared cards (prompt 01)-get their second life and where "who should I copy next" gets answered honestly.--## Build on (do not rebuild)--- `pages/feed.html` — "Your Feed" page already exists ("Recent activity from the- people and agents you follow"). Fill it; keep the route.-- `api/sniper/leaderboard.js`, `api/sniper/history.js`, `api/sniper/trader.js` — the- trade + stats truth layer.-- Copy data from the copy engine (`api/cron/copy-fanout.js`,- `api/cron/mirror-fanout.js` and their tables) — the source for "who copies whom".-- `api/_lib/db.js`, `api/_lib/http.js`, `api/_lib/validate.js`.-- PnL/trade cards from prompt 01 — feed items embed/link them.--## Deliver--1. **Feed API.** `GET /api/feed?cursor=…` returning the authenticated user's- follow-graph activity (followed/copied traders' opens, closes, big wins, vault- deposits/withdrawals, graduations), newest first, cursor-paginated. Each item- carries enough to render without an N+1 fan-out. IP + auth rate-limited.-2. **Recommendations from real copy data.** A "traders you follow also copy X"- strip computed from the actual copy graph (co-copy / collaborative signal), not a- hardcoded list. Exclude already-followed traders; rank by a defensible signal- (co-copy count × recent realized PnL). Show *why* it's recommended ("copied by 4- traders you follow").-3. **Feed UI.** Render in `pages/feed.html`: trade-close items show the PnL card- inline with a share control (prompt 01); each item links to the trader profile and- a one-tap "Copy" / "Back this agent" CTA. Live updates via the existing stream- mechanism if one is wired (e.g. `api/sniper/stream.js`/`trades-stream.js`),- otherwise poll-on-focus — no fake "live" indicator without a real source.-4. **Every state designed.** Empty (not following anyone yet → surface the- leaderboard + top recommendations as the onboarding path), loading (skeleton- rows), error (retry), overflow (long names/large numbers truncate cleanly),- end-of-feed.--## Acceptance--- The feed shows only the signed-in user's graph; a fresh account with no follows- gets the designed empty/onboarding state, not a blank page.-- Recommendations are reproducibly derived from real copy rows (a test asserts the- ranking against a fixture copy graph); no hardcoded trader arrays.-- Pagination is stable under new inserts (cursor, not offset); no dupes/skips.-- Mobile-first; hover/active/focus on every interactive element; keyboard navigable.-- `npm test` + `npm run typecheck` green. `data/changelog.json` entry (`feature`);- `npm run build:pages` run.--## When done--Run the `/CLAUDE.md` self-review protocol, then delete **only this file**-(`02-the-feed.md`).diff --git a/prompts/phase-4-virality/03-referral-wiring.md b/prompts/phase-4-virality/03-referral-wiring.mddeleted file mode 100644index 2ca68334a..000000000--- a/prompts/phase-4-virality/03-referral-wiring.md+++ /dev/null@@ -1,57 +0,0 @@-# Phase 4 · 03 — Referral wiring everywhere--Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing-files, non-negotiable rules. This task assumes them.--## Goal--The referral primitives exist but are not woven into the viral surfaces. Wire them so-**every shared card, every invite, every win** carries the sharer's referral code,-attribution survives the signup → activation → copy journey, and the referrer can-*see* their reach and earnings. Referrals are how a shared card converts into a-tracked, rewardable new user.--## Build on (do not rebuild)--- `api/_lib/referrals.js` — `generateReferralCode`, `normalizeReferralCode`,- `getReferralCodeAvailability`, `setReferralCode`, code regex/reserved checks.-- `api/_lib/referral-rewards.js`, `api/_lib/activation.js` — reward + activation.-- `api/_lib/migrations/20260628120000_referral_activation.sql` — existing schema.-- Share cards/routes from prompt 01; the feed from prompt 02; notifications- (`api/_lib/notify.js`).--## Deliver--1. **Code in every share link.** Every share URL produced in prompt 01/02 and across- profiles, leaderboard, vaults, and the feed embeds the signed-in user's referral- code (e.g. `?ref=<code>`). Anonymous/logged-out sharers fall back to a neutral- link (no broken `?ref=undefined`).-2. **Attribution capture & persistence.** Landing with `?ref=` captures the code- (cookie/storage), survives navigation, and is bound to the new account at signup —- then to activation (first copy / first vault deposit / first deploy) via- `activation.js`. Self-referral and code re-binding are rejected. No double-credit.-3. **"Your referral code" surface.** A real UI (settings/profile) to claim a custom- code (`getReferralCodeAvailability` + `setReferralCode`), copy the link, and see a- QR. Validation messages for taken/reserved/invalid codes, all states designed.-4. **Earnings & reach dashboard.** Show the referrer their funnel from real data:- clicks → signups → activations → $THREE earned (from `referral-rewards.js`). No- vanity numbers — every figure traces to a row. Notify on a successful activation- ("X joined from your link and made their first copy").-5. **Reward integrity.** Rewards are idempotent and only fire on genuine activation,- not signup. Document the split/rules inline where they're computed.--## Acceptance--- A shared card link carries the sharer's code; following it through signup +- first-copy credits the referrer exactly once (test covers the full chain +- self-referral rejection + idempotency).-- Custom-code claim flow handles taken/reserved/invalid with designed states.-- Earnings dashboard numbers reconcile to `referral-rewards.js` rows.-- `$THREE` is the only token referenced in any reward copy.-- `npm test` + `npm run typecheck` green. `data/changelog.json` entry- (`feature`/`improvement`); `npm run build:pages` run.--## When done--Run the `/CLAUDE.md` self-review protocol, then delete **only this file**-(`03-referral-wiring.md`).diff --git a/prompts/phase-4-virality/04-trader-wrapped-recap.md b/prompts/phase-4-virality/04-trader-wrapped-recap.mddeleted file mode 100644index aa9b7ab7c..000000000--- a/prompts/phase-4-virality/04-trader-wrapped-recap.md+++ /dev/null@@ -1,59 +0,0 @@-# Phase 4 · 04 — Trader Wrapped (weekly recap)--Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing-files, non-negotiable rules. This task assumes them.--## Goal--Once a week, hand every active trader a recap worth posting: their best calls,-copiers gained, $THREE earned, reputation movement — delivered in-app and (opt-in)-to Telegram, each with a one-tap share card (prompt 01) carrying their referral link-(prompt 03). This is recurring, self-propagating content: the platform manufactures a-shareable moment for every trader, every week.--## Build on (do not rebuild)--- `api/cron/rewards-distribute.js` — the canonical scheduled, idempotent cron- pattern. Copy its structure (windowing, idempotency key, batch, logging).-- `api/_lib/notify.js` (`insertNotification`), `api/_lib/notify-prefs.js`,- `api/notifications/*` — in-app delivery + per-type prefs.-- `src/pump/telegram-delivery.js`, `api/pump/deliver-telegram.js` — Telegram delivery.-- The trader-stats truth layer (`api/sniper/trader.js`/`history.js`) — recap numbers.-- Share-card endpoints from prompt 01; referral link from prompt 03.-- `vercel.json` — register the new weekly cron.--## Deliver--1. **Recap computation.** A function that, for a given week window, computes per- active trader: best trade(s), realized PnL, win rate delta vs prior week, copiers- gained/lost, $THREE earned (perf fees + referrals), reputation/score movement, and- a headline ("Your sharpest week yet" / "First week in the green"). All from real- rows; skip traders with no activity (no empty "you did nothing" spam).-2. **Weekly cron.** `api/cron/trader-wrapped.js` registered in `vercel.json`,- idempotent per (trader, week) so a re-run never double-sends. Batched, with- structured logging and a dead-letter-safe path on partial failure.-3. **In-app recap.** A notification (`insertNotification`) linking to a recap view- (a `/wrapped/<week>` route or modal) that renders the week as a designed,- screenshot-worthy card with a share control + referral link. Respects notify-prefs.-4. **Telegram recap.** Opt-in delivery via the existing Telegram path to traders who- linked Telegram, gated on their notification preferences. Plain-language, links- back with `?ref=`.-5. **Idempotency & cost.** One recap per trader per week; cron is cheap (aggregate- queries, not per-trader fan-out where avoidable).--## Acceptance--- Running the cron twice for the same week sends exactly one recap per trader (test- asserts idempotency key behavior).-- Recap numbers reconcile to the trader-stats truth layer; inactive traders are- skipped, not spammed.-- Telegram delivery only to opted-in, linked traders; in-app respects notify-prefs.-- Recap card is mobile-first, fully designed, shareable with referral link embedded.-- `$THREE` is the only token in any recap copy.-- `npm test` + `npm run typecheck` green. `data/changelog.json` entry (`feature`);- `npm run build:pages` run. New cron present in `vercel.json`.--## When done--Run the `/CLAUDE.md` self-review protocol, then delete **only this file**-(`04-trader-wrapped-recap.md`).diff --git a/prompts/phase-4-virality/05-verification-badge.md b/prompts/phase-4-virality/05-verification-badge.mddeleted file mode 100644index bc6ff88ca..000000000--- a/prompts/phase-4-virality/05-verification-badge.md+++ /dev/null@@ -1,58 +0,0 @@-# Phase 4 · 05 — Proven-track-record verification badge--Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing-files, non-negotiable rules. This task assumes them.--## Goal--When a shared card brings a stranger to a profile, the single most important question-is "can I trust this track record?" Ship a **verification badge** that answers it —-gated on attested, on-chain metrics, not self-claims — and surface it everywhere a-trader is represented (profile, leaderboard, feed, share cards, vaults). The badge is-the trust primitive the whole viral loop depends on; it must be impossible to fake.--## Build on (do not rebuild)--- `api/cron/trader-score-attest.js` — existing on-chain attestation of TraderScore.- The badge is gated on attested values, not raw API reads.-- `api/sniper/leaderboard.js` / `api/sniper/trader.js` — the truth layer that exposes- `verified`, `win_rate`, `score`, closed-trade count, etc.-- `api/trader-og.js` and share cards (prompt 01); leaderboard/profile/feed surfaces.-- `api/_lib/db.js`, `api/_lib/http.js`; a new migration for any badge state.--## Deliver--1. **Gating rule (explicit, tested).** Define the badge eligibility from attested- metrics: e.g. min closed trades, min realized PnL, min unique coins traded, and a- wash-trading ratio below a threshold (self-trades / circular volume). Encode the- exact thresholds in one place, derived from attested data only. A trader who- degrades below threshold loses the badge — it is a live status, not a one-time- stamp.-2. **Badge evaluation.** A function/endpoint that computes badge status for a trader- from attested rows, with the *reasons* (which criteria pass/fail) so a profile can- show "3/4 criteria met — needs 2 more closed trades". No badge without attestation.-3. **Surface everywhere.** Render the badge consistently on `pages/trader.html`,- `pages/leaderboard.html`, the feed (prompt 02), share/OG cards (prompt 01), and- vault rows. One component/style; tooltip explains what it means and links to the- criteria.-4. **Anti-gaming.** The wash% / circular-volume check must use real on-chain data and- be documented inline. Make it auditable: a profile can show the proof (tx- signatures) behind the verified status.-5. **States.** Verified, eligible-soon (progress shown), not-eligible, and- attestation-pending all designed.--## Acceptance--- Badge status is computed only from attested metrics; a fixture trader below any- threshold is correctly denied, and losing eligibility revokes the badge (tests- cover each criterion boundary + wash% gate).-- The badge renders identically across profile, leaderboard, feed, cards, vaults.-- Tooltip/criteria view explains the gate; verified status links to on-chain proof.-- No self-claimed or unverifiable path to the badge exists.-- `npm test` + `npm run typecheck` green. `data/changelog.json` entry- (`feature`/`security`); `npm run build:pages` run.--## When done--Run the `/CLAUDE.md` self-review protocol, then delete **only this file**-(`05-verification-badge.md`).diff --git a/prompts/phase-4-virality/06-kol-claim-flow.md b/prompts/phase-4-virality/06-kol-claim-flow.mddeleted file mode 100644index 0c8869717..000000000--- a/prompts/phase-4-virality/06-kol-claim-flow.md+++ /dev/null@@ -1,62 +0,0 @@-# Phase 4 · 06 — KOL pre-seed + "claim this profile"--Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing-files, non-negotiable rules. This task assumes them.--## Goal--Solve cold-start on the *demand* side: pre-seed the leaderboard with real, well-known-on-chain traders (KOLs) rendered as **unclaimed** profiles built from their actual-trade history, each with a "claim this profile" flow. New visitors arrive to a board-full of recognizable, provable track records; the KOLs themselves have a reason to-show up and claim. Every number is real on-chain data — no invented stats, and never-any token other than `$THREE` referenced anywhere in copy.--## Build on (do not rebuild)--- `api/kol/[action].js` — Birdeye/GMGN proxy for on-chain histories.-- `api/kol/trades.js`, `src/kol/leaderboard.js`, `src/kol/wallet-pnl.js`,- `src/kol/wallets.js`, `src/kol/wallets.json` (the curated wallet set),- `src/kol/gmgn-parser.js`, `src/kol/kolscan-live.js`.-- `api/sniper/leaderboard.js` / `pages/leaderboard.html` — where unclaimed profiles- render alongside platform traders.-- The verification-badge logic (prompt 05) and the trader-stats truth layer.--## Deliver--1. **Pre-seed pipeline.** Import real on-chain histories for the curated wallet set- (`src/kol/wallets.json`) into trader profiles flagged `unclaimed`, with stats- computed by the **same truth layer** as platform traders so an unclaimed KOL and a- real agent are ranked apples-to-apples. Cache/refresh on a schedule (reuse the- cron pattern); respect provider rate limits with backoff — no errors without- fallbacks.-2. **Unclaimed profile rendering.** Unclaimed profiles appear on the leaderboard and- have their own profile view clearly marked "Unclaimed — real on-chain history" with- a prominent "Is this you? Claim this profile" CTA. They are watch-only (no copy- button until claimed, or copy points at the read-only history — your call, but- designed and explained).-3. **Claim flow.** A real claim path: the wallet owner proves control (sign a message- with the wallet, the standard Solana ownership proof) → the profile is bound to- their account, badge re-evaluated, copy/vault features unlocked. Reject claims that- fail the signature check. One claim per wallet; no claim-jacking.-4. **States & integrity.** Designed loading/empty/error for the import; a profile that- fails to import data is hidden, not shown broken. Make clear these are real public- histories, not endorsements.--## Acceptance--- Curated KOL wallets render as unclaimed profiles with real, truth-layer-consistent- stats; ranking is comparable to platform traders.-- The claim flow verifies wallet ownership via signature and binds the profile;- forged/failed signatures are rejected (test covers verify + reject + single-claim).-- No token other than `$THREE` is named in any KOL profile/copy; wallet addresses are- rendered as data, never marketed.-- Provider failures degrade gracefully (cached/last-known or hidden), never a broken- card or 500.-- `npm test` + `npm run typecheck` green. `data/changelog.json` entry (`feature`);- `npm run build:pages` run.--## When done--Run the `/CLAUDE.md` self-review protocol, then delete **only this file**-(`06-kol-claim-flow.md`).diff --git a/prompts/phase-4-virality/07-telegram-x-bots.md b/prompts/phase-4-virality/07-telegram-x-bots.mddeleted file mode 100644index c6a7cafd8..000000000--- a/prompts/phase-4-virality/07-telegram-x-bots.md+++ /dev/null@@ -1,58 +0,0 @@-# Phase 4 · 07 — Telegram / X distribution bots--Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing-files, non-negotiable rules. This task assumes them.--## Goal--Push wins off-platform to where the audience already is. A Telegram channel (and an X-poster) that broadcasts notable, provable events — big closes, new graduations,-leaderboard moves, weekly Wrapped highlights — each as a PnL card (prompt 01) with a-referral-tagged link back (prompt 03). Distribution, not spam: only verified,-genuinely notable events, rate-limited, with clear unsubscribe/opt-in semantics.--## Build on (do not rebuild)--- `src/pump/telegram-delivery.js`, `api/pump/deliver-telegram.js`,- `scripts/changelog-telegram.mjs` — existing Telegram delivery + the bot token- convention (`TELEGRAM_BOT_TOKEN`, channel/chat id env vars). Reuse, don't reinvent.-- Migrations `*_sniper_telegram_notify.sql`, `*_copy_telegram.sql` — existing- Telegram link state.-- Share-card endpoints (prompt 01), referral links (prompt 03), the verification- badge (prompt 05 — only broadcast verified traders), `api/cron/rewards-distribute.js`- cron pattern.--## Deliver--1. **Event selection.** A defensible "is this notable?" filter from real data: e.g.- realized PnL above a threshold, ROI above X%, a graduation, a top-N leaderboard- entry, or a Wrapped highlight — and **only from verified traders** (prompt 05).- No threshold-gaming: dedupe per trade/event, cap posts per trader per window.-2. **Telegram broadcaster.** A scheduled job (cron, idempotent like- `rewards-distribute.js`) or hook off the close path that posts the card image +- caption + referral link to the channel via the existing delivery module. One post- per event (idempotency key), structured logging, graceful skip if creds absent- locally (mirror the changelog-telegram `--dry-run` convention).-3. **X poster (real or cleanly gated).** If X/Twitter API creds are configured, post- the same card + link. If creds are absent, the path is a no-op that logs why —- never a fake "posted" success and never a hardcoded credential. Document the env- vars needed.-4. **Controls.** Per-trader opt-out (don't broadcast me), global kill switch via env,- and rate limits enforced server-side. All copy plain-language; `$THREE` only.--## Acceptance--- Only verified, genuinely-notable, deduped events are broadcast; per-trader and- global caps enforced (test covers selection + dedup + opt-out).-- Telegram posts carry the real PnL card + a `?ref=` link; re-running the job never- double-posts (idempotency).-- Missing Telegram/X creds → clean dry-run/no-op with a log line, not a crash or a- fake success. No credentials committed.-- No token other than `$THREE` appears in any post.-- `npm test` + `npm run typecheck` green. `data/changelog.json` entry- (`feature`/`infra`); `npm run build:pages` run. New cron (if any) in `vercel.json`.--## When done--Run the `/CLAUDE.md` self-review protocol, then delete **only this file**-(`07-telegram-x-bots.md`).diff --git a/prompts/phase-4-virality/08-integration-qa-and-polish.md b/prompts/phase-4-virality/08-integration-qa-and-polish.mddeleted file mode 100644index c3bdd8c58..000000000--- a/prompts/phase-4-virality/08-integration-qa-and-polish.md+++ /dev/null@@ -1,62 +0,0 @@-# Phase 4 · 08 — Integration QA & polish (run last)--Read `00-README.md` in this folder and `/CLAUDE.md` first. **Run this only after-prompts 01–07 have merged.** This is the pass that proves Phase 4 is a coherent loop,-not seven features in a trench coat.--## Goal--Walk the entire virality loop end-to-end as a real user would, find every seam, and-fix it. The loop must close: a win → a shared card → a referral landing → a new-copier → the new copier's win. If any link in that chain is broken, jank, or-unverifiable, fix it here.--## Walk the loop (exercise in a real browser, mobile + desktop)--1. **Win → card.** Close a real (devnet/paper) trade; confirm it produces a PnL card- (prompt 01) with real, truth-layer-consistent numbers and a verified badge- (prompt 05) if eligible.-2. **Card → share.** Share it: native sheet on mobile, copy + X/Telegram intents on- desktop. Paste the link into a link-preview validator — the OG card renders with- real numbers and the `?ref=` code is present (prompt 03).-3. **Share → landing → signup.** Follow the link logged out; confirm referral capture- survives navigation and binds at signup; verify no self-referral / double-credit.-4. **Feed.** Confirm the new follow shows up in the feed (prompt 02) with live/poll- updates and honest recommendations from real copy data; empty/loading/error states- all correct.-5. **Copy → activation → reward.** First copy/vault deposit fires activation and- credits the referrer exactly once (prompt 03), with the activation notification.-6. **Recap & broadcast.** Trigger the Wrapped cron (prompt 04) and the Telegram/X- broadcaster (prompt 07) in dry-run; confirm idempotency, opt-out, dedup, and that- only verified/notable events go out — `$THREE` only, everywhere.--## Fix & polish--- **No console errors or warnings** from Phase 4 code on any touched page.-- **Consistency:** badge, card, and CTA styling identical across profile, leaderboard,- feed, vaults, share routes. One component each, not copies.-- **Every state designed** on every new/changed surface (loading/empty/error/overflow),- mobile-first, hover/active/focus on all interactive elements, keyboard + ARIA.-- **Coin compliance sweep:** grep the Phase 4 diff for any token reference other than- `$THREE` (code, copy, cards, bot captions, fixtures) — remove any found.-- **Cross-links:** profile ↔ feed ↔ leaderboard ↔ vaults ↔ share routes all navigate- naturally; no dead paths, no `?ref=undefined`, no broken OG images.-- **Truth audit:** spot-check that every user-facing number traces to the shared- trader-stats truth layer / attested rows — no display-only recomputation that can- drift.--## Acceptance--- The full loop completes in one session on a fresh account, mobile and desktop.-- `npm test` (vitest + playwright) and `npm run typecheck` green; `npm run lint` clean- on touched files.-- No console errors/warnings; network tab shows real API calls with real data.-- No token other than `$THREE` anywhere in the Phase 4 surface.-- `data/changelog.json` reflects all user-visible Phase 4 changes; `npm run build:pages`- run and passing. (Optionally run the `completionist` subagent over the Phase 4 diff.)--## When done--Run the `/CLAUDE.md` self-review protocol, then delete **only this file**-(`08-integration-qa-and-polish.md`). Once 01–08 are deleted, only `00-README.md`-remains — Phase 4 is shipped.diff --git a/src/solana/vanity/pool-protocol.js b/src/solana/vanity/pool-protocol.jsnew file mode 100644index 000000000..2f572f238--- /dev/null+++ b/src/solana/vanity/pool-protocol.js@@ -0,0 +1,278 @@+/**+ * Grind-to-earn pool protocol — `three-grind-pool/v1`.+ *+ * The pure, isomorphic rules of the decentralized grinding pool: how the offset+ * keyspace is sharded across workers, how a worker proves real contributed work+ * (proof-of-contribution shares), and how a bounty's escrow is split fairly among+ * the winner and every honest contributor. The server (claim/settlement handler),+ * the Colyseus coordination room, the browser/agent workers, and the tests all+ * import this one module so there is a single verified implementation of every+ * economic and anti-cheat rule.+ *+ * ── Sharding (no duplicated effort, resumable) ────────────────────────────────+ * For split-key grinding the keyspace is the space of offset scalars a2. A worker+ * is handed a distinct base offset derived deterministically from+ * (bountyId, workerId, shardIndex); it then walks a2, a2+1, a2+2, … by single+ * point additions. Two random 256-bit base offsets cannot collide within any+ * feasible attempt budget, so workers never grind the same region. Determinism+ * lets the room reassign a shard after a disconnect and lets a worker resume+ * exactly where a fresh shard begins.+ *+ * ── Proof-of-contribution shares (anti-freeloader, anti-sybil) ────────────────+ * You cannot trust a worker's self-reported attempt count. Like a mining pool, a+ * worker proves work by submitting *shares*: offsets whose derived address clears+ * an easy target — `leadingZeroBits(sha256(address)) >= shareBits`. Each share is+ * a verifiable proof that the worker evaluated ~2^shareBits candidates *against+ * this bounty's P1* (a share is bound to P1, so it can't be precomputed or reused+ * on another bounty). The server verifies a share with one secret-free point check+ * plus a hash, then credits the worker proportionally. Splitting into many sybil+ * identities yields the same total shares as one identity — payout tracks real+ * work, not identity count — so sybils gain nothing.+ *+ * ── Fair, conservative payout split ───────────────────────────────────────────+ * On a verified win the escrow is divided: a transparent platform fee, a winner+ * bonus to the finder (who did the decisive work and bore the submit), and the+ * remainder distributed pro-rata across ALL share-holders. Refund-on-expiry returns+ * the full escrow to the requester (the platform fee is only ever taken on success).+ * All arithmetic is integer atomics and provably conserves the escrow to the last+ * unit (rounding dust is assigned to the winner), pinned by tests.+ *+ * Pure + isomorphic: @noble hashing + the split-key primitives only.+ */++import { sha256 } from '@noble/hashes/sha256.js';+import { hmac } from '@noble/hashes/hmac.js';+import { bytesToHex, utf8ToBytes, concatBytes } from '@noble/hashes/utils.js';+import bs58 from 'bs58';++import { scalarToBytes, bytesToScalar, verifySplitKeyClaim } from './split-key.js';+import { expectedAttempts } from './validation.js';++export const POOL_PROTOCOL = 'three-grind-pool/v1';++// USDC / $THREE atomic units (both 6 decimals on the platform).+export const ATOMICS = 1_000_000;++/**+ * Economic constants — published, bounded, and shown in the UI so the market is+ * transparent. The fee funds the platform + payout gas; the winner bonus rewards+ * the decisive find; the rest flows to contributors by share.+ */+export const ECONOMICS = Object.freeze({+ platformFeeBps: 500, // 5.0% platform fee, taken on success only+ winnerBonusBps: 6000, // 60% of the post-fee pool to the finder+ minShareBits: 8, // a share is never easier than 1-in-256+ maxShareBits: 24, // nor harder than 1-in-16.7M (keeps share cadence sane)+ // Target number of shares a full expected grind should yield, used to pick the+ // per-bounty share difficulty so contribution accounting has useful resolution+ // without flooding the server with share submissions.+ targetSharesPerGrind: 256,+ feeBps: 500,+});++const TAG_SHARD = utf8ToBytes('three-grind-pool/shard/v1');++// ── share difficulty ──────────────────────────────────────────────────────────++/**+ * Choose the share difficulty (in leading-zero bits of sha256(address)) for a+ * bounty, so a full expected grind yields ~targetSharesPerGrind shares — enough+ * resolution to apportion fairly, few enough to not flood the network. Clamped to+ * [minShareBits, maxShareBits].+ * @param {{prefix?:string,suffix?:string,ignoreCase?:boolean}} pattern+ * @returns {number} shareBits+ */+export function shareDifficultyBits(pattern) {+ const attempts = Math.max(1, expectedAttempts(pattern?.prefix || '', pattern?.suffix || '', !!pattern?.ignoreCase));+ // shares ≈ attempts / 2^bits ⇒ bits = log2(attempts / targetShares)+ const raw = Math.floor(Math.log2(attempts / ECONOMICS.targetSharesPerGrind));+ return Math.max(ECONOMICS.minShareBits, Math.min(ECONOMICS.maxShareBits, Number.isFinite(raw) ? raw : ECONOMICS.minShareBits));+}++/** Count leading zero bits of a byte array. */+export function leadingZeroBits(bytes) {+ let bits = 0;+ for (let i = 0; i < bytes.length; i++) {+ const b = bytes[i];+ if (b === 0) {+ bits += 8;+ continue;+ }+ bits += Math.clz32(b) - 24; // clz32 of a byte counts from a 32-bit word+ break;+ }+ return bits;+}++/** Does an address clear the share target? (sha256(address) has ≥ shareBits leading zeros) */+export function meetsShareTarget(address, shareBits) {+ const h = sha256(utf8ToBytes(String(address || '')));+ return leadingZeroBits(h) >= shareBits;+}++/**+ * Verify a submitted share with NO secret: the offset must derive the claimed+ * address from P1 (anti-cheat, same point check as a win) and the address must+ * clear the share target. A valid share proves ~2^shareBits real attempts on this+ * bounty's P1.+ * @param {object} p+ * @param {string} p.p1+ * @param {Uint8Array|string} p.offset+ * @param {string} p.address+ * @param {number} p.shareBits+ * @returns {{ ok:boolean, reason:string }}+ */+export function verifyShare({ p1, offset, address, shareBits }) {+ const d = verifySplitKeyClaim({ p1, offset, address });+ if (!d.derivationOk) return { ok: false, reason: d.reason || 'offset does not derive the claimed address' };+ if (!meetsShareTarget(address, shareBits)) return { ok: false, reason: `address does not clear the share target (${shareBits} bits)` };+ return { ok: true, reason: '' };+}++/** Weight (expected attempts) one share represents at a given difficulty. */+export function shareWeight(shareBits) {+ return Math.pow(2, shareBits);+}++// ── sharding ────────────────────────────────────────────────────────────────++/**+ * Deterministic, collision-free base offset scalar for a worker's shard. Derived+ * via HMAC-SHA256 keyed on the bounty id so shards differ across bounties; the+ * worker increments from here. Returns LE 32-byte scalar hex (the `startOffset`+ * grindSplitKeyOffset accepts).+ * @param {string} bountyId+ * @param {string} workerId+ * @param {number} shardIndex+ * @returns {string} hex offset scalar+ */+export function deriveShardOffset(bountyId, workerId, shardIndex = 0) {+ const msg = concatBytes(+ TAG_SHARD,+ utf8ToBytes(`${bountyId}|${workerId}|${shardIndex >>> 0}`),+ );+ const digest = hmac(sha256, utf8ToBytes(String(bountyId || 'pool')), msg);+ // Reduce into a scalar; the LE bytes are the worker's base offset.+ return bytesToHex(scalarToBytes(bytesToScalar(digest)));+}++// ── payout math ────────────────────────────────────────────────────────────++function toBig(n) {+ if (typeof n === 'bigint') return n;+ return BigInt(String(n).split('.')[0] || '0');+}++/**+ * Split a bounty's escrow on a verified win. Conserves the escrow exactly:+ * reward = fee + winnerBonus + Σ contributor distributions (+ dust → winner)+ *+ * @param {object} p+ * @param {bigint|number|string} p.rewardAtomics total escrowed reward+ * @param {string} p.winnerId worker id credited with the find+ * @param {Array<{workerId:string, shares:number|bigint}>} [p.contributions] validated shares per worker+ * @param {number} [p.feeBps=ECONOMICS.platformFeeBps]+ * @param {number} [p.winnerBonusBps=ECONOMICS.winnerBonusBps]+ * @returns {{ feeAtomics:bigint, winnerId:string, winnerAtomics:bigint,+ * distributions:Array<{workerId:string, atomics:bigint, shares:bigint}>, totalPaid:bigint }}+ */+export function computePayouts({+ rewardAtomics,+ winnerId,+ contributions = [],+ feeBps = ECONOMICS.platformFeeBps,+ winnerBonusBps = ECONOMICS.winnerBonusBps,+}) {+ const reward = toBig(rewardAtomics);+ if (reward <= 0n) throw new Error('computePayouts: rewardAtomics must be > 0');+ if (!winnerId) throw new Error('computePayouts: winnerId required');++ const fee = (reward * BigInt(feeBps)) / 10_000n;+ const net = reward - fee;+ const winnerBonus = (net * BigInt(winnerBonusBps)) / 10_000n;+ const sharePool = net - winnerBonus;++ // Aggregate shares per worker (a worker may appear once; sum defensively).+ const byWorker = new Map();+ let totalShares = 0n;+ for (const c of contributions) {+ const s = toBig(c.shares);+ if (s <= 0n) continue;+ byWorker.set(c.workerId, (byWorker.get(c.workerId) || 0n) + s);+ totalShares += s;+ }++ const distributions = [];+ let distributed = 0n;+ if (totalShares > 0n && sharePool > 0n) {+ for (const [workerId, shares] of byWorker) {+ const atomics = (sharePool * shares) / totalShares; // floor+ if (atomics > 0n) {+ distributions.push({ workerId, atomics, shares });+ distributed += atomics;+ } else {+ distributions.push({ workerId, atomics: 0n, shares });+ }+ }+ }++ // Winner gets the bonus + any undistributed remainder (dust + the whole pool+ // when there were no shares at all). This conserves the escrow to the last unit.+ const winnerAtomics = winnerBonus + (sharePool - distributed);+ const totalPaid = fee + winnerAtomics + distributed;+ if (totalPaid !== reward) {+ throw new Error(`computePayouts: conservation violated (${totalPaid} ≠ ${reward})`);+ }+ return { feeAtomics: fee, winnerId, winnerAtomics, distributions, totalPaid };+}++/**+ * Honest difficulty → suggested reward, anchored to expected compute. Returns USDC+ * atomic units. Mirrors the bounty-protocol oracle's intent but lives here so the+ * pool board, post form, and worker estimates share one source.+ * @param {{prefix?:string,suffix?:string,ignoreCase?:boolean}} pattern+ * @returns {{ expectedAttempts:number, floorAtomics:number, suggestedAtomics:number, generousAtomics:number, expectedGrindSeconds:number }}+ */+export function suggestRewardAtomics(pattern) {+ const attempts = expectedAttempts(pattern?.prefix || '', pattern?.suffix || '', !!pattern?.ignoreCase);+ const refRatePerSec = 1_500_000; // reference fleet throughput (intuition only)+ const usdcPerGrindHour = 1 * ATOMICS;+ const floorAtomics = 50_000; // $0.05+ const maxAtomics = 5_000 * ATOMICS;+ const grindSeconds = attempts / refRatePerSec;+ const fair = (grindSeconds / 3600) * usdcPerGrindHour;+ const suggested = Math.max(floorAtomics, Math.min(maxAtomics, Math.round(fair)));+ return {+ expectedAttempts: Math.round(attempts),+ floorAtomics,+ suggestedAtomics: suggested,+ generousAtomics: Math.min(maxAtomics, Math.round(suggested * 2.5)),+ expectedGrindSeconds: Math.round(grindSeconds),+ };+}++/** Validate a reward amount is in the legal band; throws 400-tagged otherwise. */+export function validateRewardAtomics(atomics) {+ const v = Math.round(Number(atomics));+ const floor = 50_000;+ const max = 5_000 * ATOMICS;+ if (!Number.isFinite(v) || v < floor) {+ throw Object.assign(new Error(`reward must be at least ${floor} atomic units ($${(floor / ATOMICS).toFixed(2)})`), { status: 400, code: 'amount_too_low' });+ }+ if (v > max) {+ throw Object.assign(new Error(`reward exceeds the ${max}-atomic ceiling`), { status: 400, code: 'amount_too_high' });+ }+ return v;+}++/** Base58 sanity for an address (used at API boundaries). */+export function isBase58Address(s) {+ return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(String(s || ''));+}++/** Stable hex id for a contribution share (idempotency anchor). */+export function shareId({ bountyId, address }) {+ return bytesToHex(sha256(utf8ToBytes(`${bountyId}|${address}`))).slice(0, 32);+}++export { bs58 };