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(copy-trade): syndicates, named copier teams that follow a leader together over the guarded copy engine

nirholasb1493eaa9a34
diff --git a/api/_lib/copy-subscribe.js b/api/_lib/copy-subscribe.js
new file mode 100644
index 000000000..562bbfcf2
--- /dev/null
+++ b/api/_lib/copy-subscribe.js
@@ -0,0 +1,128 @@
+/**
+ * The one guarded path that attaches a copier to a leader.
+ *
+ * Both POST /api/copy/subscriptions (a single follow) and a syndicate join
+ * (api/_lib/syndicates.js, one follow per syndicate leader) create copy
+ * subscriptions through this function, so every follow on the platform clears
+ * the same gates in the same order:
+ *
+ * 1. the leader is a public, live agent;
+ * 2. SELF-COPY: a copier may not follow an agent they own;
+ * 3. the COPYABLE BAR: a real closed on-chain record (api/_lib/copy-eligibility.js);
+ * 4. the copier's sizing and guard rules are valid (api/_lib/copy-engine.js).
+ *
+ * Returns a result object instead of writing a response, so each endpoint keeps
+ * its own response shape. Non-custodial: it stores the copier's wallet address
+ * and rules, never a key.
+ */
+
+import { sql } from './db.js';
+import { normalizeSubscriptionInput } from './copy-engine.js';
+import { LEADER_ELIGIBILITY, evaluateLeaderEligibility, leaderCopyProfile } from './copy-eligibility.js';
+import { isUuid } from './validate.js';
+
+export const COPY_NETWORKS = new Set(['mainnet', 'devnet']);
+export const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+const fail = (status, code, message, extra = {}) => ({ ok: false, status, code, message, extra });
+
+/**
+ * Create or update the copier's subscription to one leader.
+ *
+ * @param {object} p
+ * @param {string} p.userId the copier.
+ * @param {object} p.body the raw request fields: leader_agent_id, copier_wallet, network, and the tunables.
+ * @returns {Promise<{ok:true, subscription:object, leader:{id:string,name:string|null}, profile:object}
+ * | {ok:false, status:number, code:string, message:string, extra:object}>}
+ */
+export async function subscribeCopier({ userId, body }) {
+ const leaderId = String(body.leader_agent_id || '').trim();
+ const wallet = String(body.copier_wallet || '').trim();
+ const network = COPY_NETWORKS.has(body.network) ? body.network : 'mainnet';
+ if (!isUuid(leaderId)) return fail(400, 'invalid_leader', 'leader_agent_id must be an agent UUID');
+ if (!BASE58_RE.test(wallet)) return fail(400, 'invalid_wallet', 'copier_wallet must be a valid Solana address');
+
+ const [leader] = await sql`
+ select id, user_id, name, is_public from agent_identities
+ where id = ${leaderId} and deleted_at is null limit 1
+ `;
+ if (!leader || leader.is_public === false) return fail(404, 'leader_not_found', 'No such public trader.');
+
+ // Wash-trade guard: copying your own agent routes the performance fee back to
+ // you while inflating that leader's copier count, copied volume, and the public
+ // "earned X for being copied" figure. Refused outright: there is no legitimate
+ // version of it, since the owner already controls the agent's own trading.
+ if (leader.user_id === userId) {
+ return fail(403, 'self_copy', 'You cannot copy an agent you own; you already control its trading.');
+ }
+
+ // Sybil bar: a leader needs a real, closed, on-chain track record before a
+ // copier can attach money to it. The unmet criteria go back in the body so the
+ // UI can say exactly what is missing instead of "not eligible".
+ const profile = await leaderCopyProfile(leaderId, network);
+ const eligibility = evaluateLeaderEligibility(profile);
+ if (!eligibility.eligible) {
+ return fail(
+ 409,
+ 'leader_not_copyable',
+ `${leader.name || 'This trader'} does not have enough verified history to be copied yet: ${eligibility.unmet.map((u) => u.label).join(', ')}.`,
+ { eligibility: { ...eligibility, requirements: LEADER_ELIGIBILITY, network } },
+ );
+ }
+
+ const norm = normalizeSubscriptionInput(body);
+ if (!norm.ok) return fail(400, 'invalid_config', norm.error);
+ const v = norm.value;
+
+ // Denormalize the leader's trading wallet from their most recent sniper position.
+ const [pos] = await sql`
+ select wallet from agent_sniper_positions
+ where agent_id = ${leaderId} and network = ${network}
+ order by opened_at desc limit 1
+ `;
+ const leaderWallet = pos?.wallet || null;
+
+ const [row] = await sql`
+ insert into copy_subscriptions (
+ copier_user_id, copier_wallet, leader_agent_id, leader_wallet, network, status,
+ sizing_rule, fixed_sol, multiplier, pct_balance,
+ per_trade_cap_sol, min_order_sol, daily_budget_sol, max_open_copies,
+ mcap_floor_usd, mcap_ceiling_usd, copy_sells, require_safety_pass, min_oracle_score, perf_fee_bps,
+ max_drawdown_pct, telegram_chat_id
+ ) values (
+ ${userId}, ${wallet}, ${leaderId}, ${leaderWallet}, ${network}, 'active',
+ ${v.sizing_rule}, ${v.fixed_sol}, ${v.multiplier}, ${v.pct_balance},
+ ${v.per_trade_cap_sol}, ${v.min_order_sol}, ${v.daily_budget_sol}, ${v.max_open_copies},
+ ${v.mcap_floor_usd}, ${v.mcap_ceiling_usd}, ${v.copy_sells}, ${v.require_safety_pass}, ${v.min_oracle_score}, ${v.perf_fee_bps},
+ ${v.max_drawdown_pct}, ${v.telegram_chat_id || null}
+ )
+ on conflict (copier_user_id, leader_agent_id, network) do update set
+ copier_wallet = excluded.copier_wallet,
+ leader_wallet = excluded.leader_wallet,
+ status = 'active',
+ sizing_rule = excluded.sizing_rule,
+ fixed_sol = excluded.fixed_sol,
+ multiplier = excluded.multiplier,
+ pct_balance = excluded.pct_balance,
+ per_trade_cap_sol = excluded.per_trade_cap_sol,
+ min_order_sol = excluded.min_order_sol,
+ daily_budget_sol = excluded.daily_budget_sol,
+ max_open_copies = excluded.max_open_copies,
+ mcap_floor_usd = excluded.mcap_floor_usd,
+ mcap_ceiling_usd = excluded.mcap_ceiling_usd,
+ copy_sells = excluded.copy_sells,
+ require_safety_pass = excluded.require_safety_pass,
+ min_oracle_score = excluded.min_oracle_score,
+ perf_fee_bps = excluded.perf_fee_bps,
+ max_drawdown_pct = excluded.max_drawdown_pct,
+ telegram_chat_id = excluded.telegram_chat_id,
+ -- Re-subscribing is a deliberate act, so it clears an auto-pause. A
+ -- breaker that stayed latched here would silently re-arm a subscription
+ -- the copier just reconfigured to a wider limit.
+ paused_reason = null,
+ paused_at = null,
+ updated_at = now()
+ returning *
+ `;
+ return { ok: true, subscription: row, leader: { id: leaderId, name: leader.name || null }, profile };
+}
diff --git a/api/_lib/migrations/20260929120000_copy_syndicates.sql b/api/_lib/migrations/20260929120000_copy_syndicates.sql
new file mode 100644
index 000000000..39ebd03d1
--- /dev/null
+++ b/api/_lib/migrations/20260929120000_copy_syndicates.sql
@@ -0,0 +1,93 @@
+-- Migration: syndicates, named groups of copiers who follow the same leader(s).
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260929120000_copy_syndicates.sql
+-- Idempotent.
+--
+-- A syndicate is a team on top of the existing copy loop, not a new money path.
+-- Joining one creates ordinary copy_subscriptions rows through the same guarded
+-- subscribe path /api/copy/subscriptions uses (self-copy refusal, the copyable
+-- bar, the member's own sizing, per-trade cap, daily budget and drawdown
+-- breaker), so the fanout cron, the intents on /dashboard/copy and the HWM
+-- performance fee all work unchanged. No member funds are pooled: every member
+-- keeps their own wallet and their own caps, and leaving stops only the
+-- subscriptions the join itself created.
+--
+-- Group performance is read live from copy_executions (the members' real copy
+-- intents inside their membership window), priced exactly the way
+-- api/_lib/copy-earnings.js prices a copier's realized profit. Nothing here
+-- stores a performance number. api/_lib/syndicates.js owns reads and writes.
+
+begin;
+
+create table if not exists copy_syndicates (
+ id uuid primary key default gen_random_uuid(),
+ slug text not null unique,
+ name text not null,
+ motto text,
+ color text not null default '#7c5cff',
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ founder_user_id uuid not null references users(id) on delete cascade,
+ status text not null default 'active' check (status in ('active','archived')),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint copy_syndicates_slug_shape check (slug ~ '^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$'),
+ constraint copy_syndicates_name_len check (char_length(name) between 3 and 40),
+ constraint copy_syndicates_motto_len check (motto is null or char_length(motto) <= 140),
+ constraint copy_syndicates_color_hex check (color ~ '^#[0-9a-f]{6}$')
+);
+
+-- Two syndicates may not share a name on a network, whatever the casing.
+create unique index if not exists copy_syndicates_name_uniq
+ on copy_syndicates (network, lower(name));
+create index if not exists copy_syndicates_board
+ on copy_syndicates (network, status, created_at desc);
+create index if not exists copy_syndicates_founder
+ on copy_syndicates (founder_user_id, network, status);
+
+-- The leader(s) a syndicate follows: one to three agents, fixed at founding.
+create table if not exists copy_syndicate_leaders (
+ syndicate_id uuid not null references copy_syndicates(id) on delete cascade,
+ leader_agent_id uuid not null references agent_identities(id) on delete cascade,
+ position smallint not null default 0,
+ primary key (syndicate_id, leader_agent_id)
+);
+create index if not exists copy_syndicate_leaders_agent
+ on copy_syndicate_leaders (leader_agent_id);
+
+create table if not exists copy_syndicate_members (
+ id uuid primary key default gen_random_uuid(),
+ syndicate_id uuid not null references copy_syndicates(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ role text not null default 'member' check (role in ('founder','member')),
+ status text not null default 'active' check (status in ('active','left')),
+ joined_at timestamptz not null default now(),
+ left_at timestamptz
+);
+
+-- One team per copier per network. A syndicate is an identity ("whose side are
+-- you on"), and two memberships would also make the group curves double-count
+-- the same copy intents.
+create unique index if not exists copy_syndicate_members_one_team
+ on copy_syndicate_members (user_id, network)
+ where status = 'active';
+create index if not exists copy_syndicate_members_roster
+ on copy_syndicate_members (syndicate_id, status, joined_at);
+
+-- Which copy subscriptions a membership rides on. created_by_join records
+-- whether the join created the subscription (leaving stops it) or found the
+-- member already copying that leader (leaving leaves it exactly as it was).
+create table if not exists copy_syndicate_member_subs (
+ member_id uuid not null references copy_syndicate_members(id) on delete cascade,
+ subscription_id uuid not null references copy_subscriptions(id) on delete cascade,
+ created_by_join boolean not null default true,
+ primary key (member_id, subscription_id)
+);
+create index if not exists copy_syndicate_member_subs_sub
+ on copy_syndicate_member_subs (subscription_id);
+
+comment on table copy_syndicates is
+ 'Named groups of copiers following the same leader(s). Membership rides on ordinary copy_subscriptions; no funds are pooled.';
+comment on column copy_syndicate_member_subs.created_by_join is
+ 'true when joining created the subscription (leaving stops it); false when the member already copied that leader (leaving keeps it).';
+
+commit;
diff --git a/api/_lib/streaks.js b/api/_lib/streaks.js
index a25228bc6..488df0164 100644
--- a/api/_lib/streaks.js
+++ b/api/_lib/streaks.js
@@ -27,6 +27,11 @@ export const BADGES = Object.freeze({
FIRST_REMIX_RECEIVED: 'first_remix_received',
STREAK_7: 'streak_7',
COPY_PATH_COMPLETE: 'copy_path_complete',
+ SYNDICATE_FOUNDER: 'syndicate_founder',
+ SYNDICATE_MEMBER: 'syndicate_member',
+ QUEST_FIRST: 'quest_first',
+ QUEST_CLEAR: 'quest_clear',
+ QUEST_STREAK_7: 'quest_streak_7',
TOP10: (metric) => `top10_${metric}`,
});
@@ -51,6 +56,31 @@ export const BADGE_META = {
description: 'Watched a verified trade, ghost-copied a leader, placed a real trade, and started a guarded copy.',
icon: '🧭',
},
+ syndicate_founder: {
+ label: 'Syndicate Founder',
+ description: 'Raised a flag: founded a copy-trading syndicate around a verified leader.',
+ icon: '🚩',
+ },
+ syndicate_member: {
+ label: 'Syndicate Member',
+ description: 'Joined a copy-trading syndicate and rode with the team under your own caps.',
+ icon: '🛡️',
+ },
+ quest_first: {
+ label: 'First Quest',
+ description: 'Completed a daily trading quest.',
+ icon: '🎯',
+ },
+ quest_clear: {
+ label: 'Daily Clear',
+ description: 'Cleared the daily trading quests in a single UTC day.',
+ icon: '⚡',
+ },
+ quest_streak_7: {
+ label: 'Quest Streak 7',
+ description: 'Cleared the daily trading quests seven days running.',
+ icon: '🏅',
+ },
};
function top10Meta(metric) {
diff --git a/api/_lib/syndicates.js b/api/_lib/syndicates.js
new file mode 100644
index 000000000..b69980959
--- /dev/null
+++ b/api/_lib/syndicates.js
@@ -0,0 +1,740 @@
+// Syndicates: named teams of copiers who follow the same leader(s) together.
+// ---------------------------------------------------------------------------
+// Tribalism is the strongest retention force in crypto, so a syndicate gives a
+// copier a team, a flag, and a rival: a named group with a public page, a
+// roster, a group equity curve, and a standing on a board against every other
+// syndicate. Leaders can run one as their fan club.
+//
+// It is a layer over the existing copy loop, never a parallel money path:
+//
+// - Joining creates ordinary copy_subscriptions rows through subscribeCopier
+// (api/_lib/copy-subscribe.js), the exact gates /api/copy/subscriptions
+// runs: self-copy refusal, the copyable bar, the member's OWN sizing, per-
+// trade cap, daily budget and drawdown breaker. The fanout cron, the intents
+// on /dashboard/copy and the HWM performance fee work unchanged.
+// - No funds are pooled and nothing is custodied. Every member keeps their own
+// wallet and caps. Leaving stops only the subscriptions the join created; a
+// subscription the member already had before joining is left exactly as it was.
+// - Group performance is read live from the members' real copy_executions
+// inside their membership window, priced the way api/_lib/copy-earnings.js
+// prices a copier's realized profit (committed size x the leader's realized
+// return on the positions the copier acted on). Nothing stores a number.
+//
+// The coins behind any of this are whatever the leaders traded (runtime data).
+// $THREE remains the only coin this platform promotes.
+
+import { sql } from './db.js';
+import { subscribeCopier, BASE58_RE, COPY_NETWORKS } from './copy-subscribe.js';
+import { normalizeSubscriptionInput } from './copy-engine.js';
+import { LEADER_ELIGIBILITY, evaluateLeaderEligibility, leaderCopyProfile } from './copy-eligibility.js';
+import { containsHateSlur } from './display-name-safety.js';
+import { SIMULATED_SIG } from './trade-card.js';
+import { unlockBadge, BADGES } from './streaks.js';
+import { isUuid } from './validate.js';
+
+/** The flag palette. A fixed set keeps every board legible in both themes. */
+export const SYNDICATE_COLORS = Object.freeze([
+ '#7c5cff', '#22d3ee', '#34d399', '#f59e0b', '#fb7185', '#f472b6', '#60a5fa', '#a3e635',
+]);
+export const MAX_SYNDICATE_LEADERS = 3;
+/** Active syndicates one user may found per network: a floor against squatting names. */
+export const MAX_FOUNDED_PER_NETWORK = 3;
+export const BOARD_SORTS = Object.freeze(['profit', 'members', 'new']);
+/** Slugs that name an API route under /api/syndicates/, so no syndicate may take them. */
+const RESERVED_SLUGS = new Set(['leaders', 'membership', 'index', 'new']);
+
+const LAMPORTS = 1e9;
+const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
+const round2 = (x) => Math.round(x * 100) / 100;
+const round4 = (x) => Math.round(x * 1e4) / 1e4;
+const round6 = (x) => Math.round(x * 1e6) / 1e6;
+const lamToSol = (l) => n(l) / LAMPORTS;
+const iso = (v) => (v ? new Date(v).toISOString() : null);
+const fail = (status, code, message, extra = {}) => ({ ok: false, status, code, message, extra });
+const isUniqueViolation = (err) => err?.code === '23505' || /duplicate key|unique constraint/i.test(err?.message || '');
+
+// ── Pure helpers ─────────────────────────────────────────────────────────────
+
+/** A URL slug from a syndicate name: lowercase ascii, hyphen-joined, 3 to 40 chars. PURE. */
+export function slugifyName(name) {
+ const s = String(name || '')
+ .normalize('NFKD')
+ .replace(/[̀-ͯ]/g, '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 40)
+ .replace(/-+$/g, '');
+ return /^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(s) ? s : null;
+}
+
+/**
+ * Validate founding input. PURE.
+ * @returns {{ok:true, value:{name:string, motto:string|null, color:string, network:string, leader_agent_ids:string[], slug:string}} | {ok:false, error:string}}
+ */
+export function validateSyndicateInput(raw = {}) {
+ const name = typeof raw.name === 'string' ? raw.name.replace(/\s+/g, ' ').trim() : '';
+ if (name.length < 3 || name.length > 40) return { ok: false, error: 'Name must be 3 to 40 characters.' };
+ const slug = slugifyName(name);
+ if (!slug) return { ok: false, error: 'Name needs at least three letters or numbers.' };
+ if (RESERVED_SLUGS.has(slug)) return { ok: false, error: 'That name is reserved. Pick another.' };
+
+ const mottoRaw = typeof raw.motto === 'string' ? raw.motto.replace(/\s+/g, ' ').trim() : '';
+ if (mottoRaw.length > 140) return { ok: false, error: 'Motto must be 140 characters or fewer.' };
+ const motto = mottoRaw || null;
+
+ if (containsHateSlur(name) || (motto && containsHateSlur(motto))) {
+ return { ok: false, error: 'That name or motto is not allowed.' };
+ }
+
+ const color = typeof raw.color === 'string' ? raw.color.toLowerCase() : SYNDICATE_COLORS[0];
+ if (!SYNDICATE_COLORS.includes(color)) return { ok: false, error: 'Pick one of the flag colors.' };
+
+ const network = COPY_NETWORKS.has(raw.network) ? raw.network : 'mainnet';
+
+ const ids = Array.isArray(raw.leader_agent_ids) ? raw.leader_agent_ids.map((x) => String(x || '').trim()) : [];
+ const unique = [...new Set(ids)];
+ if (unique.length === 0) return { ok: false, error: 'Pick at least one leader to follow.' };
+ if (unique.length > MAX_SYNDICATE_LEADERS) return { ok: false, error: `A syndicate follows at most ${MAX_SYNDICATE_LEADERS} leaders.` };
+ if (!unique.every(isUuid)) return { ok: false, error: 'Every leader must be an agent id.' };
+
+ return { ok: true, value: { name, motto, color, network, leader_agent_ids: unique, slug } };
+}
+
+/**
+ * Fold a syndicate's closed copies into its group curve. PURE.
+ * @param {Array<{closed_at:*, profit_sol:*}>} rows acted buy copies whose leader position closed, oldest first.
+ * @param {number} [maxPoints]
+ * @returns {{points:Array<{t:string, cum_sol:number}>, peak_sol:number, trough_sol:number, final_sol:number}}
+ */
+export function buildGroupCurve(rows = [], maxPoints = 120) {
+ let cum = 0;
+ let peak = 0;
+ let trough = 0;
+ const all = [];
+ for (const r of rows) {
+ const t = r?.closed_at ? new Date(r.closed_at) : null;
+ if (!t || Number.isNaN(t.getTime())) continue;
+ cum += n(r.profit_sol);
+ if (cum > peak) peak = cum;
+ if (cum < trough) trough = cum;
+ all.push({ t: t.toISOString(), cum_sol: round6(cum) });
+ }
+ let points = all;
+ if (all.length > maxPoints) {
+ // Keep the shape honest when thinning: always keep the first and last point
+ // and sample evenly between them, never drop the endpoint the headline shows.
+ const step = (all.length - 1) / (maxPoints - 1);
+ points = Array.from({ length: maxPoints }, (_, i) => all[Math.round(i * step)]);
+ }
+ return { points, peak_sol: round6(peak), trough_sol: round6(trough), final_sol: round6(cum) };
+}
+
+/** Shape one board row from the aggregate query. PURE. */
+export function shapeBoardRow(r) {
+ const acted = n(r.acted);
+ const closed = n(r.closed_copies);
+ const wins = n(r.winning_copies);
+ const leaderPnl = lamToSol(r.leader_pnl_lamports);
+ const leaderEntry = lamToSol(r.leader_entry_lamports);
+ return {
+ id: r.id,
+ slug: r.slug,
+ name: r.name,
+ motto: r.motto || null,
+ color: r.color,
+ network: r.network,
+ created_at: iso(r.created_at),
+ official: r.official === true,
+ members: n(r.members),
+ leaders: Array.isArray(r.leaders) ? r.leaders.map((l) => ({ agent_id: l.agent_id, name: l.name || 'Unnamed trader', image: l.image || null })) : [],
+ performance: {
+ intents: n(r.intents),
+ acted,
+ copied_sol: round4(n(r.copied_sol)),
+ realized_profit_sol: round6(n(r.profit_sol)),
+ closed_copies: closed,
+ win_rate_pct: closed > 0 ? round2((wins / closed) * 100) : null,
+ },
+ // What the followed leaders did on-chain since the day this syndicate formed:
+ // the edge the group was riding, measurable before any member has copied.
+ since_founding: {
+ leader_closes: n(r.leader_closes),
+ leader_pnl_sol: round4(leaderPnl),
+ leader_roi_pct: leaderEntry > 0 ? round2((leaderPnl / leaderEntry) * 100) : null,
+ },
+ rank: r.rank == null ? null : n(r.rank),
+ url: `/syndicates/${r.slug}`,
+ };
+}
+
+/**
+ * A syndicate's standing on the profit board and its rival: the syndicate right
+ * above it (the one to catch) or, for the leader of the board, the one right
+ * below (the one chasing). PURE.
+ * @param {Array<{id:string, slug:string, name:string, color:string, rank:number, performance:{realized_profit_sol:number}}>} rows
+ * board rows carrying their board-wide profit rank (at least the syndicate and its neighbors).
+ * @param {string} syndicateId
+ * @param {number} total active syndicates on the board.
+ */
+export function computeStanding(rows = [], syndicateId, total = rows.length) {
+ const me = rows.find((s) => s.id === syndicateId);
+ if (!me || me.rank == null) return { rank: null, total, rival: null };
+ const ahead = me.rank > 1;
+ const other = rows.find((s) => s.rank === (ahead ? me.rank - 1 : me.rank + 1)) || null;
+ const rival = other
+ ? {
+ slug: other.slug,
+ name: other.name,
+ color: other.color,
+ url: `/syndicates/${other.slug}`,
+ direction: ahead ? 'ahead' : 'behind',
+ realized_profit_sol: other.performance.realized_profit_sol,
+ gap_sol: round6(Math.abs(other.performance.realized_profit_sol - me.performance.realized_profit_sol)),
+ }
+ : null;
+ return { rank: me.rank, total, rival };
+}
+
+// ── Reads ────────────────────────────────────────────────────────────────────
+
+function orderClause(sort) {
+ if (sort === 'members') return sql`order by members desc, profit_sol desc, s.created_at asc`;
+ if (sort === 'new') return sql`order by s.created_at desc`;
+ return sql`order by profit_sol desc, members desc, s.created_at asc`;
+}
+
+/**
+ * The public board: every active syndicate on a network with its roster size,
+ * its group performance from real copy_executions, and its leaders' live record
+ * since founding. Ranked by realized group profit unless sorted otherwise.
+ */
+export async function loadBoard({ network = 'mainnet', sort = 'profit', limit = 24, offset = 0, onlyId = null, rankFrom = null, rankTo = null } = {}) {
+ const lim = Math.min(100, Math.max(1, Math.floor(n(limit)) || 24));
+ const off = Math.max(0, Math.floor(n(offset)));
+ const rows = await sql`
+ with s as (
+ select * from copy_syndicates where network = ${network} and status = 'active'
+ ),
+ mem as (
+ select m.syndicate_id, count(*)::int as members
+ from copy_syndicate_members m
+ join s on s.id = m.syndicate_id
+ where m.status = 'active'
+ group by m.syndicate_id
+ ),
+ perf as (
+ select m.syndicate_id,
+ count(*) filter (where e.direction = 'buy')::int as intents,
+ count(*) filter (where e.direction = 'buy' and e.status = 'acted')::int as acted,
+ coalesce(sum(e.planned_sol) filter (where e.direction = 'buy' and e.status = 'acted'), 0) as copied_sol,
+ coalesce(sum(e.planned_sol * (p.realized_pnl_pct / 100.0)) filter (where e.direction = 'buy' and e.status = 'acted' and p.id is not null), 0) as profit_sol,
+ count(*) filter (where e.direction = 'buy' and e.status = 'acted' and p.id is not null)::int as closed_copies,
+ count(*) filter (where e.direction = 'buy' and e.status = 'acted' and p.id is not null and p.realized_pnl_pct > 0)::int as winning_copies
+ from copy_syndicate_members m
+ join s on s.id = m.syndicate_id
+ join copy_syndicate_member_subs ms on ms.member_id = m.id
+ join copy_executions e on e.subscription_id = ms.subscription_id
+ and e.created_at >= m.joined_at and (m.left_at is null or e.created_at < m.left_at)
+ left join agent_sniper_positions p on p.id = e.leader_position_id
+ and p.status = 'closed' and p.realized_pnl_pct is not null
+ group by m.syndicate_id
+ ),
+ lead as (
+ select l.syndicate_id,
+ json_agg(json_build_object('agent_id', a.id, 'name', a.name,
+ 'image', coalesce(a.avatar_url, a.profile_image_url)) order by l.position) as leaders,
+ bool_or(a.user_id = s.founder_user_id) as official
+ from copy_syndicate_leaders l
+ join s on s.id = l.syndicate_id
+ join agent_identities a on a.id = l.leader_agent_id
+ group by l.syndicate_id
+ ),
+ since as (
+ select l.syndicate_id,
+ count(p.id)::int as leader_closes,
+ coalesce(sum(p.realized_pnl_lamports), 0)::text as leader_pnl_lamports,
+ coalesce(sum(p.entry_quote_lamports), 0)::text as leader_entry_lamports
+ from copy_syndicate_leaders l
+ join s on s.id = l.syndicate_id
+ left join agent_sniper_positions p on p.agent_id = l.leader_agent_id
+ and p.network = s.network and p.status = 'closed' and p.closed_at >= s.created_at
+ and p.buy_sig is not null and p.buy_sig <> ${SIMULATED_SIG}
+ group by l.syndicate_id
+ ),
+ ranked as (
+ select s.id, s.slug, s.name, s.motto, s.color, s.network, s.created_at,
+ coalesce(mem.members, 0) as members,
+ coalesce(perf.intents, 0) as intents, coalesce(perf.acted, 0) as acted,
+ coalesce(perf.copied_sol, 0) as copied_sol, coalesce(perf.profit_sol, 0) as profit_sol,
+ coalesce(perf.closed_copies, 0) as closed_copies, coalesce(perf.winning_copies, 0) as winning_copies,
+ lead.leaders, coalesce(lead.official, false) as official,
+ coalesce(since.leader_closes, 0) as leader_closes,
+ coalesce(since.leader_pnl_lamports, '0') as leader_pnl_lamports,
+ coalesce(since.leader_entry_lamports, '0') as leader_entry_lamports,
+ row_number() over (order by coalesce(perf.profit_sol, 0) desc, coalesce(mem.members, 0) desc, s.created_at asc) as rank,
+ count(*) over () as total
+ from s
+ left join mem on mem.syndicate_id = s.id
+ left join perf on perf.syndicate_id = s.id
+ left join lead on lead.syndicate_id = s.id
+ left join since on since.syndicate_id = s.id
+ )
+ select * from ranked s
+ where (${onlyId}::uuid is null or s.id = ${onlyId}::uuid)
+ and (${rankFrom}::int is null or s.rank >= ${rankFrom}::int)
+ and (${rankTo}::int is null or s.rank <= ${rankTo}::int)
+ ${orderClause(sort)}
+ limit ${lim} offset ${off}
+ `;
+ // total counts the whole board (the window runs before the filters above).
+ const total = rows.length ? n(rows[0].total) : 0;
+ return { network, sort, limit: lim, offset: off, total, syndicates: rows.map(shapeBoardRow) };
+}
+
+/**
+ * Leaders a syndicate can be founded around, with their whole closed record and
+ * the copyable verdict. The same universe ghost-copy draws from (public agents
+ * with closed round-trips), judged by the same bar a follow must clear.
+ */
+export async function loadFoundingCandidates(network = 'mainnet', { limit = 12 } = {}) {
+ const rows = await sql`
+ select a.id, a.name, a.avatar_url, a.profile_image_url,
+ count(p.id)::int as settled,
+ count(p.id) filter (where p.realized_pnl_lamports > 0)::int as wins,
+ max(p.closed_at) as last_close_at
+ from agent_identities a
+ join agent_sniper_positions p on p.agent_id = a.id
+ where a.deleted_at is null and a.is_public <> false
+ and p.network = ${network} and p.status = 'closed' and p.closed_at is not null
+ group by a.id, a.name, a.avatar_url, a.profile_image_url
+ order by max(p.closed_at) desc
+ limit ${Math.min(50, Math.max(1, Math.floor(n(limit)) || 12))}
+ `;
+ const profiles = await Promise.all(rows.map((r) => leaderCopyProfile(r.id, network)));
+ const out = rows.map((r, i) => {
+ const profile = profiles[i];
+ const eligibility = evaluateLeaderEligibility(profile);
+ const settled = n(r.settled);
+ return {
+ agent_id: r.id,
+ name: r.name || 'Unnamed trader',
+ image: r.avatar_url || r.profile_image_url || null,
+ record: {
+ settled: profile.settled,
+ win_rate_pct: settled > 0 ? round2((n(r.wins) / settled) * 100) : null,
+ realized_pnl_sol: profile.realized_pnl_sol,
+ deployed_sol: profile.deployed_sol,
+ roi_pct: profile.deployed_sol > 0 ? round2((profile.realized_pnl_sol / profile.deployed_sol) * 100) : null,
+ max_drawdown_pct: profile.max_drawdown_pct,
+ last_close_at: iso(r.last_close_at),
+ },
+ copyable: eligibility.eligible,
+ unmet: eligibility.unmet.map((u) => u.label),
+ trader_url: `/trader/${r.id}`,
+ ghost_url: `/ghost-copy?leader=${r.id}&budget=1&window=7d`,
+ };
+ });
+ // Copyable first (a syndicate can only form around them), then most recently active.
+ out.sort((a, b) => Number(b.copyable) - Number(a.copyable));
+ return { network, requirements: LEADER_ELIGIBILITY, leaders: out };
+}
+
+async function syndicateBySlug(slug) {
+ if (!slugifyName(slug) || slugifyName(slug) !== slug) return null;
+ const [row] = await sql`
+ select s.*, u.username as founder_username, u.display_name as founder_display_name
+ from copy_syndicates s
+ left join users u on u.id = s.founder_user_id
+ where s.slug = ${slug}
+ limit 1
+ `;
+ return row || null;
+}
+
+async function syndicateLeaders(syndicateId) {
+ return sql`
+ select l.leader_agent_id, l.position, a.user_id, a.name, a.avatar_url, a.profile_image_url,
+ a.is_public, a.deleted_at
+ from copy_syndicate_leaders l
+ join agent_identities a on a.id = l.leader_agent_id
+ where l.syndicate_id = ${syndicateId}
+ order by l.position asc
+ `;
+}
+
+/** The public syndicate page payload. Returns null for an unknown slug. */
+export async function loadSyndicate(slug) {
+ const s = await syndicateBySlug(slug);
+ if (!s) return null;
+
+ const [leaderRows, roster, counts, curveRows, board] = await Promise.all([
+ syndicateLeaders(s.id),
+ sql`
+ select m.role, m.joined_at, u.username, u.display_name, u.avatar_url
+ from copy_syndicate_members m
+ join users u on u.id = m.user_id
+ where m.syndicate_id = ${s.id} and m.status = 'active'
+ order by (m.role = 'founder') desc, m.joined_at asc
+ limit 60
+ `,
+ sql`
+ select count(*) filter (where m.status = 'active')::int as members,
+ count(*) filter (where m.status = 'left')::int as alumni,
+ count(distinct m.id) filter (where m.status = 'active' and cs.status = 'active')::int as copying
+ from copy_syndicate_members m
+ left join copy_syndicate_member_subs ms on ms.member_id = m.id
+ left join copy_subscriptions cs on cs.id = ms.subscription_id
+ where m.syndicate_id = ${s.id}
+ `,
+ sql`
+ select p.closed_at, e.planned_sol * (p.realized_pnl_pct / 100.0) as profit_sol
+ from copy_syndicate_members m
+ join copy_syndicate_member_subs ms on ms.member_id = m.id
+ join copy_executions e on e.subscription_id = ms.subscription_id
+ and e.created_at >= m.joined_at and (m.left_at is null or e.created_at < m.left_at)
+ join agent_sniper_positions p on p.id = e.leader_position_id
+ and p.status = 'closed' and p.realized_pnl_pct is not null
+ where m.syndicate_id = ${s.id} and e.direction = 'buy' and e.status = 'acted'
+ order by p.closed_at asc
+ limit 5000
+ `,
+ s.status === 'active' ? loadBoard({ network: s.network, onlyId: s.id, limit: 1 }) : Promise.resolve({ syndicates: [], total: 0 }),
+ ]);
+
+ const profiles = await Promise.all(leaderRows.map((l) => leaderCopyProfile(l.leader_agent_id, s.network)));
+ const leaders = leaderRows.map((l, i) => {
+ const p = profiles[i];
+ const eligibility = evaluateLeaderEligibility(p);
+ return {
+ agent_id: l.leader_agent_id,
+ name: l.name || 'Unnamed trader',
+ image: l.avatar_url || l.profile_image_url || null,
+ available: l.deleted_at == null && l.is_public !== false,
+ record: {
+ settled: p.settled,
+ realized_pnl_sol: p.realized_pnl_sol,
+ deployed_sol: p.deployed_sol,
+ roi_pct: p.deployed_sol > 0 ? round2((p.realized_pnl_sol / p.deployed_sol) * 100) : null,
+ max_drawdown_pct: p.max_drawdown_pct,
+ last_closed_at: p.last_closed_at,
+ },
+ copyable: eligibility.eligible,
+ unmet: eligibility.unmet.map((u) => u.label),
+ trader_url: `/trader/${l.leader_agent_id}`,
+ };
+ });
+ const official = leaderRows.some((l) => l.user_id === s.founder_user_id);
+
+ const self = board.syndicates[0] || null;
+ // The rival is whoever sits one rank away on the profit board.
+ const neighbors = self?.rank
+ ? (await loadBoard({ network: s.network, rankFrom: Math.max(1, self.rank - 1), rankTo: self.rank + 1, limit: 3 })).syndicates
+ : [];
+ const standing = computeStanding(neighbors.length ? neighbors : self ? [self] : [], s.id, board.total);
+ const curve = buildGroupCurve(curveRows);
+ const c = counts[0] || {};
+
+ return {
+ syndicate: {
+ id: s.id,
+ slug: s.slug,
+ name: s.name,
+ motto: s.motto || null,
+ color: s.color,
+ network: s.network,
+ status: s.status,
+ created_at: iso(s.created_at),
+ official,
+ founder: { username: s.founder_username || null, display_name: s.founder_display_name || null },
+ url: `/syndicates/${s.slug}`,
+ },
+ leaders,
+ members: {
+ count: n(c.members),
+ copying: n(c.copying),
+ alumni: n(c.alumni),
+ list: roster.map((m) => ({
+ username: m.username || null,
+ display_name: m.display_name || m.username || 'Member',
+ avatar_url: m.avatar_url || null,
+ role: m.role,
+ joined_at: iso(m.joined_at),
+ })),
+ },
+ performance: {
+ ...(self?.performance || { intents: 0, acted: 0, copied_sol: 0, realized_profit_sol: 0, closed_copies: 0, win_rate_pct: null }),
+ curve,
+ },
+ since_founding: self?.since_founding || { leader_closes: 0, leader_pnl_sol: 0, leader_roi_pct: null },
+ standing,
+ joinable: s.status === 'active' && leaders.every((l) => l.available && l.copyable),
+ };
+}
+
+/** The signed-in viewer's relationship to a syndicate: membership, subscriptions, conflicts. */
+export async function loadMembership(userId, slug) {
+ const s = await syndicateBySlug(slug);
+ if (!s) return null;
+ const [leaderRows, mine, subs] = await Promise.all([
+ syndicateLeaders(s.id),
+ sql`
+ select m.id, m.syndicate_id, m.role, m.status, m.joined_at, cs.slug, cs.name
+ from copy_syndicate_members m
+ join copy_syndicates cs on cs.id = m.syndicate_id
+ where m.user_id = ${userId} and m.network = ${s.network} and m.status = 'active'
+ limit 1
+ `,
+ sql`
+ select ms.subscription_id, ms.created_by_join, c.leader_agent_id, c.status, c.paused_reason, c.copier_wallet
+ from copy_syndicate_members m
+ join copy_syndicate_member_subs ms on ms.member_id = m.id
+ join copy_subscriptions c on c.id = ms.subscription_id
+ where m.user_id = ${userId} and m.syndicate_id = ${s.id} and m.status = 'active'
+ `,
+ ]);
+ const active = mine[0] || null;
+ const isMember = !!active && active.syndicate_id === s.id;
+ const ownsLeader = leaderRows.some((l) => l.user_id === userId);
+ return {
+ slug: s.slug,
+ is_founder: s.founder_user_id === userId,
+ owns_leader: ownsLeader,
+ member: isMember
+ ? {
+ role: active.role,
+ joined_at: iso(active.joined_at),
+ subscriptions: subs.map((r) => ({
+ subscription_id: r.subscription_id,
+ leader_agent_id: r.leader_agent_id,
+ status: r.status,
+ paused_reason: r.paused_reason || null,
+ created_by_join: r.created_by_join,
+ })),
+ wallet: subs[0]?.copier_wallet || null,
+ }
+ : null,
+ other_syndicate: active && !isMember ? { slug: active.slug, name: active.name, url: `/syndicates/${active.slug}` } : null,
+ };
+}
+
+// ── Writes ───────────────────────────────────────────────────────────────────
+
+/**
+ * Found a syndicate around one to three copyable leaders.
+ * @returns {Promise<{ok:true, syndicate:object, official:boolean} | {ok:false, status:number, code:string, message:string, extra:object}>}
+ */
+export async function createSyndicate({ userId, input }) {
+ const v = validateSyndicateInput(input);
+ if (!v.ok) return fail(400, 'invalid_syndicate', v.error);
+ const { name, motto, color, network, leader_agent_ids: leaderIds, slug } = v.value;
+
+ const [{ founded = 0 } = {}] = await sql`
+ select count(*)::int as founded from copy_syndicates
+ where founder_user_id = ${userId} and network = ${network} and status = 'active'
+ `;
+ if (n(founded) >= MAX_FOUNDED_PER_NETWORK) {
+ return fail(409, 'founder_limit', `You already run ${MAX_FOUNDED_PER_NETWORK} syndicates. Grow the ones you have first.`);
+ }
+
+ const agents = await sql`
+ select id, user_id, name from agent_identities
+ where id = any(${leaderIds}) and deleted_at is null and is_public <> false
+ `;
+ if (agents.length !== leaderIds.length) return fail(404, 'leader_not_found', 'Every leader must be a public trader.');
+
+ // A syndicate that nobody can join is a dead page, so every leader has to clear
+ // the same copyable bar a single follow must clear.
+ const profiles = await Promise.all(leaderIds.map((id) => leaderCopyProfile(id, network)));
+ const blocked = [];
+ leaderIds.forEach((id, i) => {
+ const e = evaluateLeaderEligibility(profiles[i]);
+ if (!e.eligible) {
+ const a = agents.find((x) => x.id === id);
+ blocked.push({ agent_id: id, name: a?.name || 'Unnamed trader', unmet: e.unmet.map((u) => u.label) });
+ }
+ });
+ if (blocked.length) {
+ return fail(409, 'leader_not_copyable',
+ `${blocked.map((b) => b.name).join(', ')} ${blocked.length === 1 ? 'does' : 'do'} not have a copyable record yet.`,
+ { leaders: blocked, requirements: LEADER_ELIGIBILITY });
+ }
+
+ let syndicate;
+ try {
+ [syndicate] = await sql`
+ insert into copy_syndicates (slug, name, motto, color, network, founder_user_id)
+ values (${slug}, ${name}, ${motto}, ${color}, ${network}, ${userId})
+ returning *
+ `;
+ } catch (err) {
+ if (isUniqueViolation(err)) return fail(409, 'name_taken', 'A syndicate with that name already exists. Pick another.');
+ throw err;
+ }
+
+ try {
+ for (let i = 0; i < leaderIds.length; i++) {
+ await sql`
+ insert into copy_syndicate_leaders (syndicate_id, leader_agent_id, position)
+ values (${syndicate.id}, ${leaderIds[i]}, ${i})
+ `;
+ }
+ } catch (err) {
+ await sql`delete from copy_syndicates where id = ${syndicate.id}`.catch(() => {});
+ throw err;
+ }
+
+ await unlockBadge(userId, BADGES.SYNDICATE_FOUNDER, { syndicate: syndicate.slug });
+ const official = agents.some((a) => a.user_id === userId);
+ return { ok: true, syndicate: { ...syndicate, url: `/syndicates/${syndicate.slug}` }, official };
+}
+
+/**
+ * Join a syndicate: one real, guarded copy subscription per leader, sized by the
+ * member's own rules. A subscription the member already had to a leader is linked,
+ * never overwritten, so joining can never silently change caps someone set earlier.
+ */
+export async function joinSyndicate({ userId, slug, body = {} }) {
+ const wallet = String(body.copier_wallet || '').trim();
+ if (!BASE58_RE.test(wallet)) return fail(400, 'invalid_wallet', 'Enter the Solana wallet you will copy from.');
+ const norm = normalizeSubscriptionInput(body);
+ if (!norm.ok) return fail(400, 'invalid_config', norm.error);
+
+ const s = await syndicateBySlug(slug);
+ if (!s) return fail(404, 'not_found', 'No such syndicate.');
+ if (s.status !== 'active') return fail(409, 'archived', 'This syndicate is no longer taking members.');
+
+ const leaderRows = await syndicateLeaders(s.id);
+ if (!leaderRows.length) return fail(409, 'no_leaders', 'This syndicate has no leaders to follow.');
+ const owned = leaderRows.find((l) => l.user_id === userId);
+ if (owned) {
+ return fail(403, 'self_copy', `You run ${owned.name || 'one of these leaders'}, so you cannot copy it. Share this page with your followers instead.`);
+ }
+
+ const [current] = await sql`
+ select m.id, m.syndicate_id, cs.slug, cs.name
+ from copy_syndicate_members m
+ join copy_syndicates cs on cs.id = m.syndicate_id
+ where m.user_id = ${userId} and m.network = ${s.network} and m.status = 'active'
+ limit 1
+ `;
+ if (current && current.syndicate_id === s.id) return { ok: true, already: true, membership: await loadMembership(userId, slug) };
+ if (current) {
+ return fail(409, 'already_in_syndicate', `You already ride with ${current.name}. Leave it before joining another.`,
+ { current: { slug: current.slug, name: current.name, url: `/syndicates/${current.slug}` } });
+ }
+
+ const leaderIds = leaderRows.map((l) => l.leader_agent_id);
+ const existing = await sql`
+ select id, leader_agent_id, status from copy_subscriptions
+ where copier_user_id = ${userId} and network = ${s.network} and leader_agent_id = any(${leaderIds})
+ `;
+ const live = new Map(existing.filter((e) => e.status !== 'stopped').map((e) => [e.leader_agent_id, e.id]));
+
+ // Check every leader that needs a NEW subscription before writing anything, so a
+ // join either follows the whole syndicate or changes nothing.
+ const toCreate = leaderRows.filter((l) => !live.has(l.leader_agent_id));
+ const profiles = await Promise.all(toCreate.map((l) => leaderCopyProfile(l.leader_agent_id, s.network)));
+ const blocked = [];
+ toCreate.forEach((l, i) => {
+ const e = evaluateLeaderEligibility(profiles[i]);
+ if (!e.eligible) blocked.push({ agent_id: l.leader_agent_id, name: l.name || 'Unnamed trader', unmet: e.unmet.map((u) => u.label) });
+ });
+ if (blocked.length) {
+ return fail(409, 'leader_not_copyable',
+ `${blocked.map((b) => b.name).join(', ')} cannot be copied right now, so this syndicate is closed to new members until it clears the bar.`,
+ { leaders: blocked, requirements: LEADER_ELIGIBILITY });
+ }
+
+ // Claim the team slot first: the partial unique index is the atomic guard
+ // against two concurrent joins putting one copier on two teams.
+ let member;
+ try {
+ [member] = await sql`
+ insert into copy_syndicate_members (syndicate_id, user_id, network, role)
+ values (${s.id}, ${userId}, ${s.network}, ${s.founder_user_id === userId ? 'founder' : 'member'})
+ returning *
+ `;
+ } catch (err) {
+ if (isUniqueViolation(err)) return fail(409, 'already_in_syndicate', 'You already ride with another syndicate. Leave it before joining this one.');
+ throw err;
+ }
+
+ const created = [];
+ const rollback = async () => {
+ if (created.length) {
+ await sql`
+ update copy_subscriptions set status = 'stopped', updated_at = now()
+ where id = any(${created}) and copier_user_id = ${userId}
+ `.catch(() => {});
+ }
+ await sql`delete from copy_syndicate_members where id = ${member.id}`.catch(() => {});
+ };
+
+ try {
+ for (const l of leaderRows) {
+ const linkedId = live.get(l.leader_agent_id);
+ if (linkedId) {
+ await sql`
+ insert into copy_syndicate_member_subs (member_id, subscription_id, created_by_join)
+ values (${member.id}, ${linkedId}, false)
+ on conflict do nothing
+ `;
+ continue;
+ }
+ const r = await subscribeCopier({ userId, body: { ...body, leader_agent_id: l.leader_agent_id, network: s.network, copier_wallet: wallet } });
+ if (!r.ok) {
+ await rollback();
+ return fail(r.status, r.code, r.message, r.extra);
+ }
+ created.push(r.subscription.id);
+ await sql`
+ insert into copy_syndicate_member_subs (member_id, subscription_id, created_by_join)
+ values (${member.id}, ${r.subscription.id}, true)
+ on conflict do nothing
+ `;
+ }
+ } catch (err) {
+ await rollback();
+ throw err;
+ }
+
+ await unlockBadge(userId, BADGES.SYNDICATE_MEMBER, { syndicate: s.slug });
+ return { ok: true, already: false, membership: await loadMembership(userId, slug) };
+}
+
+/**
+ * Leave a syndicate. Stops only the subscriptions the join created; any
+ * subscription the member already had before joining keeps running untouched.
+ */
+export async function leaveSyndicate({ userId, slug }) {
+ const s = await syndicateBySlug(slug);
+ if (!s) return fail(404, 'not_found', 'No such syndicate.');
+ const [member] = await sql`
+ select id from copy_syndicate_members
+ where syndicate_id = ${s.id} and user_id = ${userId} and status = 'active'
+ limit 1
+ `;
+ if (!member) return fail(404, 'not_member', 'You are not in this syndicate.');
+
+ const links = await sql`
+ select subscription_id, created_by_join from copy_syndicate_member_subs where member_id = ${member.id}
+ `;
+ const ownIds = links.filter((l) => l.created_by_join).map((l) => l.subscription_id);
+ const stopped = ownIds.length
+ ? await sql`
+ update copy_subscriptions set status = 'stopped', updated_at = now()
+ where id = any(${ownIds}) and copier_user_id = ${userId} and status <> 'stopped'
+ returning id
+ `
+ : [];
+ await sql`
+ update copy_syndicate_members set status = 'left', left_at = now()
+ where id = ${member.id}
+ `;
+ return {
+ ok: true,
+ stopped_subscriptions: stopped.map((r) => r.id),
+ kept_subscriptions: links.filter((l) => !l.created_by_join).map((l) => l.subscription_id),
+ };
+}
diff --git a/api/copy/subscriptions.js b/api/copy/subscriptions.js
index bf3c9eaaa..2a33c6a7b 100644
--- a/api/copy/subscriptions.js
+++ b/api/copy/subscriptions.js
@@ -21,13 +21,10 @@ 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 { normalizeSubscriptionInput } from '../_lib/copy-engine.js';
-import { BREAKER_REASON, LEADER_ELIGIBILITY, evaluateDrawdownBreaker, evaluateLeaderEligibility, leaderCopyProfile } from '../_lib/copy-eligibility.js';
+import { BREAKER_REASON, evaluateDrawdownBreaker, leaderCopyProfile } from '../_lib/copy-eligibility.js';
+import { subscribeCopier } from '../_lib/copy-subscribe.js';
import { isUuid } from '../_lib/validate.js';
-const NETWORKS = new Set(['mainnet', 'devnet']);
-const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
-
// Returns { userId, viaSession } or null (after writing a 401). Cookie-session
// writes additionally require a CSRF token; bearer clients are not CSRF-vulnerable.
async function requireUser(req, res) {
@@ -131,95 +128,9 @@ export default wrap(async (req, res) => {
return json(res, 200, { subscription: row });
}
- // Create / update.
- const leaderId = String(body.leader_agent_id || '').trim();
- const wallet = String(body.copier_wallet || '').trim();
- const network = NETWORKS.has(body.network) ? body.network : 'mainnet';
- if (!isUuid(leaderId)) return error(res, 400, 'invalid_leader', 'leader_agent_id must be an agent UUID');
- if (!BASE58_RE.test(wallet)) return error(res, 400, 'invalid_wallet', 'copier_wallet must be a valid Solana address');
-
- const [leader] = await sql`
- select id, user_id, name, is_public from agent_identities
- where id = ${leaderId} and deleted_at is null limit 1
- `;
- if (!leader || leader.is_public === false) return error(res, 404, 'leader_not_found', 'No such public trader.');
-
- // Wash-trade guard: copying your own agent routes the performance fee back to
- // you while inflating that leader's copier count, copied volume, and the public
- // "earned X for being copied" figure. Refused outright: there is no legitimate
- // version of it, since the owner already controls the agent's own trading.
- if (leader.user_id === userId) {
- return error(res, 403, 'self_copy', 'You cannot copy an agent you own; you already control its trading.');
- }
-
- // Sybil bar: a leader needs a real, closed, on-chain track record before a
- // copier can attach money to it. The unmet criteria go back in the body so the
- // UI can say exactly what is missing instead of "not eligible".
- const profile = await leaderCopyProfile(leaderId, network);
- const eligibility = evaluateLeaderEligibility(profile);
- if (!eligibility.eligible) {
- return error(
- res,
- 409,
- 'leader_not_copyable',
- `${leader.name || 'This trader'} does not have enough verified history to be copied yet: ${eligibility.unmet.map((u) => u.label).join(', ')}.`,
- { eligibility: { ...eligibility, requirements: LEADER_ELIGIBILITY, network } },
- );
- }
-
- const norm = normalizeSubscriptionInput(body);
- if (!norm.ok) return error(res, 400, 'invalid_config', norm.error);
- const v = norm.value;
-
- // Denormalize the leader's trading wallet from their most recent sniper position.
- const [pos] = await sql`
- select wallet from agent_sniper_positions
- where agent_id = ${leaderId} and network = ${network}
- order by opened_at desc limit 1
- `;
- const leaderWallet = pos?.wallet || null;
-
- const [row] = await sql`
- insert into copy_subscriptions (
- copier_user_id, copier_wallet, leader_agent_id, leader_wallet, network, status,
- sizing_rule, fixed_sol, multiplier, pct_balance,
- per_trade_cap_sol, min_order_sol, daily_budget_sol, max_open_copies,
- mcap_floor_usd, mcap_ceiling_usd, copy_sells, require_safety_pass, min_oracle_score, perf_fee_bps,
- max_drawdown_pct, telegram_chat_id
- ) values (
- ${userId}, ${wallet}, ${leaderId}, ${leaderWallet}, ${network}, 'active',
- ${v.sizing_rule}, ${v.fixed_sol}, ${v.multiplier}, ${v.pct_balance},
- ${v.per_trade_cap_sol}, ${v.min_order_sol}, ${v.daily_budget_sol}, ${v.max_open_copies},
- ${v.mcap_floor_usd}, ${v.mcap_ceiling_usd}, ${v.copy_sells}, ${v.require_safety_pass}, ${v.min_oracle_score}, ${v.perf_fee_bps},
- ${v.max_drawdown_pct}, ${v.telegram_chat_id || null}
- )
- on conflict (copier_user_id, leader_agent_id, network) do update set
- copier_wallet = excluded.copier_wallet,
- leader_wallet = excluded.leader_wallet,
- status = 'active',
- sizing_rule = excluded.sizing_rule,
- fixed_sol = excluded.fixed_sol,
- multiplier = excluded.multiplier,
- pct_balance = excluded.pct_balance,
- per_trade_cap_sol = excluded.per_trade_cap_sol,
- min_order_sol = excluded.min_order_sol,
- daily_budget_sol = excluded.daily_budget_sol,
- max_open_copies = excluded.max_open_copies,
- mcap_floor_usd = excluded.mcap_floor_usd,
- mcap_ceiling_usd = excluded.mcap_ceiling_usd,
- copy_sells = excluded.copy_sells,
- require_safety_pass = excluded.require_safety_pass,
- min_oracle_score = excluded.min_oracle_score,
- perf_fee_bps = excluded.perf_fee_bps,
- max_drawdown_pct = excluded.max_drawdown_pct,
- telegram_chat_id = excluded.telegram_chat_id,
- -- Re-subscribing is a deliberate act, so it clears an auto-pause. A
- -- breaker that stayed latched here would silently re-arm a subscription
- -- the copier just reconfigured to a wider limit.
- paused_reason = null,
- paused_at = null,
- updated_at = now()
- returning *
- `;
- return json(res, 200, { subscription: row, leader: { id: leaderId, name: leader.name || null }, leader_profile: profile });
+ // Create / update, through the one guarded follow path (self-copy refusal,
+ // the copyable bar, the copier's own caps) that a syndicate join also uses.
+ const result = await subscribeCopier({ userId, body });
+ if (!result.ok) return error(res, result.status, result.code, result.message, result.extra);
+ return json(res, 200, { subscription: result.subscription, leader: result.leader, leader_profile: result.profile });
});
diff --git a/api/syndicates/[slug].js b/api/syndicates/[slug].js
new file mode 100644
index 000000000..563094906
--- /dev/null
+++ b/api/syndicates/[slug].js
@@ -0,0 +1,45 @@
+// GET /api/syndicates/:slug
+// ---------------------------------------------------------------------------
+// One syndicate's public page: identity and flag, its leaders with their whole
+// closed record and copyable verdict, the roster (usernames only; never a
+// wallet or a size), the group equity curve from members' real acted copies,
+// what the leaders did on-chain since founding, and its standing on the profit
+// board with the rival one rank away. The signed-in viewer's own membership
+// lives at GET /api/syndicates/membership, so this stays cacheable.
+
+import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { loadSyndicate, slugifyName } from '../_lib/syndicates.js';
+
+/** The slug is the path segment; route params win over the query string. */
+export function syndicateSlugFromRequest(req) {
+ const fromRoute = req?.query?.slug;
+ let raw = typeof fromRoute === 'string' && fromRoute ? fromRoute : '';
+ if (!raw) {
+ const segments = new URL(req?.url || '/', 'http://x').pathname.split('/').filter(Boolean);
+ try {
+ raw = decodeURIComponent(segments[segments.length - 1] || '');
+ } catch {
+ return null;
+ }
+ }
+ const slug = String(raw).toLowerCase();
+ return slugifyName(slug) === slug ? slug : null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const slug = syndicateSlugFromRequest(req);
+ if (!slug) return error(res, 400, 'invalid_slug', 'That is not a syndicate address.');
+
+ const data = await loadSyndicate(slug);
+ if (!data) return error(res, 404, 'not_found', 'No syndicate flies that name.');
+
+ res.setHeader?.('cache-control', 'public, max-age=20, s-maxage=30');
+ return json(res, 200, { ...data, custody: 'none' });
+});
diff --git a/api/syndicates/index.js b/api/syndicates/index.js
new file mode 100644
index 000000000..219017a5a
--- /dev/null
+++ b/api/syndicates/index.js
@@ -0,0 +1,67 @@
+// Syndicates board and founding.
+// ---------------------------------------------------------------------------
+// GET /api/syndicates?network=mainnet&sort=profit|members|new&limit=24&offset=0
+// The public board: every active syndicate with its roster size, its group
+// performance from members' real copy intents, and what its leaders did
+// on-chain since it formed. While the board is empty the response also
+// carries `candidates`: the leaders a first syndicate could form around
+// today, each with its whole closed record and copyable verdict.
+//
+// POST /api/syndicates { name, motto?, color, network?, leader_agent_ids: [..1-3] }
+// Found a syndicate (auth + CSRF for cookie sessions). Every leader must
+// be a public trader that clears the copyable bar. Founding does not
+// subscribe anyone: members join with their own wallet and caps through
+// POST /api/syndicates/membership.
+//
+// Non-custodial and additive over the copy loop: see api/_lib/syndicates.js.
+
+import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { BOARD_SORTS, SYNDICATE_COLORS, MAX_SYNDICATE_LEADERS, createSyndicate, loadBoard, loadFoundingCandidates } from '../_lib/syndicates.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+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);
+
+ if (req.method === 'GET') {
+ const q = new URL(req.url, 'http://x').searchParams;
+ const network = NETWORKS.has(q.get('network')) ? q.get('network') : 'mainnet';
+ const sort = BOARD_SORTS.includes(q.get('sort')) ? q.get('sort') : 'profit';
+ const limit = Math.min(100, Math.max(1, parseInt(q.get('limit') || '24', 10) || 24));
+ const offset = Math.max(0, parseInt(q.get('offset') || '0', 10) || 0);
+
+ const board = await loadBoard({ network, sort, limit, offset });
+ const wantCandidates = board.total === 0 || q.get('include') === 'candidates';
+ const candidates = wantCandidates ? await loadFoundingCandidates(network, { limit: 12 }) : null;
+
+ res.setHeader?.('cache-control', 'public, max-age=30, s-maxage=60');
+ return json(res, 200, {
+ ...board,
+ colors: SYNDICATE_COLORS,
+ max_leaders: MAX_SYNDICATE_LEADERS,
+ custody: 'none',
+ ...(candidates ? { candidates } : {}),
+ });
+ }
+
+ // POST: found a syndicate.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'Sign in to start a syndicate.');
+ const userId = session?.id ?? bearer.userId;
+ if (session && !(await requireCsrf(req, res, userId))) return;
+
+ const body = await readJson(req).catch(() => null);
+ if (!body || typeof body !== 'object') return error(res, 400, 'bad_request', 'JSON body required');
+
+ const result = await createSyndicate({ userId, input: body });
+ if (!result.ok) return error(res, result.status, result.code, result.message, result.extra);
+ return json(res, 201, { syndicate: result.syndicate, official: result.official });
+});
diff --git a/api/syndicates/leaders.js b/api/syndicates/leaders.js
new file mode 100644
index 000000000..0616e29b2
--- /dev/null
+++ b/api/syndicates/leaders.js
@@ -0,0 +1,29 @@
+// GET /api/syndicates/leaders?network=mainnet&limit=12
+// ---------------------------------------------------------------------------
+// The leaders a syndicate can be founded around: public trader agents with
+// closed on-chain round-trips, each with its whole record (settled trades, win
+// rate, realized P&L on capital deployed, max drawdown) and the copyable verdict
+// a follow has to clear, with every unmet criterion named. Copyable leaders
+// come first. Public and cacheable; reads settled history only.
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { loadFoundingCandidates } from '../_lib/syndicates.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const q = new URL(req.url, 'http://x').searchParams;
+ const network = NETWORKS.has(q.get('network')) ? q.get('network') : 'mainnet';
+ const limit = Math.min(50, Math.max(1, parseInt(q.get('limit') || '12', 10) || 12));
+
+ const out = await loadFoundingCandidates(network, { limit });
+ res.setHeader?.('cache-control', 'public, max-age=60, s-maxage=120');
+ return json(res, 200, out);
+});
diff --git a/api/syndicates/membership.js b/api/syndicates/membership.js
new file mode 100644
index 000000000..b94ae8517
--- /dev/null
+++ b/api/syndicates/membership.js
@@ -0,0 +1,74 @@
+// Syndicate membership for the signed-in copier.
+// ---------------------------------------------------------------------------
+// GET /api/syndicates/membership?slug=<slug>
+// Your relationship to a syndicate: whether you are in it, the copy
+// subscriptions your membership rides on (and which ones the join
+// created), whether you run one of its leaders, and which other
+// syndicate you are in, if any.
+//
+// POST /api/syndicates/membership { slug, action: 'join', copier_wallet, sizing_rule, fixed_sol,
+// multiplier, pct_balance, per_trade_cap_sol, daily_budget_sol,
+// max_drawdown_pct?, ...the /api/copy/subscriptions tunables }
+// Join: one real copy subscription per syndicate leader through the same
+// guarded path as a single follow (self-copy refusal, the copyable bar,
+// your own caps). A subscription you already had to a leader is linked,
+// never overwritten. One syndicate per copier per network.
+//
+// POST /api/syndicates/membership { slug, action: 'leave' }
+// Leave: stops only the subscriptions the join created; any you had
+// before joining keep running exactly as they were.
+//
+// Auth required; cookie-session writes also need a CSRF token. Non-custodial:
+// only your wallet ADDRESS and rules are stored, and your wallet signs every trade.
+
+import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { joinSyndicate, leaveSyndicate, loadMembership, slugifyName } from '../_lib/syndicates.js';
+
+const cleanSlug = (v) => {
+ const s = String(v || '').trim().toLowerCase();
+ return slugifyName(s) === s ? s : null;
+};
+
+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 session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'Sign in to join a syndicate.');
+ const userId = session?.id ?? bearer.userId;
+
+ if (req.method === 'GET') {
+ const slug = cleanSlug(new URL(req.url, 'http://x').searchParams.get('slug'));
+ if (!slug) return error(res, 400, 'invalid_slug', 'slug is required');
+ const membership = await loadMembership(userId, slug);
+ if (!membership) return error(res, 404, 'not_found', 'No such syndicate.');
+ res.setHeader?.('cache-control', 'private, no-store');
+ return json(res, 200, { membership });
+ }
+
+ if (session && !(await requireCsrf(req, res, userId))) return;
+
+ const body = await readJson(req).catch(() => null);
+ if (!body || typeof body !== 'object') return error(res, 400, 'bad_request', 'JSON body required');
+ const slug = cleanSlug(body.slug);
+ if (!slug) return error(res, 400, 'invalid_slug', 'slug is required');
+
+ if (body.action === 'join') {
+ const result = await joinSyndicate({ userId, slug, body });
+ if (!result.ok) return error(res, result.status, result.code, result.message, result.extra);
+ return json(res, result.already ? 200 : 201, { joined: !result.already, already: result.already, membership: result.membership });
+ }
+ if (body.action === 'leave') {
+ const result = await leaveSyndicate({ userId, slug });
+ if (!result.ok) return error(res, result.status, result.code, result.message, result.extra);
+ return json(res, 200, { left: true, stopped_subscriptions: result.stopped_subscriptions, kept_subscriptions: result.kept_subscriptions });
+ }
+ return error(res, 400, 'invalid_action', "action must be 'join' or 'leave'");
+});
diff --git a/tests/syndicates.test.js b/tests/syndicates.test.js
new file mode 100644
index 000000000..4b2d0fb50
--- /dev/null
+++ b/tests/syndicates.test.js
@@ -0,0 +1,292 @@
+/**
+ * Syndicates (api/_lib/syndicates.js): named teams of copiers over the existing
+ * copy loop. The pure halves (naming, validation, the group curve, standings)
+ * and the two money-adjacent writes, join and leave, which must:
+ *
+ * - create subscriptions ONLY through the guarded subscribe path, with the
+ * member's own caps, and link (never overwrite) a subscription the member
+ * already had;
+ * - refuse a member who runs one of the leaders (self-copy) and a member who
+ * is already on another team;
+ * - roll back cleanly when a follow fails midway, so a join is all or nothing;
+ * - on leave, stop only what the join created.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const SYN = '99999999-9999-4999-8999-999999999999';
+const L1 = '11111111-1111-4111-8111-111111111111';
+const L2 = '22222222-2222-4222-8222-222222222222';
+const USER = 'user-copier';
+const WALLET = 'THREEsyntheticWa11et111111111111111111111';
+
+let db;
+const sqlCalls = [];
+
+function resetDb() {
+ db = {
+ syndicate: { id: SYN, slug: 'night-shift', name: 'Night Shift', status: 'active', network: 'mainnet', founder_user_id: 'founder-1' },
+ leaders: [
+ { leader_agent_id: L1, position: 0, user_id: 'owner-a', name: 'Alpha', is_public: true, deleted_at: null },
+ { leader_agent_id: L2, position: 1, user_id: 'owner-b', name: 'Beta', is_public: true, deleted_at: null },
+ ],
+ current: [],
+ existingSubs: [],
+ memberInsert: () => [{ id: 'member-1' }],
+ links: [],
+ stopped: [],
+ deletedMembers: [],
+ };
+}
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ const text = strings.join('?');
+ sqlCalls.push({ text, values });
+ if (text.includes('from copy_syndicates s') && text.includes('left join users u')) return Promise.resolve(db.syndicate ? [db.syndicate] : []);
+ if (text.includes('from copy_syndicate_leaders l') && text.includes('join agent_identities a')) return Promise.resolve(db.leaders);
+ if (text.includes('from copy_syndicate_members m') && text.includes('join copy_syndicates cs') && text.includes('limit 1')) return Promise.resolve(db.current);
+ if (text.includes('select id, leader_agent_id, status from copy_subscriptions')) return Promise.resolve(db.existingSubs);
+ if (text.includes('insert into copy_syndicate_members')) {
+ try { return Promise.resolve(db.memberInsert()); } catch (e) { return Promise.reject(e); }
+ }
+ if (text.includes('insert into copy_syndicate_member_subs')) {
+ db.links.push({ subscription_id: values[1], created_by_join: text.includes('true') });
+ return Promise.resolve([]);
+ }
+ if (text.includes("update copy_subscriptions set status = 'stopped'")) {
+ db.stopped.push(...values[0]);
+ return Promise.resolve(values[0].map((id) => ({ id })));
+ }
+ if (text.includes('delete from copy_syndicate_members')) { db.deletedMembers.push(values[0]); return Promise.resolve([]); }
+ if (text.includes('select id from copy_syndicate_members')) return Promise.resolve(db.activeMember || []);
+ if (text.includes('select subscription_id, created_by_join from copy_syndicate_member_subs')) return Promise.resolve(db.memberLinks || []);
+ if (text.includes("update copy_syndicate_members set status = 'left'")) return Promise.resolve([]);
+ return Promise.resolve([]);
+ },
+}));
+
+vi.mock('../api/_lib/streaks.js', () => ({
+ unlockBadge: vi.fn(async () => true),
+ BADGES: { SYNDICATE_FOUNDER: 'syndicate_founder', SYNDICATE_MEMBER: 'syndicate_member' },
+}));
+
+// Every leader clears the bar unless a test says otherwise.
+let profiles = {};
+vi.mock('../api/_lib/copy-eligibility.js', async (importOriginal) => {
+ const real = await importOriginal();
+ return { ...real, leaderCopyProfile: async (id) => profiles[id] ?? { settled: 30, span_hours: 200, deployed_sol: 2, max_drawdown_pct: 10 } };
+});
+
+const subscribeCopier = vi.fn();
+vi.mock('../api/_lib/copy-subscribe.js', async (importOriginal) => {
+ const real = await importOriginal();
+ return { ...real, subscribeCopier: (...args) => subscribeCopier(...args) };
+});
+
+const S = await import('../api/_lib/syndicates.js');
+
+const joinBody = (over = {}) => ({
+ copier_wallet: WALLET,
+ sizing_rule: 'fixed',
+ fixed_sol: 0.1,
+ per_trade_cap_sol: 0.5,
+ daily_budget_sol: 1,
+ ...over,
+});
+
+beforeEach(() => {
+ resetDb();
+ profiles = {};
+ sqlCalls.length = 0;
+ subscribeCopier.mockReset();
+ subscribeCopier.mockImplementation(async ({ body }) => ({ ok: true, subscription: { id: `sub-${body.leader_agent_id}` } }));
+});
+
+describe('slugifyName', () => {
+ it('turns a name into a clean url slug', () => {
+ expect(S.slugifyName('Night Shift Degens!')).toBe('night-shift-degens');
+ expect(S.slugifyName(' Café Crème ')).toBe('cafe-creme');
+ });
+ it('refuses names with too little to address', () => {
+ expect(S.slugifyName('!!')).toBeNull();
+ expect(S.slugifyName('a')).toBeNull();
+ });
+});
+
+describe('validateSyndicateInput', () => {
+ const base = { name: 'Night Shift', color: '#22d3ee', leader_agent_ids: [L1] };
+ it('accepts a valid founding and dedupes leaders', () => {
+ const v = S.validateSyndicateInput({ ...base, leader_agent_ids: [L1, L1, L2] });
+ expect(v.ok).toBe(true);
+ expect(v.value.leader_agent_ids).toEqual([L1, L2]);
+ expect(v.value.slug).toBe('night-shift');
+ expect(v.value.network).toBe('mainnet');
+ });
+ it('caps the leader set at three', () => {
+ const four = [L1, L2, '33333333-3333-4333-8333-333333333333', '44444444-4444-4444-8444-444444444444'];
+ expect(S.validateSyndicateInput({ ...base, leader_agent_ids: four }).ok).toBe(false);
+ });
+ it('requires a palette color and at least one leader', () => {
+ expect(S.validateSyndicateInput({ ...base, color: '#123456' }).ok).toBe(false);
+ expect(S.validateSyndicateInput({ ...base, leader_agent_ids: [] }).ok).toBe(false);
+ });
+ it('reserves slugs that name an API route', () => {
+ expect(S.validateSyndicateInput({ ...base, name: 'Leaders' }).error).toMatch(/reserved/);
+ expect(S.validateSyndicateInput({ ...base, name: 'Membership' }).ok).toBe(false);
+ });
+ it('bounds the motto', () => {
+ expect(S.validateSyndicateInput({ ...base, motto: 'x'.repeat(141) }).ok).toBe(false);
+ expect(S.validateSyndicateInput({ ...base, motto: ' ' }).value.motto).toBeNull();
+ });
+});
+
+describe('buildGroupCurve', () => {
+ it('accumulates realized copy profit in close order and tracks peak and trough', () => {
+ const c = S.buildGroupCurve([
+ { closed_at: '2026-09-01T00:00:00Z', profit_sol: 0.05 },
+ { closed_at: '2026-09-02T00:00:00Z', profit_sol: -0.12 },
+ { closed_at: '2026-09-03T00:00:00Z', profit_sol: 0.03 },
+ ]);
+ expect(c.points.map((p) => p.cum_sol)).toEqual([0.05, -0.07, -0.04]);
+ expect(c.peak_sol).toBe(0.05);
+ expect(c.trough_sol).toBe(-0.07);
+ expect(c.final_sol).toBe(-0.04);
+ });
+ it('thins a long curve but always keeps the final point', () => {
+ const rows = Array.from({ length: 500 }, (_, i) => ({ closed_at: new Date(Date.UTC(2026, 0, 1) + i * 60000).toISOString(), profit_sol: 0.001 }));
+ const c = S.buildGroupCurve(rows, 50);
+ expect(c.points).toHaveLength(50);
+ expect(c.points.at(-1).cum_sol).toBe(c.final_sol);
+ expect(c.final_sol).toBeCloseTo(0.5, 6);
+ });
+ it('is empty, not zero-filled, with no closed copies', () => {
+ expect(S.buildGroupCurve([]).points).toEqual([]);
+ });
+});
+
+describe('shapeBoardRow and computeStanding', () => {
+ const row = (id, rank, profit) => S.shapeBoardRow({
+ id, slug: id, name: id.toUpperCase(), color: '#7c5cff', network: 'mainnet', created_at: '2026-09-01T00:00:00Z',
+ members: '3', intents: '4', acted: '2', copied_sol: '0.4', profit_sol: String(profit), closed_copies: '2', winning_copies: '1',
+ leaders: [{ agent_id: L1, name: null, image: null }], official: false,
+ leader_closes: '5', leader_pnl_lamports: '250000000', leader_entry_lamports: '1000000000', rank: String(rank),
+ });
+
+ it('shapes numbers from the aggregate query', () => {
+ const r = row('a', 1, 0.2);
+ expect(r.members).toBe(3);
+ expect(r.performance.win_rate_pct).toBe(50);
+ expect(r.since_founding).toEqual({ leader_closes: 5, leader_pnl_sol: 0.25, leader_roi_pct: 25 });
+ expect(r.leaders[0].name).toBe('Unnamed trader');
+ expect(r.url).toBe('/syndicates/a');
+ });
+
+ it('names the syndicate one rank ahead as the rival', () => {
+ const s = S.computeStanding([row('a', 1, 0.5), row('b', 2, 0.2), row('c', 3, 0.1)], 'b', 3);
+ expect(s.rank).toBe(2);
+ expect(s.rival).toMatchObject({ slug: 'a', direction: 'ahead', gap_sol: 0.3 });
+ });
+
+ it('gives the board leader the chaser behind it', () => {
+ const s = S.computeStanding([row('a', 1, 0.5), row('b', 2, 0.2)], 'a', 2);
+ expect(s.rival).toMatchObject({ slug: 'b', direction: 'behind' });
+ });
+
+ it('has no rival when alone on the board', () => {
+ expect(S.computeStanding([row('a', 1, 0)], 'a', 1)).toEqual({ rank: 1, total: 1, rival: null });
+ });
+});
+
+describe('joinSyndicate', () => {
+ it('creates one guarded subscription per leader with the member\'s own caps', async () => {
+ const r = await S.joinSyndicate({ userId: USER, slug: 'night-shift', body: joinBody({ max_drawdown_pct: 30 }) });
+ expect(r.ok).toBe(true);
+ expect(subscribeCopier).toHaveBeenCalledTimes(2);
+ const firstBody = subscribeCopier.mock.calls[0][0].body;
+ expect(firstBody).toMatchObject({ leader_agent_id: L1, network: 'mainnet', copier_wallet: WALLET, per_trade_cap_sol: 0.5, max_drawdown_pct: 30 });
+ expect(db.links).toEqual([
+ { subscription_id: `sub-${L1}`, created_by_join: true },
+ { subscription_id: `sub-${L2}`, created_by_join: true },
+ ]);
+ });
+
+ it('links a subscription the member already had instead of overwriting its caps', async () => {
+ db.existingSubs = [{ id: 'mine-before', leader_agent_id: L1, status: 'active' }];
+ const r = await S.joinSyndicate({ userId: USER, slug: 'night-shift', body: joinBody() });
+ expect(r.ok).toBe(true);
+ expect(subscribeCopier).toHaveBeenCalledTimes(1);
+ expect(subscribeCopier.mock.calls[0][0].body.leader_agent_id).toBe(L2);
+ expect(db.links[0]).toEqual({ subscription_id: 'mine-before', created_by_join: false });
+ });
+
+ it('re-subscribes a leader the member had stopped, as a new follow', async () => {
+ db.existingSubs = [{ id: 'old-stopped', leader_agent_id: L1, status: 'stopped' }];
+ await S.joinSyndicate({ userId: USER, slug: 'night-shift', body: joinBody() });
+ expect(subscribeCopier).toHaveBeenCalledTimes(2);
+ });
+
+ it('refuses a member who runs one of the leaders', async () => {
+ const r = await S.joinSyndicate({ userId: 'owner-b', slug: 'night-shift', body: joinBody() });
+ expect(r).toMatchObject({ ok: false, status: 403, code: 'self_copy' });
+ expect(subscribeCopier).not.toHaveBeenCalled();
+ });
+
+ it('refuses a member already on another team and names it', async () => {
+ db.current = [{ id: 'm-x', syndicate_id: 'other', slug: 'curve-chasers', name: 'Curve Chasers' }];
+ const r = await S.joinSyndicate({ userId: USER, slug: 'night-shift', body: joinBody() });
+ expect(r).toMatchObject({ ok: false, status: 409, code: 'already_in_syndicate' });
+ expect(r.extra.current.slug).toBe('curve-chasers');
+ });
+
+ it('changes nothing when a leader has lost its copyable record', async () => {
+ profiles[L2] = { settled: 1, span_hours: 0, deployed_sol: 0.001, max_drawdown_pct: null };
+ const r = await S.joinSyndicate({ userId: USER, slug: 'night-shift', body: joinBody() });
+ expect(r).toMatchObject({ ok: false, status: 409, code: 'leader_not_copyable' });
+ expect(r.extra.leaders[0].agent_id).toBe(L2);
+ expect(sqlCalls.some((c) => c.text.includes('insert into copy_syndicate_members'))).toBe(false);
+ expect(subscribeCopier).not.toHaveBeenCalled();
+ });
+
+ it('rolls back the membership and any follow it made when a later follow fails', async () => {
+ subscribeCopier.mockImplementation(async ({ body }) => (
+ body.leader_agent_id === L2
+ ? { ok: false, status: 409, code: 'leader_not_copyable', message: 'no', extra: {} }
+ : { ok: true, subscription: { id: `sub-${body.leader_agent_id}` } }
+ ));
+ const r = await S.joinSyndicate({ userId: USER, slug: 'night-shift', body: joinBody() });
+ expect(r.ok).toBe(false);
+ expect(db.stopped).toEqual([`sub-${L1}`]);
+ expect(db.deletedMembers).toEqual(['member-1']);
+ });
+
+ it('maps a concurrent join racing the one-team index to a clean conflict', async () => {
+ db.memberInsert = () => { throw Object.assign(new Error('duplicate key value violates unique constraint'), { code: '23505' }); };
+ const r = await S.joinSyndicate({ userId: USER, slug: 'night-shift', body: joinBody() });
+ expect(r).toMatchObject({ ok: false, status: 409, code: 'already_in_syndicate' });
+ });
+
+ it('validates the wallet and caps before touching the database', async () => {
+ expect((await S.joinSyndicate({ userId: USER, slug: 'night-shift', body: joinBody({ copier_wallet: 'nope' }) })).code).toBe('invalid_wallet');
+ expect((await S.joinSyndicate({ userId: USER, slug: 'night-shift', body: joinBody({ per_trade_cap_sol: 0 }) })).code).toBe('invalid_config');
+ expect(sqlCalls).toHaveLength(0);
+ });
+});
+
+describe('leaveSyndicate', () => {
+ it('stops only the subscriptions the join created', async () => {
+ db.activeMember = [{ id: 'member-1' }];
+ db.memberLinks = [
+ { subscription_id: 'made-by-join', created_by_join: true },
+ { subscription_id: 'had-before', created_by_join: false },
+ ];
+ const r = await S.leaveSyndicate({ userId: USER, slug: 'night-shift' });
+ expect(r).toEqual({ ok: true, stopped_subscriptions: ['made-by-join'], kept_subscriptions: ['had-before'] });
+ expect(db.stopped).toEqual(['made-by-join']);
+ });
+
+ it('says so when the user is not a member', async () => {
+ db.activeMember = [];
+ expect(await S.leaveSyndicate({ userId: USER, slug: 'night-shift' })).toMatchObject({ ok: false, status: 404, code: 'not_member' });
+ });
+});