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.

feat(security): fuse RugCheck into the oracle risk read and make EVM token risk honeypot-aware

nirholas0fdc9f0fa3d4
diff --git a/api/_lib/honeypot.js b/api/_lib/honeypot.js
new file mode 100644
index 000000000..b6ac164f8
--- /dev/null
+++ b/api/_lib/honeypot.js
@@ -0,0 +1,130 @@
+// Honeypot.is: keyless EVM honeypot detector (api.honeypot.is).
+//
+// Runs a real buy/sell/transfer simulation of the token on a fork of its own
+// chain and reports whether holders can actually exit, the effective taxes,
+// and the contract-verification posture. This is the one scam signal a
+// market-shape read (liquidity, age, order flow) structurally cannot see: a
+// token can chart perfectly while its sell path is bricked.
+//
+// Wired into the generic token security snapshot (api/_lib/token-market.js):
+// fetchTokenMarket attaches the report for EVM addresses and buildTokenRisk
+// folds it into the risk score. Fails soft to null, never blocks a read.
+//
+// Endpoint (verified live 2026-08-05, no key, no auth):
+// GET https://api.honeypot.is/v2/IsHoneypot?address=0x..[&chainID=1]
+// -> { token, withToken, summary: { risk, riskLevel, flags },
+// simulationSuccess, honeypotResult: { isHoneypot[, honeypotReason] },
+// simulationResult: { buyTax, sellTax, transferTax, buyGas, sellGas },
+// flags, contractCode: { openSource, rootOpenSource, isProxy,
+// hasProxyCalls }, chain: { id, name, shortName, currency }, router,
+// pair, pairAddress }
+// 404 { code: 404, error: "No pairs found" | "Token not found" } when the
+// address has no simulatable market.
+// Without chainID the API auto-detects the deployment, but that detection
+// misses Base-native tokens (verified live: a Base-only address answers 404
+// unpinned and succeeds with chainID=8453), so callers that know the chain
+// must pin it.
+
+const HONEYPOT_API = 'https://api.honeypot.is/v2/IsHoneypot';
+const FETCH_TIMEOUT_MS = 6000;
+
+// Chains Honeypot.is can simulate, keyed by DexScreener chainId slug.
+const CHAIN_IDS = { ethereum: 1, bsc: 56, base: 8453 };
+
+const num = (v) => {
+ const n = typeof v === 'string' ? parseFloat(v) : Number(v);
+ return Number.isFinite(n) ? n : null;
+};
+
+/**
+ * Numeric Honeypot.is chain id for a DexScreener chainId slug, or null when
+ * Honeypot.is cannot simulate that chain (so callers skip it rather than
+ * misattribute a sibling deployment's report).
+ *
+ * @param {string|null|undefined} dexChainId e.g. 'ethereum', 'base', 'bsc'
+ * @returns {number|null}
+ */
+export function honeypotChainId(dexChainId) {
+ return CHAIN_IDS[String(dexChainId || '').toLowerCase()] ?? null;
+}
+
+/**
+ * Fetch and normalize a Honeypot.is v2 IsHoneypot report for one EVM token.
+ *
+ * Returns null when the address has no simulatable market (404) or the body
+ * is malformed; throws only on transport failure (timeout, DNS), which
+ * callers catch to null.
+ *
+ * @param {string} address EVM 0x token address
+ * @param {{ chainId?: number|null, signal?: AbortSignal }} [opts] `chainId`
+ * pins the simulation to one deployment (1 Ethereum, 56 BSC, 8453 Base);
+ * omitted, the API auto-detects (and misses Base-native tokens).
+ * @returns {Promise<null | {
+ * address: string,
+ * chain: { id: string|null, name: string|null, short: string|null }|null,
+ * is_honeypot: boolean|null, honeypot_reason: string|null,
+ * risk: string|null, risk_level: number|null, flags: string[],
+ * simulation_success: boolean|null,
+ * buy_tax: number|null, sell_tax: number|null, transfer_tax: number|null,
+ * open_source: boolean|null, is_proxy: boolean|null,
+ * token: { name: string|null, symbol: string|null, decimals: number|null, holders: number|null }|null,
+ * pair_address: string|null, pair_liquidity_usd: number|null,
+ * source: 'honeypot.is',
+ * }>}
+ */
+export async function fetchHoneypot(address, opts = {}) {
+ const url = new URL(HONEYPOT_API);
+ url.searchParams.set('address', address);
+ if (opts.chainId != null) url.searchParams.set('chainID', String(opts.chainId));
+ const r = await fetch(url, {
+ headers: { accept: 'application/json' },
+ signal: opts.signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ });
+ if (!r.ok) return null;
+ const d = await r.json().catch(() => null);
+ if (!d || typeof d !== 'object') return null;
+ // A real report always carries at least one of these three sections.
+ if (!d.honeypotResult && !d.summary && d.simulationSuccess == null) return null;
+ const sim = d.simulationResult || {};
+ const code = d.contractCode || {};
+ // Flags arrive both at the top level and under summary; entries may be
+ // plain strings or { flag, description, severity } objects.
+ const flags = [
+ ...(Array.isArray(d.summary?.flags) ? d.summary.flags : []),
+ ...(Array.isArray(d.flags) ? d.flags : []),
+ ]
+ .map((f) => (typeof f === 'string' ? f : f && typeof f === 'object' ? f.flag || f.name || null : null))
+ .filter(Boolean);
+ return {
+ address,
+ chain: d.chain
+ ? {
+ id: d.chain.id != null ? String(d.chain.id) : null,
+ name: d.chain.name || null,
+ short: d.chain.shortName || null,
+ }
+ : null,
+ is_honeypot: d.honeypotResult?.isHoneypot != null ? Boolean(d.honeypotResult.isHoneypot) : null,
+ honeypot_reason: d.honeypotResult?.honeypotReason || null,
+ risk: d.summary?.risk || null,
+ risk_level: num(d.summary?.riskLevel),
+ flags: [...new Set(flags)],
+ simulation_success: d.simulationSuccess != null ? Boolean(d.simulationSuccess) : null,
+ buy_tax: num(sim.buyTax),
+ sell_tax: num(sim.sellTax),
+ transfer_tax: num(sim.transferTax),
+ open_source: code.openSource != null ? Boolean(code.openSource) : null,
+ is_proxy: code.isProxy != null ? Boolean(code.isProxy) : null,
+ token: d.token
+ ? {
+ name: d.token.name || null,
+ symbol: d.token.symbol || null,
+ decimals: num(d.token.decimals),
+ holders: num(d.token.totalHolders),
+ }
+ : null,
+ pair_address: d.pairAddress || null,
+ pair_liquidity_usd: num(d.pair?.liquidity),
+ source: 'honeypot.is',
+ };
+}
diff --git a/api/_lib/oracle/market.js b/api/_lib/oracle/market.js
index 56184dd0f..9c4011d38 100644
--- a/api/_lib/oracle/market.js
+++ b/api/_lib/oracle/market.js
@@ -17,15 +17,18 @@
// · GeckoTerminal(keyless) — total supply, FDV, graduation %, CoinGecko id
// · GoPlus (keyless) — mint/freeze authority, mutable metadata, transfer
// fee, holder count + top-10 concentration
+// · RugCheck (keyless) - overall 0-100 risk score, named risk findings,
+// LP-lock % (second security opinion next to GoPlus)
// · Birdeye (keyed) — holders + circulating supply + price (redundancy)
// · CoinGecko (keyed) — ATH/ATL, market-cap rank, categories (listed coins)
//
// Merge precedence favors the richest/most-specific source per field; every
// number traces to a live upstream. Cached L1 (per-instance) + L2 (Upstash) so a
-// coin page poll almost never fans out to six upstreams.
+// coin page poll almost never fans out to seven upstreams.
import { cacheGet, cacheSet } from '../cache.js';
import { createCache } from '../mem-cache.js';
+import { fetchRugcheckSummary } from '../rugcheck.js';
import { bondingProgressPct } from '../pump-bonding.js';
import { gmgnTokenUrl } from '../../../src/shared/trading-terminals.js';
@@ -229,6 +232,26 @@ async function fromGoPlus(mint) {
};
}
+// RugCheck is the second security opinion next to GoPlus: GoPlus states the
+// on-chain facts (authorities, fees, concentration); RugCheck grades the mint
+// with its own risk engine (normalized 0-100 score where higher is riskier,
+// named findings, LP-lock coverage). The two blend in mergeMarketSources with
+// either one failing soft, so a GoPlus outage no longer blanks `security`.
+async function fromRugCheck(mint) {
+ const s = await fetchRugcheckSummary(mint);
+ if (!s) return null;
+ return {
+ sources: ['rugcheck'],
+ security: {
+ rugcheck_score: s.score_normalised,
+ rugcheck_level: s.level,
+ rugcheck_risks: s.risks,
+ lp_locked_pct: s.lp_locked_pct,
+ source: 'rugcheck',
+ },
+ };
+}
+
async function fromBirdeye(mint) {
const key = process.env.BIRDEYE_API_KEY;
if (!key) return null;
@@ -308,11 +331,11 @@ function pick(partials, path) {
*
* @param {string} mint
* @param {string} network
- * @param {{dex?:object,pump?:object,gecko?:object,goplus?:object,birdeye?:object,coingecko?:object}} p
+ * @param {{dex?:object,pump?:object,gecko?:object,goplus?:object,rugcheck?:object,birdeye?:object,coingecko?:object}} p
* @param {string} fetchedAt ISO timestamp (injected so the merge stays pure)
*/
export function mergeMarketSources(mint, network, p, fetchedAt) {
- const { dex, pump, gecko, goplus, birdeye, coingecko } = p;
+ const { dex, pump, gecko, goplus, rugcheck, birdeye, coingecko } = p;
// Precedence chains per field family (richest/most-specific first).
const idOrder = [pump, dex, gecko, birdeye];
const priceOrder = [dex, birdeye, gecko];
@@ -320,7 +343,19 @@ export function mergeMarketSources(mint, network, p, fetchedAt) {
const liqOrder = [dex, gecko, birdeye];
const supplyOrder = [gecko, birdeye, pump, goplus];
- const sources = [...new Set([dex, pump, gecko, goplus, birdeye, coingecko].filter(Boolean).flatMap((s) => s.sources || []))];
+ const sources = [...new Set([dex, pump, gecko, goplus, rugcheck, birdeye, coingecko].filter(Boolean).flatMap((s) => s.sources || []))];
+
+ // Security blends the two independent opinions: GoPlus's on-chain facts keep
+ // their fields, RugCheck contributes its score/findings/LP-lock alongside
+ // (`rugcheck_*` keys, no collisions). Either opinion alone still yields a
+ // security block; `source` names exactly who answered.
+ const security = goplus?.security || rugcheck?.security
+ ? {
+ ...(rugcheck?.security || {}),
+ ...(goplus?.security || {}),
+ source: [goplus?.security ? 'goplus' : null, rugcheck?.security ? 'rugcheck' : null].filter(Boolean).join('+'),
+ }
+ : null;
// pump.fun graduation truth: prefer the explicit flag, fall back to Gecko's %.
const pf = pump?.pumpfun || {};
@@ -390,7 +425,7 @@ export function mergeMarketSources(mint, network, p, fetchedAt) {
decimals: num(pick([gecko, birdeye], 'identity.decimals')) ?? 6,
},
pumpfun,
- security: goplus?.security || null,
+ security,
top_holders: goplus?.top_holders || [],
listing: coingecko?.listing || (gecko?.coingecko_id ? { coingecko_id: gecko.coingecko_id } : null),
pairs: dex?.pairs || [],
@@ -439,23 +474,24 @@ export async function fetchCoinMarket(mint, network = 'mainnet', { fresh = false
}
// Stage 1: every keyless/keyed source that resolves from the mint alone.
- const [dex, pump, gecko, goplus, birdeye] = await Promise.all([
+ const [dex, pump, gecko, goplus, rugcheck, birdeye] = await Promise.all([
fromDexScreener(mint).catch(() => null),
network === 'mainnet' ? fromPumpFun(mint).catch(() => null) : Promise.resolve(null),
fromGeckoTerminal(mint).catch(() => null),
network === 'mainnet' ? fromGoPlus(mint).catch(() => null) : Promise.resolve(null),
+ network === 'mainnet' ? fromRugCheck(mint).catch(() => null) : Promise.resolve(null),
fromBirdeye(mint).catch(() => null),
]);
// Every upstream missed and we have no price — a true "no market" answer.
- if (!dex && !pump && !gecko && !goplus && !birdeye) return null;
+ if (!dex && !pump && !gecko && !goplus && !rugcheck && !birdeye) return null;
// Stage 2: CoinGecko, but only for coins Gecko proved are listed (has an id).
const coingecko = gecko?.coingecko_id
? await fromCoinGecko(gecko.coingecko_id).catch(() => null)
: null;
- const merged = mergeMarketSources(mint, network, { dex, pump, gecko, goplus, birdeye, coingecko }, new Date().toISOString());
+ const merged = mergeMarketSources(mint, network, { dex, pump, gecko, goplus, rugcheck, birdeye, coingecko }, new Date().toISOString());
// Only cache a read that actually established a live price — never memoize a
// hollow all-null result that a transient outage produced.
diff --git a/api/_lib/rugcheck.js b/api/_lib/rugcheck.js
new file mode 100644
index 000000000..85b2ee603
--- /dev/null
+++ b/api/_lib/rugcheck.js
@@ -0,0 +1,89 @@
+// RugCheck: keyless Solana token risk reports (api.rugcheck.xyz).
+//
+// The Oracle market aggregator (api/_lib/oracle/market.js) uses this as the
+// second security opinion next to GoPlus. GoPlus states the on-chain facts
+// (mint/freeze authority, transfer fee, holder concentration); RugCheck runs
+// its own risk engine over the same mint and answers with an overall 0-100
+// score, named risk findings, and the LP-lock coverage GoPlus does not have.
+// Either source failing degrades its slice to null, never the whole read.
+//
+// Endpoint (verified live 2026-08-05, no key, no auth):
+// GET https://api.rugcheck.xyz/v1/tokens/{mint}/report/summary
+// -> { tokenProgram, tokenType, risks: [{ name, value, description, score,
+// level }], score, score_normalised, lpLockedPct }
+// `score_normalised` is 0-100 with HIGHER meaning MORE risk; each finding's
+// `level` is RugCheck's own grading ("warn" / "danger"). Unknown or invalid
+// mints answer 400 with an error body.
+
+const RUGCHECK_API = 'https://api.rugcheck.xyz/v1';
+const FETCH_TIMEOUT_MS = 6000;
+
+const num = (v) => {
+ const n = typeof v === 'string' ? parseFloat(v) : Number(v);
+ return Number.isFinite(n) ? n : null;
+};
+
+/**
+ * Map RugCheck's normalized 0-100 score onto the platform's shared risk
+ * ladder. Same cut points as buildTokenRisk (api/_lib/token-market.js), so
+ * "high" means the same thing wherever a holder reads it.
+ *
+ * @param {number|null} scoreNormalised 0-100, higher = riskier
+ * @returns {'low'|'medium'|'high'|'critical'|null}
+ */
+export function rugcheckLevel(scoreNormalised) {
+ if (scoreNormalised == null || !Number.isFinite(scoreNormalised)) return null;
+ if (scoreNormalised >= 70) return 'critical';
+ if (scoreNormalised >= 45) return 'high';
+ if (scoreNormalised >= 22) return 'medium';
+ return 'low';
+}
+
+/**
+ * Fetch and normalize RugCheck's summary risk report for one Solana mint.
+ *
+ * Returns null when RugCheck does not know the mint or answers with a
+ * non-2xx / malformed body; throws only on transport failure (timeout, DNS),
+ * which fan-out callers catch to null, mirroring the GoPlus adapter in
+ * oracle/market.js.
+ *
+ * @param {string} mint Solana mint address
+ * @param {{ signal?: AbortSignal }} [opts]
+ * @returns {Promise<null | {
+ * mint: string,
+ * score_normalised: number|null,
+ * level: 'low'|'medium'|'high'|'critical'|null,
+ * risks: Array<{ name: string, description: string|null, level: string|null, score: number|null }>,
+ * lp_locked_pct: number|null,
+ * token_program: string|null,
+ * }>}
+ */
+export async function fetchRugcheckSummary(mint, opts = {}) {
+ const r = await fetch(`${RUGCHECK_API}/tokens/${encodeURIComponent(mint)}/report/summary`, {
+ headers: { accept: 'application/json' },
+ signal: opts.signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ });
+ if (!r.ok) return null;
+ const d = await r.json().catch(() => null);
+ if (!d || typeof d !== 'object') return null;
+ const score = num(d.score_normalised);
+ // A real report always carries the normalized score and/or a risks array;
+ // anything else (error bodies, shape drift) is treated as "no report".
+ if (score == null && !Array.isArray(d.risks)) return null;
+ const clamped = score == null ? null : Math.max(0, Math.min(100, score));
+ return {
+ mint,
+ score_normalised: clamped,
+ level: rugcheckLevel(clamped),
+ risks: (Array.isArray(d.risks) ? d.risks : [])
+ .filter((x) => x && x.name)
+ .map((x) => ({
+ name: String(x.name),
+ description: x.description || null,
+ level: x.level || null,
+ score: num(x.score),
+ })),
+ lp_locked_pct: num(d.lpLockedPct),
+ token_program: d.tokenProgram || null,
+ };
+}
diff --git a/api/_lib/token-market.js b/api/_lib/token-market.js
index c9df84ced..acf1c342a 100644
--- a/api/_lib/token-market.js
+++ b/api/_lib/token-market.js
@@ -8,8 +8,15 @@
//
// The $THREE-specific oracle (/api/x402/three-intel) keeps its own THREE-branded
// copy on purpose — it is pinned to one mint and unit-tested as such.
+//
+// EVM addresses additionally get a keyless Honeypot.is sell-simulation
+// (api/_lib/honeypot.js) attached as `honeypot`, fetched in parallel with the
+// market read and failing soft to null; buildTokenRisk folds it into the risk
+// score. Solana mints keep their security read in the Oracle aggregator
+// (GoPlus + RugCheck, api/_lib/oracle/market.js) and /api/v1/token/security.
import { isValidSolanaAddress, isValidEvmAddress } from './validate.js';
+import { fetchHoneypot, honeypotChainId } from './honeypot.js';
const DEXSCREENER_TOKENS = 'https://api.dexscreener.com/latest/dex/tokens/';
@@ -45,19 +52,31 @@ function num(v) {
* the buyer is never charged for missing data).
*
* @param {string} ca contract address (Solana mint or EVM 0x)
- * @param {{ signal?: AbortSignal, chain?: string|null }} [opts] `chain` restricts
- * the pair search to one DexScreener chainId (e.g. 'solana', 'base') — an EVM
- * contract deployed on several chains otherwise resolves to whichever chain
- * holds the deepest pool.
+ * @param {{ signal?: AbortSignal, chain?: string|null, security?: boolean }} [opts]
+ * `chain` restricts the pair search to one DexScreener chainId (e.g.
+ * 'solana', 'base'); an EVM contract deployed on several chains otherwise
+ * resolves to whichever chain holds the deepest pool. `security: false`
+ * skips the Honeypot.is simulation for callers that only want price shape.
* @returns {Promise<null | {
* mint: string, symbol: string|null, name: string|null, image: string|null,
* chain: string|null, dex: string|null, pair_url: string|null,
* price_usd: number|null, change_24h: number|null, market_cap_usd: number|null,
* fdv_usd: number|null,
* liquidity_usd: number|null, volume_24h_usd: number|null, pair_created_at: number|null,
+ * honeypot: object|null,
* }>}
*/
export async function fetchTokenMarket(ca, opts = {}) {
+ // EVM addresses also get Honeypot.is's keyless buy/sell simulation, kicked
+ // off in parallel with the market read and failing soft to null. When the
+ // caller pinned a chain Honeypot.is cannot simulate, skip it entirely
+ // rather than let auto-detection describe a sibling deployment elsewhere.
+ const pinnedHpChain = opts.chain ? honeypotChainId(opts.chain) : undefined;
+ const wantHoneypot = chainOf(ca) === 'evm' && opts.security !== false && pinnedHpChain !== null;
+ const honeypotPromise = wantHoneypot
+ ? fetchHoneypot(ca, { chainId: pinnedHpChain ?? undefined }).catch(() => null)
+ : Promise.resolve(null);
+
const r = await fetch(`${DEXSCREENER_TOKENS}${encodeURIComponent(ca)}`, {
headers: { Accept: 'application/json' },
signal: opts.signal ?? AbortSignal.timeout(6000),
@@ -87,6 +106,23 @@ export async function fetchTokenMarket(ca, opts = {}) {
const pairLabel =
base.symbol && quote.symbol ? `${base.symbol}/${quote.symbol}` : null;
+ // Attribute the honeypot simulation to the SAME deployment DexScreener
+ // resolved. If the deepest pool lives on a chain Honeypot.is cannot
+ // simulate, drop the report (it would describe a sibling deployment). If
+ // the chain is simulatable but the unpinned answer missed or landed on a
+ // different chain (auto-detection misses Base-native tokens), re-run once,
+ // pinned to the resolved chain.
+ let honeypot = await honeypotPromise;
+ if (wantHoneypot) {
+ const want = honeypotChainId(p.chainId);
+ const got = honeypot?.chain?.id != null ? String(honeypot.chain.id) : null;
+ if (want == null) {
+ honeypot = null;
+ } else if (got !== String(want) && (honeypot != null || pinnedHpChain == null)) {
+ honeypot = await fetchHoneypot(ca, { chainId: want }).catch(() => null);
+ }
+ }
+
return {
mint: tok.address || ca,
symbol: tok.symbol || null,
@@ -115,6 +151,9 @@ export async function fetchTokenMarket(ca, opts = {}) {
// Buy/sell transaction counts over 24 h — real order flow, the difference
// between accumulation and distribution behind the same price move.
txns_24h: { buys: num(txns.h24?.buys), sells: num(txns.h24?.sells) },
+ // Honeypot.is buy/sell simulation for EVM deployments; null for Solana
+ // mints, unsupported chains, or when the simulator is unavailable.
+ honeypot,
};
}
@@ -137,7 +176,8 @@ function fmtAge(ms) {
/**
* Score the safety of any token from its live market shape — the due-diligence
* layer behind the CA → x402 oracle. Higher score = MORE risk (0 safe … 100
- * critical). Every input is real DexScreener data; nothing is fabricated, and a
+ * critical). Every input is real DexScreener data (plus the real Honeypot.is
+ * simulation on `m.honeypot` for EVM tokens); nothing is fabricated, and a
* missing field degrades to an honest "unknown" factor rather than a fake pass.
*
* `now` is injectable so the result is deterministic under test.
@@ -200,7 +240,38 @@ export function buildTokenRisk(m, now = Date.now()) {
}
}
- // 4) Order flow — are the trades net buys or net sells over 24 h?
+ // 4) Honeypot simulation (EVM tokens): Honeypot.is actually buys and sells
+ // the token on a fork of its chain. A failed sell is the one scam the
+ // market shape above cannot see; heavy taxes and an unverified contract
+ // are its milder cousins. Absent for Solana mints and when the simulator
+ // is unavailable, so the factor list degrades honestly, never fabricates.
+ const hp = m.honeypot;
+ if (hp) {
+ if (hp.is_honeypot === true) {
+ factors.push({ label: 'Honeypot', status: 'critical', detail: `Sell simulation FAILED${hp.honeypot_reason ? ` (${hp.honeypot_reason})` : ''}: holders cannot exit.` });
+ risk += 55;
+ } else if (hp.simulation_success === false) {
+ factors.push({ label: 'Honeypot', status: 'high', detail: 'Buy/sell simulation could not complete; sellability is unproven.' });
+ risk += 18;
+ } else {
+ const tax = Math.max(hp.buy_tax ?? 0, hp.sell_tax ?? 0, hp.transfer_tax ?? 0);
+ if (tax >= 20) {
+ factors.push({ label: 'Honeypot', status: 'high', detail: `Sell simulation passes but taxes run ${Math.round(tax)}%; exits are heavily skimmed.` });
+ risk += 22;
+ } else if (tax >= 10) {
+ factors.push({ label: 'Honeypot', status: 'medium', detail: `Simulated round-trip tax is ${Math.round(tax)}%.` });
+ risk += 10;
+ } else {
+ factors.push({ label: 'Honeypot', status: 'low', detail: 'Sell simulation passes with negligible taxes.' });
+ }
+ }
+ if (hp.open_source === false) {
+ factors.push({ label: 'Contract', status: 'medium', detail: 'Contract source is not verified; behavior cannot be audited.' });
+ risk += 8;
+ }
+ }
+
+ // 5) Order flow: are the trades net buys or net sells over 24 h?
const buys = m.txns_24h?.buys;
const sells = m.txns_24h?.sells;
if (buys != null && sells != null && buys + sells > 0) {
diff --git a/tests/api/honeypot.test.js b/tests/api/honeypot.test.js
new file mode 100644
index 000000000..fe077013f
--- /dev/null
+++ b/tests/api/honeypot.test.js
@@ -0,0 +1,269 @@
+// Honeypot.is client (api/_lib/honeypot.js) and its wiring into the generic
+// token security snapshot (api/_lib/token-market.js).
+//
+// The EVM fixture mirrors the live api.honeypot.is/v2/IsHoneypot shape
+// captured 2026-08-05 for WETH on Ethereum (a major, well-known token used
+// for shape verification only). The Solana mint is $THREE, the platform's
+// own promoted coin. No network is touched (URL-routing fetch mock).
+
+import { describe, it, expect, vi, afterAll } from 'vitest';
+import { fetchHoneypot, honeypotChainId } from '../../api/_lib/honeypot.js';
+import { fetchTokenMarket, buildTokenRisk } from '../../api/_lib/token-market.js';
+
+const WETH = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const NOW = Date.parse('2026-08-05T00:00:00.000Z');
+
+const realFetch = global.fetch;
+afterAll(() => { global.fetch = realFetch; });
+
+function jres(obj, ok = true, status = 200) {
+ return { ok, status, json: async () => obj, text: async () => JSON.stringify(obj) };
+}
+
+// Live shape from GET /v2/IsHoneypot?address={WETH} (captured 2026-08-05),
+// trimmed to the sections the client reads.
+const WETH_REPORT = {
+ token: { name: 'Wrapped Ether', symbol: 'WETH', decimals: 18, address: WETH, totalHolders: 3311580 },
+ summary: { risk: 'low', riskLevel: 1, flags: [] },
+ simulationSuccess: true,
+ honeypotResult: { isHoneypot: false },
+ simulationResult: { buyTax: 0, sellTax: 0, transferTax: 0, buyGas: '146653', sellGas: '130824' },
+ flags: [],
+ contractCode: { openSource: true, rootOpenSource: true, isProxy: false, hasProxyCalls: false },
+ chain: { id: '1', name: 'Ethereum', shortName: 'eth', currency: 'ETH' },
+ pairAddress: '0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640',
+ pair: { pair: { name: 'Uniswap V3: USDC-WETH' }, liquidity: 95423022.35809729 },
+};
+
+describe('fetchHoneypot', () => {
+ it('normalizes the live WETH report shape', async () => {
+ global.fetch = vi.fn(async (url) => {
+ const u = new URL(String(url));
+ expect(u.origin + u.pathname).toBe('https://api.honeypot.is/v2/IsHoneypot');
+ expect(u.searchParams.get('address')).toBe(WETH);
+ expect(u.searchParams.get('chainID')).toBeNull();
+ return jres(WETH_REPORT);
+ });
+ const h = await fetchHoneypot(WETH);
+ expect(h.is_honeypot).toBe(false);
+ expect(h.simulation_success).toBe(true);
+ expect(h.buy_tax).toBe(0);
+ expect(h.sell_tax).toBe(0);
+ expect(h.open_source).toBe(true);
+ expect(h.is_proxy).toBe(false);
+ expect(h.risk).toBe('low');
+ expect(h.risk_level).toBe(1);
+ expect(h.chain).toEqual({ id: '1', name: 'Ethereum', short: 'eth' });
+ expect(h.token).toEqual({ name: 'Wrapped Ether', symbol: 'WETH', decimals: 18, holders: 3311580 });
+ expect(h.pair_address).toBe('0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640');
+ expect(h.pair_liquidity_usd).toBeCloseTo(95423022.36, 1);
+ expect(h.source).toBe('honeypot.is');
+ });
+
+ it('pins the deployment when chainId is given', async () => {
+ global.fetch = vi.fn(async (url) => {
+ expect(new URL(String(url)).searchParams.get('chainID')).toBe('8453');
+ return jres({ ...WETH_REPORT, chain: { id: '8453', name: 'Base', shortName: 'base', currency: 'ETH' } });
+ });
+ const h = await fetchHoneypot(WETH, { chainId: 8453 });
+ expect(h.chain.id).toBe('8453');
+ });
+
+ it('surfaces a honeypot verdict with its reason and flags', async () => {
+ global.fetch = vi.fn(async () => jres({
+ ...WETH_REPORT,
+ summary: { risk: 'honeypot', riskLevel: 100, flags: [{ flag: 'honeypot', severity: 'critical' }] },
+ honeypotResult: { isHoneypot: true, honeypotReason: 'Unable to sell' },
+ simulationResult: { buyTax: 0, sellTax: 100, transferTax: 0 },
+ }));
+ const h = await fetchHoneypot(WETH);
+ expect(h.is_honeypot).toBe(true);
+ expect(h.honeypot_reason).toBe('Unable to sell');
+ expect(h.sell_tax).toBe(100);
+ expect(h.flags).toContain('honeypot');
+ });
+
+ it('returns null on 404 (live: {"code":404,"error":"No pairs found"})', async () => {
+ global.fetch = vi.fn(async () => jres({ code: 404, error: 'No pairs found' }, false, 404));
+ expect(await fetchHoneypot(WETH)).toBeNull();
+ });
+
+ it('returns null on a malformed body', async () => {
+ global.fetch = vi.fn(async () => jres({ something: 'else' }));
+ expect(await fetchHoneypot(WETH)).toBeNull();
+ global.fetch = vi.fn(async () => ({ ok: true, status: 200, json: async () => { throw new Error('bad json'); } }));
+ expect(await fetchHoneypot(WETH)).toBeNull();
+ });
+});
+
+describe('honeypotChainId', () => {
+ it('maps the DexScreener slugs Honeypot.is can simulate', () => {
+ expect(honeypotChainId('ethereum')).toBe(1);
+ expect(honeypotChainId('bsc')).toBe(56);
+ expect(honeypotChainId('base')).toBe(8453);
+ });
+ it('answers null for chains it cannot simulate', () => {
+ expect(honeypotChainId('polygon')).toBeNull();
+ expect(honeypotChainId('solana')).toBeNull();
+ expect(honeypotChainId(null)).toBeNull();
+ });
+});
+
+// ── fetchTokenMarket: honeypot attachment ────────────────────────────────────
+
+function dexPair(chainId, extra = {}) {
+ return {
+ chainId,
+ dexId: 'uniswap',
+ url: 'https://dexscreener.com/x',
+ pairAddress: '0xPAIR',
+ baseToken: { address: WETH, name: 'Wrapped Ether', symbol: 'WETH' },
+ quoteToken: { address: '0x0000000000000000000000000000000000000002', symbol: 'USDC' },
+ priceUsd: '3600',
+ priceChange: { h24: 1.2 },
+ volume: { h24: 1000000 },
+ liquidity: { usd: 95000000 },
+ marketCap: 9000000000,
+ txns: { h24: { buys: 500, sells: 400 } },
+ pairCreatedAt: NOW - 400 * 86_400_000,
+ ...extra,
+ };
+}
+
+describe('fetchTokenMarket honeypot wiring', () => {
+ it('attaches the Honeypot.is report for an EVM address', async () => {
+ global.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes('dexscreener.com')) return jres({ pairs: [dexPair('ethereum')] });
+ if (u.includes('api.honeypot.is')) return jres(WETH_REPORT);
+ throw new Error(`unexpected url ${u}`);
+ });
+ const m = await fetchTokenMarket(WETH);
+ expect(m.symbol).toBe('WETH');
+ expect(m.honeypot).not.toBeNull();
+ expect(m.honeypot.is_honeypot).toBe(false);
+ expect(m.honeypot.chain.id).toBe('1');
+ });
+
+ it('re-pins to the resolved chain when unpinned detection misses (Base-native case)', async () => {
+ // Verified live: auto-detection answers 404 for a Base-only deployment
+ // and succeeds pinned with chainID=8453.
+ const hpCalls = [];
+ global.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes('dexscreener.com')) return jres({ pairs: [dexPair('base')] });
+ if (u.includes('api.honeypot.is')) {
+ const chainID = new URL(u).searchParams.get('chainID');
+ hpCalls.push(chainID);
+ if (chainID === '8453') return jres({ ...WETH_REPORT, chain: { id: '8453', name: 'Base', shortName: 'base', currency: 'ETH' } });
+ return jres({ code: 404, error: 'Token not found' }, false, 404);
+ }
+ throw new Error(`unexpected url ${u}`);
+ });
+ const m = await fetchTokenMarket(WETH);
+ expect(hpCalls).toEqual([null, '8453']);
+ expect(m.honeypot.chain.id).toBe('8453');
+ });
+
+ it('drops a sibling-deployment report when the resolved chain is not simulatable', async () => {
+ global.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes('dexscreener.com')) return jres({ pairs: [dexPair('polygon')] });
+ if (u.includes('api.honeypot.is')) return jres(WETH_REPORT); // auto-detect found the Ethereum deployment
+ throw new Error(`unexpected url ${u}`);
+ });
+ const m = await fetchTokenMarket(WETH);
+ expect(m.chain).toBe('polygon');
+ expect(m.honeypot).toBeNull();
+ });
+
+ it('never calls Honeypot.is for a Solana mint', async () => {
+ global.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes('api.honeypot.is')) throw new Error('honeypot must not be called for solana');
+ if (u.includes('dexscreener.com')) {
+ return jres({ pairs: [{ ...dexPair('solana'), baseToken: { address: THREE, name: 'three.ws', symbol: 'three' }, dexId: 'pumpswap' }] });
+ }
+ throw new Error(`unexpected url ${u}`);
+ });
+ const m = await fetchTokenMarket(THREE);
+ expect(m.symbol).toBe('three');
+ expect(m.honeypot).toBeNull();
+ expect(global.fetch.mock.calls.every(([u]) => !String(u).includes('api.honeypot.is'))).toBe(true);
+ });
+
+ it('security: false opts out of the simulation entirely', async () => {
+ global.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes('api.honeypot.is')) throw new Error('honeypot must not be called when opted out');
+ if (u.includes('dexscreener.com')) return jres({ pairs: [dexPair('ethereum')] });
+ throw new Error(`unexpected url ${u}`);
+ });
+ const m = await fetchTokenMarket(WETH, { security: false });
+ expect(m.honeypot).toBeNull();
+ });
+
+ it('a Honeypot.is outage fails soft: the market read still answers', async () => {
+ global.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes('api.honeypot.is')) throw new Error('ECONNRESET');
+ if (u.includes('dexscreener.com')) return jres({ pairs: [dexPair('ethereum')] });
+ throw new Error(`unexpected url ${u}`);
+ });
+ const m = await fetchTokenMarket(WETH);
+ expect(m.price_usd).toBe(3600);
+ expect(m.honeypot).toBeNull();
+ });
+});
+
+// ── buildTokenRisk: the honeypot factor ──────────────────────────────────────
+
+// A healthy market shape so only the honeypot factor moves the score.
+const HEALTHY = {
+ symbol: 'WETH',
+ liquidity_usd: 95_000_000,
+ market_cap_usd: 9_000_000_000,
+ pair_created_at: NOW - 400 * 86_400_000,
+ txns_24h: { buys: 500, sells: 400 },
+};
+
+describe('buildTokenRisk honeypot factor', () => {
+ it('a failed sell simulation is critical and dominates the score', () => {
+ const r = buildTokenRisk({ ...HEALTHY, honeypot: { is_honeypot: true, honeypot_reason: 'Unable to sell', simulation_success: true, buy_tax: 0, sell_tax: 100, transfer_tax: 0, open_source: true } }, NOW);
+ const f = r.factors.find((x) => x.label === 'Honeypot');
+ expect(f.status).toBe('critical');
+ expect(f.detail).toContain('Unable to sell');
+ expect(r.score).toBeGreaterThanOrEqual(55);
+ expect(['high', 'critical']).toContain(r.level);
+ });
+
+ it('an incomplete simulation reads as unproven sellability (high)', () => {
+ const r = buildTokenRisk({ ...HEALTHY, honeypot: { is_honeypot: null, simulation_success: false, buy_tax: null, sell_tax: null, transfer_tax: null, open_source: true } }, NOW);
+ expect(r.factors.find((x) => x.label === 'Honeypot').status).toBe('high');
+ });
+
+ it('heavy taxes are flagged even when the sell passes', () => {
+ const r = buildTokenRisk({ ...HEALTHY, honeypot: { is_honeypot: false, simulation_success: true, buy_tax: 2, sell_tax: 25, transfer_tax: 0, open_source: true } }, NOW);
+ const f = r.factors.find((x) => x.label === 'Honeypot');
+ expect(f.status).toBe('high');
+ expect(f.detail).toContain('25%');
+ });
+
+ it('an unverified contract adds its own factor', () => {
+ const r = buildTokenRisk({ ...HEALTHY, honeypot: { is_honeypot: false, simulation_success: true, buy_tax: 0, sell_tax: 0, transfer_tax: 0, open_source: false } }, NOW);
+ expect(r.factors.find((x) => x.label === 'Contract').status).toBe('medium');
+ });
+
+ it('a clean simulation reads low and the level stays low', () => {
+ const r = buildTokenRisk({ ...HEALTHY, honeypot: { is_honeypot: false, simulation_success: true, buy_tax: 0, sell_tax: 0, transfer_tax: 0, open_source: true } }, NOW);
+ expect(r.factors.find((x) => x.label === 'Honeypot').status).toBe('low');
+ expect(r.level).toBe('low');
+ });
+
+ it('no honeypot data (Solana / unavailable) leaves the read unchanged', () => {
+ const r = buildTokenRisk({ ...HEALTHY, honeypot: null }, NOW);
+ expect(r.factors.some((x) => x.label === 'Honeypot')).toBe(false);
+ expect(r.factors.some((x) => x.label === 'Contract')).toBe(false);
+ });
+});
diff --git a/tests/api/rugcheck.test.js b/tests/api/rugcheck.test.js
new file mode 100644
index 000000000..f423d7c25
--- /dev/null
+++ b/tests/api/rugcheck.test.js
@@ -0,0 +1,205 @@
+// RugCheck client (api/_lib/rugcheck.js) and its wiring into the Oracle
+// live-market aggregator (api/_lib/oracle/market.js) as the second security
+// opinion next to GoPlus.
+//
+// Fixtures mirror the live api.rugcheck.xyz shapes captured 2026-08-05 for
+// $THREE (the platform's own promoted coin, the only real mint used here); no
+// network is touched (URL-routing fetch mock, oracle-market test style).
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { fetchRugcheckSummary, rugcheckLevel } from '../../api/_lib/rugcheck.js';
+import { mergeMarketSources, fetchCoinMarket, __resetCoinMarketCache } from '../../api/_lib/oracle/market.js';
+
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const AT = '2026-08-05T00:00:00.000Z';
+
+const realFetch = global.fetch;
+const realBirdeyeKey = process.env.BIRDEYE_API_KEY;
+afterAll(() => {
+ global.fetch = realFetch;
+ if (realBirdeyeKey == null) delete process.env.BIRDEYE_API_KEY;
+ else process.env.BIRDEYE_API_KEY = realBirdeyeKey;
+});
+
+function jres(obj, ok = true, status = 200) {
+ return { ok, status, json: async () => obj, text: async () => JSON.stringify(obj) };
+}
+
+// Live shape from GET /v1/tokens/{$THREE}/report/summary (captured 2026-08-05).
+const THREE_SUMMARY = {
+ tokenProgram: 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',
+ tokenType: '',
+ risks: [],
+ score: 1,
+ score_normalised: 1,
+ lpLockedPct: 62.07117368099572,
+};
+
+describe('fetchRugcheckSummary', () => {
+ it('normalizes the live summary shape for $THREE', async () => {
+ global.fetch = vi.fn(async (url) => {
+ expect(String(url)).toBe(`https://api.rugcheck.xyz/v1/tokens/${THREE}/report/summary`);
+ return jres(THREE_SUMMARY);
+ });
+ const s = await fetchRugcheckSummary(THREE);
+ expect(s.mint).toBe(THREE);
+ expect(s.score_normalised).toBe(1);
+ expect(s.level).toBe('low');
+ expect(s.risks).toEqual([]);
+ expect(s.lp_locked_pct).toBeCloseTo(62.07, 1);
+ expect(s.token_program).toBe('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb');
+ });
+
+ it('maps populated risk findings (live shape: name/value/description/score/level)', async () => {
+ global.fetch = vi.fn(async () => jres({
+ tokenProgram: 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',
+ tokenType: '',
+ risks: [{ name: 'Creator history of rugged tokens', value: '', description: 'Creator has a history of rugging tokens.', score: 115200, level: 'danger' }],
+ score: 115201,
+ score_normalised: 80,
+ lpLockedPct: 0,
+ }));
+ const s = await fetchRugcheckSummary(THREE);
+ expect(s.score_normalised).toBe(80);
+ expect(s.level).toBe('critical');
+ expect(s.risks).toEqual([
+ { name: 'Creator history of rugged tokens', description: 'Creator has a history of rugging tokens.', level: 'danger', score: 115200 },
+ ]);
+ });
+
+ it('clamps an out-of-range score into 0-100', async () => {
+ global.fetch = vi.fn(async () => jres({ risks: [], score_normalised: 250, lpLockedPct: 0 }));
+ const s = await fetchRugcheckSummary(THREE);
+ expect(s.score_normalised).toBe(100);
+ expect(s.level).toBe('critical');
+ });
+
+ it('returns null on a non-2xx answer (RugCheck 400s unknown/invalid mints)', async () => {
+ global.fetch = vi.fn(async () => jres({ error: 'invalid length, expected 32, got 6' }, false, 400));
+ expect(await fetchRugcheckSummary(THREE)).toBeNull();
+ });
+
+ it('returns null on a malformed or shape-drifted body', async () => {
+ global.fetch = vi.fn(async () => jres({ something: 'else' }));
+ expect(await fetchRugcheckSummary(THREE)).toBeNull();
+ global.fetch = vi.fn(async () => ({ ok: true, status: 200, json: async () => { throw new Error('bad json'); } }));
+ expect(await fetchRugcheckSummary(THREE)).toBeNull();
+ });
+});
+
+describe('rugcheckLevel', () => {
+ it('uses the same cut points as buildTokenRisk (22 / 45 / 70)', () => {
+ expect(rugcheckLevel(0)).toBe('low');
+ expect(rugcheckLevel(21)).toBe('low');
+ expect(rugcheckLevel(22)).toBe('medium');
+ expect(rugcheckLevel(44)).toBe('medium');
+ expect(rugcheckLevel(45)).toBe('high');
+ expect(rugcheckLevel(69)).toBe('high');
+ expect(rugcheckLevel(70)).toBe('critical');
+ expect(rugcheckLevel(null)).toBeNull();
+ });
+});
+
+// ── mergeMarketSources: GoPlus + RugCheck security blend ─────────────────────
+
+const GOPLUS_PARTIAL = {
+ sources: ['goplus'],
+ holders: 12943,
+ security: { mint_authority_revoked: true, freeze_authority_revoked: true, metadata_mutable: false, transfer_fee_pct: 0, top10_holder_pct: 17.34, source: 'goplus' },
+ top_holders: [{ account: 'poolAcct', pct: 3.37, is_locked: false, tag: null }],
+};
+const RUGCHECK_PARTIAL = {
+ sources: ['rugcheck'],
+ security: { rugcheck_score: 1, rugcheck_level: 'low', rugcheck_risks: [], lp_locked_pct: 62.07, source: 'rugcheck' },
+};
+const DEX_PARTIAL = { sources: ['dexscreener'], identity: { symbol: 'three' }, price_usd: 0.0021, change: {}, volume: {}, pairs: [], links: {} };
+
+describe('mergeMarketSources security second opinion', () => {
+ it('blends GoPlus facts with the RugCheck grade when both answer', () => {
+ const m = mergeMarketSources(THREE, 'mainnet', { dex: DEX_PARTIAL, pump: null, gecko: null, goplus: GOPLUS_PARTIAL, rugcheck: RUGCHECK_PARTIAL, birdeye: null, coingecko: null }, AT);
+ expect(m.security.mint_authority_revoked).toBe(true);
+ expect(m.security.top10_holder_pct).toBe(17.34);
+ expect(m.security.rugcheck_score).toBe(1);
+ expect(m.security.rugcheck_level).toBe('low');
+ expect(m.security.lp_locked_pct).toBe(62.07);
+ expect(m.security.source).toBe('goplus+rugcheck');
+ expect(m.sources).toEqual(expect.arrayContaining(['goplus', 'rugcheck']));
+ });
+
+ it('RugCheck alone still yields a security block (GoPlus outage fails soft)', () => {
+ const m = mergeMarketSources(THREE, 'mainnet', { dex: DEX_PARTIAL, pump: null, gecko: null, goplus: null, rugcheck: RUGCHECK_PARTIAL, birdeye: null, coingecko: null }, AT);
+ expect(m.security.rugcheck_score).toBe(1);
+ expect(m.security.rugcheck_risks).toEqual([]);
+ expect(m.security.source).toBe('rugcheck');
+ expect(m.top_holders).toEqual([]);
+ });
+
+ it('GoPlus alone keeps its original read (RugCheck outage fails soft)', () => {
+ const m = mergeMarketSources(THREE, 'mainnet', { dex: DEX_PARTIAL, pump: null, gecko: null, goplus: GOPLUS_PARTIAL, rugcheck: null, birdeye: null, coingecko: null }, AT);
+ expect(m.security.mint_authority_revoked).toBe(true);
+ expect(m.security.source).toBe('goplus');
+ expect(m.security.rugcheck_score).toBeUndefined();
+ });
+
+ it('neither opinion answering leaves security null, as before', () => {
+ const m = mergeMarketSources(THREE, 'mainnet', { dex: DEX_PARTIAL, pump: null, gecko: null, goplus: null, rugcheck: null, birdeye: null, coingecko: null }, AT);
+ expect(m.security).toBeNull();
+ });
+});
+
+// ── fetchCoinMarket: RugCheck in the live fan-out ────────────────────────────
+
+function routeFetch(overrides = {}) {
+ return vi.fn(async (url) => {
+ const u = String(url);
+ for (const [needle, answer] of Object.entries(overrides)) {
+ if (u.includes(needle)) return answer(u);
+ }
+ if (u.includes('dexscreener.com')) return jres({ pairs: [{ chainId: 'solana', dexId: 'pumpswap', url: 'https://d/x', pairAddress: 'P', baseToken: { name: 'three.ws', symbol: 'three' }, quoteToken: { symbol: 'SOL' }, priceUsd: '0.0021', priceChange: { h24: 3 }, volume: { h24: 465000 }, liquidity: { usd: 223000 }, marketCap: 2100000 }] });
+ if (u.includes('frontend-api-v3.pump.fun')) return jres({}, false, 404);
+ if (u.includes('geckoterminal.com')) return jres({ data: { attributes: { decimals: 6, price_usd: '0.0021' } } });
+ if (u.includes('gopluslabs.io')) return jres({ result: { [THREE]: { holder_count: 12943, mintable: { status: '0' }, freezable: { status: '0' }, metadata_mutable: { status: '0' }, transfer_fee: {}, holders: [] } } });
+ if (u.includes('api.rugcheck.xyz')) return jres(THREE_SUMMARY);
+ throw new Error(`unexpected url ${u}`);
+ });
+}
+
+describe('fetchCoinMarket RugCheck fan-out', () => {
+ beforeEach(() => {
+ __resetCoinMarketCache();
+ delete process.env.BIRDEYE_API_KEY; // Birdeye stays out of these cases
+ });
+
+ it('calls RugCheck alongside GoPlus and blends both into security', async () => {
+ global.fetch = routeFetch();
+ const m = await fetchCoinMarket(THREE, 'mainnet', { fresh: true });
+ expect(global.fetch.mock.calls.some(([u]) => String(u).includes(`api.rugcheck.xyz/v1/tokens/${THREE}/report/summary`))).toBe(true);
+ expect(m.security.mint_authority_revoked).toBe(true);
+ expect(m.security.rugcheck_score).toBe(1);
+ expect(m.security.lp_locked_pct).toBeCloseTo(62.07, 1);
+ expect(m.security.source).toBe('goplus+rugcheck');
+ expect(m.sources).toEqual(expect.arrayContaining(['goplus', 'rugcheck']));
+ });
+
+ it('fails soft when RugCheck is down: the read survives with GoPlus-only security', async () => {
+ global.fetch = routeFetch({ 'api.rugcheck.xyz': () => { throw new Error('ECONNRESET'); } });
+ const m = await fetchCoinMarket(THREE, 'mainnet', { fresh: true });
+ expect(m.price.usd).toBe(0.0021);
+ expect(m.security.source).toBe('goplus');
+ expect(m.security.rugcheck_score).toBeUndefined();
+ });
+
+ it('fails soft the other way: GoPlus down, RugCheck still delivers security', async () => {
+ global.fetch = routeFetch({ 'gopluslabs.io': () => { throw new Error('ECONNRESET'); } });
+ const m = await fetchCoinMarket(THREE, 'mainnet', { fresh: true });
+ expect(m.price.usd).toBe(0.0021);
+ expect(m.security.source).toBe('rugcheck');
+ expect(m.security.rugcheck_level).toBe('low');
+ });
+
+ it('skips RugCheck off mainnet, like GoPlus', async () => {
+ global.fetch = routeFetch();
+ await fetchCoinMarket(THREE, 'devnet', { fresh: true });
+ expect(global.fetch.mock.calls.some(([u]) => String(u).includes('api.rugcheck.xyz'))).toBe(false);
+ });
+});