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.

Copy-trading performance fee accounting + alert URL fix

nirholasc00530b9bb1b
diff --git a/api/_lib/copy-earnings.js b/api/_lib/copy-earnings.js
new file mode 100644
index 000000000..71fc1d3d1
--- /dev/null
+++ b/api/_lib/copy-earnings.js
@@ -0,0 +1,114 @@
+/**
+ * Copy-trading performance-fee accounting.
+ *
+ * The fee a leader earns is charged on a COPIER'S REALIZED PROFIT ONLY, with a
+ * high-water mark so the same gains are never billed twice. This module holds the
+ * pure HWM math (tested) and the real attribution over the copier's acted copies.
+ *
+ * Profit basis (transparent, stated up-front to the copier when they subscribe):
+ * for each leader position the copier ACTED on (entered a copy of) that has since
+ * CLOSED, the copy's realized profit is the copier's committed size scaled by the
+ * leader's realized return — planned_sol × (leader_realized_pnl_pct / 100). It is
+ * the copier's copy, at the copier's size, at the leader's return. Losers count
+ * (they lower the cumulative), so the HWM only ever bills genuinely new profit.
+ *
+ * The fee itself settles in $THREE via the shared token rails under the
+ * `copy_performance_fee` split policy (leader 80% / treasury 15% / holders 5%).
+ */
+
+import { sql } from './db.js';
+
+const round6 = (x) => Math.round(x * 1e6) / 1e6;
+const n = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
+
+/**
+ * High-water-mark performance fee. PURE.
+ *
+ * @param {object} p
+ * @param {number} p.realizedProfitSol cumulative realized copy profit to date (signed SOL).
+ * @param {number} p.highWaterMarkSol the cumulative profit peak already billed.
+ * @param {number} p.feeBps leader's fee in basis points (e.g. 1000 = 10%).
+ * @returns {{ fee_sol:number, billable_profit_sol:number, new_high_water_mark_sol:number }}
+ */
+export function computePerfFee({ realizedProfitSol, highWaterMarkSol = 0, feeBps = 1000 }) {
+ const cumulative = n(realizedProfitSol);
+ const hwm = n(highWaterMarkSol);
+ const billable = Math.max(0, cumulative - hwm);
+ const fee = billable * (n(feeBps) / 10_000);
+ return {
+ fee_sol: round6(fee),
+ billable_profit_sol: round6(billable),
+ // HWM only ratchets up when there's new billable profit; a drawdown never
+ // lowers it (otherwise a recovery would be billed twice).
+ new_high_water_mark_sol: round6(Math.max(hwm, cumulative)),
+ };
+}
+
+/**
+ * Cumulative realized copy profit for one subscription, from the copier's acted
+ * buys whose leader position has closed. Returns { profit_sol, closed_copies }.
+ */
+export async function cumulativeCopyProfit(subscriptionId) {
+ const [row] = await sql`
+ select
+ coalesce(sum(e.planned_sol * (p.realized_pnl_pct / 100.0)), 0) as profit_sol,
+ count(*) as closed_copies
+ from copy_executions e
+ join agent_sniper_positions p on p.id = e.leader_position_id
+ where e.subscription_id = ${subscriptionId}
+ and e.direction = 'buy' and e.status = 'acted'
+ and p.status = 'closed' and p.realized_pnl_pct is not null
+ `;
+ return { profit_sol: round6(n(row?.profit_sol)), closed_copies: Number(row?.closed_copies) || 0 };
+}
+
+/**
+ * What a single subscription currently OWES (accrued, uncharged) — the perf fee
+ * on cumulative realized profit above the subscription's high-water mark.
+ */
+export async function subscriptionOwed(sub) {
+ const { profit_sol, closed_copies } = await cumulativeCopyProfit(sub.id);
+ const fee = computePerfFee({
+ realizedProfitSol: profit_sol,
+ highWaterMarkSol: n(sub.high_water_mark_sol),
+ feeBps: n(sub.perf_fee_bps) || 1000,
+ });
+ return {
+ subscription_id: sub.id,
+ cumulative_profit_sol: profit_sol,
+ closed_copies,
+ ...fee,
+ };
+}
+
+/**
+ * A leader's accrued copy earnings, aggregated across their active copiers. Public
+ * aggregate (no per-copier identity) — the social-proof "this trader has earned X
+ * for being copied" figure. Best-effort: degrades to zeros if copy tables are
+ * absent (not yet migrated).
+ *
+ * @returns {Promise<{ copiers:number, accrued_fee_sol:number, copier_profit_sol:number }>}
+ */
+export async function accruedLeaderEarnings(leaderAgentId, network) {
+ 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'
+ `;
+ } 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);
+ }
+ return {
+ copiers: subs.length,
+ accrued_fee_sol: round6(accruedFee),
+ copier_profit_sol: round6(profit),
+ };
+}
diff --git a/api/_lib/oracle/alerts.js b/api/_lib/oracle/alerts.js
index e5c746f9f..0dbf716e1 100644
--- a/api/_lib/oracle/alerts.js
+++ b/api/_lib/oracle/alerts.js
@@ -46,7 +46,7 @@ function format(coin) {
pillars ? `<i>${pillars}</i>` : '',
`<code>${escHtml(coin.mint)}</code>`,
`${category}${smart}`,
- `<a href="https://pump.fun/coin/${encodeURIComponent(coin.mint)}">pump.fun</a> · <a href="https://three.ws/launch-detail?mint=${encodeURIComponent(coin.mint)}">Oracle</a>`,
+ `<a href="https://pump.fun/coin/${encodeURIComponent(coin.mint)}">pump.fun</a> · <a href="https://three.ws/oracle?mint=${encodeURIComponent(coin.mint)}">Oracle</a>`,
].filter(Boolean).join('\n');
}
diff --git a/api/_lib/token/config.js b/api/_lib/token/config.js
index 62c0ba3d8..67e2eabc4 100644
--- a/api/_lib/token/config.js
+++ b/api/_lib/token/config.js
@@ -154,6 +154,15 @@ export const SPLIT_POLICIES = Object.freeze({
{ role: 'treasury', bps: 8000 },
{ role: 'rewards', bps: 2000 },
],
+ // Copy-trading performance fee — charged on a copier's realized profit only.
+ // The leader (seller leg) keeps 80%; the platform takes 15% (funds buybacks +
+ // the referrer's share via the existing referral ledger); 5% reflects to
+ // holders. Same on-chain split machinery as every other paid surface.
+ copy_performance_fee: [
+ { role: 'seller', bps: 8000 },
+ { role: 'treasury', bps: 1500 },
+ { role: 'rewards', bps: 500 },
+ ],
});
function resolveRole(role, { sellerWallet } = {}) {
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.js
index ef0377234..af67c336f 100644
--- a/api/pump-fun-mcp.js
+++ b/api/pump-fun-mcp.js
@@ -936,6 +936,9 @@ async function handleGetCoinIntel({ mint, network = 'mainnet' } = {}) {
// Outcome (null if coin not yet labeled)
outcome,
+
+ // Learning model: conditional win-rates so agents can see the evidence behind the score
+ model,
};
} catch (err) {
const missing = /relation .* does not exist/i.test(String(err?.message));
diff --git a/data/changelog.json b/data/changelog.json
index 5aea224f6..9c12ae81a 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$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-06-16",
+ "title": "Coin intelligence — per-signal win-rates explain every oracle decision",
+ "summary": "The oracle's quality score is no longer a black box. After each learning-loop run, the system now computes per-signal conditional win-rates — for every signal dimension (bundle score, organic score, smart-money count, category, dev behaviour, and more), it reports the observed graduation rate for each value tier against the platform baseline. An agent calling get_coin_intel now receives the full model alongside the coin snapshot: exactly how often coins with 'clean' bundle scores graduated vs. coins with 'high' bundle scores, or what the graduation rate is when three or more smart-money wallets entered early. The oracle page shows these rates as context behind each risk flag and quality band. The learning loop updates the rates every time a cron run labels new outcomes and retrains — so the evidence improves as the platform watches more coins.",
+ "tags": ["feature", "improvement"],
+ "link": "/oracle"
+ },
{
"date": "2026-06-16",
"title": "Copy trading — mirror proven traders, non-custodially, on your own terms",
diff --git a/tests/copy-earnings.test.js b/tests/copy-earnings.test.js
new file mode 100644
index 000000000..a27eda4da
--- /dev/null
+++ b/tests/copy-earnings.test.js
@@ -0,0 +1,55 @@
+/**
+ * Copy-trading performance-fee math — high-water-mark correctness.
+ * Money-adjacent: the HWM must never double-bill a recovery, never bill a loss.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { computePerfFee } from '../api/_lib/copy-earnings.js';
+
+describe('computePerfFee', () => {
+ it('bills the leader fee on first profit and ratchets the HWM', () => {
+ const r = computePerfFee({ realizedProfitSol: 10, highWaterMarkSol: 0, feeBps: 1000 });
+ expect(r.billable_profit_sol).toBe(10);
+ expect(r.fee_sol).toBeCloseTo(1, 6); // 10% of 10
+ expect(r.new_high_water_mark_sol).toBe(10);
+ });
+
+ it('charges nothing on a drawdown below the HWM and keeps the HWM', () => {
+ const r = computePerfFee({ realizedProfitSol: 8, highWaterMarkSol: 10, feeBps: 1000 });
+ expect(r.billable_profit_sol).toBe(0);
+ expect(r.fee_sol).toBe(0);
+ expect(r.new_high_water_mark_sol).toBe(10);
+ });
+
+ it('only bills NEW profit above the prior peak after a recovery', () => {
+ const r = computePerfFee({ realizedProfitSol: 15, highWaterMarkSol: 10, feeBps: 1000 });
+ expect(r.billable_profit_sol).toBe(5); // not the full 15
+ expect(r.fee_sol).toBeCloseTo(0.5, 6);
+ expect(r.new_high_water_mark_sol).toBe(15);
+ });
+
+ it('never bills a net loss', () => {
+ const r = computePerfFee({ realizedProfitSol: -4, highWaterMarkSol: 0, feeBps: 1000 });
+ expect(r.fee_sol).toBe(0);
+ expect(r.billable_profit_sol).toBe(0);
+ expect(r.new_high_water_mark_sol).toBe(0); // a loss never lowers the HWM
+ });
+
+ it('honors the leader fee rate', () => {
+ expect(computePerfFee({ realizedProfitSol: 100, highWaterMarkSol: 0, feeBps: 2000 }).fee_sol).toBeCloseTo(20, 6);
+ expect(computePerfFee({ realizedProfitSol: 100, highWaterMarkSol: 0, feeBps: 0 }).fee_sol).toBe(0);
+ });
+
+ it('is sequence-correct across draw-down then recovery (no double billing)', () => {
+ // peak 10 (billed) → dip to 8 (no bill) → recover to 15 (bill only the +5)
+ let hwm = 0, totalFee = 0;
+ for (const cum of [10, 8, 15]) {
+ const r = computePerfFee({ realizedProfitSol: cum, highWaterMarkSol: hwm, feeBps: 1000 });
+ totalFee += r.fee_sol;
+ hwm = r.new_high_water_mark_sol;
+ }
+ // fees: 1.0 (on 10) + 0 (dip) + 0.5 (on +5) = 1.5 — the same as billing 15 once.
+ expect(totalFee).toBeCloseTo(1.5, 6);
+ expect(hwm).toBe(15);
+ });
+});