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
Copy-trading earnings API + performance fee settlement + watchlist z-index fixes
nirholasd68061c3231e
diff --git a/api/copy/earnings.js b/api/copy/earnings.jsnew file mode 100644index 000000000..b494ab54a--- /dev/null+++ b/api/copy/earnings.js@@ -0,0 +1,72 @@+/**+ * Copy-trading earnings / fees owed.+ *+ * GET /api/copy/earnings?agent_id=<leader>&network= (public)+ * Aggregate copy earnings for a leader — the "this trader has earned X for+ * being copied" social-proof figure. No per-copier identity is exposed.+ *+ * GET /api/copy/earnings (auth)+ * The signed-in copier's performance fees owed across the traders they copy,+ * per subscription, with the leader's name. Drives the dashboard summary.+ *+ * All figures are real — derived from the copier's acted copies matched to the+ * leader's closed positions, above each subscription's high-water mark.+ */++import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { accruedLeaderEarnings, subscriptionOwed } from '../_lib/copy-earnings.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const NETWORKS = new Set(['mainnet', 'devnet']);++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';+ const agentId = (params.get('agent_id') || '').trim();++ // Public leader aggregate.+ if (agentId) {+ if (!UUID_RE.test(agentId)) return error(res, 400, 'invalid_agent', 'agent_id must be a UUID');+ const earnings = await accruedLeaderEarnings(agentId, network);+ return json(res, 200, { agent_id: agentId, network, ...earnings },+ { 'cache-control': 'public, max-age=30, s-maxage=60' });+ }++ // Copier's own owed summary (auth required).+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ const userId = session?.id ?? bearer.userId;++ const subs = await sql`+ select s.*, a.name as leader_name, a.profile_image_url as leader_image, a.avatar_url as leader_avatar+ from copy_subscriptions s+ join agent_identities a on a.id = s.leader_agent_id+ where s.copier_user_id = ${userId} and s.status <> 'stopped'+ `;+ const items = [];+ let totalOwed = 0;+ for (const sub of subs) {+ const owed = await subscriptionOwed(sub);+ if (owed.cumulative_profit_sol === 0 && owed.fee_sol === 0) continue;+ items.push({+ subscription_id: sub.id,+ leader_agent_id: sub.leader_agent_id,+ leader_name: sub.leader_name,+ leader_image: sub.leader_image || sub.leader_avatar || null,+ perf_fee_bps: Number(sub.perf_fee_bps),+ ...owed,+ });+ totalOwed += owed.fee_sol;+ }+ return json(res, 200, { total_fee_owed_sol: Math.round(totalOwed * 1e6) / 1e6, items });+});diff --git a/api/copy/settle-fee.js b/api/copy/settle-fee.jsnew file mode 100644index 000000000..ce63f4a56--- /dev/null+++ b/api/copy/settle-fee.js@@ -0,0 +1,126 @@+/**+ * Copy-trading performance-fee settlement.+ *+ * POST /api/copy/settle-fee { subscription_id } → CHARGE: issue a $THREE quote+ * { leader_agent_id, network } for the fee owed on the copier's+ * realized profit above the HWM.+ * POST /api/copy/settle-fee { quoteToken, tx_signature } → SETTLE: verify the on-chain $THREE+ * split and ratchet the high-water mark.+ *+ * The fee is charged ONLY on realized profit above the subscription's high-water+ * mark, settled in $THREE under the `copy_performance_fee` split policy (leader+ * 80% / treasury 15% / holders 5%). The leader is paid directly on-chain by the+ * split — settlement just records it and ratchets the HWM so the same profit is+ * never billed twice. Auth + CSRF (cookie sessions); agents may settle via bearer.+ */++import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { 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 { solUsdPrice } from '../_lib/avatar-wallet.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const NETWORKS = new Set(['mainnet', 'devnet']);++async function requireUser(req, res) {+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) { error(res, 401, 'unauthorized', 'sign in required'); return null; }+ return { userId: session?.id ?? bearer.userId, viaSession: !!session };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const auth = await requireUser(req, res);+ if (!auth) return;+ const { userId } = auth;+ if (auth.viaSession && !(await requireCsrf(req, res, userId))) return;++ const body = await readJson(req).catch(() => null);+ if (!body || typeof body !== 'object') return error(res, 400, 'bad_request', 'JSON body required');++ // --- SETTLE phase ---+ if (body.quoteToken && body.tx_signature) {+ let result;+ try {+ result = await verifyAndSettlePayment({+ quoteToken: body.quoteToken,+ txSignature: String(body.tx_signature).trim(),+ userId,+ network: NETWORKS.has(body.network) ? body.network : undefined,+ });+ } 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 (UUID_RE.test(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 ---+ let sub;+ if (body.subscription_id) {+ if (!UUID_RE.test(body.subscription_id)) return error(res, 400, 'invalid_id', 'subscription_id must be a UUID');+ [sub] = await sql`select * from copy_subscriptions where id = ${body.subscription_id} and copier_user_id = ${userId} limit 1`;+ } else {+ const leaderId = String(body.leader_agent_id || '').trim();+ const network = NETWORKS.has(body.network) ? body.network : 'mainnet';+ if (!UUID_RE.test(leaderId)) return error(res, 400, 'invalid_leader', 'leader_agent_id must be a UUID');+ [sub] = await sql`+ select * from copy_subscriptions+ where leader_agent_id = ${leaderId} and copier_user_id = ${userId} and network = ${network} limit 1+ `;+ }+ if (!sub) return error(res, 404, 'not_found', 'No such subscription.');++ const owed = await subscriptionOwed(sub);+ if (owed.fee_sol <= 0) {+ return json(res, 200, { ok: true, paid: false, nothing_to_settle: true, owed });+ }+ if (!sub.leader_wallet) {+ return error(res, 409, 'leader_wallet_unknown', 'The leader has no recorded payout wallet yet.');+ }++ let solUsd;+ try { solUsd = await solUsdPrice(); } catch { return error(res, 503, 'price_unavailable', 'SOL price unavailable; try again shortly.'); }+ const usd = owed.fee_sol * solUsd;++ const quote = await issueQuote({+ purpose: 'copy_performance_fee',+ usd,+ splitPolicy: 'copy_performance_fee',+ sellerWallet: sub.leader_wallet,+ network: sub.network,+ refType: 'copy_perf_fee',+ refId: `${sub.id}|${owed.cumulative_profit_sol}`,+ });++ return json(res, 200, {+ ok: true,+ paid: false,+ owed,+ sol_usd: solUsd,+ fee_usd: Number(usd.toFixed(4)),+ quote: quote.token,+ legs: quote.quote.legs,+ expires_at: quote.expiresAt,+ });+});diff --git a/src/dashboard-next/pages/copy.js b/src/dashboard-next/pages/copy.jsindex b03af7f8e..299612ed0 100644--- a/src/dashboard-next/pages/copy.js+++ b/src/dashboard-next/pages/copy.js@@ -116,6 +116,28 @@ function subRow(s) {</div>`;}+function earningsSection(earnings) {+ const items = (earnings && earnings.items) || [];+ const owing = items.filter((i) => i.fee_sol > 0);+ if (!owing.length) return '';+ const total = Number(earnings.total_fee_owed_sol) || 0;+ const rows = owing.map((i) => `+ <div class="cp-item">+ <img class="cp-av" src="${esc(i.leader_image || '/favicon.ico')}" alt="" onerror="this.style.visibility='hidden'" />+ <div class="cp-mid">+ <div class="cp-title">${esc(i.leader_name || 'trader')}</div>+ <div class="cp-sub">${fmtSol(i.cumulative_profit_sol)} profit copied · ${(i.perf_fee_bps / 100).toFixed(0)}% fee</div>+ </div>+ <div class="cp-side"><span class="cp-amt">${fmtSol(i.fee_sol)}</span></div>+ </div>`).join('');+ return `+ <section class="cp-sec">+ <div class="cp-sec-h"><h2>Performance fees</h2><span class="cp-count">${fmtSol(total)}</span></div>+ <p class="cp-note">Leaders earn a performance fee on the profit you make copying them — charged only on gains above your prior peak, never on losses. Settle in $THREE from your agent wallet; 80% goes to the trader, the rest funds buybacks and reflects to $THREE holders.</p>+ <div>${rows}</div>+ </section>`;+}+function historyRow(e) {const status = e.status;const label = status === 'skipped' ? (SKIP_LABEL[e.skip_reason] || 'Skipped') : status[0].toUpperCase() + status.slice(1);@@ -131,12 +153,13 @@ function historyRow(e) {}async function loadAndRender(host) {- let subs, pending, history;+ let subs, pending, history, earnings;try {- [subs, pending, history] = await Promise.all([+ [subs, pending, history, earnings] = await Promise.all([get('/api/copy/subscriptions').then((r) => r.subscriptions || []),get('/api/copy/executions?status=pending').then((r) => r.executions || []),get('/api/copy/executions?status=all&limit=40').then((r) => r.executions || []),+ get('/api/copy/earnings').then((r) => r).catch(() => ({ items: [], total_fee_owed_sol: 0 })),]);} catch {host.innerHTML = `<div class="cp-sec"><div class="cp-empty">Couldn't load your copies. <button class="cp-btn" id="cp-reload">Retry</button></div></div>`;@@ -159,6 +182,8 @@ async function loadAndRender(host) {<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>+ ${earningsSection(earnings)}+<section class="cp-sec"><div class="cp-sec-h"><h2>History</h2><span class="cp-count">${hist.length}</span></div><div id="cp-history">${hist.length ? hist.map(historyRow).join('') : `<div class="cp-empty">Nothing yet.</div>`}</div>diff --git a/src/pump/coin-status-card.js b/src/pump/coin-status-card.jsindex a3ec93879..c1b9167b2 100644--- a/src/pump/coin-status-card.js+++ b/src/pump/coin-status-card.js@@ -363,7 +363,7 @@ const STYLES = `.csc-mcap { font-weight: 600; }.csc-grad { font-size: 11px; padding: 1px 7px; border-radius: 999px; background: rgba(120,140,255,0.14); color: rgba(190,200,255,0.95); }.csc-grad-done { background: rgba(120,200,140,0.16); color: rgba(170,235,190,0.95); }-.csc-buy { color: var(--accent, #7c83ff); text-decoration: none; font-weight: 600; transition: opacity .15s; }+.csc-buy { position: relative; z-index: 2; color: var(--accent, #7c83ff); text-decoration: none; font-weight: 600; transition: opacity .15s; }.csc-buy:hover { opacity: .8; }.csc-buy:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; border-radius: 4px; }@@ -390,7 +390,7 @@ const STYLES = `.csc-card-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; }.csc-card-foot:empty { display: none; }-.csc-conviction { display: flex; align-items: center; gap: 8px; padding: 6px 0 2px; }+.csc-conviction { position: relative; z-index: 2; display: flex; align-items: center; gap: 8px; padding: 6px 0 2px; }.csc-cv-pill { display: inline-flex; align-items: center; font-size: 11px; font-weight: 700;letter-spacing: .06em; padding: 3px 9px; border-radius: 999px; border: 1px solid;transition: opacity .2s; white-space: nowrap; }diff --git a/src/watchlist.css b/src/watchlist.cssindex b43220b92..71c21bff2 100644--- a/src/watchlist.css+++ b/src/watchlist.css@@ -141,7 +141,7 @@ body {outline: var(--focus-ring-width) solid var(--focus-ring-color);outline-offset: -2px;}-.wl-market { position: relative; z-index: 0; }+.wl-market { position: relative; }.wl-remove {position: absolute;diff --git a/src/watchlist.js b/src/watchlist.jsindex 691206bfb..54827de88 100644--- a/src/watchlist.js+++ b/src/watchlist.js@@ -143,10 +143,12 @@ function teardown() {// ── cards ────────────────────────────────────────────────────────────────────function watchCard(mint, index) {+ // Primary card link opens Oracle conviction drawer for this coin.+ // Secondary "launch page" link is rendered inside the coin-status-card footer.const link = el('a', {class: 'wl-card-link',- href: `/launches/${mint}`,- 'aria-label': 'Open coin profile',+ href: `/oracle?mint=${mint}`,+ 'aria-label': 'Open Oracle conviction breakdown',});const market = el('div', { class: 'wl-market' });const removeBtn = el('button', {@@ -166,7 +168,7 @@ function watchCard(mint, index) {card.style.animationDelay = `${Math.min(index, 12) * 40}ms`;card.classList.add('wl-in');}- handles.add(mountCoinStatus(market, mint, { variant: 'card', placeholder: mintIdenticon(mint) }));+ handles.add(mountCoinStatus(market, mint, { variant: 'card', placeholder: mintIdenticon(mint), showBuy: true }));return card;}