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(pump): attribute GitHub fee-PDA claims to a coin, or say plainly it cannot
nirholas1bade5e2faa9
diff --git a/api/_lib/pump-claims-attribution.js b/api/_lib/pump-claims-attribution.jsnew file mode 100644index 000000000..f549dd228--- /dev/null+++ b/api/_lib/pump-claims-attribution.js@@ -0,0 +1,255 @@+// pump-claims-attribution.js+// --------------------------+// Which coin a GitHub social-fee-PDA withdrawal belongs to, and whether the+// claim should be held for review.+//+// A claim_social_fee_pda transaction pays a GitHub identity's fee PDA; it does+// not by itself name the coin, because one PDA can be a shareholder on more+// than one SharingConfig (a scam vector: paste the same PDA into a copycat+// coin's metadata). Two rules attribute a withdrawal to a specific mint, in+// order of strength:+//+// 1. same_transaction_distribution: the claim transaction itself carries a+// DistributeCreatorFeesEvent that pays this exact PDA. Strongest -- the+// payout and the attribution are in the same atomic transaction.+// 2. pda_history_distribution: no distribution rode along with this claim,+// but the PDA's own transaction history since its previous claim shows+// one coin paid at least 90% of what was withdrawn. Ported from the+// owner's pumpfun-github-claims bot (src/claim-monitor.ts).+//+// A withdrawal that matches neither rule is NOT attributed to any coin: the+// claim is real (the GitHub identity really pulled fees out of the vault),+// but which coin paid them is unproven, so the feed must say so rather than+// guess from the highest-market-cap candidate.+//+// Impersonation is a separate, additive gate: even an attributed claim gets+// held for review when a brand-new GitHub account claims fees from a+// same-name copy of a much larger coin, or from a repo created right before+// the claim -- the signature of "register a lookalike account, push a repo,+// put it in a copycat coin's metadata, claim its delegated fees" (see+// `assessImpersonation`).++/** A distribution with no V2 quote_mint, or the system id, was paid in SOL. */+const WSOL_MINT = 'So11111111111111111111111111111111111111112';+const SOL_QUOTE_ALIASES = new Set([WSOL_MINT, '11111111111111111111111111111111']);++function sameQuote(a, b) {+ const norm = (m) => (!m || SOL_QUOTE_ALIASES.has(m) ? WSOL_MINT : m);+ return norm(a) === norm(b);+}++/**+ * Evidence from a distribution paid to this PDA inside the claim's own+ * transaction. One entry per mint that distributed to the PDA in this tx (a+ * transaction can carry more than one distribution when the PDA earns from+ * more than one coin and both get swept together).+ * @param {Array<{mint:string, sharingConfig:string, shareholders:Array<{address:string,shareBps:number}>, distributedRaw:string, quoteMint?:string}>} distributions+ * @param {string} socialFeePda+ * @returns {Array<{mint:string, sharingConfig:string, shareBps:number, distributedRaw:string, recipientAmountRaw:string, quoteMint?:string, source:'same_transaction_distribution'}>}+ */+export function evidenceForSocialFeePda(distributions, socialFeePda) {+ if (!socialFeePda) return [];+ const byMint = new Map();+ for (const distribution of distributions) {+ const shareholder = distribution.shareholders.find((s) => s.address === socialFeePda);+ if (!shareholder || shareholder.shareBps <= 0) continue;+ const distributedRaw = BigInt(distribution.distributedRaw);+ const recipientAmountRaw = (distributedRaw * BigInt(shareholder.shareBps)) / 10_000n;+ byMint.set(distribution.mint, {+ mint: distribution.mint,+ sharingConfig: distribution.sharingConfig,+ shareBps: shareholder.shareBps,+ distributedRaw: distributedRaw.toString(),+ recipientAmountRaw: recipientAmountRaw.toString(),+ quoteMint: distribution.quoteMint,+ source: 'same_transaction_distribution',+ });+ }+ return [...byMint.values()];+}++/** A distribution that pays this PDA must hold at least this share of the withdrawal. */+export const HISTORY_DOMINANT_SHARE_BPS = 9_000n;++/**+ * Attribute a withdrawal from the distributions that filled the PDA since its+ * previous claim. Only the claim's own quote currency counts. The result is a+ * single mint or nothing: the observed distributions must cover at least 90%+ * of the amount withdrawn (so history the lookback did not reach cannot hide a+ * different coin), and one mint must account for at least 90% of that.+ * @param {Array<{mint:string, sharingConfig:string, shareholders:Array<{address:string,shareBps:number}>, distributedRaw:string, quoteMint?:string}>} distributions+ * @param {string} socialFeePda+ * @param {bigint} claimedRaw+ * @param {string} [claimQuoteMint]+ */+export function evidenceFromPdaHistory(distributions, socialFeePda, claimedRaw, claimQuoteMint) {+ if (claimedRaw <= 0n) return [];+ const byMint = new Map();+ let total = 0n;+ for (const distribution of distributions) {+ if (!sameQuote(distribution.quoteMint, claimQuoteMint)) continue;+ const shareholder = distribution.shareholders.find((s) => s.address === socialFeePda);+ if (!shareholder || shareholder.shareBps <= 0) continue;+ const distributedRaw = BigInt(distribution.distributedRaw);+ const raw = (distributedRaw * BigInt(shareholder.shareBps)) / 10_000n;+ if (raw === 0n) continue;+ total += raw;+ const prev = byMint.get(distribution.mint);+ byMint.set(distribution.mint, { raw: (prev?.raw ?? 0n) + raw, last: distribution, bps: shareholder.shareBps });+ }+ if (total * 10_000n < claimedRaw * HISTORY_DOMINANT_SHARE_BPS) return [];+ const [top] = [...byMint.entries()].sort((a, b) => (b[1].raw > a[1].raw ? 1 : b[1].raw < a[1].raw ? -1 : 0));+ if (!top || top[1].raw * 10_000n < total * HISTORY_DOMINANT_SHARE_BPS) return [];+ const [mint, { raw, last, bps }] = top;+ return [+ {+ mint,+ sharingConfig: last.sharingConfig,+ shareBps: bps,+ distributedRaw: total.toString(),+ recipientAmountRaw: raw.toString(),+ quoteMint: last.quoteMint,+ source: 'pda_history_distribution',+ },+ ];+}++// ============================================================================+// Attribution labels+// ============================================================================++export const ATTRIBUTION_LABELS = Object.freeze({+ TRANSACTION_ATTRIBUTED: 'transaction_attributed',+ FEE_HISTORY_ATTRIBUTED: 'fee_history_attributed',+ VERIFIED_REPOSITORY: 'verified_repository',+ VERIFIED_CREATOR_WALLET: 'verified_creator_wallet',+ IDENTITY_MISMATCH: 'identity_mismatch',+ UNRESOLVED_POOLED: 'unresolved_pooled',+ UNVERIFIED: 'unverified',+});++/**+ * Classify only the relationship a claim can actually prove. A successful+ * GitHub-PDA withdrawal proves a payment to a GitHub identity; it does not by+ * itself prove that identity created, owns, or endorses a particular coin.+ * @param {{+ * evidence?: {source:'same_transaction_distribution'|'pda_history_distribution'}|null,+ * candidateMintCount?: number,+ * githubLogin?: string|null,+ * githubRepoOwner?: string|null,+ * claimerWallet?: string|null,+ * tokenCreatorWallet?: string|null,+ * }} ctx+ */+export function classifyClaimAttribution(ctx) {+ const { evidence, candidateMintCount = 0, githubLogin, githubRepoOwner, claimerWallet, tokenCreatorWallet } = ctx;++ if (evidence) {+ if (evidence.source === 'pda_history_distribution') {+ return {+ label: ATTRIBUTION_LABELS.FEE_HISTORY_ATTRIBUTED,+ headline: 'FEE-HISTORY-ATTRIBUTED GITHUB FEE CLAIM',+ explanation:+ 'This coin paid at least 90% of the fees withdrawn, in distributions to this exact GitHub fee account since its previous claim.',+ };+ }+ return {+ label: ATTRIBUTION_LABELS.TRANSACTION_ATTRIBUTED,+ headline: 'TRANSACTION-ATTRIBUTED GITHUB FEE CLAIM',+ explanation: 'This transaction distributed fees from this exact coin to the claimed GitHub fee account.',+ };+ }++ if (candidateMintCount > 1) {+ return {+ label: ATTRIBUTION_LABELS.UNRESOLVED_POOLED,+ headline: 'UNRESOLVED POOLED GITHUB FEE WITHDRAWAL',+ explanation: `One shared fee account is linked to ${candidateMintCount} coins. This withdrawal cannot be assigned to one CA.`,+ };+ }++ const claimer = githubLogin ? githubLogin.toLowerCase() : null;+ const owner = githubRepoOwner ? githubRepoOwner.toLowerCase() : null;+ if (claimer && owner && owner !== claimer) {+ return {+ label: ATTRIBUTION_LABELS.IDENTITY_MISMATCH,+ headline: 'IDENTITY MISMATCH, GITHUB FEE WITHDRAWAL',+ explanation: `The claiming GitHub account is not the owner linked in the token metadata (${owner}).`,+ };+ }+ if (claimer && owner && owner === claimer) {+ return {+ label: ATTRIBUTION_LABELS.VERIFIED_REPOSITORY,+ headline: 'VERIFIED GITHUB FEE CLAIM',+ explanation: 'The claiming GitHub identity matches the repository owner linked in the token metadata.',+ };+ }++ if (claimerWallet && tokenCreatorWallet && claimerWallet === tokenCreatorWallet) {+ return {+ label: ATTRIBUTION_LABELS.VERIFIED_CREATOR_WALLET,+ headline: 'CREATOR-WALLET GITHUB FEE CLAIM',+ explanation: 'The claim recipient matches the token creator wallet. No repository-owner match was established.',+ };+ }++ return {+ label: ATTRIBUTION_LABELS.UNVERIFIED,+ headline: 'UNVERIFIED GITHUB FEE WITHDRAWAL',+ explanation: 'A real fee withdrawal occurred, but it does not prove this GitHub user created or endorses the coin.',+ };+}++// ============================================================================+// Impersonation gate+// ============================================================================++/**+ * A repository-owner match is circular when the claimer controls both sides:+ * anyone can register a lookalike GitHub account, push a repo, put that repo+ * in a copycat coin's metadata, delegate the coin's fees to the account and+ * claim them. A young account alone is not suspicious, and neither is a+ * same-name coin; the combination is the scam's signature, so both must hold+ * before a claim is held.+ */+export const NEW_ACCOUNT_DAYS = 30;+/** A repo created this close to the claim was likely made for the coin. */+export const FRESH_REPO_DAYS = 7;+/** A same-name coin this many times larger marks this one as the copy. */+export const COPYCAT_MCAP_RATIO = 1.5;++const DAY_MS = 86_400_000;++function ageDays(iso, nowMs) {+ if (!iso) return null;+ const t = new Date(iso).getTime();+ return Number.isFinite(t) ? (nowMs - t) / DAY_MS : null;+}++/**+ * @param {{+ * githubUser?: {createdAt?:string}|null,+ * tokenInfo?: {usdMarketCap?:number}|null,+ * sameNameTokens?: Array<{mint:string, usdMarketCap:number}>|null,+ * repoInfo?: {createdAt?:string}|null,+ * }} input+ * @param {number} [nowMs]+ * @returns {{suspected: boolean, reasons: string[]}}+ */+export function assessImpersonation(input, nowMs = Date.now()) {+ const accountAge = ageDays(input.githubUser?.createdAt, nowMs);+ if (accountAge == null || accountAge >= NEW_ACCOUNT_DAYS) return { suspected: false, reasons: [] };++ const reasons = [`GitHub account ${Math.floor(accountAge)}d old`];+ const top = input.sameNameTokens?.[0];+ const copycat = Boolean(+ top && input.tokenInfo && top.usdMarketCap > input.tokenInfo.usdMarketCap * COPYCAT_MCAP_RATIO,+ );+ if (copycat) reasons.push(`same-name coin ${top.mint.slice(0, 6)} is larger ($${Math.round(top.usdMarketCap)})`);++ const repoAge = ageDays(input.repoInfo?.createdAt, nowMs);+ const freshRepo = repoAge != null && repoAge < FRESH_REPO_DAYS;+ if (freshRepo) reasons.push(`metadata repo ${Math.floor(repoAge)}d old`);++ return { suspected: copycat || freshRepo, reasons };+}diff --git a/api/_lib/pump-claims-github.js b/api/_lib/pump-claims-github.jsnew file mode 100644index 000000000..48c573a1d--- /dev/null+++ b/api/_lib/pump-claims-github.js@@ -0,0 +1,159 @@+// pump-claims-github.js+// ---------------------+// GitHub identity and token-metadata lookups for GitHub fee-claim attribution+// (api/_lib/pump-claims-attribution.js, api/_lib/pump-claims.js). Every call+// hits the real GitHub REST API and pump.fun's public coin API; nothing here+// is mocked or cached to disk. Uses the key-optional pattern already used for+// anonymous GitHub reads elsewhere in this codebase (github-trending.js,+// commit-feed-push.js): a token raises the rate limit but is never required.++import { searchPumpTokens } from './pump-search.js';++const GITHUB_API = 'https://api.github.com';+const PUMPFUN_COIN_API = 'https://frontend-api-v3.pump.fun/coins-v2';+const CACHE_TTL_MS = 10 * 60_000;++function githubHeaders() {+ const headers = { accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28' };+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;+ if (token) headers.authorization = `Bearer ${token}`;+ return headers;+}++const userByIdCache = new Map();+const repoCache = new Map();++function cached(cache, key) {+ const hit = cache.get(key);+ if (!hit) return undefined;+ if (Date.now() > hit.expiresAt) {+ cache.delete(key);+ return undefined;+ }+ return hit.value;+}++function setCached(cache, key, value, ttlMs = CACHE_TTL_MS) {+ cache.set(key, { value, expiresAt: Date.now() + ttlMs });+ if (cache.size > 500) {+ const now = Date.now();+ for (const [k, v] of cache) if (now > v.expiresAt) cache.delete(k);+ }+}++async function githubGet(path) {+ try {+ const resp = await fetch(`${GITHUB_API}${path}`, { headers: githubHeaders(), signal: AbortSignal.timeout(8000) });+ if (!resp.ok) return null;+ return await resp.json();+ } catch {+ return null;+ }+}++/**+ * Resolve a numeric GitHub user id to its login and account age. The REST API+ * has no direct "get user by numeric id" route for anonymous callers, so this+ * walks the public user list starting just below the id (the same resolution+ * the owner's pumpfun-github-claims bot uses) and confirms the exact id match.+ * @param {string} userId+ * @returns {Promise<{login:string, createdAt:string}|null>}+ */+export async function resolveGithubUserById(userId) {+ const cacheKey = String(userId);+ const hit = cached(userByIdCache, cacheKey);+ if (hit !== undefined) return hit;++ const numId = Number(userId);+ let result = null;+ if (Number.isInteger(numId) && numId > 0) {+ const since = Math.max(0, numId - 1);+ const list = await githubGet(`/users?since=${since}&per_page=20`);+ const match = Array.isArray(list) ? list.find((u) => Number(u.id) === numId) : null;+ if (match?.login) {+ const profile = await githubGet(`/users/${encodeURIComponent(match.login)}`);+ if (profile) result = { login: String(profile.login), createdAt: String(profile.created_at || '') };+ }+ }+ setCached(userByIdCache, cacheKey, result, result ? CACHE_TTL_MS : 30_000);+ return result;+}++const GITHUB_URL_RE = /https?:\/\/github\.com\/([a-z0-9-]+)\/([a-z0-9._-]+)/gi;++/** Every distinct owner/repo pair named in free text (description, website, socials). */+export function extractGithubRepoRefs(text) {+ const out = [];+ const seen = new Set();+ for (const match of String(text || '').matchAll(GITHUB_URL_RE)) {+ const owner = match[1];+ const repo = match[2].replace(/\.git$/i, '');+ const key = `${owner}/${repo}`.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ out.push({ owner, repo });+ }+ return out;+}++/**+ * The repository owner and creation date for the first GitHub repo linked in+ * a coin's metadata (description, website, or socials), plus the coin's+ * creator wallet, display name, and USD market cap for the impersonation+ * check. Returns a partial object (all fields optional) rather than null, so+ * a coin with some fields resolvable still contributes evidence.+ * @param {string} mint+ */+export async function resolveCoinGithubContext(mint) {+ let coin;+ try {+ const resp = await fetch(`${PUMPFUN_COIN_API}/${encodeURIComponent(mint)}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(7000),+ });+ coin = resp.ok ? await resp.json() : null;+ } catch {+ coin = null;+ }+ if (!coin) return {};++ const text = [coin.description, coin.website, coin.twitter, coin.telegram, coin.metadata_uri]+ .filter(Boolean)+ .join(' ');+ const refs = extractGithubRepoRefs(text);+ const [ref] = refs;+ const out = {+ creatorWallet: coin.creator ? String(coin.creator) : undefined,+ tokenName: coin.name ? String(coin.name) : undefined,+ usdMarketCap: typeof coin.usd_market_cap === 'number' ? coin.usd_market_cap : undefined,+ };+ if (!ref) return out;++ const cacheKey = `${ref.owner}/${ref.repo}`.toLowerCase();+ let repo = cached(repoCache, cacheKey);+ if (repo === undefined) {+ const raw = await githubGet(`/repos/${encodeURIComponent(ref.owner)}/${encodeURIComponent(ref.repo)}`);+ repo = raw ? { owner: String(raw.owner?.login || ref.owner), createdAt: String(raw.created_at || '') } : null;+ setCached(repoCache, cacheKey, repo);+ }+ if (repo) {+ out.repoOwner = repo.owner;+ out.repoCreatedAt = repo.createdAt;+ }+ return out;+}++/**+ * Other coins sharing a name, largest market cap first, for the impersonation+ * copycat check. Excludes the mint being evaluated.+ * @param {string} name+ * @param {string} excludeMint+ */+export async function resolveSameNameTokens(name, excludeMint) {+ if (!name) return [];+ const matches = await searchPumpTokens(name, 10);+ return matches+ .filter((t) => t.mint !== excludeMint && typeof t.usd_market_cap === 'number')+ .map((t) => ({ mint: t.mint, usdMarketCap: t.usd_market_cap }))+ .sort((a, b) => b.usdMarketCap - a.usdMarketCap);+}diff --git a/api/_lib/pump-claims-push.js b/api/_lib/pump-claims-push.jsindex 50a209f98..1a35a8dca 100644--- a/api/_lib/pump-claims-push.js+++ b/api/_lib/pump-claims-push.js@@ -15,7 +15,7 @@// audience. An unset chat id reports { skipped: 'not_configured' }.//// State (app_settings key `pump_claims_push_telegram`):-// { lastTs: number|null, seen: string[] }+// { lastTs: number|null, seen: string[], githubSeen: string[] }// `lastTs` is the block time of the newest claim posted; `seen` is a bounded// ring of recently posted transaction signatures. Both are needed because the// two failure modes are different:@@ -26,6 +26,14 @@// 2. `seen` is bounded, so it cannot answer for a claim older than the ring.// `lastTs` bounds the query window so the ring never has to.//+// `githubSeen` is a second, independent dedupe for GitHub fee-PDA claims+// (api/_lib/pump-claims.js's `_fetchGithubClaimsFromRpc`), keyed by GitHub+// user id plus mint rather than by signature: the same GitHub identity can+// submit more than one claim_social_fee_pda transaction against the same coin+// (a sweep followed by a claim, or simply claiming again later), and each has+// its own signature, but the channel should only ever announce that pairing+// once, the way it only announces a wallet's first claim once.+//// On first run (no state) the lane seeds from the current scan WITHOUT posting,// so enabling this feature never dumps a backlog of history into the channel.@@ -111,9 +119,11 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));*/export function newClaimsSince(claims, state = {}, nowMs = Date.now()) {const seen = new Set(state.seen || []);+ const githubSeen = new Set(state.githubSeen || []);const oldestPostableTs = Math.floor(nowMs / 1000) - CUTOFF_MINUTES * 60;return claims.filter((c) => c.signature && !seen.has(c.signature))+ .filter((c) => !c.githubUserId || !githubSeen.has(githubClaimKey(c))).filter((c) => Number.isFinite(c.ts) && c.ts >= oldestPostableTs).sort((a, b) => a.ts - b.ts);}@@ -124,6 +134,18 @@ export function rememberSignatures(seen = [], signatures = []) {return merged.slice(Math.max(0, merged.length - SEEN_LIMIT));}+/** `githubUserId:mint` dedupe key for a GitHub fee-PDA claim. */+export function githubClaimKey(claim) {+ return `${claim.githubUserId}:${claim.mint || ''}`;+}++/** Appends GitHub user+mint keys to the bounded ring, newest kept. */+export function rememberGithubClaims(githubSeen = [], claims = []) {+ const keys = claims.filter((c) => c.githubUserId).map(githubClaimKey);+ const merged = [...githubSeen, ...keys];+ return merged.slice(Math.max(0, merged.length - SEEN_LIMIT));+}+const escapeHtml = (s) =>String(s).replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' })[c]);@@ -148,12 +170,17 @@ export function formatSol(lamports) {// a malformed scan result can never break out of the HTML entity structure and// smuggle a clickable link posted under the platform bot's identity./**- * @param {{creator:string, mint:string, signature:string, lamports:number, ts:number}} claim+ * @param {{creator:string, mint:string, signature:string, lamports:number, ts:number,+ * githubUserId?:string, githubLogin?:string|null, attribution?:{label:string,headline:string,explanation:string},+ * held?:boolean, heldReasons?:string[]}} claim*/export function formatTelegramMessage(claim) {const when = Number.isFinite(claim.ts)? new Date(claim.ts * 1000).toISOString().replace('T', ' ').slice(0, 16) + ' UTC': '';++ if (claim.githubUserId) return formatGithubClaimMessage(claim, when);+const lines = ['<b>First creator fee claim</b>','',@@ -174,6 +201,35 @@ export function formatTelegramMessage(claim) {return lines.join('\n');}+/**+ * A GitHub fee-PDA claim's message, held or attributed. A held claim never+ * gets the celebratory framing above: it states plainly that a withdrawal+ * happened and why it is held, instead of crediting a coin or identity the+ * evidence does not support yet.+ */+function formatGithubClaimMessage(claim, when) {+ const identity = claim.githubLogin ? `github.com/${claim.githubLogin}` : `GitHub id ${claim.githubUserId}`;+ const lines = claim.held+ ? [+ '<b>GitHub fee withdrawal held for review</b>',+ '',+ `Claimant <code>${escapeHtml(identity)}</code>`,+ ...(claim.heldReasons?.length ? [`Held: ${escapeHtml(claim.heldReasons.join('; '))}`] : []),+ ]+ : ['<b>GitHub fee claim</b>', '', `${escapeHtml(claim.attribution?.headline || 'UNVERIFIED GITHUB FEE WITHDRAWAL')}`, '', `Claimant <code>${escapeHtml(identity)}</code>`];++ if (claim.mint) lines.push(`Coin <code>${escapeHtml(claim.mint)}</code>`);+ lines.push('', `Claimed ${escapeHtml(formatSol(claim.lamports))}`);+ if (claim.attribution?.explanation) lines.push('', escapeHtml(claim.attribution.explanation));++ const refs = [+ `<a href="https://solscan.io/tx/${encodeURIComponent(claim.signature)}">tx ${escapeHtml(shortAddress(claim.signature))}</a>`,+ ];+ if (claim.mint) refs.push(`<a href="https://pump.fun/coin/${encodeURIComponent(claim.mint)}">pump.fun</a>`);+ lines.push('', `${refs.join(' · ')}${when ? ` · ${escapeHtml(when)}` : ''}`);+ return lines.join('\n');+}+async function sendTelegram(botToken, chatId, text) {const res = await fetchUpstream(`https://api.telegram.org/bot${botToken}/sendMessage`, {method: 'POST',@@ -202,7 +258,7 @@ export async function pushTelegramLane({ scan = scanFirstClaims, now = Date.nowif (!botToken || !chatId) return { skipped: 'not_configured' };const nowMs = now();- const state = (await getState(STATE_KEY)) || { lastTs: null, seen: [] };+ const state = (await getState(STATE_KEY)) || { lastTs: null, seen: [], githubSeen: [] };// A resumed lane re-scans from its cursor so a gap wider than one window// still resolves, bounded by the cutoff so it can never replay history.const windowStart = Math.floor(nowMs / 1000) - SCAN_MINUTES * 60;@@ -219,6 +275,7 @@ export async function pushTelegramLane({ scan = scanFirstClaims, now = Date.nowawait setState(STATE_KEY, {lastTs: claims.length ? Math.max(...claims.map((c) => c.ts)) : Math.floor(nowMs / 1000),seen: rememberSignatures([], claims.map((c) => c.signature)),+ githubSeen: rememberGithubClaims([], claims),});return { posted: 0, seeded: true, scanned: claims.length };}@@ -237,17 +294,18 @@ export async function pushTelegramLane({ scan = scanFirstClaims, now = Date.now}let sent = 0;- let { lastTs, seen } = state;+ let { lastTs, seen, githubSeen = [] } = state;try {for (const claim of batch) {await sendTelegram(botToken, chatId, formatTelegramMessage(claim));lastTs = Math.max(Number(lastTs) || 0, claim.ts);seen = rememberSignatures(seen, [claim.signature]);+ githubSeen = rememberGithubClaims(githubSeen, [claim]);sent++;// Written per claim, not per run: a tick killed mid-batch (the Cloud// Run request deadline is shorter than a full paced run) resumes at// the next claim rather than repeating the ones already delivered.- await setState(STATE_KEY, { lastTs, seen });+ await setState(STATE_KEY, { lastTs, seen, githubSeen });await sleep(TELEGRAM_PACE_MS);}} catch (err) {diff --git a/api/_lib/pump-claims.js b/api/_lib/pump-claims.jsindex ebfaea76a..c28378191 100644--- a/api/_lib/pump-claims.js+++ b/api/_lib/pump-claims.js@@ -13,13 +13,28 @@* 1. PUMPFUN_BOT_URL (an indexer) when configured — fast, pre-aggregated.* 2. Direct RPC scan of the pump program's recent signatures — always works,* no indexer required.+ *+ * A separate GitHub-fee-claim path (`_fetchGithubClaimsFromRpc`) always runs+ * alongside whichever source above is active: it scans the PumpFees program+ * (`PUMP_FEE_PROGRAM_ID`) for `claim_social_fee_pda` withdrawals, which an+ * indexer built around the main pump program does not see. Each one is+ * attributed to a coin (or left unattributed) by `pump-claims-attribution.js`+ * and checked for impersonation before it is merged into the result.*/import bs58 from 'bs58';import { getConnection } from './pump.js';import { filterFirstClaims } from '../../src/pump/first-claims.js';+import { PUMP_PROGRAM_ID, PUMP_FEE_PROGRAM_ID, WSOL_MINT } from './solana/programs.js';+import {+ isSocialClaimLog,+ parseSocialFeeClaim,+ parseTransactionDistributions,+} from './pump-events.js';+import { evidenceForSocialFeePda, evidenceFromPdaHistory, classifyClaimAttribution, assessImpersonation } from './pump-claims-attribution.js';+import { resolveGithubUserById, resolveCoinGithubContext, resolveSameNameTokens } from './pump-claims-github.js';-const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';+const PUMP_PROGRAM = PUMP_PROGRAM_ID;// Anchor discriminators for the three pump.fun fee-claim instruction variants.const CLAIM_DISCS = new Set(['e8f5c2eeeada3a59', '7a027f010ebf0caf', 'a537817004b3ca28']);// Pull a wider lookback so prior claimers are visible and "first" is real.@@ -30,6 +45,23 @@ const QUOTE_MINTS = new Set(['EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC]);+// GitHub platform id in SharingConfig.shareholder.platform (claim_social_fee_pda's `platform` byte).+const GITHUB_SOCIAL_PLATFORM = 2;+// Per-request budget: each candidate can cost one GitHub user lookup, one coin+// metadata fetch, and (lacking same-transaction evidence) up to HISTORY_MAX_TX+// extra RPC calls walking the PDA's history. This is a live HTTP handler, not+// the owner's long-running claim-monitor bot, so the per-scan candidate count+// is bounded tightly; claim instructions are rare enough (per the RPC-fallback+// limits below) that this still covers a normal scan window in practice.+const GITHUB_CLAIMS_BUDGET = 8;+// Ported from the owner's pumpfun-github-claims bot (src/claim-monitor.ts).+const HISTORY_MAX_TX = 40;+const HISTORY_MAX_AGE_SEC = 7 * 86400;++function isSolQuote(quoteMint) {+ return !quoteMint || quoteMint === WSOL_MINT || quoteMint === '11111111111111111111111111111111';+}+/*** First-time claimers in [sinceTs, now]. Newest first, capped at `limit`.* @param {{ sinceTs: number, limit: number }} opts@@ -39,10 +71,13 @@ export async function scanFirstClaims({ sinceTs, limit }) {const lim = Math.max(1, Math.min(50, limit));const lookbackTs =sinceTs - Math.max(3600, (Math.floor(Date.now() / 1000) - sinceTs) * LOOKBACK_MULT);- const allClaims = process.env.PUMPFUN_BOT_URL- ? await _fetchFromBot(lookbackTs, lim * LOOKBACK_MULT)- : await _fetchFromRpc(lookbackTs, lim * LOOKBACK_MULT);- return filterFirstClaims(allClaims, sinceTs, lim);+ const [baseClaims, githubClaims] = await Promise.all([+ process.env.PUMPFUN_BOT_URL+ ? _fetchFromBot(lookbackTs, lim * LOOKBACK_MULT)+ : _fetchFromRpc(lookbackTs, lim * LOOKBACK_MULT),+ _fetchGithubClaimsFromRpc(lookbackTs),+ ]);+ return filterFirstClaims([...baseClaims, ...githubClaims], sinceTs, lim);}async function _fetchFromBot(lookbackTs, maxItems) {@@ -178,3 +213,143 @@ function _mintFromBalances(tx) {}return null;}++/**+ * GitHub-attributed fee-PDA withdrawals since `lookbackTs`, each already+ * labeled by `pump-claims-attribution.js` and checked for impersonation. One+ * entry per `claim_social_fee_pda` transaction on the PumpFees program whose+ * claimed platform is GitHub (platform id 2); a claim that resolved to no+ * coin at all (see `classifyClaimAttribution`'s `unverified` label) is still+ * included; it just has `mint: ''`, matching the base scanner's shape for an+ * unresolvable coin.+ * @param {number} lookbackTs+ * @returns {Promise<Array>}+ */+async function _fetchGithubClaimsFromRpc(lookbackTs) {+ try {+ const connection = getConnection({ network: 'mainnet' });+ const { PublicKey } = await import('@solana/web3.js');+ const sigs = await connection.getSignaturesForAddress(new PublicKey(PUMP_FEE_PROGRAM_ID), {+ limit: 200,+ });+ const inWindow = sigs.filter((s) => s.blockTime != null && s.blockTime >= lookbackTs && !s.err);+ if (!inWindow.length) return [];++ const out = [];+ for (const s of inWindow) {+ if (out.length >= GITHUB_CLAIMS_BUDGET) break;+ const tx = await connection.getParsedTransaction(s.signature, {+ maxSupportedTransactionVersion: 1,+ commitment: 'confirmed',+ });+ const logs = tx?.meta?.logMessages;+ if (!logs || tx?.meta?.err || !isSocialClaimLog(logs)) continue;+ const claim = parseSocialFeeClaim(logs);+ if (!claim || claim.socialPlatform !== GITHUB_SOCIAL_PLATFORM) continue;+ out.push(await _attributeGithubClaim(connection, claim, s.signature, s.blockTime));+ }+ return out;+ } catch {+ return [];+ }+}++/** Attribute and label one decoded GitHub fee-PDA claim. Never throws. */+async function _attributeGithubClaim(connection, claim, signature, blockTime) {+ const amountClaimedRaw = BigInt(claim.amountClaimedRaw);+ let evidence = null;+ let candidateMintCount = 0;++ try {+ const txLogs = await _logsForSignature(connection, signature);+ const sameTx = evidenceForSocialFeePda(parseTransactionDistributions(txLogs), claim.socialFeePda);+ if (sameTx.length) {+ evidence = sameTx[0];+ candidateMintCount = sameTx.length;+ } else {+ const history = await _pdaHistoryDistributions(connection, claim.socialFeePda, signature, blockTime);+ const historyEvidence = evidenceFromPdaHistory(history, claim.socialFeePda, amountClaimedRaw, claim.quoteMint);+ if (historyEvidence.length) {+ evidence = historyEvidence[0];+ candidateMintCount = 1;+ } else {+ candidateMintCount = new Set(history.map((d) => d.mint)).size;+ }+ }+ } catch {+ // Attribution evidence is best-effort; an RPC failure here still leaves+ // a real, unattributed claim worth reporting rather than dropping it.+ }++ const mint = evidence?.mint || '';+ const [githubUser, coinCtx] = await Promise.all([+ resolveGithubUserById(claim.githubUserId).catch(() => null),+ mint ? resolveCoinGithubContext(mint).catch(() => ({})) : Promise.resolve({}),+ ]);++ const classification = classifyClaimAttribution({+ evidence,+ candidateMintCount,+ githubLogin: githubUser?.login || null,+ githubRepoOwner: coinCtx.repoOwner || null,+ claimerWallet: claim.recipient,+ tokenCreatorWallet: coinCtx.creatorWallet || null,+ });++ const sameNameTokens = mint && coinCtx.tokenName ? await resolveSameNameTokens(coinCtx.tokenName, mint).catch(() => []) : [];+ const impersonation = assessImpersonation({+ githubUser,+ tokenInfo: coinCtx.usdMarketCap != null ? { usdMarketCap: coinCtx.usdMarketCap } : null,+ sameNameTokens,+ repoInfo: coinCtx.repoCreatedAt ? { createdAt: coinCtx.repoCreatedAt } : null,+ });++ return {+ creator: claim.recipient,+ mint,+ signature,+ lamports: isSolQuote(claim.quoteMint) ? Number(amountClaimedRaw) : 0,+ ts: blockTime ?? 0,+ source: 'github_fee_claim',+ githubUserId: claim.githubUserId,+ githubLogin: githubUser?.login || null,+ quoteMint: claim.quoteMint || null,+ amountRaw: claim.amountClaimedRaw,+ attribution: classification,+ held: impersonation.suspected,+ heldReasons: impersonation.reasons,+ };+}++async function _logsForSignature(connection, signature) {+ const tx = await connection.getParsedTransaction(signature, {+ maxSupportedTransactionVersion: 1,+ commitment: 'confirmed',+ });+ return tx?.meta?.logMessages || [];+}++/**+ * Every DistributeCreatorFeesEvent paid to `socialFeePda` since its previous+ * claim, oldest work first. Walks the PDA's own signature history backward+ * from just before `beforeSignature`, stopping at whichever bound is hit+ * first: the previous `claim_social_fee_pda` on this PDA, `HISTORY_MAX_TX`+ * transactions, or `HISTORY_MAX_AGE_SEC` of age.+ */+async function _pdaHistoryDistributions(connection, socialFeePda, beforeSignature, claimBlockTime) {+ const { PublicKey } = await import('@solana/web3.js');+ const sigs = await connection.getSignaturesForAddress(new PublicKey(socialFeePda), {+ limit: HISTORY_MAX_TX,+ before: beforeSignature,+ });+ const minTs = (claimBlockTime || Math.floor(Date.now() / 1000)) - HISTORY_MAX_AGE_SEC;+ const distributions = [];+ for (const s of sigs) {+ if (s.err || s.blockTime == null || s.blockTime < minTs) continue;+ const logs = await _logsForSignature(connection, s.signature);+ if (!logs.length) continue;+ if (isSocialClaimLog(logs)) break; // the previous claim on this PDA: stop here+ distributions.push(...parseTransactionDistributions(logs));+ }+ return distributions;+}diff --git a/api/_lib/pump-events.js b/api/_lib/pump-events.jsnew file mode 100644index 000000000..da732864d--- /dev/null+++ b/api/_lib/pump-events.js@@ -0,0 +1,91 @@+// pump-events.js+// --------------+// Shared Pump / PumpSwap / PumpFees log decoder.+//+// Wraps the installed @nirholas/pump-sdk's Anchor-IDL-driven decoder+// (parsePumpEventsFromLogs) so every caller that needs typed on-chain events+// -- creates, trades, completions, fee collections, fee distributions, and+// GitHub social-fee claims -- reads them the same way instead of hand-rolling+// Borsh offsets per caller. The SDK keys off the invoking program in the log+// stack (Pump, PumpSwap, or PumpFees) and returns each event as+// `{ type, data }`, with the Anchor event name camel-cased and its trailing+// "Event" stripped (e.g. "DistributeCreatorFeesEvent" decodes as+// `type: "distributeCreatorFees"`). Numeric fields decode as BN; the+// normalising helpers below convert the ones this codebase consumes to plain+// strings so attribution math can use BigInt directly.++import { parsePumpEventsFromLogs } from '@nirholas/pump-sdk';++/** Every decodable event in a transaction's logs, oldest first. Never throws. */+export function parseEventsFromLogs(logs) {+ if (!Array.isArray(logs) || logs.length === 0) return [];+ try {+ return parsePumpEventsFromLogs(logs) || [];+ } catch {+ return [];+ }+}++function eventsOfType(logs, type) {+ return parseEventsFromLogs(logs).filter((e) => e?.type === type);+}++export const getCreateEvents = (logs) => eventsOfType(logs, 'create');+export const getTradeEvents = (logs) => eventsOfType(logs, 'trade');+export const getCompleteEvents = (logs) => eventsOfType(logs, 'complete');+export const getCollectCreatorFeeEvents = (logs) => eventsOfType(logs, 'collectCreatorFee');+export const getDistributeCreatorFeesEvents = (logs) => eventsOfType(logs, 'distributeCreatorFees');+export const getSocialFeePdaClaimedEvents = (logs) => eventsOfType(logs, 'socialFeePdaClaimed');++/**+ * Every DistributeCreatorFeesEvent in a transaction's logs, normalised to+ * plain values. This is the event the fee-sharing program emits whenever a+ * coin's creator fees are split between its shareholders (which includes a+ * GitHub social-fee PDA, when the coin delegates fees to one) -- the event+ * both attribution rules below are built on.+ * @param {string[]} logs+ * @returns {Array<{mint:string, sharingConfig:string, shareholders:Array<{address:string,shareBps:number}>, distributedRaw:string, quoteMint?:string}>}+ */+/** The SDK decodes Anchor `pubkey` fields as PublicKey instances; base58-stringify, or pass through nullish. */+function pubkeyString(v) {+ return v == null ? v : v.toString();+}++export function parseTransactionDistributions(logs) {+ return getDistributeCreatorFeesEvents(logs).map((e) => ({+ mint: pubkeyString(e.data.mint),+ sharingConfig: pubkeyString(e.data.sharingConfig),+ shareholders: (e.data.shareholders || []).map((s) => ({+ address: pubkeyString(s.address),+ shareBps: Number(s.shareBps),+ })),+ distributedRaw: e.data.distributed.toString(),+ quoteMint: pubkeyString(e.data.quoteMint),+ }));+}++/**+ * The SocialFeePdaClaimed event from a claim_social_fee_pda transaction's+ * logs, or null when the instruction emitted no event (a claim that reverted+ * or paid out nothing).+ * @param {string[]} logs+ */+export function parseSocialFeeClaim(logs) {+ const [event] = getSocialFeePdaClaimedEvents(logs);+ if (!event) return null;+ const d = event.data;+ return {+ githubUserId: d.userId,+ socialPlatform: Number(d.platform),+ socialFeePda: pubkeyString(d.socialFeePda),+ recipient: pubkeyString(d.recipient),+ amountClaimedRaw: d.amountClaimed.toString(),+ lifetimeClaimedRaw: d.lifetimeClaimed.toString(),+ quoteMint: pubkeyString(d.quoteMint),+ };+}++/** True when a transaction's logs show a claim_social_fee_pda instruction (V1 or V2). */+export function isSocialClaimLog(logs) {+ return (logs || []).some((line) => line.includes('Program log: Instruction: ClaimSocialFeePda'));+}diff --git a/docs/pump-claims-channel.md b/docs/pump-claims-channel.mdindex 7dad3576f..841c14d5f 100644--- a/docs/pump-claims-channel.md+++ b/docs/pump-claims-channel.md@@ -3,30 +3,89 @@A live feed of **first-time pump.fun creator fee claims**, delivered to aTelegram channel (`@pumpfunclaims`), one message per claim.-A claim is a real on-chain withdrawal. For GitHub social fees, it proves payment-to a GitHub fee account, not automatically that the GitHub user created, owns, or-endorses a particular coin. Token metadata can name lookalike accounts, and one-fee account can pool rewards from several coins.--Trader-facing cards use five evidence labels: **Verified GitHub Fee Claim**,-**Creator-Wallet GitHub Fee Claim**, **Identity Mismatch**, **Unverified**, and-**Unresolved Pooled**. A pooled event selects no primary CA or per-coin amount.-“First-ever” refers to the shared fee account, and trade links appear only for-verified relationships. The feed is a research lead, not an endorsement.+Two kinds of claim feed this channel: an ordinary wallet withdrawing its own+coin's creator fees (the original feature), and a GitHub identity withdrawing+fees a coin delegated to it through pump.fun's fee-sharing program (the+`claim_social_fee_pda` instruction). A GitHub withdrawal is a real on-chain+payment to that GitHub identity's fee account, but it does not by itself prove+which coin paid for it, or that the GitHub user created, owns, or endorses that+coin: one fee account (a "social fee PDA") can be a shareholder on more than one+coin's `SharingConfig`, and a scammer can paste someone else's PDA, or their own+freshly-registered one, into a copycat coin's metadata. Attribution below+answers "which coin, if any, paid this" from on-chain evidence, never from the+highest-market-cap guess.++## GitHub fee-claim attribution++`api/_lib/pump-claims-attribution.js` classifies every GitHub+`claim_social_fee_pda` withdrawal into exactly one of seven labels, using two+evidence rules in order of strength, then two identity checks when neither rule+finds evidence:++1. **Transaction-attributed.** The claim transaction itself also carries a+ `DistributeCreatorFeesEvent` that pays the exact PDA being claimed. Payout+ and attribution are in the same atomic transaction, so this is the strongest+ evidence a withdrawal can have.+2. **Fee-history-attributed.** No distribution rode along with the claim, so the+ scanner walks the PDA's own transaction history backward from the claim (up+ to 40 transactions or 7 days, whichever comes first, stopping early at the+ PDA's previous claim) looking for distributions in the claim's own quote+ currency. If those distributions cover at least 90% of the amount withdrawn,+ and one coin accounts for at least 90% of what was observed, the withdrawal+ is attributed to that coin. Short of either threshold, nothing is attributed+ from history.+3. **Verified repository.** Neither rule found a paying coin, but the claiming+ GitHub login matches the repository owner linked in the coin's metadata+ (description, website, X/Telegram links, or metadata URI).+4. **Identity mismatch.** A repository link exists in the coin's metadata, but+ its owner is a different GitHub account than the one that claimed. This is+ the strongest public signal of a lookalike coin.+5. **Creator-wallet verified.** No repository link exists at all, but the claim+ recipient wallet matches the coin's on-chain creator wallet.+6. **Unresolved pooled.** No evidence rule found a payer, and the PDA has been a+ shareholder in more than one coin recently. The withdrawal is real but cannot+ be assigned to a single CA or amount.+7. **Unverified.** A real withdrawal occurred, and none of the above resolved+ it. The claim is reported; no coin is credited.++**The impersonation hold** (`assessImpersonation`) is a separate, additive gate+applied after classification. Even an attributed claim is held for review, not+posted with its celebratory framing, when the claiming GitHub account is less+than 30 days old AND either: a same-name coin on pump.fun is at least 1.5x+larger by market cap than the one the claim is about, or the metadata repository+was created less than 7 days before the claim. A new account alone is not+suspicious, and neither is a same-name coin; the combination is the pattern a+scam follows (register a lookalike account, push a repo, put it in a copycat+coin's metadata, delegate fees to it, claim them), so both conditions must hold+before a claim is held. A held claim's Telegram message and feed card+(`buildClaimCard` in `src/pump/first-claims.js`) state plainly that a withdrawal+happened and why it is held, instead of naming a coin or identity the evidence+does not support yet.## How it works```pump.fun program activity│- ▼-scanFirstClaims() api/_lib/pump-claims.js- ├── PUMPFUN_BOT_URL indexer (preferred)- └── direct Solana RPC scan (fallback, see "Known limits")+ ├── creator fee claims (Pump program)+ │ │+ │ ▼+ │ scanFirstClaims() api/_lib/pump-claims.js+ │ ├── PUMPFUN_BOT_URL indexer (preferred)+ │ └── direct Solana RPC scan (fallback, see "Known limits")+ │+ └── GitHub fee-PDA claims (PumpFees program, claim_social_fee_pda)+ │+ ▼+ _fetchGithubClaimsFromRpc() api/_lib/pump-claims.js+ ├── direct Solana RPC scan (always runs; no indexer dependency)+ ├── same-tx / fee-history evidence pump-claims-attribution.js+ └── GitHub user + coin metadata lookups pump-claims-github.js│▼pushTelegramLane() api/_lib/pump-claims-push.js├── diff against app_settings['pump_claims_push_telegram']+ ├── wallet claims deduped by signature, GitHub claims by user id + mint├── oldest-first, 10 per tick, 3.5s apart└── Telegram sendMessage → TELEGRAM_PUMP_CLAIMS_CHAT_ID│@@ -67,7 +126,10 @@ gcloud run services update three-ws-api \## Verifying it```bash-# 1. Is the scan returning claims at all?+# 1. Is the scan returning claims at all? GitHub claims carry githubUserId and+# attribution; wallet claims do not. An empty items array with HTTP 200 is a+# correct result when no first-time claim of either kind happened in the+# window, not a failure (GitHub fee-PDA claims are rare on mainnet).curl -s 'https://three.ws/api/pump/first-claims?sinceMinutes=60&limit=5'# 2. Does the bot have channel access? (replace $TOKEN)@@ -88,16 +150,23 @@ call reports exactly what happened: `{ posted, scanned, backlog }`, orState lives in `app_settings` under `pump_claims_push_telegram`:```json-{ "lastTs": 1723661000, "seen": ["<tx signature>", "..."] }+{ "lastTs": 1723661000, "seen": ["<tx signature>", "..."], "githubSeen": ["<githubUserId>:<mint>", "..."] }```- **First run seeds without posting.** Enabling the lane records what is alreadyon-chain and starts posting from the next tick, so switching it on never dumpsa backlog into the channel.-- **Dedupe is by transaction signature**, not by timestamp. Two claims landing in- the same second are common; a timestamp-only cursor would silently drop the- second one. `seen` is a bounded ring of 400 signatures; `lastTs` bounds the- scan window so the ring never has to answer for anything older.+- **Wallet claims dedupe by transaction signature**, not by timestamp. Two+ claims landing in the same second are common; a timestamp-only cursor would+ silently drop the second one. `seen` is a bounded ring of 400 signatures;+ `lastTs` bounds the scan window so the ring never has to answer for anything+ older.+- **GitHub claims dedupe by GitHub user id plus mint**, in a second bounded ring,+ `githubSeen`. The same GitHub identity can submit more than one+ `claim_social_fee_pda` transaction against the same coin (a sweep followed by+ a claim, or claiming again later), each with its own signature; the channel+ announces that pairing once, the same way it announces a wallet's first claim+ once.- **A three-hour cutoff** bounds any catch-up. A lane that has been down for aday drains recent claims and drops stale ones rather than replaying history.- **State is written per message, not per run.** A tick killed mid-batch (the@@ -112,11 +181,16 @@ State lives in `app_settings` under `pump_claims_push_telegram`:data; unescaped text could otherwise smuggle a clickable link posted under theplatform bot's identity.-## Known limits: the RPC fallback cannot serve this feed+## Known limits: the RPC fallback cannot serve the wallet-claim feed++This limit is specific to **ordinary wallet claims**. The GitHub fee-claim path+(`_fetchGithubClaimsFromRpc`) always runs a direct RPC scan, independent of+`PUMPFUN_BOT_URL`; see "Verifying it" below for a live check of that path.-`scanFirstClaims` prefers the `PUMPFUN_BOT_URL` indexer and falls back to a-direct RPC scan of the pump program's recent signatures. **That fallback cannot-produce a useful result, and the channel will stay silent without the indexer.**+`scanFirstClaims` prefers the `PUMPFUN_BOT_URL` indexer for wallet claims and+falls back to a direct RPC scan of the pump program's recent signatures. **That+fallback cannot produce a useful result, and the channel will stay silent for+wallet claims without the indexer.**Measured against mainnet on 2026-08-14:@@ -152,7 +226,11 @@ built yet.## Related-- [api/_lib/pump-claims.js](../api/_lib/pump-claims.js) - the shared scanner+- [api/_lib/pump-claims.js](../api/_lib/pump-claims.js) - the shared scanner (wallet claims and GitHub fee-PDA claims)+- [api/_lib/pump-events.js](../api/_lib/pump-events.js) - typed Pump/PumpFees event decoder (wraps `@nirholas/pump-sdk`)+- [api/_lib/pump-claims-attribution.js](../api/_lib/pump-claims-attribution.js) - the evidence rules, the seven labels, and the impersonation hold+- [api/_lib/pump-claims-github.js](../api/_lib/pump-claims-github.js) - GitHub identity and coin-metadata lookups used by attribution- [api/_lib/pump-claims-push.js](../api/_lib/pump-claims-push.js) - the delivery lane- [api/cron/pump-claims-push.js](../api/cron/pump-claims-push.js) - the cron entry point+- [src/pump/first-claims.js](../src/pump/first-claims.js) - `buildClaimCard`, the shared held/attributed/claimed view model- [api/_lib/commit-feed-push.js](../api/_lib/commit-feed-push.js) - the sibling commit feed this lane mirrorsdiff --git a/src/pump/first-claims.js b/src/pump/first-claims.jsindex a299ff0b7..68f94ee32 100644--- a/src/pump/first-claims.js+++ b/src/pump/first-claims.js@@ -55,3 +55,55 @@ export async function fetchFirstClaims({ sinceTs, limit = 50 }) {if (!r.ok) throw new Error(`first-claims: ${r.status}`);return r.json();}++/**+ * Pure view model for one claim card: a celebratory card for an ordinary or+ * attributed claim, a "held for review" card for one `pump-claims.js` flagged+ * as suspected impersonation. Consumed by the Telegram formatter+ * (`pump-claims-push.js`) and by any future rendered feed page, so the two+ * never drift on what a held claim looks like.+ *+ * @param {{creator:string, mint:string, signature:string, lamports:number, ts:number,+ * githubUserId?:string, githubLogin?:string|null,+ * attribution?:{label:string, headline:string, explanation:string},+ * held?:boolean, heldReasons?:string[]}} claim+ * @returns {{+ * state: 'held'|'attributed'|'claimed',+ * title: string,+ * subtitle: string,+ * label: string|null,+ * explanation: string|null,+ * heldReasons: string[],+ * }}+ */+export function buildClaimCard(claim) {+ const isGithubClaim = Boolean(claim.githubUserId);+ if (isGithubClaim && claim.held) {+ return {+ state: 'held',+ title: 'Held for review',+ subtitle: claim.githubLogin ? `github.com/${claim.githubLogin}` : `GitHub id ${claim.githubUserId}`,+ label: claim.attribution?.label ?? null,+ explanation: claim.attribution?.explanation ?? null,+ heldReasons: claim.heldReasons || [],+ };+ }+ if (isGithubClaim) {+ return {+ state: 'attributed',+ title: claim.attribution?.headline || 'GitHub fee claim',+ subtitle: claim.githubLogin ? `github.com/${claim.githubLogin}` : `GitHub id ${claim.githubUserId}`,+ label: claim.attribution?.label ?? null,+ explanation: claim.attribution?.explanation ?? null,+ heldReasons: [],+ };+ }+ return {+ state: 'claimed',+ title: 'First creator fee claim',+ subtitle: claim.creator,+ label: null,+ explanation: null,+ heldReasons: [],+ };+}diff --git a/tests/_helpers/pump-log-fixtures.js b/tests/_helpers/pump-log-fixtures.jsnew file mode 100644index 000000000..3ea546e9c--- /dev/null+++ b/tests/_helpers/pump-log-fixtures.js@@ -0,0 +1,183 @@+// Synthetic recorded-transaction log fixtures for pump.fun / PumpFees event+// decoding tests. Hand-encodes Borsh bytes for DistributeCreatorFeesEvent+// (Pump program) and SocialFeePdaClaimed (PumpFees program) using the exact+// field order read from the installed @nirholas/pump-sdk's IDL+// (PumpIdl.types / PumpFeesIdl.types), then wraps them as "Program data:"+// log lines inside the invoke/success frame parsePumpEventsFromLogs expects.+// Every account below is a synthetic placeholder, never a real mainnet key.++import bs58 from 'bs58';+import { PUMP_PROGRAM_ID, PUMP_FEE_PROGRAM_ID } from '../../api/_lib/solana/programs.js';++class BorshWriter {+ constructor() {+ this.chunks = [];+ }+ u8(v) {+ this.chunks.push(Buffer.from([v]));+ return this;+ }+ u16(v) {+ const b = Buffer.alloc(2);+ b.writeUInt16LE(v);+ this.chunks.push(b);+ return this;+ }+ u64(v) {+ const b = Buffer.alloc(8);+ b.writeBigUInt64LE(BigInt(v));+ this.chunks.push(b);+ return this;+ }+ i64(v) {+ const b = Buffer.alloc(8);+ b.writeBigInt64LE(BigInt(v));+ this.chunks.push(b);+ return this;+ }+ pubkey(base58) {+ const bytes = bs58.decode(base58);+ if (bytes.length !== 32) throw new Error(`fixture pubkey must decode to 32 bytes: ${base58}`);+ this.chunks.push(Buffer.from(bytes));+ return this;+ }+ string(s) {+ const utf8 = Buffer.from(s, 'utf8');+ const len = Buffer.alloc(4);+ len.writeUInt32LE(utf8.length);+ this.chunks.push(len, utf8);+ return this;+ }+ vec(items, writeItem) {+ const len = Buffer.alloc(4);+ len.writeUInt32LE(items.length);+ this.chunks.push(len);+ for (const item of items) writeItem(this, item);+ return this;+ }+ bytes() {+ return Buffer.concat(this.chunks);+ }+}++function discriminatorBuffer(disc) {+ return Buffer.from(disc, 'hex');+}++const DISTRIBUTE_CREATOR_FEES_DISC = 'a537817004b3ca28';+const SOCIAL_FEE_PDA_CLAIMED_DISC = '3212c141edd2eaec';++/**+ * @param {{mint:string, bondingCurve:string, sharingConfig:string, admin:string,+ * shareholders:Array<{address:string, shareBps:number}>, distributed:bigint|number, timestamp?:number}} fields+ */+export function encodeDistributeCreatorFeesEvent(fields) {+ const w = new BorshWriter();+ w.i64(fields.timestamp ?? 1_760_000_000)+ .pubkey(fields.mint)+ .pubkey(fields.bondingCurve)+ .pubkey(fields.sharingConfig)+ .pubkey(fields.admin)+ .vec(fields.shareholders, (writer, sh) => writer.pubkey(sh.address).u16(sh.shareBps))+ .u64(fields.distributed);+ return Buffer.concat([discriminatorBuffer(DISTRIBUTE_CREATOR_FEES_DISC), w.bytes()]);+}++/**+ * @param {{userId:string, platform:number, socialFeePda:string, recipient:string,+ * socialClaimAuthority:string, amountClaimed:bigint|number, claimableBefore?:bigint|number,+ * lifetimeClaimed:bigint|number, recipientBalanceBefore?:bigint|number,+ * recipientBalanceAfter?:bigint|number, timestamp?:number}} fields+ */+export function encodeSocialFeePdaClaimed(fields) {+ const w = new BorshWriter();+ w.i64(fields.timestamp ?? 1_760_000_100)+ .string(fields.userId)+ .u8(fields.platform)+ .pubkey(fields.socialFeePda)+ .pubkey(fields.recipient)+ .pubkey(fields.socialClaimAuthority)+ .u64(fields.amountClaimed)+ .u64(fields.claimableBefore ?? 0)+ .u64(fields.lifetimeClaimed)+ .u64(fields.recipientBalanceBefore ?? 0)+ .u64(fields.recipientBalanceAfter ?? 0);+ return Buffer.concat([discriminatorBuffer(SOCIAL_FEE_PDA_CLAIMED_DISC), w.bytes()]);+}++function programDataLogLine(bytes) {+ return `Program data: ${bytes.toString('base64')}`;+}++/**+ * Wraps one or more already-encoded event payloads as a recorded+ * transaction's log lines: one invoke/success frame per program, each+ * carrying its "Program data:" lines in order. Matches the shape+ * `parsePumpEventsFromLogs` (and this codebase's pump-events.js wrapper)+ * reads from `tx.meta.logMessages`.+ * @param {Array<{programId:string, instruction:string, dataPayloads:Buffer[]}>} frames+ */+export function buildTransactionLogs(frames) {+ const logs = [];+ for (const frame of frames) {+ logs.push(`Program ${frame.programId} invoke [1]`);+ if (frame.instruction) logs.push(`Program log: Instruction: ${frame.instruction}`);+ for (const payload of frame.dataPayloads) logs.push(programDataLogLine(payload));+ logs.push(`Program ${frame.programId} success`);+ }+ return logs;+}++/** Logs for a claim_social_fee_pda transaction alone (no same-tx distribution). */+export function socialClaimLogs(claimFields) {+ return buildTransactionLogs([+ {+ programId: PUMP_FEE_PROGRAM_ID,+ instruction: 'ClaimSocialFeePda',+ dataPayloads: [encodeSocialFeePdaClaimed(claimFields)],+ },+ ]);+}++/** Logs for a claim_social_fee_pda transaction that also carries same-tx distributions. */+export function socialClaimWithDistributionsLogs(claimFields, distributions) {+ return buildTransactionLogs([+ { programId: PUMP_PROGRAM_ID, instruction: null, dataPayloads: distributions.map(encodeDistributeCreatorFeesEvent) },+ {+ programId: PUMP_FEE_PROGRAM_ID,+ instruction: 'ClaimSocialFeePda',+ dataPayloads: [encodeSocialFeePdaClaimed(claimFields)],+ },+ ]);+}++/** Logs for a plain distribution transaction (e.g. a history entry between two claims). */+export function distributionLogs(distribution) {+ return buildTransactionLogs([+ { programId: PUMP_PROGRAM_ID, instruction: null, dataPayloads: [encodeDistributeCreatorFeesEvent(distribution)] },+ ]);+}++/** A deterministic, valid 32-byte base58 pubkey from a short ASCII tag. Never a real key. */+function synthPubkey(tag) {+ const buf = Buffer.alloc(32);+ Buffer.from(tag, 'utf8').copy(buf);+ return bs58.encode(buf);+}++// Synthetic, non-mainnet accounts. Base58, 32 bytes, never a real third-party key.+// MINT_A is the $THREE mint, the only coin this platform promotes; the rest are+// tagged placeholders encoded fresh above rather than real addresses.+export const SYNTH = {+ PDA_A: synthPubkey('synth-social-fee-pda-a'),+ PDA_B: synthPubkey('synth-social-fee-pda-b'),+ MINT_A: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ MINT_B: synthPubkey('synth-mint-b'),+ BONDING_CURVE_A: synthPubkey('synth-bonding-curve-a'),+ BONDING_CURVE_B: synthPubkey('synth-bonding-curve-b'),+ SHARING_CONFIG_A: synthPubkey('synth-sharing-config-a'),+ SHARING_CONFIG_B: synthPubkey('synth-sharing-config-b'),+ ADMIN: synthPubkey('synth-admin'),+ RECIPIENT: synthPubkey('synth-recipient'),+ CLAIM_AUTHORITY: synthPubkey('synth-claim-authority'),+};diff --git a/tests/pump-claims-push.test.js b/tests/pump-claims-push.test.jsindex 910bc16a3..0f79799c2 100644--- a/tests/pump-claims-push.test.js+++ b/tests/pump-claims-push.test.js@@ -5,6 +5,8 @@ import {formatSol,shortAddress,formatTelegramMessage,+ githubClaimKey,+ rememberGithubClaims,} from '../api/_lib/pump-claims-push.js';// Fixed clock so the cutoff arithmetic is deterministic.@@ -24,6 +26,14 @@ function claim(signature, ts, overrides = {}) {};}+function githubClaim(signature, ts, overrides = {}) {+ return claim(signature, ts, {+ githubUserId: '111',+ githubLogin: 'octocat',+ ...overrides,+ });+}+describe('newClaimsSince selection', () => {it('returns unseen claims oldest-first', () => {const claims = [claim('c', NOW_S - 60), claim('a', NOW_S - 300), claim('b', NOW_S - 120)];@@ -61,6 +71,62 @@ describe('newClaimsSince selection', () => {const out = newClaimsSince([claim('a', NOW_S - 60)], {}, NOW_MS);expect(out).toHaveLength(1);});++ it('drops a GitHub claim already seen for the same GitHub user and mint, by a different signature', () => {+ const prior = githubClaim('sig1', NOW_S - 300);+ const repeat = githubClaim('sig2', NOW_S - 60);+ const out = newClaimsSince([repeat], { seen: [], githubSeen: [githubClaimKey(prior)] }, NOW_MS);+ expect(out).toHaveLength(0);+ });++ it('keeps a GitHub claim from the same user against a different mint', () => {+ const other = githubClaim('sig1', NOW_S - 60, { mint: 'THREEsynthMintOther111111111111111111111111' });+ const out = newClaimsSince(+ [other],+ { seen: [], githubSeen: [githubClaimKey(githubClaim('seed', 0))] },+ NOW_MS,+ );+ expect(out.map((c) => c.signature)).toEqual(['sig1']);+ });++ it('does not apply the GitHub dedupe to an ordinary wallet claim', () => {+ const out = newClaimsSince([claim('a', NOW_S - 60)], { seen: [], githubSeen: ['111:anything'] }, NOW_MS);+ expect(out).toHaveLength(1);+ });+});++describe('githubClaimKey', () => {+ it('keys on GitHub user id and mint', () => {+ expect(githubClaimKey({ githubUserId: '111', mint: 'MintA' })).toBe('111:MintA');+ });++ it('falls back to an empty mint when none is present', () => {+ expect(githubClaimKey({ githubUserId: '111' })).toBe('111:');+ });+});++describe('rememberGithubClaims bounded ring', () => {+ it('records only claims carrying a GitHub user id', () => {+ const out = rememberGithubClaims([], [githubClaim('a', 1), claim('b', 2)]);+ expect(out).toEqual([githubClaimKey(githubClaim('a', 1))]);+ });++ it('appends to an existing ring', () => {+ const out = rememberGithubClaims(['999:MintZ'], [githubClaim('a', 1)]);+ expect(out).toEqual(['999:MintZ', githubClaimKey(githubClaim('a', 1))]);+ });++ it('caps the ring and keeps the newest entries', () => {+ const seen = Array.from({ length: 400 }, (_, i) => `u${i}:m`);+ const out = rememberGithubClaims(seen, [githubClaim('a', 1, { githubUserId: 'new' })]);+ expect(out).toHaveLength(400);+ expect(out.at(-1)).toBe(githubClaimKey(githubClaim('a', 1, { githubUserId: 'new' })));+ expect(out).not.toContain('u0:m');+ });++ it('defaults both arguments', () => {+ expect(rememberGithubClaims()).toEqual([]);+ });});describe('rememberSignatures bounded ring', () => {@@ -142,4 +208,40 @@ describe('formatTelegramMessage', () => {expect(msg).toContain('<a href=');expect(msg).not.toContain('<a href="https://evil.example"');});++ it('renders a held-for-review message for a GitHub claim flagged by the impersonation gate, without the celebratory framing', () => {+ const msg = formatTelegramMessage(+ githubClaim('sig123', NOW_S, { held: true, heldReasons: ['GitHub account 5d old'] }),+ );+ expect(msg).toContain('GitHub fee withdrawal held for review');+ expect(msg).toContain('github.com/octocat');+ expect(msg).toContain('Held: GitHub account 5d old');+ expect(msg).not.toContain('First creator fee claim');+ });++ it('renders the attribution headline and explanation for an attributed, non-held GitHub claim', () => {+ const msg = formatTelegramMessage(+ githubClaim('sig123', NOW_S, {+ held: false,+ attribution: {+ label: 'transaction_attributed',+ headline: 'TRANSACTION-ATTRIBUTED GITHUB FEE CLAIM',+ explanation: 'This transaction distributed fees from this exact coin to the claimed GitHub fee account.',+ },+ }),+ );+ expect(msg).toContain('TRANSACTION-ATTRIBUTED GITHUB FEE CLAIM');+ expect(msg).toContain('This transaction distributed fees from this exact coin');+ expect(msg).not.toContain('held for review');+ });++ it('identifies an attributed GitHub claim by GitHub id when no login resolved', () => {+ const msg = formatTelegramMessage(+ githubClaim('sig123', NOW_S, {+ githubLogin: null,+ attribution: { label: 'unverified', headline: 'UNVERIFIED GITHUB FEE WITHDRAWAL', explanation: 'x' },+ }),+ );+ expect(msg).toContain('GitHub id 111');+ });});diff --git a/tests/pump-first-claims.test.js b/tests/pump-first-claims.test.jsindex 978a2486a..765824cb3 100644--- a/tests/pump-first-claims.test.js+++ b/tests/pump-first-claims.test.js@@ -1,5 +1,17 @@import { describe, it, expect } from 'vitest';-import { filterFirstClaims } from '../src/pump/first-claims.js';+import { filterFirstClaims, buildClaimCard } from '../src/pump/first-claims.js';+import { parseSocialFeeClaim, parseTransactionDistributions } from '../api/_lib/pump-events.js';+import {+ evidenceForSocialFeePda,+ evidenceFromPdaHistory,+ classifyClaimAttribution,+ assessImpersonation,+ ATTRIBUTION_LABELS,+ NEW_ACCOUNT_DAYS,+ FRESH_REPO_DAYS,+ COPYCAT_MCAP_RATIO,+} from '../api/_lib/pump-claims-attribution.js';+import { socialClaimWithDistributionsLogs, distributionLogs, SYNTH } from './_helpers/pump-log-fixtures.js';const sinceTs = 1000; // boundary: claims < 1000 are "prior"@@ -7,7 +19,7 @@ function claim(creator, ts, overrides = {}) {return { creator, mint: `mint_${ts}`, signature: `sig_${ts}`, lamports: 1e9, ts, ...overrides };}-describe('filterFirstClaims — dedupe rule', () => {+describe('filterFirstClaims: dedupe rule', () => {it('includes a creator whose only claim is within the window', () => {const result = filterFirstClaims([claim('A', 1200)], sinceTs, 50);expect(result).toHaveLength(1);@@ -17,7 +29,7 @@ describe('filterFirstClaims — dedupe rule', () => {it('excludes a creator with any prior claim before sinceTs', () => {const result = filterFirstClaims([- claim('B', 500), // prior — before sinceTs+ claim('B', 500), // prior, before sinceTsclaim('B', 1200), // within window],sinceTs,@@ -54,7 +66,7 @@ describe('filterFirstClaims — dedupe rule', () => {});it('returns the earliest claim per creator (the first-claim event)', () => {- // Creator with two claims both within window — should surface the earlier one.+ // Creator with two claims both within window, should surface the earlier one.const claims = [claim('D', 1300), claim('D', 1100)];const result = filterFirstClaims(claims, sinceTs, 50);expect(result).toHaveLength(1);@@ -84,3 +96,300 @@ describe('filterFirstClaims — dedupe rule', () => {expect(result).toHaveLength(0);});});++// GitHub fee-claim attribution. Fixtures are recorded-transaction-shaped log+// lines decoded by the real @nirholas/pump-sdk via api/_lib/pump-events.js+// (see tests/_helpers/pump-log-fixtures.js), with synthetic accounts standing+// in for real pubkeys, per the $THREE-or-synthetic fixture rule.+describe('evidenceForSocialFeePda: same-transaction rule', () => {+ it('attributes a claim to the mint whose distribution paid the claimed PDA in the same tx', () => {+ const claimFields = {+ userId: '111',+ platform: 2,+ socialFeePda: SYNTH.PDA_A,+ recipient: SYNTH.RECIPIENT,+ socialClaimAuthority: SYNTH.CLAIM_AUTHORITY,+ amountClaimed: 50_000_000_000n,+ lifetimeClaimed: 50_000_000_000n,+ };+ const distribution = {+ mint: SYNTH.MINT_A,+ bondingCurve: SYNTH.BONDING_CURVE_A,+ sharingConfig: SYNTH.SHARING_CONFIG_A,+ admin: SYNTH.ADMIN,+ shareholders: [{ address: SYNTH.PDA_A, shareBps: 5000 }],+ distributed: 100_000_000_000n,+ };+ const logs = socialClaimWithDistributionsLogs(claimFields, [distribution]);+ const claimEvent = parseSocialFeeClaim(logs);+ const evidence = evidenceForSocialFeePda(parseTransactionDistributions(logs), claimEvent.socialFeePda);+ expect(evidence).toHaveLength(1);+ expect(evidence[0]).toMatchObject({ mint: SYNTH.MINT_A, source: 'same_transaction_distribution' });+ });++ it('finds nothing when no distribution in the transaction paid the claimed PDA', () => {+ const distribution = {+ mint: SYNTH.MINT_A,+ bondingCurve: SYNTH.BONDING_CURVE_A,+ sharingConfig: SYNTH.SHARING_CONFIG_A,+ admin: SYNTH.ADMIN,+ shareholders: [{ address: SYNTH.PDA_B, shareBps: 5000 }], // pays a different PDA+ distributed: 100_000_000_000n,+ };+ const logs = distributionLogs(distribution);+ const evidence = evidenceForSocialFeePda(parseTransactionDistributions(logs), SYNTH.PDA_A);+ expect(evidence).toHaveLength(0);+ });++ it('reports more than one candidate mint when the PDA is a shareholder in two distributions in one tx', () => {+ const claimFields = {+ userId: '111',+ platform: 2,+ socialFeePda: SYNTH.PDA_A,+ recipient: SYNTH.RECIPIENT,+ socialClaimAuthority: SYNTH.CLAIM_AUTHORITY,+ amountClaimed: 10_000_000_000n,+ lifetimeClaimed: 10_000_000_000n,+ };+ const distA = {+ mint: SYNTH.MINT_A,+ bondingCurve: SYNTH.BONDING_CURVE_A,+ sharingConfig: SYNTH.SHARING_CONFIG_A,+ admin: SYNTH.ADMIN,+ shareholders: [{ address: SYNTH.PDA_A, shareBps: 5000 }],+ distributed: 10_000_000_000n,+ };+ const distB = {+ mint: SYNTH.MINT_B,+ bondingCurve: SYNTH.BONDING_CURVE_B,+ sharingConfig: SYNTH.SHARING_CONFIG_B,+ admin: SYNTH.ADMIN,+ shareholders: [{ address: SYNTH.PDA_A, shareBps: 5000 }],+ distributed: 10_000_000_000n,+ };+ const logs = socialClaimWithDistributionsLogs(claimFields, [distA, distB]);+ const claimEvent = parseSocialFeeClaim(logs);+ const evidence = evidenceForSocialFeePda(parseTransactionDistributions(logs), claimEvent.socialFeePda);+ expect(evidence.map((e) => e.mint).sort()).toEqual([SYNTH.MINT_A, SYNTH.MINT_B].sort());+ });+});++describe('evidenceFromPdaHistory: the 90% fee-history rule', () => {+ const distributionTo = (mint, pda, raw) => ({+ mint,+ sharingConfig: SYNTH.SHARING_CONFIG_A,+ shareholders: [{ address: pda, shareBps: 10_000 }], // 100% share for simple raw-amount math+ distributedRaw: raw.toString(),+ });++ it('attributes when observed history covers the claim and one mint dominates at exactly 90%', () => {+ const claimedRaw = 100_000_000_000n;+ const distributions = [+ distributionTo(SYNTH.MINT_A, SYNTH.PDA_A, 90_000_000_000n),+ distributionTo(SYNTH.MINT_B, SYNTH.PDA_A, 10_000_000_000n),+ ];+ const evidence = evidenceFromPdaHistory(distributions, SYNTH.PDA_A, claimedRaw, undefined);+ expect(evidence).toHaveLength(1);+ expect(evidence[0]).toMatchObject({ mint: SYNTH.MINT_A, source: 'pda_history_distribution' });+ });++ it('finds nothing when the dominant mint falls just under 90% of observed history', () => {+ const claimedRaw = 100_000_000_000n;+ const distributions = [+ distributionTo(SYNTH.MINT_A, SYNTH.PDA_A, 89_000_000_000n),+ distributionTo(SYNTH.MINT_B, SYNTH.PDA_A, 11_000_000_000n),+ ];+ const evidence = evidenceFromPdaHistory(distributions, SYNTH.PDA_A, claimedRaw, undefined);+ expect(evidence).toHaveLength(0);+ });++ it('finds nothing when observed history covers less than 90% of the claimed amount, even if one mint is 100% of what was observed', () => {+ const claimedRaw = 100_000_000_000n;+ const distributions = [distributionTo(SYNTH.MINT_A, SYNTH.PDA_A, 50_000_000_000n)];+ const evidence = evidenceFromPdaHistory(distributions, SYNTH.PDA_A, claimedRaw, undefined);+ expect(evidence).toHaveLength(0);+ });++ it('ignores distributions in a different quote currency than the claim', () => {+ const claimedRaw = 100_000_000_000n;+ const distributions = [+ { ...distributionTo(SYNTH.MINT_A, SYNTH.PDA_A, 95_000_000_000n), quoteMint: 'SomeOtherQuoteMint11111111111111111111111' },+ ];+ const evidence = evidenceFromPdaHistory(distributions, SYNTH.PDA_A, claimedRaw, undefined);+ expect(evidence).toHaveLength(0);+ });+});++describe('classifyClaimAttribution: the seven labels', () => {+ const evidence = { source: 'same_transaction_distribution' };+ const historyEvidence = { source: 'pda_history_distribution' };++ it('transaction_attributed: same-transaction distribution evidence', () => {+ const result = classifyClaimAttribution({ evidence, candidateMintCount: 1 });+ expect(result.label).toBe(ATTRIBUTION_LABELS.TRANSACTION_ATTRIBUTED);+ });++ it('fee_history_attributed: pda-history distribution evidence', () => {+ const result = classifyClaimAttribution({ evidence: historyEvidence, candidateMintCount: 1 });+ expect(result.label).toBe(ATTRIBUTION_LABELS.FEE_HISTORY_ATTRIBUTED);+ });++ it('unresolved_pooled: no evidence, PDA shared by more than one coin', () => {+ const result = classifyClaimAttribution({ evidence: null, candidateMintCount: 2 });+ expect(result.label).toBe(ATTRIBUTION_LABELS.UNRESOLVED_POOLED);+ });++ it('verified_repository: claiming GitHub login matches the metadata repo owner', () => {+ const result = classifyClaimAttribution({+ evidence: null,+ candidateMintCount: 0,+ githubLogin: 'octocat',+ githubRepoOwner: 'octocat',+ });+ expect(result.label).toBe(ATTRIBUTION_LABELS.VERIFIED_REPOSITORY);+ });++ it('identity_mismatch: claiming GitHub login does not match the metadata repo owner', () => {+ const result = classifyClaimAttribution({+ evidence: null,+ candidateMintCount: 0,+ githubLogin: 'mallory',+ githubRepoOwner: 'octocat',+ });+ expect(result.label).toBe(ATTRIBUTION_LABELS.IDENTITY_MISMATCH);+ });++ it('verified_creator_wallet: claim recipient matches the token creator wallet', () => {+ const result = classifyClaimAttribution({+ evidence: null,+ candidateMintCount: 0,+ claimerWallet: SYNTH.RECIPIENT,+ tokenCreatorWallet: SYNTH.RECIPIENT,+ });+ expect(result.label).toBe(ATTRIBUTION_LABELS.VERIFIED_CREATOR_WALLET);+ });++ it('unverified: no evidence and nothing else resolves', () => {+ const result = classifyClaimAttribution({ evidence: null, candidateMintCount: 0 });+ expect(result.label).toBe(ATTRIBUTION_LABELS.UNVERIFIED);+ });++ it('every label carries a non-empty headline and explanation', () => {+ const cases = [+ { evidence, candidateMintCount: 1 },+ { evidence: historyEvidence, candidateMintCount: 1 },+ { evidence: null, candidateMintCount: 2 },+ { evidence: null, candidateMintCount: 0, githubLogin: 'a', githubRepoOwner: 'a' },+ { evidence: null, candidateMintCount: 0, githubLogin: 'a', githubRepoOwner: 'b' },+ { evidence: null, candidateMintCount: 0, claimerWallet: 'x', tokenCreatorWallet: 'x' },+ { evidence: null, candidateMintCount: 0 },+ ];+ const labels = new Set();+ for (const ctx of cases) {+ const result = classifyClaimAttribution(ctx);+ expect(result.headline.length).toBeGreaterThan(0);+ expect(result.explanation.length).toBeGreaterThan(0);+ labels.add(result.label);+ }+ expect(labels.size).toBe(7);+ });+});++describe('assessImpersonation: the impersonation hold', () => {+ const NOW = Date.now();+ const daysAgo = (days) => new Date(NOW - days * 86_400_000).toISOString();++ it('holds a new account claiming from a coin with a much larger same-name copycat', () => {+ const result = assessImpersonation(+ {+ githubUser: { createdAt: daysAgo(5) },+ tokenInfo: { usdMarketCap: 10_000 },+ sameNameTokens: [{ mint: SYNTH.MINT_B, usdMarketCap: 10_000 * (COPYCAT_MCAP_RATIO + 1) }],+ },+ NOW,+ );+ expect(result.suspected).toBe(true);+ expect(result.reasons.join(' ')).toMatch(/larger/);+ });++ it('holds a new account whose metadata repo was created right before the claim', () => {+ const result = assessImpersonation(+ { githubUser: { createdAt: daysAgo(5) }, repoInfo: { createdAt: daysAgo(FRESH_REPO_DAYS - 1) } },+ NOW,+ );+ expect(result.suspected).toBe(true);+ expect(result.reasons.join(' ')).toMatch(/repo/);+ });++ it('does not hold a new account with no copycat coin and no fresh repo', () => {+ const result = assessImpersonation({ githubUser: { createdAt: daysAgo(5) } }, NOW);+ expect(result.suspected).toBe(false);+ });++ it('does not hold an account older than NEW_ACCOUNT_DAYS, even with a copycat coin', () => {+ const result = assessImpersonation(+ {+ githubUser: { createdAt: daysAgo(NEW_ACCOUNT_DAYS + 1) },+ tokenInfo: { usdMarketCap: 10_000 },+ sameNameTokens: [{ mint: SYNTH.MINT_B, usdMarketCap: 1_000_000 }],+ },+ NOW,+ );+ expect(result.suspected).toBe(false);+ });++ it('does not hold when the same-name coin is not large enough to count as a copycat', () => {+ const result = assessImpersonation(+ {+ githubUser: { createdAt: daysAgo(5) },+ tokenInfo: { usdMarketCap: 10_000 },+ sameNameTokens: [{ mint: SYNTH.MINT_B, usdMarketCap: 10_000 * COPYCAT_MCAP_RATIO }], // not strictly greater+ },+ NOW,+ );+ expect(result.suspected).toBe(false);+ });++ it('treats a GitHub account with no resolvable creation date as not new', () => {+ const result = assessImpersonation({ githubUser: null }, NOW);+ expect(result.suspected).toBe(false);+ expect(result.reasons).toEqual([]);+ });+});++describe('buildClaimCard: held vs attributed vs ordinary claim cards', () => {+ it('builds a held-for-review card when the claim was flagged for impersonation', () => {+ const card = buildClaimCard({+ creator: SYNTH.RECIPIENT,+ mint: SYNTH.MINT_A,+ githubUserId: '111',+ githubLogin: 'mallory',+ held: true,+ heldReasons: ['GitHub account 5d old'],+ attribution: { label: ATTRIBUTION_LABELS.UNVERIFIED, headline: 'x', explanation: 'y' },+ });+ expect(card.state).toBe('held');+ expect(card.title).toBe('Held for review');+ expect(card.heldReasons).toContain('GitHub account 5d old');+ });++ it('builds an attributed card for a non-held GitHub claim', () => {+ const card = buildClaimCard({+ creator: SYNTH.RECIPIENT,+ mint: SYNTH.MINT_A,+ githubUserId: '111',+ githubLogin: 'octocat',+ held: false,+ attribution: { label: ATTRIBUTION_LABELS.TRANSACTION_ATTRIBUTED, headline: 'TRANSACTION-ATTRIBUTED GITHUB FEE CLAIM', explanation: 'y' },+ });+ expect(card.state).toBe('attributed');+ expect(card.title).toBe('TRANSACTION-ATTRIBUTED GITHUB FEE CLAIM');+ expect(card.label).toBe(ATTRIBUTION_LABELS.TRANSACTION_ATTRIBUTED);+ });++ it('builds the ordinary celebratory card for a non-GitHub claim', () => {+ const card = buildClaimCard({ creator: SYNTH.RECIPIENT, mint: SYNTH.MINT_A });+ expect(card.state).toBe('claimed');+ expect(card.title).toBe('First creator fee claim');+ });+});