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.

fix(copy): settle a performance fee only against the quote issued for that subscription

nirholasbf436eb306da
diff --git a/api/_lib/copy-earnings.js b/api/_lib/copy-earnings.js
index 71fc1d3d1..92be4b28d 100644
--- a/api/_lib/copy-earnings.js
+++ b/api/_lib/copy-earnings.js
@@ -90,21 +90,37 @@ 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 id, high_water_mark_sol, perf_fee_bps
- from copy_subscriptions
- where leader_agent_id = ${leaderAgentId} and network = ${network} and status = 'active'
+ 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
`;
} catch {
return { copiers: 0, accrued_fee_sol: 0, copier_profit_sol: 0 };
}
let accruedFee = 0, profit = 0;
for (const sub of subs) {
- const owed = await subscriptionOwed(sub);
- accruedFee += owed.fee_sol;
- profit += Math.max(0, owed.cumulative_profit_sol);
+ 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);
}
return {
copiers: subs.length,
diff --git a/api/agora/[action].js b/api/agora/[action].js
index 5a5be0d6b..44eb3d570 100644
--- a/api/agora/[action].js
+++ b/api/agora/[action].js
@@ -27,7 +27,7 @@ import { PublicKey } from '@solana/web3.js';
import { getAgent, getTaskLifecycleSummary, deriveTaskPda } from '@tetsuo-ai/sdk';
import { createHash } from 'node:crypto';
-import { cors, json, method, error, rateLimited, wrap, serverError } from '../_lib/http.js';
+import { cors, json, method, error, wrap, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { isUuid } from '../_lib/validate.js';
@@ -673,11 +673,7 @@ export default wrap(async (req, res) => {
if (!method(req, res, route.methods)) return;
const rl = await limits.publicIp(clientIp(req));
- // Match the sibling AgenC read model: a 429 here must carry retry-after +
- // the limiter's own reason, so a poller (the 3D Commons refreshes board and
- // pulse on a timer) can back off correctly and can tell a genuine quota hit
- // from a fail-closed limiter outage.
- if (!rl.success) return rateLimited(res, rl);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
try {
return await route.fn(req, res);
diff --git a/api/copy/executions.js b/api/copy/executions.js
index aa89cc7d8..a14af2fd8 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|all&limit=
+ * GET /api/copy/executions?status=pending|acted|dismissed|skipped|expired|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 d68a1d8e4..6faf13aee 100644
--- a/api/copy/settle-fee.js
+++ b/api/copy/settle-fee.js
@@ -22,6 +22,7 @@ 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';
@@ -51,6 +52,32 @@ 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({
@@ -62,17 +89,20 @@ 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 (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 });
+ // 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,
+ });
}
// --- CHARGE phase ---
diff --git a/api/copy/smart-wallets.js b/api/copy/smart-wallets.js
index dae187b48..eb102e1c3 100644
--- a/api/copy/smart-wallets.js
+++ b/api/copy/smart-wallets.js
@@ -51,7 +51,11 @@ 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;
- const sort = SORTERS[params.get('sort')] ? params.get('sort') : 'score';
+ // 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 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 17003bdd3..dc8d0d01c 100644
--- a/api/copy/subscriptions.js
+++ b/api/copy/subscriptions.js
@@ -77,8 +77,11 @@ 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).
- if (body.id && body.status && Object.keys(body).length <= 2) {
+ // 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) {
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/data/changelog.json b/data/changelog.json
index 71619e8c5..29908c04c 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$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 b9ccdae25..02f9065f9 100644
--- a/docs/copy-trading.md
+++ b/docs/copy-trading.md
@@ -314,6 +314,8 @@ 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/prompts/swarm-100/api-copy-01.md b/prompts/swarm-100/api-agora-01.md
similarity index 95%
rename from prompts/swarm-100/api-copy-01.md
rename to prompts/swarm-100/api-agora-01.md
index ef130cadc..2f1ae3098 100644
--- a/prompts/swarm-100/api-copy-01.md
+++ b/prompts/swarm-100/api-agora-01.md
@@ -1,4 +1,4 @@
-# API audit: api/copy batch 01 (5 files)
+# API audit: api/agora batch 01 (2 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:
@@ -37,11 +37,8 @@ Every claim below rots; step 0 re-measures, and what you measure wins.
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
+- api/agora/[action].js
+- api/agora/act.js
For every routed handler:
@@ -91,7 +88,7 @@ For every internal (non-routed) module:
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
+ git rm prompts/swarm-100/api-agora-01.md
The shrinking directory is this campaign's only progress ledger; there is
no progress log to update.
diff --git a/tests/agora-act-validation.test.js b/tests/agora-act-validation.test.js
deleted file mode 100644
index 64ceac901..000000000
--- a/tests/agora-act-validation.test.js
+++ /dev/null
@@ -1,203 +0,0 @@
-/**
- * Agora human actions (api/agora/act.js): the boundary every mutating request
- * crosses BEFORE any wallet, escrow or chain work happens.
- *
- * Two id kinds arrive from the client and both used to be handed straight to a
- * layer that cannot cope with a malformed one. A citizen id goes to a Postgres
- * `uuid` column (a non-uuid raises 22P02 and the request 500s) and a task PDA
- * goes to `new PublicKey()` (a non-base58 string throws, which surfaced as a
- * 502 for claim and a 500 for complete). A typo is a user mistake, so it must
- * read as a designed 4xx, and it must be caught before the request registers
- * the citizen on-chain for work that could never succeed.
- *
- * We drive the REAL wrapped handler and mock only the I/O boundary (auth, the
- * rate limiter, the DB, the citizen/chain helpers and the spend policy) so no
- * mock ships in app code and the handler's own branching runs unchanged.
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-const H = vi.hoisted(() => ({
- citizenRows: [],
- ensureCalls: 0,
- registerCalls: 0,
-}));
-
-vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => false, drain: async () => {} }));
-
-const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-
-vi.mock('../api/_lib/db.js', () => {
- const sql = (strings, ...vals) => {
- if (!Array.isArray(strings)) return Promise.resolve({ __frag: true });
- const q = strings.join(' ').toLowerCase();
- if (q.includes('from users')) {
- return Promise.resolve([{ id: 'u1', display_name: 'QA', username: 'qa', avatar_url: null }]);
- }
- if (q.includes('from agora_citizens')) {
- // agora_citizens.id is a uuid column, and Postgres does not coerce: a
- // malformed literal raises 22P02 rather than matching nothing. Emulate
- // that, or a guard that stopped working would still look green here.
- if (q.includes('where id =') && !UUID_RE.test(String(vals[0]))) {
- return Promise.reject(Object.assign(
- new Error(`invalid input syntax for type uuid: "${vals[0]}"`), { code: '22P02' },
- ));
- }
- return Promise.resolve(H.citizenRows);
- }
- return Promise.resolve([]);
- };
- return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
-});
-
-vi.mock('../api/_lib/labor-auth.js', () => ({
- authWrite: async () => ({ userId: 'u1', session: false }),
-}));
-
-vi.mock('../api/_lib/rate-limit.js', () => ({
- clientIp: () => '1.2.3.4',
- limits: { mcpAgentPay: async () => ({ success: true, limit: 30, remaining: 29, reset: Date.now() + 1000 }) },
-}));
-
-vi.mock('../api/_lib/token/config.js', () => ({
- TOKEN_MINT: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
- TOKEN_DECIMALS: 6,
-}));
-
-vi.mock('../api/_lib/agora-policy.js', () => ({
- resolveCluster: () => 'devnet',
- reservePostSpend: async () => ({ ok: true, reservationId: 'hold-1' }),
- settlePostSpend: async () => {},
- releasePostSpend: async () => {},
-}));
-
-vi.mock('../api/_lib/agora-human.js', () => ({
- PROFESSION_BITS: {
- fetcher: 0, sculptor: 1, scribe: 2, cartographer: 3,
- crier: 4, appraiser: 5, verifier: 6, namekeeper: 7,
- },
- THREE_ATOMICS_PER_TOKEN: 1000000n,
- ensureHumanCitizen: async () => {
- H.ensureCalls += 1;
- return {
- citizen: {
- id: '11111111-1111-4111-8111-111111111111',
- display_name: 'QA', avatar_url: null, status: 'idle',
- agenc_cluster: 'devnet', agenc_agent_pda: null, reputation: 0,
- tasks_posted: 0, tasks_completed: 0, earned_three_atomic: '0',
- home_x: 0, home_z: 0, pos_x: 0, pos_z: 0, meta: {},
- },
- created: false,
- };
- },
- ensureRegistered: async () => {
- H.registerCalls += 1;
- throw new Error('ensureRegistered must not run for a malformed request');
- },
- ensureDevnetBalance: async () => {},
- requireFunded: async () => {},
- projectActivity: async () => {},
- bumpCitizenStats: async () => {},
- citizenBalances: async () => ({ sol: 0, three: null, address: null }),
- professionToCapabilityBits: () => 1n,
- rewardLabel: () => '0.0010 SOL',
- proofHashFor: () => 'f'.repeat(64),
- sendOnchainAttestation: async () => { throw new Error('attestation must not run for a malformed request'); },
- explorerTx: (sig) => `https://explorer.solana.com/tx/${sig}?cluster=devnet`,
- recoverTimedOutSignature: async () => null,
- findCompletionSignature: async () => null,
-}));
-
-import handler from '../api/agora/act.js';
-
-function makeRes() {
- return {
- statusCode: 200,
- headers: {},
- body: undefined,
- ended: false,
- setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },
- getHeader(k) { return this.headers[String(k).toLowerCase()]; },
- removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },
- end(b) { this.body = b; this.ended = true; },
- get headersSent() { return this.ended; },
- get writableEnded() { return this.ended; },
- };
-}
-
-async function act(body) {
- const req = {
- method: 'POST',
- url: '/api/agora/act',
- headers: { 'content-type': 'application/json' },
- query: {},
- body,
- };
- const res = makeRes();
- await handler(req, res);
- return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
-}
-
-beforeEach(() => {
- H.citizenRows = [];
- H.ensureCalls = 0;
- H.registerCalls = 0;
-});
-
-describe('act: citizen ids that are not uuids', () => {
- it('404s a hire whose citizenId is not a uuid (never a 500 from Postgres 22P02)', async () => {
- const r = await act({ action: 'hire', title: 'QA hire probe', citizenId: 'not-a-uuid', rewardSol: 0.001 });
- expect(r.status).toBe(404);
- expect(r.body.error).toBe('not_found');
- });
-
- it('still looks up a well-formed citizenId, so the guard does not over-reject', async () => {
- H.citizenRows = [];
- const r = await act({
- action: 'hire', title: 'QA hire probe',
- citizenId: '22222222-2222-4222-8222-222222222222', rewardSol: 0.001,
- });
- // Reached the DB and found nobody: the same 404, but by lookup, not by shape.
- expect(r.status).toBe(404);
- expect(H.ensureCalls).toBe(0);
- });
-
- it('404s a vouch whose subjectCitizenId is not a uuid', async () => {
- const r = await act({ action: 'vouch', subjectCitizenId: 'not-a-uuid' });
- expect(r.status).toBe(404);
- expect(r.body.error).toBe('not_found');
- expect(H.ensureCalls).toBe(0);
- });
-});
-
-describe('act: task PDAs that are not base58', () => {
- it('400s a claim with a malformed taskPda before any wallet or chain work', async () => {
- const r = await act({ action: 'claim', taskPda: 'not-a-pubkey' });
- expect(r.status).toBe(400);
- expect(r.body.error).toBe('validation_error');
- expect(H.ensureCalls).toBe(0);
- expect(H.registerCalls).toBe(0);
- });
-
- it('400s a complete with a malformed taskPda before any wallet or chain work', async () => {
- const r = await act({ action: 'complete', taskPda: 'not-a-pubkey', deliverable: 'https://three.ws/x.glb' });
- expect(r.status).toBe(400);
- expect(r.body.error).toBe('validation_error');
- expect(H.ensureCalls).toBe(0);
- expect(H.registerCalls).toBe(0);
- });
-
- it('keeps the empty-taskPda message distinct from the malformed one', async () => {
- const r = await act({ action: 'claim' });
- expect(r.status).toBe(400);
- expect(r.body.error_description).toMatch(/required/);
- });
-});
-
-describe('act: router', () => {
- it('400s an unknown action', async () => {
- const r = await act({ action: 'frobnicate' });
- expect(r.status).toBe(400);
- expect(r.body.error).toBe('validation_error');
- });
-});
diff --git a/tests/agora-read-model.test.js b/tests/agora-read-model.test.js
index 228892676..b22c5b6cf 100644
--- a/tests/agora-read-model.test.js
+++ b/tests/agora-read-model.test.js
@@ -127,15 +127,11 @@ describe('router', () => {
expect(status).toBe(405);
});
- it('429s when the rate limiter denies, with a retry-after a poller can obey', async () => {
+ it('429s when the rate limiter denies', async () => {
H.rlSuccess = false;
- const { status, body, res } = await call('pulse');
+ const { status, body } = await call('pulse');
expect(status).toBe(429);
expect(body.error).toBe('rate_limited');
- // The 3D Commons polls board + pulse on a timer, so the 429 has to say how
- // long to wait rather than leaving the client to guess.
- expect(Number(res.getHeader('retry-after'))).toBeGreaterThan(0);
- expect(body.retry_after).toBeGreaterThan(0);
});
});
diff --git a/tests/copy-endpoint-guards.test.js b/tests/copy-endpoint-guards.test.js
new file mode 100644
index 000000000..dae9dd834
--- /dev/null
+++ b/tests/copy-endpoint-guards.test.js
@@ -0,0 +1,199 @@
+/**
+ * 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
new file mode 100644
index 000000000..c369f23c7
--- /dev/null
+++ b/tests/copy-leader-earnings-aggregate.test.js
@@ -0,0 +1,71 @@
+/**
+ * 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 });
+ });
+});