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
feat(copy): let leaders drip their signal by tier and copiers cap their drawdown
nirholasd09dfefd69fe
diff --git a/api/_lib/alpha-drip-stats.js b/api/_lib/alpha-drip-stats.jsnew file mode 100644index 000000000..f1fc23a4b--- /dev/null+++ b/api/_lib/alpha-drip-stats.js@@ -0,0 +1,55 @@+/**+ * How fast a leader's edge actually decays — measured, not assumed.+ *+ * Alpha-drip prices latency, so the only honest way to judge a ladder is against+ * how long this leader's entry advantage survives in their own history. The+ * proxy is the MEDIAN hold time of their profitable closed positions: the window+ * in which following them was still worth something. A ladder whose slowest tier+ * waits longer than that is selling a signal that is already spent, which is+ * exactly what `assessFairness` refuses to ship quietly.+ *+ * Median, not mean, because one position held overnight would otherwise justify+ * a delay nobody should be sold. Returns null rather than a guess when the+ * leader has too few profitable closes to measure — every caller treats a null+ * half-life as "cannot judge" and says nothing instead of inventing a number.+ */++import { sql } from './db.js';++/** Below this many profitable closes the median is noise, not a measurement. */+export const MIN_CLOSES_FOR_HALFLIFE = 5;++/**+ * @param {string} leaderAgentId agent_identities.id+ * @param {object} [opts] { network }+ * @returns {Promise<number|null>} seconds, or null when unmeasurable+ */+export async function leaderEdgeHalflifeSec(leaderAgentId, { network = 'mainnet' } = {}) {+ if (!leaderAgentId) return null;+ try {+ const rows = await sql`+ select extract(epoch from (closed_at - opened_at)) as hold_sec+ from agent_sniper_positions+ where agent_id = ${leaderAgentId}+ and network = ${network}+ and status = 'closed'+ and closed_at is not null+ and closed_at > opened_at+ and realized_pnl_lamports is not null+ and realized_pnl_lamports > 0+ order by closed_at desc+ limit 200+ `;+ const holds = rows.map((r) => Number(r.hold_sec)).filter((s) => Number.isFinite(s) && s > 0).sort((a, b) => a - b);+ if (holds.length < MIN_CLOSES_FOR_HALFLIFE) return null;+ return median(holds);+ } catch {+ // A stats read must never block a leader from saving their ladder.+ return null;+ }+}++function median(sorted) {+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+}diff --git a/api/_lib/alpha-drip.js b/api/_lib/alpha-drip.jsnew file mode 100644index 000000000..dfb3c5b88--- /dev/null+++ b/api/_lib/alpha-drip.js@@ -0,0 +1,288 @@+/**+ * Alpha-drip — tiered release of a leader's OWN copy signal. PURE: no DB, no network.+ *+ * A leader's edge decays in seconds, so the thing worth selling is not only a+ * share of the profit but the LATENCY: $THREE holders in higher tiers see the+ * copy intent first, everyone else after a leader-set delay. That is a real+ * reason to hold $THREE and a real product the leader can sell, and unlike a+ * private signal group it is enforced by the fanout instead of by trust.+ *+ * Two rules are structural, not stylistic, and every caller depends on them:+ *+ * 1. A drip delays the REVEAL, never the RECORD. The intent row is written in+ * full at fanout time and the leader's public track record is untouched, so+ * there are no hidden trades — only delayed ones. Nothing here can express+ * "do not disclose".+ * 2. Delay never increases with tier. A higher-tier holder can never wait longer+ * than a lower-tier one, so paying more can only ever help.+ *+ * The leader gates their OWN self-produced signal. Nothing here touches, delays,+ * or reorders anybody else's orderflow, and `dripDisclosure()` states that in+ * plain English on every subscribing surface.+ */++import { TIERS, tierForUsd } from './three-tier.js';++/** Hard ceiling on any delay a leader can set, public tier included. */+export const MAX_DELAY_SEC = 900;++/** Ordered low→high tier ids, the vocabulary a schedule may use. */+export const TIER_IDS = Object.freeze(TIERS.map((t) => t.id));++const LEVEL_BY_ID = new Map(TIERS.map((t) => [t.id, t.level]));+const TIER_BY_ID = new Map(TIERS.map((t) => [t.id, t]));++const int = (v) => (Number.isFinite(Number(v)) ? Math.round(Number(v)) : NaN);+const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : NaN);++/**+ * Validate + normalize a leader's release schedule.+ *+ * Accepts a sparse array — a leader prices the tiers they care about and the rest+ * inherit. The result is sorted high→low tier level so `planRelease` can walk it+ * once, and is guaranteed monotonic (rule 2 above).+ *+ * @param {object} raw { enabled, schedule: [{tier, delay_sec, max_copy_size_sol}], public_delay_sec, disclosure, capacity_note }+ * @returns {{ ok: true, value: object } | { ok: false, error: string }}+ */+export function normalizeDripConfig(raw = {}) {+ const publicDelay = raw.public_delay_sec == null || raw.public_delay_sec === '' ? 0 : int(raw.public_delay_sec);+ if (!Number.isFinite(publicDelay) || publicDelay < 0) return { ok: false, error: 'public_delay_sec must be zero or more seconds' };+ if (publicDelay > MAX_DELAY_SEC) return { ok: false, error: `public_delay_sec cannot exceed ${MAX_DELAY_SEC} seconds` };++ const rows = Array.isArray(raw.schedule) ? raw.schedule : [];+ if (rows.length > TIER_IDS.length) return { ok: false, error: 'schedule has more entries than there are tiers' };++ const seen = new Set();+ const entries = [];+ for (const row of rows) {+ const tier = typeof row?.tier === 'string' ? row.tier.trim().toLowerCase() : '';+ if (!LEVEL_BY_ID.has(tier)) return { ok: false, error: `unknown tier "${row?.tier}" (expected one of ${TIER_IDS.join(', ')})` };+ if (seen.has(tier)) return { ok: false, error: `tier "${tier}" appears more than once` };+ seen.add(tier);++ const delay = row.delay_sec == null || row.delay_sec === '' ? 0 : int(row.delay_sec);+ if (!Number.isFinite(delay) || delay < 0) return { ok: false, error: `delay_sec for "${tier}" must be zero or more seconds` };+ if (delay > MAX_DELAY_SEC) return { ok: false, error: `delay_sec for "${tier}" cannot exceed ${MAX_DELAY_SEC} seconds` };++ let cap = null;+ if (row.max_copy_size_sol != null && row.max_copy_size_sol !== '') {+ cap = num(row.max_copy_size_sol);+ if (!Number.isFinite(cap) || cap <= 0) return { ok: false, error: `max_copy_size_sol for "${tier}" must be greater than 0` };+ cap = Math.round(cap * 1e6) / 1e6;+ }+ entries.push({ tier, delay_sec: delay, max_copy_size_sol: cap });+ }++ // High tier first — the order planRelease walks and the order a UI reads best.+ entries.sort((a, b) => LEVEL_BY_ID.get(b.tier) - LEVEL_BY_ID.get(a.tier));++ // Rule 2: paying more can never buy a longer wait. Checked against the public+ // delay too, since everything below the lowest priced tier falls through to it.+ let prev = 0;+ for (const e of entries) {+ if (e.delay_sec < prev) {+ return { ok: false, error: `delay for "${e.tier}" is shorter than a higher tier's — a higher tier can never wait longer` };+ }+ prev = e.delay_sec;+ }+ if (entries.length && publicDelay < prev) {+ return { ok: false, error: 'public_delay_sec cannot be shorter than a paid tier\'s delay' };+ }++ const enabled = raw.enabled === true || raw.enabled === 'true';+ if (enabled && !entries.length && publicDelay === 0) {+ return { ok: false, error: 'enable a drip only with at least one tier delay or a public delay set' };+ }++ const text = (v, max) => {+ const s = v == null ? '' : String(v).trim();+ return s ? s.slice(0, max) : null;+ };++ return {+ ok: true,+ value: {+ enabled,+ schedule: entries,+ public_delay_sec: publicDelay,+ disclosure: text(raw.disclosure, 280),+ capacity_note: text(raw.capacity_note, 280),+ },+ };+}++/**+ * Resolve one copier's release for a leader's signal.+ *+ * A tier with no explicit entry inherits the nearest LOWER priced tier (holding+ * more is never worse), and anything under the lowest priced tier waits the+ * public delay.+ *+ * @param {object} config normalized config from `normalizeDripConfig` (or null/disabled)+ * @param {string} tierId the copier's current $THREE tier id+ * @returns {{ delay_sec:number, tier:string, matched_tier:string|null, max_copy_size_sol:number|null }}+ */+export function planRelease(config, tierId) {+ const tier = LEVEL_BY_ID.has(tierId) ? tierId : TIER_IDS[0];+ if (!config?.enabled) return { delay_sec: 0, tier, matched_tier: null, max_copy_size_sol: null };++ const level = LEVEL_BY_ID.get(tier);+ const entries = Array.isArray(config.schedule) ? config.schedule : [];+ // Entries are high→low, so the first one at or below the copier's level is the+ // best price they qualify for.+ const match = entries.find((e) => LEVEL_BY_ID.get(e.tier) <= level);++ if (!match) {+ const publicDelay = Math.min(Math.max(int(config.public_delay_sec) || 0, 0), MAX_DELAY_SEC);+ return { delay_sec: publicDelay, tier, matched_tier: null, max_copy_size_sol: null };+ }+ return {+ delay_sec: Math.min(Math.max(match.delay_sec, 0), MAX_DELAY_SEC),+ tier,+ matched_tier: match.tier,+ max_copy_size_sol: match.max_copy_size_sol ?? null,+ };+}++/** Convenience: resolve a release straight from the USD value of $THREE held. */+export function planReleaseForUsd(config, usdHeld) {+ return planRelease(config, tierForUsd(usdHeld).id);+}++/**+ * The disclosure shown to every copier before they subscribe. A leader may+ * override the wording, but never the standing sentence that says what a drip is+ * and what it is not — that is appended regardless.+ */+export function dripDisclosure(config) {+ const standing =+ 'This is the leader gating their own call as a subscription. It is not privileged access to anyone else\'s orderflow, and every trade still lands in the leader\'s public track record.';+ if (!config?.enabled) return null;+ const custom = config.disclosure ? `${config.disclosure} ` : '';+ return `${custom}${standing}`;+}++/**+ * Human summary of a schedule, longest wait last: "Gold+ instant, Bronze+ after+ * 20s, everyone else after 60s."+ */+export function describeSchedule(config) {+ if (!config?.enabled) return 'Every copier gets this leader\'s signal at the same moment.';+ const parts = [];+ for (const e of config.schedule) {+ const label = TIER_BY_ID.get(e.tier)?.label || e.tier;+ parts.push(`${label}+ ${e.delay_sec === 0 ? 'instant' : `after ${formatDelay(e.delay_sec)}`}`);+ }+ const pub = Math.max(int(config.public_delay_sec) || 0, 0);+ parts.push(`everyone else ${pub === 0 ? 'instant' : `after ${formatDelay(pub)}`}`);+ return `${parts.join(', ')}.`;+}++/** "45s" / "2m 30s" — the one format every drip surface prints. */+export function formatDelay(sec) {+ const s = Math.max(0, int(sec) || 0);+ if (s < 60) return `${s}s`;+ const m = Math.floor(s / 60);+ const r = s % 60;+ return r ? `${m}m ${r}s` : `${m}m`;+}++/**+ * Fairness check against how fast the leader's edge actually decays. When the+ * longest wait outruns the edge's half-life, the slowest tier is being sold a+ * signal that is already spent — say so instead of shipping it quietly.+ *+ * @returns {{ fair: boolean, longest_delay_sec: number, warning: string|null }}+ */+export function assessFairness(config, edgeHalflifeSec) {+ const longest = maxDelaySec(config);+ const half = num(edgeHalflifeSec);+ if (!config?.enabled || longest === 0) return { fair: true, longest_delay_sec: longest, warning: null };+ if (!Number.isFinite(half) || half <= 0) return { fair: true, longest_delay_sec: longest, warning: null };+ if (longest <= half) return { fair: true, longest_delay_sec: longest, warning: null };+ return {+ fair: false,+ longest_delay_sec: longest,+ warning: `The slowest tier waits ${formatDelay(longest)} but this leader's edge halves in about ${formatDelay(Math.round(half))}. Shorten the delay or release to everyone at once.`,+ };+}++/** The longest any copier waits under this config. */+export function maxDelaySec(config) {+ if (!config?.enabled) return 0;+ const delays = (config.schedule || []).map((e) => e.delay_sec || 0);+ delays.push(int(config.public_delay_sec) || 0);+ return Math.max(0, ...delays);+}++/**+ * Clamp a sized copy order to the tier's capacity allowance.+ *+ * A leader with real size has finite capacity: if the earliest tier copies the+ * full order, the fills the later tiers get are the ones the early tier already+ * moved through. `max_copy_size_sol` is how a leader splits that, so it is+ * applied AFTER the copy engine has sized and gated the order, never before —+ * the copier's own caps still bind first.+ *+ * A cap that pushes an order under the copier's minimum is a skip, not a dust+ * fill: the copier said what is too small to be worth signing.+ *+ * @returns {{ ok: true, order_sol: number, capped: boolean }+ * | { ok: false, reason: 'drip_capacity_cap', detail: string }}+ */+export function applyCapacityCap(orderSol, capSol, minOrderSol = 0) {+ const order = num(orderSol);+ if (!Number.isFinite(order) || order <= 0) return { ok: true, order_sol: orderSol, capped: false };+ const cap = num(capSol);+ if (!Number.isFinite(cap) || cap <= 0 || order <= cap) return { ok: true, order_sol: order, capped: false };++ const capped = Math.round(cap * 1e6) / 1e6;+ const min = num(minOrderSol);+ if (Number.isFinite(min) && min > 0 && capped < min) {+ return {+ ok: false,+ reason: 'drip_capacity_cap',+ detail: `This leader caps your tier at ${capped} SOL per copy, below your ${min} SOL minimum.`,+ };+ }+ return { ok: true, order_sol: capped, capped: true };+}++/**+ * Hide the tradeable content of an intent the copier's seat has not reached yet.+ *+ * The row exists, the copier knows WHO traded and that something fired — what+ * they do not get early is the coin and the size, which is the whole thing the+ * ladder sells. Masking happens on the way OUT rather than in the query so the+ * record stays complete in the database and the same row unmasks itself the+ * moment its reveal passes.+ *+ * Only a pending intent can be masked: once acted, dismissed, skipped, or+ * expired it is history, and history is never hidden from the person it+ * belongs to.+ */+export function maskUnreleasedIntent(row, now = Date.now()) {+ const visibleAt = row?.visible_at ? new Date(row.visible_at).getTime() : null;+ if (row?.status !== 'pending' || !visibleAt || visibleAt <= now) {+ return { ...row, locked: false, unlocks_in_sec: 0 };+ }+ const {+ mint, symbol, name, planned_sol, leader_entry_sol, safety, quote, leader_buy_sig,+ ...rest+ } = row;+ return {+ ...rest,+ mint: null, symbol: null, name: null,+ planned_sol: null, leader_entry_sol: null,+ safety: null, quote: null, leader_buy_sig: null,+ locked: true,+ unlocks_at: new Date(visibleAt).toISOString(),+ unlocks_in_sec: Math.max(0, Math.ceil((visibleAt - now) / 1000)),+ };+}++/** Config shape for a leader who has never set one up. */+export function emptyDripConfig() {+ return { enabled: false, schedule: [], public_delay_sec: 0, disclosure: null, capacity_note: null };+}diff --git a/api/_lib/copy-drip-runtime.js b/api/_lib/copy-drip-runtime.jsnew file mode 100644index 000000000..5b5cd3513--- /dev/null+++ b/api/_lib/copy-drip-runtime.js@@ -0,0 +1,173 @@+/**+ * Alpha-drip at fanout time — the DB-facing half of the tiered signal release.+ *+ * `api/_lib/alpha-drip.js` decides WHAT seat a copier gets (pure, exhaustively+ * tested). This module is what the copy-fanout cron actually calls: it loads the+ * leaders' ladders, prices each copier against their live $THREE balance, and+ * later releases the alerts it held back.+ *+ * Cost discipline: a leader with the drip off costs nothing here — no config+ * row, no balance read, no branch taken. Balance reads are memoized per wallet+ * for the length of one tick, because a copier following three leaders should+ * not be priced three times.+ *+ * The invariant this module exists to keep: an intent row is ALWAYS written in+ * full at fanout time. `visible_at` moves when the copier is shown it, never+ * whether it happened.+ */++import { sql } from './db.js';+import { holderUsd, tierForUsd } from './three-tier.js';+import {+ normalizeDripConfig, planRelease, applyCapacityCap, formatDelay, emptyDripConfig,+} from './alpha-drip.js';++/** How long a copier gets to act once an intent is revealed to them. */+const ACT_WINDOW_MS = 30 * 60 * 1000;++/**+ * Load the enabled ladders for a batch of leaders in one query.+ * @returns {Promise<Map<string, object>>} leader_agent_id → normalized config (enabled only)+ */+export async function loadDripConfigs(leaderIds) {+ const configs = new Map();+ if (!leaderIds?.length) return configs;+ const rows = await sql`+ select leader_agent_id, enabled, schedule, public_delay_sec, disclosure, capacity_note+ from copy_alpha_drip+ where leader_agent_id = any(${leaderIds}) and enabled+ `;+ for (const row of rows) {+ const norm = normalizeDripConfig(row);+ // A row that no longer satisfies the release rules (a tier renamed under it,+ // say) releases to everyone at once rather than silently delaying anybody.+ if (norm.ok && norm.value.enabled) configs.set(row.leader_agent_id, norm.value);+ }+ return configs;+}++/** Per-tick memo of wallet → $THREE tier id, so one copier is priced once. */+export function newTierCache() {+ return new Map();+}++async function tierFor(wallet, cache) {+ if (!wallet) return tierForUsd(0).id;+ if (cache.has(wallet)) return cache.get(wallet);+ const { usd } = await holderUsd(wallet);+ const id = tierForUsd(usd).id;+ cache.set(wallet, id);+ return id;+}++/**+ * Price one copier's seat for one leader's signal.+ *+ * Returns the columns the fanout insert needs plus the capacity verdict. A+ * leader with no ladder returns the no-drip shape, which is exactly what every+ * row looked like before alpha-drip existed.+ *+ * @param {object} p+ * @param {object} p.subscription copy_subscriptions row (needs copier_wallet, min_order_sol)+ * @param {object|null} p.config normalized ladder, or null when the leader has none+ * @param {number|null} p.plannedSol the order the copy engine already sized and gated+ * @param {Map} p.tierCache from `newTierCache()`+ */+export async function priceRelease({ subscription, config, plannedSol, tierCache }) {+ if (!config?.enabled) {+ return {+ delaySec: 0, tier: null, matchedTier: null,+ visibleAt: null, expiresAt: null, notifyNow: true,+ plannedSol, capacitySkip: null,+ };+ }++ const tierId = await tierFor(subscription.copier_wallet, tierCache);+ const release = planRelease(config, tierId);++ const capped = applyCapacityCap(plannedSol, release.max_copy_size_sol, Number(subscription.min_order_sol) || 0);+ if (!capped.ok) {+ // The cap made the order too small to be worth signing: record the skip with+ // its own reason instead of a dust intent the copier would dismiss anyway.+ return {+ delaySec: release.delay_sec, tier: release.tier, matchedTier: release.matched_tier,+ visibleAt: null, expiresAt: null, notifyNow: false,+ plannedSol: null, capacitySkip: capped,+ };+ }++ const now = Date.now();+ const delayMs = release.delay_sec * 1000;+ return {+ delaySec: release.delay_sec,+ tier: release.tier,+ matchedTier: release.matched_tier,+ // A zero-delay seat is written exactly like a no-drip row, so nothing+ // downstream has to special-case "delayed by nothing".+ visibleAt: release.delay_sec > 0 ? new Date(now + delayMs) : null,+ expiresAt: release.delay_sec > 0 ? new Date(now + delayMs + ACT_WINDOW_MS) : null,+ notifyNow: release.delay_sec === 0,+ plannedSol: capped.order_sol,+ capacitySkip: null,+ };+}++function releaseMessage({ sym, name, plannedSol, leaderName, mint, network, delaySec, tier }) {+ const coin = sym ? `$${sym}${name ? ` (${name})` : ''}` : mint?.slice(0, 8) || 'unknown';+ const net = network === 'devnet' ? ' [devnet]' : '';+ const seat = tier ? ` · ${tier} seat` : '';+ const lines = [+ `⏱ Signal released${net}`,+ `${coin}`,+ `Leader: ${leaderName || 'unknown'}${seat}`,+ `Held ${formatDelay(delaySec)} on this leader's release ladder.`,+ `Your order: ${plannedSol != null ? `${Number(plannedSol).toFixed(4)} SOL` : 'sized by your rules'}`,+ ``,+ `Act now → https://three.ws/dashboard/copy`,+ ];+ if (mint) lines.push(`pump.fun → https://pump.fun/${mint}`);+ return lines.join('\n');+}++/**+ * Send the alerts held back by a drip, for every pending intent whose reveal has+ * now passed. Runs at the top of each fanout tick, so the release cadence is the+ * fanout cadence and no second cron is needed.+ *+ * `notified_at` is stamped for every row it touches, chat id or not, so a+ * subscription with notifications off is scanned once and never again.+ *+ * @param {object} p+ * @param {(chatId: string, text: string) => any} p.sendTg+ * @param {object} p.stats mutated with a `drip_released` counter+ */+export async function releaseDueDrips({ sendTg, stats = {} }) {+ const due = await sql`+ select e.id, e.mint, e.symbol, e.name, e.planned_sol, e.network, e.drip_delay_sec, e.drip_tier,+ s.telegram_chat_id, a.name as leader_name+ from copy_executions e+ join copy_subscriptions s on s.id = e.subscription_id+ left join agent_identities a on a.id = e.leader_agent_id+ where e.status = 'pending'+ and e.notified_at is null+ and e.visible_at is not null+ and e.visible_at <= now()+ order by e.visible_at asc+ limit 500+ `;+ if (!due.length) return;++ for (const row of due) {+ if (row.telegram_chat_id) {+ sendTg(row.telegram_chat_id, releaseMessage({+ sym: row.symbol, name: row.name, plannedSol: row.planned_sol,+ leaderName: row.leader_name, mint: row.mint, network: row.network,+ delaySec: row.drip_delay_sec || 0, tier: row.drip_tier,+ }));+ }+ }+ await sql`update copy_executions set notified_at = now() where id = any(${due.map((r) => r.id)})`;+ stats.drip_released = (stats.drip_released || 0) + due.length;+}++export { emptyDripConfig };diff --git a/api/_lib/copy-eligibility.js b/api/_lib/copy-eligibility.jsnew file mode 100644index 000000000..c9a13c201--- /dev/null+++ b/api/_lib/copy-eligibility.js@@ -0,0 +1,232 @@+/**+ * Copy-trading anti-gaming layer — who may be copied, and when copying stops.+ *+ * Copy-trading dies the moment a track record can be faked or a follower can be+ * strapped to a runaway leader. Three defenses live here, all of them enforced+ * before money is committed and all of them derived from real, closed, on-chain+ * round-trips (agent_sniper_positions) — never from a self-reported number:+ *+ * 1. SELF-COPY (wash trading). A user subscribing to an agent they own pays a+ * performance fee to themselves, inflates that leader's public copier count,+ * and inflates the "earned X for being copied" social-proof figure. Blocked+ * at subscribe time and skipped again in the fanout, so a row that predates+ * this rule cannot keep firing.+ * 2. SYBIL BAR on copyable status. A brand-new agent with no history could be+ * followed the minute it was created. A leader now needs a real record —+ * closed round-trips, elapsed time, and capital actually deployed — before+ * anyone can attach money to it, so dust-trading a curve into existence+ * buys nothing.+ * 3. DRAWDOWN CIRCUIT BREAKER. A copier sets the peak-to-trough loss they are+ * willing to ride. When the leader's realized equity curve breaches it the+ * subscription auto-pauses with a recorded reason, instead of mirroring a+ * leader into the ground. The copier resumes it deliberately or not at all.+ *+ * Drawdown is expressed as a share of capital actually deployed+ * (max peak-to-trough loss / gross entry), the same definition+ * api/_lib/meta-allocator.js ranks on and api/_lib/mirror-stats.js reports, so+ * the number a copier sets a breaker against is the number on the Trader Card.+ */++import { sql } from './db.js';++const LAMPORTS = 1e9;+const lamToSol = (l) => (l == null ? 0 : Number(BigInt(Math.trunc(Number(l)))) / LAMPORTS);+const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);+const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));+const round2 = (x) => Math.round(x * 100) / 100;+const round4 = (x) => Math.round(x * 1e4) / 1e4;++/**+ * Machine reason recorded on copy_subscriptions.paused_reason when the drawdown+ * breaker trips. The resume path in api/copy/subscriptions.js keys off it to+ * refuse a resume that would just re-pause on the next tick.+ */+export const BREAKER_REASON = 'leader_drawdown_breach';++/**+ * The bar an agent must clear before a copier may attach money to it.+ *+ * Deliberately modest: this is a floor against a zero-history sybil, not a+ * curation filter. A real trader clears it inside a normal week of trading.+ * Every threshold is measured on CLOSED round-trips, so open positions and+ * paper mode contribute nothing.+ */+export const LEADER_ELIGIBILITY = {+ /** Closed round-trips (a buy AND its exit) on the network being copied. */+ minSettled: 5,+ /** Hours between the leader's first and most recent close. Blocks a burst of dust trades minted in one minute. */+ minSpanHours: 24,+ /** Gross SOL actually deployed across those closes. Blocks a curve built out of 0.0001 SOL trades. */+ minDeployedSol: 0.1,+};++/** Human labels for each unmet criterion, for the UI and the API error body. */+const CRITERION_LABELS = {+ settled: (need, have) => `${have} of ${need} closed round-trips`,+ span_hours: (need, have) => `${have}h of ${need}h of trading history`,+ deployed_sol: (need, have) => `${have} of ${need} SOL deployed`,+};++/**+ * Decide whether a leader's record clears the copyable bar. PURE.+ *+ * @param {object} record { settled, span_hours, deployed_sol } — real closed-trade stats.+ * @param {object} [bar] override thresholds (tests, future per-tier bars).+ * @returns {{ eligible:boolean, unmet:Array<{criterion:string,need:number,have:number,label:string}>, met:object }}+ */+export function evaluateLeaderEligibility(record = {}, bar = LEADER_ELIGIBILITY) {+ const have = {+ settled: Math.floor(n(record.settled)),+ span_hours: round2(n(record.span_hours)),+ deployed_sol: round4(n(record.deployed_sol)),+ };+ const need = {+ settled: bar.minSettled,+ span_hours: bar.minSpanHours,+ deployed_sol: bar.minDeployedSol,+ };++ const unmet = [];+ for (const criterion of ['settled', 'span_hours', 'deployed_sol']) {+ if (have[criterion] < need[criterion]) {+ unmet.push({+ criterion,+ need: need[criterion],+ have: have[criterion],+ label: CRITERION_LABELS[criterion](need[criterion], have[criterion]),+ });+ }+ }+ return { eligible: unmet.length === 0, unmet, met: have };+}++/**+ * Decide whether a leader's realized drawdown has breached a copier's tolerance. PURE.+ *+ * A null tolerance means the copier opted out of the breaker; a null drawdown+ * means the leader has no measurable curve yet (no deployed capital), and an+ * unmeasurable leader is never auto-paused — the eligibility bar is what keeps+ * a history-less leader from being copied in the first place.+ *+ * @returns {{ breached:boolean, drawdown_pct:number|null, limit_pct:number|null, detail?:string }}+ */+export function evaluateDrawdownBreaker(sub = {}, leaderDrawdownPct = null) {+ const limit = sub.max_drawdown_pct == null ? null : n(sub.max_drawdown_pct);+ if (limit == null || limit <= 0) return { breached: false, drawdown_pct: leaderDrawdownPct, limit_pct: null };+ if (leaderDrawdownPct == null) return { breached: false, drawdown_pct: null, limit_pct: limit };++ const dd = n(leaderDrawdownPct);+ if (dd < limit) return { breached: false, drawdown_pct: round2(dd), limit_pct: limit };+ return {+ breached: true,+ drawdown_pct: round2(dd),+ limit_pct: limit,+ detail: `Leader drawdown ${round2(dd)}% reached your ${limit}% limit — copying paused.`,+ };+}++/**+ * Real closed-trade profile for one leader on one network: the numbers both the+ * eligibility bar and the drawdown breaker are judged on.+ *+ * Returns zeros (never nulls dressed as numbers) for a leader with no closes, and+ * `max_drawdown_pct: null` when no capital was deployed, because a drawdown share+ * of zero deployed capital is undefined rather than 0%.+ */+export async function leaderCopyProfile(agentId, network = 'mainnet') {+ const rows = await sql`+ select realized_pnl_lamports, entry_quote_lamports, closed_at+ from agent_sniper_positions+ where agent_id = ${agentId} and network = ${network}+ and status = 'closed' and closed_at is not null+ order by closed_at asc+ `.catch(() => []);++ return summarizeCopyProfile(rows);+}++/**+ * Fold closed round-trips into the copy profile. PURE — exported so the equity+ * curve walk is testable without a database.+ *+ * @param {Array<{realized_pnl_lamports:*, entry_quote_lamports:*, closed_at:*}>} rows+ * closed round-trips, oldest first.+ */+export function summarizeCopyProfile(rows = []) {+ let equity = 0;+ let peak = 0;+ let maxDrawdownSol = 0;+ let deployedSol = 0;+ let first = null;+ let last = null;++ for (const r of rows) {+ deployedSol += lamToSol(r.entry_quote_lamports);+ equity += lamToSol(r.realized_pnl_lamports);+ if (equity > peak) peak = equity;+ const dd = peak - equity;+ if (dd > maxDrawdownSol) maxDrawdownSol = dd;++ const at = r.closed_at ? new Date(r.closed_at).getTime() : NaN;+ if (Number.isFinite(at)) {+ if (first == null || at < first) first = at;+ if (last == null || at > last) last = at;+ }+ }++ const spanHours = first != null && last != null ? (last - first) / 3_600_000 : 0;+ const maxDrawdownPct = deployedSol > 0 ? clamp((maxDrawdownSol / deployedSol) * 100, 0, 100) : null;++ return {+ settled: rows.length,+ deployed_sol: round4(deployedSol),+ span_hours: round2(spanHours),+ realized_pnl_sol: round4(equity),+ max_drawdown_sol: round4(maxDrawdownSol),+ max_drawdown_pct: maxDrawdownPct == null ? null : round2(maxDrawdownPct),+ first_closed_at: first == null ? null : new Date(first).toISOString(),+ last_closed_at: last == null ? null : new Date(last).toISOString(),+ };+}++/**+ * Batch the drawdown percentage for a set of leaders in one query — the fanout+ * cron checks every leader it is about to mirror, and a leader with a thousand+ * copiers must not cost a thousand round-trips.+ *+ * @returns {Promise<Map<string, number|null>>} agent id → drawdown %, or null when unmeasurable.+ */+export async function leaderDrawdownPcts(agentIds, network = 'mainnet') {+ const out = new Map();+ if (!Array.isArray(agentIds) || agentIds.length === 0) return out;++ const rows = await sql`+ with closed as (+ select agent_id, closed_at, entry_quote_lamports,+ sum(realized_pnl_lamports) over (+ partition by agent_id order by closed_at+ rows between unbounded preceding and current row) as cum_pnl+ from agent_sniper_positions+ where agent_id = any(${agentIds}) and network = ${network}+ and status = 'closed' and closed_at is not null+ ),+ curve as (+ select agent_id, cum_pnl, entry_quote_lamports,+ max(cum_pnl) over (+ partition by agent_id order by closed_at+ rows between unbounded preceding and current row) as peak+ from closed+ )+ select agent_id,+ max(peak - cum_pnl)::text as max_dd_lamports,+ coalesce(sum(entry_quote_lamports), 0)::text as entry_lamports+ from curve group by agent_id+ `.catch(() => []);++ for (const r of rows) {+ const deployed = lamToSol(r.entry_lamports);+ const dd = lamToSol(r.max_dd_lamports);+ out.set(r.agent_id, deployed > 0 ? round2(clamp((dd / deployed) * 100, 0, 100)) : null);+ }+ return out;+}diff --git a/api/_lib/copy-engine.js b/api/_lib/copy-engine.jsindex bba2f6a82..2fca0f0aa 100644--- a/api/_lib/copy-engine.js+++ b/api/_lib/copy-engine.js@@ -51,6 +51,14 @@ export function normalizeSubscriptionInput(raw = {}) {return { ok: false, error: 'min_oracle_score must be between 0 and 100' };}+ // Drawdown circuit breaker (null = opted out). Enforced per tick by+ // api/cron/copy-fanout.js against the leader's realized equity curve; see+ // api/_lib/copy-eligibility.js for the definition the percentage is measured on.+ const maxDrawdownPct = raw.max_drawdown_pct == null || raw.max_drawdown_pct === '' ? null : n(raw.max_drawdown_pct);+ if (maxDrawdownPct != null && !(maxDrawdownPct > 0 && maxDrawdownPct <= 100)) {+ return { ok: false, error: 'max_drawdown_pct must be between 0 and 100' };+ }+// Telegram chat ID: numeric string (positive or negative integer).const tgRaw = raw.telegram_chat_id == null ? null : String(raw.telegram_chat_id).trim();const telegramChatId = tgRaw === '' || tgRaw === null ? null : tgRaw;@@ -74,6 +82,7 @@ export function normalizeSubscriptionInput(raw = {}) {copy_sells: raw.copy_sells !== false,require_safety_pass: raw.require_safety_pass === true,min_oracle_score: minOracleScore,+ max_drawdown_pct: maxDrawdownPct,perf_fee_bps: perfBps,telegram_chat_id: telegramChatId,},diff --git a/api/_lib/migrations/20260903235500_copy_alpha_drip.sql b/api/_lib/migrations/20260903235500_copy_alpha_drip.sqlnew file mode 100644index 000000000..a9b6f7cdd--- /dev/null+++ b/api/_lib/migrations/20260903235500_copy_alpha_drip.sql@@ -0,0 +1,63 @@+-- Migration: alpha-drip — tiered release of a leader's own copy signal.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260903235500_copy_alpha_drip.sql+-- Idempotent.+--+-- A leader's edge decays in seconds, so the leader can sell the LATENCY of their+-- own signal instead of only a share of the profit: $THREE holders in higher+-- tiers receive the copy intent first, everyone else after a leader-set delay.+--+-- Non-negotiable: this gates only WHEN a copier is shown the intent. Every trade+-- is still recorded in full at fanout time and still lands in the leader's public+-- on-chain track record, so downside-transparency is untouched. There are no+-- hidden trades, only delayed reveals.++begin;++create table if not exists copy_alpha_drip (+ leader_agent_id uuid primary key references agent_identities(id) on delete cascade,+ owner_user_id uuid not null references users(id) on delete cascade,+ enabled boolean not null default false,+ -- [{ "tier": "gold", "delay_sec": 0, "max_copy_size_sol": 0.5|null }, ...]+ -- One entry per $THREE tier the leader prices; tiers left out inherit the+ -- nearest lower tier, and anything below the lowest priced tier waits+ -- public_delay_sec.+ schedule jsonb not null default '[]'::jsonb,+ public_delay_sec int not null default 0,+ disclosure text,+ capacity_note text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ constraint copy_alpha_drip_public_delay_range check (public_delay_sec >= 0 and public_delay_sec <= 900),+ constraint copy_alpha_drip_schedule_is_array check (jsonb_typeof(schedule) = 'array')+);++create index if not exists copy_alpha_drip_owner+ on copy_alpha_drip (owner_user_id);+create index if not exists copy_alpha_drip_enabled+ on copy_alpha_drip (leader_agent_id)+ where enabled;++-- Per-intent release state. A null visible_at means "no drip applied" (every row+-- written before this migration, and every intent from a leader with drip off),+-- which every reader treats as immediately visible.+alter table copy_executions+ add column if not exists visible_at timestamptz,+ add column if not exists drip_tier text,+ add column if not exists drip_delay_sec int,+ add column if not exists notified_at timestamptz;++comment on column copy_executions.visible_at is+ 'When this intent is revealed to the copier. Null = immediately. The row itself+ is always written in full at fanout time; only the reveal is delayed.';+comment on column copy_executions.drip_tier is+ 'The $THREE tier id the copier held when this intent was released.';+comment on column copy_executions.notified_at is+ 'When the held Telegram alert was sent (or skipped because the subscription has+ no chat id). Null while an intent is still waiting on its release.';++-- Release scan: pending intents whose delayed alert has not gone out yet.+create index if not exists copy_executions_drip_release+ on copy_executions (visible_at)+ where status = 'pending' and notified_at is null;++commit;diff --git a/api/_lib/migrations/20260903240000_copy_drawdown_breaker.sql b/api/_lib/migrations/20260903240000_copy_drawdown_breaker.sqlnew file mode 100644index 000000000..bb3f007d2--- /dev/null+++ b/api/_lib/migrations/20260903240000_copy_drawdown_breaker.sql@@ -0,0 +1,47 @@+-- Migration: a copier-set drawdown circuit breaker on copy_subscriptions.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260903240000_copy_drawdown_breaker.sql+-- Idempotent.+--+-- Before this, a copier could cap the size of any single copy (per_trade_cap_sol)+-- and the SOL fanned out per day (daily_budget_sol), but nothing capped the one+-- risk that actually strands a follower: a leader whose realized equity curve+-- rolls over and keeps going. The subscription mirrored every new entry the+-- whole way down, and the only exit was the copier noticing and pausing by hand.+--+-- max_drawdown_pct is the copier's answer to "how far down do I ride this?",+-- measured as peak-to-trough realized loss over gross capital deployed, the same+-- definition api/_lib/meta-allocator.js ranks leaders on and the Trader Card+-- shows. api/cron/copy-fanout.js evaluates it per leader per tick and flips a+-- breached subscription to status='paused', recording why and when. Pausing (not+-- stopping) is deliberate: the copier's guards, sizing, and high-water mark+-- survive, so resuming is one deliberate action and never a silent restart.+--+-- NULL means the copier opted out of the breaker, which is the behavior every+-- existing row had, so no backfill is needed and no live subscription changes.+--+-- paused_reason / paused_at also cover the future auto-pause cases (a leader who+-- goes quiet, a copier whose safety gate keeps rejecting) — any code path that+-- pauses a subscription on the copier's behalf owes them the reason.++begin;++alter table copy_subscriptions+ add column if not exists max_drawdown_pct numeric,+ add column if not exists paused_reason text,+ add column if not exists paused_at timestamptz;++-- 0 would mean "pause before the first losing trade", which is never what a+-- copier means; the engine treats <= 0 as opted out, so keep the column honest.+alter table copy_subscriptions+ drop constraint if exists copy_max_drawdown_range;++alter table copy_subscriptions+ add constraint copy_max_drawdown_range+ check (max_drawdown_pct is null or (max_drawdown_pct > 0 and max_drawdown_pct <= 100));++comment on column copy_subscriptions.max_drawdown_pct is+ 'Copier-set circuit breaker: auto-pause when the leader''s realized peak-to-trough drawdown, as a share of capital deployed, reaches this percentage. NULL = no breaker.';+comment on column copy_subscriptions.paused_reason is+ 'Machine reason a subscription was paused on the copier''s behalf (e.g. leader_drawdown_breach). NULL when the copier paused it themselves.';++commit;diff --git a/api/copy/alpha-drip.js b/api/copy/alpha-drip.jsnew file mode 100644index 000000000..49d43f1e4--- /dev/null+++ b/api/copy/alpha-drip.js@@ -0,0 +1,228 @@+/**+ * Alpha-drip configuration — a leader prices the latency of their own signal.+ *+ * GET /api/copy/alpha-drip?leader_agent_id=<uuid>+ * Public read. Returns the leader's release ladder, the standing+ * disclosure, and — for a signed-in caller — the seat THEY would get, so+ * a copier sees their real wait before they subscribe rather than after.+ *+ * POST /api/copy/alpha-drip { leader_agent_id, enabled, schedule,+ * public_delay_sec, disclosure, capacity_note }+ * The agent's owner sets the ladder. Owner-only, CSRF-guarded.+ *+ * POST /api/copy/alpha-drip { action: 'recommend', leader_agent_id,+ * edge_halflife_sec }+ * Asks the LLM chain for a ladder tuned to how fast this leader's edge+ * actually decays. It only ever RETURNS a draft — the leader still has to+ * save it — and the draft is validated through the same normalizer as a+ * hand-written one, so the model can never talk the ladder past a rule.+ *+ * The drip delays the reveal, never the record: the intent row is written in+ * full at fanout time and the leader's public track record is untouched.+ */++import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { sql } from '../_lib/db.js';+import { isUuid } from '../_lib/validate.js';+import { resolveUserTier, TIERS } from '../_lib/three-tier.js';+import {+ normalizeDripConfig, planRelease, dripDisclosure, describeSchedule,+ assessFairness, maxDelaySec, emptyDripConfig, formatDelay, MAX_DELAY_SEC, TIER_IDS,+} from '../_lib/alpha-drip.js';+import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';+import { leaderEdgeHalflifeSec } from '../_lib/alpha-drip-stats.js';++const RECOMMEND_SYSTEM = `You decide how a LEADER's OWN trade signal is released across the leader's OWN subscriber tiers. You are gating the leader's self-produced signal as a subscription product. You are NOT accessing, delaying, or front-running anyone else's orders — only the leader's own.++Reply with STRICT JSON and nothing else:+{+ "schedule": [ { "tier": "<tier id>", "delay_sec": <int>, "max_copy_size_sol": <number|null> } ],+ "public_delay_sec": <int>,+ "disclosure": "<plain-English line the leader can show subscribers>",+ "capacity_note": "<how size was split so early tiers do not exhaust the leader's edge or capacity>"+}++Rules:+- Tier ids, lowest to highest, are exactly: ${TIER_IDS.join(', ')}. Use only these.+- A higher tier can NEVER wait longer than a lower one, and public_delay_sec is the longest wait of all.+- No delay may exceed ${MAX_DELAY_SEC} seconds.+- The full trade ALWAYS becomes part of the public on-chain record. You are timing the copy signal, never whether the trade is disclosed. Never suggest hiding a trade.+- If the edge half-life is very short, tiering is unfair to slower tiers: recommend equal release (every delay 0) and say so in the disclosure.+- Never imply access to third-party orderflow.`;++async function requireUser(req, res) {+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) { error(res, 401, 'unauthorized', 'sign in required'); return null; }+ return { userId: session?.id ?? bearer.userId, user: session, viaSession: !!session };+}++/** Read a leader's stored config, normalized. Never throws on a malformed row. */+async function loadConfig(leaderAgentId) {+ const [row] = await sql`+ select enabled, schedule, public_delay_sec, disclosure, capacity_note, updated_at+ from copy_alpha_drip where leader_agent_id = ${leaderAgentId} limit 1+ `;+ if (!row) return { config: emptyDripConfig(), updatedAt: null };+ const norm = normalizeDripConfig(row);+ return { config: norm.ok ? norm.value : emptyDripConfig(), updatedAt: row.updated_at };+}++/** The public shape every drip surface renders from. */+function present(config) {+ return {+ enabled: config.enabled,+ schedule: config.schedule,+ public_delay_sec: config.public_delay_sec,+ disclosure: dripDisclosure(config),+ leader_note: config.disclosure,+ capacity_note: config.capacity_note,+ summary: describeSchedule(config),+ longest_delay_sec: maxDelaySec(config),+ tiers: TIERS.map((t) => ({ id: t.id, label: t.label, min_usd: t.minUsd })),+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;+ if (await rateLimited(req, res, limits.api, clientIp(req))) return;++ const leaderFromQuery = String(req.query?.leader_agent_id || '').trim();++ if (req.method === 'GET') {+ if (!isUuid(leaderFromQuery)) return error(res, 400, 'invalid_leader', 'leader_agent_id must be an agent UUID');+ const [leader] = await sql`+ select id, user_id, name, is_public from agent_identities+ where id = ${leaderFromQuery} and deleted_at is null limit 1+ `;+ if (!leader || leader.is_public === false) return error(res, 404, 'leader_not_found', 'No such public trader.');++ const { config, updatedAt } = await loadConfig(leaderFromQuery);+ const body = { leader_agent_id: leader.id, leader_name: leader.name, updated_at: updatedAt, drip: present(config) };++ // A signed-in caller sees the seat they personally get. Signed-out callers+ // get the ladder only — we have no wallet to price them against.+ const session = await getSessionUser(req);+ if (session) {+ const { tier, usd } = await resolveUserTier(session);+ const release = planRelease(config, tier.id);+ body.you = {+ tier: tier.id,+ tier_label: tier.label,+ three_usd: Math.round(usd * 100) / 100,+ delay_sec: release.delay_sec,+ delay_label: formatDelay(release.delay_sec),+ matched_tier: release.matched_tier,+ max_copy_size_sol: release.max_copy_size_sol,+ is_owner: leader.user_id === session.id,+ };+ }+ return json(res, 200, body);+ }++ const auth = await requireUser(req, res);+ if (!auth) return;+ if (auth.viaSession && !requireCsrf(req, res)) return;++ const input = await readJson(req);+ if (!input) return error(res, 400, 'invalid_body', 'expected a JSON body');++ const leaderId = String(input.leader_agent_id || '').trim();+ if (!isUuid(leaderId)) return error(res, 400, 'invalid_leader', 'leader_agent_id must be an agent UUID');++ const [leader] = await sql`+ select id, user_id, name from agent_identities+ where id = ${leaderId} and deleted_at is null limit 1+ `;+ if (!leader) return error(res, 404, 'leader_not_found', 'No such trader.');+ if (leader.user_id !== auth.userId) {+ return error(res, 403, 'not_owner', 'Only the agent\'s owner can price its signal.');+ }++ // Half-life is measured from the leader's real closed trades, so a+ // recommendation and a fairness warning are both grounded in this leader's+ // history rather than a guess. Null when they have too few closes to measure.+ const halflife = input.edge_halflife_sec != null && input.edge_halflife_sec !== ''+ ? Number(input.edge_halflife_sec)+ : await leaderEdgeHalflifeSec(leaderId);++ if (input.action === 'recommend') {+ const { config: current } = await loadConfig(leaderId);+ const userPrompt = JSON.stringify({+ leader: leader.name || 'this trader',+ estimated_edge_halflife_sec: Number.isFinite(halflife) ? Math.round(halflife) : null,+ tiers: TIERS.map((t) => ({ tier: t.id, label: t.label, min_usd_held: t.minUsd })),+ current_schedule: current.schedule,+ current_public_delay_sec: current.public_delay_sec,+ });++ let raw;+ try {+ raw = await llmComplete({ system: RECOMMEND_SYSTEM, user: userPrompt, maxTokens: 700, timeoutMs: 25_000, track: { userId: auth.userId } });+ } catch (err) {+ if (err instanceof LlmUnavailableError) {+ return error(res, 503, 'llm_unavailable', 'No language model is reachable right now. Set the ladder by hand and try the suggestion later.');+ }+ return error(res, err.status || 502, err.code || 'recommend_failed', err.message || 'Could not draft a ladder.');+ }++ const parsed = parseJsonBlock(raw?.text ?? raw);+ if (!parsed) return error(res, 502, 'recommend_unparsable', 'The model did not return a usable ladder. Set it by hand.');++ const norm = normalizeDripConfig({ ...parsed, enabled: true });+ if (!norm.ok) {+ return error(res, 502, 'recommend_invalid', `The suggested ladder broke a release rule (${norm.error}). Set it by hand.`);+ }+ return json(res, 200, {+ leader_agent_id: leaderId,+ suggestion: present(norm.value),+ fairness: assessFairness(norm.value, halflife),+ edge_halflife_sec: Number.isFinite(halflife) ? Math.round(halflife) : null,+ applied: false,+ note: 'This is a draft. Save it to make it live.',+ });+ }++ const norm = normalizeDripConfig(input);+ if (!norm.ok) return error(res, 400, 'invalid_config', norm.error);+ const v = norm.value;++ await sql`+ insert into copy_alpha_drip (+ leader_agent_id, owner_user_id, enabled, schedule, public_delay_sec, disclosure, capacity_note+ ) values (+ ${leaderId}, ${auth.userId}, ${v.enabled}, ${JSON.stringify(v.schedule)}::jsonb,+ ${v.public_delay_sec}, ${v.disclosure}, ${v.capacity_note}+ )+ on conflict (leader_agent_id) do update set+ owner_user_id = excluded.owner_user_id,+ enabled = excluded.enabled,+ schedule = excluded.schedule,+ public_delay_sec = excluded.public_delay_sec,+ disclosure = excluded.disclosure,+ capacity_note = excluded.capacity_note,+ updated_at = now()+ `;++ return json(res, 200, {+ leader_agent_id: leaderId,+ drip: present(v),+ fairness: assessFairness(v, halflife),+ edge_halflife_sec: Number.isFinite(halflife) ? Math.round(halflife) : null,+ });+});++/** Pull the first JSON object out of a model reply, fenced or bare. Never throws. */+function parseJsonBlock(text) {+ if (typeof text !== 'string') return null;+ const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);+ const candidate = fenced ? fenced[1] : text;+ const start = candidate.indexOf('{');+ const end = candidate.lastIndexOf('}');+ if (start < 0 || end <= start) return null;+ try { return JSON.parse(candidate.slice(start, end + 1)); } catch { return null; }+}diff --git a/api/copy/executions.js b/api/copy/executions.jsindex a14af2fd8..14e75cee4 100644--- a/api/copy/executions.js+++ b/api/copy/executions.js@@ -17,6 +17,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.import { requireCsrf } from '../_lib/csrf.js';import { sql } from '../_lib/db.js';import { isUuid } from '../_lib/validate.js';+import { maskUnreleasedIntent } from '../_lib/alpha-drip.js';const STATUSES = new Set(['pending', 'acted', 'dismissed', 'skipped', 'expired', 'all']);@@ -65,7 +66,11 @@ export default wrap(async (req, res) => {where e.copier_user_id = ${userId} and e.status = ${status}order by e.created_at desc limit ${limit}`;- return json(res, 200, { executions: rows });+ // A leader on an alpha-drip releases their signal to higher $THREE tiers+ // first. The row is complete in the database; the coin and size are held+ // back on the way out until this copier's own reveal passes.+ const now = Date.now();+ return json(res, 200, { executions: rows.map((r) => maskUnreleasedIntent(r, now)) });}// POST — act / dismiss. Enforce CSRF for cookie-session callers.@@ -81,12 +86,29 @@ export default wrap(async (req, res) => {const txSig = action === 'acted' && typeof body.tx_signature === 'string'? body.tx_signature.trim().slice(0, 128) || null : null;+ // `visible_at` gates the action too, not just the render: an intent this+ // copier's tier has not reached yet is not theirs to act on, and the guard+ // lives in the same statement so it cannot be raced.const [row] = await sql`update copy_executionsset status = ${action}, tx_signature = ${txSig}, updated_at = now()where id = ${id} and copier_user_id = ${userId} and status = 'pending'+ and (visible_at is null or visible_at <= now())returning *`;- if (!row) return error(res, 409, 'not_actionable', 'No such pending intent (it may have expired or already been actioned).');- return json(res, 200, { execution: row });+ if (!row) {+ const [held] = await sql`+ select visible_at from copy_executions+ where id = ${id} and copier_user_id = ${userId} and status = 'pending'+ and visible_at is not null and visible_at > now()+ limit 1+ `;+ if (held) {+ return error(res, 409, 'not_released', 'This signal has not been released to your tier yet.', {+ unlocks_at: new Date(held.visible_at).toISOString(),+ });+ }+ return error(res, 409, 'not_actionable', 'No such pending intent (it may have expired or already been actioned).');+ }+ return json(res, 200, { execution: maskUnreleasedIntent(row) });});diff --git a/api/copy/subscriptions.js b/api/copy/subscriptions.jsindex dc8d0d01c..59cc2dead 100644--- a/api/copy/subscriptions.js+++ b/api/copy/subscriptions.js@@ -8,6 +8,12 @@** Auth required (session cookie or bearer). Non-custodial: we store the copier's* own wallet and their sizing/guard rules — never keys, never custody.+ *+ * Two anti-gaming gates run before a follow is accepted (api/_lib/copy-eligibility.js):+ * a copier may not follow an agent they own (a self-copy pays a performance fee+ * to itself and inflates the leader's public copier count and earnings), and a+ * leader must have cleared the copyable bar on real closed round-trips before+ * anyone can attach money to it.*/import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';@@ -16,6 +22,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.import { requireCsrf } from '../_lib/csrf.js';import { sql } from '../_lib/db.js';import { normalizeSubscriptionInput } from '../_lib/copy-engine.js';+import { BREAKER_REASON, LEADER_ELIGIBILITY, evaluateDrawdownBreaker, evaluateLeaderEligibility, leaderCopyProfile } from '../_lib/copy-eligibility.js';import { isUuid } from '../_lib/validate.js';const NETWORKS = new Set(['mainnet', 'devnet']);@@ -86,8 +93,37 @@ export default wrap(async (req, res) => {if (!['active', 'paused', 'stopped'].includes(body.status)) {return error(res, 400, 'invalid_status', 'status must be active, paused, or stopped');}+ // Resuming an auto-paused subscription must not hand the copier a button that+ // re-pauses on the next tick. If the breaker is still breached, refuse and say+ // what would clear it — raise the limit, or drop it.+ if (body.status === 'active') {+ const [paused] = await sql`+ select id, network, leader_agent_id, max_drawdown_pct, paused_reason+ from copy_subscriptions+ where id = ${body.id} and copier_user_id = ${userId}+ limit 1+ `;+ if (!paused) return error(res, 404, 'not_found', 'No such subscription.');+ if (paused.paused_reason === BREAKER_REASON && paused.max_drawdown_pct != null) {+ const leaderProfile = await leaderCopyProfile(paused.leader_agent_id, paused.network);+ const breaker = evaluateDrawdownBreaker(paused, leaderProfile.max_drawdown_pct);+ if (breaker.breached) {+ return error(+ res,+ 409,+ 'drawdown_still_breached',+ `This trader is still ${breaker.drawdown_pct}% below their peak, past your ${breaker.limit_pct}% limit. Raise or clear your drawdown limit to resume.`,+ { breaker, leader_profile: leaderProfile },+ );+ }+ }+ }++ // A status change made BY the copier carries no machine reason, so the+ // auto-pause bookkeeping is cleared on every branch of this path: paused_reason+ // is only ever set by a guard acting on the copier's behalf.const [row] = await sql`- update copy_subscriptions set status = ${body.status}, updated_at = now()+ update copy_subscriptions set status = ${body.status}, paused_reason = null, paused_at = null, updated_at = now()where id = ${body.id} and copier_user_id = ${userId}returning *`;@@ -103,10 +139,34 @@ export default wrap(async (req, res) => {if (!BASE58_RE.test(wallet)) return error(res, 400, 'invalid_wallet', 'copier_wallet must be a valid Solana address');const [leader] = await sql`- select id, is_public from agent_identities where id = ${leaderId} limit 1+ select id, user_id, name, is_public from agent_identities+ where id = ${leaderId} and deleted_at is null limit 1`;if (!leader || leader.is_public === false) return error(res, 404, 'leader_not_found', 'No such public trader.');+ // Wash-trade guard: copying your own agent routes the performance fee back to+ // you while inflating that leader's copier count, copied volume, and the public+ // "earned X for being copied" figure. Refused outright — there is no legitimate+ // version of it, since the owner already controls the agent's own trading.+ if (leader.user_id === userId) {+ return error(res, 403, 'self_copy', 'You cannot copy an agent you own — you already control its trading.');+ }++ // Sybil bar: a leader needs a real, closed, on-chain track record before a+ // copier can attach money to it. The unmet criteria go back in the body so the+ // UI can say exactly what is missing instead of "not eligible".+ const profile = await leaderCopyProfile(leaderId, network);+ const eligibility = evaluateLeaderEligibility(profile);+ if (!eligibility.eligible) {+ return error(+ res,+ 409,+ 'leader_not_copyable',+ `${leader.name || 'This trader'} does not have enough verified history to be copied yet: ${eligibility.unmet.map((u) => u.label).join(', ')}.`,+ { eligibility: { ...eligibility, requirements: LEADER_ELIGIBILITY, network } },+ );+ }+const norm = normalizeSubscriptionInput(body);if (!norm.ok) return error(res, 400, 'invalid_config', norm.error);const v = norm.value;@@ -125,13 +185,13 @@ export default wrap(async (req, res) => {sizing_rule, fixed_sol, multiplier, pct_balance,per_trade_cap_sol, min_order_sol, daily_budget_sol, max_open_copies,mcap_floor_usd, mcap_ceiling_usd, copy_sells, require_safety_pass, min_oracle_score, perf_fee_bps,- telegram_chat_id+ max_drawdown_pct, telegram_chat_id) values (${userId}, ${wallet}, ${leaderId}, ${leaderWallet}, ${network}, 'active',${v.sizing_rule}, ${v.fixed_sol}, ${v.multiplier}, ${v.pct_balance},${v.per_trade_cap_sol}, ${v.min_order_sol}, ${v.daily_budget_sol}, ${v.max_open_copies},${v.mcap_floor_usd}, ${v.mcap_ceiling_usd}, ${v.copy_sells}, ${v.require_safety_pass}, ${v.min_oracle_score}, ${v.perf_fee_bps},- ${v.telegram_chat_id || null}+ ${v.max_drawdown_pct}, ${v.telegram_chat_id || null})on conflict (copier_user_id, leader_agent_id, network) do update setcopier_wallet = excluded.copier_wallet,@@ -151,9 +211,15 @@ export default wrap(async (req, res) => {require_safety_pass = excluded.require_safety_pass,min_oracle_score = excluded.min_oracle_score,perf_fee_bps = excluded.perf_fee_bps,+ max_drawdown_pct = excluded.max_drawdown_pct,telegram_chat_id = excluded.telegram_chat_id,+ -- Re-subscribing is a deliberate act, so it clears an auto-pause. A+ -- breaker that stayed latched here would silently re-arm a subscription+ -- the copier just reconfigured to a wider limit.+ paused_reason = null,+ paused_at = null,updated_at = now()returning *`;- return json(res, 200, { subscription: row });+ return json(res, 200, { subscription: row, leader: { id: leaderId, name: leader.name || null }, leader_profile: profile });});diff --git a/api/cron/copy-fanout.js b/api/cron/copy-fanout.jsindex 7ab0b7bf9..e7c29c67e 100644--- a/api/cron/copy-fanout.js+++ b/api/cron/copy-fanout.js@@ -15,6 +15,16 @@// acted on the matching buy. Oracle sells are not modelled (there// is no explicit exit event — outcomes are graded after the fact).//+// Two guards run BEFORE any sizing (api/_lib/copy-eligibility.js), because both+// protect money rather than shaping an intent:+// • DRAWDOWN BREAKER — the leader's realized peak-to-trough loss is measured+// once per leader per tick; every subscription whose max_drawdown_pct it+// breaches is flipped to 'paused' with the reason recorded, and fans out+// nothing further. A copier is never mirrored into a leader's slide.+// • SELF-COPY — a subscription whose copier owns the leader agent is skipped.+// Subscribing to your own agent is refused at the endpoint; this catches any+// row that predates that rule, so a wash-trade loop cannot keep firing.+//// Idempotent via partial unique indexes:// (subscription_id, leader_position_id, direction) when leader_position_id is not null// (subscription_id, leader_oracle_action_id, direction) when leader_oracle_action_id is not null@@ -22,6 +32,8 @@import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { planCopyOrder } from '../_lib/copy-engine.js';+import { BREAKER_REASON, evaluateDrawdownBreaker, leaderDrawdownPcts } from '../_lib/copy-eligibility.js';+import { loadDripConfigs, newTierCache, priceRelease, releaseDueDrips } from '../_lib/copy-drip-runtime.js';import { requireCron } from '../_lib/cron-auth.js';import { pumpFetchJson, PUMP_FRONTEND_BASE } from '../_lib/pump-feed-fetch.js';import { fetchTokenMarketData } from '../_lib/market/token-market.js';@@ -120,6 +132,81 @@ async function oracleScore(mint, network) {} catch { return null; }}+// ── Pre-sizing guards ─────────────────────────────────────────────────────────++function breakerMessage({ leaderName, drawdownPct, limitPct }) {+ return [+ '\u26d4 Copy trading paused',+ `Leader: ${leaderName || 'unknown'}`,+ `Drawdown ${drawdownPct}% reached your ${limitPct}% limit.`,+ '',+ 'Nothing was copied. Review and resume when you are ready:',+ 'https://three.ws/dashboard/copy',+ ].join('\n');+}++/**+ * Active subscriptions for a batch of leaders, grouped by leader, with the two+ * money-protecting guards already applied.+ *+ * Self-copy rows are dropped (a copier who owns the leader would pay a+ * performance fee to themselves and inflate that leader's public copier count),+ * and any subscription whose copier-set drawdown limit the leader has breached is+ * flipped to 'paused' here, with the reason and timestamp recorded, before it can+ * size a single order.+ */+async function activeSubscriptionsByLeader(leaderIds, network, stats) {+ const byLeader = new Map();+ if (!leaderIds.length) return byLeader;++ // The leader's owner comes back on the row so the self-copy test costs no+ // extra round trip.+ const subRows = await sql`+ select s.*, a.user_id as leader_user_id, a.name as leader_name+ from copy_subscriptions s+ join agent_identities a on a.id = s.leader_agent_id+ where s.leader_agent_id = any(${leaderIds}) and s.network = ${network} and s.status = 'active'+ `;+ if (!subRows.length) return byLeader;++ // One drawdown query for every leader in the batch, not one per subscription.+ const drawdowns = await leaderDrawdownPcts(leaderIds, network);++ for (const sub of subRows) {+ if (sub.leader_user_id && sub.leader_user_id === sub.copier_user_id) {+ stats.skipped_self_copy = (stats.skipped_self_copy || 0) + 1;+ continue;+ }++ const breaker = evaluateDrawdownBreaker(sub, drawdowns.get(sub.leader_agent_id) ?? null);+ if (breaker.breached) {+ const [paused] = await sql`+ update copy_subscriptions+ set status = 'paused', paused_reason = ${BREAKER_REASON}, paused_at = now(), updated_at = now()+ where id = ${sub.id} and status = 'active'+ returning id+ `;+ // Only the tick that actually flipped the row counts it and notifies, so a+ // retry or an overlapping run cannot double-report or double-message.+ if (paused) {+ stats.paused_drawdown = (stats.paused_drawdown || 0) + 1;+ if (sub.telegram_chat_id) {+ sendTg(sub.telegram_chat_id, breakerMessage({+ leaderName: sub.leader_name,+ drawdownPct: breaker.drawdown_pct,+ limitPct: breaker.limit_pct,+ }));+ }+ }+ continue;+ }++ if (!byLeader.has(sub.leader_agent_id)) byLeader.set(sub.leader_agent_id, []);+ byLeader.get(sub.leader_agent_id).push(sub);+ }+ return byLeader;+}+async function fanoutBuys(network, stats) {const positions = await sql`select p.id, p.agent_id, p.mint, p.symbol, p.name, p.entry_quote_lamports, p.buy_sig, p.opened_at@@ -152,17 +239,13 @@ async function fanoutBuys(network, stats) {const open = new Map(openRows.map((r) => [r.subscription_id, Number(r.open) || 0]));// Active subscriptions for every leader in this batch, fetched once and grouped- // by leader_agent_id — replaces a per-position query.+ // by leader_agent_id — replaces a per-position query. Self-copy rows are dropped+ // and drawdown-breached ones are auto-paused before anything is sized.const leaderIds = [...new Set(positions.map((p) => p.agent_id))];- const subRows = await sql`- select * from copy_subscriptions- where leader_agent_id = any(${leaderIds}) and network = ${network} and status = 'active'- `;- const subsByLeader = new Map();- for (const s of subRows) {- if (!subsByLeader.has(s.leader_agent_id)) subsByLeader.set(s.leader_agent_id, []);- subsByLeader.get(s.leader_agent_id).push(s);- }+ const subsByLeader = await activeSubscriptionsByLeader(leaderIds, network, stats);+ // Alpha-drip ladders for this batch. Leaders without one cost nothing below.+ const drips = await loadDripConfigs(leaderIds);+ const tierCache = newTierCache();for (const pos of positions) {const subs = subsByLeader.get(pos.agent_id) || [];@@ -179,19 +262,31 @@ async function fanoutBuys(network, stats) {spentTodaySol: spent.get(sub.id) || 0,openCopies: open.get(sub.id) || 0,});- const status = decision.action === 'copy' ? 'pending' : 'skipped';- const planned = decision.action === 'copy' ? decision.order_sol : null;+ // Alpha-drip: price this copier's seat, apply the tier's capacity cap, and+ // work out when the intent is revealed to them. The row itself is written+ // in full either way — only the reveal moves.+ const release = decision.action === 'copy'+ ? await priceRelease({ subscription: sub, config: drips.get(pos.agent_id) || null, plannedSol: decision.order_sol, tierCache })+ : null;+ const capacitySkip = release?.capacitySkip || null;+ const status = decision.action === 'copy' && !capacitySkip ? 'pending' : 'skipped';+ const planned = status === 'pending' ? release.plannedSol : null;+ const skipReason = capacitySkip ? capacitySkip.reason : (status === 'skipped' ? decision.reason : null);const [inserted] = await sql`insert into copy_executions (subscription_id, copier_user_id, leader_agent_id, leader_position_id, network,mint, symbol, name, direction, planned_sol, leader_entry_sol, status, skip_reason,- safety, leader_buy_sig+ safety, leader_buy_sig, visible_at, drip_tier, drip_delay_sec, notified_at,+ expires_at) values (${sub.id}, ${sub.copier_user_id}, ${pos.agent_id}, ${pos.id}, ${network},${pos.mint}, ${pos.symbol}, ${pos.name}, 'buy', ${planned}, ${entrySol}, ${status},- ${decision.reason && status === 'skipped' ? decision.reason : null},- ${coin ? JSON.stringify(coin) : null}::jsonb, ${pos.buy_sig}+ ${skipReason},+ ${coin ? JSON.stringify(coin) : null}::jsonb, ${pos.buy_sig},+ ${release?.visibleAt ?? null}, ${release?.tier ?? null}, ${release?.delaySec ?? null},+ ${release && !release.notifyNow ? null : new Date()},+ ${release?.expiresAt ?? new Date(Date.now() + 30 * 60 * 1000)})on conflict (subscription_id, leader_position_id, direction) do nothingreturning id@@ -202,7 +297,10 @@ async function fanoutBuys(network, stats) {spent.set(sub.id, (spent.get(sub.id) || 0) + (planned || 0));open.set(sub.id, (open.get(sub.id) || 0) + 1);// Telegram notify copier of the new buy intent (best-effort, async).- if (sub.telegram_chat_id) {+ // A dripped seat stays quiet here — releaseDueDrips sends it when+ // the intent is actually revealed, so the alert cannot leak the+ // coin ahead of the copier's own release time.+ if (sub.telegram_chat_id && release?.notifyNow !== false) {const leader = await agentName(pos.agent_id);sendTg(sub.telegram_chat_id, buyIntentMessage({sym: pos.symbol, name: pos.name, plannedSol: planned,@@ -250,6 +348,11 @@ async function fanoutSells(network, stats) {for (const pos of closes) {const buys = buysByPosition.get(pos.id) || [];for (const b of buys) {+ // Exit signals deliberately survive a pause. A subscription paused by the+ // drawdown breaker has its BUYS frozen, but the copier is already in the+ // position this close exits — withholding the sell intent would strand+ // them in the exact leader the breaker just fired on. Only a stopped+ // subscription (the copier's own hard exit) stops mirroring exits.if (!b.copy_sells || b.sub_status === 'stopped') continue;const [inserted] = await sql`insert into copy_executions (@@ -307,17 +410,13 @@ async function fanoutOracleBuys(network, stats) {const open = new Map(openRows.map((r) => [r.subscription_id, Number(r.open) || 0]));// Active subscriptions for every acting agent in this batch, fetched once and- // grouped by leader_agent_id — replaces a per-action query.+ // grouped by leader_agent_id — replaces a per-action query. Same two guards as+ // the sniper path: self-copy dropped, drawdown-breached auto-paused.const leaderIds = [...new Set(actions.map((a) => a.agent_id))];- const subRows = await sql`- select * from copy_subscriptions- where leader_agent_id = any(${leaderIds}) and network = ${network} and status = 'active'- `;- const subsByLeader = new Map();- for (const s of subRows) {- if (!subsByLeader.has(s.leader_agent_id)) subsByLeader.set(s.leader_agent_id, []);- subsByLeader.get(s.leader_agent_id).push(s);- }+ const subsByLeader = await activeSubscriptionsByLeader(leaderIds, network, stats);+ // Alpha-drip ladders for this batch. Leaders without one cost nothing below.+ const drips = await loadDripConfigs(leaderIds);+ const tierCache = newTierCache();for (const action of actions) {const subs = subsByLeader.get(action.agent_id) || [];@@ -334,8 +433,14 @@ async function fanoutOracleBuys(network, stats) {spentTodaySol: spent.get(sub.id) || 0,openCopies: open.get(sub.id) || 0,});- const status = decision.action === 'copy' ? 'pending' : 'skipped';- const planned = decision.action === 'copy' ? decision.order_sol : null;+ // Alpha-drip: same seat pricing and capacity cap as the sniper path.+ const release = decision.action === 'copy'+ ? await priceRelease({ subscription: sub, config: drips.get(action.agent_id) || null, plannedSol: decision.order_sol, tierCache })+ : null;+ const capacitySkip = release?.capacitySkip || null;+ const status = decision.action === 'copy' && !capacitySkip ? 'pending' : 'skipped';+ const planned = status === 'pending' ? release.plannedSol : null;+ const skipReason = capacitySkip ? capacitySkip.reason : (status === 'skipped' ? decision.reason : null);// Note: leader_position_id is null for oracle-sourced intents.// Idempotency is guaranteed by the copy_executions_oracle_idem partial unique index.@@ -343,12 +448,15 @@ async function fanoutOracleBuys(network, stats) {insert into copy_executions (subscription_id, copier_user_id, leader_agent_id, leader_position_id, leader_oracle_action_id,network, mint, symbol, direction, planned_sol, leader_entry_sol, status, skip_reason,- safety+ safety, visible_at, drip_tier, drip_delay_sec, notified_at, expires_at) values (${sub.id}, ${sub.copier_user_id}, ${action.agent_id}, null, ${action.id},${network}, ${action.mint}, ${action.symbol || null}, 'buy', ${planned}, ${entrySol},- ${status}, ${decision.reason && status === 'skipped' ? decision.reason : null},- ${coin ? JSON.stringify(coin) : null}::jsonb+ ${status}, ${skipReason},+ ${coin ? JSON.stringify(coin) : null}::jsonb,+ ${release?.visibleAt ?? null}, ${release?.tier ?? null}, ${release?.delaySec ?? null},+ ${release && !release.notifyNow ? null : new Date()},+ ${release?.expiresAt ?? new Date(Date.now() + 30 * 60 * 1000)})on conflict (subscription_id, leader_oracle_action_id, direction)where leader_oracle_action_id is not null@@ -362,7 +470,8 @@ async function fanoutOracleBuys(network, stats) {spent.set(sub.id, (spent.get(sub.id) || 0) + (planned || 0));open.set(sub.id, (open.get(sub.id) || 0) + 1);// Telegram notify copier of the new oracle-sourced buy intent (best-effort).- if (sub.telegram_chat_id) {+ // Held back for a dripped seat — releaseDueDrips sends it on reveal.+ if (sub.telegram_chat_id && release?.notifyNow !== false) {const leader = await agentName(action.agent_id);sendTg(sub.telegram_chat_id, buyIntentMessage({sym: action.symbol, name: null, plannedSol: planned,@@ -392,6 +501,16 @@ export default wrapCron(async (req, res) => {_coinCache.clear();_oracleScoreCache.clear();_agentNameCache.clear();++ // Alerts held back by an alpha-drip go out the moment their reveal passes.+ // Running it at the top of the tick means the release cadence is the fanout+ // cadence, with no second cron to keep in sync.+ try {+ await releaseDueDrips({ sendTg, stats });+ } catch (err) {+ stats.error_drip_release = err.message;+ }+for (const network of NETWORKS) {try {await fanoutBuys(network, stats);diff --git a/pages/ghost-copy.html b/pages/ghost-copy.htmlindex 389e06413..5b40802f5 100644--- a/pages/ghost-copy.html+++ b/pages/ghost-copy.html@@ -3,6 +3,7 @@<head><script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script><meta charset="utf-8" />+ <script src="/referral-capture.js"></script><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Ghost-copy: what if you'd copied them? · three.ws</title><meta name="description" content="Paper-copy any verified pump.fun trader agent with fake money over their real on-chain trades. Pick a leader, a budget and a window, and see the equity curve you would have had. No wallet, no signature, no custody." />@@ -117,6 +118,13 @@.gc-table a:hover { text-decoration: underline; }.gc-coin { font-weight: 700; }.gc-coin small { display: block; font-weight: 500; color: var(--gc-faint); font-size: 11px; }+ /* Fork: the one live action on this page. Opens the real trade panel at+ your ghost size (src/fork-trade.js), your wallet signs it. */+ .gc-fork { appearance: none; font: inherit; font-weight: 700; font-size: 12px; padding: 6px 12px; border-radius: 8px; cursor: pointer; border: 1px solid color-mix(in srgb, var(--gc-accent) 45%, var(--gc-line)); background: color-mix(in srgb, var(--gc-accent) 14%, transparent); color: var(--gc-text); transition: background .15s, border-color .15s, transform .15s; }+ .gc-fork:hover { background: var(--gc-accent); border-color: var(--gc-accent); color: #fff; transform: translateY(-1px); }+ .gc-fork:active { transform: none; }+ .gc-fork:focus-visible { outline: 2px solid var(--gc-accent-2); outline-offset: 2px; }+ @media (prefers-reduced-motion: reduce) { .gc-fork { transition: none; } .gc-fork:hover { transform: none; } }details.gc-details { border: 1px solid var(--gc-line); border-radius: 12px; background: var(--gc-panel); padding: 4px 14px; }details.gc-details summary { cursor: pointer; font-weight: 600; font-size: 13.5px; color: var(--gc-dim); padding: 10px 0; }diff --git a/src/copy-panel.js b/src/copy-panel.jsindex 3934ce7f9..3a3446483 100644--- a/src/copy-panel.js+++ b/src/copy-panel.js@@ -6,9 +6,15 @@* turns the leader's future trades into sized, safety-checked intents the copier* acts on from `/dashboard/copy`.*- * Self-contained: handles signed-out (CTA), first-time (form), and already-- * copying (summary + edit) states, plus loading/error. Import and call+ * Self-contained: handles signed-out (CTA), first-time (form), already-copying+ * (summary + edit) and auto-paused states, plus loading/error. Import and call* `mountCopyPanel(el, { leaderAgentId, leaderName, network })`.+ *+ * Two server-side guards surface here rather than as a generic failure, because+ * both are answerable by the copier: a leader who has not yet earned a copyable+ * track record comes back as a checklist of what is still missing, and a+ * subscription auto-paused by the drawdown breaker explains what tripped it and+ * refuses a resume that would immediately re-trip.*/import { escapeHtml } from './trader-format.js';@@ -74,19 +80,42 @@ function renderActive(el, { existing, leaderName, leaderAgentId, network }) {: s.sizing_rule === 'multiplier' ? `${Number(s.multiplier)}× their size`: `${Number(s.pct_balance)}% of balance`;const paused = s.status === 'paused';+ // An auto-pause is a different state from a pause the copier chose: it needs to+ // say what tripped, because the copier did not do it and cannot otherwise tell.+ const tripped = paused && s.paused_reason === 'leader_drawdown_breach';+ const limit = s.max_drawdown_pct == null ? null : Number(s.max_drawdown_pct);el.innerHTML = `<h2>You're copying ${escapeHtml(leaderName || 'this trader')} ${paused ? '<span class="tp-soon" style="color:var(--ink-faint);border-color:var(--stroke)">Paused</span>' : '<span class="cp-on">● Active</span>'}</h2>- <p>${escapeHtml(sizeLabel)} · cap ${Number(s.per_trade_cap_sol)} SOL/trade · ${Number(s.daily_budget_sol)} SOL/day.+ ${tripped ? `<p class="cp-tripped"><strong>Your drawdown limit stopped new copies.</strong>+ ${escapeHtml(leaderName || 'This trader')} fell past the ${limit}% peak-to-trough loss you set, so nothing new is being copied.+ Exits you were already in still come through. Resume when they recover, or edit your limit.</p>` : ''}+ <p>${escapeHtml(sizeLabel)} · cap ${Number(s.per_trade_cap_sol)} SOL/trade · ${Number(s.daily_budget_sol)} SOL/day${limit ? ` · pause at ${limit}% drawdown` : ''}.New trades arrive as intents in your dashboard.${s.telegram_chat_id ? ` Telegram alerts on.` : ''}</p>+ <p class="cp-err" id="cp-toggle-err" hidden></p><div class="cp-actions"><a class="lb-btn lb-btn-primary" href="/dashboard/copy">Manage copies →</a><button class="lb-btn" id="cp-toggle">${paused ? 'Resume' : 'Pause'}</button>- <button class="lb-btn" id="cp-edit">Edit size</button>+ <button class="lb-btn" id="cp-edit">${tripped ? 'Edit limit' : 'Edit size'}</button></div>`;$('#cp-toggle', el)?.addEventListener('click', async () => {const next = paused ? 'active' : 'paused';- const r = await api('/api/copy/subscriptions', { method: 'POST', body: JSON.stringify({ id: s.id, status: next }) });- if (r.ok) mountCopyPanel(el, { leaderAgentId, leaderName, network });+ const btn = $('#cp-toggle', el);+ const errEl = $('#cp-toggle-err', el);+ errEl.hidden = true;+ btn.disabled = true;+ const label = btn.textContent;+ btn.textContent = paused ? 'Resuming…' : 'Pausing…';+ try {+ const r = await api('/api/copy/subscriptions', { method: 'POST', body: JSON.stringify({ id: s.id, status: next }) });+ if (r.ok) return mountCopyPanel(el, { leaderAgentId, leaderName, network });+ // A refused resume used to do nothing at all, which read as a dead button.+ const data = await r.json().catch(() => ({}));+ showErr(errEl, data.error_description || 'Could not change this subscription.');+ } catch {+ showErr(errEl, 'Network error — try again.');+ }+ btn.disabled = false;+ btn.textContent = label;});$('#cp-edit', el)?.addEventListener('click', () => renderForm(el, { leaderAgentId, leaderName, network, prefill: s }));}@@ -139,6 +168,15 @@ function renderForm(el, { leaderAgentId, leaderName, network, prefill }) {</label></div>+ <div class="cp-row">+ <label class="cp-field">+ <span class="cp-label">Stop copying at drawdown (%)</span>+ <input class="cp-input" id="cp-dd" type="number" step="1" min="1" max="100" placeholder="never"+ value="${p.max_drawdown_pct ?? ''}" />+ <span class="cp-hint">Pause new copies if this trader falls this far below their best point, measured on their real closed trades. Exits you're already in still come through. Leave blank to ride it out.</span>+ </label>+ </div>+<details class="cp-advanced"><summary>Advanced filters</summary><div class="cp-row">@@ -207,6 +245,7 @@ function renderForm(el, { leaderAgentId, leaderName, network, prefill }) {mcap_floor_usd: $('#cp-mcf', el).value === '' ? null : num('cp-mcf'),mcap_ceiling_usd: $('#cp-mcc', el).value === '' ? null : num('cp-mcc'),min_oracle_score: $('#cp-oracle', el).value === '' ? null : Math.round(num('cp-oracle')),+ max_drawdown_pct: $('#cp-dd', el).value === '' ? null : num('cp-dd'),copy_sells: $('#cp-sells', el).checked,require_safety_pass: $('#cp-safe', el).checked,telegram_chat_id: (() => { const v = ($('#cp-tg', el)?.value || '').trim(); return /^-?[0-9]+$/.test(v) ? v : null; })(),@@ -217,7 +256,18 @@ function renderForm(el, { leaderAgentId, leaderName, network, prefill }) {try {const r = await api('/api/copy/subscriptions', { method: 'POST', body: JSON.stringify(body) });const data = await r.json().catch(() => ({}));- if (!r.ok) { btn.disabled = false; btn.textContent = prefill ? 'Save copy settings' : 'Start copying'; return showErr(errEl, data.message || 'Could not save.'); }+ if (!r.ok) {+ btn.disabled = false;+ btn.textContent = prefill ? 'Save copy settings' : 'Start copying';+ // A leader who has not earned a copyable record is not an error the+ // copier can retry — show exactly what is still missing instead.+ if (data.error === 'leader_not_copyable' && Array.isArray(data.eligibility?.unmet)) {+ return showEligibility(errEl, leaderName, data.eligibility);+ }+ // The API names its message error_description; reading `message` meant+ // every server refusal collapsed into the generic line below.+ return showErr(errEl, data.error_description || 'Could not save.');+ }mountCopyPanel(el, { leaderAgentId, leaderName, network });} catch {btn.disabled = false; btn.textContent = prefill ? 'Save copy settings' : 'Start copying';@@ -227,3 +277,19 @@ function renderForm(el, { leaderAgentId, leaderName, network, prefill }) {}function showErr(el, msg) { el.textContent = msg; el.hidden = false; }++/**+ * The copyable-bar refusal, as a checklist. A leader clears this by trading, so+ * the useful answer is which criteria are short and by how much — not "denied".+ */+function showEligibility(el, leaderName, eligibility) {+ const items = eligibility.unmet+ .map((u) => `<li>${escapeHtml(u.label)}</li>`)+ .join('');+ el.innerHTML = `+ <strong>${escapeHtml(leaderName || 'This trader')} can't be copied yet.</strong>+ A trader needs a real, closed, on-chain record before anyone can put money behind it. Still short:+ <ul class="cp-unmet">${items}</ul>+ Follow their profile and copy them once they clear it.`;+ el.hidden = false;+}diff --git a/src/ghost-copy.js b/src/ghost-copy.jsindex 3942d72cb..5675fb7a9 100644--- a/src/ghost-copy.js+++ b/src/ghost-copy.js@@ -5,9 +5,14 @@// in the URL (?leader&budget&window) so a result is deep-linkable and shareable,// which is the entire point: the artifact travels, the referral comes back.//-// Nothing on this page signs, spends, or connects a wallet. The only outbound-// actions are links to the leader's verified record and to the real (custodial--// guardrailed) copy surface at /vaults.+// The page itself signs and spends nothing: the replay is arithmetic over trades+// that already happened. The one live action is Fork (src/fork-trade.js) on a+// position the leader is STILL holding. That opens the real pump.fun trade+// panel at your ghost size, and your own wallet signs it. Everything else is a+// link out to the leader's verified record or the guardrailed copy surface at+// /vaults.++import { initFork, forkButton } from './fork-trade.js';const leadersEl = document.getElementById('gcLeaders');const resultEl = document.getElementById('gcResult');@@ -267,10 +272,10 @@ function renderResult(data) {const stillOpen = s.still_open_count ? `<section class="gc-section">- <h2>Still open <span>· marked at the leader's last on-chain quote, not realized</span></h2>+ <h2>Still open <span>· marked at the leader's last on-chain quote, not realized. Fork opens the real trade at your ghost size; your wallet signs it.</span></h2><div class="gc-tablewrap"><table class="gc-table">- <thead><tr><th scope="col">Coin</th><th scope="col">Your size</th><th scope="col">Mark</th><th scope="col">Unrealized</th><th scope="col">Opened</th></tr></thead>+ <thead><tr><th scope="col">Coin</th><th scope="col">Your size</th><th scope="col">Mark</th><th scope="col">Unrealized</th><th scope="col">Opened</th><th scope="col">For real</th></tr></thead><tbody>${data.still_open.map((o) => `<tr>@@ -279,6 +284,7 @@ function renderResult(data) {<td class="num ${tone(o.mark_pct)}">${o.mark_pct == null ? 'at cost' : pct(o.mark_pct)}</td><td class="num ${tone(o.unrealized_sol)}">${signed(o.unrealized_sol, 4)}</td><td>${esc(shortDate(o.opened_at))}</td>+ <td>${forkButton({ mint: o.mint, symbol: o.symbol, name: o.name, size: o.order_sol }, { className: 'gc-fork' })}</td></tr>`).join('')}</tbody></table>@@ -385,6 +391,9 @@ windowSeg.addEventListener('click', (e) => {});readUrl();+// Before writeUrl() rewrites the query string: an inbound ?fork=<mint> link+// opens the real trade panel on arrival.+initFork();budgetEl.value = String(state.budget);for (const b of windowSeg.querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.window === state.window));writeUrl();diff --git a/src/trader.css b/src/trader.cssindex a53417aa4..b3b94b96f 100644--- a/src/trader.css+++ b/src/trader.css@@ -241,6 +241,31 @@.cp-fine { color: var(--ink-faint); font-size: var(--text-2xs); margin: 0; }.cp-hint { display: block; font-size: var(--text-2xs); color: var(--ink-faint); margin-top: 4px; line-height: 1.4; }+/* Drawdown circuit breaker: the auto-pause notice, and the copyable-bar checklist.+ Both carry a left rule so they read as a status the system is reporting rather+ than as another paragraph of body copy. */+.cp-tripped {+ font-size: var(--text-xs);+ color: var(--ink-dim);+ line-height: 1.5;+ margin: 0 0 var(--space-sm);+ padding: var(--space-sm) var(--space-md);+ border-left: 2px solid var(--warn);+ border-radius: 0 var(--radius-sm) var(--radius-sm) 0;+ background: var(--surface-2);+}+.cp-tripped strong { display: block; color: var(--ink-bright); margin-bottom: 2px; }+.cp-err .cp-unmet {+ list-style: none;+ margin: var(--space-2xs) 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.cp-err .cp-unmet li { color: var(--ink-dim); }+.cp-err .cp-unmet li::before { content: "○ "; color: var(--ink-faint); }+/* ---- States / skeleton ---- */.tp-skel { border: 1px solid var(--stroke); border-radius: var(--radius-card); background: var(--surface-1); padding: var(--space-lg); }.tp-sk { height: 14px; border-radius: var(--radius-sm); background: linear-gradient(90deg, var(--surface-2) 25%, var(--surface-3) 37%, var(--surface-2) 63%); background-size: 400% 100%; animation: lb-shimmer 1.4s ease infinite; margin-bottom: var(--space-sm); }diff --git a/tests/alpha-drip.test.js b/tests/alpha-drip.test.jsnew file mode 100644index 000000000..f5b7dd2a1--- /dev/null+++ b/tests/alpha-drip.test.js@@ -0,0 +1,239 @@+/**+ * Alpha-drip — pure release-planning tests.+ *+ * Money-adjacent and trust-adjacent: a bug here either leaks a leader's signal+ * early or sells a holder a slower seat than the one below them, so every rule+ * the module promises is pinned.+ */++import { describe, it, expect } from 'vitest';+import {+ normalizeDripConfig, planRelease, planReleaseForUsd, dripDisclosure,+ describeSchedule, formatDelay, assessFairness, maxDelaySec, emptyDripConfig, applyCapacityCap, maskUnreleasedIntent,+ MAX_DELAY_SEC, TIER_IDS,+} from '../api/_lib/alpha-drip.js';++const ok = (raw) => {+ const r = normalizeDripConfig(raw);+ expect(r.ok, r.error).toBe(true);+ return r.value;+};++const ladder = {+ enabled: true,+ schedule: [+ { tier: 'gold', delay_sec: 0 },+ { tier: 'bronze', delay_sec: 20 },+ ],+ public_delay_sec: 60,+};++describe('normalizeDripConfig', () => {+ it('sorts the schedule high tier first', () => {+ const v = ok({ ...ladder, schedule: [{ tier: 'bronze', delay_sec: 20 }, { tier: 'genesis', delay_sec: 0 }] });+ expect(v.schedule.map((e) => e.tier)).toEqual(['genesis', 'bronze']);+ });++ it('defaults an unset cap to null and rounds a set one', () => {+ const v = ok({ ...ladder, schedule: [{ tier: 'gold', delay_sec: 0, max_copy_size_sol: 0.1234567 }] });+ expect(v.schedule[0].max_copy_size_sol).toBe(0.123457);+ const w = ok(ladder);+ expect(w.schedule[0].max_copy_size_sol).toBeNull();+ });++ it('rejects a tier that is not on the $THREE ladder', () => {+ expect(normalizeDripConfig({ ...ladder, schedule: [{ tier: 'platinum', delay_sec: 0 }] }))+ .toMatchObject({ ok: false });+ });++ it('rejects a duplicated tier', () => {+ expect(normalizeDripConfig({ ...ladder, schedule: [{ tier: 'gold', delay_sec: 0 }, { tier: 'gold', delay_sec: 5 }] }))+ .toMatchObject({ ok: false });+ });++ it('rejects a higher tier waiting longer than a lower one', () => {+ const r = normalizeDripConfig({+ enabled: true,+ schedule: [{ tier: 'gold', delay_sec: 30 }, { tier: 'bronze', delay_sec: 5 }],+ public_delay_sec: 60,+ });+ expect(r.ok).toBe(false);+ expect(r.error).toMatch(/never wait longer/);+ });++ it('rejects a public delay shorter than a paid tier', () => {+ const r = normalizeDripConfig({ enabled: true, schedule: [{ tier: 'bronze', delay_sec: 60 }], public_delay_sec: 10 });+ expect(r.ok).toBe(false);+ });++ it('rejects delays past the ceiling and below zero', () => {+ expect(normalizeDripConfig({ enabled: true, schedule: [{ tier: 'gold', delay_sec: MAX_DELAY_SEC + 1 }] }).ok).toBe(false);+ expect(normalizeDripConfig({ enabled: true, public_delay_sec: -1 }).ok).toBe(false);+ });++ it('refuses to enable a drip that delays nobody', () => {+ expect(normalizeDripConfig({ enabled: true, schedule: [], public_delay_sec: 0 }).ok).toBe(false);+ });++ it('accepts a disabled empty config (the off switch)', () => {+ const v = ok({ enabled: false, schedule: [], public_delay_sec: 0 });+ expect(v.enabled).toBe(false);+ });++ it('trims and caps free text', () => {+ const v = ok({ ...ladder, disclosure: ` ${'x'.repeat(400)} `, capacity_note: ' ' });+ expect(v.disclosure).toHaveLength(280);+ expect(v.capacity_note).toBeNull();+ });+});++describe('planRelease', () => {+ const cfg = ok(ladder);++ it('gives the top tier the priced instant seat', () => {+ expect(planRelease(cfg, 'genesis')).toMatchObject({ delay_sec: 0, matched_tier: 'gold' });+ });++ it('inherits the nearest lower priced tier', () => {+ expect(planRelease(cfg, 'silver')).toMatchObject({ delay_sec: 20, matched_tier: 'bronze' });+ });++ it('falls through to the public delay below the lowest priced tier', () => {+ expect(planRelease(cfg, 'member')).toMatchObject({ delay_sec: 60, matched_tier: null });+ });++ it('never delays when the leader has the drip off', () => {+ expect(planRelease({ ...cfg, enabled: false }, 'member').delay_sec).toBe(0);+ expect(planRelease(null, 'member').delay_sec).toBe(0);+ expect(planRelease(emptyDripConfig(), 'member').delay_sec).toBe(0);+ });++ it('treats an unknown tier id as the free floor', () => {+ expect(planRelease(cfg, 'nonsense')).toMatchObject({ delay_sec: 60, tier: TIER_IDS[0] });+ });++ it('is monotonic across the whole ladder', () => {+ const delays = TIER_IDS.map((t) => planRelease(cfg, t).delay_sec);+ for (let i = 1; i < delays.length; i++) expect(delays[i]).toBeLessThanOrEqual(delays[i - 1]);+ });++ it('carries the tier capacity cap through', () => {+ const capped = ok({ enabled: true, schedule: [{ tier: 'gold', delay_sec: 0, max_copy_size_sol: 0.25 }], public_delay_sec: 30 });+ expect(planRelease(capped, 'gold').max_copy_size_sol).toBe(0.25);+ expect(planRelease(capped, 'member').max_copy_size_sol).toBeNull();+ });++ it('resolves straight from USD held', () => {+ expect(planReleaseForUsd(cfg, 0).delay_sec).toBe(60);+ expect(planReleaseForUsd(cfg, 10_000).delay_sec).toBe(0);+ });+});++describe('disclosure and copy', () => {+ it('always appends the standing not-your-orderflow sentence', () => {+ const line = dripDisclosure(ok({ ...ladder, disclosure: 'Subscribers first.' }));+ expect(line).toMatch(/^Subscribers first\./);+ expect(line).toMatch(/not privileged access/);+ expect(line).toMatch(/public track record/);+ });++ it('has no disclosure to make when the drip is off', () => {+ expect(dripDisclosure(emptyDripConfig())).toBeNull();+ });++ it('describes the ladder longest wait last', () => {+ expect(describeSchedule(ok(ladder))).toBe('Gold+ instant, Bronze+ after 20s, everyone else after 1m.');+ expect(describeSchedule(emptyDripConfig())).toMatch(/same moment/);+ });++ it('formats delays the one way every surface prints', () => {+ expect(formatDelay(0)).toBe('0s');+ expect(formatDelay(45)).toBe('45s');+ expect(formatDelay(120)).toBe('2m');+ expect(formatDelay(150)).toBe('2m 30s');+ });+});++describe('assessFairness', () => {+ it('flags a slowest tier that outlives the edge', () => {+ const r = assessFairness(ok(ladder), 30);+ expect(r.fair).toBe(false);+ expect(r.warning).toMatch(/release to everyone at once/);+ });++ it('passes when the edge outlives the longest wait', () => {+ expect(assessFairness(ok(ladder), 600)).toMatchObject({ fair: true, warning: null });+ });++ it('cannot judge without a half-life, and says nothing rather than guessing', () => {+ expect(assessFairness(ok(ladder), null).warning).toBeNull();+ });++ it('reports the longest wait anyone serves', () => {+ expect(maxDelaySec(ok(ladder))).toBe(60);+ expect(maxDelaySec(emptyDripConfig())).toBe(0);+ });+});++describe('applyCapacityCap', () => {+ it('leaves an order under the cap alone', () => {+ expect(applyCapacityCap(0.1, 0.5, 0.02)).toEqual({ ok: true, order_sol: 0.1, capped: false });+ });++ it('clamps an order over the cap', () => {+ expect(applyCapacityCap(0.9, 0.25, 0.02)).toEqual({ ok: true, order_sol: 0.25, capped: true });+ });++ it('skips rather than filling below the copier\'s minimum', () => {+ expect(applyCapacityCap(0.9, 0.01, 0.05)).toMatchObject({ ok: false, reason: 'drip_capacity_cap' });+ });++ it('is a no-op with no cap, a zero cap, or a sell mirror', () => {+ expect(applyCapacityCap(0.4, null, 0.02).capped).toBe(false);+ expect(applyCapacityCap(0.4, 0, 0.02).capped).toBe(false);+ expect(applyCapacityCap(0, 0.25, 0.02).capped).toBe(false);+ });+});++describe('maskUnreleasedIntent', () => {+ const now = Date.UTC(2026, 8, 3, 12, 0, 0);+ const row = () => ({+ id: 'e1', status: 'pending', leader_agent_id: 'a1', leader_name: 'Nine',+ direction: 'buy', mint: 'THREEsynthetic1111', symbol: 'TICKER', name: 'Ticker',+ planned_sol: 0.2, leader_entry_sol: 1.5, safety: { market_cap_usd: 40000 },+ quote: { out: 1 }, leader_buy_sig: 'sig', drip_tier: 'member',+ visible_at: new Date(now + 45_000).toISOString(),+ });++ it('hides the coin and the size until the seat is reached', () => {+ const masked = maskUnreleasedIntent(row(), now);+ expect(masked.locked).toBe(true);+ expect(masked.unlocks_in_sec).toBe(45);+ for (const k of ['mint', 'symbol', 'name', 'planned_sol', 'leader_entry_sol', 'safety', 'quote', 'leader_buy_sig']) {+ expect(masked[k]).toBeNull();+ }+ });++ it('still names the leader and the direction — only the trade is held', () => {+ const masked = maskUnreleasedIntent(row(), now);+ expect(masked.leader_name).toBe('Nine');+ expect(masked.direction).toBe('buy');+ expect(masked.drip_tier).toBe('member');+ });++ it('unmasks itself the moment the reveal passes', () => {+ const masked = maskUnreleasedIntent(row(), now + 45_000);+ expect(masked.locked).toBe(false);+ expect(masked.mint).toBe('THREEsynthetic1111');+ });++ it('never masks a row with no drip applied', () => {+ expect(maskUnreleasedIntent({ ...row(), visible_at: null }, now).locked).toBe(false);+ });++ it('never hides history from the copier it belongs to', () => {+ for (const status of ['acted', 'dismissed', 'skipped', 'expired']) {+ expect(maskUnreleasedIntent({ ...row(), status }, now).locked).toBe(false);+ }+ });+});diff --git a/tests/copy-eligibility.test.js b/tests/copy-eligibility.test.jsnew file mode 100644index 000000000..a7fd82ec0--- /dev/null+++ b/tests/copy-eligibility.test.js@@ -0,0 +1,159 @@+/**+ * The copy-trading anti-gaming layer (api/_lib/copy-eligibility.js).+ *+ * Three defenses stand between a copier and the two ways copy-trading gets+ * gamed — a manufactured track record, and a leader who keeps trading on the way+ * down. These are the pure halves; tests/copy-subscribe-guards.test.js covers the+ * endpoint that enforces them.+ */++import { describe, it, expect } from 'vitest';+import {+ BREAKER_REASON,+ LEADER_ELIGIBILITY,+ evaluateDrawdownBreaker,+ evaluateLeaderEligibility,+ summarizeCopyProfile,+} from '../api/_lib/copy-eligibility.js';++const SOL = 1e9;+// A closed round-trip in the exact shape agent_sniper_positions hands back:+// lamport columns as bigint-safe values, closed_at as a timestamp.+const close = (pnlSol, entrySol, closedAt) => ({+ realized_pnl_lamports: Math.round(pnlSol * SOL),+ entry_quote_lamports: Math.round(entrySol * SOL),+ closed_at: closedAt,+});++const hoursAgo = (h) => new Date(Date.UTC(2026, 0, 10) - h * 3_600_000).toISOString();++describe('evaluateLeaderEligibility — the sybil bar on copyable status', () => {+ it('clears a leader with a real record', () => {+ const r = evaluateLeaderEligibility({ settled: 30, span_hours: 200, deployed_sol: 2.5 });+ expect(r.eligible).toBe(true);+ expect(r.unmet).toEqual([]);+ expect(r.met).toEqual({ settled: 30, span_hours: 200, deployed_sol: 2.5 });+ });++ it('refuses a leader with no history at all, naming every missing criterion', () => {+ const r = evaluateLeaderEligibility({ settled: 0, span_hours: 0, deployed_sol: 0 });+ expect(r.eligible).toBe(false);+ expect(r.unmet.map((u) => u.criterion).sort()).toEqual(['deployed_sol', 'settled', 'span_hours']);+ // The labels are what the UI shows, so they carry both numbers.+ expect(r.unmet.find((u) => u.criterion === 'settled').label).toBe('0 of 5 closed round-trips');+ });++ it('refuses a curve minted out of dust in one burst', () => {+ // The exact sybil shape: enough closes, but no elapsed time and no capital.+ const r = evaluateLeaderEligibility({ settled: 40, span_hours: 0.2, deployed_sol: 0.004 });+ expect(r.eligible).toBe(false);+ expect(r.unmet.map((u) => u.criterion).sort()).toEqual(['deployed_sol', 'span_hours']);+ });++ it('is a floor, not a curation filter: a losing leader with a real record still clears', () => {+ // Eligibility asks "is this record real?", never "is it good?". Hiding+ // losers is exactly the survivorship theater the whole surface refuses.+ expect(evaluateLeaderEligibility({ settled: 12, span_hours: 100, deployed_sol: 1 }).eligible).toBe(true);+ });++ it('treats missing fields as zero rather than passing them', () => {+ expect(evaluateLeaderEligibility({}).eligible).toBe(false);+ expect(evaluateLeaderEligibility().eligible).toBe(false);+ });++ it('holds the boundary exactly at the documented thresholds', () => {+ const at = {+ settled: LEADER_ELIGIBILITY.minSettled,+ span_hours: LEADER_ELIGIBILITY.minSpanHours,+ deployed_sol: LEADER_ELIGIBILITY.minDeployedSol,+ };+ expect(evaluateLeaderEligibility(at).eligible).toBe(true);+ expect(evaluateLeaderEligibility({ ...at, settled: at.settled - 1 }).eligible).toBe(false);+ });+});++describe('evaluateDrawdownBreaker — the copier\'s circuit breaker', () => {+ it('does nothing when the copier set no limit', () => {+ expect(evaluateDrawdownBreaker({ max_drawdown_pct: null }, 90).breached).toBe(false);+ expect(evaluateDrawdownBreaker({}, 90).breached).toBe(false);+ });++ it('treats a zero or negative limit as opted out, never as "pause immediately"', () => {+ expect(evaluateDrawdownBreaker({ max_drawdown_pct: 0 }, 5).breached).toBe(false);+ expect(evaluateDrawdownBreaker({ max_drawdown_pct: -10 }, 5).breached).toBe(false);+ });++ it('holds while the leader is inside the limit', () => {+ const r = evaluateDrawdownBreaker({ max_drawdown_pct: 40 }, 39.9);+ expect(r.breached).toBe(false);+ expect(r.drawdown_pct).toBe(39.9);+ expect(r.limit_pct).toBe(40);+ });++ it('trips at the limit and explains itself in the copier\'s own numbers', () => {+ const r = evaluateDrawdownBreaker({ max_drawdown_pct: 40 }, 52.348);+ expect(r.breached).toBe(true);+ expect(r.drawdown_pct).toBe(52.35);+ expect(r.detail).toContain('52.35%');+ expect(r.detail).toContain('40%');+ });++ it('never auto-pauses on an unmeasurable leader', () => {+ // A null drawdown means no capital was ever deployed. Pausing on "unknown"+ // would freeze every subscription the moment a leader's history is thin —+ // the eligibility bar is what keeps a history-less leader uncopyable.+ expect(evaluateDrawdownBreaker({ max_drawdown_pct: 10 }, null).breached).toBe(false);+ });++ it('exports the reason the fanout records and the resume path keys off', () => {+ expect(BREAKER_REASON).toBe('leader_drawdown_breach');+ });+});++describe('summarizeCopyProfile — the equity curve both defenses read', () => {+ it('returns an honest empty record for a leader who has closed nothing', () => {+ expect(summarizeCopyProfile([])).toMatchObject({+ settled: 0, deployed_sol: 0, span_hours: 0, max_drawdown_pct: null,+ });+ });++ it('measures peak-to-trough drawdown as a share of capital deployed', () => {+ // Equity walks +1 → +3 → +1 → +2 on 4 SOL deployed: peak 3, trough 1,+ // so the worst drawdown is 2 SOL of the 4 deployed = 50%.+ const rows = [+ close(1, 1, hoursAgo(96)),+ close(2, 1, hoursAgo(72)),+ close(-2, 1, hoursAgo(48)),+ close(1, 1, hoursAgo(24)),+ ];+ const p = summarizeCopyProfile(rows);+ expect(p.settled).toBe(4);+ expect(p.deployed_sol).toBe(4);+ expect(p.realized_pnl_sol).toBe(2);+ expect(p.max_drawdown_sol).toBe(2);+ expect(p.max_drawdown_pct).toBe(50);+ expect(p.span_hours).toBe(72);+ });++ it('reports zero drawdown for a leader who never gave back a peak', () => {+ const p = summarizeCopyProfile([close(1, 1, hoursAgo(48)), close(1, 1, hoursAgo(24))]);+ expect(p.max_drawdown_sol).toBe(0);+ expect(p.max_drawdown_pct).toBe(0);+ });++ it('leaves drawdown undefined rather than 0% when no capital was deployed', () => {+ // 0% would read as "this leader never drew down", which is a lie about a+ // leader who never risked anything.+ expect(summarizeCopyProfile([close(0, 0, hoursAgo(1))]).max_drawdown_pct).toBe(null);+ });++ it('caps drawdown at 100% of deployed capital', () => {+ const p = summarizeCopyProfile([close(5, 0.1, hoursAgo(48)), close(-5, 0.1, hoursAgo(24))]);+ expect(p.max_drawdown_pct).toBe(100);+ });++ it('spans the real window even when rows arrive out of order', () => {+ const p = summarizeCopyProfile([close(1, 1, hoursAgo(10)), close(1, 1, hoursAgo(100))]);+ expect(p.span_hours).toBe(90);+ });+});diff --git a/tests/copy-subscribe-guards.test.js b/tests/copy-subscribe-guards.test.jsnew file mode 100644index 000000000..6ed5c5fa3--- /dev/null+++ b/tests/copy-subscribe-guards.test.js@@ -0,0 +1,198 @@+/**+ * The two gates POST /api/copy/subscriptions runs before it will attach a+ * copier's money to a leader, and the resume path that the drawdown breaker+ * would otherwise turn into a dead button.+ *+ * 1. SELF-COPY. Following an agent you own routes the performance fee back to+ * yourself while inflating that leader's public copier count and its+ * "earned X for being copied" figure. There is no legitimate version of it.+ * 2. COPYABLE BAR. A leader with no real closed record cannot be followed, and+ * the refusal names every unmet criterion so the UI can say what is missing.+ * 3. RESUME. Resuming a breaker-paused subscription while the leader is still+ * past the copier's limit is refused, instead of un-pausing a row the next+ * fanout tick would immediately re-pause.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const LEADER = '33333333-3333-4333-8333-333333333333';+const SUB = '11111111-1111-4111-8111-111111111111';++let sessionUser = { id: 'copier-1' };+let leaderRow = [{ id: LEADER, user_id: 'owner-2', name: 'Steady', is_public: true }];+let pausedRow = [];+const sqlCalls = [];++vi.mock('../api/_lib/http.js', () => ({+ wrap: (fn) => fn,+ cors: () => false,+ method: () => true,+ readJson: async (req) => req.body ?? {},+ rateLimited: (res) => { res._json = { status: 429, body: { error: 'rate_limited' } }; return res; },+ error: (res, status, code, message, extra = {}) => {+ res._json = { status, body: { error: code, error_description: message, ...extra } };+ return res;+ },+ json: (res, status, body) => { res._json = { status, body }; return res; },+}));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: async () => ({ success: true }) },+ clientIp: () => '1.2.3.4',+}));+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: async () => sessionUser,+ authenticateBearer: async () => null,+ extractBearer: () => null,+}));+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));+vi.mock('../api/_lib/db.js', () => ({+ sql: (strings, ...values) => {+ const text = strings.join('?');+ sqlCalls.push({ text, values });+ if (text.includes('from agent_identities')) return Promise.resolve(leaderRow);+ if (text.includes('select id, network, leader_agent_id')) return Promise.resolve(pausedRow);+ if (text.includes('insert into copy_subscriptions')) {+ return Promise.resolve([{ id: SUB, leader_agent_id: LEADER, max_drawdown_pct: values.at(-2) }]);+ }+ if (text.includes('update copy_subscriptions set status')) {+ return Promise.resolve([{ id: values[0] === undefined ? SUB : SUB, status: values[0] }]);+ }+ return Promise.resolve([]);+ },+}));++// The leader's real closed-trade profile, swapped per test.+let profile = { settled: 30, span_hours: 200, deployed_sol: 2, max_drawdown_pct: 12 };+vi.mock('../api/_lib/copy-eligibility.js', async (importOriginal) => {+ const real = await importOriginal();+ return { ...real, leaderCopyProfile: async () => profile };+});++const subscriptions = (await import('../api/copy/subscriptions.js')).default;++const res = () => ({ setHeader() {}, _json: null });+const post = (body) => ({ method: 'POST', url: '/api/copy/subscriptions', headers: {}, body });++const validBody = (over = {}) => ({+ leader_agent_id: LEADER,+ copier_wallet: 'So11111111111111111111111111111111111111112',+ sizing_rule: 'fixed',+ fixed_sol: 0.1,+ per_trade_cap_sol: 0.5,+ daily_budget_sol: 1,+ ...over,+});++beforeEach(() => {+ sqlCalls.length = 0;+ sessionUser = { id: 'copier-1' };+ leaderRow = [{ id: LEADER, user_id: 'owner-2', name: 'Steady', is_public: true }];+ pausedRow = [];+ profile = { settled: 30, span_hours: 200, deployed_sol: 2, max_drawdown_pct: 12 };+});++describe('self-copy guard', () => {+ it('refuses a copier who owns the leader agent', async () => {+ leaderRow = [{ id: LEADER, user_id: 'copier-1', name: 'My Own Bot', is_public: true }];+ const r = res();+ await subscriptions(post(validBody()), r);+ expect(r._json.status).toBe(403);+ expect(r._json.body.error).toBe('self_copy');+ // Refused BEFORE any row is written — a wash-trade edge must never exist.+ expect(sqlCalls.some((c) => c.text.includes('insert into copy_subscriptions'))).toBe(false);+ });++ it('allows a copier following someone else\'s agent', async () => {+ const r = res();+ await subscriptions(post(validBody()), r);+ expect(r._json.status).toBe(200);+ expect(r._json.body.subscription).toMatchObject({ id: SUB });+ });+});++describe('copyable bar', () => {+ it('refuses a leader with no verified history and names what is missing', async () => {+ profile = { settled: 1, span_hours: 0, deployed_sol: 0.002, max_drawdown_pct: 28 };+ const r = res();+ await subscriptions(post(validBody()), r);+ expect(r._json.status).toBe(409);+ expect(r._json.body.error).toBe('leader_not_copyable');+ expect(r._json.body.error_description).toContain('1 of 5 closed round-trips');+ // The structured form is what the UI renders a checklist from.+ expect(r._json.body.eligibility.unmet.map((u) => u.criterion).sort())+ .toEqual(['deployed_sol', 'settled', 'span_hours']);+ expect(r._json.body.eligibility.requirements.minSettled).toBe(5);+ expect(sqlCalls.some((c) => c.text.includes('insert into copy_subscriptions'))).toBe(false);+ });++ it('still refuses a private or deleted leader before it ever asks for a profile', async () => {+ leaderRow = [];+ const r = res();+ await subscriptions(post(validBody()), r);+ expect(r._json.status).toBe(404);+ expect(r._json.body.error).toBe('leader_not_found');+ });+});++describe('drawdown limit', () => {+ it('persists the copier\'s limit on the subscription', async () => {+ const r = res();+ await subscriptions(post(validBody({ max_drawdown_pct: 35 })), r);+ expect(r._json.status).toBe(200);+ const insert = sqlCalls.find((c) => c.text.includes('insert into copy_subscriptions'));+ expect(insert.values).toContain(35);+ });++ it('rejects a limit outside 0-100 without writing anything', async () => {+ const r = res();+ await subscriptions(post(validBody({ max_drawdown_pct: 150 })), r);+ expect(r._json.status).toBe(400);+ expect(r._json.body.error).toBe('invalid_config');+ expect(sqlCalls.some((c) => c.text.includes('insert into copy_subscriptions'))).toBe(false);+ });+});++describe('resuming a breaker-paused subscription', () => {+ it('refuses while the leader is still past the copier\'s limit, and says what would clear it', async () => {+ pausedRow = [{+ id: SUB, network: 'mainnet', leader_agent_id: LEADER,+ max_drawdown_pct: 10, paused_reason: 'leader_drawdown_breach',+ }];+ profile = { settled: 30, span_hours: 200, deployed_sol: 2, max_drawdown_pct: 42 };+ const r = res();+ await subscriptions(post({ id: SUB, status: 'active' }), r);+ expect(r._json.status).toBe(409);+ expect(r._json.body.error).toBe('drawdown_still_breached');+ expect(r._json.body.error_description).toContain('Raise or clear your drawdown limit');+ expect(r._json.body.breaker.drawdown_pct).toBe(42);+ expect(sqlCalls.some((c) => c.text.includes('update copy_subscriptions set status'))).toBe(false);+ });++ it('resumes once the leader has recovered inside the limit', async () => {+ pausedRow = [{+ id: SUB, network: 'mainnet', leader_agent_id: LEADER,+ max_drawdown_pct: 50, paused_reason: 'leader_drawdown_breach',+ }];+ profile = { settled: 30, span_hours: 200, deployed_sol: 2, max_drawdown_pct: 12 };+ const r = res();+ await subscriptions(post({ id: SUB, status: 'active' }), r);+ expect(r._json.status).toBe(200);+ expect(sqlCalls.some((c) => c.text.includes('update copy_subscriptions set status'))).toBe(true);+ });++ it('does not re-check a subscription the copier paused themselves', async () => {+ // paused_reason is null for a manual pause, so resuming is unconditional.+ pausedRow = [{ id: SUB, network: 'mainnet', leader_agent_id: LEADER, max_drawdown_pct: 10, paused_reason: null }];+ profile = { settled: 30, span_hours: 200, deployed_sol: 2, max_drawdown_pct: 99 };+ const r = res();+ await subscriptions(post({ id: SUB, status: 'active' }), r);+ expect(r._json.status).toBe(200);+ });++ it('pausing never consults the breaker', async () => {+ const r = res();+ await subscriptions(post({ id: SUB, status: 'paused' }), r);+ expect(r._json.status).toBe(200);+ expect(sqlCalls.some((c) => c.text.includes('select id, network, leader_agent_id'))).toBe(false);+ });+});diff --git a/vercel.json b/vercel.jsonindex dc903b148..1779975e4 100644--- a/vercel.json+++ b/vercel.json@@ -3487,6 +3487,10 @@"src": "/api/copy/earnings","dest": "/api/copy/earnings.js"},+ {+ "src": "/api/copy/alpha-drip",+ "dest": "/api/copy/alpha-drip.js"+ },{"src": "/api/copy/settle-fee","dest": "/api/copy/settle-fee.js"