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.

Add closed trade history to sniper dashboard

nirholas2ff3ff4dbdae
diff --git a/api/sniper/history.js b/api/sniper/history.js
new file mode 100644
index 000000000..3b9872553
--- /dev/null
+++ b/api/sniper/history.js
@@ -0,0 +1,103 @@
+/**
+ * Agent Sniper — closed trade history for the authenticated owner.
+ *
+ * GET /api/sniper/history?network=mainnet&limit=50&agent_id=<uuid>
+ *
+ * Returns the calling user's own closed sniper positions — the exact rows that
+ * feed the summary stats on /dashboard/sniper, but as individual trades so the
+ * owner can audit every win and loss.
+ *
+ * Auth: session cookie OR bearer token (same as /api/sniper/strategy).
+ * Rate-limited: authIp bucket.
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+function solscan(sig, network) {
+ if (!sig || sig === 'SIMULATED') return null;
+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;
+}
+
+const sol = (l) => (l != null ? Number(BigInt(l)) / 1e9 : null);
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const userId = await resolveUserId(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in to view your trade history');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';
+ const limitN = Math.min(200, Math.max(1, Number(params.get('limit')) || 50));
+ const agentIdParam = (params.get('agent_id') || '').trim();
+ const agentId = UUID_RE.test(agentIdParam) ? agentIdParam : null;
+
+ const rows = agentId
+ ? await sql`
+ select p.id, p.agent_id, p.network, p.mint, p.symbol, p.name,
+ p.status, p.exit_reason, p.entry_quote_lamports, p.exit_quote_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,
+ p.opened_at, p.closed_at,
+ a.name as agent_name, a.profile_image_url as agent_image, a.avatar_url as agent_avatar
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id
+ where p.user_id = ${userId}
+ and p.network = ${network}
+ and p.agent_id = ${agentId}
+ and p.status = 'closed'
+ order by p.closed_at desc
+ limit ${limitN}
+ `
+ : await sql`
+ select p.id, p.agent_id, p.network, p.mint, p.symbol, p.name,
+ p.status, p.exit_reason, p.entry_quote_lamports, p.exit_quote_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,
+ p.opened_at, p.closed_at,
+ a.name as agent_name, a.profile_image_url as agent_image, a.avatar_url as agent_avatar
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id
+ where p.user_id = ${userId}
+ and p.network = ${network}
+ and p.status = 'closed'
+ order by p.closed_at desc
+ limit ${limitN}
+ `;
+
+ const trades = rows.map((r) => ({
+ id: r.id,
+ agent_id: r.agent_id,
+ agent_name: r.agent_name,
+ agent_image: r.agent_image || r.agent_avatar || null,
+ mint: r.mint,
+ symbol: r.symbol || r.name || 'UNKNOWN',
+ exit_reason: r.exit_reason,
+ entry_sol: sol(r.entry_quote_lamports),
+ exit_sol: sol(r.exit_quote_lamports),
+ pnl_sol: sol(r.realized_pnl_lamports),
+ pnl_pct: r.realized_pnl_pct != null ? Number(r.realized_pnl_pct) : null,
+ buy_url: solscan(r.buy_sig, network),
+ sell_url: solscan(r.sell_sig, network),
+ opened_at: r.opened_at,
+ closed_at: r.closed_at,
+ }));
+
+ return json(res, 200, { trades, total: trades.length, network });
+});
diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.js
index b8bfe8577..2a740c23c 100644
--- a/src/dashboard-next/pages/sniper.js
+++ b/src/dashboard-next/pages/sniper.js
@@ -129,6 +129,27 @@ const STYLE = `<style>
.sn-ob-tier { font: 600 8px/1 var(--nxt-mono, monospace); text-transform: uppercase; letter-spacing: .06em; opacity: .8; }
.sn-empty { color: var(--nxt-ink-faint); font-size: 13px; padding: 24px 16px; text-align: center; }
+/* trade history */
+.sn-hist { background: var(--nxt-panel); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); overflow: hidden; }
+.sn-hist-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 18px 12px; border-bottom: 1px solid var(--nxt-line); }
+.sn-hist-head h3 { font-size: 14px; margin: 0; }
+.sn-hist-table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
+.sn-hist-table th { padding: 9px 14px; text-align: left; font: 600 10px/1 var(--nxt-mono, monospace); letter-spacing: .07em; text-transform: uppercase; color: var(--nxt-ink-faint); border-bottom: 1px solid var(--nxt-line); white-space: nowrap; }
+.sn-hist-table th.r, .sn-hist-table td.r { text-align: right; }
+.sn-hist-row td { padding: 10px 14px; border-bottom: 1px solid rgba(255,255,255,0.04); vertical-align: middle; white-space: nowrap; }
+.sn-hist-row:last-child td { border-bottom: none; }
+.sn-hist-sym { font-weight: 700; font-size: 13px; }
+.sn-hist-agent { font-size: 11px; color: var(--nxt-ink-faint); margin-top: 2px; }
+.sn-hist-mono { font-family: var(--nxt-mono, monospace); font-variant-numeric: tabular-nums; }
+.sn-hist-tag { font-size: 10px; padding: 2px 7px; border-radius: 999px; border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-faint); }
+.sn-hist-tag.tp { color: var(--nxt-success); border-color: color-mix(in srgb, var(--nxt-success) 40%, transparent); }
+.sn-hist-tag.sl { color: var(--nxt-danger, #f87171); border-color: color-mix(in srgb, var(--nxt-danger, #f87171) 40%, transparent); }
+.sn-hist-link { color: var(--nxt-accent); text-decoration: none; font-size: 11px; }
+.sn-hist-link:hover { text-decoration: underline; }
+.sn-hist-more { display: block; text-align: center; padding: 12px; font-size: 12px; color: var(--nxt-ink-faint); border-top: 1px solid var(--nxt-line); background: none; border-left:0;border-right:0;border-bottom:0; width:100%; cursor:pointer; }
+.sn-hist-more:hover { color: var(--nxt-ink); }
+@media (max-width: 640px) { .sn-hist-table th.hide-mobile, .sn-hist-row td.hide-mobile { display: none; } }
+
/* new strategy cta */
.sn-new { background: var(--nxt-panel); border: 1px dashed var(--nxt-stroke); border-radius: var(--nxt-radius); padding: 20px 24px; display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
.sn-new-text { font-size: 13px; color: var(--nxt-ink-faint); max-width: 340px; }
@@ -188,6 +209,7 @@ async function refresh(root) {
root.innerHTML = render();
wireEvents(root);
startSse(root);
+ loadTradeHistory(root);
}
function render() {
@@ -199,6 +221,7 @@ function render() {
${hasStrats ? _strategies.map(stratCard).join('') : ''}
</div>
${livePositionsSection()}
+ <div id="sn-hist-mount"></div>
${newStrategyCta()}
</div>`;
}
@@ -509,6 +532,109 @@ async function enrichPositionOracle() {
} catch { /* non-fatal */ }
}
+// ── Trade history ─────────────────────────────────────────────────────────────
+
+const EXIT_TAG = {
+ take_profit: ['tp', 'Take profit'],
+ stop_loss: ['sl', 'Stop loss'],
+ trailing_stop: ['sl', 'Trailing stop'],
+ timeout: ['', 'Timeout'],
+ kill_switch: ['', 'Kill switch'],
+ manual: ['', 'Manual'],
+};
+
+function histRow(t) {
+ const pnlCls = t.pnl_sol > 0 ? 'sn-pos' : t.pnl_sol < 0 ? 'sn-neg' : '';
+ const pnlStr = t.pnl_sol != null ? `<span class="${pnlCls} sn-hist-mono">${fmtSol(t.pnl_sol)}</span>` : '—';
+ const pctStr = t.pnl_pct != null ? `<span class="${pnlCls} sn-hist-mono">${t.pnl_pct >= 0 ? '+' : ''}${t.pnl_pct.toFixed(1)}%</span>` : '—';
+ const [tagCls, tagLabel] = EXIT_TAG[t.exit_reason] || ['', t.exit_reason || '—'];
+ const entrySol = t.entry_sol != null ? `<span class="sn-hist-mono">${fmtSol(t.entry_sol)}</span>` : '—';
+ const links = [
+ t.buy_url ? `<a class="sn-hist-link" href="${esc(t.buy_url)}" target="_blank" rel="noopener">buy ↗</a>` : '',
+ t.sell_url ? `<a class="sn-hist-link" href="${esc(t.sell_url)}" target="_blank" rel="noopener">sell ↗</a>` : '',
+ ].filter(Boolean).join(' · ');
+ const holdMs = t.opened_at && t.closed_at
+ ? new Date(t.closed_at).getTime() - new Date(t.opened_at).getTime()
+ : null;
+ const holdStr = holdMs != null ? holdDuration(holdMs) : '—';
+ return `<tr class="sn-hist-row">
+ <td>
+ <div class="sn-hist-sym">${esc(t.symbol)}</div>
+ <div class="sn-hist-agent">${esc(t.agent_name || '')}</div>
+ </td>
+ <td class="r">${entrySol}</td>
+ <td class="r">${pnlStr}</td>
+ <td class="r hide-mobile">${pctStr}</td>
+ <td class="r hide-mobile"><span class="sn-hist-mono">${holdStr}</span></td>
+ <td class="r"><span class="sn-hist-tag ${tagCls}">${esc(tagLabel)}</span></td>
+ <td class="r hide-mobile">${links || '—'}</td>
+ </tr>`;
+}
+
+function holdDuration(ms) {
+ const s = Math.round(ms / 1000);
+ if (s < 60) return `${s}s`;
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m}m`;
+ return `${Math.floor(m / 60)}h ${m % 60}m`;
+}
+
+let _histLoading = false;
+let _histLimit = 25;
+
+async function loadTradeHistory(root, append = false) {
+ if (_histLoading) return;
+ const mount = root.querySelector('#sn-hist-mount');
+ if (!mount) return;
+ _histLoading = true;
+ if (!append) {
+ mount.innerHTML = `<div class="sn-hist"><div class="sn-hist-head"><h3>Trade History</h3></div><div class="sn-empty" style="padding:24px 18px">Loading…</div></div>`;
+ }
+ try {
+ const data = await get(`/api/sniper/history?limit=${_histLimit}`);
+ const trades = data.trades || [];
+ if (!trades.length) {
+ mount.innerHTML = `<div class="sn-hist"><div class="sn-hist-head"><h3>Trade History</h3></div><div class="sn-empty" style="padding:24px 18px">No closed trades yet. Your completed snipes appear here.</div></div>`;
+ return;
+ }
+ const hasMore = trades.length >= _histLimit;
+ mount.innerHTML = `
+ <div class="sn-hist">
+ <div class="sn-hist-head">
+ <h3>Trade History</h3>
+ <span style="font-size:12px;color:var(--nxt-ink-faint)">${trades.length} closed trade${trades.length !== 1 ? 's' : ''}</span>
+ </div>
+ <div style="overflow-x:auto">
+ <table class="sn-hist-table">
+ <thead>
+ <tr>
+ <th>Coin</th>
+ <th class="r">Entry</th>
+ <th class="r">PnL</th>
+ <th class="r hide-mobile">PnL %</th>
+ <th class="r hide-mobile">Hold</th>
+ <th class="r">Exit</th>
+ <th class="r hide-mobile">Proof</th>
+ </tr>
+ </thead>
+ <tbody>${trades.map(histRow).join('')}</tbody>
+ </table>
+ </div>
+ ${hasMore ? `<button class="sn-hist-more" id="sn-hist-more">Load more</button>` : ''}
+ </div>`;
+ if (hasMore) {
+ mount.querySelector('#sn-hist-more')?.addEventListener('click', () => {
+ _histLimit += 25;
+ loadTradeHistory(root, false);
+ });
+ }
+ } catch {
+ mount.innerHTML = `<div class="sn-hist"><div class="sn-hist-head"><h3>Trade History</h3></div><div class="sn-empty" style="padding:20px 18px;color:var(--nxt-ink-faint)">Couldn't load trade history.</div></div>`;
+ } finally {
+ _histLoading = false;
+ }
+}
+
// ── New strategy CTA ──────────────────────────────────────────────────────────
function newStrategyCta() {
diff --git a/vercel.json b/vercel.json
index b1a7a811f..a2192c3d3 100644
--- a/vercel.json
+++ b/vercel.json
@@ -238,6 +238,9 @@
"api/sniper/leaderboard.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 30
+ },
+ "api/sniper/history.js": {
+ "maxDuration": 20
}
},
"routes": [
@@ -1929,6 +1932,10 @@
"src": "/api/sniper/leaderboard",
"dest": "/api/sniper/leaderboard.js"
},
+ {
+ "src": "/api/sniper/history",
+ "dest": "/api/sniper/history.js"
+ },
{
"src": "/api/pump/build-metadata",
"dest": "/api/pump/[action]?action=build-metadata"