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
feat(copy-trade): refuse to copy a leader who is secretly the coin's creator
nirholasaf1226c7421b
diff --git a/api/_lib/copy-eligibility.js b/api/_lib/copy-eligibility.jsindex f4089d309..8d15affc4 100644--- a/api/_lib/copy-eligibility.js+++ b/api/_lib/copy-eligibility.js@@ -20,6 +20,12 @@* willing to ride. When the leader's realized equity curve breaches it the* subscription auto-pauses with a recorded reason, instead of mirroring a* leader into the ground. The copier resumes it deliberately or not at all.+ * 4. CREATOR-LINKED LEADER. A "leader" whose trading wallet shares control with+ * a coin's creator (shared fee payer, first funder) is not a trader to copy+ * on that coin: a follower would just be mirroring the creator's own buy of+ * their own launch, dressed up as a signal. Checked per (leader, mint) in the+ * fanout, before any order is sized, with the reason surfaced on the skipped+ * copy_executions row so the follower sees exactly why.** Drawdown is expressed as a share of capital actually deployed* (max peak-to-trough loss / gross entry), the same definition@@ -28,6 +34,7 @@*/import { sql } from './db.js';+import { resolveCreatorWallet } from './cosmetics-economy.js';const LAMPORTS = 1e9;const lamToSol = (l) => (l == null ? 0 : Number(BigInt(Math.trunc(Number(l)))) / LAMPORTS);@@ -230,3 +237,69 @@ export async function leaderDrawdownPcts(agentIds, network = 'mainnet') {}return out;}++const LINKAGE_BAND_ORDER = ['none', 'weak', 'moderate', 'strong', 'confirmed'];++/**+ * Human reason shown on the skipped copy_executions row when a leader's wallet+ * links to the coin's creator. Mirrors the honeypot/mcap reasons copy-engine.js+ * already attaches to a skip.+ */+export const CREATOR_LINK_REASON = 'leader_linked_to_creator';++/**+ * Decide whether a single wallet-linkage pair means "this leader is the+ * creator" for copy-trading purposes. PURE: takes the one pair+ * `analyzeLinkage()` returns for a 2-address call, never touches DB/RPC.+ *+ * @param {{score:number, band:string, topSignal?:string|null}|null} pair+ * @param {{ band?: string }} [opts] trip threshold, default "strong" (score 65+)+ * @returns {{ linked:boolean, score:number|null, band:string|null, topSignal:string|null }}+ */+export function evaluateLeaderCreatorLinkPair(pair, { band = 'strong' } = {}) {+ if (!pair) return { linked: false, score: null, band: null, topSignal: null };+ const threshold = LINKAGE_BAND_ORDER.indexOf(band);+ const linked = LINKAGE_BAND_ORDER.indexOf(pair.band) >= threshold;+ return { linked, score: pair.score ?? null, band: pair.band ?? null, topSignal: pair.topSignal ?? null };+}++/**+ * Is this leader's trading wallet the same controller as this coin's creator?+ * Resolves the creator (DB first, live pump.fun bonding-curve read as a last+ * resort, via `resolveCreatorWallet`), then scores the one pair with+ * `@three-ws/wallet-linkage`'s `analyzeLinkage`, given the caller's own+ * injected RPC connection so this never hits a hardcoded endpoint.+ *+ * Fails CLOSED toward "not linked": a missing creator, a missing leader+ * wallet, or any RPC/DB error returns `linked:false` rather than guessing.+ * The eligibility bar above already keeps a history-less leader uncopyable,+ * so this check only adds signal, it never has to carry the whole gate alone.+ *+ * @param {object} o+ * @param {string} o.leaderWallet the leader's own trading wallet (runtime input)+ * @param {string} o.mint the coin being copied+ * @param {import('@solana/web3.js').Connection} o.connection injected RPC+ * @param {{ band?: string }} [o.opts]+ * @returns {Promise<{ linked:boolean, creator:string|null, score:number|null, band:string|null, topSignal:string|null }>}+ */+export async function checkLeaderCreatorLinkage({ leaderWallet, mint, connection, opts = {} }) {+ if (!leaderWallet) return { linked: false, creator: null, score: null, band: null, topSignal: null };++ let creator = null;+ try {+ ({ wallet: creator } = await resolveCreatorWallet(mint));+ } catch {+ return { linked: false, creator: null, score: null, band: null, topSignal: null };+ }+ if (!creator || creator === leaderWallet) {+ return { linked: false, creator, score: null, band: null, topSignal: null };+ }++ try {+ const { analyzeLinkage } = await import('@three-ws/wallet-linkage');+ const { pairs } = await analyzeLinkage(connection, [leaderWallet, creator]);+ return { ...evaluateLeaderCreatorLinkPair(pairs[0] ?? null, opts), creator };+ } catch {+ return { linked: false, creator, score: null, band: null, topSignal: null };+ }+}diff --git a/api/_lib/copy-engine.js b/api/_lib/copy-engine.jsindex 8008a76a7..55e73f572 100644--- a/api/_lib/copy-engine.js+++ b/api/_lib/copy-engine.js@@ -141,7 +141,7 @@ export function rawOrderSol(sub, { leaderEntrySol = 0, copierBalanceSol = null }* @param {object} p* @param {object} p.subscription normalized subscription row.* @param {object} p.position triggering agent_sniper_positions row (entry_sol, mint, direction…).- * @param {object} [p.coin] coin context: { market_cap_usd, dev_holding_pct, liquidity_usd, honeypot, graduated }.+ * @param {object} [p.coin] coin context: { market_cap_usd, dev_holding_pct, liquidity_usd, honeypot, graduated, leader_linked_to_creator }.* @param {number} [p.copierBalanceSol] copier's spendable SOL (required only for pct_balance sizing).* @param {number} [p.spentTodaySol] SOL already fanned out for this sub today.* @param {number} [p.openCopies] copier's current pending intents on this sub.@@ -194,6 +194,13 @@ export function evaluateSafety(sub, coin) {: { ok: true };}if (coin.honeypot === true) return { ok: false, reason: 'honeypot', detail: 'Coin flagged as a honeypot (sells blocked).' };+ if (coin.leader_linked_to_creator === true) {+ return {+ ok: false,+ reason: 'leader_linked_to_creator',+ detail: "This leader's wallet appears linked to this coin's creator (shared fee payer or first funder), so copying would mirror the creator's own buy, not an independent trade.",+ };+ }const mcap = n(coin.market_cap_usd);if (sub.mcap_floor_usd != null && mcap > 0 && mcap < sub.mcap_floor_usd) {diff --git a/api/cron/copy-fanout.js b/api/cron/copy-fanout.jsindex b9294cff4..30fdd1831 100644--- a/api/cron/copy-fanout.js+++ b/api/cron/copy-fanout.js@@ -25,6 +25,15 @@// Subscribing to your own agent is refused at the endpoint; this catches any// row that predates that rule, so a wash-trade loop cannot keep firing.//+// A third guard runs per (leader, mint) rather than per subscription, inside the+// coin-safety gate itself (api/_lib/copy-engine.js's evaluateSafety):+// • CREATOR-LINKED LEADER: if the leader's own trading wallet scores as the+// same controller as the coin's creator (api/_lib/copy-eligibility.js's+// checkLeaderCreatorLinkage, backed by @three-ws/wallet-linkage), every+// follower's intent on that trade is skipped with skip_reason+// 'leader_linked_to_creator' instead of sized: copying it would just mirror+// the creator's own buy of their own launch.+//// Idempotent via partial unique indexes:// (subscription_id, leader_position_id, direction) when leader_position_id is not null// (subscription_id, leader_oracle_action_id, direction) when leader_oracle_action_id is not null@@ -32,7 +41,8 @@import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { planCopyOrder } from '../_lib/copy-engine.js';-import { BREAKER_REASON, evaluateDrawdownBreaker, leaderDrawdownPcts } from '../_lib/copy-eligibility.js';+import { BREAKER_REASON, evaluateDrawdownBreaker, leaderDrawdownPcts, checkLeaderCreatorLinkage } from '../_lib/copy-eligibility.js';+import { getConnection } from '../_lib/pump.js';import { loadDripConfigs, newTierCache, priceRelease, releaseDueDrips } from '../_lib/copy-drip-runtime.js';import { requireCron } from '../_lib/cron-auth.js';import { pumpFetchJson, PUMP_FRONTEND_BASE } from '../_lib/pump-feed-fetch.js';@@ -114,6 +124,28 @@ async function coinContext(mint, oracleScore) {return oracleScore != null ? { ...(ctx || {}), oracle_score: oracleScore } : ctx;}+// Is this leader's trading wallet the coin's creator in disguise? Checked once+// per (agent, mint) per tick, not once per copier: a leader with a thousand+// followers must not cost a thousand linkage calls. `leaderWallet` comes off+// the already-fetched subscription rows (denormalized at subscribe time), so+// this adds no extra query, only the one wallet-linkage RPC scoring pass.+const _creatorLinkCache = new Map();+async function creatorLinkedToCreator(agentId, mint, leaderWallet, network) {+ if (!leaderWallet) return false;+ const key = `${network}:${agentId}:${mint}`;+ if (_creatorLinkCache.has(key)) return _creatorLinkCache.get(key);+ let linked = false;+ try {+ const connection = getConnection({ network });+ const verdict = await checkLeaderCreatorLinkage({ leaderWallet, mint, connection });+ linked = verdict.linked === true;+ } catch {+ linked = false;+ }+ _creatorLinkCache.set(key, linked);+ return linked;+}+// Fetch the latest Oracle conviction score for a mint from the DB. Returns null// if unscored. Called in the sniper fanout path (Oracle fanout has the score inline).const _oracleScoreCache = new Map();@@ -255,7 +287,10 @@ async function fanoutBuys(network, stats) {const subs = subsByLeader.get(pos.agent_id) || [];if (!subs.length) continue;const score = await oracleScore(pos.mint, network);- const coin = await coinContext(pos.mint, score);+ let coin = await coinContext(pos.mint, score);+ if (await creatorLinkedToCreator(pos.agent_id, pos.mint, subs[0]?.leader_wallet, network)) {+ coin = { ...(coin || {}), leader_linked_to_creator: true };+ }const entrySol = lamToSol(pos.entry_quote_lamports);for (const sub of subs) {@@ -426,7 +461,10 @@ async function fanoutOracleBuys(network, stats) {const subs = subsByLeader.get(action.agent_id) || [];if (!subs.length) continue;// Oracle action has conviction inline — no DB lookup needed.- const coin = await coinContext(action.mint, action.conviction != null ? Number(action.conviction) : null);+ let coin = await coinContext(action.mint, action.conviction != null ? Number(action.conviction) : null);+ if (await creatorLinkedToCreator(action.agent_id, action.mint, subs[0]?.leader_wallet, network)) {+ coin = { ...(coin || {}), leader_linked_to_creator: true };+ }const entrySol = Number(action.size_sol) || 0;for (const sub of subs) {diff --git a/tests/copy-eligibility.test.js b/tests/copy-eligibility.test.jsindex f4b918ec6..05cf18a14 100644--- a/tests/copy-eligibility.test.js+++ b/tests/copy-eligibility.test.js@@ -7,12 +7,33 @@* endpoint that enforces them.*/-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';++// Synthetic addresses only, no real wallets. `resolveCreatorWallet` and+// `analyzeLinkage` are mocked below so `checkLeaderCreatorLinkage` is tested as+// pure orchestration, with no DB or RPC involved.+const LEADER = 'Leader1111111111111111111111111111111111111';+const CREATOR = 'Creator11111111111111111111111111111111111';++const H = vi.hoisted(() => ({ creatorWallet: null, pair: null, analyzeThrows: false }));+vi.mock('../api/_lib/cosmetics-economy.js', () => ({+ resolveCreatorWallet: async () => ({ wallet: H.creatorWallet, source: H.creatorWallet ? 'coin_launches' : 'none' }),+}));+vi.mock('@three-ws/wallet-linkage', () => ({+ analyzeLinkage: async (_connection, addresses) => {+ if (H.analyzeThrows) throw new Error('rpc unavailable');+ return { addresses, pairs: H.pair ? [H.pair] : [], complete: true };+ },+}));+import {BREAKER_REASON,LEADER_ELIGIBILITY,+ CREATOR_LINK_REASON,evaluateDrawdownBreaker,evaluateLeaderEligibility,+ evaluateLeaderCreatorLinkPair,+ checkLeaderCreatorLinkage,summarizeCopyProfile,} from '../api/_lib/copy-eligibility.js';@@ -157,3 +178,71 @@ describe('summarizeCopyProfile: the equity curve both defenses read', () => {expect(p.span_hours).toBe(90);});});++describe('evaluateLeaderCreatorLinkPair (pure band decision)', () => {+ it('treats a missing pair as not linked', () => {+ expect(evaluateLeaderCreatorLinkPair(null)).toEqual({ linked: false, score: null, band: null, topSignal: null });+ });+ it('trips at the default "strong" band', () => {+ expect(evaluateLeaderCreatorLinkPair({ score: 70, band: 'strong', topSignal: 'solana-fee-payer' }).linked).toBe(true);+ expect(evaluateLeaderCreatorLinkPair({ score: 90, band: 'confirmed', topSignal: 'solana-fee-payer' }).linked).toBe(true);+ });+ it('does not trip below the default band', () => {+ expect(evaluateLeaderCreatorLinkPair({ score: 30, band: 'weak', topSignal: 'direct-transfer' }).linked).toBe(false);+ expect(evaluateLeaderCreatorLinkPair({ score: 0, band: 'none', topSignal: null }).linked).toBe(false);+ });+ it('honors a custom band threshold', () => {+ const pair = { score: 30, band: 'weak', topSignal: 'direct-transfer' };+ expect(evaluateLeaderCreatorLinkPair(pair).linked).toBe(false);+ expect(evaluateLeaderCreatorLinkPair(pair, { band: 'weak' }).linked).toBe(true);+ });+});++describe('checkLeaderCreatorLinkage (refuse a leader who is secretly the creator)', () => {+ it('is not linked when the leader has no known trading wallet', async () => {+ const r = await checkLeaderCreatorLinkage({ leaderWallet: null, mint: 'Mint111', connection: {} });+ expect(r.linked).toBe(false);+ });++ it('is not linked when the coin has no resolvable creator', async () => {+ H.creatorWallet = null;+ const r = await checkLeaderCreatorLinkage({ leaderWallet: LEADER, mint: 'Mint111', connection: {} });+ expect(r.linked).toBe(false);+ expect(r.creator).toBeNull();+ });++ it('is not linked when the leader IS the on-record creator (nothing to detect, no RPC call needed)', async () => {+ H.creatorWallet = LEADER;+ const r = await checkLeaderCreatorLinkage({ leaderWallet: LEADER, mint: 'Mint111', connection: {} });+ expect(r.linked).toBe(false);+ });++ it('refuses a leader whose wallet scores as the same controller as the creator', async () => {+ H.creatorWallet = CREATOR;+ H.pair = { a: LEADER, b: CREATOR, score: 92, band: 'confirmed', topSignal: 'solana-fee-payer' };+ const r = await checkLeaderCreatorLinkage({ leaderWallet: LEADER, mint: 'Mint111', connection: {} });+ expect(r.linked).toBe(true);+ expect(r.creator).toBe(CREATOR);+ expect(r.score).toBe(92);+ expect(r.topSignal).toBe('solana-fee-payer');+ });++ it('is not linked when the score falls below the warn band', async () => {+ H.creatorWallet = CREATOR;+ H.pair = { a: LEADER, b: CREATOR, score: 10, band: 'weak', topSignal: 'direct-transfer' };+ const r = await checkLeaderCreatorLinkage({ leaderWallet: LEADER, mint: 'Mint111', connection: {} });+ expect(r.linked).toBe(false);+ });++ it('fails closed (not linked) when the linkage scorer errors, never blocking on a data outage', async () => {+ H.creatorWallet = CREATOR;+ H.analyzeThrows = true;+ const r = await checkLeaderCreatorLinkage({ leaderWallet: LEADER, mint: 'Mint111', connection: {} });+ expect(r.linked).toBe(false);+ H.analyzeThrows = false;+ });++ it('exports a stable machine reason for the follower-facing skip', () => {+ expect(CREATOR_LINK_REASON).toBe('leader_linked_to_creator');+ });+});diff --git a/tests/copy-engine.test.js b/tests/copy-engine.test.jsindex a04f48854..c700423f5 100644--- a/tests/copy-engine.test.js+++ b/tests/copy-engine.test.js@@ -127,6 +127,21 @@ describe('evaluateSafety / planCopyOrder safety gate', () => {expect(d.action).toBe('skip');expect(d.reason).toBe('honeypot');});+ it('blocks a leader wallet linked to the coin creator', () => {+ const r = evaluateSafety(baseSub, { leader_linked_to_creator: true });+ expect(r.ok).toBe(false);+ expect(r.reason).toBe('leader_linked_to_creator');+ expect(r.detail).toMatch(/creator/i);+ });+ it('a buy mirroring a creator-linked leader is skipped end-to-end, even with require_safety_pass off', () => {+ const d = planCopyOrder({+ subscription: baseSub,+ position: buy(1),+ coin: { market_cap_usd: 30000, leader_linked_to_creator: true },+ });+ expect(d.action).toBe('skip');+ expect(d.reason).toBe('leader_linked_to_creator');+ });});describe('normalizeSubscriptionInput', () => {