// Read-only safety screens and paper-fill prices. Every failure is recorded and treated as "no trade" (fail-closed).
import { sha256hex } from './receipt.js';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Retries transient 429/5xx (bounded) before giving up; the final failure is still fail-closed.
async function getJson(d, url, label) {
const tries = d.retries ?? 3; let r;
for (let i = 0; i < tries; i++) {
r = await getJsonOnce(d, url, label);
if (r.status === 'ok' || !(r.http_status === 429 || r.http_status >= 500)) break;
if (i < tries - 1) await sleep((d.backoffMs ?? 1200) * (i + 1));
}
if (r.status !== 'ok' && tries > 1) r.attempts = tries;
return r;
}
async function getJsonOnce(d, url, label) {
const ctl = new AbortController(); const t = setTimeout(() => ctl.abort(), d.timeoutMs ?? 20000);
const started = Date.now();
try {
const res = await d.fetch(url, { signal: ctl.signal, headers: { accept: 'application/json', 'user-agent': 'SignalTrail/0.1 (+https://signaltrail.agentgate.workers.dev)' } });
const txt = await res.text();
let body; try { body = JSON.parse(txt); } catch { return { status: 'error', error: `${label} non-JSON (HTTP ${res.status})`, http_status: res.status }; }
if (res.status !== 200) return { status: 'error', error: `${label} HTTP ${res.status}`, http_status: res.status };
return { status: 'ok', http_status: 200, body, response_sha256: await sha256hex(txt), latency_ms: Date.now() - started };
} catch (e) { return { status: 'error', error: `${label} ${e.name === 'AbortError' ? 'timeout' : 'unreachable'}` }; }
finally { clearTimeout(t); }
}
export async function injectScan(d, text) {
const url = `${d.base}/injectscan/v1/scan/preview?text=${encodeURIComponent(text.slice(0, 1500))}`;
const r = await getJson(d, url, 'InjectScan');
if (r.status !== 'ok') return { tool: 'InjectScan', ...r, flagged: null };
return { tool: 'InjectScan', status: 'ok', endpoint: url.split('?')[0], response_sha256: r.response_sha256, flagged: !!r.body.flagged, verdict: r.body.verdict, risk_score: r.body.risk_score, categories: (r.body.categories || []).map((c) => c.category) };
}
export async function tokenVerdict(d, address) {
if (!/^0x[0-9a-fA-F]{40}$/.test(address || '')) return { tool: 'TokenVerdict', status: 'error', error: 'no Base contract address for this token' };
const url = `${d.base}/tokenverdict/v1/preview?token=${address}`;
const r = await getJson(d, url, 'TokenVerdict');
if (r.status !== 'ok') return { tool: 'TokenVerdict', ...r };
const b = r.body;
if (!['SAFE', 'CAUTION', 'DANGER'].includes(b.verdict)) return { tool: 'TokenVerdict', status: 'error', error: 'TokenVerdict returned no verdict' };
return { tool: 'TokenVerdict', status: 'ok', endpoint: url.split('?')[0], response_sha256: r.response_sha256, engine: b.engine, checked_at: b.checked_at, result: { symbol: b.symbol, verdict: b.verdict, score: b.score, confidence: b.confidence, degraded: b.degraded, sellable: b.sellable, liquidity_usd: b.liquidity_usd, flags: b.flags } };
}
// Paper-fill price: DexScreener public API (free, no key), deepest Base pair; fallback GeckoTerminal public API (free, no key).
// Quotes are cached for 60 s (store-backed), so one fetch serves a run and the free APIs are not hammered. The quote's own fetched_at is kept.
export async function price(d, address) {
if (!address) return { source: 'DexScreener', status: 'error', error: 'no address' };
const key = 'price:' + address.toLowerCase(), ttl = d.priceTtlMs ?? 60000;
const hit = d.store?.cacheGet ? await d.store.cacheGet(key) : null;
if (hit && d.now() - Date.parse(hit.fetched_at) < ttl) return { ...hit, cached: true };
const r = await priceLive(d, address);
if (r.status === 'ok' && d.store?.cachePut) await d.store.cachePut(key, r);
return r;
}
async function priceLive(d, address) {
const a = await dexscreener(d, address);
if (a.status === 'ok') return a;
const b = await geckoterminal(d, address);
if (b.status === 'ok') return { ...b, fallback_from: { source: a.source, error: a.error } };
return { source: 'DexScreener+GeckoTerminal', status: 'error', error: `${a.error}; ${b.error}`, http_status: a.http_status };
}
async function dexscreener(d, address) {
const url = `${d.dexBase || 'https://api.dexscreener.com'}/latest/dex/tokens/${address}`;
const r = await getJson(d, url, 'DexScreener');
if (r.status !== 'ok') return { source: 'DexScreener', ...r };
const pairs = (r.body.pairs || []).filter((p) => p.chainId === 'base' && p.baseToken?.address?.toLowerCase() === address.toLowerCase());
const best = pairs.sort((a, b) => (b.liquidity?.usd || 0) - (a.liquidity?.usd || 0))[0];
if (!best || !(Number(best.priceUsd) > 0)) return { source: 'DexScreener', status: 'error', error: 'no Base pair with a price' };
return { source: 'DexScreener', status: 'ok', endpoint: url, response_sha256: r.response_sha256, fetched_at: d.now().toISOString(), price_usd: Number(best.priceUsd), pair: best.pairAddress, dex: best.dexId, pair_liquidity_usd: best.liquidity?.usd ?? null };
}
async function geckoterminal(d, address) {
const url = `${d.geckoBase || 'https://api.geckoterminal.com'}/api/v2/networks/base/tokens/${address.toLowerCase()}/pools?page=1`;
const r = await getJson(d, url, 'GeckoTerminal');
if (r.status !== 'ok') return { source: 'GeckoTerminal', ...r };
const want = 'base_' + address.toLowerCase();
const pools = (r.body.data || []).filter((p) => p.relationships?.base_token?.data?.id === want);
const best = pools.sort((x, y) => Number(y.attributes?.reserve_in_usd || 0) - Number(x.attributes?.reserve_in_usd || 0))[0];
const px = Number(best?.attributes?.base_token_price_usd);
if (!(px > 0)) return { source: 'GeckoTerminal', status: 'error', error: 'no Base pool with a price' };
return { source: 'GeckoTerminal', status: 'ok', endpoint: url, response_sha256: r.response_sha256, fetched_at: d.now().toISOString(), price_usd: px, pair: best.attributes.address, dex: best.relationships?.dex?.data?.id ?? null, pair_liquidity_usd: Number(best.attributes.reserve_in_usd) || null };
}
agentgate-source: code mirror on Cloudflare Pages. All repos