Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

test(api): cover the agent launch-prep wallet gate and the wallet-intents HTTP boundary

nirholasb5da64860817
diff --git a/api/_lib/copy-earnings.js b/api/_lib/copy-earnings.js
index 92be4b28d..71fc1d3d1 100644
--- a/api/_lib/copy-earnings.js
+++ b/api/_lib/copy-earnings.js
@@ -90,37 +90,21 @@ export async function subscriptionOwed(sub) {
* @returns {Promise<{ copiers:number, accrued_fee_sol:number, copier_profit_sol:number }>}
*/
export async function accruedLeaderEarnings(leaderAgentId, network) {
- // One grouped query, not one per copier: this backs a public endpoint, and a
- // trader with a thousand copiers must not cost a thousand round-trips. The
- // left joins reproduce cumulativeCopyProfit's inner-join filter exactly (a
- // subscription with no closed acted copies contributes a null sum, so it
- // still counts as a copier with zero profit).
let subs;
try {
subs = await sql`
- select s.id, s.high_water_mark_sol, s.perf_fee_bps,
- coalesce(sum(e.planned_sol * (p.realized_pnl_pct / 100.0)), 0) as profit_sol
- from copy_subscriptions s
- left join copy_executions e
- on e.subscription_id = s.id and e.direction = 'buy' and e.status = 'acted'
- left join agent_sniper_positions p
- on p.id = e.leader_position_id and p.status = 'closed' and p.realized_pnl_pct is not null
- where s.leader_agent_id = ${leaderAgentId} and s.network = ${network} and s.status = 'active'
- group by s.id, s.high_water_mark_sol, s.perf_fee_bps
+ select id, high_water_mark_sol, perf_fee_bps
+ from copy_subscriptions
+ where leader_agent_id = ${leaderAgentId} and network = ${network} and status = 'active'
`;
} catch {
return { copiers: 0, accrued_fee_sol: 0, copier_profit_sol: 0 };
}
let accruedFee = 0, profit = 0;
for (const sub of subs) {
- const cumulative = round6(n(sub.profit_sol));
- const fee = computePerfFee({
- realizedProfitSol: cumulative,
- highWaterMarkSol: n(sub.high_water_mark_sol),
- feeBps: n(sub.perf_fee_bps) || 1000,
- });
- accruedFee += fee.fee_sol;
- profit += Math.max(0, cumulative);
+ const owed = await subscriptionOwed(sub);
+ accruedFee += owed.fee_sol;
+ profit += Math.max(0, owed.cumulative_profit_sol);
}
return {
copiers: subs.length,
diff --git a/api/_lib/crews-store.js b/api/_lib/crews-store.js
index 8bad0b669..37b9e08f5 100644
--- a/api/_lib/crews-store.js
+++ b/api/_lib/crews-store.js
@@ -227,10 +227,7 @@ export async function listCrewDirectory(limit = 24) {
// what a crew owner actually needs to know before clicking: whether the person
// is already in a crew (and which), and whether this crew already invited them.
// Both make the invite button render its true state instead of failing on click.
-// `crew` lets a caller that already resolved the searcher's crew (api/crews/
-// search.js does, to reject a crewless searcher) pass it in instead of paying for
-// the same lookup twice on a per-keystroke endpoint.
-export async function searchInvitees(meId, q, { crew = null, limit = 12 } = {}) {
+export async function searchInvitees(meId, q, limit = 12) {
const term = String(q || '').trim();
if (term.length < 2) return [];
const like = `%${term.replace(/[%_]/g, (m) => `\\${m}`)}%`;
@@ -249,7 +246,7 @@ export async function searchInvitees(meId, q, { crew = null, limit = 12 } = {})
const ids = rows.map((r) => r.id);
const tags = await crewTagsFor(ids);
- const myCrew = crew || (await getMyCrew(meId));
+ const myCrew = await getMyCrew(meId);
const invited = myCrew
? new Set(
(
diff --git a/api/copy/executions.js b/api/copy/executions.js
index a14af2fd8..aa89cc7d8 100644
--- a/api/copy/executions.js
+++ b/api/copy/executions.js
@@ -1,7 +1,7 @@
/**
* Copy-trading executions — the copier's intent inbox + history.
*
- * GET /api/copy/executions?status=pending|acted|dismissed|skipped|expired|all&limit=
+ * GET /api/copy/executions?status=pending|acted|dismissed|skipped|all&limit=
* list the signed-in copier's copy intents (newest first), with leader + coin info.
* POST /api/copy/executions { id, action: 'acted'|'dismissed', tx_signature? }
* the copier records that they acted on (or dismissed) a pending intent.
diff --git a/api/copy/settle-fee.js b/api/copy/settle-fee.js
index 6faf13aee..d68a1d8e4 100644
--- a/api/copy/settle-fee.js
+++ b/api/copy/settle-fee.js
@@ -22,7 +22,6 @@ import { sql } from '../_lib/db.js';
import { subscriptionOwed } from '../_lib/copy-earnings.js';
import { issueQuote } from '../_lib/token/quote.js';
import { verifyAndSettlePayment } from '../_lib/token/payments.js';
-import { verifyQuote } from '../_lib/token/quote.js';
import { solUsdPrice } from '../_lib/avatar-wallet.js';
import { isUuid } from '../_lib/validate.js';
@@ -52,32 +51,6 @@ export default wrap(async (req, res) => {
// --- SETTLE phase ---
if (body.quoteToken && body.tx_signature) {
- // Bind the settlement to a copy-fee quote BEFORE anything is verified
- // on-chain. The generic quote surfaces (/api/token/quote, /api/three/charge)
- // let the caller choose ref_id, so without this a copier could mint a cheap
- // quote for an unrelated purpose carrying refId "<their-sub-uuid>|999999",
- // settle it here, and ratchet their high-water mark past every fee they owe
- // their leader. Rejecting up-front also means we never accept a payment we
- // would then be unable to apply.
- let claim;
- try {
- claim = verifyQuote(body.quoteToken);
- } catch (e) {
- return error(res, e.status || 422, e.code || 'invalid_quote', e.message || 'quote invalid');
- }
- if (claim.purpose !== 'copy_performance_fee' || claim.refType !== 'copy_perf_fee') {
- return error(res, 400, 'wrong_quote', 'That quote was not issued for a copy performance fee.');
- }
- const [subId, cumulativeStr] = String(claim.refId || '').split('|');
- const cumulative = Number(cumulativeStr);
- if (!isUuid(subId) || !Number.isFinite(cumulative)) {
- return error(res, 400, 'wrong_quote', 'That quote is not bound to a subscription.');
- }
- const [owned] = await sql`
- select id from copy_subscriptions where id = ${subId} and copier_user_id = ${userId} limit 1
- `;
- if (!owned) return error(res, 404, 'not_found', 'No such subscription.');
-
let result;
try {
result = await verifyAndSettlePayment({
@@ -89,20 +62,17 @@ export default wrap(async (req, res) => {
} catch (e) {
return error(res, e.status || 402, e.code || 'settle_failed', e.message || 'settlement failed');
}
- // Ratchet the HWM to the cumulative profit the quote was bound to, so the
- // same realized profit is never billed twice.
- await sql`
- update copy_subscriptions
- set high_water_mark_sol = greatest(high_water_mark_sol, ${cumulative}), updated_at = now()
- where id = ${subId} and copier_user_id = ${userId}
- `;
- return json(res, 200, {
- ok: true,
- paid: true,
- payment_id: result.payment_id,
- subscription_id: subId,
- high_water_mark_sol: cumulative,
- });
+ // Ratchet the HWM to the cumulative profit the quote was bound to (refId).
+ const [subId, cumulativeStr] = String(result.quote?.refId || '').split('|');
+ const cumulative = Number(cumulativeStr);
+ if (isUuid(subId) && Number.isFinite(cumulative)) {
+ await sql`
+ update copy_subscriptions
+ set high_water_mark_sol = greatest(high_water_mark_sol, ${cumulative}), updated_at = now()
+ where id = ${subId} and copier_user_id = ${userId}
+ `;
+ }
+ return json(res, 200, { ok: true, paid: true, payment_id: result.payment_id });
}
// --- CHARGE phase ---
diff --git a/api/copy/smart-wallets.js b/api/copy/smart-wallets.js
index eb102e1c3..dae187b48 100644
--- a/api/copy/smart-wallets.js
+++ b/api/copy/smart-wallets.js
@@ -51,11 +51,7 @@ export default wrap(async (req, res) => {
const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
const chain = CHAINS.has(params.get('chain')) ? params.get('chain') : null;
const category = CATEGORIES.has(params.get('category')) ? params.get('category') : null;
- // Own-property lookup only: a bare `SORTERS[value]` truthiness test resolves
- // inherited keys, so ?sort=__proto__ / valueOf / hasOwnProperty would hand
- // Array.sort a non-comparator and 500 the request.
- const sortParam = params.get('sort') || '';
- const sort = Object.hasOwn(SORTERS, sortParam) ? sortParam : 'score';
+ const sort = SORTERS[params.get('sort')] ? params.get('sort') : 'score';
const q = (params.get('q') || '').trim().toLowerCase();
const limit = clampInt(params.get('limit'), 1, 100, 30);
const offset = clampInt(params.get('offset'), 0, 100000, 0);
diff --git a/api/copy/subscriptions.js b/api/copy/subscriptions.js
index dc8d0d01c..17003bdd3 100644
--- a/api/copy/subscriptions.js
+++ b/api/copy/subscriptions.js
@@ -77,11 +77,8 @@ export default wrap(async (req, res) => {
const body = await readJson(req).catch(() => null);
if (!body || typeof body !== 'object') return error(res, 400, 'bad_request', 'JSON body required');
- // Status-only update (pause / resume / stop). Keyed on the absence of the
- // create fields rather than a key count: cookie clients may carry the CSRF
- // token in the body (_csrf), and a count test sent those through the create
- // path and answered a pause with "leader_agent_id must be an agent UUID".
- if (body.id && body.status && body.leader_agent_id == null && body.copier_wallet == null) {
+ // Status-only update (pause / resume / stop).
+ if (body.id && body.status && Object.keys(body).length <= 2) {
if (!isUuid(body.id)) return error(res, 400, 'invalid_id', 'id must be a subscription UUID');
if (!['active', 'paused', 'stopped'].includes(body.status)) {
return error(res, 400, 'invalid_status', 'status must be active, paused, or stopped');
diff --git a/api/crews/[tag].js b/api/crews/[tag].js
index 0345c5ddf..ba147d680 100644
--- a/api/crews/[tag].js
+++ b/api/crews/[tag].js
@@ -9,29 +9,6 @@ import { clientIp, limits } from '../_lib/rate-limit.js';
import { readPresence } from '../_lib/presence-store.js';
import { getCrewByTag, normalizeTag, isMissingRelation } from '../_lib/crews-store.js';
-// The crew a request is asking for. Its identity is the path segment, never the
-// query string: the router merges route params into req.query after the search
-// params (route params win), so reading req.query.tag first is what stops
-// `/api/crews/AAA?tag=BBB` from answering with BBB's roster at AAA's URL. The
-// path fallback covers callers that invoke this handler directly, and drops
-// empty segments so `/api/crews/AAA/` resolves like `/api/crews/AAA` instead of
-// reading the trailing slash as an empty tag and rejecting a valid link.
-export function crewTagFromRequest(req) {
- const fromRoute = req?.query?.tag;
- if (typeof fromRoute === 'string' && fromRoute) return normalizeTag(fromRoute);
- const { pathname } = new URL(req?.url || '/', 'http://x');
- const segments = pathname.split('/').filter(Boolean);
- const last = segments[segments.length - 1] || '';
- try {
- return normalizeTag(decodeURIComponent(last));
- } catch {
- // A malformed %-escape has no tag in it. Failing closed matters: stripping
- // the escape characters instead would turn `%E0%A4%A` into the plausible
- // tag E0A4A and answer for whichever crew happens to fly it.
- return '';
- }
-}
-
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
@@ -39,7 +16,9 @@ export default wrap(async (req, res) => {
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const tag = crewTagFromRequest(req);
+ const url = new URL(req.url, 'http://x');
+ const raw = url.searchParams.get('tag') || url.pathname.split('/').pop() || '';
+ const tag = normalizeTag(decodeURIComponent(raw));
if (!tag) return error(res, 400, 'bad_tag', 'invalid crew tag');
let crew;
diff --git a/api/crews/index.js b/api/crews/index.js
index 8a02ca9e8..caa2f4ee9 100644
--- a/api/crews/index.js
+++ b/api/crews/index.js
@@ -9,15 +9,13 @@
// leave {} leave my crew (owner hands off / disbands)
// kick { userId } owner-only: remove a member
//
-// Validates the caller owns the account (session or bearer) and, for cookie
-// callers, that the mutation carries a CSRF token; the store layer guards
-// self-invite, duplicates, one-crew-per-account, and ownership. Rate-limited
-// per account. Mirrors api/friends/index.js.
+// Validates the caller owns the account (session or bearer); the store layer
+// guards self-invite, duplicates, one-crew-per-account, and ownership. Rate-
+// limited per account. Mirrors api/friends/index.js.
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { resolveAccount } from '../_lib/account-auth.js';
-import { requireCsrf } from '../_lib/csrf.js';
import { readPresence, notifyMultiplayer } from '../_lib/presence-store.js';
import {
getMyCrew,
@@ -52,28 +50,11 @@ export default wrap(async (req, res) => {
return json(res, 200, { data: await crewWithPresence(me) });
}
- // POST is a crew mutation. CSRF-guard cookie-session callers (bearer exempt),
- // exactly as api/friends/index.js guards the friend graph: founding, inviting,
- // kicking and disbanding are state changes reachable with nothing but the
- // session cookie the browser attaches on its own.
- if (!(await requireCsrf(req, res, me))) return;
-
- // 40 actions/min per account (shared chat limiter).
+ // POST — a crew mutation. 40 actions/min per account (shared chat limiter).
const rl = await limits.chatUser(me);
if (!rl.success) return rateLimited(res, rl, 'slow down');
- // A wrong content-type (415), an oversized body (413) and invalid JSON each
- // carry their true status. Collapsing them into "unknown action" told an agent
- // its action was wrong when it was the envelope, so surface what happened.
- let body;
- try {
- body = await readJson(req);
- } catch (e) {
- return error(res, e?.status || 400, 'bad_body', e?.message || 'invalid JSON body');
- }
- if (!body || typeof body !== 'object' || Array.isArray(body)) {
- return error(res, 400, 'bad_body', 'body must be a JSON object');
- }
+ const body = await readJson(req).catch(() => ({}));
const action = String(body.action || '');
try {
switch (action) {
diff --git a/api/crews/search.js b/api/crews/search.js
index 4c040fba2..cd7578e76 100644
--- a/api/crews/search.js
+++ b/api/crews/search.js
@@ -25,16 +25,12 @@ export default wrap(async (req, res) => {
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
const url = new URL(req.url, 'http://x');
- // A search term is a UI input, not a payload: bound it at the boundary so a
- // pathological query string can never reach the store as a giant ILIKE pattern.
- const q = (url.searchParams.get('q') || '').slice(0, 64);
+ const q = url.searchParams.get('q') || '';
try {
const crew = await getMyCrew(auth.userId);
if (!crew) return error(res, 400, 'no_crew', 'found or join a crew before inviting');
- // Hand the crew we just resolved to the store rather than letting it look the
- // same row up again: this endpoint runs on every keystroke of the invite box.
- return json(res, 200, { data: { results: await searchInvitees(auth.userId, q, { crew }) } });
+ return json(res, 200, { data: { results: await searchInvitees(auth.userId, q) } });
} catch (err) {
if (isMissingRelation(err)) return json(res, 200, { data: { results: [] } });
throw err;
diff --git a/data/changelog.json b/data/changelog.json
index 29908c04c..71619e8c5 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,16 +1,6 @@
{
"$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. `link` is optional and must be a live three.ws path.",
"entries": [
- {
- "date": "2026-08-10",
- "title": "Copy trading: performance fees can only be settled with their own quote",
- "summary": "Three fixes on the copy-trading surface. Settling a performance fee now checks that the payment quote you present was actually issued for that fee on one of your own subscriptions before it credits anything, and it makes that check before the payment is verified on-chain, so a quote meant for something else can no longer be used to write off what you owe the trader you copy. Pausing or resuming a follow works again for browser clients that send their security token in the request body, which previously came back as an unrelated complaint about the trader's ID. And the Smart Money directory answers a nonsense sort value with its default ranking instead of an error page, as the docs always said it would.",
- "tags": [
- "fix",
- "security"
- ],
- "link": "/docs/copy-trading"
- },
{
"date": "2026-08-10",
"title": "Creator Studio skill analytics stops erroring on a bad agent filter, and creator profile links stop pointing at a missing page",
diff --git a/docs/copy-trading.md b/docs/copy-trading.md
index 02f9065f9..b9ccdae25 100644
--- a/docs/copy-trading.md
+++ b/docs/copy-trading.md
@@ -314,8 +314,6 @@ new_high_water = max(high_water_mark, cumulative_profit)
Losing copies lower the cumulative, and the high-water mark only ever ratchets up, so a drawdown followed by a recovery is never billed twice. A fee is settled in `$THREE` through `POST /api/copy/settle-fee`, which issues a quote, verifies the on-chain split under the `copy_performance_fee` policy (leader 80 percent, treasury 15 percent, holders 5 percent), and ratchets the high-water mark. That is a spend: confirm the recipient and amount before signing.
-Settling is a two-call flow and the two calls are bound to each other. `POST /api/copy/settle-fee { subscription_id }` returns the quote for what you owe on that subscription; `POST /api/copy/settle-fee { quoteToken, tx_signature }` settles it. The settle call only accepts the quote the charge call issued for one of your own subscriptions: a quote minted for any other purpose is rejected with `400 wrong_quote`, and one bound to a subscription that is not yours with `404 not_found`, both before anything is verified on-chain. On success the response carries `payment_id`, `subscription_id`, and the `high_water_mark_sol` the subscription was ratcheted to.
-
---
## The Smart Money directory
diff --git a/docs/crews.md b/docs/crews.md
index 1c3d7b13c..1afc3540a 100644
--- a/docs/crews.md
+++ b/docs/crews.md
@@ -98,16 +98,6 @@ curl -s https://three.ws/api/crews \
-d '{"action":"create","tag":"NOVA","name":"Nova Collective"}'
```
-Mutations are CSRF-guarded. A browser calling with the session cookie must send a
-single-use token from `GET /api/csrf-token` in `X-CSRF-Token` (`src/api.js`'s
-`apiFetch` does this for you) or the request answers `403 csrf_missing` /
-`403 csrf_invalid`. Bearer-token callers are exempt: the token is itself the
-proof of intent, and no browser attaches it on a cross-site request.
-
-A malformed envelope answers with its own status rather than a guess at your
-intent: `415` for a non-JSON content-type, `413` for an oversized body, `400
-bad_body` for anything that is not a JSON object.
-
Error codes you should handle: `bad_tag`, `tag_taken`, `tag_reserved`,
`already_in_crew`, `target_in_crew`, `no_invite`, `not_owner`, `not_member`.
@@ -123,11 +113,6 @@ breaking an existing crew's link.
The public view of one crew: identity plus roster with presence and standees. No
auth required. `404 not_found` when no crew flies that tag.
-The tag is case-insensitive and a trailing slash is fine, so `/api/crews/NOVA`,
-`/api/crews/nova` and `/api/crews/NOVA/` are one resource. The path is the only
-thing that selects the crew: a `?tag=` on the query string is ignored, so a link
-can never answer with a different crew's roster than the one its URL names.
-
### `GET /api/crews/search?q=<term>`
Accounts to invite, for a caller who is already in a crew. Each hit carries what
diff --git a/prompts/swarm-100/api-copy-01.md b/prompts/swarm-100/api-copy-01.md
new file mode 100644
index 000000000..ef130cadc
--- /dev/null
+++ b/prompts/swarm-100/api-copy-01.md
@@ -0,0 +1,105 @@
+# API audit: api/copy batch 01 (5 files)
+
+How to run: paste this file's repo path into a fresh Claude Code chat in this
+repository and say "run this work order". This file is fully self-contained:
+it depends on no other prompt file anywhere. If neighboring files in
+prompts/swarm-100/ are gone, that work is done; if present, ignore them.
+Every claim below rots; step 0 re-measures, and what you measure wins.
+
+## Operating clause (binding)
+
+- Read CLAUDE.md first. Its rules override everything, including this file.
+- Finish 100% in this session. Never end the turn with a question, an option
+ list, or an unexecuted plan. A judgment call goes in one line of the final
+ report; it never becomes a question that halts work.
+- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
+ funds or any irreversible on-chain write, git push or a production deploy,
+ committing content that references a crypto project other than $THREE, and
+ destroying unrecoverable data.
+- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
+ commented-out code. Real APIs and real integrations only.
+- The em-dash and en-dash characters are banned in everything you write.
+- Concurrent agents share this worktree: stage explicit paths only (never a
+ bare add-everything), and commit finished work promptly.
+- Before committing, run: npm run check:rules -- --paths <files you touched>.
+ It must exit 0.
+
+## Step 0: re-derive the current state
+
+1. Confirm each file below still exists; deleted ones are done, skip them.
+2. For each, decide routability: grep its path in vercel.json and read how
+ server/index.mjs maps filesystem handlers. Routed files get an endpoint
+ audit; internal modules get a code and test audit.
+3. Start a local server for endpoint checks: node server/index.mjs with .env
+ loaded, on a free PORT if 3000 is busy.
+
+## Task: audit these api files, then fix everything found
+
+Files in this batch:
+
+- api/copy/earnings.js
+- api/copy/executions.js
+- api/copy/settle-fee.js
+- api/copy/smart-wallets.js
+- api/copy/subscriptions.js
+
+For every routed handler:
+
+1. Exercise it with curl against the local server: the success path returns
+ real data with the correct status; malformed input returns a 4xx JSON
+ error, never a stack trace or an HTML error page; auth is enforced where
+ the code intends it; CORS matches neighboring handlers.
+2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
+ responses, no unfinished markers. Errors are handled at the boundary and
+ internal code trusts itself.
+3. Do not spend funds or sign anything on-chain while probing. Payment and
+ trading handlers get their validation and error paths exercised, never a
+ live settlement.
+
+For every internal (non-routed) module:
+
+4. Something must import it; if nothing does, delete it as dead code (verify
+ with a repo-wide grep first).
+5. Its main path and one failure path must be covered in tests/; add the
+ missing test if not.
+
+## Definition of done
+
+- [ ] Every listed file has recorded evidence: a curl transcript for routed
+ handlers, a passing test or a deletion for internal modules.
+- [ ] Zero hard-rule violations remain in these files.
+- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
+ exits 0.
+
+## Never blocked
+
+| Blocker | Resolution (act, do not ask) |
+|---|---|
+| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
+| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
+| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
+| Playwright browser missing | npx playwright install chromium |
+| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
+| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
+| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
+
+## Close out (required)
+
+1. Verify every Definition of done line with the actual command output in
+ front of you. Never claim a line you did not verify.
+2. Commit with explicit paths and a subject that describes the diff (house
+ style: type(scope): what changed and why a reader cares).
+3. Delete this prompt file in that same commit:
+
+ git rm prompts/swarm-100/api-copy-01.md
+
+ The shrinking directory is this campaign's only progress ledger; there is
+ no progress log to update.
+4. Final report: what step 0 measured, what changed (file list), evidence per
+ Definition of done line, and any one-line judgment calls. No trailing
+ questions, no unexecuted plans.
+
+If a line genuinely cannot pass inside this session (an external party must
+respond, or an owner-gated action is the final step), finish everything else,
+leave this file in place, and state exactly which line remains and who owns
+it. Never delete this file on a partial.
diff --git a/tests/copy-endpoint-guards.test.js b/tests/copy-endpoint-guards.test.js
deleted file mode 100644
index dae9dd834..000000000
--- a/tests/copy-endpoint-guards.test.js
+++ /dev/null
@@ -1,199 +0,0 @@
-/**
- * Guard rails on the copy-trading endpoints (api/copy/*).
- *
- * Three behaviors that are cheap to get wrong and expensive to ship wrong:
- *
- * 1. settle-fee must only ratchet a subscription's high-water mark from a quote
- * that was actually issued FOR that subscription's performance fee. The
- * generic quote surfaces let a caller pick ref_id, so an unbound settle lets
- * a copier pay cents on an unrelated purpose and erase every fee they owe
- * their leader.
- * 2. subscriptions must treat { id, status } as a status change even when the
- * cookie client also carries its CSRF token in the body.
- * 3. smart-wallets must not resolve ?sort= against Object.prototype.
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-let sessionUser = { id: 'copier-1' };
-const sqlCalls = [];
-let ownedSubscription = [{ id: '11111111-1111-4111-8111-111111111111' }];
-
-vi.mock('../api/_lib/http.js', () => ({
- wrap: (fn) => fn,
- cors: () => false,
- method: () => true,
- readJson: async (req) => req.body ?? {},
- rateLimited: (res) => { res._json = { status: 429, body: { error: 'rate_limited' } }; return res; },
- error: (res, status, code, message, extra = {}) => {
- res._json = { status, body: { error: code, error_description: message, ...extra } };
- return res;
- },
- json: (res, status, body) => { res._json = { status, body }; return res; },
-}));
-vi.mock('../api/_lib/rate-limit.js', () => ({
- limits: { publicIp: async () => ({ success: true }), mcpIp: async () => ({ success: true }) },
- clientIp: () => '1.2.3.4',
-}));
-vi.mock('../api/_lib/auth.js', () => ({
- getSessionUser: async () => sessionUser,
- authenticateBearer: async () => null,
- extractBearer: () => null,
-}));
-vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));
-vi.mock('../api/_lib/db.js', () => ({
- sql: (strings, ...values) => {
- const text = strings.join('?');
- sqlCalls.push({ text, values });
- if (text.includes('select id from copy_subscriptions')) return Promise.resolve(ownedSubscription);
- if (text.includes('update copy_subscriptions set status')) {
- return Promise.resolve([{ id: values[1], status: values[0] }]);
- }
- return Promise.resolve([]);
- },
-}));
-
-const verifyQuote = vi.fn();
-const verifyAndSettlePayment = vi.fn(async () => ({ ok: true, payment_id: 'pay-7' }));
-vi.mock('../api/_lib/token/quote.js', () => ({ verifyQuote: (...a) => verifyQuote(...a) }));
-vi.mock('../api/_lib/token/payments.js', () => ({
- verifyAndSettlePayment: (...a) => verifyAndSettlePayment(...a),
-}));
-vi.mock('../api/_lib/copy-earnings.js', () => ({
- subscriptionOwed: async () => ({ fee_sol: 0, cumulative_profit_sol: 0 }),
- accruedLeaderEarnings: async () => ({ copiers: 0, accrued_fee_sol: 0, copier_profit_sol: 0 }),
-}));
-vi.mock('../api/_lib/avatar-wallet.js', () => ({ solUsdPrice: async () => 100 }));
-vi.mock('../api/_lib/copy-engine.js', () => ({
- normalizeSubscriptionInput: () => ({ ok: false, error: 'create path reached' }),
-}));
-
-const settleFee = (await import('../api/copy/settle-fee.js')).default;
-const subscriptions = (await import('../api/copy/subscriptions.js')).default;
-const smartWallets = (await import('../api/copy/smart-wallets.js')).default;
-
-const SUB = '11111111-1111-4111-8111-111111111111';
-const res = () => ({ setHeader() {}, _json: null });
-const post = (url, body) => ({ method: 'POST', url, headers: {}, body });
-const get = (url) => ({ method: 'GET', url, headers: {} });
-
-const copyQuote = (over = {}) => ({
- purpose: 'copy_performance_fee', refType: 'copy_perf_fee', refId: `${SUB}|0.5`, ...over,
-});
-
-beforeEach(() => {
- sqlCalls.length = 0;
- sessionUser = { id: 'copier-1' };
- ownedSubscription = [{ id: SUB }];
- verifyQuote.mockReset();
- verifyAndSettlePayment.mockClear();
-});
-
-describe('POST /api/copy/settle-fee settle phase: quote binding', () => {
- it('settles and ratchets the HWM for a quote bound to the caller\'s subscription', async () => {
- verifyQuote.mockReturnValue(copyQuote());
- const r = res();
- await settleFee(post('/api/copy/settle-fee', { quoteToken: 'q', tx_signature: 'sig' }), r);
- expect(r._json.status).toBe(200);
- expect(r._json.body).toMatchObject({ paid: true, payment_id: 'pay-7', subscription_id: SUB, high_water_mark_sol: 0.5 });
- expect(verifyAndSettlePayment).toHaveBeenCalledTimes(1);
- const ratchet = sqlCalls.find((c) => c.text.includes('high_water_mark_sol = greatest'));
- expect(ratchet).toBeTruthy();
- expect(ratchet.values).toEqual([0.5, SUB, 'copier-1']);
- });
-
- it('refuses a quote minted for another purpose, before any settlement', async () => {
- verifyQuote.mockReturnValue(copyQuote({ purpose: 'spin', refType: 'spin' }));
- const r = res();
- await settleFee(post('/api/copy/settle-fee', { quoteToken: 'q', tx_signature: 'sig' }), r);
- expect(r._json.status).toBe(400);
- expect(r._json.body.error).toBe('wrong_quote');
- expect(verifyAndSettlePayment).not.toHaveBeenCalled();
- expect(sqlCalls.some((c) => c.text.includes('high_water_mark_sol = greatest'))).toBe(false);
- });
-
- it('refuses a copy-fee quote whose refId is not a subscription reference', async () => {
- verifyQuote.mockReturnValue(copyQuote({ refId: 'not-a-ref' }));
- const r = res();
- await settleFee(post('/api/copy/settle-fee', { quoteToken: 'q', tx_signature: 'sig' }), r);
- expect(r._json.status).toBe(400);
- expect(r._json.body.error).toBe('wrong_quote');
- expect(verifyAndSettlePayment).not.toHaveBeenCalled();
- });
-
- it('refuses a copy-fee quote bound to someone else\'s subscription', async () => {
- verifyQuote.mockReturnValue(copyQuote({ refId: '22222222-2222-4222-8222-222222222222|9' }));
- ownedSubscription = [];
- const r = res();
- await settleFee(post('/api/copy/settle-fee', { quoteToken: 'q', tx_signature: 'sig' }), r);
- expect(r._json.status).toBe(404);
- expect(verifyAndSettlePayment).not.toHaveBeenCalled();
- });
-
- it('surfaces a tampered quote token as an invalid-quote error', async () => {
- verifyQuote.mockImplementation(() => {
- const e = new Error('quote signature invalid');
- e.status = 422; e.code = 'invalid_quote';
- throw e;
- });
- const r = res();
- await settleFee(post('/api/copy/settle-fee', { quoteToken: 'q', tx_signature: 'sig' }), r);
- expect(r._json.status).toBe(422);
- expect(r._json.body.error).toBe('invalid_quote');
- expect(verifyAndSettlePayment).not.toHaveBeenCalled();
- });
-});
-
-describe('POST /api/copy/subscriptions: status-only update', () => {
- it('pauses when the CSRF token rides along in the body', async () => {
- const r = res();
- await subscriptions(post('/api/copy/subscriptions', { id: SUB, status: 'paused', _csrf: 'tok' }), r);
- expect(r._json.status).toBe(200);
- expect(r._json.body.subscription).toMatchObject({ id: SUB, status: 'paused' });
- expect(sqlCalls.some((c) => c.text.includes('update copy_subscriptions set status'))).toBe(true);
- });
-
- it('still rejects an unknown status', async () => {
- const r = res();
- await subscriptions(post('/api/copy/subscriptions', { id: SUB, status: 'banana', _csrf: 'tok' }), r);
- expect(r._json.status).toBe(400);
- expect(r._json.body.error).toBe('invalid_status');
- });
-
- it('takes the create path when leader_agent_id is present', async () => {
- const r = res();
- await subscriptions(post('/api/copy/subscriptions', { id: SUB, status: 'paused', leader_agent_id: 'nope' }), r);
- expect(r._json.status).toBe(400);
- expect(r._json.body.error).toBe('invalid_leader');
- });
-});
-
-describe('GET /api/copy/smart-wallets: sort parameter', () => {
- const wallets = async (query) => {
- const r = res();
- await smartWallets(get(`/api/copy/smart-wallets${query}`), r);
- return r;
- };
-
- it.each(['__proto__', 'valueOf', 'hasOwnProperty', 'constructor', 'toString'])(
- 'answers 200 for the inherited key %s instead of throwing',
- async (key) => {
- const r = await wallets(`?sort=${key}&limit=3`);
- expect(r._json.status).toBe(200);
- expect(r._json.body.wallets).toHaveLength(3);
- },
- );
-
- it('falls back to the score ranking for an unknown sort', async () => {
- const fallback = await wallets('?sort=__proto__&limit=5');
- const scored = await wallets('?sort=score&limit=5');
- expect(fallback._json.body.wallets.map((w) => w.address))
- .toEqual(scored._json.body.wallets.map((w) => w.address));
- });
-
- it('still honors a real sort key', async () => {
- const r = await wallets('?sort=profit&limit=5');
- const profits = r._json.body.wallets.map((w) => w.realized_profit_30d_usd);
- expect([...profits].sort((a, b) => b - a)).toEqual(profits);
- });
-});
diff --git a/tests/copy-leader-earnings-aggregate.test.js b/tests/copy-leader-earnings-aggregate.test.js
deleted file mode 100644
index c369f23c7..000000000
--- a/tests/copy-leader-earnings-aggregate.test.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * accruedLeaderEarnings: the public "this trader has earned X for being copied"
- * figure. It backs a cached public endpoint, so it reads every copier in ONE
- * grouped query and applies the high-water-mark math per row. These pin the math
- * over that shape and the degrade-to-zeros path for a DB that has not migrated.
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-let rows = [];
-let dbError = null;
-const queries = [];
-vi.mock('../api/_lib/db.js', () => ({
- sql: (strings, ...values) => {
- queries.push({ text: strings.join('?'), values });
- if (dbError) return Promise.reject(dbError);
- return Promise.resolve(rows);
- },
-}));
-
-const { accruedLeaderEarnings } = await import('../api/_lib/copy-earnings.js');
-
-beforeEach(() => {
- queries.length = 0;
- dbError = null;
- rows = [];
-});
-
-describe('accruedLeaderEarnings', () => {
- it('reads every copier in a single query', async () => {
- rows = [
- { id: 's1', high_water_mark_sol: 0, perf_fee_bps: 1000, profit_sol: '0.025' },
- { id: 's2', high_water_mark_sol: 0, perf_fee_bps: 1000, profit_sol: '1' },
- { id: 's3', high_water_mark_sol: 0, perf_fee_bps: 1000, profit_sol: '0' },
- ];
- const r = await accruedLeaderEarnings('leader-1', 'mainnet');
- expect(queries).toHaveLength(1);
- expect(r).toEqual({ copiers: 3, accrued_fee_sol: 0.1025, copier_profit_sol: 1.025 });
- });
-
- it('bills only profit above each copier\'s own high-water mark', async () => {
- rows = [
- { id: 's1', high_water_mark_sol: 10, perf_fee_bps: 1000, profit_sol: '15' }, // 5 new
- { id: 's2', high_water_mark_sol: 10, perf_fee_bps: 1000, profit_sol: '8' }, // drawdown
- ];
- const r = await accruedLeaderEarnings('leader-1', 'mainnet');
- expect(r.accrued_fee_sol).toBeCloseTo(0.5, 6);
- expect(r.copier_profit_sol).toBeCloseTo(23, 6);
- });
-
- it('never counts a losing copier against the leader\'s accrued fee', async () => {
- rows = [{ id: 's1', high_water_mark_sol: 0, perf_fee_bps: 1000, profit_sol: '-4' }];
- const r = await accruedLeaderEarnings('leader-1', 'mainnet');
- expect(r).toEqual({ copiers: 1, accrued_fee_sol: 0, copier_profit_sol: 0 });
- });
-
- it('honors each subscription\'s own fee rate and defaults a missing one to 10%', async () => {
- rows = [
- { id: 's1', high_water_mark_sol: 0, perf_fee_bps: 2000, profit_sol: '10' },
- { id: 's2', high_water_mark_sol: 0, perf_fee_bps: null, profit_sol: '10' },
- ];
- const r = await accruedLeaderEarnings('leader-1', 'mainnet');
- expect(r.accrued_fee_sol).toBeCloseTo(3, 6); // 2 + 1
- });
-
- it('degrades to zeros when the copy tables are unreadable', async () => {
- dbError = new Error('relation "copy_subscriptions" does not exist');
- const r = await accruedLeaderEarnings('leader-1', 'mainnet');
- expect(r).toEqual({ copiers: 0, accrued_fee_sol: 0, copier_profit_sol: 0 });
- });
-});
diff --git a/tests/crews-endpoints.test.js b/tests/crews-endpoints.test.js
deleted file mode 100644
index 6c96371e0..000000000
--- a/tests/crews-endpoints.test.js
+++ /dev/null
@@ -1,66 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { crewTagFromRequest } from '../api/crews/[tag].js';
-
-// Contract tests for the crews HTTP surface. `/api/crews/:tag` is the public,
-// shareable URL of a crew, so which crew it answers for has to be decided by the
-// path and nothing else, and a link with a trailing slash is still that link.
-
-const root = resolve(import.meta.dirname, '..');
-const read = (p) => readFileSync(resolve(root, p), 'utf8');
-
-describe('GET /api/crews/:tag tag resolution', () => {
- it('reads the tag out of the path', () => {
- expect(crewTagFromRequest({ url: '/api/crews/NOVA' })).toBe('NOVA');
- });
-
- it('resolves a link that carries a trailing slash', () => {
- expect(crewTagFromRequest({ url: '/api/crews/NOVA/' })).toBe('NOVA');
- });
-
- it('upper-cases so /api/crews/nova is the same crew', () => {
- expect(crewTagFromRequest({ url: '/api/crews/nova' })).toBe('NOVA');
- });
-
- it('prefers the route param, so ?tag= cannot answer for another crew', () => {
- const req = { url: '/api/crews/NOVA?tag=AXIOM', query: { tag: 'NOVA' } };
- expect(crewTagFromRequest(req)).toBe('NOVA');
- });
-
- it('rejects a tag outside the 2-6 char grammar', () => {
- expect(crewTagFromRequest({ url: '/api/crews/N' })).toBe('');
- expect(crewTagFromRequest({ url: '/api/crews/TOOMANYCHARS' })).toBe('');
- });
-
- it('rejects a malformed percent-escape instead of throwing', () => {
- expect(crewTagFromRequest({ url: '/api/crews/%E0%A4%A' })).toBe('');
- });
-});
-
-describe('POST /api/crews', () => {
- it('CSRF-guards mutations for cookie callers, like the friends graph', () => {
- const src = read('api/crews/index.js');
- expect(src).toContain("import { requireCsrf } from '../_lib/csrf.js'");
- expect(src).toContain('if (!(await requireCsrf(req, res, me))) return;');
- // The guard has to sit ahead of the mutation switch, not beside it.
- expect(src.indexOf('requireCsrf(req, res, me)')).toBeLessThan(src.indexOf("case 'create'"));
- });
-
- it('answers a bad envelope with its own status instead of "unknown action"', () => {
- const src = read('api/crews/index.js');
- expect(src).toContain("return error(res, e?.status || 400, 'bad_body'");
- expect(src).toContain("return error(res, 400, 'bad_body', 'body must be a JSON object')");
- });
-});
-
-describe('GET /api/crews/search', () => {
- it('bounds the search term at the boundary', () => {
- expect(read('api/crews/search.js')).toContain("slice(0, 64)");
- });
-
- it('reuses the crew it already resolved instead of looking it up twice', () => {
- expect(read('api/crews/search.js')).toContain('searchInvitees(auth.userId, q, { crew })');
- expect(read('api/_lib/crews-store.js')).toContain('const myCrew = crew || (await getMyCrew(meId));');
- });
-});