Skip to content

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.

feat(growth-programs): ship the big-win X poster, first-rug softener and early-leader bonus, all disarmed

nirholas221b39d9badb
diff --git a/CLAUDE.md b/CLAUDE.md
index 564c648a9..7029b9e06 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -311,7 +311,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.
- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).
- 3D: Three.js with glTF/GLB.
- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.
-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (121 as of 2026-09-24, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (123 as of 2026-09-29, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.
- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).
- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.
- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.
diff --git a/README.md b/README.md
index ae287d588..cdec05ce3 100644
--- a/README.md
+++ b/README.md
@@ -9996,7 +9996,7 @@ The full OpenAPI 3.1 spec is available at `/openapi.json`. The key API surface i
Cron schedules are declared in `vercel.json` (still the live cron/route config the server reads) and executed in production by **Google Cloud Scheduler**, which calls each endpoint on its schedule. All cron endpoints are fail-closed — a missing auth token aborts with an error rather than silently skipping (see [Security Hardening](#security-hardening)).
-The crons in `vercel.json` (121 entries on 2026-09-24) are routed through a single dynamic handler at [`api/cron/[name].js`](api/cron/[name].js); the `name` segment selects the handler function. Scheduler jobs are provisioned from the `vercel.json` cron list via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs). The table below is a selection of the notable jobs, each schedule quoted verbatim from `vercel.json`; that file is the complete list.
+The crons in `vercel.json` (123 entries on 2026-09-29) are routed through a single dynamic handler at [`api/cron/[name].js`](api/cron/[name].js); the `name` segment selects the handler function. Scheduler jobs are provisioned from the `vercel.json` cron list via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs). The table below is a selection of the notable jobs, each schedule quoted verbatim from `vercel.json`; that file is the complete list.
| Schedule | Endpoint | Purpose |
| -------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
diff --git a/api/_lib/growth-programs/big-win-x.js b/api/_lib/growth-programs/big-win-x.js
new file mode 100644
index 000000000..11310a58d
--- /dev/null
+++ b/api/_lib/growth-programs/big-win-x.js
@@ -0,0 +1,314 @@
+// @ts-check
+// Big-win auto-poster for @trythreews (roadmap 917, 3.8 and 13.5).
+//
+// When a live agent trade closes as a meaningful win, post it to X with a link
+// to its trade card (/trade/:id, rendered by api/trade-share.js with the OG
+// image from api/trade-og.js), so the numbers that unfurl are the on-chain
+// numbers. Telegram copy intents already shipped; this is the X leg.
+//
+// Posting to a public feed with no human in the loop is owner gate 2, so the
+// lane ships disarmed: BIG_WIN_X_ENABLED unset means every tick is a dry run
+// that reports exactly which trade it would post and the exact text, and
+// writes nothing.
+//
+// What may be posted, and why (every rule is a guard below):
+// - Live fills only. A paper fill is a simulation; calling it a win on a
+// public feed would be a lie. Both legs must carry real signatures.
+// - Big AND sized: at least minPct return, minEntrySol deployed, minPnlSol
+// realized. A +200% on a 0.001 SOL test fill is not news.
+// - Public agents only, never P&L on a coin the owner launched (the
+// self-dealing rule from trader-stats.js).
+// - $THREE is the only coin the account promotes, so the post never names
+// the traded coin: no ticker, no cashtag, no mint. The card carries the
+// detail for anyone who clicks.
+// - The composed text must pass the same content filter as the changelog X
+// lane (data/changelog-x-filter.json: no wallet internals, no money
+// movement internals, no other coins, no gated project names) and the
+// account's voice lint (api/_lib/x-content/quality.js). The agent's name is
+// user-controlled, so a name carrying a cashtag, handle, hashtag, or link
+// disqualifies the post rather than being passed through.
+// - Rate: one post per run, dailyCap per 24h, one per agent per
+// perAgentHours, and never past accountDailyCap across every automated
+// lane on the account (changelog replies and the content queue included).
+
+import { sql as defaultSql } from '../db.js';
+import { shapeTradeCard, SIMULATED_SIG } from '../trade-card.js';
+import { loadXFilter, classifyXError } from '../changelog-push.js';
+import { copyProblems, hasUrl } from '../x-content/quality.js';
+import { selfDealMintsByUsers } from '../trader-stats.js';
+
+const STATE_KEY = 'big_win_x';
+const LOCK_KEY = 'big_win_x_lock';
+const LOCK_TTL_S = 180;
+const DAY_MS = 86_400_000;
+const HOUR_MS = 3_600_000;
+const ORIGIN = 'https://three.ws';
+
+const realSig = (s) => typeof s === 'string' && s.trim() !== '' && s.trim() !== SIMULATED_SIG;
+const lamToSol = (v) => (v == null ? null : Number(v) / 1e9);
+
+/** SOL for a post: plain text, three decimals, no glyphs. */
+export function solText(v) {
+ const x = Number(v);
+ if (!Number.isFinite(x)) return null;
+ return `${x.toFixed(3)} SOL`;
+}
+
+/**
+ * Why a closed position is not a postable big win, or null when it is. PURE.
+ * @param {object} row position joined to its agent (see candidateRows)
+ * @param {object} cfg programConfig().bigWinX
+ * @param {{ selfDealing?: boolean }} [ctx]
+ */
+export function bigWinRejection(row, cfg, { selfDealing = false } = {}) {
+ if (!realSig(row.buy_sig) || !realSig(row.sell_sig)) return 'paper_or_unsigned';
+ if (row.network !== 'mainnet') return 'not_mainnet';
+ if (row.is_public !== true) return 'agent_private';
+ if (row.exit_reason === 'error') return 'closed_on_error';
+ if (selfDealing) return 'self_dealing';
+ const pct = Number(row.realized_pnl_pct);
+ if (!(pct >= cfg.minPct)) return `below_min_pct (${Number.isFinite(pct) ? pct.toFixed(1) : 'n/a'}% < ${cfg.minPct}%)`;
+ const entry = lamToSol(row.entry_quote_lamports) ?? 0;
+ if (!(entry >= cfg.minEntrySol)) return `below_min_entry (${entry.toFixed(4)} < ${cfg.minEntrySol} SOL)`;
+ const pnl = lamToSol(row.realized_pnl_lamports) ?? 0;
+ if (!(pnl >= cfg.minPnlSol)) return `below_min_pnl (${pnl.toFixed(4)} < ${cfg.minPnlSol} SOL)`;
+ return null;
+}
+
+/** The agent name, if it is safe to print on the account; else null. PURE. */
+export function safeAgentName(name) {
+ const s = String(name || '').trim();
+ if (!s || s.length > 40) return null;
+ if (/[$@#<>]/.test(s) || hasUrl(s)) return null;
+ return s;
+}
+
+/**
+ * Compose the post. PURE. The coin is never named: the card carries it.
+ * @param {ReturnType<typeof shapeTradeCard>} card
+ */
+export function composeBigWinPost(card) {
+ const name = safeAgentName(card.agentName);
+ if (!name) return null;
+ const mult = card.multipleLabel ? ` (${card.multipleLabel})` : '';
+ const held = card.holdLabel ? ` in ${card.holdLabel}` : '';
+ const legs = [solText(card.entrySol) && `${solText(card.entrySol)} in`, solText(card.exitSol) && `${solText(card.exitSol)} out`]
+ .filter(Boolean)
+ .join(', ');
+ const moonbag = card.moonbag ? ' A moon-bag is still riding.' : '';
+ return [
+ `${name} closed a live pump.fun trade at ${card.headline}${mult}${held}: ${legs}.${moonbag} Both legs link to their on-chain transactions on the card.`,
+ '',
+ `${ORIGIN}/trade/${card.id}`,
+ ].join('\n');
+}
+
+/**
+ * Every reason the composed text must not go out. PURE given a filter.
+ * @param {string} text
+ * @param {{ patterns: Array<{pattern:string, reason:string}> }} filter
+ */
+export function bigWinContentProblems(text, filter) {
+ const problems = copyProblems(text, { minimum: 60, maximum: 280, requireUrl: true });
+ for (const rule of filter.patterns || []) {
+ if (new RegExp(rule.pattern, 'i').test(text)) problems.push(`filter: ${rule.reason}`);
+ }
+ return problems;
+}
+
+/** Candidate closes in the lookback window, wide enough to show near misses. */
+async function candidateRows(cfg, sql) {
+ return sql`
+ select p.id, p.agent_id, p.user_id, p.network, p.mint, p.symbol, p.name, p.status, p.exit_reason,
+ p.entry_quote_lamports, p.exit_quote_lamports, p.realized_pnl_lamports, p.realized_pnl_pct,
+ p.buy_sig, p.sell_sig, p.moonbag_base_amount, p.moonbag_last_value_lamports,
+ p.opened_at, p.closed_at,
+ a.name as agent_name, a.profile_image_url as agent_image, a.avatar_url as agent_avatar, a.is_public
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id and a.deleted_at is null
+ where p.status = 'closed' and p.network = 'mainnet'
+ and p.closed_at >= now() - make_interval(hours => ${cfg.lookbackHours})
+ and p.realized_pnl_pct >= 50
+ order by p.realized_pnl_lamports desc nulls last
+ limit 100
+ `;
+}
+
+async function readSetting(key, sql) {
+ const [row] = await sql`select value from app_settings where key = ${key}`.catch(() => []);
+ return row?.value ?? null;
+}
+
+async function writeSetting(key, value, sql) {
+ await sql`
+ insert into app_settings (key, value) values (${key}, ${JSON.stringify(value)}::jsonb)
+ on conflict (key) do update set value = excluded.value, updated_at = now()
+ `;
+}
+
+/**
+ * Posts in the trailing 24h across every automated lane on the account. PURE.
+ * @param {{ lane: any, changelog: any, content: any }} states
+ */
+export function accountPostsLast24h({ lane, changelog, content }, now = Date.now()) {
+ const inDay = (t) => Number.isFinite(t) && now - t < DAY_MS;
+ const laneRecent = (lane?.recent || []).filter(inDay).length;
+ const changelogRecent = (changelog?.recent || []).filter(inDay).length;
+ const contentRecent = (content?.published || []).map((p) => Date.parse(p?.publishedAt)).filter(inDay).length;
+ return { lane: laneRecent, changelog: changelogRecent, content: contentRecent, total: laneRecent + changelogRecent + contentRecent };
+}
+
+/**
+ * Select what this tick would post. Pure over its inputs (rows, state, time).
+ * @returns {{ pick: object|null, considered: object[], blocked: string|null }}
+ */
+export function selectBigWin({ rows, cfg, state, budget, filter, selfDealByUser, now = Date.now() }) {
+ const posted = new Set(state?.posted || []);
+ const perAgent = state?.perAgent || {};
+ const considered = [];
+ let pick = null;
+ for (const row of rows) {
+ const own = selfDealByUser?.get(row.user_id);
+ const card = shapeTradeCard(row, { origin: ORIGIN });
+ const entry = {
+ position_id: row.id,
+ agent: row.agent_name,
+ pnl_pct: card.pnlPct,
+ entry_sol: card.entrySol,
+ pnl_sol: card.pnlSol,
+ closed_at: row.closed_at,
+ card_url: card.shareUrl,
+ reason: null,
+ text: null,
+ problems: [],
+ };
+ entry.reason = bigWinRejection(row, cfg, { selfDealing: Boolean(own && own.has(row.mint)) });
+ if (!entry.reason && posted.has(row.id)) entry.reason = 'already_posted';
+ if (!entry.reason && perAgent[row.agent_id] && now - perAgent[row.agent_id] < cfg.perAgentHours * HOUR_MS) {
+ entry.reason = `agent_posted_within_${cfg.perAgentHours}h`;
+ }
+ if (!entry.reason) {
+ const text = composeBigWinPost(card);
+ if (!text) entry.reason = 'agent_name_unsafe';
+ else {
+ entry.text = text;
+ entry.problems = bigWinContentProblems(text, filter);
+ if (entry.problems.length) entry.reason = 'content_filter';
+ }
+ }
+ if (!entry.reason && !pick) pick = entry;
+ considered.push(entry);
+ }
+ let blocked = null;
+ if (budget.lane >= cfg.dailyCap) blocked = `daily_cap (${budget.lane}/${cfg.dailyCap} in 24h)`;
+ else if (budget.total >= cfg.accountDailyCap) blocked = `account_daily_cap (${budget.total}/${cfg.accountDailyCap} across all lanes in 24h)`;
+ else if (state?.backoffUntil && state.backoffUntil > now) blocked = `rate_limited until ${new Date(state.backoffUntil).toISOString()}`;
+ return { pick, considered, blocked };
+}
+
+async function acquireLock(sql) {
+ const rows = await sql`
+ insert into app_settings (key, value)
+ values (${LOCK_KEY}, jsonb_build_object('until', extract(epoch from now()) + ${LOCK_TTL_S}))
+ on conflict (key) do update
+ set value = excluded.value, updated_at = now()
+ where (app_settings.value->>'until')::numeric < extract(epoch from now())
+ returning key
+ `;
+ return rows.length > 0;
+}
+
+function xCreds(env) {
+ const creds = {
+ appKey: env.X_API_KEY,
+ appSecret: env.X_API_SECRET,
+ accessToken: env.X_ACCESS_TOKEN,
+ accessSecret: env.X_ACCESS_SECRET,
+ };
+ return creds.appKey && creds.appSecret && creds.accessToken && creds.accessSecret ? creds : null;
+}
+
+async function defaultPoster(creds) {
+ const { TwitterApi } = await import('twitter-api-v2');
+ const client = new TwitterApi(creds);
+ return async (text) => {
+ const { data } = await client.v2.tweet(text);
+ return data.id;
+ };
+}
+
+/**
+ * One tick of the lane.
+ * @param {object} p
+ * @param {object} p.cfg programConfig().bigWinX
+ * @param {Function} [p.sql]
+ * @param {Record<string,string|undefined>} [p.env]
+ * @param {(creds:object) => Promise<(text:string) => Promise<string>>} [p.makePoster] injected in tests
+ * @param {number} [p.now]
+ */
+export async function runBigWinLane({ cfg, sql = defaultSql, env = process.env, makePoster = defaultPoster, now = Date.now() }) {
+ const [rows, lane, changelog, content] = await Promise.all([
+ candidateRows(cfg, sql),
+ readSetting(STATE_KEY, sql),
+ readSetting('changelog_push_x', sql),
+ readSetting('x_content', sql),
+ ]);
+ const state = lane || { posted: [], recent: [], perAgent: {} };
+ const budget = accountPostsLast24h({ lane: state, changelog, content }, now);
+ const selfDealByUser = await selfDealMintsByUsers([...new Set(rows.map((r) => r.user_id))], 'mainnet');
+ const filter = loadXFilter();
+ const { pick, considered, blocked } = selectBigWin({ rows, cfg, state, budget, filter, selfDealByUser, now });
+
+ const report = {
+ lane: 'big_win_x',
+ armed: cfg.enabled,
+ thresholds: { min_pct: cfg.minPct, min_entry_sol: cfg.minEntrySol, min_pnl_sol: cfg.minPnlSol, lookback_hours: cfg.lookbackHours },
+ budget: { ...budget, daily_cap: cfg.dailyCap, account_daily_cap: cfg.accountDailyCap },
+ would_post: pick ? { position_id: pick.position_id, text: pick.text, card_url: pick.card_url } : null,
+ blocked,
+ considered,
+ };
+
+ if (!cfg.enabled) return { ...report, executed: false, reason: `${cfg.flag} is not set, so nothing is posted` };
+ if (!pick) return { ...report, executed: false, reason: 'no qualifying win in the window' };
+ if (blocked) return { ...report, executed: false, reason: blocked };
+ const creds = xCreds(env);
+ if (!creds) return { ...report, executed: false, reason: 'X credentials not configured' };
+ if (!(await acquireLock(sql))) return { ...report, executed: false, reason: 'another tick holds the lane lock' };
+
+ try {
+ const post = await makePoster(creds);
+ const next = {
+ posted: [...(state.posted || []), pick.position_id].slice(-500),
+ recent: (state.recent || []).filter((t) => now - t < DAY_MS),
+ perAgent: Object.fromEntries(Object.entries(state.perAgent || {}).filter(([, t]) => now - Number(t) < 30 * DAY_MS)),
+ backoffUntil: 0,
+ lastError: null,
+ lastPostAt: state.lastPostAt || null,
+ lastPostId: state.lastPostId || null,
+ };
+ const agentId = rows.find((r) => r.id === pick.position_id)?.agent_id;
+ try {
+ const id = await post(pick.text);
+ next.recent.push(now);
+ if (agentId) next.perAgent[agentId] = now;
+ next.lastPostAt = new Date(now).toISOString();
+ next.lastPostId = id;
+ await writeSetting(STATE_KEY, next, sql);
+ return { ...report, executed: true, posted: { position_id: pick.position_id, tweet_id: id } };
+ } catch (err) {
+ const verdict = classifyXError(err, now);
+ if (verdict.kind === 'duplicate') {
+ // X already holds this exact text; mark it so it never blocks the lane.
+ await writeSetting(STATE_KEY, next, sql);
+ return { ...report, executed: false, reason: 'duplicate content, marked posted' };
+ }
+ const failed = { ...next, posted: state.posted || [], lastError: String(err?.message || err).slice(0, 300) };
+ if (verdict.kind === 'rate_limited') failed.backoffUntil = verdict.until;
+ await writeSetting(STATE_KEY, failed, sql);
+ return { ...report, executed: false, reason: `post failed (${verdict.kind}): ${failed.lastError}` };
+ }
+ } finally {
+ await sql`update app_settings set value = '{"until":0}'::jsonb, updated_at = now() where key = ${LOCK_KEY}`.catch(() => {});
+ }
+}
diff --git a/api/_lib/growth-programs/config.js b/api/_lib/growth-programs/config.js
new file mode 100644
index 000000000..d2d43536d
--- /dev/null
+++ b/api/_lib/growth-programs/config.js
@@ -0,0 +1,108 @@
+// @ts-check
+// Trading growth programs: the arm flags and caps for the three owner-gated
+// levers of the pump.fun trading roadmap (917 sections 3.8, 12.15, 13.4).
+//
+// big_win_x posts notable live wins to @trythreews (owner gate 2)
+// rug_softener pays $THREE toward a first-timer's first rug (owner gate 1)
+// early_leader pays $THREE bonuses to the first N leaders (owner gate 1)
+//
+// Every program ships DISARMED. The selection logic always runs on real data
+// and is inspectable (GET /api/ops/growth-programs, the crons' dry-run output,
+// scripts/growth-programs-report.mjs), but the side-effecting leg only runs
+// when its flag is exactly "1" or "true". Anything else, including unset, a
+// typo, or "yes", reads as off: a flag that moves money fails closed.
+//
+// Every numeric knob has a code ceiling. An env var can lower a cap, never
+// raise it past the ceiling, so a fat-fingered "RUG_SOFTENER_DAILY_CAP_USD=10000"
+// still pays at most the ceiling. Raising a ceiling is a code change, reviewed
+// in git, which is the point.
+
+/** Read a flag strictly. Only "1" and "true" arm; everything else is off. */
+export function flagOn(name, env = process.env) {
+ const v = String(env[name] ?? '').trim().toLowerCase();
+ return v === '1' || v === 'true';
+}
+
+/**
+ * A number from env, clamped into [min, ceiling], or the default when unset or
+ * unparseable. The default itself is clamped too, so a default can never sit
+ * above its own ceiling.
+ */
+export function boundedNumber(env, name, { def, min = 0, ceiling }) {
+ const raw = env[name];
+ const parsed = raw == null || String(raw).trim() === '' ? NaN : Number(raw);
+ const value = Number.isFinite(parsed) ? parsed : def;
+ return Math.min(ceiling, Math.max(min, value));
+}
+
+/** Hard ceilings. Env can lower these, never raise them. */
+export const CEILINGS = Object.freeze({
+ bigWin: {
+ dailyCap: 4, // posts per 24h from this lane
+ accountDailyCap: 15, // posts per 24h across every automated lane on the account
+ lookbackHours: 72,
+ },
+ rugSoftener: {
+ reimbursePct: 50,
+ maxPerClaimUsd: 100,
+ dailyCapUsd: 500,
+ claimWindowDays: 30,
+ },
+ earlyLeader: {
+ slots: 50,
+ bonusUsd: 250,
+ weeklyCapUsd: 1000,
+ },
+});
+
+/**
+ * Resolve every program's configuration from the environment.
+ * @param {Record<string, string|undefined>} [env]
+ */
+export function programConfig(env = process.env) {
+ return {
+ bigWinX: {
+ flag: 'BIG_WIN_X_ENABLED',
+ enabled: flagOn('BIG_WIN_X_ENABLED', env),
+ // A "big win" is a live, closed, meaningfully sized trade that at least
+ // doubled. A +200% on a 0.001 SOL test fill is not news, so size gates
+ // sit beside the percentage.
+ minPct: boundedNumber(env, 'BIG_WIN_X_MIN_PCT', { def: 100, min: 50, ceiling: 100_000 }),
+ minEntrySol: boundedNumber(env, 'BIG_WIN_X_MIN_ENTRY_SOL', { def: 0.1, min: 0.01, ceiling: 1000 }),
+ minPnlSol: boundedNumber(env, 'BIG_WIN_X_MIN_PNL_SOL', { def: 0.1, min: 0.01, ceiling: 1000 }),
+ lookbackHours: boundedNumber(env, 'BIG_WIN_X_LOOKBACK_HOURS', { def: 24, min: 1, ceiling: CEILINGS.bigWin.lookbackHours }),
+ dailyCap: Math.floor(boundedNumber(env, 'BIG_WIN_X_DAILY_CAP', { def: 2, min: 0, ceiling: CEILINGS.bigWin.dailyCap })),
+ perAgentHours: boundedNumber(env, 'BIG_WIN_X_PER_AGENT_HOURS', { def: 24, min: 1, ceiling: 24 * 30 }),
+ accountDailyCap: Math.floor(
+ boundedNumber(env, 'BIG_WIN_X_ACCOUNT_DAILY_CAP', { def: 15, min: 0, ceiling: CEILINGS.bigWin.accountDailyCap }),
+ ),
+ },
+ rugSoftener: {
+ flag: 'RUG_SOFTENER_ENABLED',
+ enabled: flagOn('RUG_SOFTENER_ENABLED', env),
+ reimbursePct: boundedNumber(env, 'RUG_SOFTENER_REIMBURSE_PCT', { def: 50, min: 1, ceiling: CEILINGS.rugSoftener.reimbursePct }),
+ maxPerClaimUsd: boundedNumber(env, 'RUG_SOFTENER_MAX_PER_CLAIM_USD', { def: 25, min: 1, ceiling: CEILINGS.rugSoftener.maxPerClaimUsd }),
+ dailyCapUsd: boundedNumber(env, 'RUG_SOFTENER_DAILY_CAP_USD', { def: 100, min: 0, ceiling: CEILINGS.rugSoftener.dailyCapUsd }),
+ minLossSol: boundedNumber(env, 'RUG_SOFTENER_MIN_LOSS_SOL', { def: 0.02, min: 0.005, ceiling: 100 }),
+ minEntrySol: boundedNumber(env, 'RUG_SOFTENER_MIN_ENTRY_SOL', { def: 0.05, min: 0.01, ceiling: 100 }),
+ claimWindowDays: boundedNumber(env, 'RUG_SOFTENER_CLAIM_WINDOW_DAYS', { def: 14, min: 1, ceiling: CEILINGS.rugSoftener.claimWindowDays }),
+ minAccountAgeHours: boundedNumber(env, 'RUG_SOFTENER_MIN_ACCOUNT_AGE_HOURS', { def: 24, min: 1, ceiling: 24 * 365 }),
+ },
+ earlyLeader: {
+ flag: 'EARLY_LEADER_ENABLED',
+ enabled: flagOn('EARLY_LEADER_ENABLED', env),
+ slots: Math.floor(boundedNumber(env, 'EARLY_LEADER_SLOTS', { def: 20, min: 0, ceiling: CEILINGS.earlyLeader.slots })),
+ bonusUsd: boundedNumber(env, 'EARLY_LEADER_BONUS_USD', { def: 50, min: 1, ceiling: CEILINGS.earlyLeader.bonusUsd }),
+ weeklyCapUsd: boundedNumber(env, 'EARLY_LEADER_WEEKLY_CAP_USD', { def: 250, min: 0, ceiling: CEILINGS.earlyLeader.weeklyCapUsd }),
+ minSettled: Math.floor(boundedNumber(env, 'EARLY_LEADER_MIN_SETTLED', { def: 30, min: 5, ceiling: 10_000 })),
+ minSpanDays: boundedNumber(env, 'EARLY_LEADER_MIN_SPAN_DAYS', { def: 30, min: 1, ceiling: 365 }),
+ minWinRatePct: boundedNumber(env, 'EARLY_LEADER_MIN_WIN_RATE_PCT', { def: 55, min: 50, ceiling: 100 }),
+ minDeployedSol: boundedNumber(env, 'EARLY_LEADER_MIN_DEPLOYED_SOL', { def: 1, min: 0.1, ceiling: 10_000 }),
+ maxDrawdownPct: boundedNumber(env, 'EARLY_LEADER_MAX_DRAWDOWN_PCT', { def: 50, min: 1, ceiling: 100 }),
+ minFollowers: Math.floor(boundedNumber(env, 'EARLY_LEADER_MIN_FOLLOWERS', { def: 1, min: 1, ceiling: 1000 })),
+ },
+ };
+}
+
+/** The program names, as stored in growth_program_payouts.program. */
+export const PAYOUT_PROGRAMS = Object.freeze(['rug_softener', 'early_leader']);
diff --git a/api/_lib/growth-programs/early-leaders.js b/api/_lib/growth-programs/early-leaders.js
new file mode 100644
index 000000000..8f4133f38
--- /dev/null
+++ b/api/_lib/growth-programs/early-leaders.js
@@ -0,0 +1,263 @@
+// @ts-check
+// Early-leader program (roadmap 917, 13.4): a bounded $THREE bonus for the
+// first N traders who build a verified record that followers actually profit
+// from. It exists to manufacture a supply of credible leaders before organic
+// copy demand does.
+//
+// "Verified" here means the same truth layer the Trader Card and the copy
+// eligibility bar use, never a self-reported number:
+//
+// record live (non-paper) closed round-trips on mainnet from
+// agent_sniper_positions, leaving out P&L on the trader's own
+// coins, the self-dealing rule that trader-stats.js applies
+// thresholds at least minSettled closes spanning minSpanDays, a win rate of
+// at least minWinRatePct, at least minDeployedSol deployed,
+// positive realized P&L, a max drawdown at or under
+// maxDrawdownPct, and the copyable bar in copy-eligibility.js
+// followers at least minFollowers distinct copiers (never the leader's own
+// account) with closed copies, whose net copy profit is >= 0,
+// measured the way copy-earnings.js bills performance fees
+// one slot per owner account, never a platform or service account, only
+// public agents with a Solana wallet to pay
+//
+// "First N" is by qualification time: the close at which the record FIRST
+// cleared every trading threshold. Slots already taken in the ledger are kept.
+
+import { sql as defaultSql } from '../db.js';
+import { LEADER_ELIGIBILITY, evaluateLeaderEligibility, summarizeCopyProfile } from '../copy-eligibility.js';
+import { selfDealMintsByUsers } from '../trader-stats.js';
+
+const DAY_MS = 86_400_000;
+const round2 = (x) => Math.round(x * 100) / 100;
+const round4 = (x) => Math.round(x * 1e4) / 1e4;
+const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
+
+/**
+ * The first close at which a record met every trading threshold, walking
+ * cumulative stats in close order. PURE.
+ *
+ * @param {Array<{ realized_pnl_lamports:*, entry_quote_lamports:*, closed_at:* }>} rows oldest first
+ * @param {object} cfg programConfig().earlyLeader
+ * @returns {string|null} ISO time, or null if the record never qualified
+ */
+export function qualifiedAt(rows, cfg) {
+ let wins = 0;
+ let deployed = 0;
+ let pnl = 0;
+ let peak = 0;
+ let maxDd = 0;
+ let first = null;
+ for (let i = 0; i < rows.length; i++) {
+ const r = rows[i];
+ const p = n(r.realized_pnl_lamports) / 1e9;
+ deployed += n(r.entry_quote_lamports) / 1e9;
+ pnl += p;
+ if (p > 0) wins += 1;
+ if (pnl > peak) peak = pnl;
+ maxDd = Math.max(maxDd, peak - pnl);
+ const at = new Date(r.closed_at).getTime();
+ if (first == null) first = at;
+ const settled = i + 1;
+ const spanDays = (at - first) / DAY_MS;
+ const ddPct = deployed > 0 ? (maxDd / deployed) * 100 : 100;
+ if (
+ settled >= cfg.minSettled &&
+ spanDays >= cfg.minSpanDays &&
+ (wins / settled) * 100 >= cfg.minWinRatePct &&
+ deployed >= cfg.minDeployedSol &&
+ pnl > 0 &&
+ ddPct <= cfg.maxDrawdownPct
+ ) {
+ return new Date(at).toISOString();
+ }
+ }
+ return null;
+}
+
+/**
+ * Judge one leader's current record. PURE.
+ *
+ * @param {object} rec
+ * @param {Array} rec.rows closed live positions, oldest first, self-dealing removed
+ * @param {{ followers:number, net_profit_sol:number }} rec.followers
+ * @param {{ is_public:boolean, wallet:string|null, platform:boolean }} rec.agent
+ * @param {object} cfg
+ */
+export function evaluateEarlyLeader(rec, cfg) {
+ const rows = rec.rows || [];
+ const profile = summarizeCopyProfile(rows);
+ const wins = rows.filter((r) => n(r.realized_pnl_lamports) > 0).length;
+ const winRate = rows.length ? (wins / rows.length) * 100 : 0;
+ const spanDays = profile.span_hours / 24;
+
+ const unmet = [];
+ const need = (ok, criterion, label) => {
+ if (!ok) unmet.push({ criterion, label });
+ };
+ need(profile.settled >= cfg.minSettled, 'settled', `${profile.settled} of ${cfg.minSettled} live closed trades`);
+ need(spanDays >= cfg.minSpanDays, 'span_days', `${round2(spanDays)} of ${cfg.minSpanDays} days of history`);
+ need(winRate >= cfg.minWinRatePct, 'win_rate', `${round2(winRate)}% of ${cfg.minWinRatePct}% win rate`);
+ need(profile.deployed_sol >= cfg.minDeployedSol, 'deployed_sol', `${profile.deployed_sol} of ${cfg.minDeployedSol} SOL deployed`);
+ need(profile.realized_pnl_sol > 0, 'profitable', `realized P&L is ${profile.realized_pnl_sol} SOL`);
+ need(
+ profile.max_drawdown_pct != null && profile.max_drawdown_pct <= cfg.maxDrawdownPct,
+ 'drawdown',
+ `max drawdown ${profile.max_drawdown_pct ?? 'n/a'}% (limit ${cfg.maxDrawdownPct}%)`,
+ );
+ const copyable = evaluateLeaderEligibility(profile, LEADER_ELIGIBILITY);
+ need(copyable.eligible, 'copyable', copyable.unmet.map((u) => u.label).join(', ') || 'copyable');
+ const f = rec.followers || { followers: 0, net_profit_sol: 0 };
+ need(f.followers >= cfg.minFollowers, 'followers', `${f.followers} of ${cfg.minFollowers} copiers with closed copies`);
+ need(f.followers === 0 || f.net_profit_sol >= 0, 'follower_outcome', `copiers net ${round4(f.net_profit_sol)} SOL`);
+ need(rec.agent?.is_public === true, 'public', 'agent profile is private');
+ need(Boolean(rec.agent?.wallet), 'wallet', 'agent has no Solana wallet to pay');
+ need(!rec.agent?.platform, 'not_platform', 'platform-owned agents are not eligible');
+
+ return {
+ eligible: unmet.length === 0,
+ unmet,
+ qualified_at: qualifiedAt(rows, cfg),
+ stats: {
+ settled: profile.settled,
+ span_days: round2(spanDays),
+ win_rate_pct: round2(winRate),
+ deployed_sol: profile.deployed_sol,
+ realized_pnl_sol: profile.realized_pnl_sol,
+ max_drawdown_pct: profile.max_drawdown_pct,
+ followers: f.followers,
+ follower_net_profit_sol: round4(f.net_profit_sol),
+ },
+ };
+}
+
+/**
+ * Fill the open slots. PURE.
+ * Eligible leaders sorted by qualification time; one per owner; slots already
+ * taken (in the ledger) count against the total and their owners are skipped.
+ *
+ * @param {Array<{ agent_id:string, user_id:string, eligible:boolean, qualified_at:string|null }>} standings
+ * @param {{ takenAgentIds:Set<string>, takenUserIds:Set<string>, slots:number }} p
+ */
+export function assignSlots(standings, { takenAgentIds, takenUserIds, slots }) {
+ const open = Math.max(0, slots - takenAgentIds.size);
+ const owners = new Set(takenUserIds);
+ const winners = [];
+ const ordered = standings
+ .filter((s) => s.eligible && s.qualified_at && !takenAgentIds.has(s.agent_id))
+ .sort((a, b) => (a.qualified_at < b.qualified_at ? -1 : a.qualified_at > b.qualified_at ? 1 : a.agent_id < b.agent_id ? -1 : 1));
+ for (const s of ordered) {
+ if (winners.length >= open) break;
+ if (owners.has(s.user_id)) continue;
+ owners.add(s.user_id);
+ winners.push(s);
+ }
+ return { open_slots: open, winners };
+}
+
+/**
+ * Follower outcomes per leader: distinct non-self copiers with closed acted
+ * copies, and their net copy profit (copy-earnings.js basis).
+ */
+async function followerOutcomes(agentIds, sql) {
+ const map = new Map();
+ if (!agentIds.length) return map;
+ const rows = await sql`
+ select e.leader_agent_id,
+ count(distinct e.copier_user_id)::int as followers,
+ coalesce(sum(e.planned_sol * (p.realized_pnl_pct / 100.0)), 0)::float as net_profit_sol
+ from copy_executions e
+ join agent_sniper_positions p on p.id = e.leader_position_id
+ join agent_identities a on a.id = e.leader_agent_id
+ where e.leader_agent_id = any(${agentIds}::uuid[])
+ and e.direction = 'buy' and e.status = 'acted' and e.network = 'mainnet'
+ and p.status = 'closed' and p.realized_pnl_pct is not null
+ and e.copier_user_id is distinct from a.user_id
+ group by e.leader_agent_id
+ `.catch(() => []);
+ for (const r of rows) map.set(r.leader_agent_id, { followers: n(r.followers), net_profit_sol: n(r.net_profit_sol) });
+ return map;
+}
+
+/**
+ * Every agent with a live mainnet record, judged, plus the slot assignment.
+ * @param {object} cfg programConfig().earlyLeader
+ */
+export async function earlyLeaderStandings(cfg, { sql = defaultSql } = {}) {
+ const positions = await sql`
+ select p.agent_id, p.user_id, p.mint, p.realized_pnl_lamports, p.entry_quote_lamports, p.closed_at
+ from agent_sniper_positions p
+ where p.network = 'mainnet' and p.status = 'closed' and p.closed_at is not null
+ and p.buy_sig is not null and p.buy_sig <> 'SIMULATED'
+ order by p.closed_at asc
+ `;
+ const byAgent = new Map();
+ for (const p of positions) {
+ let list = byAgent.get(p.agent_id);
+ if (!list) byAgent.set(p.agent_id, (list = []));
+ list.push(p);
+ }
+ const agentIds = [...byAgent.keys()];
+ if (!agentIds.length) return { standings: [], slots: assignSlots([], { takenAgentIds: new Set(), takenUserIds: new Set(), slots: cfg.slots }), taken: [] };
+
+ const [agents, followers, taken] = await Promise.all([
+ sql`
+ select a.id, a.user_id, a.name, a.is_public, a.meta->>'solana_address' as wallet,
+ coalesce(u.is_admin, false) as is_admin, coalesce(u.service_account, false) as service_account
+ from agent_identities a
+ left join users u on u.id = a.user_id
+ where a.id = any(${agentIds}::uuid[]) and a.deleted_at is null
+ `,
+ followerOutcomes(agentIds, sql),
+ sql`
+ select agent_id, user_id, status from growth_program_payouts
+ where program = 'early_leader' and status <> 'blocked'
+ `.catch(() => []),
+ ]);
+ const selfDeal = await selfDealMintsByUsers(agents.map((a) => a.user_id), 'mainnet');
+
+ const standings = [];
+ for (const a of agents) {
+ const own = selfDeal.get(a.user_id);
+ const rows = (byAgent.get(a.id) || []).filter((r) => !(own && own.has(r.mint)));
+ const verdict = evaluateEarlyLeader(
+ {
+ rows,
+ followers: followers.get(a.id) || { followers: 0, net_profit_sol: 0 },
+ agent: { is_public: a.is_public === true, wallet: a.wallet || null, platform: Boolean(a.is_admin || a.service_account) },
+ },
+ cfg,
+ );
+ standings.push({ agent_id: a.id, user_id: a.user_id, name: a.name, wallet: a.wallet || null, ...verdict });
+ }
+ standings.sort((x, y) => y.stats.realized_pnl_sol - x.stats.realized_pnl_sol);
+
+ const slots = assignSlots(standings, {
+ takenAgentIds: new Set(taken.map((t) => t.agent_id).filter(Boolean)),
+ takenUserIds: new Set(taken.map((t) => t.user_id).filter(Boolean)),
+ slots: cfg.slots,
+ });
+ return { standings, slots, taken };
+}
+
+/**
+ * Commit newly won slots to the ledger ('claimed'), so the payout queue pays
+ * them. Only called when the program is armed. Idempotent: the ledger's unique
+ * indexes turn a re-run into a no-op.
+ */
+export async function enrollWinners(winners, cfg, { sql = defaultSql } = {}) {
+ let enrolled = 0;
+ for (const w of winners) {
+ const basis = { stats: w.stats, qualified_at: w.qualified_at, bonus_usd: cfg.bonusUsd };
+ const rows = await sql`
+ insert into growth_program_payouts
+ (program, subject_key, user_id, agent_id, recipient_wallet, usd_value, basis, status)
+ values
+ ('early_leader', ${'agent:' + w.agent_id}, ${w.user_id}, ${w.agent_id}, ${w.wallet},
+ ${cfg.bonusUsd}, ${JSON.stringify(basis)}::jsonb, 'claimed')
+ on conflict do nothing
+ returning id
+ `;
+ enrolled += rows.length;
+ }
+ return enrolled;
+}
diff --git a/api/_lib/growth-programs/index.js b/api/_lib/growth-programs/index.js
new file mode 100644
index 000000000..7e00776d4
--- /dev/null
+++ b/api/_lib/growth-programs/index.js
@@ -0,0 +1,123 @@
+// @ts-check
+// Trading growth programs: the entry points the crons, the ops endpoint and the
+// report script share. See docs/growth-programs.md for the owner's view.
+
+import { sql as defaultSql } from '../db.js';
+import { programConfig, CEILINGS } from './config.js';
+import { runBigWinLane } from './big-win-x.js';
+import { rugSoftenerCandidates } from './rug-softener.js';
+import { earlyLeaderStandings, enrollWinners } from './early-leaders.js';
+import { runPayoutQueue } from './payouts.js';
+
+export { programConfig, CEILINGS };
+
+const RUG_PERIOD_HOURS = 24;
+const LEADER_PERIOD_HOURS = 24 * 7;
+
+async function solUsdOrNull() {
+ const { solPriceUsd } = await import('../sol-price.js');
+ const v = await solPriceUsd().catch(() => 0);
+ return v > 0 ? v : null;
+}
+
+/**
+ * The payout tick: enroll any newly qualified early leaders (armed only), then
+ * pay each program's queue within its cap (armed only). Disarmed, this reads
+ * and reports and changes nothing.
+ */
+export async function runPayoutPrograms({ env = process.env, sql = defaultSql, deps = null } = {}) {
+ const cfg = programConfig(env);
+
+ const leaders = await earlyLeaderStandings(cfg.earlyLeader, { sql });
+ let enrolled = 0;
+ if (cfg.earlyLeader.enabled && leaders.slots.winners.length) {
+ enrolled = await enrollWinners(leaders.slots.winners, cfg.earlyLeader, { sql });
+ }
+
+ const queue = (opts) =>
+ runPayoutQueue(opts).catch((err) => {
+ // The ledger migration has not been applied on this database yet: a
+ // clean "nothing to pay" rather than a failed tick.
+ if (/growth_program_payouts.*does not exist/i.test(String(err?.message))) {
+ return { program: opts.program, armed: opts.enabled, executed: false, reason: 'growth_program_payouts not migrated yet' };
+ }
+ throw err;
+ });
+
+ const [rug, early] = await Promise.all([
+ queue({
+ program: 'rug_softener',
+ enabled: cfg.rugSoftener.enabled,
+ flag: cfg.rugSoftener.flag,
+ capUsd: cfg.rugSoftener.dailyCapUsd,
+ periodHours: RUG_PERIOD_HOURS,
+ deps,
+ sql,
+ }),
+ queue({
+ program: 'early_leader',
+ enabled: cfg.earlyLeader.enabled,
+ flag: cfg.earlyLeader.flag,
+ capUsd: cfg.earlyLeader.weeklyCapUsd,
+ periodHours: LEADER_PERIOD_HOURS,
+ deps,
+ sql,
+ }),
+ ]);
+
+ return {
+ rug_softener: rug,
+ early_leader: {
+ ...early,
+ enrolled,
+ would_enroll: cfg.earlyLeader.enabled ? [] : leaders.slots.winners.map((w) => ({ agent_id: w.agent_id, name: w.name, qualified_at: w.qualified_at, bonus_usd: cfg.earlyLeader.bonusUsd })),
+ open_slots: leaders.slots.open_slots,
+ },
+ };
+}
+
+/**
+ * The full dry-run report: what each program would do right now, on real data,
+ * and why. Never writes, never sends, never posts.
+ */
+export async function growthProgramsReport({ env = process.env, sql = defaultSql } = {}) {
+ const cfg = programConfig(env);
+ const solUsd = await solUsdOrNull();
+
+ const [bigWin, rugCandidates, leaders, ledger] = await Promise.all([
+ // Force the lane's dry-run path regardless of the live flag: a report is
+ // never allowed to post.
+ runBigWinLane({ cfg: { ...cfg.bigWinX, enabled: false }, sql, env }),
+ rugSoftenerCandidates(cfg.rugSoftener, { sql, solUsd }),
+ earlyLeaderStandings(cfg.earlyLeader, { sql }),
+ sql`
+ select program, status, count(*)::int as n, coalesce(sum(usd_value), 0)::float as usd
+ from growth_program_payouts group by 1, 2 order by 1, 2
+ `.catch((err) => (/does not exist/i.test(String(err?.message)) ? [{ note: 'growth_program_payouts not migrated yet' }] : Promise.reject(err))),
+ ]);
+
+ return {
+ generated_at: new Date().toISOString(),
+ flags: {
+ BIG_WIN_X_ENABLED: cfg.bigWinX.enabled,
+ RUG_SOFTENER_ENABLED: cfg.rugSoftener.enabled,
+ EARLY_LEADER_ENABLED: cfg.earlyLeader.enabled,
+ },
+ ceilings: CEILINGS,
+ big_win_x: { config: cfg.bigWinX, ...bigWin, armed: cfg.bigWinX.enabled },
+ rug_softener: {
+ config: cfg.rugSoftener,
+ sol_usd: solUsd,
+ eligible: rugCandidates.filter((c) => c.eligible),
+ would_pay_usd: Math.round(rugCandidates.filter((c) => c.eligible).reduce((s, c) => s + (c.amount?.usd || 0), 0) * 100) / 100,
+ candidates: rugCandidates,
+ },
+ early_leader: {
+ config: cfg.earlyLeader,
+ open_slots: leaders.slots.open_slots,
+ would_enroll: leaders.slots.winners.map((w) => ({ agent_id: w.agent_id, name: w.name, wallet: w.wallet, qualified_at: w.qualified_at, bonus_usd: cfg.earlyLeader.bonusUsd })),
+ standings: leaders.standings,
+ },
+ ledger,
+ };
+}
diff --git a/api/_lib/growth-programs/payouts.js b/api/_lib/growth-programs/payouts.js
new file mode 100644
index 000000000..ef0b525ba
--- /dev/null
+++ b/api/_lib/growth-programs/payouts.js
@@ -0,0 +1,293 @@
+// @ts-check
+// The capped, disarmed $THREE payout leg shared by the rug softener and the
+// early-leader program (docs/growth-programs.md).
+//
+// Both programs end the same way: a set of committed payouts in
+// growth_program_payouts, each worth a USD amount, that should become real
+// $THREE transfers. This module is the only place that transfer happens, and
+// it refuses unless every one of these holds:
+//
+// 1. The program's arm flag is exactly "1"/"true" (config.js). Unset means a
+// dry run: the plan is computed and returned, nothing is written or sent.
+// 2. The dedicated payout key is configured: THREE_PRIZE_PAYOUT_KEY, the key
+// the Arena prize rail pays from (resolved by tournament-settlement.js), so
+// there is one funded $THREE payout wallet to watch, not three. The prize
+// rail's fallback to the club treasury secret is NOT taken here: in
+// production that secret is the economy master wallet.
+// 3. The recipient is a valid Solana address and not a platform wallet
+// (treasury, rewards pool, or the payout key itself).
+// 4. The payout fits under the program's rolling per-period USD cap, summed
+// over every row already 'sending' or 'sent' in the period.
+//
+// A row is moved to 'sending' with a compare-and-set BEFORE the transfer, so
+// two overlapping ticks can never pay it twice, and a crash mid-transfer leaves
+// it in 'sending' for a human to reconcile against the chain rather than
+// retrying into a double payment.
+
+import { Keypair } from '@solana/web3.js';
+import bs58 from 'bs58';
+import { sql as defaultSql } from '../db.js';
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const LOCK_TTL_S = 300;
+
+/**
+ * Take payouts in order while they fit under the remaining cap. PURE.
+ * An item that does not fit stops the walk (it is not skipped for a smaller
+ * one behind it), so the queue stays first-come-first-served.
+ *
+ * @template {{ usd_value: number|string }} T
+ * @param {T[]} items
+ * @param {number} remainingUsd
+ * @returns {{ fits: T[], deferred: T[] }}
+ */
+export function takeWithinCap(items, remainingUsd) {
+ const fits = [];
+ let left = Math.max(0, Number(remainingUsd) || 0);
+ let i = 0;
+ for (; i < items.length; i++) {
+ const usd = Number(items[i].usd_value) || 0;
+ if (usd > left + 1e-9) break;
+ fits.push(items[i]);
+ left -= usd;
+ }
+ return { fits, deferred: items.slice(i) };
+}
+
+/**
+ * Why a single payout must not be sent, or null. PURE.
+ * @param {{ recipient_wallet?: string|null, usd_value?: number|string }} row
+ * @param {Set<string>} platformWallets
+ */
+export function rowBlockReason(row, platformWallets) {
+ const w = String(row?.recipient_wallet || '');
+ if (!BASE58_RE.test(w)) return 'invalid_wallet';
+ if (platformWallets.has(w)) return 'platform_wallet';
+ if (!(Number(row?.usd_value) > 0)) return 'zero_amount';
+ return null;
+}
+
+/**
+ * Convert a USD value to $THREE atomics at a price. PURE.
+ * @param {number} usd
+ * @param {number} priceUsd USD per whole $THREE
+ * @param {bigint} atomicsPerToken
+ */
+export function usdToAtomics(usd, priceUsd, atomicsPerToken) {
+ if (!(usd > 0) || !(priceUsd > 0)) return 0n;
+ const tokens = usd / priceUsd;
+ const scaled = Math.floor(tokens * Number(atomicsPerToken));
+ return Number.isFinite(scaled) && scaled > 0 ? BigInt(scaled) : 0n;
+}
+
+/** Rolling-window USD already committed (sending or sent) for a program. */
+export async function periodSpentUsd(program, hours, sql = defaultSql) {
+ const [row] = await sql`
+ select coalesce(sum(usd_value), 0)::float as usd
+ from growth_program_payouts
+ where program = ${program}
+ and status in ('sending', 'sent')
+ and coalesce(sent_at, updated_at) >= now() - make_interval(hours => ${hours})
+ `;
+ return Number(row?.usd) || 0;
+}
+
+async function acquireLock(key, sql) {
+ const rows = await sql`
+ insert into app_settings (key, value)
+ values (${key}, jsonb_build_object('until', extract(epoch from now()) + ${LOCK_TTL_S}))
+ on conflict (key) do update
+ set value = excluded.value, updated_at = now()
+ where (app_settings.value->>'until')::numeric < extract(epoch from now())
+ returning key
+ `;
+ return rows.length > 0;
+}
+
+async function releaseLock(key, sql) {
+ await sql`update app_settings set value = '{"until":0}'::jsonb, updated_at = now() where key = ${key}`;
+}
+
+/** Public key of a Base58 64-byte secret, or null. */
+function pubkeyOf(secretB58) {
+ try {
+ return Keypair.fromSecretKey(bs58.decode(secretB58)).publicKey.toBase58();
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Real dependencies, loaded lazily so a disarmed tick never even imports the
+ * signing stack.
+ */
+async function defaultDeps() {
+ const [{ resolvePrizeKeyBase58 }, { transferSplTokenChecked }, price, tokenCfg] = await Promise.all([
+ import('../tournament-settlement.js'),
+ import('../solana-transfer.js'),
+ import('../token/price.js'),
+ import('../token/config.js'),
+ ]);
+ return {
+ // Dedicated key only: the prize rail's club-treasury fallback is the
+ // economy master wallet in production, which these programs must never spend.
+ payoutKey: () => resolvePrizeKeyBase58({ dedicatedOnly: true }),
+ price: () => price.getTokenPriceUsd({ fresh: true }),
+ transfer: transferSplTokenChecked,
+ mint: tokenCfg.TOKEN_MINT,
+ decimals: tokenCfg.TOKEN_DECIMALS,
+ atomicsPerToken: tokenCfg.ATOMICS_PER_TOKEN,
+ platformWallets: [tokenCfg.treasuryWalletOrNull(), tokenCfg.rewardsWalletOrNull()].filter(Boolean),
+ };
+}
+
+/**
+ * Pay a program's committed queue, within its cap, if and only if it is armed.
+ *
+ * @param {object} p
+ * @param {'rug_softener'|'early_leader'} p.program
+ * @param {boolean} p.enabled the arm flag, already resolved
+ * @param {string} p.flag the flag's env name, for the report
+ * @param {number} p.capUsd rolling cap for the period
+ * @param {number} p.periodHours the cap's window
+ * @param {number} [p.limit] rows per tick
+ * @param {object} [p.deps] injected dependencies (tests)
+ * @param {Function} [p.sql]
+ */
+export async function runPayoutQueue({ program, enabled, flag, capUsd, periodHours, limit = 20, deps = null, sql = defaultSql }) {
+ const queue = await sql`
+ select id, subject_key, user_id, agent_id, position_id, recipient_wallet,
+ usd_value::float as usd_value, status, created_at
+ from growth_program_payouts
+ where program = ${program} and status in ('claimed', 'failed')
+ order by created_at asc
+ limit ${limit}
+ `;
+ const spent = await periodSpentUsd(program, periodHours, sql);
+ const remaining = Math.max(0, capUsd - spent);
+ const { fits, deferred } = takeWithinCap(queue, remaining);
+ const cap = { cap_usd: capUsd, period_hours: periodHours, spent_usd: round2(spent), remaining_usd: round2(remaining) };
+
+ if (!enabled) {
+ // The disarmed path: report exactly what an armed tick would attempt, and
+ // touch nothing. No lock, no status change, no signing import.
+ return {
+ program,
+ armed: false,
+ executed: false,
+ reason: `${flag} is not set, so nothing is sent`,
+ cap,
+ queued: queue.length,
+ would_pay: fits.map(shapeRow),
+ deferred_by_cap: deferred.map(shapeRow),
+ };
+ }
+
+ const d = deps || (await defaultDeps());
+ const key = d.payoutKey();
+ if (!key) {
+ return {
+ program,
+ armed: true,
+ executed: false,
+ reason: 'payout_unconfigured: set THREE_PRIZE_PAYOUT_KEY (Base58 64-byte secret holding $THREE)',
+ cap,
+ queued: queue.length,
+ would_pay: fits.map(shapeRow),
+ deferred_by_cap: deferred.map(shapeRow),
+ };
+ }
+
+ const lockKey = `growth_payout_lock:${program}`;
+ if (!(await acquireLock(lockKey, sql))) {
+ return { program, armed: true, executed: false, reason: 'another tick holds the payout lock', cap };
+ }
+
+ const results = [];
+ try {
+ const platform = new Set([...(d.platformWallets || []), pubkeyOf(key)].filter(Boolean));
+ // One live price per tick. A payout never proceeds on a guessed price:
+ // getTokenPriceUsd throws when no feed answers, which ends the tick with
+ // every row still queued.
+ const quote = await d.price();
+ const priceUsd = Number(quote?.priceUsd);
+ if (!(priceUsd > 0)) throw new Error('no live $THREE price');
+
+ // Re-check the cap inside the lock: another tick may have paid since the
+ // read above.
+ let left = Math.max(0, capUsd - (await periodSpentUsd(program, periodHours, sql)));
+
+ for (const row of fits) {
+ const blocked = rowBlockReason(row, platform);
+ if (blocked) {
+ await sql`
+ update growth_program_payouts set status = 'blocked', note = ${blocked}, updated_at = now()
+ where id = ${row.id} and status in ('claimed', 'failed')
+ `;
+ results.push({ ...shapeRow(row), status: 'blocked', reason: blocked });
+ continue;
+ }
+ if (row.usd_value > left + 1e-9) {
+ results.push({ ...shapeRow(row), status: 'deferred', reason: 'period_cap' });
+ break;
+ }
+ const atomics = usdToAtomics(row.usd_value, priceUsd, d.atomicsPerToken);
+ if (atomics <= 0n) {
+ results.push({ ...shapeRow(row), status: 'deferred', reason: 'rounds_to_zero' });
+ continue;
+ }
+
+ const claimed = await sql`
+ update growth_program_payouts
+ set status = 'sending', amount_atomics = ${atomics.toString()}, price_usd = ${priceUsd},
+ price_source = ${quote.source || null}, updated_at = now()
+ where id = ${row.id} and status in ('claimed', 'failed')
+ returning id
+ `;
+ if (!claimed.length) continue; // someone else moved it; never pay twice
+ left -= row.usd_value;
+
+ try {
+ const tx = await d.transfer({
+ fromWallet: key,
+ toAddress: row.recipient_wallet,
+ amount: atomics,
+ mint: d.mint,
+ decimals: d.decimals,
+ });
+ await sql`
+ update growth_program_payouts
+ set status = 'sent', tx_signature = ${tx}, sent_at = now(), note = null, updated_at = now()
+ where id = ${row.id}
+ `;
+ results.push({ ...shapeRow(row), status: 'sent', tx, amount_atomics: atomics.toString() });
+ } catch (err) {
+ const note = `transfer failed: ${String(err?.message || err).slice(0, 300)}`;
+ await sql`
+ update growth_program_payouts set status = 'failed', note = ${note}, updated_at = now()
+ where id = ${row.id}
+ `;
+ left += row.usd_value; // a failed send spent nothing
+ results.push({ ...shapeRow(row), status: 'failed', reason: note });
+ }
+ }
+ return { program, armed: true, executed: true, cap, price_usd: priceUsd, results, deferred_by_cap: deferred.map(shapeRow) };
+ } finally {
+ await releaseLock(lockKey, sql).catch(() => {});
+ }
+}
+
+function round2(x) {
+ return Math.round(x * 100) / 100;
+}
+
+function shapeRow(r) {
+ return {
+ id: r.id,
+ subject: r.subject_key,
+ user_id: r.user_id || null,
+ agent_id: r.agent_id || null,
+ recipient_wallet: r.recipient_wallet,
+ usd_value: round2(Number(r.usd_value) || 0),
+ };
+}
diff --git a/api/_lib/growth-programs/rug-softener.js b/api/_lib/growth-programs/rug-softener.js
new file mode 100644
index 000000000..61fa9ae99
--- /dev/null
+++ b/api/_lib/growth-programs/rug-softener.js
@@ -0,0 +1,310 @@
+// @ts-check
+// First-rug softener (roadmap 917, 12.15): an optional $THREE pool that pays
+// back part of a first-timer's first rug, as a welcome guarantee.
+//
+// The abuse surface is the whole design problem, so eligibility is tight and
+// every criterion is derived from real records, never from what a claimant
+// says:
+//
+// first trade the claim is against the account's FIRST-EVER live
+// position (agent_sniper_positions, real on-chain buy), with
+// no earlier acted copy trade either. Paper fills never count.
+// real loss the position closed at a realized loss of at least
+// minLossSol, on at least minEntrySol deployed, so a dust
+// trade cannot farm the pool.
+// verified rug the coin carries a rugged verdict from the Coin Intelligence
+// labeler (pump_coin_outcomes, or its durable copy
+// oracle_training_set). A coin that merely went down is a bad
+// trade, not a rug.
+// not the rugger the coin's creator is known (pump_coin_intel) and is none
+// of the claimant's wallets, the coin was not launched through
+// the claimant's own account, none of the claimant's wallets
+// net-sold the coin (a wallet that profited from the rug), and
+// the position wallet was not funded by the creator.
+// one person the position wallet is used by exactly one account (the
+// self-copy rule from copy-eligibility.js, applied to claims),
+// the account is older than minAccountAgeHours, is not a
+// platform account, and the ledger's unique indexes allow one
+// claim per account and one per receiving wallet, ever.
+// fresh claims open for claimWindowDays after the close, and the
+// evidence above has to exist at claim time. It is snapshotted
+// into the ledger row, so the payout later never depends on
+// data the retention window has since pruned.
+//
+// The payout is reimbursePct of the realized SOL loss, valued in USD at claim
+// time and capped at maxPerClaimUsd; it is converted to $THREE at the live
+// price when it is paid (payouts.js), under a rolling daily cap.
+
+import { sql as defaultSql } from '../db.js';
+import { isAdminUser } from '../admin.js';
+
+const LAMPORTS = 1e9;
+const HOUR_MS = 3_600_000;
+const DAY_MS = 86_400_000;
+const round2 = (x) => Math.round(x * 100) / 100;
+const round6 = (x) => Math.round(x * 1e6) / 1e6;
+const lamToSol = (v) => (v == null ? null : Number(v) / LAMPORTS);
+
+export const SIMULATED_SIG = 'SIMULATED';
+
+/** Every criterion, in the order the UI and the ops report list them. */
+export const RUG_CRITERIA = Object.freeze([
+ 'has_live_position',
+ 'first_position_closed',
+ 'first_trade',
+ 'realized_loss',
+ 'min_entry',
+ 'verified_rug',
+ 'claim_window',
+ 'account_age',
+ 'not_platform_account',
+ 'creator_verified',
+ 'not_creator',
+ 'not_insider',
+ 'wallet_unshared',
+ 'not_claimed',
+ 'price_available',
+]);
+
+/**
+ * Decide a first-rug claim from gathered evidence. PURE: evidence in, verdict
+ * out, no clock unless one is passed.
+ *
+ * @param {object} ev see gatherRugEvidence for the shape
+ * @param {ReturnType<typeof import('./config.js').programConfig>['rugSoftener']} cfg
+ * @param {number} [now]
+ */
+export function evaluateRugClaim(ev, cfg, now = Date.now()) {
+ const unmet = [];
+ const miss = (criterion, label) => unmet.push({ criterion, label });
+ const p = ev?.position || null;
+
+ if (!p) {
+ miss('has_live_position', 'no live (non-paper) trade on record yet');
+ return { eligible: false, unmet, amount: null };
+ }
+ if (p.status !== 'closed' || !p.closed_at) miss('first_position_closed', 'your first trade is still open');
+ if (ev.earlierCopyAt) miss('first_trade', 'an earlier copy trade came before this position, so it is not your first trade');
+
+ const entrySol = lamToSol(p.entry_quote_lamports) ?? 0;
+ const pnlSol = lamToSol(p.realized_pnl_lamports);
+ const lossSol = pnlSol != null && pnlSol < 0 ? -pnlSol : 0;
+ if (!(lossSol >= cfg.minLossSol)) miss('realized_loss', `needs a realized loss of at least ${cfg.minLossSol} SOL (had ${round6(lossSol)})`);
+ if (!(entrySol >= cfg.minEntrySol)) miss('min_entry', `needs at least ${cfg.minEntrySol} SOL deployed (had ${round6(entrySol)})`);
+
+ if (ev.rug?.rugged !== true) {
+ miss('verified_rug', ev.rug ? `the coin's verified outcome is "${ev.rug.outcome}", not a rug` : 'the coin has no verified outcome yet');
+ }
+
+ if (p.closed_at) {
+ const ageMs = now - new Date(p.closed_at).getTime();
+ if (!(ageMs <= cfg.claimWindowDays * DAY_MS)) miss('claim_window', `claims close ${cfg.claimWindowDays} days after the trade closed`);
+ }
+
+ const accountAgeH = ev.user?.created_at ? (now - new Date(ev.user.created_at).getTime()) / HOUR_MS : 0;
+ if (!(accountAgeH >= cfg.minAccountAgeHours)) miss('account_age', `the account must be at least ${cfg.minAccountAgeHours}h old`);
+ if (ev.user?.is_admin || ev.user?.service_account) {
+ miss('not_platform_account', 'platform and service accounts are not eligible');
+ }
+
+ const wallets = new Set(ev.userWallets || []);
+ if (!ev.creator) miss('creator_verified', "the coin's creator could not be verified");
+ if ((ev.creator && wallets.has(ev.creator)) || ev.selfLaunched) miss('not_creator', 'this coin was created by one of your wallets or launched from your account');
+
+ if ((ev.netSellerWallets || []).length > 0) miss('not_insider', 'one of your wallets sold this coin at a profit');
+ else if (ev.creator && ev.positionFunder && ev.positionFunder === ev.creator) {
+ miss('not_insider', "the trading wallet was funded by the coin's creator");
+ }
+
+ if ((ev.walletUsers || 1) > 1) miss('wallet_unshared', 'the trading wallet is used by more than one account');
+ if (ev.existingClaim) miss('not_claimed', 'a softener claim already exists for this account or wallet');
+ if (!(ev.solUsd > 0)) miss('price_available', 'the SOL price is unavailable right now, so the amount cannot be quoted');
+
+ const amount = computeSoftenerAmount({ lossSol, solUsd: ev.solUsd, cfg });
+ return { eligible: unmet.length === 0, unmet, amount };
+}
+
+/**
+ * The softener amount. PURE.
+ * reimbursePct of the realized loss, in USD at solUsd, capped per claim.
+ */
+export function computeSoftenerAmount({ lossSol, solUsd, cfg }) {
+ const reimburseSol = Math.max(0, Number(lossSol) || 0) * (cfg.reimbursePct / 100);
+ const rawUsd = solUsd > 0 ? reimburseSol * solUsd : 0;
+ const usd = Math.min(rawUsd, cfg.maxPerClaimUsd);
+ return {
+ loss_sol: round6(Number(lossSol) || 0),
+ reimburse_pct: cfg.reimbursePct,
+ reimburse_sol: round6(reimburseSol),
+ sol_usd: solUsd > 0 ? round2(solUsd) : null,
+ usd: round2(usd),
+ capped: rawUsd > cfg.maxPerClaimUsd,
+ };
+}
+
+/**
+ * Gather every fact evaluateRugClaim needs for one account, from real tables.
+ * Each read degrades to "unknown" (which fails the matching criterion) rather
+ * than to a permissive default.
+ */
+export async function gatherRugEvidence(userId, { sql = defaultSql, solUsd = null } = {}) {
+ const [user] = await sql`
+ select id, created_at, is_admin, service_account, deleted_at, wallet_address from users where id = ${userId}
+ `;
+ if (!user || user.deleted_at) return { user: null, position: null };
+ // Admin by wallet list counts as a platform account too, not only is_admin.
+ const admin = user.is_admin || (await isAdminUser(user).catch(() => false));
+
+ const [position] = await sql`
+ select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.status, p.exit_reason,
+ p.entry_quote_lamports, p.realized_pnl_lamports, p.realized_pnl_pct,
+ p.opened_at, p.closed_at, p.buy_sig, p.sell_sig
+ from agent_sniper_positions p
+ where p.user_id = ${userId} and p.network = 'mainnet'
+ and p.status in ('open', 'closed')
+ and p.buy_sig is not null and p.buy_sig <> ${SIMULATED_SIG}
+ order by p.opened_at asc
+ limit 1
+ `;
+ const base = { user: { ...user, is_admin: admin }, position: position || null, solUsd };
+ if (!position) return base;
+
+ const [earlierCopy, rugRows, creatorRow, walletRows, walletUserRows, launched, claimRows] = await Promise.all([
+ sql`
+ select min(created_at) as at from copy_executions
+ where copier_user_id = ${userId} and status = 'acted' and direction = 'buy'
+ and created_at < ${position.opened_at}
+ `.catch(() => [{ at: null }]),
+ sql`
+ select rugged, outcome, 'pump_coin_outcomes' as source from pump_coin_outcomes where mint = ${position.mint}
+ union all
+ select rugged, outcome, 'oracle_training_set' as source from oracle_training_set
+ where mint = ${position.mint} and network = 'mainnet'
+ `.catch(() => []),
+ sql`select creator from pump_coin_intel where mint = ${position.mint} and network = 'mainnet' limit 1`.catch(() => []),
+ sql`
+ select address from user_wallets where user_id = ${userId}
+ union
+ select meta->>'solana_address' from agent_identities where user_id = ${userId} and meta->>'solana_address' is not null
+ union
+ select wallet from agent_sniper_positions where user_id = ${userId} and wallet is not null
+ `.catch(() => []),
+ sql`select count(distinct user_id)::int as n from agent_sniper_positions where wallet = ${position.wallet}`.catch(() => [{ n: 1 }]),
+ sql`select 1 from pump_agent_mints where user_id = ${userId} and mint = ${position.mint} limit 1`.catch(() => []),
+ sql`
+ select id from growth_program_payouts
+ where program = 'rug_softener' and (user_id = ${userId} or recipient_wallet = ${position.wallet})
+ limit 1
+ `.catch(() => []),
+ ]);
+
+ const userWallets = walletRows.map((r) => r.address).filter(Boolean);
+ const trading = await sql`
+ select wallet, buy_lamports, sell_lamports, funder from pump_coin_wallets
+ where mint = ${position.mint} and wallet = any(${userWallets}::text[])
+ `.catch(() => []);
+ const netSellerWallets = trading
+ .filter((t) => Number(t.sell_lamports || 0) > Number(t.buy_lamports || 0))
+ .map((t) => t.wallet);
+ const positionFunder = trading.find((t) => t.wallet === position.wallet)?.funder || null;
+
+ // Prefer the live labeler's verdict; fall back to the durable copy.
+ const rug = rugRows.find((r) => r.source === 'pump_coin_outcomes' && r.rugged != null) || rugRows.find((r) => r.rugged != null) || null;
+
+ return {
+ ...base,
+ earlierCopyAt: earlierCopy?.[0]?.at || null,
+ rug: rug ? { rugged: rug.rugged === true, outcome: rug.outcome, source: rug.source } : null,
+ creator: creatorRow?.[0]?.creator || null,
+ selfLaunched: launched.length > 0,
+ userWallets,
+ netSellerWallets,
+ positionFunder,
+ walletUsers: Number(walletUserRows?.[0]?.n) || 1,
+ existingClaim: claimRows.length > 0,
+ };
+}
+
+/** Shape evidence for a response or a ledger basis, without any other account's data. */
+export function evidenceSummary(ev) {
+ const p = ev.position;
+ return {
+ position_id: p?.id || null,
+ agent_id: p?.agent_id || null,
+ wallet: p?.wallet || null,
+ mint: p?.mint || null,
+ symbol: p?.symbol || null,
+ opened_at: p?.opened_at || null,
+ closed_at: p?.closed_at || null,
+ entry_sol: p ? round6(lamToSol(p.entry_quote_lamports) ?? 0) : null,
+ realized_pnl_sol: p ? round6(lamToSol(p.realized_pnl_lamports) ?? 0) : null,
+ buy_sig: p?.buy_sig || null,
+ sell_sig: p?.sell_sig || null,
+ rug: ev.rug || null,
+ creator: ev.creator || null,
+ };
+}
+
+/**
+ * Evaluate one account end to end.
+ * @param {string} userId
+ * @param {object} cfg programConfig().rugSoftener
+ * @param {{ sql?: Function, solUsd?: number|null, now?: number }} [opts]
+ */
+export async function rugSoftenerStatus(userId, cfg, { sql = defaultSql, solUsd = null, now = Date.now() } = {}) {
+ const ev = await gatherRugEvidence(userId, { sql, solUsd });
+ const verdict = evaluateRugClaim(ev, cfg, now);
+ return { ev, verdict, evidence: evidenceSummary(ev) };
+}
+
+/**
+ * Every account with a live position, evaluated: the ops dry run. Bounded to
+ * the most recent first trades, which is where any claim could come from.
+ */
+export async function rugSoftenerCandidates(cfg, { sql = defaultSql, solUsd = null, limit = 200, now = Date.now() } = {}) {
+ const users = await sql`
+ select user_id, min(opened_at) as first_opened_at
+ from agent_sniper_positions
+ where network = 'mainnet' and status in ('open', 'closed')
+ and buy_sig is not null and buy_sig <> ${SIMULATED_SIG} and user_id is not null
+ group by user_id
+ order by first_opened_at desc
+ limit ${limit}
+ `;
+ const out = [];
+ for (const u of users) {
+ const { verdict, evidence } = await rugSoftenerStatus(u.user_id, cfg, { sql, solUsd, now });
+ out.push({ user_id: u.user_id, eligible: verdict.eligible, amount: verdict.amount, unmet: verdict.unmet, evidence });
+ }
+ return out;
+}
+
+/**
+ * Record a claim for an eligible account. Only callable when the program is
+ * armed; the caller checks the flag. The row lands 'claimed' and the payout
+ * cron pays it within the daily cap.
+ *
+ * @returns {Promise<{ ok: true, claim: object } | { ok: false, code: string, verdict?: object }>}
+ */
+export async function submitRugClaim(userId, cfg, { sql = defaultSql, solUsd, now = Date.now() } = {}) {
+ const { ev, verdict, evidence } = await rugSoftenerStatus(userId, cfg, { sql, solUsd, now });
+ if (!verdict.eligible) return { ok: false, code: 'not_eligible', verdict };
+ const p = ev.position;
+ const basis = { ...evidence, amount: verdict.amount, criteria: RUG_CRITERIA, evaluated_at: new Date(now).toISOString() };
+ try {
+ const [row] = await sql`
+ insert into growth_program_payouts
+ (program, subject_key, user_id, agent_id, position_id, recipient_wallet, usd_value, basis, status)
+ values
+ ('rug_softener', ${'position:' + p.id}, ${userId}, ${p.agent_id}, ${p.id}, ${p.wallet},
+ ${verdict.amount.usd}, ${JSON.stringify(basis)}::jsonb, 'claimed')
+ returning id, status, usd_value::float as usd_value, recipient_wallet, created_at
+ `;
+ return { ok: true, claim: row };
+ } catch (err) {
+ // The unique indexes are the last line: a concurrent double-submit, or a
+ // second account pointing at the same wallet, lands here.
+ if (/duplicate key|unique/i.test(String(err?.message))) return { ok: false, code: 'already_claimed' };
+ throw err;
+ }
+}
diff --git a/api/_lib/migrations/20260929120000_growth_program_payouts.sql b/api/_lib/migrations/20260929120000_growth_program_payouts.sql
new file mode 100644
index 000000000..f3f464e93
--- /dev/null
+++ b/api/_lib/migrations/20260929120000_growth_program_payouts.sql
@@ -0,0 +1,72 @@
+-- Trading growth programs: the ledger behind the two $THREE payout programs
+-- (the first-rug softener and the early-leader bonus, docs/growth-programs.md).
+-- Apply: npm run db:status, then npm run db:migrate. Idempotent and additive.
+--
+-- One row is one payout the platform has committed to: a first-timer's claim
+-- against their first rug, or an early leader's enrollment bonus. Both programs
+-- ship disarmed, so in production this table stays empty until the owner arms
+-- one. The dry-run reports compute everything from source data and never write
+-- here.
+--
+-- The uniqueness rules ARE the anti-sybil backstop, enforced by the database
+-- rather than by application code that a race could slip past:
+-- (program, subject_key) one payout per position (rug) or per agent (leader)
+-- (program, user_id) one payout per account per program
+-- (program, recipient_wallet) one payout per receiving wallet per program
+--
+-- Status lifecycle:
+-- claimed recorded, waiting for the payout cron (rug softener claims start here)
+-- sending the cron has claimed the row and is about to transfer. A row left
+-- in 'sending' (a crash between claim and confirm) is NEVER retried
+-- automatically: it is reconciled by hand against the chain, so a
+-- crash can never turn into a double payment.
+-- sent the transfer landed; tx_signature holds it
+-- failed the transfer threw; note says why. Eligible for retry.
+-- blocked refused by a guard (cap, missing key, invalid wallet); note says why.
+--
+-- usd_value is what the payout was worth at the price it was quoted at, and is
+-- what the per-period caps sum over.
+
+begin;
+
+create table if not exists growth_program_payouts (
+ id uuid primary key default gen_random_uuid(),
+ program text not null check (program in ('rug_softener', 'early_leader')),
+ subject_key text not null,
+ user_id uuid,
+ agent_id uuid,
+ position_id uuid,
+ recipient_wallet text not null,
+ usd_value numeric(18, 6) not null check (usd_value >= 0),
+ amount_atomics numeric(40, 0),
+ price_usd numeric(30, 12),
+ price_source text,
+ basis jsonb not null default '{}'::jsonb,
+ status text not null default 'claimed'
+ check (status in ('claimed', 'sending', 'sent', 'failed', 'blocked')),
+ tx_signature text,
+ note text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ sent_at timestamptz
+);
+
+create unique index if not exists growth_program_payouts_subject_uniq
+ on growth_program_payouts (program, subject_key);
+
+create unique index if not exists growth_program_payouts_user_uniq
+ on growth_program_payouts (program, user_id)
+ where user_id is not null;
+
+create unique index if not exists growth_program_payouts_wallet_uniq
+ on growth_program_payouts (program, recipient_wallet);
+
+create unique index if not exists growth_program_payouts_tx_uniq
+ on growth_program_payouts (tx_signature)
+ where tx_signature is not null;
+
+-- The payout cron's work queue and the cap sums both read by program + status.
+create index if not exists growth_program_payouts_queue
+ on growth_program_payouts (program, status, created_at);
+
+commit;
diff --git a/api/_lib/solana-transfer.js b/api/_lib/solana-transfer.js
index aeb243286..acc497098 100644
--- a/api/_lib/solana-transfer.js
+++ b/api/_lib/solana-transfer.js
@@ -6,8 +6,10 @@ import {
getAssociatedTokenAddress,
createAssociatedTokenAccountIdempotentInstruction,
createTransferInstruction,
+ createTransferCheckedInstruction,
} from '@solana/spl-token';
import bs58 from 'bs58';
+import { tokenProgramIdForMint } from './token/token-program.js';
const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
@@ -52,6 +54,56 @@ export async function transferSolanaUSDC({ fromWallet, toAddress, amount, mint }
return signature;
}
+/**
+ * Transfer an SPL token from a platform key to a recipient, resolving which
+ * token program owns the mint first. transferSolanaUSDC above assumes the
+ * legacy token program, which is right for legacy mints and wrong for $THREE:
+ * $THREE is a Token-2022 mint, so the legacy associated-token address it derives
+ * does not exist and the transfer is rejected on-chain. This variant reads the mint's
+ * owner (memoized, api/_lib/token/token-program.js), derives both ATAs under
+ * that program, and sends a TransferChecked so the amount is validated against
+ * the mint's decimals by the chain itself.
+ *
+ * @param {object} opts
+ * @param {string} opts.fromWallet base58-encoded sender keypair (64 bytes)
+ * @param {string} opts.toAddress recipient Solana address (wallet owner, not an ATA)
+ * @param {bigint|number|string} opts.amount atomics (smallest units), > 0
+ * @param {string} opts.mint SPL mint address
+ * @param {number} opts.decimals the mint's decimals
+ * @returns {Promise<string>} transaction signature
+ */
+export async function transferSplTokenChecked({ fromWallet, toAddress, amount, mint, decimals }) {
+ const atomics = BigInt(amount);
+ if (atomics <= 0n) throw new Error('transferSplTokenChecked: amount must be > 0');
+ const kp = Keypair.fromSecretKey(bs58.decode(fromWallet));
+ const mintPubkey = new PublicKey(mint);
+ const recipientPubkey = new PublicKey(toAddress);
+
+ const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
+ const programId = await tokenProgramIdForMint(connection, mintPubkey);
+
+ const senderATA = await getAssociatedTokenAddress(mintPubkey, kp.publicKey, false, programId);
+ const recipientATA = await getAssociatedTokenAddress(mintPubkey, recipientPubkey, false, programId);
+
+ const instructions = [];
+ if (!(await ataExists(connection, recipientATA))) {
+ instructions.push(
+ createAssociatedTokenAccountIdempotentInstruction(kp.publicKey, recipientATA, recipientPubkey, mintPubkey, programId),
+ );
+ }
+ instructions.push(
+ createTransferCheckedInstruction(senderATA, mintPubkey, recipientATA, kp.publicKey, atomics, Number(decimals), [], programId),
+ );
+
+ const { signature } = await submitProtected({
+ network: 'mainnet',
+ connection,
+ payer: kp,
+ instructions,
+ });
+ return signature;
+}
+
/**
* Transfer native SOL from a signing keypair to a recipient address. Used by the
* trading-swarm treasury to pay pro-rata profit distributions and exit
diff --git a/api/_lib/tournament-settlement.js b/api/_lib/tournament-settlement.js
index 2e0fc660b..d3e9496c5 100644
--- a/api/_lib/tournament-settlement.js
+++ b/api/_lib/tournament-settlement.js
@@ -28,8 +28,16 @@ const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
* Resolve the prize payout wallet as a Base58 64-byte secret, from the dedicated
* THREE_PRIZE_PAYOUT_KEY (Base58 or base64) or the existing base64 club treasury
* secret. Returns null when nothing is configured.
+ *
+ * `dedicatedOnly` skips the club treasury fallback. In production that secret
+ * resolves to the economy master (funding root) wallet, so a payout program
+ * that should only ever spend from a purpose-funded $THREE wallet (the growth
+ * programs, api/_lib/growth-programs/payouts.js) passes it and gets null
+ * rather than the funding root when THREE_PRIZE_PAYOUT_KEY is unset.
+ *
+ * @param {{ dedicatedOnly?: boolean }} [opts]
*/
-function resolvePrizeKeyBase58() {
+export function resolvePrizeKeyBase58({ dedicatedOnly = false } = {}) {
const dedicated = env.THREE_PRIZE_PAYOUT_KEY;
if (dedicated && dedicated.trim()) {
const s = dedicated.trim();
@@ -45,6 +53,7 @@ function resolvePrizeKeyBase58() {
/* ignore */
}
}
+ if (dedicatedOnly) return null;
const clubB64 = process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64;
if (clubB64) {
try {
diff --git a/api/cron/big-win-x.js b/api/cron/big-win-x.js
new file mode 100644
index 000000000..da818c71a
--- /dev/null
+++ b/api/cron/big-win-x.js
@@ -0,0 +1,25 @@
+// @ts-check
+// GET /api/cron/big-win-x: the big-win auto-poster for @trythreews.
+//
+// Every tick selects the best live, sized win closed in the lookback window and
+// composes its post (docs/growth-programs.md). Posting to X is owner-gated, so
+// unless BIG_WIN_X_ENABLED is exactly "1"/"true" the tick is a dry run: it
+// returns the post it WOULD send and writes nothing. Armed, it sends at most one
+// post per tick under the lane's daily cap and the account-wide cap shared with
+// the changelog and content lanes.
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { programConfig } from '../_lib/growth-programs/config.js';
+import { runBigWinLane } from '../_lib/growth-programs/big-win-x.js';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const cfg = programConfig().bigWinX;
+ const result = await runBigWinLane({ cfg });
+ // The per-candidate list is for the ops report; the cron log keeps the verdict.
+ const { considered, ...summary } = result;
+ return json(res, 200, { ok: true, ...summary, considered_count: considered.length });
+});
diff --git a/api/cron/growth-payouts.js b/api/cron/growth-payouts.js
new file mode 100644
index 000000000..4d4df03bc
--- /dev/null
+++ b/api/cron/growth-payouts.js
@@ -0,0 +1,21 @@
+// @ts-check
+// GET /api/cron/growth-payouts: the $THREE payout leg of the first-rug softener
+// and the early-leader program (docs/growth-programs.md).
+//
+// Each tick enrolls newly qualified early leaders and pays each program's queue
+// within its rolling cap, but only for a program whose arm flag
+// (RUG_SOFTENER_ENABLED, EARLY_LEADER_ENABLED) is exactly "1"/"true". Disarmed,
+// the tick is a dry run: it reports the queue, the cap headroom, and who would
+// be enrolled, and changes nothing.
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { runPayoutPrograms } from '../_lib/growth-programs/index.js';
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const result = await runPayoutPrograms();
+ return json(res, 200, { ok: true, ...result });
+});
diff --git a/api/ops/growth-programs.js b/api/ops/growth-programs.js
new file mode 100644
index 000000000..d86d25e40
--- /dev/null
+++ b/api/ops/growth-programs.js
@@ -0,0 +1,32 @@
+// @ts-check
+// GET /api/ops/growth-programs: the dry-run board for the trading growth
+// programs (docs/growth-programs.md).
+//
+// Shows, on live data, exactly what each disarmed program would do right now:
+// the big win the X lane would post and its exact text, every account the
+// first-rug softener evaluated with the criteria each one failed, and the
+// early-leader standings with the slot assignment. Read-only: this endpoint
+// never posts, never writes a ledger row, never signs.
+//
+// Auth: authorizeOps (admin session, or x-ops-secret), the same gate as the
+// other /api/ops boards. It names wallets and per-account outcomes, so it is
+// never public.
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { authorizeOps } from '../_lib/ops-auth.js';
+import { growthProgramsReport } from '../_lib/growth-programs/index.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authedReadIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const auth = await authorizeOps(req);
+ if (!auth.ok) return error(res, 401, 'unauthorized', 'ops access required');
+
+ const report = await growthProgramsReport();
+ return json(res, 200, { ok: true, actor: auth.actor, ...report }, { 'cache-control': 'no-store' });
+});
diff --git a/api/sniper/rug-softener.js b/api/sniper/rug-softener.js
new file mode 100644
index 000000000..734be798a
--- /dev/null
+++ b/api/sniper/rug-softener.js
@@ -0,0 +1,94 @@
+// @ts-check
+// /api/sniper/rug-softener: the first-rug softener, for the signed-in account
+// (docs/growth-programs.md).
+//
+// GET eligibility for the caller's first-ever live trade: every criterion
+// met or unmet with a plain reason, the amount it would pay, and any
+// claim already on file. Always answers, armed or not.
+// POST record a claim. Refused with 403 program_not_open unless the owner
+// has armed the program (RUG_SOFTENER_ENABLED). An accepted claim lands
+// in the payout ledger as 'claimed' and is paid by
+// /api/cron/growth-payouts within the program's daily cap.
+//
+// Auth: session (with CSRF on POST) or a bearer token. The response only ever
+// describes the caller's own account.
+
+import { cors, json, error, method, wrap, 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 { programConfig } from '../_lib/growth-programs/config.js';
+import { rugSoftenerStatus, submitRugClaim } from '../_lib/growth-programs/rug-softener.js';
+import { solPriceUsd } from '../_lib/sol-price.js';
+
+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, viaSession: !!session };
+}
+
+async function existingClaim(userId) {
+ const rows = await sql`
+ select id, status, usd_value::float as usd_value, amount_atomics::text as amount_atomics,
+ tx_signature, recipient_wallet, created_at, sent_at
+ from growth_program_payouts
+ where program = 'rug_softener' and user_id = ${userId}
+ limit 1
+ `.catch(() => []);
+ return rows[0] || null;
+}
+
+function programView(cfg) {
+ return {
+ armed: cfg.enabled,
+ reimburse_pct: cfg.reimbursePct,
+ max_per_claim_usd: cfg.maxPerClaimUsd,
+ claim_window_days: cfg.claimWindowDays,
+ min_loss_sol: cfg.minLossSol,
+ min_entry_sol: cfg.minEntrySol,
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const auth = await requireUser(req, res);
+ if (!auth) return;
+ const cfg = programConfig().rugSoftener;
+ const solUsd = (await solPriceUsd().catch(() => 0)) || null;
+
+ if (req.method === 'GET') {
+ const [{ verdict, evidence }, claim] = await Promise.all([
+ rugSoftenerStatus(auth.userId, cfg, { solUsd }),
+ existingClaim(auth.userId),
+ ]);
+ return json(res, 200, {
+ program: programView(cfg),
+ eligible: verdict.eligible && !claim,
+ unmet: verdict.unmet,
+ amount: verdict.amount,
+ position: evidence,
+ claim,
+ }, { 'cache-control': 'no-store' });
+ }
+
+ if (auth.viaSession && !(await requireCsrf(req, res, auth.userId))) return;
+ if (!cfg.enabled) {
+ return error(res, 403, 'program_not_open', 'The first-rug softener is not open for claims yet.');
+ }
+ const result = await submitRugClaim(auth.userId, cfg, { solUsd });
+ if (!result.ok) {
+ if (result.code === 'already_claimed') return error(res, 409, 'already_claimed', 'A claim is already on file for this account or wallet.');
+ return error(res, 422, 'not_eligible', 'This account is not eligible for the first-rug softener.', { unmet: result.verdict?.unmet || [] });
+ }
+ return json(res, 201, { ok: true, claim: result.claim });
+});
diff --git a/docs/build.md b/docs/build.md
index 123814ce5..fc62f6d54 100644
--- a/docs/build.md
+++ b/docs/build.md
@@ -47,7 +47,7 @@ front-end, the `vercel.json` route table, and every `api/**` handler from source
provisioned from the `crons` array in `vercel.json` by
[scripts/create-gcp-scheduler.mjs](../scripts/create-gcp-scheduler.mjs); that
array is the count, so read it there rather than trusting a number quoted here
-(121 entries on 2026-09-24). There is **no GitHub Actions CI**. Full runbook: [docs/ops/gcp-production.md](./ops/gcp-production.md).
+(123 entries on 2026-09-29). There is **no GitHub Actions CI**. Full runbook: [docs/ops/gcp-production.md](./ops/gcp-production.md).
`.npmrc` sets `legacy-peer-deps=true` (npm never auto-installs peers — the
reason `audit:deploy` checks the peer tree), and `engines.node` pins Node
diff --git a/scripts/growth-programs-report.mjs b/scripts/growth-programs-report.mjs
new file mode 100644
index 000000000..4a3e02a55
--- /dev/null
+++ b/scripts/growth-programs-report.mjs
@@ -0,0 +1,55 @@
+#!/usr/bin/env node
+// Print the trading growth programs' dry-run report against the real database:
+// which big win the X lane would post (and the exact text), which accounts the
+// first-rug softener would pay and why the rest are ineligible, and the
+// early-leader standings and slot assignment. Read-only: it never posts, never
+// writes a ledger row, never signs. See docs/growth-programs.md.
+//
+// node --env-file=.env.local scripts/growth-programs-report.mjs summary
+// node --env-file=.env.local scripts/growth-programs-report.mjs --json full report
+
+import { growthProgramsReport } from '../api/_lib/growth-programs/index.js';
+
+const asJson = process.argv.includes('--json');
+const report = await growthProgramsReport();
+
+if (asJson) {
+ console.log(JSON.stringify(report, null, 2));
+ process.exit(0);
+}
+
+const line = (s = '') => console.log(s);
+line(`Growth programs dry run, ${report.generated_at}`);
+line(`Flags: ${Object.entries(report.flags).map(([k, v]) => `${k}=${v ? 'ARMED' : 'off'}`).join(' ')}`);
+line();
+
+const bw = report.big_win_x;
+line('Big-win X lane');
+line(` thresholds: >= ${bw.thresholds.min_pct}% on >= ${bw.thresholds.min_entry_sol} SOL in, >= ${bw.thresholds.min_pnl_sol} SOL realized, last ${bw.thresholds.lookback_hours}h`);
+line(` account posts in 24h: ${bw.budget.total} (lane ${bw.budget.lane}/${bw.budget.daily_cap}, account cap ${bw.budget.account_daily_cap})`);
+line(` would post: ${bw.would_post ? `\n ${bw.would_post.text.replace(/\n/g, '\n ')}` : 'nothing'}`);
+if (bw.blocked) line(` blocked: ${bw.blocked}`);
+const reasons = {};
+for (const c of bw.considered) reasons[c.reason || 'eligible'] = (reasons[c.reason || 'eligible'] || 0) + 1;
+line(` considered ${bw.considered.length} closes >= 50%: ${Object.entries(reasons).map(([k, v]) => `${v} ${k.replace(/ \(.*/, '')}`).join(', ') || 'none'}`);
+line();
+
+const rs = report.rug_softener;
+line('First-rug softener');
+line(` SOL/USD: ${rs.sol_usd ?? 'unavailable'}; pays ${rs.config.reimbursePct}% of the loss, max $${rs.config.maxPerClaimUsd}/claim, $${rs.config.dailyCapUsd}/day`);
+line(` accounts evaluated: ${rs.candidates.length}; eligible: ${rs.eligible.length}; would pay: $${rs.would_pay_usd}`);
+for (const c of rs.candidates) {
+ const tag = c.eligible ? `ELIGIBLE $${c.amount.usd}` : c.unmet.map((u) => u.criterion).join(', ');
+ line(` ${c.user_id.slice(0, 8)} first trade ${c.evidence.symbol || '?'} ${c.evidence.realized_pnl_sol ?? '?'} SOL ${tag}`);
+}
+line();
+
+const el = report.early_leader;
+line('Early-leader program');
+line(` ${el.config.slots} slots, $${el.config.bonusUsd} each, $${el.config.weeklyCapUsd}/week; open slots: ${el.open_slots}`);
+line(` would enroll: ${el.would_enroll.length ? el.would_enroll.map((w) => w.name).join(', ') : 'nobody yet'}`);
+for (const s of el.standings) {
+ line(` ${String(s.name).slice(0, 24).padEnd(24)} ${String(s.stats.settled).padStart(4)} trades ${String(s.stats.win_rate_pct).padStart(6)}% win ${String(s.stats.realized_pnl_sol).padStart(9)} SOL unmet: ${s.unmet.map((u) => u.criterion).join(', ') || 'none'}`);
+}
+line();
+line(`Ledger: ${JSON.stringify(report.ledger)}`);
diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.js
index 169cc600d..8091b9a11 100644
--- a/src/dashboard-next/pages/sniper.js
+++ b/src/dashboard-next/pages/sniper.js
@@ -18,6 +18,7 @@ import { StudioAdapter } from '../studio-adapter.js';
import { mountMoneyStudio } from '../../studio/money/money-studio.js';
import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles, attachRetry } from '../../shared/state-kit.js';
import { toast } from '../../shared/toast.js';
+import { mountRugSoftenerBanner } from '../rug-softener-banner.js';
const SOL = 1_000_000_000n;
const lamportsToSol = (l) => Number(BigInt(l || '0')) / 1e9;
@@ -51,6 +52,7 @@ function pumpUrl(mint) { return `https://pump.fun/coin/${encodeURIComponent(mint
const STYLE = `<style>
.sn-wrap { display: grid; gap: 20px; }
+#sn-softener-mount:empty { display: none; }
/* overview strip */
.sn-strip { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 12px; }
@@ -293,6 +295,7 @@ async function refresh(root) {
wireEvents(root);
startSse();
loadTradeHistory(root);
+ mountRugSoftenerBanner(root.querySelector('#sn-softener-mount'));
// Auto-open arm modal when arriving from Strategy Lab with a preset
const qp = new URLSearchParams(location.search);
@@ -306,6 +309,7 @@ function render() {
return `
<div class="sn-wrap">
${overviewStrip()}
+ <div id="sn-softener-mount"></div>
<div class="sn-cards" id="sn-cards">
${hasStrats ? _strategies.map(stratCard).join('') : ''}
</div>
diff --git a/src/dashboard-next/rug-softener-banner.js b/src/dashboard-next/rug-softener-banner.js
new file mode 100644
index 000000000..d45963ecc
--- /dev/null
+++ b/src/dashboard-next/rug-softener-banner.js
@@ -0,0 +1,124 @@
+// First-rug softener banner for the Sniper dashboard (docs/growth-programs.md).
+//
+// Renders nothing unless the owner has armed the program AND the signed-in
+// account either qualifies or already has a claim on file. While the program is
+// disarmed the host stays empty, so the page looks exactly as it did before.
+//
+// GET /api/sniper/rug-softener eligibility + any existing claim
+// POST /api/sniper/rug-softener record the claim (CSRF via api.js)
+
+import { get, post, esc } from './api.js';
+import { toast } from '../shared/toast.js';
+
+const STYLE_ID = 'rs-banner-style';
+const STYLE = `
+.rs-banner { display: flex; gap: 14px; align-items: center; flex-wrap: wrap; padding: 14px 16px;
+ background: color-mix(in srgb, var(--nxt-accent) 7%, var(--nxt-panel)); border: 1px solid color-mix(in srgb, var(--nxt-accent) 35%, var(--nxt-stroke));
+ border-radius: var(--nxt-radius); opacity: 0; transform: translateY(-4px); transition: opacity .2s ease, transform .2s ease; }
+.rs-banner.in { opacity: 1; transform: none; }
+.rs-banner-body { flex: 1; min-width: 220px; }
+.rs-banner-title { font-weight: 600; font-size: 15px; }
+.rs-banner-sub { font-size: 13px; color: var(--nxt-ink-dim); margin-top: 3px; line-height: 1.45; }
+.rs-banner-sub a { color: inherit; text-decoration: underline; text-underline-offset: 2px; }
+.rs-banner-btn { font: inherit; font-weight: 600; font-size: 13px; padding: 8px 14px; border-radius: 8px; cursor: pointer;
+ border: 1px solid var(--nxt-accent); background: var(--nxt-accent); color: var(--nxt-accent-ink, #0b0b0f); transition: filter .14s, transform .14s; }
+.rs-banner-btn:hover { filter: brightness(1.08); }
+.rs-banner-btn:active { transform: translateY(1px); }
+.rs-banner-btn:focus-visible { outline: 2px solid var(--nxt-accent); outline-offset: 2px; }
+.rs-banner-btn[disabled] { opacity: .6; cursor: progress; }
+.rs-banner-status { font-size: 12px; padding: 3px 10px; border-radius: 999px; border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-dim); white-space: nowrap; }
+@media (prefers-reduced-motion: reduce) { .rs-banner { transition: none; transform: none; } }
+`;
+
+function ensureStyle() {
+ if (document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = STYLE;
+ document.head.appendChild(el);
+}
+
+const usd = (n) => `$${Number(n || 0).toFixed(2)}`;
+
+const STATUS_LABEL = {
+ claimed: 'Claim received, payout queued',
+ sending: 'Payout sending',
+ sent: 'Paid in $THREE',
+ failed: 'Payout retrying',
+ blocked: 'Payout on hold, contact support',
+};
+
+function claimView(claim) {
+ const tx = claim.tx_signature
+ ? ` <a href="https://solscan.io/tx/${encodeURIComponent(claim.tx_signature)}" target="_blank" rel="noopener">View the transfer</a>.`
+ : '';
+ return `
+ <div class="rs-banner-body">
+ <div class="rs-banner-title">First-rug softener</div>
+ <div class="rs-banner-sub">Your claim for ${usd(claim.usd_value)} in $THREE is on file.${tx}</div>
+ </div>
+ <span class="rs-banner-status" role="status">${esc(STATUS_LABEL[claim.status] || claim.status)}</span>`;
+}
+
+function eligibleView(data) {
+ const p = data.position || {};
+ const loss = Math.abs(Number(p.realized_pnl_sol || 0)).toFixed(3);
+ const card = p.position_id ? ` <a href="/trade/${encodeURIComponent(p.position_id)}">See the trade</a>.` : '';
+ return `
+ <div class="rs-banner-body">
+ <div class="rs-banner-title">Your first trade hit a verified rug</div>
+ <div class="rs-banner-sub">You lost ${esc(loss)} SOL on your first live trade, and the coin was verified as a rug.
+ The softener pays back ${esc(String(data.program.reimburse_pct))}% of that loss, worth ${usd(data.amount?.usd)} in $THREE, once per account.${card}</div>
+ </div>
+ <button type="button" class="rs-banner-btn" data-rs-claim>Claim ${usd(data.amount?.usd)} in $THREE</button>`;
+}
+
+/**
+ * Mount the banner into `host`. Resolves quietly to an empty host on any
+ * failure: this is an optional program, never a reason for the page to break.
+ * @param {HTMLElement|null} host
+ */
+export async function mountRugSoftenerBanner(host) {
+ if (!host) return;
+ let data;
+ try {
+ data = await get('/api/sniper/rug-softener');
+ } catch {
+ host.innerHTML = '';
+ return;
+ }
+ if (!data?.program?.armed) {
+ host.innerHTML = '';
+ return;
+ }
+ if (!data.claim && !data.eligible) {
+ host.innerHTML = '';
+ return;
+ }
+
+ ensureStyle();
+ host.innerHTML = `<section class="rs-banner" aria-label="First-rug softener">${data.claim ? claimView(data.claim) : eligibleView(data)}</section>`;
+ const banner = host.firstElementChild;
+ requestAnimationFrame(() => banner?.classList.add('in'));
+
+ const btn = host.querySelector('[data-rs-claim]');
+ btn?.addEventListener('click', async () => {
+ btn.disabled = true;
+ btn.textContent = 'Claiming…';
+ try {
+ const out = await post('/api/sniper/rug-softener', {});
+ banner.innerHTML = claimView(out.claim);
+ toast('Claim received. The $THREE payout is queued.', { variant: 'success' });
+ } catch (err) {
+ btn.disabled = false;
+ btn.textContent = `Claim ${usd(data.amount?.usd)} in $THREE`;
+ const msg =
+ err?.code === 'already_claimed'
+ ? 'A claim is already on file for this account.'
+ : err?.code === 'program_not_open'
+ ? 'The softener closed for claims. Try again later.'
+ : err?.message || 'The claim could not be recorded. Try again.';
+ toast(msg, { variant: 'error' });
+ }
+ });
+}
diff --git a/tests/growth-programs.test.js b/tests/growth-programs.test.js
new file mode 100644
index 000000000..474807522
--- /dev/null
+++ b/tests/growth-programs.test.js
@@ -0,0 +1,515 @@
+// Trading growth programs (docs/growth-programs.md): the big-win X lane, the
+// first-rug softener, and the early-leader bonus. Every program ships disarmed,
+// so the load-bearing tests here are the ones proving the side-effecting leg
+// (a post to X, a $THREE transfer) never runs while its flag is unset, and that
+// the caps hold when it is set.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Keypair } from '@solana/web3.js';
+import bs58 from 'bs58';
+
+// A recording stand-in for the Neon tagged template. Handlers match on the SQL
+// text; anything unmatched resolves to no rows.
+function fakeSql(handlers = []) {
+ const calls = [];
+ const fn = (strings, ...values) => {
+ const text = strings.join('?').replace(/\s+/g, ' ').trim();
+ calls.push({ text, values });
+ for (const [re, result] of handlers) {
+ if (re.test(text)) return Promise.resolve(typeof result === 'function' ? result(values, text) : result);
+ }
+ return Promise.resolve([]);
+ };
+ fn.calls = calls;
+ fn.writes = () => calls.filter((c) => /^(insert|update|delete)\b/i.test(c.text));
+ return fn;
+}
+
+const globalSql = fakeSql();
+vi.mock('../api/_lib/db.js', () => ({ sql: (...a) => globalSql(...a) }));
+
+const { programConfig, flagOn, boundedNumber, CEILINGS } = await import('../api/_lib/growth-programs/config.js');
+const { evaluateRugClaim, computeSoftenerAmount } = await import('../api/_lib/growth-programs/rug-softener.js');
+const { qualifiedAt, evaluateEarlyLeader, assignSlots } = await import('../api/_lib/growth-programs/early-leaders.js');
+const { bigWinRejection, composeBigWinPost, bigWinContentProblems, safeAgentName, selectBigWin, accountPostsLast24h, runBigWinLane } =
+ await import('../api/_lib/growth-programs/big-win-x.js');
+const { takeWithinCap, rowBlockReason, usdToAtomics, runPayoutQueue } = await import('../api/_lib/growth-programs/payouts.js');
+const { runPayoutPrograms } = await import('../api/_lib/growth-programs/index.js');
+const { shapeTradeCard } = await import('../api/_lib/trade-card.js');
+const { loadXFilter } = await import('../api/_lib/changelog-push.js');
+
+const NOW = Date.parse('2026-09-29T12:00:00Z');
+const HOUR = 3_600_000;
+const DAY = 86_400_000;
+const wallet = () => Keypair.generate().publicKey.toBase58();
+const SOL = (x) => String(Math.round(x * 1e9));
+
+// ── config ────────────────────────────────────────────────────────────────────
+
+describe('config', () => {
+ it('arms a flag only on exactly "1" or "true"', () => {
+ for (const v of ['1', 'true', 'TRUE', ' true ']) expect(flagOn('F', { F: v })).toBe(true);
+ for (const v of [undefined, '', '0', 'false', 'yes', 'on', 'armed', '2']) expect(flagOn('F', { F: v })).toBe(false);
+ });
+
+ it('ships every program disarmed', () => {
+ const cfg = programConfig({});
+ expect(cfg.bigWinX.enabled).toBe(false);
+ expect(cfg.rugSoftener.enabled).toBe(false);
+ expect(cfg.earlyLeader.enabled).toBe(false);
+ });
+
+ it('never lets env raise a cap past its code ceiling', () => {
+ const cfg = programConfig({
+ RUG_SOFTENER_DAILY_CAP_USD: '1000000',
+ RUG_SOFTENER_MAX_PER_CLAIM_USD: '5000',
+ RUG_SOFTENER_REIMBURSE_PCT: '100',
+ EARLY_LEADER_WEEKLY_CAP_USD: '99999',
+ EARLY_LEADER_BONUS_USD: '9999',
+ EARLY_LEADER_SLOTS: '100000',
+ BIG_WIN_X_DAILY_CAP: '500',
+ BIG_WIN_X_ACCOUNT_DAILY_CAP: '500',
+ });
+ expect(cfg.rugSoftener.dailyCapUsd).toBe(CEILINGS.rugSoftener.dailyCapUsd);
+ expect(cfg.rugSoftener.maxPerClaimUsd).toBe(CEILINGS.rugSoftener.maxPerClaimUsd);
+ expect(cfg.rugSoftener.reimbursePct).toBe(CEILINGS.rugSoftener.reimbursePct);
+ expect(cfg.earlyLeader.weeklyCapUsd).toBe(CEILINGS.earlyLeader.weeklyCapUsd);
+ expect(cfg.earlyLeader.bonusUsd).toBe(CEILINGS.earlyLeader.bonusUsd);
+ expect(cfg.earlyLeader.slots).toBe(CEILINGS.earlyLeader.slots);
+ expect(cfg.bigWinX.dailyCap).toBe(CEILINGS.bigWin.dailyCap);
+ expect(cfg.bigWinX.accountDailyCap).toBe(CEILINGS.bigWin.accountDailyCap);
+ });
+
+ it('falls back to the default on garbage and clamps below the minimum', () => {
+ expect(boundedNumber({ X: 'abc' }, 'X', { def: 5, min: 1, ceiling: 10 })).toBe(5);
+ expect(boundedNumber({ X: '-3' }, 'X', { def: 5, min: 1, ceiling: 10 })).toBe(1);
+ expect(boundedNumber({}, 'X', { def: 50, min: 1, ceiling: 10 })).toBe(10);
+ });
+});
+
+// ── first-rug softener ───────────────────────────────────────────────────────
+
+const rugCfg = programConfig({}).rugSoftener;
+
+function rugEvidence(over = {}) {
+ const posWallet = over.posWallet || wallet();
+ return {
+ user: { id: 'u1', created_at: new Date(NOW - 10 * DAY).toISOString(), is_admin: false, service_account: false },
+ position: {
+ id: 'p1',
+ agent_id: 'a1',
+ wallet: posWallet,
+ mint: 'THREEsynthetic1111111111111111111111111111',
+ status: 'closed',
+ entry_quote_lamports: SOL(0.2),
+ realized_pnl_lamports: SOL(-0.15),
+ opened_at: new Date(NOW - 3 * DAY).toISOString(),
+ closed_at: new Date(NOW - 2 * DAY).toISOString(),
+ },
+ solUsd: 120,
+ earlierCopyAt: null,
+ rug: { rugged: true, outcome: 'rugged', source: 'pump_coin_outcomes' },
+ creator: wallet(),
+ selfLaunched: false,
+ userWallets: [posWallet],
+ netSellerWallets: [],
+ positionFunder: null,
+ walletUsers: 1,
+ existingClaim: false,
+ ...over,
+ };
+}
+
+const unmetOf = (v) => v.unmet.map((u) => u.criterion);
+
+describe('first-rug softener eligibility', () => {
+ it('pays a first-timer whose first live trade hit a verified rug', () => {
+ const v = evaluateRugClaim(rugEvidence(), rugCfg, NOW);
+ expect(v.eligible).toBe(true);
+ expect(v.unmet).toEqual([]);
+ // 50% of 0.15 SOL at $120 = $9.00
+ expect(v.amount.usd).toBe(9);
+ expect(v.amount.capped).toBe(false);
+ });
+
+ it('refuses an account with no live trade', () => {
+ const v = evaluateRugClaim(rugEvidence({ position: null }), rugCfg, NOW);
+ expect(v.eligible).toBe(false);
+ expect(unmetOf(v)).toEqual(['has_live_position']);
+ });
+
+ it('refuses a coin that went down but was not verified as a rug', () => {
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ rug: { rugged: false, outcome: 'flat' } }), rugCfg, NOW))).toContain('verified_rug');
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ rug: null }), rugCfg, NOW))).toContain('verified_rug');
+ });
+
+ it('refuses dust trades and gains', () => {
+ const dust = rugEvidence();
+ dust.position.entry_quote_lamports = SOL(0.001);
+ dust.position.realized_pnl_lamports = SOL(-0.0009);
+ expect(unmetOf(evaluateRugClaim(dust, rugCfg, NOW))).toEqual(expect.arrayContaining(['min_entry', 'realized_loss']));
+ const win = rugEvidence();
+ win.position.realized_pnl_lamports = SOL(0.05);
+ expect(unmetOf(evaluateRugClaim(win, rugCfg, NOW))).toContain('realized_loss');
+ });
+
+ it('refuses the rugger: creator wallet, own launch, profitable insider wallet, or creator-funded wallet', () => {
+ const creator = wallet();
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ creator, userWallets: [creator] }), rugCfg, NOW))).toContain('not_creator');
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ selfLaunched: true }), rugCfg, NOW))).toContain('not_creator');
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ netSellerWallets: [wallet()] }), rugCfg, NOW))).toContain('not_insider');
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ creator, positionFunder: creator }), rugCfg, NOW))).toContain('not_insider');
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ creator: null }), rugCfg, NOW))).toContain('creator_verified');
+ });
+
+ it('refuses sybil patterns: shared wallet, fresh account, platform account, repeat claim, earlier copy', () => {
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ walletUsers: 2 }), rugCfg, NOW))).toContain('wallet_unshared');
+ const fresh = rugEvidence();
+ fresh.user.created_at = new Date(NOW - 2 * HOUR).toISOString();
+ expect(unmetOf(evaluateRugClaim(fresh, rugCfg, NOW))).toContain('account_age');
+ const admin = rugEvidence();
+ admin.user.is_admin = true;
+ expect(unmetOf(evaluateRugClaim(admin, rugCfg, NOW))).toContain('not_platform_account');
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ existingClaim: true }), rugCfg, NOW))).toContain('not_claimed');
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ earlierCopyAt: '2026-09-01T00:00:00Z' }), rugCfg, NOW))).toContain('first_trade');
+ });
+
+ it('closes the claim window and needs the first trade closed', () => {
+ const old = rugEvidence();
+ old.position.closed_at = new Date(NOW - 40 * DAY).toISOString();
+ expect(unmetOf(evaluateRugClaim(old, rugCfg, NOW))).toContain('claim_window');
+ const open = rugEvidence();
+ open.position.status = 'open';
+ open.position.closed_at = null;
+ expect(unmetOf(evaluateRugClaim(open, rugCfg, NOW))).toContain('first_position_closed');
+ });
+
+ it('caps the amount per claim and refuses to quote without a price', () => {
+ const a = computeSoftenerAmount({ lossSol: 10, solUsd: 150, cfg: rugCfg });
+ expect(a.usd).toBe(rugCfg.maxPerClaimUsd);
+ expect(a.capped).toBe(true);
+ expect(unmetOf(evaluateRugClaim(rugEvidence({ solUsd: null }), rugCfg, NOW))).toContain('price_available');
+ });
+});
+
+// ── early leaders ─────────────────────────────────────────────────────────────
+
+const leaderCfg = programConfig({}).earlyLeader;
+
+function closes(count, { winEvery = 2, pnlWin = 0.05, pnlLoss = -0.01, entry = 0.1, spanDays = 40, start = NOW - 60 * DAY } = {}) {
+ const rows = [];
+ for (let i = 0; i < count; i++) {
+ const win = i % winEvery !== winEvery - 1;
+ rows.push({
+ realized_pnl_lamports: SOL(win ? pnlWin : pnlLoss),
+ entry_quote_lamports: SOL(entry),
+ closed_at: new Date(start + (spanDays * DAY * i) / Math.max(1, count - 1)).toISOString(),
+ });
+ }
+ return rows;
+}
+
+const goodAgent = { is_public: true, wallet: 'W', platform: false };
+
+describe('early-leader program', () => {
+ it('qualifies a profitable, long, followed record', () => {
+ const rows = closes(40, { winEvery: 3 }); // 2 of every 3 win: ~67%
+ const v = evaluateEarlyLeader({ rows, followers: { followers: 2, net_profit_sol: 0.4 }, agent: goodAgent }, leaderCfg);
+ expect(v.unmet).toEqual([]);
+ expect(v.eligible).toBe(true);
+ expect(v.qualified_at).not.toBeNull();
+ });
+
+ it('needs followers who actually profit', () => {
+ const rows = closes(40, { winEvery: 3 });
+ expect(evaluateEarlyLeader({ rows, followers: { followers: 0, net_profit_sol: 0 }, agent: goodAgent }, leaderCfg).unmet.map((u) => u.criterion)).toContain('followers');
+ expect(
+ evaluateEarlyLeader({ rows, followers: { followers: 3, net_profit_sol: -0.2 }, agent: goodAgent }, leaderCfg).unmet.map((u) => u.criterion),
+ ).toContain('follower_outcome');
+ });
+
+ it('refuses a short, losing, private, or platform-owned record', () => {
+ const short = evaluateEarlyLeader({ rows: closes(10, { spanDays: 5 }), followers: { followers: 1, net_profit_sol: 0 }, agent: goodAgent }, leaderCfg);
+ expect(short.unmet.map((u) => u.criterion)).toEqual(expect.arrayContaining(['settled', 'span_days']));
+ const losing = evaluateEarlyLeader({ rows: closes(40, { winEvery: 2, pnlWin: 0.01, pnlLoss: -0.05 }), followers: { followers: 1, net_profit_sol: 0 }, agent: goodAgent }, leaderCfg);
+ expect(losing.unmet.map((u) => u.criterion)).toEqual(expect.arrayContaining(['win_rate', 'profitable']));
+ const rows = closes(40, { winEvery: 3 });
+ const f = { followers: 1, net_profit_sol: 0.1 };
+ expect(evaluateEarlyLeader({ rows, followers: f, agent: { ...goodAgent, is_public: false } }, leaderCfg).unmet.map((u) => u.criterion)).toContain('public');
+ expect(evaluateEarlyLeader({ rows, followers: f, agent: { ...goodAgent, platform: true } }, leaderCfg).unmet.map((u) => u.criterion)).toContain('not_platform');
+ expect(evaluateEarlyLeader({ rows, followers: f, agent: { ...goodAgent, wallet: null } }, leaderCfg).unmet.map((u) => u.criterion)).toContain('wallet');
+ });
+
+ it('dates qualification to the first close that cleared every threshold', () => {
+ const rows = closes(60, { winEvery: 3, spanDays: 59 });
+ const at = qualifiedAt(rows, leaderCfg);
+ const idx = rows.findIndex((r) => r.closed_at === at);
+ // Needs 30 closes and 30 days of span; with one close a day, day 30 is the first.
+ expect(idx).toBeGreaterThanOrEqual(leaderCfg.minSettled - 1);
+ expect(qualifiedAt(rows.slice(0, idx), leaderCfg)).toBeNull();
+ });
+
+ it('fills slots first-come, one per owner, keeping slots already taken', () => {
+ const s = (agent_id, user_id, qualified_at, eligible = true) => ({ agent_id, user_id, qualified_at, eligible });
+ const standings = [
+ s('a3', 'u3', '2026-09-03T00:00:00Z'),
+ s('a1', 'u1', '2026-09-01T00:00:00Z'),
+ s('a1b', 'u1', '2026-09-02T00:00:00Z'), // same owner as a1
+ s('a4', 'u4', '2026-09-04T00:00:00Z'),
+ s('a0', 'u0', '2026-08-01T00:00:00Z', false), // not eligible
+ s('a9', 'u9', '2026-08-15T00:00:00Z'), // already has a slot
+ ];
+ const { open_slots, winners } = assignSlots(standings, { takenAgentIds: new Set(['a9']), takenUserIds: new Set(['u9']), slots: 3 });
+ expect(open_slots).toBe(2);
+ expect(winners.map((w) => w.agent_id)).toEqual(['a1', 'a3']);
+ });
+});
+
+// ── big-win X lane ───────────────────────────────────────────────────────────
+
+const bigCfg = programConfig({}).bigWinX;
+const filter = loadXFilter();
+
+function winRow(over = {}) {
+ return {
+ id: '11111111-1111-4111-8111-111111111111',
+ agent_id: 'agent-1',
+ user_id: 'user-1',
+ network: 'mainnet',
+ mint: 'THREEsynthetic1111111111111111111111111111',
+ symbol: 'SYNTH',
+ name: 'Synthetic',
+ status: 'closed',
+ exit_reason: 'take_profit',
+ entry_quote_lamports: SOL(0.5),
+ exit_quote_lamports: SOL(1.6),
+ realized_pnl_lamports: SOL(1.1),
+ realized_pnl_pct: 220,
+ buy_sig: '5'.repeat(88),
+ sell_sig: '4'.repeat(88),
+ moonbag_base_amount: null,
+ moonbag_last_value_lamports: null,
+ opened_at: new Date(NOW - 2 * HOUR).toISOString(),
+ closed_at: new Date(NOW - HOUR).toISOString(),
+ agent_name: 'Crosshair',
+ agent_image: null,
+ is_public: true,
+ ...over,
+ };
+}
+
+describe('big-win X lane', () => {
+ it('accepts a live, sized win and rejects paper, small, and private ones', () => {
+ expect(bigWinRejection(winRow(), bigCfg)).toBeNull();
+ expect(bigWinRejection(winRow({ buy_sig: 'SIMULATED' }), bigCfg)).toBe('paper_or_unsigned');
+ expect(bigWinRejection(winRow({ sell_sig: null }), bigCfg)).toBe('paper_or_unsigned');
+ expect(bigWinRejection(winRow({ entry_quote_lamports: SOL(0.001), realized_pnl_lamports: SOL(0.002) }), bigCfg)).toMatch(/^below_min_entry/);
+ expect(bigWinRejection(winRow({ realized_pnl_pct: 40 }), bigCfg)).toMatch(/^below_min_pct/);
+ expect(bigWinRejection(winRow({ is_public: false }), bigCfg)).toBe('agent_private');
+ expect(bigWinRejection(winRow(), bigCfg, { selfDealing: true })).toBe('self_dealing');
+ });
+
+ it('never names the traded coin, links the trade card, and passes the account filter', () => {
+ const card = shapeTradeCard(winRow(), { origin: 'https://three.ws' });
+ const text = composeBigWinPost(card);
+ expect(text).toContain('https://three.ws/trade/11111111-1111-4111-8111-111111111111');
+ expect(text).not.toMatch(/\$[A-Za-z]/);
+ expect(text).not.toContain('SYNTH');
+ expect(text).not.toContain('THREEsynthetic');
+ expect(text).not.toMatch(/[\u2013\u2014]/);
+ expect(bigWinContentProblems(text, filter)).toEqual([]);
+ });
+
+ it('refuses an agent name carrying a cashtag, handle, hashtag, or link', () => {
+ for (const bad of ['Buy $SCAM', '@someone', '#pump', 'visit scam.io', 'x'.repeat(41), '']) expect(safeAgentName(bad)).toBeNull();
+ expect(safeAgentName('Crosshair')).toBe('Crosshair');
+ });
+
+ it('respects the lane cap, the account-wide cap, and the per-agent cooldown', () => {
+ const rows = [winRow()];
+ const base = { rows, cfg: bigCfg, filter, selfDealByUser: new Map(), now: NOW };
+ const ok = selectBigWin({ ...base, state: {}, budget: { lane: 0, total: 0 } });
+ expect(ok.pick?.position_id).toBe(rows[0].id);
+ expect(ok.blocked).toBeNull();
+ expect(selectBigWin({ ...base, state: {}, budget: { lane: bigCfg.dailyCap, total: 0 } }).blocked).toMatch(/^daily_cap/);
+ expect(selectBigWin({ ...base, state: {}, budget: { lane: 0, total: bigCfg.accountDailyCap } }).blocked).toMatch(/^account_daily_cap/);
+ const cooled = selectBigWin({ ...base, state: { perAgent: { 'agent-1': NOW - HOUR } }, budget: { lane: 0, total: 0 } });
+ expect(cooled.pick).toBeNull();
+ const posted = selectBigWin({ ...base, state: { posted: [rows[0].id] }, budget: { lane: 0, total: 0 } });
+ expect(posted.pick).toBeNull();
+ });
+
+ it('counts posts from every automated lane toward the account budget', () => {
+ const b = accountPostsLast24h(
+ {
+ lane: { recent: [NOW - HOUR, NOW - 2 * DAY] },
+ changelog: { recent: [NOW - HOUR, NOW - 3 * HOUR] },
+ content: { published: [{ publishedAt: new Date(NOW - HOUR).toISOString() }, { publishedAt: new Date(NOW - 3 * DAY).toISOString() }] },
+ },
+ NOW,
+ );
+ expect(b).toEqual({ lane: 1, changelog: 2, content: 1, total: 4 });
+ });
+
+ it('never posts or writes state while BIG_WIN_X_ENABLED is unset, even with a qualifying win and credentials', async () => {
+ const sql = fakeSql([[/from agent_sniper_positions p join agent_identities/i, [winRow({ closed_at: new Date(Date.now() - HOUR).toISOString() })]]]);
+ const makePoster = vi.fn();
+ const env = { X_API_KEY: 'k', X_API_SECRET: 's', X_ACCESS_TOKEN: 't', X_ACCESS_SECRET: 'a' };
+ const out = await runBigWinLane({ cfg: programConfig({}).bigWinX, sql, env, makePoster });
+ expect(out.executed).toBe(false);
+ expect(out.would_post?.text).toContain('/trade/');
+ expect(makePoster).not.toHaveBeenCalled();
+ expect(sql.writes()).toEqual([]);
+ });
+
+ it('posts exactly one win and records it when armed', async () => {
+ const sql = fakeSql([
+ [/from agent_sniper_positions p join agent_identities/i, [winRow({ closed_at: new Date(Date.now() - HOUR).toISOString() })]],
+ [/^insert into app_settings \(key, value\) values \(\?, jsonb_build_object/i, [{ key: 'big_win_x_lock' }]],
+ ]);
+ const post = vi.fn(async () => '1900000000000000000');
+ const makePoster = vi.fn(async () => post);
+ const env = { BIG_WIN_X_ENABLED: '1', X_API_KEY: 'k', X_API_SECRET: 's', X_ACCESS_TOKEN: 't', X_ACCESS_SECRET: 'a' };
+ const out = await runBigWinLane({ cfg: programConfig(env).bigWinX, sql, env, makePoster });
+ expect(out.executed).toBe(true);
+ expect(post).toHaveBeenCalledTimes(1);
+ const saved = sql.calls.find((c) => /^insert into app_settings \(key, value\) values \(\?, \?::jsonb\)/i.test(c.text) && c.values[0] === 'big_win_x');
+ expect(JSON.parse(saved.values[1]).posted).toContain(winRow().id);
+ });
+});
+
+// ── payout leg ────────────────────────────────────────────────────────────────
+
+describe('capped payout leg', () => {
+ it('takes queued payouts first-come while they fit the cap', () => {
+ const items = [{ usd_value: 40 }, { usd_value: 40 }, { usd_value: 10 }];
+ const { fits, deferred } = takeWithinCap(items, 90);
+ expect(fits).toHaveLength(3);
+ const tight = takeWithinCap(items, 60);
+ expect(tight.fits).toHaveLength(1);
+ expect(tight.deferred).toHaveLength(2); // the small one does not jump the queue
+ });
+
+ it('blocks invalid, platform, and zero payouts', () => {
+ const w = wallet();
+ expect(rowBlockReason({ recipient_wallet: 'nope', usd_value: 5 }, new Set())).toBe('invalid_wallet');
+ expect(rowBlockReason({ recipient_wallet: w, usd_value: 5 }, new Set([w]))).toBe('platform_wallet');
+ expect(rowBlockReason({ recipient_wallet: w, usd_value: 0 }, new Set())).toBe('zero_amount');
+ expect(rowBlockReason({ recipient_wallet: w, usd_value: 5 }, new Set())).toBeNull();
+ });
+
+ it('converts USD to atomics at a live price', () => {
+ expect(usdToAtomics(10, 0.002, 1_000_000n)).toBe(5_000_000_000n);
+ expect(usdToAtomics(0, 1, 1_000_000n)).toBe(0n);
+ expect(usdToAtomics(5, 0, 1_000_000n)).toBe(0n);
+ });
+
+ const queueRows = () => [
+ { id: 'r1', subject_key: 'position:p1', user_id: 'u1', recipient_wallet: wallet(), usd_value: 20, status: 'claimed' },
+ { id: 'r2', subject_key: 'position:p2', user_id: 'u2', recipient_wallet: wallet(), usd_value: 20, status: 'claimed' },
+ { id: 'r3', subject_key: 'position:p3', user_id: 'u3', recipient_wallet: wallet(), usd_value: 20, status: 'claimed' },
+ ];
+
+ function payoutSql(rows, { spent = 0 } = {}) {
+ return fakeSql([
+ [/^select id, subject_key/i, rows],
+ [/coalesce\(sum\(usd_value\), 0\)::float as usd/i, [{ usd: spent }]],
+ [/^insert into app_settings/i, [{ key: 'lock' }]],
+ [/^update growth_program_payouts set status = 'sending'/i, (values) => [{ id: values[values.length - 1] }]],
+ ]);
+ }
+
+ function deps() {
+ return {
+ payoutKey: () => bs58.encode(Keypair.generate().secretKey),
+ price: vi.fn(async () => ({ priceUsd: 0.002, source: 'test' })),
+ transfer: vi.fn(async () => 'sig' + Math.random().toString(36).slice(2)),
+ mint: 'THREEsynthetic1111111111111111111111111111',
+ decimals: 6,
+ atomicsPerToken: 1_000_000n,
+ platformWallets: [],
+ };
+ }
+
+ it('pays only from the dedicated payout key, never the club treasury fallback', async () => {
+ const { resolvePrizeKeyBase58 } = await import('../api/_lib/tournament-settlement.js');
+ const saved = { p: process.env.THREE_PRIZE_PAYOUT_KEY, c: process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64 };
+ try {
+ delete process.env.THREE_PRIZE_PAYOUT_KEY;
+ process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64 = Buffer.from(Keypair.generate().secretKey).toString('base64');
+ expect(resolvePrizeKeyBase58()).not.toBeNull(); // the Arena prize rail keeps its fallback
+ expect(resolvePrizeKeyBase58({ dedicatedOnly: true })).toBeNull();
+ const dedicated = bs58.encode(Keypair.generate().secretKey);
+ process.env.THREE_PRIZE_PAYOUT_KEY = dedicated;
+ expect(resolvePrizeKeyBase58({ dedicatedOnly: true })).toBe(dedicated);
+ } finally {
+ if (saved.p === undefined) delete process.env.THREE_PRIZE_PAYOUT_KEY;
+ else process.env.THREE_PRIZE_PAYOUT_KEY = saved.p;
+ if (saved.c === undefined) delete process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64;
+ else process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64 = saved.c;
+ }
+ });
+
+ it('never transfers or writes while the program flag is unset', async () => {
+ const sql = payoutSql(queueRows());
+ const d = deps();
+ const out = await runPayoutQueue({ program: 'rug_softener', enabled: false, flag: 'RUG_SOFTENER_ENABLED', capUsd: 100, periodHours: 24, deps: d, sql });
+ expect(out.executed).toBe(false);
+ expect(out.would_pay).toHaveLength(3);
+ expect(d.transfer).not.toHaveBeenCalled();
+ expect(d.price).not.toHaveBeenCalled();
+ expect(sql.writes()).toEqual([]);
+ });
+
+ it('does not transfer when armed but the payout key is missing', async () => {
+ const sql = payoutSql(queueRows());
+ const d = { ...deps(), payoutKey: () => null };
+ const out = await runPayoutQueue({ program: 'rug_softener', enabled: true, flag: 'RUG_SOFTENER_ENABLED', capUsd: 100, periodHours: 24, deps: d, sql });
+ expect(out.executed).toBe(false);
+ expect(out.reason).toMatch(/^payout_unconfigured/);
+ expect(d.transfer).not.toHaveBeenCalled();
+ expect(sql.writes()).toEqual([]);
+ });
+
+ it('pays within the period cap when armed, and stops at the cap', async () => {
+ const sql = payoutSql(queueRows(), { spent: 55 });
+ const d = deps();
+ const out = await runPayoutQueue({ program: 'rug_softener', enabled: true, flag: 'RUG_SOFTENER_ENABLED', capUsd: 100, periodHours: 24, deps: d, sql });
+ // $45 of headroom: two $20 payouts fit, the third waits for the window.
+ expect(d.transfer).toHaveBeenCalledTimes(2);
+ expect(out.results.filter((r) => r.status === 'sent')).toHaveLength(2);
+ expect(out.deferred_by_cap).toHaveLength(1);
+ const amounts = d.transfer.mock.calls.map(([arg]) => arg.amount);
+ expect(amounts).toEqual([10_000_000_000n, 10_000_000_000n]); // $20 at $0.002 = 10,000 $THREE
+ });
+
+ it('pays nothing when the cap is already spent', async () => {
+ const sql = payoutSql(queueRows(), { spent: 100 });
+ const d = deps();
+ await runPayoutQueue({ program: 'early_leader', enabled: true, flag: 'EARLY_LEADER_ENABLED', capUsd: 100, periodHours: 168, deps: d, sql });
+ expect(d.transfer).not.toHaveBeenCalled();
+ });
+
+ it('the payout tick moves nothing and enrolls nobody with every flag unset', async () => {
+ const leaderRows = closes(40, { winEvery: 3 }).map((r) => ({ ...r, agent_id: 'a1', user_id: 'u1', mint: 'm' }));
+ const sql = fakeSql([
+ [/from agent_sniper_positions p where p.network = 'mainnet' and p.status = 'closed'/i, leaderRows],
+ [/from agent_identities a left join users u/i, [{ id: 'a1', user_id: 'u1', name: 'Leader', is_public: true, wallet: wallet(), is_admin: false, service_account: false }]],
+ [/from copy_executions e/i, [{ leader_agent_id: 'a1', followers: 2, net_profit_sol: 0.3 }]],
+ [/^select id, subject_key/i, queueRows()],
+ [/coalesce\(sum\(usd_value\), 0\)::float as usd/i, [{ usd: 0 }]],
+ ]);
+ const d = deps();
+ const out = await runPayoutPrograms({ env: {}, sql, deps: d });
+ expect(out.early_leader.would_enroll.map((w) => w.agent_id)).toEqual(['a1']);
+ expect(out.early_leader.enrolled).toBe(0);
+ expect(out.rug_softener.executed).toBe(false);
+ expect(out.early_leader.executed).toBe(false);
+ expect(d.transfer).not.toHaveBeenCalled();
+ expect(sql.writes()).toEqual([]);
+ });
+});
+
+beforeEach(() => {
+ globalSql.calls.length = 0;
+});
diff --git a/vercel.json b/vercel.json
index b1f6eb2c0..2761b2747 100644
--- a/vercel.json
+++ b/vercel.json
@@ -6685,6 +6685,14 @@
"path": "/api/cron/changelog-push",
"schedule": "*/20 * * * *"
},
+ {
+ "path": "/api/cron/big-win-x",
+ "schedule": "11,41 * * * *"
+ },
+ {
+ "path": "/api/cron/growth-payouts",
+ "schedule": "23 * * * *"
+ },
{
"path": "/api/cron/x-content",
"schedule": "*/15 * * * *"