Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(syndicates): board, syndicate pages and daily quests page, linked from trader profiles, the copy dashboard and the arena
nirholas50094678e23d
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 8a74dd88d..676c8c10b 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -305,6 +305,8 @@ bottom.| Meta-Allocator (the ETF of degens) | [pages/meta-allocator.html](pages/meta-allocator.html) + [src/meta-allocator.js](src/meta-allocator.js) `→ /meta-allocator`, brain [api/_lib/meta-allocator.js](api/_lib/meta-allocator.js), endpoint [api/meta-allocator.js](api/meta-allocator.js) | Live (non-custodial planning) | Spreads a budget across the top verified pump.fun leader agents, ranked by risk-adjusted on-chain track record (win rate, realized ROI, peak-to-trough max drawdown from `agent_sniper_positions`) and diversified across derived correlation groups, then returns a rebalance rule. Free-first `llmComplete` shaping with a deterministic same-shape fallback so it never fails. Returns a plan (weights + suggested sizes), never a transaction; users act one leader at a time via [/vaults](pages/vaults.html). Doc: [docs/meta-allocator.md](docs/meta-allocator.md). || Alpha-drip (a leader prices their signal latency) | Ladder rules [api/\_lib/alpha-drip.js](api/_lib/alpha-drip.js), fanout half [api/\_lib/copy-drip-runtime.js](api/_lib/copy-drip-runtime.js), measured edge half-life [api/\_lib/alpha-drip-stats.js](api/_lib/alpha-drip-stats.js), endpoint [api/copy/alpha-drip.js](api/copy/alpha-drip.js) `-> /api/copy/alpha-drip`, leader editor [src/alpha-drip-panel.js](src/alpha-drip-panel.js) mounted on [/dashboard/copy](src/dashboard-next/pages/copy.js), copier seat on the trader page [src/copy-panel.js](src/copy-panel.js), schema [api/\_lib/migrations/20260903235500\_copy\_alpha\_drip.sql](api/_lib/migrations/20260903235500_copy_alpha_drip.sql) | Live (off unless a leader turns it on) | The $THREE sink on the copy rail: a leader sets how long each holder tier waits before a copy intent is revealed to them, so the thing being sold is latency rather than only a share of the profit. Two rules are structural and enforced server-side: a higher tier can never wait longer than a lower one, and **a drip delays the reveal, never the record** (the intent row is written in full at fanout time and the public track record is untouched, so there are no hidden trades). The copier is shown the seat their balance buys BEFORE they subscribe, not after; a locked intent renders as a countdown that unlocks in place, and `POST /api/copy/executions` refuses an unreleased one in the same statement that changes its status, so the guard cannot be raced. Tier size caps are applied after the copy engine has sized and gated the order, never before, so the copier's own caps still bind first. The edge half-life the fairness warning judges a ladder against is measured from the leader's own profitable closes, and is null rather than guessed below five of them. Release runs inside [api/cron/copy-fanout.js](api/cron/copy-fanout.js) rather than a second cron, so the release cadence is the fanout cadence. Doc: [docs/alpha-drip.md](docs/alpha-drip.md). Tests: [tests/alpha-drip.test.js](tests/alpha-drip.test.js) || Ghost-copy (paper-copy a leader) | [pages/ghost-copy.html](pages/ghost-copy.html) + [src/ghost-copy.js](src/ghost-copy.js) `→ /ghost-copy`, simulator [api/_lib/ghost-copy.js](api/_lib/ghost-copy.js), endpoint [api/pump/ghost-copy.js](api/pump/ghost-copy.js), tests [tests/ghost-copy.test.js](tests/ghost-copy.test.js) | Live (paper only, zero custody) | The bridge between the leaderboard and actually copying someone. Pick a verified trader agent, a budget and a window, and it replays that agent's real closed on-chain round-trips (`agent_sniper_positions`) against a wallet that does not exist, sizing every order through `planCopyOrder`, the SAME function the live [copy-fanout cron](api/cron/copy-fanout.js) uses, so the result is what the copy engine would actually have generated rather than a marketing figure. Deliberately unflattering: P&L per trade is derived from exact chain lamports (never the stored pct column), losing round-trips all count, the ghost wallet has a real cash constraint so capital locked in an open copy blocks the next one, every skip carries a machine reason plus a human sentence, and the leader's still-open positions are marked at THEIR last on-chain quote and reported as unrealized outside the realized headline. Needs no account, no wallet, no signature and no funded signer, so it ships ahead of any custody decision; state lives in the query string so a result is deep-linkable and shareable. Converts into [/vaults](pages/vaults.html) for real money. Doc: [docs/ghost-copy.md](docs/ghost-copy.md). |+| Syndicates (copy-trade as a team) | Board [pages/syndicates.html](pages/syndicates.html) + [src/syndicates.js](src/syndicates.js) `→ /syndicates`, detail [pages/syndicate.html](pages/syndicate.html) + [src/syndicate.js](src/syndicate.js) `→ /syndicates/:slug`, shared [src/syndicate-shared.js](src/syndicate-shared.js) + [src/syndicates.css](src/syndicates.css), trader-profile widget [src/trader-syndicates.js](src/trader-syndicates.js); model [api/_lib/syndicates.js](api/_lib/syndicates.js), guarded follow path [api/_lib/copy-subscribe.js](api/_lib/copy-subscribe.js), endpoints [api/syndicates/](api/syndicates/), migration [api/_lib/migrations/20260929120000_copy_syndicates.sql](api/_lib/migrations/20260929120000_copy_syndicates.sql), tests [tests/syndicates.test.js](tests/syndicates.test.js) | Live (non-custodial) | Roadmap 917 item 12.7. A named team (flag, motto, color) following one to three copyable leaders. Joining creates ordinary `copy_subscriptions` through the same guarded path as a single follow (self-copy refusal, copyable bar, the member's own caps); an existing subscription is linked, never overwritten; a join is all or nothing; leaving stops only what the join created. One team per copier per network. Group P&L, the curve and the rival standing are computed on read from members' real `copy_executions` inside their membership window, priced like the performance fee. The empty board lists today's copyable leaders with whole records. Linked from `/trader/:id`, `/dashboard/copy` and `/play/arena`. Doc: [docs/syndicates.md](docs/syndicates.md). |+| Daily trading quests | [pages/quests.html](pages/quests.html) + [src/quests.js](src/quests.js) `→ /quests`; model [api/_lib/trading-quests.js](api/_lib/trading-quests.js), disarmed $THREE payout [api/_lib/quest-rewards.js](api/_lib/quest-rewards.js), endpoints [api/quests/](api/quests/), trade proof recorded in [api/pump/[action].js](api/pump/[action].js) buy/sell-confirm, migration [api/_lib/migrations/20260929121000_trading_quests.sql](api/_lib/migrations/20260929121000_trading_quests.sql), tests [tests/trading-quests.test.js](tests/trading-quests.test.js), [tests/quest-rewards.test.js](tests/quest-rewards.test.js) | Live (XP + badges); $THREE rewards disarmed | Roadmap 917 item 12.11. Five daily quests scored from proof: verified trades from a linked wallet or owned-agent Co-Pilot, forks, first ghost-copies per leader, acted copy intents, an owned agent's profitable live close. Three a day is a daily clear. XP is an insert-only ledger; badges go to `user_badges`. The $THREE daily-clear reward is complete and tested but inert until `TRADING_QUEST_THREE_REWARDS=on` plus an amount and payout key are set (owner gate). Doc: [docs/trading-quests.md](docs/trading-quests.md). || Trader Wrapped (season recap) | [pages/wrapped.html](pages/wrapped.html) + [src/wrapped.js](src/wrapped.js) `→ /wrapped`, deck builder [api/_lib/wrapped.js](api/_lib/wrapped.js), endpoint [api/pump/wrapped.js](api/pump/wrapped.js), social card [api/wrapped-og.js](api/wrapped-og.js), share page [api/wrapped-share.js](api/wrapped-share.js) `→ /wrapped/<agent_id>/share`, tests [tests/wrapped.test.js](tests/wrapped.test.js) | Live (read-only, zero custody) | The artifact the trading stack was missing: one image and one link that say what a season was. Eight slides cut server-side from a trader agent's closed on-chain round-trips (scoreboard, best trade, worst trade, the coin that carried it, rhythm, rank against the field with the nearest rival, receipt), swipeable on touch and keyboard-driven on desktop, with the current slide in the URL hash so a share link lands on the slide the sharer was reading. Arithmetic is delegated wholesale to `computeTraderMetrics` in [api/_lib/trader-stats.js](api/_lib/trader-stats.js), the same truth layer the leaderboard and trader profile use, so a recap can never disagree with the profile it links to. Deliberately unflattering: the worst-trade slide is not optional, the scoreboard carries an explicit verdict and colors a red season red, per-coin ranking includes coins that lost money, self-launched coins stay excluded from every superlative, the rank always prints the size of the real field beside it, and under 3 settled round-trips the page says there is no season rather than drawing a chart out of noise. Needs no account, wallet, signature or funded signer. Converts through [Fork](src/fork-trade.js) on the best-trade slide and links onward to the verified profile, [Ghost-copy](pages/ghost-copy.html) and the rival's own wrapped. Doc: [docs/trader-wrapped.md](docs/trader-wrapped.md). || Rivalries (what changed on the trader board) | Engine [api/_lib/rivalries.js](api/_lib/rivalries.js), endpoint [api/sniper/rivalries.js](api/sniper/rivalries.js) `→ /api/sniper/rivalries`, grudge-match strip [src/play/rivalries.js](src/play/rivalries.js) mounted under the leaderboard on [pages/play/arena.html](pages/play/arena.html) `→ /play/arena`, tests [tests/rivalries.test.js](tests/rivalries.test.js) | Live (read-only) | The layer a leaderboard never has: not who is ahead, but who just took whose place. Every trader on the board is paired with the one directly above them and the pair is labelled `overtake`, `debut` or `chase`, with the P&L both sides booked inside the lookback as the reason. Derived from ONE position fetch through the shared `computeTraderMetrics`, run three times: the current window, the same window measured at the lookback cutoff, and the round-trips closed inside the lookback. The past board is re-derived from close timestamps rather than read from a snapshot table, so there is no new table and no cron, it works retroactively from the day it shipped, and it cannot drift out of agreement with `/api/sniper/leaderboard` or with either profile it links to. The copy is assembled from those numbers rather than generated, which keeps a public strip instant, free and checkable: it will not call a trader "behind" when the board ranks on score and that trader actually holds more SOL, and it will not say someone "booked 0.000 SOL" when they simply were not in the market. Ranking boards apply a three settled round-trip floor; the momentum board does not, because one settled trade is the movement it exists to show. Doc: [docs/rivalries.md](docs/rivalries.md). || Trader card embed (a leader on someone else page) | Hosted element [public/trader-card/element.js](public/trader-card/element.js) `→ /trader-card/element.js` (`<trader-card>`), compact read [api/sniper/trader-card.js](api/sniper/trader-card.js) `→ /api/sniper/trader-card`, pure projection [api/_lib/trader-card.js](api/_lib/trader-card.js), snippet builder [src/shared/trader-embed.js](src/shared/trader-embed.js), builder panel on [src/trader.js](src/trader.js) `→ /trader/:id`, tests [tests/trader-card.test.js](tests/trader-card.test.js) | Live (read-only, zero custody) | The funnel that runs on other people sites: one script tag renders a trader's live on-chain record in a stream overlay, a link in bio or a blog post, and every coin on it carries a [Fork](src/fork-trade.js) link plus a [Ghost-copy](pages/ghost-copy.html) call to action, all signed by the reader's own wallet. The leader copies the snippet from their own profile ("Embed this trader"), which renders a live preview of exactly what they are about to paste and bakes in their referral code, so every link the card emits is attributed to them. `/api/sniper/trader` is a quarter of a megabyte for a well-traded agent, which no widget on a stranger's page should pay for, so this endpoint is the few-kilobyte projection of it through the SAME `computeTraderMetrics`: an embedded card can never show a record three.ws would dispute, and an unmeasured number renders `n/a` rather than a zero. Real DOM in a shadow root (selectable, screen-reader readable, keyboard reachable, theme-aware), every link absolute because a relative href on a foreign domain goes to their site, polling that stops when the tab is hidden or the card scrolls off, and a failed refresh that keeps the last good card rather than blanking someone else's page. Doc: [docs/trader-card-embed.md](docs/trader-card-embed.md). |diff --git a/api/_lib/syndicates.js b/api/_lib/syndicates.jsindex b69980959..1526a7f3a 100644--- a/api/_lib/syndicates.js+++ b/api/_lib/syndicates.js@@ -209,7 +209,7 @@ function orderClause(sort) {* 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 } = {}) {+export async function loadBoard({ network = 'mainnet', sort = 'profit', limit = 24, offset = 0, onlyId = null, rankFrom = null, rankTo = null, leaderId = 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`@@ -280,16 +280,21 @@ export async function loadBoard({ network = 'mainnet', sort = 'profit', limit =left join lead on lead.syndicate_id = s.idleft join since on since.syndicate_id = s.id)- select * from ranked s+ select s.*, count(*) over () as matched from ranked swhere (${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)+ and (${leaderId}::uuid is null or exists (+ select 1 from copy_syndicate_leaders fl+ where fl.syndicate_id = s.id and fl.leader_agent_id = ${leaderId}::uuid))${orderClause(sort)}limit ${lim} offset ${off}`;- // total counts the whole board (the window runs before the filters above).+ // total counts the whole board (its window runs before the filters above);+ // matched counts the rows those filters let through, for pagination.const total = rows.length ? n(rows[0].total) : 0;- return { network, sort, limit: lim, offset: off, total, syndicates: rows.map(shapeBoardRow) };+ const matched = rows.length ? n(rows[0].matched) : 0;+ return { network, sort, limit: lim, offset: off, total, matched, syndicates: rows.map(shapeBoardRow) };}/**diff --git a/api/syndicates/index.js b/api/syndicates/index.jsindex 219017a5a..02e8b9a1a 100644--- a/api/syndicates/index.js+++ b/api/syndicates/index.js@@ -1,11 +1,13 @@// Syndicates board and founding.// ----------------------------------------------------------------------------// GET /api/syndicates?network=mainnet&sort=profit|members|new&limit=24&offset=0+// GET /api/syndicates?network=mainnet&sort=profit|members|new&limit=24&offset=0[&leader=<agent id>]// 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.+// `leader` narrows the board to syndicates following that agent (ranks stay+// board-wide), which is what /trader/:id shows.//// POST /api/syndicates { name, motto?, color, network?, leader_agent_ids: [..1-3] }// Found a syndicate (auth + CSRF for cookie sessions). Every leader must@@ -19,6 +21,7 @@ import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/import { limits, clientIp } from '../_lib/rate-limit.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { requireCsrf } from '../_lib/csrf.js';+import { isUuid } from '../_lib/validate.js';import { BOARD_SORTS, SYNDICATE_COLORS, MAX_SYNDICATE_LEADERS, createSyndicate, loadBoard, loadFoundingCandidates } from '../_lib/syndicates.js';const NETWORKS = new Set(['mainnet', 'devnet']);@@ -36,9 +39,11 @@ export default wrap(async (req, res) => {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 leader = (q.get('leader') || '').trim();+ if (leader && !isUuid(leader)) return error(res, 400, 'invalid_leader', 'leader must be an agent UUID');- const board = await loadBoard({ network, sort, limit, offset });- const wantCandidates = board.total === 0 || q.get('include') === 'candidates';+ const board = await loadBoard({ network, sort, limit, offset, leaderId: leader || null });+ const wantCandidates = !leader && (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');diff --git a/data/changelog.json b/data/changelog.jsonindex 0e59dd6f4..79a65e83c 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,20 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-09-29",+ "title": "Syndicates: copy the best traders as a team",+ "summary": "You can now copy-trade as a team. A syndicate is a named group with its own flag that follows one to three verified trader agents together. Every member still copies from their own wallet with their own per-trade cap, daily budget and drawdown limit, and nothing is ever pooled. The team gets a public page with its roster, a live group profit curve built from members' real copies, and a spot on the board with the rival one rank above named so you know who to catch. Leaving stops only the copies the syndicate started. Every trader profile now shows the syndicates following that trader.",+ "tags": ["feature"],+ "link": "/syndicates"+ },+ {+ "date": "2026-09-29",+ "title": "Daily trading quests with XP, levels and badges",+ "summary": "A new quests page gives you five small trading goals every day: make three trades, fork a verified trade, ghost-copy an agent you have never tried, act on a copy intent, and have your own agent close a winning trade. Each one is checked against real on-chain activity rather than a button press. Clear three in a day to keep your streak going, level up with XP, and earn the First Quest, Daily Clear and Quest Streak 7 badges on your profile.",+ "tags": ["feature"],+ "link": "/quests"+ },{"date": "2026-09-29","title": "Watch traders trade live in their own 3D trade rooms",diff --git a/data/pages.json b/data/pages.jsonindex 3a5d8ad40..9fc18371d 100644--- a/data/pages.json+++ b/data/pages.json@@ -1784,6 +1784,22 @@"changefreq": "weekly","added": "2026-08-02"},+ {+ "path": "/syndicates",+ "title": "Syndicates: copy-trade as a team",+ "description": "Named teams of copiers who follow the same verified pump.fun trader agents together. Each member copies from their own wallet under their own caps; the team shares a flag, a live equity curve from members' real copies, and a rival on the board. No pooled funds, no custody.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-09-29"+ },+ {+ "path": "/quests",+ "title": "Daily Trading Quests",+ "description": "Five trading quests that reset every UTC midnight: make three trades, fork a verified trade, ghost-copy a new agent, act on a copy intent, and let your agent close a winner. Scored from on-chain proof, rewarded with XP, levels and badges.",+ "priority": 0.6,+ "changefreq": "daily",+ "added": "2026-09-29"+ },{"path": "/wrapped","title": "Trader Wrapped: your season on pump.fun",@@ -5977,6 +5993,22 @@"changefreq": "monthly","added": "2026-08-02"},+ {+ "path": "/docs/syndicates",+ "title": "Docs · Syndicates",+ "description": "How copy-trading syndicates work: founding around copyable leaders, joining with your own wallet and caps, how the group curve and rival standing are computed from real copies, and the full API.",+ "priority": 0.6,+ "changefreq": "monthly",+ "added": "2026-09-29"+ },+ {+ "path": "/docs/trading-quests",+ "title": "Docs · Daily trading quests",+ "description": "The five daily trading quests, what proof each one is scored from, XP levels and quest badges, the disarmed $THREE reward switch, and the quests API.",+ "priority": 0.6,+ "changefreq": "monthly",+ "added": "2026-09-29"+ },{"path": "/docs/fork-trade","title": "Docs · Fork a trade",diff --git a/docs/start-here.md b/docs/start-here.mdindex db564942a..ee6c04ed5 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -148,6 +148,8 @@ Want the model in your hands rather than on a screen? [Materialize](./materializ- **Want to know why a trader bought before you copy it?** → [Trade receipts](./trade-receipts.md): press **why** on any closed trade on a track record to see the evidence the agent had at decision time (the entry trigger, the Oracle score and its base-rate reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer, paid x402 reads with their payment tx) and every leg on Solscan. Evidence logged after the exit is left out- **Want to watch a trader work before you copy them?** → [Live trade rooms](./trade-rooms.md): step into any public trader's 3D room and see their real buys and sells land as they fill, with the avatar reacting, the receipt for why on every trade, one-tap Fork, and ghost-copy or copy from the same page. A quiet room still shows their latest real trades and which rooms are live right now- **Not ready to risk money on a trader yet?** → [Ghost-copy](./ghost-copy.md): paper-copy any verified agent over their real closed on-chain trades and see the equity curve your budget would have had, sized by the same engine that runs live copy trades. No wallet, no signature, no account, and every trade your budget could not reach is listed with the reason+- **Rather copy with a crew?** → [Syndicates](./syndicates.md): a named team that follows the same verified traders together, each member from their own wallet under their own caps. A live group curve from members' real copies, a roster, and a rival on the board. Nothing pooled, nothing custodied, and leaving stops only what joining started+- **Want a reason to show up tomorrow?** → [Daily trading quests](./trading-quests.md): five small goals a day scored from on-chain proof (verified trades, forks, first ghost-copies, acted copy intents, your agent's live wins), with XP, levels, a clear streak and badges- **Have an audience of your own?** → [The trader card](./trader-card-embed.md): one script tag puts a trader's live on-chain record on your site, blog, link in bio or stream overlay, with a Fork button on every coin and a ghost-copy call to action, all signed by the reader's own wallet. It carries your referral code, holds no funds and asks for no key- **Running the platform?** → [Trading growth programs](./growth-programs.md): the big-win X poster, the first-rug softener and the early-leader $THREE bonus. All three ship disarmed; the page shows how to read what each would do today, every flag and cap, and the exact steps to arm one- **Running a chart page, a launchpad or a wallet?** → [Token in 3D, as an embed](./coin3d-embed.md): one iframe puts a live 3D view of any Solana market on your page, keyed by the mint or by the pair address your own URL already carries, with the coin's logo on a medallion, its holders as a galaxy sized by balance, a graduation ring and real swaps arriving on a tape. Free, keyless, no account, and it degrades to a data view where WebGL is unavailablediff --git a/docs/syndicates.md b/docs/syndicates.mdnew file mode 100644index 000000000..0169e485f--- /dev/null+++ b/docs/syndicates.md@@ -0,0 +1,160 @@+# Syndicates: copy-trade as a team++A syndicate is a named team of copiers who follow the same one to three+verified trader agents together. The team shares a flag (a name, a motto and a+color), a public page with its roster, a group equity curve built from its+members' real copies, and a standing on a board against every other syndicate,+with the rival one rank away named on the page.++Pages: [/syndicates](https://three.ws/syndicates) (the board and founding) ·+`/syndicates/<slug>` (one syndicate) · API: `/api/syndicates`++## What it is not++A syndicate never pools money. There is no shared wallet, no vault and no+custody. Every member copies from their **own** wallet with their **own**+per-trade cap, daily budget and drawdown limit, exactly as a solo copier on+[copy trading](copy-trading.md) does, and every copy is still an intent the+member signs. Joining creates ordinary copy subscriptions; leaving stops them.+That keeps a syndicate fully reversible: nothing about it can move a member's+funds that a solo follow could not.++## How it works++1. **Found one.** Pick a name (it becomes the address, `three.ws/syndicates/<slug>`),+ an optional motto, a flag color, and one to three leaders. Every leader must+ be a public trader agent that clears the copyable bar (at least 5 closed+ round-trips over at least 24 hours with at least 0.1 SOL deployed; see+ `LEADER_ELIGIBILITY` in `api/_lib/copy-eligibility.js`). Founding moves no+ money and subscribes nobody. A user may run at most 3 active syndicates per+ network. A leader's own owner may found one as their fan club; it is marked+ **Official** on the board.+2. **Join it.** A member enters the Solana wallet they copy from and their+ caps. The join runs the same guarded follow path as a single follow on a+ trader profile (`api/_lib/copy-subscribe.js`): the self-copy refusal, the+ copyable bar and the caps validation. It creates one copy subscription per+ leader. If the member already copies one of the leaders, that subscription is+ **linked, not overwritten**, so joining never silently changes caps someone+ set earlier. A join is all or nothing: if any follow fails, the membership and+ any subscription it created are rolled back.+3. **Ride together.** When a leader trades, each member gets a sized, safety+ checked intent on [/dashboard/copy](https://three.ws/dashboard/copy), exactly+ like a solo follow. Pause, resume or change caps per leader there.+4. **Leave.** Leaving stops only the subscriptions the join created. A+ subscription the member had before joining keeps running exactly as it was.+ Positions already held are never touched.++One syndicate per copier per network. A syndicate is a side you are on, and two+memberships would also count the same copy twice in two group curves.++## The numbers, and why they are honest++- **Group P&L** is the sum, over every member's acted copies whose leader+ position has closed, of `planned_sol x leader realized return`. That is the+ same profit basis the performance fee uses (`api/_lib/copy-earnings.js`), so a+ syndicate cannot look better than what its members would be billed on.+ Losers count. Only copies made while a member was in the syndicate count.+- **Leaders since formed** is what the followed leaders did on-chain since the+ syndicate was founded: live closes only (paper trades never generate copy+ intents, so they are excluded), realized P&L and ROI on capital deployed. It+ is measurable before any member has copied anything.+- **Leader records** on the page are whole closed records, losses included,+ with the copyable verdict and every unmet criterion named.+- **The roster** shows usernames only. A member's wallet and sizes are never+ public.++Nothing stores a performance number. Every figure is computed on read from+`copy_executions` and `agent_sniper_positions`.++## API++All responses are JSON. Errors use the platform shape+`{ "error": "<code>", "error_description": "<message>" }`.++### `GET /api/syndicates`++The board. Public and cacheable.++| Param | Default | Meaning |+|---|---|---|+| `network` | `mainnet` | `mainnet` or `devnet` |+| `sort` | `profit` | `profit`, `members` or `new` |+| `limit` | `24` | 1 to 100 |+| `offset` | `0` | for paging |+| `leader` | none | an agent id: only syndicates following that agent (ranks stay board-wide) |+| `include` | none | `candidates` to always include the founding candidates |++Returns `{ total, matched, syndicates: [...], colors, max_leaders, candidates? }`.+Each syndicate carries `rank` (its profit rank on the whole board), `members`,+`leaders`, `performance` and `since_founding`. While the board is empty,+`candidates` lists the leaders a first syndicate could form around.++```bash+curl -s 'https://three.ws/api/syndicates?sort=profit&limit=5'+```++### `GET /api/syndicates/leaders`++Leaders a syndicate can be founded around, each with its whole record and+copyable verdict, copyable first. Public. `network`, `limit` (1 to 50).++### `GET /api/syndicates/:slug`++One syndicate: `syndicate`, `leaders`, `members` (`count`, `copying`,+`alumni`, `list`), `performance` (including `curve.points`), `since_founding`,+`standing` (`rank`, `total`, `rival`), and `joinable`. Public and cacheable.++### `POST /api/syndicates`++Found a syndicate. Auth required (session cookie with a CSRF token, or a+bearer key).++```json+{ "name": "Night Shift Degens", "motto": "We ride the 3am tape together.",+ "color": "#22d3ee", "leader_agent_ids": ["<agent uuid>"] }+```++`201 { syndicate, official }`. Refusals: `invalid_syndicate` (400),+`leader_not_found` (404), `leader_not_copyable` (409, with `leaders[].unmet`),+`name_taken` (409), `founder_limit` (409).++### `GET /api/syndicates/membership?slug=<slug>`++The signed-in viewer's relationship to a syndicate: `member` (with the+subscriptions the membership rides on and which ones the join created),+`owns_leader`, `is_founder`, and `other_syndicate` when they ride elsewhere.++### `POST /api/syndicates/membership`++Join:++```json+{ "slug": "night-shift-degens", "action": "join",+ "copier_wallet": "<your Solana address>", "sizing_rule": "fixed", "fixed_sol": 0.1,+ "per_trade_cap_sol": 0.5, "daily_budget_sol": 1, "max_drawdown_pct": 35 }+```++Every tunable `/api/copy/subscriptions` accepts is accepted here and applied to+each leader. `201 { joined: true, membership }`, or `200 { already: true }` when+already a member. Refusals: `invalid_wallet`, `invalid_config` (400),+`self_copy` (403), `already_in_syndicate` (409, with `current`),+`leader_not_copyable` (409).++Leave: `{ "slug": "night-shift-degens", "action": "leave" }` returns+`{ left: true, stopped_subscriptions, kept_subscriptions }`.++## Data++Migration `api/_lib/migrations/20260929120000_copy_syndicates.sql`:+`copy_syndicates`, `copy_syndicate_leaders`, `copy_syndicate_members` (a+partial unique index enforces one active team per copier per network) and+`copy_syndicate_member_subs` (which subscriptions a membership rides on, and+whether the join created them). Code: `api/_lib/syndicates.js`,+`api/syndicates/*`, `src/syndicates.js`, `src/syndicate.js`.++## Related++- [Copy trading](copy-trading.md): the engine underneath, the fee and the caps+- [Ghost-copy](ghost-copy.md): paper-copy a leader before joining anything+- [Trading quests](trading-quests.md): daily goals and XP around the same loop+- Every trader profile (`/trader/<id>`) lists the syndicates following that traderdiff --git a/docs/trading-quests.md b/docs/trading-quests.mdnew file mode 100644index 000000000..6198a7a14--- /dev/null+++ b/docs/trading-quests.md@@ -0,0 +1,129 @@+# Daily trading quests++Five small trading goals a day that reset at 00:00 UTC. Every quest is scored+from proof, never from a click, and rewards are XP, levels and badges.++Page: [/quests](https://three.ws/quests) · API: `/api/quests`++## The quests++| Quest | Target | XP | Counted from |+|---|---|---|---|+| Make 3 trades | 3 | 30 | Trades whose signature was verified on-chain by buy-confirm / sell-confirm and signed by a Solana wallet **linked to your account**, plus confirmed Co-Pilot trades on an agent you own |+| Fork a verified trade | 1 | 25 | One of those verified trades opened from a Fork button (`src/fork-trade.js`) |+| Ghost-copy a new agent | 1 | 15 | The first time you [ghost-copy](ghost-copy.md) a leader you never replayed before |+| Act on a copy intent | 1 | 25 | A copy intent on [/dashboard/copy](https://three.ws/dashboard/copy) you marked copied today |+| Your agent closes a winner | 1 | 20 | An agent you own closes a **live** trade in profit (paper trades do not count) |++Clear any **3** in one UTC day for a **daily clear** (+50 XP). Consecutive days+with a clear make your clear streak.++### Why "linked wallet"++Trade signatures are public. Without the link, anyone could report someone+else's verified trade as their own. A trade counts only when its signing wallet+is one of your account's Solana wallets (`user_wallets`, or the wallet you+signed in with), and each signature can be claimed once.++## Levels and badges++Reaching level `L` takes `50 x L x (L - 1)` XP in total: 100 XP for level 2,+300 for level 3, 600 for level 4. XP is an insert-only ledger, so it never goes+down when an underlying row later changes.++| Badge | Earned by |+|---|---|+| First Quest | completing any quest |+| Daily Clear | your first daily clear |+| Quest Streak 7 | seven daily clears in a row |++Badges live in the shared `user_badges` table with the rest of the platform's+badges, so they show on your profile.++## When progress is awarded++Progress is computed and awarded when you (or the page) read your quests, for+today **and yesterday**. The proof tables are durable, so a quest finished at+23:59 UTC still counts when you look the next morning.++## $THREE rewards (disarmed)++A daily clear can also pay $THREE to your linked Solana wallet. Paying it moves+$THREE out of a platform wallet, which is an owner decision, so the payout+ships **disarmed**. With the switch off, `POST /api/quests/claim` answers+`409 rewards_disarmed` before it reads or writes a row, loads a key or opens an+RPC connection, and the page does not show a claim button at all.++The owner arms it with all three of these on the Cloud Run service+(`gcloud run services update three-ws-api --update-env-vars ...`, never+`--set-env-vars`):++| Variable | Meaning |+|---|---|+| `TRADING_QUEST_THREE_REWARDS` | `on` to arm. Default off. |+| `TRADING_QUEST_THREE_REWARD_AMOUNT` | whole $THREE paid per daily clear, more than 0 |+| `TRADING_QUEST_THREE_REWARD_SECRET_KEY_B64` | base64 64-byte secret of the funded payout wallet |+| `TRADING_QUEST_THREE_REWARD_DAILY_BUDGET` | optional: whole $THREE paid across all users per UTC day (default 20 x the amount) |++A half-configured deploy stays disarmed. When armed: one reward per user per+UTC day, only for a day the user cleared, only for today or yesterday, only to a+linked wallet, bounded by the daily budget. The ledger row+(`trading_quest_three_rewards`) is claimed before the Token-2022 transfer and+marked `sent` or `failed` after, so a double click never pays twice and a+failed transfer can be retried. Code: `api/_lib/quest-rewards.js`, tests:+`tests/quest-rewards.test.js`.++## API++### `GET /api/quests`++Signed out: `{ signed_in: false, day, resets_at, quests, daily_clear, three_rewards }`+with no progress. Signed in:++```json+{+ "signed_in": true,+ "day": "2026-09-29",+ "resets_at": "2026-09-30T00:00:00.000Z",+ "quests": [{ "code": "trades_3", "title": "Make 3 trades", "target": 3, "progress": 1, "done": false, "xp": 30, "cta": { "href": "/trades" } }],+ "daily_clear": { "need": 3, "xp": 50, "done_count": 1, "cleared": false },+ "xp": { "total": 40, "level": 1, "into_level": 40, "level_span": 100, "next_level_at": 100 },+ "clear_streak": { "current": 0, "longest": 0 },+ "badges": [],+ "newly_completed": [{ "day": "2026-09-29", "code": "ghost_new" }],+ "three_rewards": { "armed": false }+}+```++```bash+curl -s https://three.ws/api/quests+```++### `POST /api/quests/event`++`{ "kind": "ghost_copy", "leader_agent_id": "<uuid>", "network": "mainnet" }`,+signed in. The ghost-copy page sends this after a finished replay, because the+replay endpoint is public and cached and never learns who ran it. The leader+must be a public agent with closed trades. It also completes step 2 of the+first-copy path. Returns `{ recorded: true, new_agent }`.++### `POST /api/quests/claim`++`{ "day": "2026-09-29" }`, signed in. Disarmed by default (`409+rewards_disarmed`). When armed: `200 { status: "sent", tx_signature,+amount_three }`, or `not_cleared`, `no_wallet`, `in_flight`,+`budget_exhausted` (409), `invalid_day` (400), `payout_failed` (502).++## Data++Migration `api/_lib/migrations/20260929121000_trading_quests.sql`:+`trading_quest_events` (verified trades with their fork origin, and first+ghost-copies per leader), `trading_quest_completions` (the XP ledger) and+`trading_quest_three_rewards` (empty unless armed). Code:+`api/_lib/trading-quests.js`, `api/quests/*`, `src/quests.js`.++## Related++- [Syndicates](syndicates.md): copy-trade as a team+- [Fork a trade](fork-trade.md) and [Ghost-copy](ghost-copy.md): two of the quests+- [Copy trading](copy-trading.md): where copy intents come fromdiff --git a/pages/play/arena.html b/pages/play/arena.htmlindex a4137b2d3..ea4b68402 100644--- a/pages/play/arena.html+++ b/pages/play/arena.html@@ -420,6 +420,14 @@<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="7" cy="6.5" r="2.6"/><path d="M2.5 16a4.5 4.5 0 0 1 9 0"/><circle cx="14.5" cy="7.5" r="2.1"/><path d="M13 13.2a4 4 0 0 1 4.5 2.8"/></svg><span class="nav-lbl" data-i18n="play_arena.all_agents">All agents</span></a>+ <a class="btn arena-nav" href="/syndicates" title="Copy the winners as a team">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4.5 17.5V3"/><path d="M4.5 3.5h9.5l-2 3.25 2 3.25H4.5"/></svg>+ <span class="nav-lbl">Syndicates</span>+ </a>+ <a class="btn arena-nav" href="/quests" title="Today's trading quests">+ <svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="10" cy="10" r="7"/><circle cx="10" cy="10" r="3.5"/><circle cx="10" cy="10" r=".6" fill="currentColor"/></svg>+ <span class="nav-lbl">Quests</span>+ </a><div class="spacer"></div><button class="btn primary" id="pickBtn"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="10" cy="6.5" r="3.2"/><path d="M4 17a6 6 0 0 1 12 0"/></svg>diff --git a/pages/quests.html b/pages/quests.htmlnew file mode 100644index 000000000..c45e1cb0d--- /dev/null+++ b/pages/quests.html@@ -0,0 +1,68 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <script src="/referral-capture.js"></script>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Daily Trading Quests · three.ws</title>+ <meta name="description" content="Five small trading quests that reset every UTC midnight: make three trades, fork a verified trade, ghost-copy a new agent, act on a copy intent, and let your agent close a winner. Every quest is scored from on-chain proof. Earn XP, levels, and badges." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/quests" />+ <meta property="og:title" content="Daily Trading Quests · three.ws" />+ <meta property="og:description" content="Five trading quests a day, scored from on-chain proof. Clear three to keep your streak alive." />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Daily+Trading+Quests&d=Five+trading+quests+a+day%2C+scored+from+on-chain+proof.+Clear+three+to+keep+your+streak+alive.&p=%2Fquests" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content="Daily Trading Quests on three.ws" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Daily Trading Quests · three.ws" />+ <meta name="twitter:description" content="Five trading quests a day, scored from on-chain proof. Clear three to keep your streak alive." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Daily+Trading+Quests&d=Five+trading+quests+a+day%2C+scored+from+on-chain+proof.+Clear+three+to+keep+your+streak+alive.&p=%2Fquests" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/quests" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/syndicates.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="sy" aria-labelledby="qx-title">+ <p class="sy-kicker">Daily trading quests · reset <span id="qxReset">at 00:00 UTC</span></p>+ <h1 id="qx-title" class="sy-title">Today's quests</h1>+ <p class="sy-sub">+ Five small goals a day, each scored from proof rather than a click: trades verified on-chain,+ forks you signed, leaders you ghost-copied for the first time, copy intents you acted on, and+ your own agent's live wins. Clear three in a UTC day to keep your streak alive.+ </p>+ <div id="qxRoot" aria-live="polite" aria-busy="true">+ <div style="display:grid;gap:12px">+ <div class="sy-skel" style="height:110px"></div>+ <div class="sy-skel" style="height:74px"></div>+ <div class="sy-skel" style="height:74px"></div>+ <div class="sy-skel" style="height:74px"></div>+ </div>+ </div>+ </main>++ <div id="syToast" class="sy-toast" role="status" aria-live="polite"></div>++ <script type="module" src="/src/quests.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/pages/syndicate.html b/pages/syndicate.htmlnew file mode 100644index 000000000..ee3417e1d--- /dev/null+++ b/pages/syndicate.html@@ -0,0 +1,63 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <script src="/referral-capture.js"></script>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Syndicate · three.ws</title>+ <meta name="description" content="A three.ws syndicate: a named team of copiers following the same verified pump.fun trader agents, each from their own wallet under their own caps. Live group equity curve, roster, and standing on the board." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Syndicate · three.ws" />+ <meta property="og:description" content="A named team of copiers following verified trader agents together. Your wallet, your caps, a shared flag and a rival on the board." />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Syndicates%3A+copy-trade+as+a+team&d=Named+teams+of+copiers+who+follow+the+same+verified+trader+agents+together%2C+each+from+their+own+wallet+under+their+own+caps.&p=%2Fsyndicates" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="theme-color" content="#0a0a0a" />+ <meta name="robots" content="index, follow, max-image-preview:large" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/syndicates.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="sy" id="syRoot" aria-busy="true">+ <p style="margin:0 0 14px"><a class="sy-faint" href="/syndicates" style="text-decoration:none;font-weight:700;font-size:13.5px">← All syndicates</a></p>+ <div id="syContent">+ <div style="display:grid;gap:14px">+ <div class="sy-skel" style="height:72px"></div>+ <div class="sy-skel" style="height:260px"></div>+ <div class="sy-skel" style="height:140px"></div>+ </div>+ </div>+ </main>++ <dialog class="sy-dialog" id="syLeave" aria-labelledby="syLeaveTitle">+ <div class="sy-dialog-head">+ <h2 id="syLeaveTitle">Leave this syndicate?</h2>+ <button type="button" class="sy-x" data-close aria-label="Close">×</button>+ </div>+ <div class="sy-dialog-body" id="syLeaveBody"></div>+ </dialog>++ <div id="syToast" class="sy-toast" role="status" aria-live="polite"></div>++ <script type="module" src="/src/syndicate.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/pages/syndicates.html b/pages/syndicates.htmlnew file mode 100644index 000000000..05b8d5bc3--- /dev/null+++ b/pages/syndicates.html@@ -0,0 +1,95 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <script src="/referral-capture.js"></script>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Syndicates: copy-trade as a team · three.ws</title>+ <meta name="description" content="Named teams of copiers who follow the same verified pump.fun trader agents together. Each member copies from their own wallet with their own caps; the group shares a flag, a live equity curve, and a rival on the board. No pooled funds, no custody." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/syndicates" />+ <meta property="og:title" content="Syndicates: copy-trade as a team · three.ws" />+ <meta property="og:description" content="Pick a flag, rally around a verified trader agent, and climb the board against every other syndicate. Every member copies from their own wallet under their own caps." />+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Syndicates%3A+copy-trade+as+a+team&d=Named+teams+of+copiers+who+follow+the+same+verified+trader+agents+together%2C+each+from+their+own+wallet+under+their+own+caps.&p=%2Fsyndicates" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta property="og:image:alt" content="Syndicates: copy-trade as a team on three.ws" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Syndicates: copy-trade as a team · three.ws" />+ <meta name="twitter:description" content="Rally around a verified trader agent with a named team. Your wallet, your caps, a shared flag and a rival on the board." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Syndicates%3A+copy-trade+as+a+team&d=Named+teams+of+copiers+who+follow+the+same+verified+trader+agents+together%2C+each+from+their+own+wallet+under+their+own+caps.&p=%2Fsyndicates" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/syndicates" />+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/manifest.webmanifest" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/syndicates.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"Syndicates","applicationCategory":"FinanceApplication","operatingSystem":"Web","description":"Named teams of copiers who follow the same verified pump.fun trader agents together, each from their own wallet under their own caps. Non-custodial.","url":"https://three.ws/syndicates","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="sy" aria-labelledby="sy-title">+ <p class="sy-kicker">Copy-trade as a team · your wallet, your caps</p>+ <h1 id="sy-title" class="sy-title">Syndicates</h1>+ <p class="sy-sub">+ A syndicate is a named team that follows the same verified trader agents together. Every member+ copies from their own wallet with their own per-trade cap, daily budget, and drawdown limit, and+ the team shares a flag, a live equity curve built from members' real copies, and a rival on the board.+ Nothing is pooled and nobody holds your funds.+ </p>+ <div class="sy-actions">+ <button type="button" class="sy-btn primary" id="syStart">Start a syndicate</button>+ <a class="sy-btn" href="/quests">Today's trading quests</a>+ <a class="sy-btn" href="/docs/syndicates">How syndicates work</a>+ </div>++ <section class="sy-section" aria-labelledby="syBoardTitle">+ <div class="sy-toolbar">+ <h2 id="syBoardTitle" class="sy-h2">The board <small id="syCount"></small></h2>+ <div class="sy-seg" role="group" aria-label="Sort the board" id="sySort">+ <button type="button" data-sort="profit" aria-pressed="true">Top profit</button>+ <button type="button" data-sort="members" aria-pressed="false">Most members</button>+ <button type="button" data-sort="new" aria-pressed="false">Newest</button>+ </div>+ </div>+ <div id="syBoard" aria-live="polite" aria-busy="true"></div>+ <div class="sy-actions" style="justify-content:center;margin-top:14px">+ <button type="button" class="sy-btn" id="syMore" hidden>Show more</button>+ </div>+ </section>++ <section class="sy-section" id="syCandidatesWrap" aria-labelledby="syCandTitle" hidden>+ <h2 id="syCandTitle" class="sy-h2">Leaders you can rally around today <small>real closed on-chain records, judged by the copyable bar</small></h2>+ <div id="syCandidates" class="sy-leaders"></div>+ </section>+ </main>++ <dialog class="sy-dialog" id="syCreate" aria-labelledby="syCreateTitle">+ <div class="sy-dialog-head">+ <h2 id="syCreateTitle">Start a syndicate</h2>+ <button type="button" class="sy-x" id="syCreateClose" aria-label="Close">×</button>+ </div>+ <div class="sy-dialog-body" id="syCreateBody"></div>+ </dialog>++ <div id="syToast" class="sy-toast" role="status" aria-live="polite"></div>++ <script type="module" src="/src/syndicates.js"></script>+ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/src/dashboard-next/pages/copy.js b/src/dashboard-next/pages/copy.jsindex d59ea16f0..ea99863bd 100644--- a/src/dashboard-next/pages/copy.js+++ b/src/dashboard-next/pages/copy.js@@ -438,6 +438,7 @@ async function loadAndRender(host) {<section class="cp-sec"><div class="cp-sec-h"><h2>Your copies</h2><span class="cp-count">${subs.filter((s) => s.status !== 'stopped').length}</span></div>+ <p class="cp-note">Copy as a team in a <a href="/syndicates" style="color:var(--nxt-accent)">syndicate</a>, and clear today's <a href="/quests" style="color:var(--nxt-accent)">trading quests</a> for XP.</p><div id="cp-subs">${subs.filter((s) => s.status !== 'stopped').length ? subs.filter((s) => s.status !== 'stopped').map(subRow).join('') : `<div class="cp-empty">You're not copying anyone yet. <a href="/leaderboard" style="color:var(--nxt-accent)">Find a trader →</a></div>`}</div></section>diff --git a/src/quests.js b/src/quests.jsnew file mode 100644index 000000000..7484cc53b--- /dev/null+++ b/src/quests.js@@ -0,0 +1,230 @@+// /quests: today's trading quests, XP level, daily-clear streak, quest badges.+//+// Reads GET /api/quests. Signed out, it shows the real quest catalog with a+// sign-in CTA. Signed in, progress comes from proof tables and anything newly+// earned is awarded by that same read. The $THREE claim appears only when the+// server says rewards are armed (TRADING_QUEST_THREE_REWARDS); by default it+// does not render at all.++import { apiFetch } from './api.js';+import { esc, toast, errorMessage } from './syndicate-shared.js';++const rootEl = document.getElementById('qxRoot');+const resetEl = document.getElementById('qxReset');++const QUEST_BADGES = [+ { code: 'quest_first', label: 'First Quest', icon: '🎯', how: 'Complete any quest.' },+ { code: 'quest_clear', label: 'Daily Clear', icon: '⚡', how: 'Clear three quests in one UTC day.' },+ { code: 'quest_streak_7', label: 'Quest Streak 7', icon: '🏅', how: 'Clear the day seven days running.' },+];++let data = null;+let clockTimer = null;++async function load() {+ rootEl.setAttribute('aria-busy', 'true');+ try {+ const r = await apiFetch('/api/quests', { allowAnonymous: true, headers: { accept: 'application/json' } });+ if (!r.ok) {+ const { message } = await errorMessage(r, `Quests answered ${r.status}.`);+ return renderError(message);+ }+ data = await r.json();+ render();+ for (const n of data.newly_completed || []) {+ const q = (data.quests || []).find((x) => x.code === n.code);+ toast(n.code === 'daily_clear' ? `Day cleared. +${data.daily_clear.xp} XP` : `Quest complete: ${q?.title || n.code}. +${q?.xp ?? 0} XP`);+ }+ } catch {+ renderError('Check your connection.');+ } finally {+ rootEl.setAttribute('aria-busy', 'false');+ }+}++function renderError(message) {+ rootEl.innerHTML = `+ <div class="sy-state" role="alert">+ <h2>Quests did not load</h2>+ <p>${esc(message)} Anything you did today still counts: quests are scored from on-chain proof, so progress shows up the next time this loads.</p>+ <button type="button" class="sy-btn primary" id="qxRetry">Try again</button>+ </div>`;+ document.getElementById('qxRetry').addEventListener('click', load);+}++function ring(progress, target) {+ const r = 18;+ const c = 2 * Math.PI * r;+ const p = target > 0 ? Math.min(1, (progress ?? 0) / target) : 0;+ return `+ <svg class="qx-ring" viewBox="0 0 44 44" aria-hidden="true">+ <circle class="track" cx="22" cy="22" r="${r}" />+ <circle class="fill" cx="22" cy="22" r="${r}" stroke-dasharray="${c.toFixed(2)}" stroke-dashoffset="${(c * (1 - p)).toFixed(2)}" transform="rotate(-90 22 22)" />+ <text x="22" y="26" text-anchor="middle">${progress == null ? target : `${progress}/${target}`}</text>+ </svg>`;+}++function questItem(q, signedIn) {+ const status = q.done ? 'Complete' : signedIn ? `${q.progress} of ${q.target}` : `Goal: ${q.target}`;+ return `+ <li class="qx-quest${q.done ? ' done' : ''}">+ ${ring(q.progress, q.target)}+ <div style="min-width:0">+ <div class="qx-q-title">${esc(q.title)} <span class="qx-xp">+${esc(q.xp)} XP</span>${q.done ? ' <span class="sy-badge good">Done</span>' : ''}</div>+ <div class="qx-q-detail">${esc(q.detail)}</div>+ <span class="sr-only">${esc(status)}</span>+ </div>+ ${q.done ? '' : `<a class="sy-btn sm" href="${esc(q.cta.href)}">${esc(q.cta.label)}</a>`}+ </li>`;+}++function render() {+ const signedIn = !!data.signed_in;+ const quests = data.quests || [];+ const clear = data.daily_clear;+ tickClock();++ if (!signedIn) {+ const next = encodeURIComponent('/quests');+ rootEl.innerHTML = `+ <div class="sy-panel" style="margin-bottom:16px;display:flex;flex-wrap:wrap;gap:14px;align-items:center;justify-content:space-between">+ <div style="min-width:0;max-width:60ch">+ <b style="font-size:16px">Sign in to start earning XP</b>+ <p class="sy-muted" style="margin:4px 0 0;line-height:1.5">Progress is scored from what you actually do: trades your linked wallet signs, forks, first ghost-copies, copy intents, and your agent's live wins.</p>+ </div>+ <div class="sy-actions"><a class="sy-btn primary" href="/login?next=${next}">Sign in</a><a class="sy-btn" href="/register?next=${next}">Create an account</a></div>+ </div>+ <ul class="qx-list" aria-label="Today's quests">${quests.map((q) => questItem(q, false)).join('')}</ul>+ <p class="sy-fine" style="margin-top:14px">Clear any ${esc(clear.need)} quests in one UTC day for a +${esc(clear.xp)} XP bonus.</p>+ ${linksSection()}`;+ return;+ }++ const xp = data.xp;+ const pct = xp.level_span > 0 ? Math.round((xp.into_level / xp.level_span) * 100) : 0;+ const streak = data.clear_streak;+ const earned = new Set((data.badges || []).map((b) => b.code));++ rootEl.innerHTML = `+ <div class="qx-top">+ <section class="sy-panel" aria-label="Your level">+ <div class="qx-level">+ <span class="qx-level-num" aria-hidden="true">${esc(xp.level)}</span>+ <div style="flex:1;min-width:0">+ <div style="display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap"><b style="font-size:17px">Level ${esc(xp.level)}</b><span class="sy-faint" style="font-size:13px">${esc(xp.total)} XP total</span></div>+ <div class="qx-bar" role="progressbar" aria-label="Progress to level ${esc(xp.level + 1)}" aria-valuemin="0" aria-valuemax="${esc(xp.level_span)}" aria-valuenow="${esc(xp.into_level)}"><i style="--p:${pct}%"></i></div>+ <div class="sy-faint" style="font-size:12.5px;margin-top:6px">${esc(xp.level_span - xp.into_level)} XP to level ${esc(xp.level + 1)}</div>+ </div>+ </div>+ </section>+ <section class="sy-panel" aria-label="Daily clear streak">+ <div class="qx-clear">+ <div>+ <b style="font-size:17px">${streak.current ? `${esc(streak.current)}-day clear streak` : 'No clear streak yet'}</b>+ <div class="sy-faint" style="font-size:12.5px;margin-top:4px">${streak.longest ? `Longest: ${esc(streak.longest)} ${streak.longest === 1 ? 'day' : 'days'}` : 'Clear three quests today to start one.'}</div>+ </div>+ <div style="text-align:right">+ <div class="qx-pips" aria-hidden="true">${Array.from({ length: clear.need }, (_, i) => `<i class="${i < clear.done_count ? 'on' : ''}"></i>`).join('')}</div>+ <div class="sy-faint" style="font-size:12.5px;margin-top:6px">${clear.cleared ? `<span class="pos">Day cleared · +${esc(clear.xp)} XP</span>` : `${esc(Math.min(clear.done_count, clear.need))} of ${esc(clear.need)} to clear today`}</div>+ </div>+ </div>+ </section>+ </div>++ <ul class="qx-list" aria-label="Today's quests">${quests.map((q) => questItem(q, true)).join('')}</ul>+ ${rewardsSection()}++ <section class="sy-section" aria-labelledby="qxBadgesTitle">+ <h2 id="qxBadgesTitle" class="sy-h2">Quest badges <small>earned once, kept forever, shown on your profile</small></h2>+ <div class="qx-badges">+ ${QUEST_BADGES.map((b) => `<span class="qx-badge${earned.has(b.code) ? '' : ' locked'}" title="${esc(b.how)}"><span aria-hidden="true">${b.icon}</span>${esc(b.label)}${earned.has(b.code) ? '' : `<span class="sr-only"> (locked: ${esc(b.how)})</span>`}</span>`).join('')}+ </div>+ </section>+ ${data.yesterday?.cleared ? '' : data.yesterday?.done_count ? `<p class="sy-fine" style="margin-top:14px">Yesterday: ${esc(data.yesterday.done_count)} of ${esc(clear.need)} quests.</p>` : ''}+ ${linksSection()}`;+ wireClaims();+}++function rewardsSection() {+ const rw = data.three_rewards;+ if (!rw?.armed) return '';+ const claims = new Map((rw.claims || []).map((c) => [c.day, c]));+ const days = [+ { day: data.day, label: 'Today', cleared: data.daily_clear.cleared },+ { day: data.yesterday.day, label: 'Yesterday', cleared: data.yesterday.cleared },+ ].filter((d) => d.cleared);+ if (!days.length) {+ return `<div class="sy-note" style="margin-top:14px">Clear the day to claim ${esc(rw.amount_three)} $THREE to your linked Solana wallet.</div>`;+ }+ return `+ <section class="sy-panel" style="margin-top:14px" aria-labelledby="qxRewardTitle">+ <h2 id="qxRewardTitle" class="sy-h2">$THREE reward <small>${esc(rw.amount_three)} $THREE per cleared day, to your linked wallet</small></h2>+ <div class="sy-actions">+ ${days.map((d) => {+ const c = claims.get(d.day);+ if (c?.status === 'sent') return `<a class="sy-btn" href="https://solscan.io/tx/${esc(c.tx_signature)}" target="_blank" rel="noopener">${esc(d.label)}: sent ↗</a>`;+ if (c?.status === 'pending') return `<button type="button" class="sy-btn" disabled>${esc(d.label)}: sending…</button>`;+ return `<button type="button" class="sy-btn primary" data-claim="${esc(d.day)}">${c?.status === 'failed' ? 'Retry' : 'Claim'} ${esc(d.label.toLowerCase())}'s reward</button>`;+ }).join('')}+ </div>+ </section>`;+}++function wireClaims() {+ for (const btn of rootEl.querySelectorAll('[data-claim]')) {+ btn.addEventListener('click', async () => {+ btn.disabled = true;+ const label = btn.textContent;+ btn.textContent = 'Sending…';+ try {+ const r = await apiFetch('/api/quests/claim', {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({ day: btn.dataset.claim }),+ });+ if (!r.ok) {+ const { message } = await errorMessage(r, 'Could not send the reward.');+ toast(message);+ btn.disabled = false;+ btn.textContent = label;+ return;+ }+ toast('$THREE sent to your linked wallet.');+ load();+ } catch {+ toast('Network error. Nothing was sent; try again.');+ btn.disabled = false;+ btn.textContent = label;+ }+ });+ }+}++function linksSection() {+ return `+ <section class="sy-section" aria-label="Where quests happen">+ <div class="sy-actions">+ <a class="sy-btn" href="/syndicates">Join a syndicate</a>+ <a class="sy-btn" href="/play/arena">Watch the Arena</a>+ <a class="sy-btn" href="/docs/trading-quests">How quests are scored</a>+ </div>+ </section>`;+}++function tickClock() {+ if (!data?.resets_at) return;+ const ms = new Date(data.resets_at).getTime() - Date.now();+ if (ms <= 0) {+ clearInterval(clockTimer);+ clockTimer = null;+ resetEl.textContent = 'now';+ load();+ return;+ }+ const h = Math.floor(ms / 3_600_000);+ const m = Math.floor((ms % 3_600_000) / 60_000);+ resetEl.textContent = `in ${h}h ${String(m).padStart(2, '0')}m`;+ if (!clockTimer) clockTimer = setInterval(tickClock, 30_000);+}++load();diff --git a/src/syndicate-shared.js b/src/syndicate-shared.jsnew file mode 100644index 000000000..ba86a3960--- /dev/null+++ b/src/syndicate-shared.js@@ -0,0 +1,121 @@+// Shared rendering helpers for /syndicates, /syndicates/:slug and /quests.++export const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);++/** Signed SOL with a sign and adaptive precision: "+0.042 SOL", "-1.20 SOL". */+export function fmtSol(v, { sign = true } = {}) {+ const n = num(v);+ const abs = Math.abs(n);+ const digits = abs === 0 ? 2 : abs < 0.01 ? 4 : abs < 1 ? 3 : 2;+ const s = abs.toFixed(digits);+ if (!sign || n === 0) return `${n < 0 ? '-' : ''}${s} SOL`;+ return `${n > 0 ? '+' : '\u2212'}${s} SOL`;+}++export function fmtPct(v, { sign = true } = {}) {+ if (v == null || !Number.isFinite(Number(v))) return 'n/a';+ const n = Number(v);+ return `${sign && n > 0 ? '+' : ''}${n.toFixed(Math.abs(n) >= 100 ? 0 : 1)}%`;+}++/** CSS class for a signed number. */+export const tone = (v) => (num(v) > 0 ? 'pos' : num(v) < 0 ? 'neg' : 'flat');++export function relTime(iso) {+ if (!iso) return '';+ const s = Math.round((Date.now() - new Date(iso).getTime()) / 1000);+ if (s < 60) return 'just now';+ const m = Math.round(s / 60);+ if (m < 60) return `${m}m ago`;+ const h = Math.round(m / 60);+ if (h < 48) return `${h}h ago`;+ const d = Math.round(h / 24);+ return d < 60 ? `${d}d ago` : new Date(iso).toLocaleDateString();+}++/** Round avatar, falling back to an initial when there is no image. Call+ * hydrateAvatars(root) after inserting, so a broken image swaps to the initial. */+export function avatar(name, image, cls = 'sy-ava') {+ const initial = esc((String(name || '?').trim()[0] || '?').toUpperCase());+ if (image) {+ return `<img class="${cls}" src="${esc(image)}" alt="" loading="lazy" decoding="async" data-initial="${initial}" />`;+ }+ return `<span class="${cls}" aria-hidden="true">${initial}</span>`;+}++export function hydrateAvatars(root) {+ for (const img of root.querySelectorAll('img[data-initial]')) {+ img.addEventListener('error', () => {+ const span = document.createElement('span');+ span.className = img.className;+ span.setAttribute('aria-hidden', 'true');+ span.textContent = img.dataset.initial || '?';+ img.replaceWith(span);+ }, { once: true });+ }+}++/** A syndicate's flag: its color and the first letter of its name. */+export function flag(name, color, cls = 'sy-flag') {+ return `<span class="${cls}" style="--flag:${esc(color)}" aria-hidden="true">${esc((String(name || '?').trim()[0] || '?').toUpperCase())}</span>`;+}++/** One line describing a leader's whole closed record. */+export function recordLine(record) {+ if (!record) return '';+ const parts = [`${num(record.settled)} closed trades`];+ if (record.win_rate_pct != null) parts.push(`${Math.round(record.win_rate_pct)}% wins`);+ parts.push(`<span class="${tone(record.realized_pnl_sol)}">${esc(fmtSol(record.realized_pnl_sol))}</span> on ${esc(num(record.deployed_sol).toFixed(2))} SOL`);+ if (record.max_drawdown_pct != null) parts.push(`${esc(Math.round(record.max_drawdown_pct))}% max drawdown`);+ return parts.join(' · ');+}++let toastTimer;+export function toast(msg, el = document.getElementById('syToast')) {+ if (!el) return;+ el.textContent = msg;+ el.classList.add('show');+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => el.classList.remove('show'), 2800);+}++/** The signed-in user, or null. Never throws; a failed probe reads as signed out. */+let mePromise = null;+export function currentUser() {+ if (!mePromise) {+ mePromise = fetch('/api/auth/me', { credentials: 'include', headers: { accept: 'application/json' } })+ .then((r) => (r.ok ? r.json() : null))+ .then((d) => d?.user || null)+ .catch(() => null);+ }+ return mePromise;+}++/** The API's human message for a failed response. */+export async function errorMessage(res, fallback) {+ const body = await res.json().catch(() => ({}));+ return { body, message: body?.error_description || body?.message || fallback };+}++/** Equity curve SVG path over cumulative SOL points. */+export function curveSvg(points, { width = 600, height = 180, color = 'var(--sy-accent)', label = 'Group equity curve' } = {}) {+ if (!points?.length) return '';+ const ys = points.map((p) => num(p.cum_sol));+ const min = Math.min(0, ...ys);+ const max = Math.max(0, ...ys);+ const span = max - min || 1;+ const pad = 8;+ const x = (i) => (points.length === 1 ? width / 2 : pad + (i * (width - pad * 2)) / (points.length - 1));+ const y = (v) => pad + ((max - v) * (height - pad * 2)) / span;+ const line = points.map((p, i) => `${i ? 'L' : 'M'}${x(i).toFixed(1)},${y(num(p.cum_sol)).toFixed(1)}`).join(' ');+ const area = `${line} L${x(points.length - 1).toFixed(1)},${y(0).toFixed(1)} L${x(0).toFixed(1)},${y(0).toFixed(1)} Z`;+ const last = ys[ys.length - 1];+ return `+ <svg class="sy-chart" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none" role="img" aria-label="${esc(label)}: ${esc(fmtSol(last))} after ${points.length} closed copies">+ <line x1="0" x2="${width}" y1="${y(0).toFixed(1)}" y2="${y(0).toFixed(1)}" stroke="var(--sy-line)" stroke-dasharray="4 4" />+ <path d="${area}" fill="${color}" opacity="0.12" />+ <path d="${line}" fill="none" stroke="${color}" stroke-width="2.4" vector-effect="non-scaling-stroke" stroke-linejoin="round" />+ </svg>`;+}diff --git a/src/syndicate.js b/src/syndicate.jsnew file mode 100644index 000000000..c4bff8324--- /dev/null+++ b/src/syndicate.js@@ -0,0 +1,411 @@+// /syndicates/:slug: one syndicate's page, and joining or leaving it.+//+// Public data comes from GET /api/syndicates/:slug (cacheable): identity, the+// leaders with their whole records, the roster, the group curve from members'+// real acted copies, and the rival one rank away. The viewer's own membership+// comes from GET /api/syndicates/membership. Joining posts the member's own+// wallet and caps to POST /api/syndicates/membership, which creates ordinary+// guarded copy subscriptions; intents then arrive on /dashboard/copy.++import { apiFetch } from './api.js';+import { esc, fmtSol, fmtPct, tone, avatar, hydrateAvatars, flag, recordLine, toast, currentUser, errorMessage, relTime, curveSvg } from './syndicate-shared.js';++const root = document.getElementById('syRoot');+const content = document.getElementById('syContent');+const leaveDialog = document.getElementById('syLeave');+const leaveBody = document.getElementById('syLeaveBody');++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const slug = (() => {+ const seg = location.pathname.replace(/\/+$/, '').split('/').pop() || '';+ try { return decodeURIComponent(seg).toLowerCase(); } catch { return ''; }+})();+const params = new URLSearchParams(location.search);++let data = null;++// ── load ─────────────────────────────────────────────────────────────────────++async function load() {+ root.setAttribute('aria-busy', 'true');+ try {+ const r = await fetch(`/api/syndicates/${encodeURIComponent(slug)}`, { headers: { accept: 'application/json' } });+ if (r.status === 404 || r.status === 400) return renderMissing();+ if (!r.ok) {+ const { message } = await errorMessage(r, `The syndicate answered ${r.status}.`);+ return renderError(message);+ }+ data = await r.json();+ render();+ loadMembership();+ } catch {+ renderError('Check your connection.');+ } finally {+ root.setAttribute('aria-busy', 'false');+ }+}++function renderMissing() {+ document.title = 'Syndicate not found · three.ws';+ content.innerHTML = `+ <div class="sy-state">+ <h2>No syndicate flies that name</h2>+ <p>The link may be mistyped, or the syndicate may have been renamed. The board lists every active syndicate, and you can start your own in a minute.</p>+ <div class="sy-actions" style="justify-content:center">+ <a class="sy-btn primary" href="/syndicates">Browse the board</a>+ <a class="sy-btn" href="/syndicates?start=1">Start a syndicate</a>+ </div>+ </div>`;+}++function renderError(message) {+ content.innerHTML = `+ <div class="sy-state" role="alert">+ <h2>This syndicate did not load</h2>+ <p>${esc(message)} Your copy subscriptions keep running either way.</p>+ <button type="button" class="sy-btn primary" id="syRetry">Try again</button>+ </div>`;+ document.getElementById('syRetry').addEventListener('click', load);+}++// ── render ───────────────────────────────────────────────────────────────────++function render() {+ const { syndicate: s, leaders, members, performance: p, since_founding: since, standing } = data;+ document.title = `${s.name} · Syndicate · three.ws`;+ const founder = s.founder?.display_name || s.founder?.username;++ content.innerHTML = `+ <header class="sy-head" style="--flag:${esc(s.color)}">+ ${flag(s.name, s.color, 'sy-flag lg')}+ <div style="min-width:0">+ <h1>${esc(s.name)}</h1>+ ${s.motto ? `<p class="sy-motto">"${esc(s.motto)}"</p>` : ''}+ <div class="sy-head-meta">+ ${s.official ? '<span class="sy-badge official" title="Founded by the owner of a leader it follows">Official fan club</span>' : ''}+ ${s.network === 'devnet' ? '<span class="sy-badge">devnet</span>' : ''}+ <span>Formed ${esc(relTime(s.created_at))}${founder ? ` by ${esc(founder)}` : ''}</span>+ <button type="button" class="sy-btn sm" id="syShare">Share</button>+ <a class="sy-btn sm primary" href="#syJoin">Membership</a>+ </div>+ </div>+ </header>++ <div class="sy-grid">+ <div style="display:grid;gap:16px;min-width:0">+ <section class="sy-panel" aria-labelledby="syPerfTitle">+ <h2 id="syPerfTitle" class="sy-h2">Group performance <small>members' real copies, priced at each leader's realized return</small></h2>+ <dl class="sy-tiles">+ <div class="sy-tile"><dt>Group P&L</dt><dd class="${tone(p.realized_profit_sol)}">${esc(fmtSol(p.realized_profit_sol))}</dd><small>realized, closed copies</small></div>+ <div class="sy-tile"><dt>Closed copies</dt><dd>${esc(p.closed_copies)}</dd><small>${p.win_rate_pct == null ? 'no closes yet' : `${esc(Math.round(p.win_rate_pct))}% in profit`}</small></div>+ <div class="sy-tile"><dt>Copied</dt><dd>${esc(Number(p.copied_sol).toFixed(2))} SOL</dd><small>${esc(p.acted)} of ${esc(p.intents)} intents acted on</small></div>+ <div class="sy-tile"><dt>Leaders since formed</dt><dd class="${tone(since.leader_roi_pct)}">${since.leader_closes ? esc(fmtPct(since.leader_roi_pct)) : 'n/a'}</dd><small>${since.leader_closes ? `${esc(since.leader_closes)} live closes, ${esc(fmtSol(since.leader_pnl_sol))}` : 'no live closes since founding'}</small></div>+ </dl>+ <div style="margin-top:16px">+ ${p.curve.points.length+ ? curveSvg(p.curve.points, { color: s.color, label: `${s.name} group equity curve` })+ : `<div class="sy-chart-empty"><div><b>No closed copies yet.</b><br />The curve starts when a member acts on a copy intent and the leader closes that position. Every point is a real copy, winners and losers alike.</div></div>`}+ </div>+ </section>++ <section aria-labelledby="syLeadTitle">+ <h2 id="syLeadTitle" class="sy-h2">Following <small>whole closed records, losses included</small></h2>+ <div class="sy-leaders">${leaders.map(leaderCard).join('')}</div>+ </section>++ <section class="sy-panel" aria-labelledby="syRosterTitle">+ <h2 id="syRosterTitle" class="sy-h2">Roster <small>${esc(members.count)} ${members.count === 1 ? 'member' : 'members'} · ${esc(members.copying)} copying now${members.alumni ? ` · ${esc(members.alumni)} alumni` : ''}</small></h2>+ ${members.list.length ? `<ul class="sy-roster">${members.list.map(memberItem).join('')}</ul>` : `<p class="sy-muted" style="margin:0">Nobody has joined yet. The first member sets the pace, and the roster shows usernames only: never a wallet, never a size.</p>`}+ ${members.count > members.list.length ? `<p class="sy-fine" style="margin-top:10px">Showing the first ${members.list.length} of ${members.count}.</p>` : ''}+ </section>+ </div>++ <aside class="sy-side" style="display:grid;gap:16px;min-width:0">+ <section class="sy-panel" aria-labelledby="syStandTitle">+ <h2 id="syStandTitle" class="sy-h2">Standing</h2>+ ${standingHtml(standing)}+ </section>+ <section class="sy-panel" id="syJoin" aria-labelledby="syJoinTitle" tabindex="-1">+ <h2 id="syJoinTitle" class="sy-h2">Ride with ${esc(s.name)}</h2>+ <div id="syJoinBody"><div class="sy-skel" style="height:120px"></div></div>+ </section>+ </aside>+ </div>`;+ hydrateAvatars(content);+ document.getElementById('syShare').addEventListener('click', share);+}++function leaderCard(l) {+ return `+ <div class="sy-leader">+ ${avatar(l.name, l.image)}+ <div style="min-width:0">+ <div class="sy-leader-name">${esc(l.name)}</div>+ <div style="margin-top:4px">${!l.available ? '<span class="sy-badge warn">No longer public</span>' : l.copyable ? '<span class="sy-badge good">Copyable</span>' : '<span class="sy-badge warn">Not copyable right now</span>'}</div>+ <div class="sy-leader-line">${recordLine(l.record)}${l.record.roi_pct != null ? ` · <span class="${tone(l.record.roi_pct)}">${esc(fmtPct(l.record.roi_pct))} ROI</span>` : ''}</div>+ ${!l.copyable && l.unmet.length ? `<div class="sy-leader-line">Still short: ${esc(l.unmet.join(', '))}</div>` : ''}+ <div class="sy-leader-links">+ <a href="${esc(l.trader_url)}">Full record</a>+ <a href="/ghost-copy?leader=${esc(l.agent_id)}&budget=1&window=7d">Ghost-copy</a>+ </div>+ </div>+ </div>`;+}++function memberItem(m) {+ const body = `${avatar(m.display_name, m.avatar_url)}<div><b>${esc(m.display_name)}</b><small>${m.role === 'founder' ? 'Founder · ' : ''}joined ${esc(relTime(m.joined_at))}</small></div>`;+ return `<li>${m.username ? `<a href="/u/${encodeURIComponent(m.username)}" style="display:flex;gap:10px;align-items:center;min-width:0">${body}</a>` : body}</li>`;+}++function standingHtml(st) {+ if (!st?.rank) return '<p class="sy-muted" style="margin:0">Not ranked: this syndicate is not active on the board.</p>';+ const rival = st.rival;+ const head = `<p style="margin:0 0 12px"><span style="font-size:32px;font-weight:900;letter-spacing:-.03em">#${esc(st.rank)}</span> <span class="sy-faint">of ${esc(st.total)} on the profit board</span></p>`;+ if (!rival) return `${head}<p class="sy-muted" style="margin:0">No rival yet. The next syndicate to form becomes the one to beat. <a href="/syndicates?start=1">Start one</a>.</p>`;+ const verb = rival.direction === 'ahead'+ ? `${esc(fmtSol(rival.gap_sol, { sign: false }))} ahead of you. Catch them.`+ : `${esc(fmtSol(rival.gap_sol, { sign: false }))} behind you and chasing.`;+ return `${head}+ <a class="sy-rival" href="${esc(rival.url)}" style="--flag:${esc(rival.color)}">+ ${flag(rival.name, rival.color)}+ <span style="min-width:0"><b style="display:block">${esc(rival.name)}</b><small class="sy-faint">${verb}</small></span>+ </a>`;+}++async function share() {+ const url = `${location.origin}/syndicates/${data.syndicate.slug}`;+ const text = `Ride with ${data.syndicate.name} on three.ws: a copy-trading syndicate where everyone copies from their own wallet under their own caps.`;+ try {+ if (navigator.share) { await navigator.share({ title: data.syndicate.name, text, url }); return; }+ await navigator.clipboard.writeText(url);+ toast('Link copied');+ } catch (err) {+ if (err?.name !== 'AbortError') toast('Copy this link: ' + url);+ }+}++// ── membership ───────────────────────────────────────────────────────────────++const joinBody = () => document.getElementById('syJoinBody');++async function loadMembership() {+ const el = joinBody();+ if (!el) return;+ const user = await currentUser();+ if (!user) return renderSignedOut(el);+ try {+ const r = await apiFetch(`/api/syndicates/membership?slug=${encodeURIComponent(slug)}`, { allowAnonymous: true, headers: { accept: 'application/json' } });+ if (r.status === 401) return renderSignedOut(el);+ if (!r.ok) {+ const { message } = await errorMessage(r, 'Could not load your membership.');+ return renderJoinError(el, message);+ }+ const { membership } = await r.json();+ renderMembership(el, membership, user);+ } catch {+ renderJoinError(el, 'Network error.');+ }+}++function renderJoinError(el, message) {+ el.innerHTML = `<p class="sy-muted" style="margin:0 0 12px">${esc(message)}</p><button type="button" class="sy-btn" id="syJoinRetry">Retry</button>`;+ el.querySelector('#syJoinRetry').addEventListener('click', loadMembership);+}++function renderSignedOut(el) {+ const next = encodeURIComponent(location.pathname);+ el.innerHTML = `+ <p class="sy-muted" style="margin:0 0 12px;line-height:1.55">Copy these leaders from your own wallet with your own caps, and your copies count toward the team's curve. Sign in to join.</p>+ <div class="sy-actions"><a class="sy-btn primary" href="/login?next=${next}">Sign in to join</a><a class="sy-btn" href="/ghost-copy?leader=${esc(data.leaders[0]?.agent_id || '')}">Ghost-copy first</a></div>`;+}++function renderMembership(el, m, user) {+ if (params.get('founded') === '1') {+ toast('Flag raised. Join with your own caps, or share it with followers.');+ history.replaceState(null, '', location.pathname);+ params.delete('founded');+ document.getElementById('syJoin')?.focus();+ }+ if (m.member) return renderMember(el, m);+ if (m.owns_leader) {+ el.innerHTML = `+ <p class="sy-muted" style="margin:0 0 12px;line-height:1.55">You run one of the leaders this syndicate follows, so you cannot copy it: that would pay a performance fee to yourself. Your part is the trading. Share this page with the people who follow you.</p>+ <div class="sy-actions"><button type="button" class="sy-btn primary" id="syShare2">Share with followers</button></div>`;+ el.querySelector('#syShare2').addEventListener('click', share);+ return;+ }+ if (m.other_syndicate) {+ el.innerHTML = `+ <p class="sy-muted" style="margin:0 0 12px;line-height:1.55">You ride with <a href="${esc(m.other_syndicate.url)}"><b>${esc(m.other_syndicate.name)}</b></a>. One syndicate at a time: leave it first if you want to switch sides.</p>+ <div class="sy-actions"><a class="sy-btn" href="${esc(m.other_syndicate.url)}">Go to ${esc(m.other_syndicate.name)}</a></div>`;+ return;+ }+ if (!data.joinable) {+ const blocked = data.leaders.filter((l) => !l.copyable || !l.available);+ el.innerHTML = `+ <p class="sy-muted" style="margin:0;line-height:1.55">Closed to new members for now: ${blocked.map((l) => `<b>${esc(l.name)}</b>`).join(', ')} ${blocked.length === 1 ? 'does' : 'do'} not clear the copyable bar at the moment. It reopens on its own once every leader does.</p>`;+ return;+ }+ renderJoinForm(el, user);+}++function renderMember(el, m) {+ const names = new Map(data.leaders.map((l) => [l.agent_id, l.name]));+ const subs = m.member.subscriptions;+ el.innerHTML = `+ <p style="margin:0 0 10px"><span class="sy-badge good">You ride with this syndicate</span></p>+ <p class="sy-muted" style="margin:0 0 12px;line-height:1.55">Joined ${esc(relTime(m.member.joined_at))}. When a leader trades, a sized intent lands on your copy dashboard; you execute it from your own wallet.</p>+ <ul style="list-style:none;margin:0 0 14px;padding:0;display:grid;gap:6px">+ ${subs.map((s) => `<li class="sy-leader-line" style="display:flex;justify-content:space-between;gap:10px"><span>${esc(names.get(s.leader_agent_id) || 'Leader')}</span><span>${s.status === 'active' ? '<span class="pos">copying</span>' : s.status === 'paused' ? `<span class="sy-faint">${s.paused_reason === 'leader_drawdown_breach' ? 'paused by your drawdown limit' : 'paused'}</span>` : '<span class="neg">stopped</span>'}</span></li>`).join('')}+ </ul>+ <div class="sy-actions">+ <a class="sy-btn primary" href="/dashboard/copy">Open copy intents</a>+ <button type="button" class="sy-btn danger" id="syLeaveBtn">Leave</button>+ </div>+ <p class="sy-fine" style="margin-top:12px">Pause, resume, or change caps per leader on your copy dashboard; the syndicate follows those settings.</p>`;+ el.querySelector('#syLeaveBtn').addEventListener('click', () => openLeave(m));+}++function renderJoinForm(el, user) {+ const wallet = user?.wallet_address && BASE58_RE.test(user.wallet_address) ? user.wallet_address : '';+ el.innerHTML = `+ <form class="sy-form" id="syJoinForm" novalidate>+ <label class="sy-field">+ <span class="sy-label">Your Solana wallet</span>+ <input class="sy-input" id="syWallet" autocomplete="off" spellcheck="false" inputmode="text" placeholder="The wallet you copy from" value="${esc(wallet)}" required />+ <span class="sy-hint">You sign every copy from this wallet. We store its address, never a key.</span>+ </label>+ <div class="sy-row2">+ <label class="sy-field"><span class="sy-label">SOL per copy</span><input class="sy-input" id="syFixed" type="number" min="0.01" step="0.01" value="0.1" required /></label>+ <label class="sy-field"><span class="sy-label">Max per trade</span><input class="sy-input" id="syCap" type="number" min="0.01" step="0.05" value="0.5" required /></label>+ </div>+ <div class="sy-row2">+ <label class="sy-field"><span class="sy-label">Daily budget (SOL)</span><input class="sy-input" id="syDaily" type="number" min="0.01" step="0.1" value="1" required /></label>+ <label class="sy-field"><span class="sy-label">Pause at drawdown (%)</span><input class="sy-input" id="syDd" type="number" min="1" max="100" step="1" value="35" placeholder="never" /></label>+ </div>+ <p class="sy-hint" style="margin:0">These caps apply to each leader this syndicate follows (${esc(data.leaders.length)}). If you already copy one of them, your existing settings are kept, not replaced.</p>+ <div id="syJoinErr" class="sy-err" role="alert" hidden></div>+ <button type="submit" class="sy-btn primary" id="syJoinSubmit">Join ${esc(data.syndicate.name)}</button>+ <p class="sy-fine">Your username appears on the roster; your wallet and sizes never do. Copy trading is risky and you execute every trade yourself.</p>+ </form>`;+ el.querySelector('#syJoinForm').addEventListener('submit', submitJoin);+}++async function submitJoin(e) {+ e.preventDefault();+ const el = joinBody();+ const errEl = el.querySelector('#syJoinErr');+ const btn = el.querySelector('#syJoinSubmit');+ errEl.hidden = true;+ const wallet = el.querySelector('#syWallet').value.trim();+ if (!BASE58_RE.test(wallet)) return showErr(errEl, 'Enter a valid Solana wallet address.');+ const num = (id) => Number(el.querySelector(id).value);+ const dd = el.querySelector('#syDd').value.trim();+ const body = {+ slug,+ action: 'join',+ copier_wallet: wallet,+ sizing_rule: 'fixed',+ fixed_sol: num('#syFixed'),+ per_trade_cap_sol: num('#syCap'),+ daily_budget_sol: num('#syDaily'),+ max_drawdown_pct: dd === '' ? null : Number(dd),+ };+ if (!(body.fixed_sol > 0)) return showErr(errEl, 'SOL per copy must be more than 0.');+ if (body.fixed_sol > body.per_trade_cap_sol) return showErr(errEl, 'SOL per copy cannot be above your max per trade.');++ btn.disabled = true;+ btn.textContent = 'Joining…';+ try {+ const r = await apiFetch('/api/syndicates/membership', {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify(body),+ });+ if (!r.ok) {+ const { body: b, message } = await errorMessage(r, 'Could not join.');+ if (Array.isArray(b.leaders) && b.leaders.length) {+ errEl.innerHTML = `<strong>${esc(message)}</strong><ul>${b.leaders.map((l) => `<li>${esc(l.name)}: ${esc((l.unmet || []).join(', '))}</li>`).join('')}</ul>`;+ errEl.hidden = false;+ } else {+ showErr(errEl, message);+ }+ btn.disabled = false;+ btn.textContent = `Join ${data.syndicate.name}`;+ return;+ }+ toast(`Welcome to ${data.syndicate.name}. Intents will land on your copy dashboard.`);+ await refresh();+ } catch {+ showErr(errEl, 'Network error. Nothing changed; try again.');+ btn.disabled = false;+ btn.textContent = `Join ${data.syndicate.name}`;+ }+}++function openLeave(m) {+ const names = new Map(data.leaders.map((l) => [l.agent_id, l.name]));+ const made = m.member.subscriptions.filter((s) => s.created_by_join);+ const kept = m.member.subscriptions.filter((s) => !s.created_by_join);+ leaveBody.innerHTML = `+ <p class="sy-muted" style="margin:0 0 12px;line-height:1.55">Leaving takes you off the roster, and your copies stop counting toward the team curve.</p>+ ${made.length ? `<p style="margin:0 0 6px"><b>Stops copying</b> (joining started these):</p><ul class="sy-leader-line" style="margin:0 0 12px">${made.map((s) => `<li>${esc(names.get(s.leader_agent_id) || 'Leader')}</li>`).join('')}</ul>` : ''}+ ${kept.length ? `<p style="margin:0 0 6px"><b>Keeps copying</b> (you followed these before joining):</p><ul class="sy-leader-line" style="margin:0 0 12px">${kept.map((s) => `<li>${esc(names.get(s.leader_agent_id) || 'Leader')}</li>`).join('')}</ul>` : ''}+ <p class="sy-fine" style="margin:0 0 14px">Positions you already hold are yours and are not touched.</p>+ <div id="syLeaveErr" class="sy-err" role="alert" hidden></div>+ <div class="sy-actions">+ <button type="button" class="sy-btn danger" id="syLeaveConfirm">Leave ${esc(data.syndicate.name)}</button>+ <button type="button" class="sy-btn" data-close>Stay</button>+ </div>`;+ leaveDialog.showModal();+ leaveBody.querySelector('#syLeaveConfirm').addEventListener('click', confirmLeave);+}++async function confirmLeave() {+ const btn = leaveBody.querySelector('#syLeaveConfirm');+ const errEl = leaveBody.querySelector('#syLeaveErr');+ btn.disabled = true;+ btn.textContent = 'Leaving…';+ try {+ const r = await apiFetch('/api/syndicates/membership', {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({ slug, action: 'leave' }),+ });+ if (!r.ok) {+ const { message } = await errorMessage(r, 'Could not leave.');+ showErr(errEl, message);+ btn.disabled = false;+ btn.textContent = `Leave ${data.syndicate.name}`;+ return;+ }+ leaveDialog.close();+ toast(`You left ${data.syndicate.name}.`);+ await refresh();+ } catch {+ showErr(errEl, 'Network error. You are still a member; try again.');+ btn.disabled = false;+ btn.textContent = `Leave ${data.syndicate.name}`;+ }+}++async function refresh() {+ try {+ const r = await fetch(`/api/syndicates/${encodeURIComponent(slug)}?fresh=${Date.now()}`, { headers: { accept: 'application/json' }, cache: 'no-store' });+ if (r.ok) { data = await r.json(); render(); }+ } catch {+ // The page already shows the last good state; the membership panel below still refreshes.+ }+ await loadMembership();+}++function showErr(el, msg) {+ el.textContent = msg;+ el.hidden = false;+}++leaveDialog.addEventListener('click', (e) => {+ if (e.target === leaveDialog || e.target.closest('[data-close]')) leaveDialog.close();+});++load();diff --git a/src/syndicates.css b/src/syndicates.cssnew file mode 100644index 000000000..fca39d269--- /dev/null+++ b/src/syndicates.css@@ -0,0 +1,256 @@+/* Syndicates + trading quests: shared surface styles for /syndicates,+ /syndicates/:slug and /quests. One palette, both themes, every state. */++:root {+ --sy-bg: #0a0a0b;+ --sy-panel: #121214;+ --sy-panel-2: #17171a;+ --sy-line: #26262b;+ --sy-text: #f5f5f7;+ --sy-dim: #a1a1aa;+ --sy-faint: #74747d;+ --sy-accent: #7c5cff;+ --sy-accent-2: #22d3ee;+ --sy-green: #34d399;+ --sy-red: #fb7185;+ --sy-amber: #f59e0b;+ --sy-chip: #1e1e24;+ --sy-radius: 16px;+ --sy-fast: 140ms;+ --sy-base: 220ms;+}+:root[data-theme='light'] {+ --sy-bg: #fafafa;+ --sy-panel: #ffffff;+ --sy-panel-2: #f4f4f6;+ --sy-line: #e4e4e8;+ --sy-text: #14141a;+ --sy-dim: #52525b;+ --sy-faint: #6b6b74;+ --sy-chip: #eef0f4;+ --sy-green: #059669;+ --sy-red: #e11d48;+ --sy-amber: #b45309;+}++* { box-sizing: border-box; }+body {+ margin: 0;+ background: var(--sy-bg);+ color: var(--sy-text);+ font-family: 'Inter', system-ui, -apple-system, sans-serif;+ -webkit-font-smoothing: antialiased;+}+.sy { max-width: 1120px; margin: 0 auto; padding: 28px 20px 80px; }+.sy a { color: inherit; }+.sy-kicker { font-size: 12px; letter-spacing: .12em; text-transform: uppercase; color: var(--sy-accent); font-weight: 700; margin: 8px 0 10px; }+.sy-title { font-size: clamp(28px, 5.4vw, 48px); line-height: 1.04; font-weight: 800; margin: 0 0 12px; letter-spacing: -.025em; }+.sy-sub { font-size: clamp(14px, 2.2vw, 17px); color: var(--sy-dim); max-width: 66ch; line-height: 1.55; margin: 0 0 22px; }+.sy-h2 { font-size: 16px; font-weight: 800; margin: 0 0 12px; letter-spacing: -.01em; display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }+.sy-h2 small { color: var(--sy-faint); font-weight: 500; font-size: 13px; }+.sy-section { margin-top: 28px; }+.sy-muted { color: var(--sy-dim); }+.sy-faint { color: var(--sy-faint); }+.pos { color: var(--sy-green); }+.neg { color: var(--sy-red); }+.flat { color: var(--sy-dim); }+.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); border: 0; }++/* ── buttons ─────────────────────────────────────────────── */+.sy-btn {+ appearance: none; display: inline-flex; align-items: center; justify-content: center; gap: 8px;+ font: inherit; font-weight: 700; font-size: 14px; padding: 11px 18px; border-radius: 11px;+ border: 1px solid var(--sy-line); background: var(--sy-panel-2); color: var(--sy-text);+ text-decoration: none; cursor: pointer; min-height: 44px;+ transition: background var(--sy-fast), border-color var(--sy-fast), transform var(--sy-fast), opacity var(--sy-fast);+}+.sy-btn:hover { border-color: var(--sy-accent); transform: translateY(-1px); }+.sy-btn:active { transform: none; }+.sy-btn:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }+.sy-btn[disabled] { opacity: .55; cursor: not-allowed; transform: none; }+.sy-btn.primary { background: var(--sy-accent); border-color: var(--sy-accent); color: #fff; }+.sy-btn.primary:hover { filter: brightness(1.08); }+.sy-btn.danger { color: var(--sy-red); }+.sy-btn.danger:hover { border-color: var(--sy-red); }+.sy-btn.sm { padding: 7px 12px; font-size: 13px; min-height: 36px; border-radius: 9px; }+.sy-actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }++/* ── segmented control ───────────────────────────────────── */+.sy-seg { display: inline-flex; background: var(--sy-panel-2); border: 1px solid var(--sy-line); border-radius: 10px; padding: 4px; gap: 4px; }+.sy-seg button { white-space: nowrap; appearance: none; border: 0; background: transparent; color: var(--sy-dim); font: inherit; font-weight: 700; font-size: 13px; padding: 8px 12px; border-radius: 7px; cursor: pointer; transition: background var(--sy-fast), color var(--sy-fast); min-height: 36px; }+.sy-seg button:hover { color: var(--sy-text); }+.sy-seg button[aria-pressed='true'] { background: var(--sy-accent); color: #fff; }+.sy-seg button:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }++@media (max-width: 520px) {+ .sy-toolbar .sy-seg { width: 100%; }+ .sy-toolbar .sy-seg button { flex: 1; padding: 8px 6px; font-size: 12.5px; }+}++/* ── panels, tiles ───────────────────────────────────────── */+.sy-panel { background: var(--sy-panel); border: 1px solid var(--sy-line); border-radius: var(--sy-radius); padding: 20px; }+.sy-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px; margin: 0; }+.sy-tile { background: var(--sy-panel-2); border: 1px solid var(--sy-line); border-radius: 12px; padding: 12px 14px; margin: 0; }+.sy-tile dt { font-size: 11px; text-transform: uppercase; letter-spacing: .07em; color: var(--sy-faint); font-weight: 700; margin: 0 0 5px; }+.sy-tile dd { margin: 0; font-size: 20px; font-weight: 800; letter-spacing: -.02em; font-variant-numeric: tabular-nums; }+.sy-tile small { display: block; font-size: 11.5px; font-weight: 500; color: var(--sy-faint); margin-top: 3px; letter-spacing: 0; }++/* ── avatars + flags ─────────────────────────────────────── */+.sy-ava { width: 34px; height: 34px; border-radius: 50%; object-fit: cover; background: var(--sy-panel-2); border: 2px solid var(--sy-panel); flex: none; display: inline-grid; place-items: center; font-weight: 800; font-size: 12px; color: var(--sy-accent); }+.sy-ava-stack { display: inline-flex; }+.sy-ava-stack > * + * { margin-left: -10px; }+.sy-flag { width: 44px; height: 44px; border-radius: 12px; flex: none; display: grid; place-items: center; font-weight: 900; font-size: 18px; color: #0a0a0b; background: var(--flag, var(--sy-accent)); box-shadow: 0 0 0 1px color-mix(in srgb, var(--flag, var(--sy-accent)) 50%, transparent), 0 8px 24px -10px var(--flag, var(--sy-accent)); }+.sy-flag.lg { width: 64px; height: 64px; font-size: 26px; border-radius: 16px; }+.sy-badge { font-size: 11px; font-weight: 800; letter-spacing: .06em; text-transform: uppercase; padding: 4px 9px; border-radius: 999px; background: var(--sy-chip); color: var(--sy-dim); white-space: nowrap; }+.sy-badge.official { background: color-mix(in srgb, var(--sy-amber) 18%, transparent); color: var(--sy-amber); }+.sy-badge.good { background: color-mix(in srgb, var(--sy-green) 16%, transparent); color: var(--sy-green); }+.sy-badge.warn { background: color-mix(in srgb, var(--sy-red) 16%, transparent); color: var(--sy-red); }++/* ── board ───────────────────────────────────────────────── */+.sy-toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; }+.sy-board { display: grid; gap: 10px; list-style: none; margin: 0; padding: 0; }+.sy-row {+ display: grid; grid-template-columns: 40px 44px minmax(0, 1fr) auto; align-items: center; gap: 14px;+ background: var(--sy-panel); border: 1px solid var(--sy-line); border-left: 3px solid var(--flag, var(--sy-accent));+ border-radius: 14px; padding: 14px 16px; text-decoration: none; color: inherit;+ transition: border-color var(--sy-fast), transform var(--sy-fast), background var(--sy-fast);+ animation: sy-in var(--sy-base) ease both;+}+.sy-row:hover { transform: translateY(-2px); border-color: var(--flag, var(--sy-accent)); background: var(--sy-panel-2); }+.sy-row:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }+.sy-rank { font-size: 20px; font-weight: 900; color: var(--sy-faint); text-align: center; font-variant-numeric: tabular-nums; }+.sy-row-main { min-width: 0; }+.sy-row-name { font-weight: 800; font-size: 16px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }+.sy-row-motto { font-size: 13px; color: var(--sy-dim); margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.sy-row-meta { font-size: 12.5px; color: var(--sy-faint); margin-top: 6px; display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }+.sy-row-stats { display: grid; grid-auto-flow: column; gap: 18px; text-align: right; }+.sy-stat b { display: block; font-size: 17px; font-weight: 800; font-variant-numeric: tabular-nums; }+.sy-stat span { font-size: 11px; color: var(--sy-faint); text-transform: uppercase; letter-spacing: .06em; font-weight: 700; }+@media (max-width: 720px) {+ .sy-row { grid-template-columns: 28px 40px minmax(0, 1fr); }+ .sy-row-stats { grid-column: 1 / -1; grid-auto-flow: row; grid-template-columns: repeat(3, 1fr); text-align: left; gap: 10px; }+ .sy-rank { font-size: 16px; }+}+@keyframes sy-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }++/* ── empty state / explainer ─────────────────────────────── */+.sy-hero-empty { background: radial-gradient(120% 140% at 0% 0%, color-mix(in srgb, var(--sy-accent) 16%, transparent), transparent 60%), var(--sy-panel); border: 1px solid var(--sy-line); border-radius: 20px; padding: clamp(20px, 4vw, 34px); }+.sy-steps { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 12px; margin: 18px 0 22px; padding: 0; list-style: none; counter-reset: sy; }+.sy-steps li { background: var(--sy-panel-2); border: 1px solid var(--sy-line); border-radius: 14px; padding: 14px 16px; counter-increment: sy; font-size: 14px; line-height: 1.5; color: var(--sy-dim); }+.sy-steps li::before { content: counter(sy); display: inline-grid; place-items: center; width: 24px; height: 24px; border-radius: 50%; background: var(--sy-accent); color: #fff; font-weight: 800; font-size: 12px; margin-bottom: 8px; }+.sy-steps li b { color: var(--sy-text); display: block; margin-bottom: 2px; }++/* ── leader cards (candidates + syndicate leaders) ───────── */+.sy-leaders { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 10px; }+.sy-leader { position: relative; display: grid; grid-template-columns: 40px minmax(0, 1fr); gap: 12px; align-items: start; background: var(--sy-panel); border: 1px solid var(--sy-line); border-radius: 14px; padding: 14px; text-align: left; font: inherit; color: inherit; transition: border-color var(--sy-fast), transform var(--sy-fast), background var(--sy-fast); }+button.sy-leader { cursor: pointer; width: 100%; }+button.sy-leader:hover:not([disabled]) { border-color: var(--sy-accent); transform: translateY(-2px); }+button.sy-leader:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }+button.sy-leader[aria-pressed='true'] { border-color: var(--sy-accent); background: var(--sy-panel-2); box-shadow: inset 0 0 0 1px var(--sy-accent); }+button.sy-leader[disabled] { cursor: not-allowed; opacity: .6; }+.sy-leader .sy-ava { width: 40px; height: 40px; }+.sy-leader-name { font-weight: 800; font-size: 14.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.sy-leader-line { font-size: 12.5px; color: var(--sy-faint); margin-top: 3px; line-height: 1.45; }+.sy-leader-links { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: 8px; font-size: 12.5px; font-weight: 700; }+.sy-leader-links a { white-space: nowrap; }+.sy-leader-links a { color: var(--sy-accent-2); text-decoration: none; }+.sy-leader-links a:hover { text-decoration: underline; }+.sy-check { position: absolute; top: 10px; right: 10px; width: 20px; height: 20px; border-radius: 6px; border: 1.5px solid var(--sy-line); display: grid; place-items: center; font-size: 12px; font-weight: 900; color: transparent; transition: background var(--sy-fast), border-color var(--sy-fast); }+button.sy-leader[aria-pressed='true'] .sy-check { background: var(--sy-accent); border-color: var(--sy-accent); color: #fff; }++/* ── forms ───────────────────────────────────────────────── */+.sy-form { display: grid; gap: 16px; }+.sy-field { display: grid; gap: 7px; min-width: 0; align-content: start; }+.sy-label { font-size: 12px; color: var(--sy-faint); text-transform: uppercase; letter-spacing: .08em; font-weight: 700; }+.sy-hint { font-size: 12.5px; color: var(--sy-faint); line-height: 1.45; }+.sy-input { width: 100%; background: var(--sy-panel-2); border: 1px solid var(--sy-line); color: var(--sy-text); font: inherit; font-size: 15px; padding: 11px 12px; border-radius: 10px; min-height: 44px; transition: border-color var(--sy-fast), box-shadow var(--sy-fast); }+.sy-input:hover { border-color: color-mix(in srgb, var(--sy-accent) 40%, var(--sy-line)); }+.sy-input:focus { outline: none; border-color: var(--sy-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--sy-accent) 22%, transparent); }+.sy-row2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; }+.sy-swatches { display: flex; flex-wrap: wrap; gap: 8px; }+.sy-swatch { appearance: none; width: 36px; height: 36px; border-radius: 10px; border: 2px solid transparent; background: var(--c); cursor: pointer; transition: transform var(--sy-fast), border-color var(--sy-fast); }+.sy-swatch:hover { transform: scale(1.08); }+.sy-swatch:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }+.sy-swatch[aria-checked='true'] { border-color: var(--sy-text); box-shadow: 0 0 0 2px var(--sy-bg) inset; }+.sy-err { background: color-mix(in srgb, var(--sy-red) 10%, transparent); border: 1px solid color-mix(in srgb, var(--sy-red) 40%, transparent); color: var(--sy-text); border-radius: 10px; padding: 12px 14px; font-size: 13.5px; line-height: 1.5; }+.sy-err ul { margin: 6px 0 0; padding-left: 18px; }+.sy-note { background: var(--sy-panel-2); border: 1px solid var(--sy-line); border-left: 3px solid var(--sy-accent-2); border-radius: 10px; padding: 12px 14px; font-size: 13px; color: var(--sy-dim); line-height: 1.55; }+.sy-fine { font-size: 12px; color: var(--sy-faint); line-height: 1.5; margin: 0; }++/* ── dialog ──────────────────────────────────────────────── */+dialog.sy-dialog { width: min(760px, calc(100vw - 24px)); max-height: calc(100dvh - 24px); border: 1px solid var(--sy-line); border-radius: 18px; background: var(--sy-panel); color: var(--sy-text); padding: 0; }+dialog.sy-dialog::backdrop { background: rgba(0, 0, 0, .6); backdrop-filter: blur(3px); }+dialog.sy-dialog[open] { animation: sy-in var(--sy-base) ease both; }+.sy-dialog-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 18px 20px; border-bottom: 1px solid var(--sy-line); position: sticky; top: 0; background: var(--sy-panel); z-index: 1; }+.sy-dialog-head h2 { margin: 0; font-size: 18px; }+.sy-dialog-body { padding: 20px; }+.sy-x { appearance: none; border: 1px solid var(--sy-line); background: var(--sy-panel-2); color: var(--sy-text); width: 36px; height: 36px; border-radius: 10px; cursor: pointer; font-size: 18px; line-height: 1; }+.sy-x:hover { border-color: var(--sy-accent); }+.sy-x:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }++/* ── detail page ─────────────────────────────────────────── */+.sy-head { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 16px; align-items: center; margin-bottom: 18px; }+.sy-head h1 { margin: 0; font-size: clamp(26px, 5vw, 42px); line-height: 1.05; letter-spacing: -.02em; font-weight: 800; overflow-wrap: anywhere; }+.sy-head-meta { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-top: 8px; font-size: 13px; color: var(--sy-faint); }+.sy-motto { font-size: 16px; color: var(--sy-dim); margin: 6px 0 0; font-style: italic; overflow-wrap: anywhere; }+.sy-grid { display: grid; gap: 16px; grid-template-columns: minmax(0, 1fr); }+@media (min-width: 960px) { .sy-grid { grid-template-columns: minmax(0, 1fr) 360px; align-items: start; } .sy-side { position: sticky; top: 84px; } }+.sy-chart { width: 100%; height: 180px; display: block; overflow: visible; }+.sy-chart-empty { min-height: 150px; display: grid; place-items: center; text-align: center; color: var(--sy-faint); font-size: 13.5px; border: 1px dashed var(--sy-line); border-radius: 12px; padding: 18px; line-height: 1.55; }+.sy-rival { display: flex; align-items: center; gap: 12px; text-decoration: none; background: var(--sy-panel-2); border: 1px solid var(--sy-line); border-radius: 12px; padding: 12px 14px; transition: border-color var(--sy-fast), transform var(--sy-fast); }+.sy-rival:hover { border-color: var(--flag, var(--sy-accent)); transform: translateY(-1px); }+.sy-rival:focus-visible { outline: 2px solid var(--sy-accent-2); outline-offset: 2px; }+.sy-roster { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 8px; }+.sy-roster li { display: flex; align-items: center; gap: 10px; background: var(--sy-panel-2); border: 1px solid var(--sy-line); border-radius: 11px; padding: 8px 10px; min-width: 0; }+.sy-roster li div { min-width: 0; }+.sy-roster b { display: block; font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.sy-roster small { font-size: 11.5px; color: var(--sy-faint); }+.sy-roster a { text-decoration: none; }+.sy-roster a:hover b { color: var(--sy-accent-2); }++/* ── skeletons + states ──────────────────────────────────── */+.sy-skel { border-radius: 14px; border: 1px solid var(--sy-line); background: linear-gradient(100deg, var(--sy-panel) 30%, var(--sy-panel-2) 50%, var(--sy-panel) 70%); background-size: 200% 100%; animation: sy-sh 1.3s ease-in-out infinite; }+@keyframes sy-sh { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+.sy-state { text-align: center; padding: 44px 20px; border: 1px dashed var(--sy-line); border-radius: var(--sy-radius); background: var(--sy-panel); }+.sy-state h2, .sy-state h3 { margin: 0 0 8px; font-size: 19px; }+.sy-state p { color: var(--sy-dim); margin: 0 auto 16px; max-width: 52ch; font-size: 14px; line-height: 1.55; }+.sy-toast { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%) translateY(8px); background: var(--sy-text); color: var(--sy-bg); font-size: 13.5px; font-weight: 700; padding: 11px 18px; border-radius: 999px; opacity: 0; pointer-events: none; transition: opacity var(--sy-base), transform var(--sy-base); z-index: 80; max-width: calc(100vw - 32px); text-align: center; }+.sy-toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }++/* ── quests ──────────────────────────────────────────────── */+.qx-top { display: grid; gap: 14px; grid-template-columns: minmax(0, 1fr); margin-bottom: 18px; }+@media (min-width: 820px) { .qx-top { grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr); } }+.qx-level { display: flex; align-items: center; gap: 16px; }+.qx-level-num { width: 64px; height: 64px; border-radius: 18px; display: grid; place-items: center; font-size: 26px; font-weight: 900; color: #fff; background: linear-gradient(135deg, var(--sy-accent), var(--sy-accent-2)); flex: none; }+.qx-bar { height: 10px; border-radius: 999px; background: var(--sy-panel-2); border: 1px solid var(--sy-line); overflow: hidden; margin-top: 8px; }+.qx-bar > i { display: block; height: 100%; width: var(--p, 0%); background: linear-gradient(90deg, var(--sy-accent), var(--sy-accent-2)); border-radius: inherit; transition: width 600ms cubic-bezier(.2, .8, .2, 1); }+.qx-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }+.qx-quest { display: grid; grid-template-columns: 44px minmax(0, 1fr) auto; gap: 14px; align-items: center; background: var(--sy-panel); border: 1px solid var(--sy-line); border-radius: 14px; padding: 14px 16px; transition: border-color var(--sy-fast), background var(--sy-fast); animation: sy-in var(--sy-base) ease both; }+.qx-quest.done { border-color: color-mix(in srgb, var(--sy-green) 45%, var(--sy-line)); background: color-mix(in srgb, var(--sy-green) 6%, var(--sy-panel)); }+.qx-ring { width: 44px; height: 44px; }+.qx-ring circle { fill: none; stroke-width: 5; }+.qx-ring .track { stroke: var(--sy-panel-2); }+.qx-ring .fill { stroke: var(--sy-accent); stroke-linecap: round; transition: stroke-dashoffset 600ms cubic-bezier(.2, .8, .2, 1); }+.qx-quest.done .qx-ring .fill { stroke: var(--sy-green); }+.qx-ring text { font: 800 11px 'Inter', system-ui, sans-serif; fill: var(--sy-text); }+.qx-q-title { font-weight: 800; font-size: 15px; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }+.qx-q-detail { font-size: 13px; color: var(--sy-dim); margin-top: 3px; line-height: 1.5; }+.qx-xp { font-size: 12px; font-weight: 800; color: var(--sy-accent); background: color-mix(in srgb, var(--sy-accent) 14%, transparent); padding: 3px 8px; border-radius: 999px; white-space: nowrap; }+@media (max-width: 620px) {+ .qx-quest { grid-template-columns: 44px minmax(0, 1fr); }+ .qx-quest .sy-btn { grid-column: 1 / -1; width: 100%; }+}+.qx-clear { display: flex; gap: 14px; align-items: center; flex-wrap: wrap; justify-content: space-between; }+.qx-pips { display: flex; gap: 6px; }+.qx-pips i { width: 26px; height: 8px; border-radius: 999px; background: var(--sy-panel-2); border: 1px solid var(--sy-line); transition: background var(--sy-base); }+.qx-pips i.on { background: var(--sy-green); border-color: var(--sy-green); }+.qx-badges { display: flex; flex-wrap: wrap; gap: 8px; }+.qx-badge { display: inline-flex; gap: 8px; align-items: center; padding: 8px 12px; border-radius: 12px; background: var(--sy-panel-2); border: 1px solid var(--sy-line); font-size: 13px; font-weight: 700; }+.qx-badge.locked { opacity: .5; }++@media (prefers-reduced-motion: reduce) {+ .sy-row, .qx-quest, dialog.sy-dialog[open], .sy-skel { animation: none; }+ .sy-btn, .sy-row, .sy-leader, .sy-swatch, .qx-bar > i, .qx-ring .fill { transition: none; }+ .sy-btn:hover, .sy-row:hover, button.sy-leader:hover:not([disabled]) { transform: none; }+}+#syJoinBody p { font-size: 14px; }diff --git a/src/syndicates.js b/src/syndicates.jsnew file mode 100644index 000000000..9eabf5d43--- /dev/null+++ b/src/syndicates.js@@ -0,0 +1,398 @@+// /syndicates: the board of copier teams, and the founding flow.+//+// Reads GET /api/syndicates (the ranked board; while it is empty it also carries+// the leaders a first syndicate could form around) and founds through POST+// /api/syndicates. Founding never subscribes anyone: it lands on the new+// syndicate's page, where the founder joins with their own wallet and caps like+// any other member. Every state is designed: loading, error, empty, populated.++import { apiFetch } from './api.js';+import { esc, fmtSol, fmtPct, tone, avatar, hydrateAvatars, flag, recordLine, toast, currentUser, errorMessage, relTime } from './syndicate-shared.js';++const boardEl = document.getElementById('syBoard');+const countEl = document.getElementById('syCount');+const moreBtn = document.getElementById('syMore');+const sortSeg = document.getElementById('sySort');+const candWrap = document.getElementById('syCandidatesWrap');+const candEl = document.getElementById('syCandidates');+const dialog = document.getElementById('syCreate');+const dialogBody = document.getElementById('syCreateBody');++const PAGE = 24;+const params = new URLSearchParams(location.search);+const state = {+ sort: ['profit', 'members', 'new'].includes(params.get('sort')) ? params.get('sort') : 'profit',+ offset: 0,+ rows: [],+ total: 0,+ colors: ['#7c5cff', '#22d3ee', '#34d399', '#f59e0b', '#fb7185', '#f472b6', '#60a5fa', '#a3e635'],+ maxLeaders: 3,+ candidates: null,+};+let loadSeq = 0;++// ── board ────────────────────────────────────────────────────────────────────++function skeleton() {+ boardEl.setAttribute('aria-busy', 'true');+ boardEl.innerHTML = `<div style="display:grid;gap:10px">${'<div class="sy-skel" style="height:86px"></div>'.repeat(4)}</div>`;+}++function renderError(message) {+ boardEl.setAttribute('aria-busy', 'false');+ boardEl.innerHTML = `+ <div class="sy-state" role="alert">+ <h3>The board did not load</h3>+ <p>${esc(message || 'The syndicates service is unreachable right now.')} Your memberships and copy subscriptions are unaffected.</p>+ <button type="button" class="sy-btn primary" id="syRetry">Try again</button>+ </div>`;+ document.getElementById('syRetry').addEventListener('click', () => load(true));+}++function rowHtml(s) {+ const p = s.performance;+ const since = s.since_founding;+ const leaders = s.leaders.map((l) => avatar(l.name, l.image)).join('');+ const leaderNames = s.leaders.map((l) => esc(l.name)).join(', ');+ return `+ <li>+ <a class="sy-row" href="${esc(s.url)}" style="--flag:${esc(s.color)}" aria-label="${esc(s.name)}, rank ${esc(s.rank)}, ${esc(s.members)} members, group P&L ${esc(fmtSol(p.realized_profit_sol))}">+ <span class="sy-rank">#${esc(s.rank)}</span>+ ${flag(s.name, s.color)}+ <span class="sy-row-main">+ <span class="sy-row-name">${esc(s.name)} ${s.official ? '<span class="sy-badge official" title="Founded by the owner of a leader it follows">Official</span>' : ''}</span>+ ${s.motto ? `<span class="sy-row-motto">${esc(s.motto)}</span>` : ''}+ <span class="sy-row-meta"><span class="sy-ava-stack">${leaders}</span> <span>follows ${leaderNames}</span> <span>· formed ${esc(relTime(s.created_at))}</span></span>+ </span>+ <span class="sy-row-stats">+ <span class="sy-stat"><b>${esc(s.members)}</b><span>members</span></span>+ <span class="sy-stat"><b class="${tone(p.realized_profit_sol)}">${esc(fmtSol(p.realized_profit_sol))}</b><span>group P&L</span></span>+ <span class="sy-stat"><b class="${tone(since.leader_roi_pct)}">${since.leader_closes ? esc(fmtPct(since.leader_roi_pct)) : 'n/a'}</b><span>leaders since formed</span></span>+ </span>+ </a>+ </li>`;+}++function renderBoard() {+ boardEl.setAttribute('aria-busy', 'false');+ if (!state.rows.length) return renderEmpty();+ countEl.textContent = `${state.total} ${state.total === 1 ? 'syndicate' : 'syndicates'}`;+ boardEl.innerHTML = `<ol class="sy-board" aria-label="Syndicates ranked">${state.rows.map(rowHtml).join('')}</ol>`;+ hydrateAvatars(boardEl);+ moreBtn.hidden = state.rows.length >= state.total;+ if (state.candidates) renderCandidates(state.candidates, { compact: true });+}++function renderEmpty() {+ countEl.textContent = '';+ moreBtn.hidden = true;+ const copyable = (state.candidates?.leaders || []).filter((l) => l.copyable);+ boardEl.innerHTML = `+ <div class="sy-hero-empty">+ <p class="sy-kicker">No syndicates yet · be the first flag on the board</p>+ <h2 style="margin:0 0 8px;font-size:clamp(20px,3.6vw,28px);letter-spacing:-.02em">Copying alone is lonely. Start the first team.</h2>+ <p class="sy-muted" style="margin:0;max-width:62ch;line-height:1.55">+ A syndicate turns following a trader into a side you are on. It takes a minute and moves no money:+ </p>+ <ol class="sy-steps">+ <li><b>Raise a flag</b>Name your syndicate, pick its color, and choose one to three verified trader agents to follow.</li>+ <li><b>Ride under your own caps</b>Every member copies from their own wallet with their own per-trade cap, daily budget, and drawdown limit.</li>+ <li><b>Climb the board</b>Your group curve comes from members' real copies. Beat the syndicate one rank above you.</li>+ </ol>+ <div class="sy-actions">+ <button type="button" class="sy-btn primary" data-start>${copyable.length ? `Start the first syndicate` : 'See what a leader needs'}</button>+ <a class="sy-btn" href="/ghost-copy">Ghost-copy a leader first</a>+ </div>+ ${copyable.length ? `<p class="sy-fine" style="margin-top:12px">${copyable.length} ${copyable.length === 1 ? 'leader clears' : 'leaders clear'} the copyable bar right now. Their full records are below, losses included.</p>` : ''}+ </div>`;+ boardEl.querySelector('[data-start]').addEventListener('click', () => (copyable.length ? openCreate() : candWrap.scrollIntoView({ behavior: 'smooth' })));+ if (state.candidates) renderCandidates(state.candidates, { compact: false });+}++function candidateCard(l) {+ return `+ <div class="sy-leader">+ ${avatar(l.name, l.image)}+ <div style="min-width:0">+ <div class="sy-leader-name">${esc(l.name)}</div>+ <div style="margin-top:4px">${l.copyable ? '<span class="sy-badge good">Copyable</span>' : '<span class="sy-badge warn">Not copyable yet</span>'}</div>+ <div class="sy-leader-line">${recordLine(l.record)}</div>+ ${l.copyable ? '' : `<div class="sy-leader-line">Still short: ${esc(l.unmet.join(', '))}</div>`}+ <div class="sy-leader-links">+ <a href="${esc(l.trader_url)}">Full record</a>+ <a href="${esc(l.ghost_url)}">Ghost-copy</a>+ ${l.copyable ? `<a href="#" data-found="${esc(l.agent_id)}">Rally around</a>` : ''}+ </div>+ </div>+ </div>`;+}++function renderCandidates(data, { compact }) {+ const leaders = data?.leaders || [];+ if (!leaders.length) {+ candWrap.hidden = false;+ candEl.innerHTML = `+ <div class="sy-state" style="grid-column:1/-1">+ <h3>No trader has a closed record yet</h3>+ <p>A syndicate forms around an agent with real closed on-chain trades. Deploy one in the Strategy Lab and it can be followed once it clears the bar.</p>+ <a class="sy-btn primary" href="/strategy-lab">Open the Strategy Lab</a>+ </div>`;+ return;+ }+ const shown = compact ? leaders.filter((l) => l.copyable).slice(0, 6) : leaders;+ if (!shown.length) { candWrap.hidden = true; return; }+ candWrap.hidden = false;+ candEl.innerHTML = shown.map(candidateCard).join('');+ hydrateAvatars(candEl);+}++candEl.addEventListener('click', (e) => {+ const a = e.target.closest('[data-found]');+ if (!a) return;+ e.preventDefault();+ openCreate([a.dataset.found]);+});++async function load(reset = true) {+ const seq = ++loadSeq;+ if (reset) { state.offset = 0; state.rows = []; skeleton(); }+ moreBtn.disabled = true;+ try {+ const q = new URLSearchParams({ sort: state.sort, limit: String(PAGE), offset: String(state.offset) });+ if (reset) q.set('include', 'candidates');+ const r = await fetch(`/api/syndicates?${q}`, { headers: { accept: 'application/json' } });+ if (!r.ok) {+ const { message } = await errorMessage(r, `The board answered ${r.status}.`);+ if (seq === loadSeq) renderError(message);+ return;+ }+ const body = await r.json();+ if (seq !== loadSeq) return;+ state.total = Number(body.total) || 0;+ state.rows = reset ? body.syndicates : state.rows.concat(body.syndicates);+ if (Array.isArray(body.colors) && body.colors.length) state.colors = body.colors;+ if (body.max_leaders) state.maxLeaders = body.max_leaders;+ if (body.candidates) state.candidates = body.candidates;+ renderBoard();+ } catch {+ if (seq === loadSeq) renderError('Check your connection.');+ } finally {+ moreBtn.disabled = false;+ }+}++sortSeg.addEventListener('click', (e) => {+ const btn = e.target.closest('button[data-sort]');+ if (!btn || btn.dataset.sort === state.sort) return;+ state.sort = btn.dataset.sort;+ for (const b of sortSeg.querySelectorAll('button')) b.setAttribute('aria-pressed', String(b === btn));+ const u = new URL(location.href);+ if (state.sort === 'profit') u.searchParams.delete('sort'); else u.searchParams.set('sort', state.sort);+ history.replaceState(null, '', u);+ load(true);+});++moreBtn.addEventListener('click', () => {+ state.offset = state.rows.length;+ load(false);+});++// ── founding ─────────────────────────────────────────────────────────────────++const form = { name: '', motto: '', color: null, leaders: new Set() };++async function candidatesForForm() {+ if (state.candidates?.leaders) return state.candidates;+ const r = await fetch('/api/syndicates/leaders?limit=24', { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ state.candidates = await r.json();+ return state.candidates;+}++async function openCreate(preselect = []) {+ for (const id of preselect) form.leaders.add(id);+ if (!form.color) form.color = state.colors[Math.floor(Math.random() * state.colors.length)];+ if (!dialog.open) dialog.showModal();+ dialogBody.innerHTML = `<div style="display:grid;gap:10px"><div class="sy-skel" style="height:44px"></div><div class="sy-skel" style="height:120px"></div></div>`;++ const user = await currentUser();+ if (!user) {+ const next = encodeURIComponent(`/syndicates?start=1${preselect[0] ? `&leader=${preselect[0]}` : ''}`);+ dialogBody.innerHTML = `+ <div class="sy-state" style="border:0;padding:12px 0">+ <h3>Sign in to raise a flag</h3>+ <p>Founding a syndicate is free and moves no money. You need an account so the syndicate has a founder, and so you can join it with your own wallet afterwards.</p>+ <div class="sy-actions" style="justify-content:center">+ <a class="sy-btn primary" href="/login?next=${next}">Sign in</a>+ <a class="sy-btn" href="/register?next=${next}">Create an account</a>+ </div>+ </div>`;+ return;+ }++ let cands;+ try {+ cands = await candidatesForForm();+ } catch {+ dialogBody.innerHTML = `+ <div class="sy-state" style="border:0;padding:12px 0">+ <h3>Could not load the leaders</h3>+ <p>The list of traders a syndicate can follow did not load. Nothing was created.</p>+ <button type="button" class="sy-btn primary" id="syCandRetry">Try again</button>+ </div>`;+ dialogBody.querySelector('#syCandRetry').addEventListener('click', () => openCreate());+ return;+ }+ renderCreateForm(cands.leaders || []);+}++function renderCreateForm(leaders) {+ const copyable = leaders.filter((l) => l.copyable);+ for (const id of [...form.leaders]) if (!copyable.some((l) => l.agent_id === id)) form.leaders.delete(id);++ dialogBody.innerHTML = `+ <form class="sy-form" id="syForm" novalidate>+ <div class="sy-row2">+ <label class="sy-field">+ <span class="sy-label">Name</span>+ <input class="sy-input" id="syName" maxlength="40" minlength="3" required autocomplete="off" placeholder="Night Shift Degens" value="${esc(form.name)}" />+ <span class="sy-hint">3 to 40 characters. It becomes your address: three.ws/syndicates/<span id="sySlug">${esc(slugPreview(form.name) || 'your-name')}</span></span>+ </label>+ <label class="sy-field">+ <span class="sy-label">Motto <span class="sy-faint" style="text-transform:none;letter-spacing:0">(optional)</span></span>+ <input class="sy-input" id="syMotto" maxlength="140" autocomplete="off" placeholder="We ride the 3am tape together." value="${esc(form.motto)}" />+ </label>+ </div>+ <div class="sy-field">+ <span class="sy-label" id="syColorLbl">Flag color</span>+ <div class="sy-swatches" role="radiogroup" aria-labelledby="syColorLbl" id="sySwatches">+ ${state.colors.map((c) => `<button type="button" class="sy-swatch" role="radio" style="--c:${esc(c)}" data-color="${esc(c)}" aria-checked="${c === form.color}" aria-label="Color ${esc(c)}" tabindex="${c === form.color ? '0' : '-1'}"></button>`).join('')}+ </div>+ </div>+ <div class="sy-field">+ <span class="sy-label" id="syLeadLbl">Leaders to follow <span class="sy-faint" style="text-transform:none;letter-spacing:0">(1 to ${state.maxLeaders}, copyable only)</span></span>+ ${copyable.length ? '' : '<div class="sy-note">No trader clears the copyable bar right now, so a syndicate cannot form yet. Every record below shows exactly what is still missing.</div>'}+ <div class="sy-leaders" role="group" aria-labelledby="syLeadLbl" id="syLeaderPick">+ ${leaders.map((l) => `+ <button type="button" class="sy-leader" data-leader="${esc(l.agent_id)}" aria-pressed="${form.leaders.has(l.agent_id)}" ${l.copyable ? '' : 'disabled'}>+ <span class="sy-check" aria-hidden="true">✓</span>+ ${avatar(l.name, l.image)}+ <span style="min-width:0;display:block">+ <span class="sy-leader-name" style="display:block">${esc(l.name)}</span>+ <span class="sy-leader-line" style="display:block">${recordLine(l.record)}</span>+ ${l.copyable ? '' : `<span class="sy-leader-line" style="display:block">Still short: ${esc(l.unmet.join(', '))}</span>`}+ </span>+ </button>`).join('')}+ </div>+ </div>+ <div class="sy-note">Founding moves no money and subscribes nobody. On the next screen you can join with your own wallet and caps, or share the page with followers.</div>+ <div id="syFormErr" class="sy-err" role="alert" hidden></div>+ <div class="sy-actions">+ <button type="submit" class="sy-btn primary" id="sySubmit" ${copyable.length ? '' : 'disabled'}>Raise the flag</button>+ <button type="button" class="sy-btn" id="syCancel">Cancel</button>+ </div>+ </form>`;+ hydrateAvatars(dialogBody);++ const nameEl = dialogBody.querySelector('#syName');+ const slugEl = dialogBody.querySelector('#sySlug');+ nameEl.addEventListener('input', () => { form.name = nameEl.value; slugEl.textContent = slugPreview(form.name) || 'your-name'; });+ dialogBody.querySelector('#syMotto').addEventListener('input', (e) => { form.motto = e.target.value; });+ dialogBody.querySelector('#syCancel').addEventListener('click', () => dialog.close());++ const swatches = dialogBody.querySelector('#sySwatches');+ const pickColor = (btn) => {+ form.color = btn.dataset.color;+ for (const b of swatches.querySelectorAll('.sy-swatch')) {+ const on = b === btn;+ b.setAttribute('aria-checked', String(on));+ b.tabIndex = on ? 0 : -1;+ }+ btn.focus();+ };+ swatches.addEventListener('click', (e) => { const b = e.target.closest('.sy-swatch'); if (b) pickColor(b); });+ swatches.addEventListener('keydown', (e) => {+ const all = [...swatches.querySelectorAll('.sy-swatch')];+ const i = all.findIndex((b) => b.dataset.color === form.color);+ const step = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 0;+ if (!step) return;+ e.preventDefault();+ pickColor(all[(i + step + all.length) % all.length]);+ });++ const pick = dialogBody.querySelector('#syLeaderPick');+ pick.addEventListener('click', (e) => {+ const b = e.target.closest('button[data-leader]');+ if (!b || b.disabled) return;+ const id = b.dataset.leader;+ if (form.leaders.has(id)) form.leaders.delete(id);+ else if (form.leaders.size >= state.maxLeaders) return toast(`A syndicate follows at most ${state.maxLeaders} leaders.`);+ else form.leaders.add(id);+ b.setAttribute('aria-pressed', String(form.leaders.has(id)));+ });++ dialogBody.querySelector('#syForm').addEventListener('submit', submitCreate);+ if (!form.name) nameEl.focus();+}++function slugPreview(name) {+ return String(name || '').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);+}++async function submitCreate(e) {+ e.preventDefault();+ const errEl = dialogBody.querySelector('#syFormErr');+ const btn = dialogBody.querySelector('#sySubmit');+ errEl.hidden = true;+ const name = form.name.trim();+ if (name.length < 3) return showFormErr(errEl, 'Give your syndicate a name of at least 3 characters.');+ if (!form.leaders.size) return showFormErr(errEl, 'Pick at least one leader to follow.');++ btn.disabled = true;+ btn.textContent = 'Raising the flag…';+ try {+ const r = await apiFetch('/api/syndicates', {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify({ name, motto: form.motto.trim() || null, color: form.color, leader_agent_ids: [...form.leaders] }),+ });+ if (!r.ok) {+ const { body, message } = await errorMessage(r, 'Could not create the syndicate.');+ if (body.error === 'leader_not_copyable' && Array.isArray(body.leaders)) {+ errEl.innerHTML = `<strong>${esc(message)}</strong><ul>${body.leaders.map((l) => `<li>${esc(l.name)}: ${esc(l.unmet.join(', '))}</li>`).join('')}</ul>`;+ errEl.hidden = false;+ } else {+ showFormErr(errEl, message);+ }+ btn.disabled = false;+ btn.textContent = 'Raise the flag';+ return;+ }+ const body = await r.json();+ location.href = `${body.syndicate.url}?founded=1`;+ } catch {+ showFormErr(errEl, 'Network error. Nothing was created; try again.');+ btn.disabled = false;+ btn.textContent = 'Raise the flag';+ }+}++function showFormErr(el, msg) {+ el.textContent = msg;+ el.hidden = false;+ el.scrollIntoView({ block: 'nearest', behavior: 'smooth' });+}++document.getElementById('syStart').addEventListener('click', () => openCreate());+document.getElementById('syCreateClose').addEventListener('click', () => dialog.close());+dialog.addEventListener('click', (e) => { if (e.target === dialog) dialog.close(); });++// Deep links: /syndicates?start=1[&leader=<agent id>] opens the founding flow,+// which is where "Start a syndicate around this trader" on /trader/:id lands.+for (const b of sortSeg.querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.sort === state.sort));+load(true).then(() => {+ if (params.get('start') === '1' || params.get('leader')) {+ const leader = params.get('leader');+ openCreate(leader && /^[0-9a-f-]{36}$/i.test(leader) ? [leader] : []);+ }+});diff --git a/src/trader-syndicates.js b/src/trader-syndicates.jsnew file mode 100644index 000000000..b6bf5ac03--- /dev/null+++ b/src/trader-syndicates.js@@ -0,0 +1,46 @@+// Syndicates on a trader profile: the teams that follow this trader, and the+// one-tap way to start one. Reads GET /api/syndicates?leader=<agent id>.+// Mounted by src/trader.js under the copy panel.++import { esc, fmtSol } from './syndicate-shared.js';++// The trader page does not load the syndicates stylesheet, so the flag and the+// P&L tone are drawn inline here.+const flagChip = (name, color) => `<span aria-hidden="true" style="width:32px;height:32px;border-radius:9px;flex:none;display:grid;place-items:center;font-weight:900;color:#0a0a0b;background:${esc(color)}">${esc((String(name || '?').trim()[0] || '?').toUpperCase())}</span>`;+const toneColor = (v) => (Number(v) > 0 ? '#34d399' : Number(v) < 0 ? '#fb7185' : 'inherit');++export async function mountTraderSyndicates(el, { agentId, name, network = 'mainnet' }) {+ if (!el || !agentId) return;+ const startHref = `/syndicates?start=1&leader=${encodeURIComponent(agentId)}`;+ el.innerHTML = `<h2>Syndicates</h2><p class="tp-sk" style="width:60%;height:14px;display:block"></p>`;+ let body;+ try {+ const r = await fetch(`/api/syndicates?leader=${encodeURIComponent(agentId)}&network=${encodeURIComponent(network)}&limit=6`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error(String(r.status));+ body = await r.json();+ } catch {+ el.innerHTML = `+ <h2>Syndicates</h2>+ <p>Couldn't load the teams following ${esc(name || 'this trader')}. <a href="/syndicates">Browse every syndicate</a>.</p>`;+ return;+ }+ const list = body.syndicates || [];+ if (!list.length) {+ el.innerHTML = `+ <h2>Copy ${esc(name || 'this trader')} as a team</h2>+ <p>No syndicate follows ${esc(name || 'this trader')} yet. Start one: name it, pick a flag, and every member copies from their own wallet under their own caps while the team climbs the board together.</p>+ <div class="cp-actions"><a class="lb-btn lb-btn-primary" href="${esc(startHref)}">Start a syndicate</a><a class="lb-btn" href="/syndicates">See the board</a></div>`;+ return;+ }+ el.innerHTML = `+ <h2>Syndicates following ${esc(name || 'this trader')}</h2>+ <ul style="list-style:none;margin:0 0 12px;padding:0;display:grid;gap:8px">+ ${list.map((s) => `+ <li><a href="${esc(s.url)}" style="display:flex;align-items:center;gap:12px;text-decoration:none;color:inherit;padding:10px 12px;border:1px solid var(--stroke, #26262b);border-left:3px solid ${esc(s.color)};border-radius:12px">+ ${flagChip(s.name, s.color)}+ <span style="min-width:0;flex:1"><b style="display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(s.name)}</b><small style="opacity:.7">#${esc(s.rank)} on the board · ${esc(s.members)} ${s.members === 1 ? 'member' : 'members'}</small></span>+ <b style="color:${toneColor(s.performance.realized_profit_sol)}">${esc(fmtSol(s.performance.realized_profit_sol))}</b>+ </a></li>`).join('')}+ </ul>+ <div class="cp-actions"><a class="lb-btn" href="${esc(startHref)}">Start another</a><a class="lb-btn" href="/syndicates">See the board</a></div>`;+}diff --git a/src/trader.js b/src/trader.jsindex fe9a7a1a7..f0513e31e 100644--- a/src/trader.js+++ b/src/trader.js@@ -13,6 +13,7 @@ import {identicon, verifiedBadge, signatureCoin,} from './trader-format.js';import { mountCopyPanel } from './copy-panel.js';+import { mountTraderSyndicates } from './trader-syndicates.js';import { mountPassport, resetPassport } from './trader-passport.js';import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';import { embedSnippet } from './shared/trader-embed.js';@@ -450,6 +451,7 @@ function render(data) {</div><section class="tp-copy" id="tp-copy-panel"></section>+ <section class="tp-copy" id="tp-syndicates" aria-label="Syndicates following this trader"></section>`;wireTabs();@@ -459,6 +461,7 @@ function render(data) {openDeepLinkedReceipt();const panel = document.getElementById('tp-copy-panel');if (panel) mountCopyPanel(panel, { leaderAgentId: a.id, leaderName: a.name, network: ctx.network });+ mountTraderSyndicates(document.getElementById('tp-syndicates'), { agentId: a.id, name: a.name, network: ctx.network });// Sweep the score ring to its real fill, and count the headline score + realized// P&L from their previously-shown real values (so switching the window animatesdiff --git a/vercel.json b/vercel.jsonindex 1e23617c9..d71bb3b09 100644--- a/vercel.json+++ b/vercel.json@@ -1222,6 +1222,18 @@"src": "/ghost-copy/?","dest": "/ghost-copy.html"},+ {+ "src": "/syndicates/?",+ "dest": "/syndicates.html"+ },+ {+ "src": "/syndicates/([^/.]+)/?",+ "dest": "/syndicate.html"+ },+ {+ "src": "/quests/?",+ "dest": "/quests.html"+ },{"src": "/fade/?","dest": "/fade.html"diff --git a/vite.config.js b/vite.config.jsindex a2ec8f32e..5e7bc29af 100644--- a/vite.config.js+++ b/vite.config.js@@ -850,6 +850,9 @@ const appConfig = {'claim-wallet': resolve(__dirname, 'pages/claim-wallet.html'),'meta-allocator': resolve(__dirname, 'pages/meta-allocator.html'),'ghost-copy': resolve(__dirname, 'pages/ghost-copy.html'),+ syndicates: resolve(__dirname, 'pages/syndicates.html'),+ syndicate: resolve(__dirname, 'pages/syndicate.html'),+ quests: resolve(__dirname, 'pages/quests.html'),fade: resolve(__dirname, 'pages/fade.html'),wrapped: resolve(__dirname, 'pages/wrapped.html'),'clip-director': resolve(__dirname, 'pages/clip-director.html'),@@ -2287,6 +2290,10 @@ const appConfig = {// route in prod, so keep it out of the HTML shell here too.else if (!filePath && /^\/trader\/[^/.]+\/?$/.test(path))filePath = resolve(root, 'pages/trader.html');+ // /syndicates/:slug → one syndicate's page. Mirrors vercel.json's+ // `/syndicates/([^/.]+)/?`; the board itself is /syndicates.+ else if (!filePath && /^\/syndicates\/[^/.]+\/?$/.test(path))+ filePath = resolve(root, 'pages/syndicate.html');// /trade-rooms/:agentId → one leader's live trade room. Mirrors// vercel.json's `/trade-rooms/([^/.]+)/?`.else if (!filePath && /^\/trade-rooms\/[^/.]+\/?$/.test(path))