// Report writer + fact gate. One OpenRouter call per report (one retry when the fact check fails). // Free check: DeepSeek v4.1 Flash, short scorecard. Deep report: Opus 5.5, the full shape from the cost test (D:/tmp/wwi-cost/run.py). // HARD RULE (Marty): nothing invented. Every address, tx hash and number in the written report must be in the evidence (or plain // arithmetic of evidence numbers). A report that fails twice is not shown: the deterministic facts are shown instead, with a note. // Scores, grade and verdict are OPINION (our rubric applied to the public facts); findings are facts with tags and sources. 'use strict'; const fs = require('fs'); const path = require('path'); const RUBRIC = fs.readFileSync(path.join(__dirname, 'chain', 'rubric.md'), 'utf8'); const MODELS = { free: process.env.FREE_MODEL || 'deepseek/deepseek-v4.1-flash', deep: process.env.DEEP_MODEL || 'anthropic/claude-opus-5.5' }; const CATS = [ ['control', 'Control and upgradeability', 25], ['custody', 'Custody and exit paths', 25], ['economics', 'Economic design', 20], ['insiders', 'Insider flows', 15], ['disclosure', 'Disclosure vs code', 10], ['trajectory', 'Trajectory', 5]]; const BANNED = [[/\bscam(s|med|mer|mers)?\b/gi, 'high-risk scheme'], [/\bponzi\b/gi, 'recruitment-funded'], [/\brug[ -]?pull(s|ed|ing)?\b/gi, 'drain of funds'], [/\bfraud(ulent|ster|sters|s)?\b/gi, 'misleading'], [/\bguaranteed\b/gi, 'promised'], [/\bget rich\b/gi, 'earn'], [/\bfree money\b/gi, 'unearned payouts'], [/\bpassive income\b/gi, 'payouts'], [/\b100% safe\b/gi, 'without risk'], [/\bdouble your\b/gi, 'grow your']]; const ADVICE = /(\bget out\b|\bpull (your|all) (money|funds)\b|\bwithdraw (now|immediately|everything)\b|\bdo not (invest|join|deposit|buy)\b|\bdon'?t (invest|join|deposit|buy)\b|\bstay away\b|\bavoid (this|it|the project)\b|\byou should (not )?(invest|join|buy|deposit|sell|exit)\b|\brun\b(?= away))/i; function clean(s) { if (typeof s !== 'string') return s; let t = s.replace(/\s*\u2014\s*/g, ', ').replace(/(\d)\s*\u2013\s*(\d)/g, '$1 to $2').replace(/\s*\u2013\s*/g, ', ').replace(/\u2012|\u2015/g, '-'); for (const [re, rep] of BANNED) t = t.replace(re, rep); // strip advice sentences ("get out", "do not invest" ...): a report gives facts and our opinion of risk, never instructions t = t.split(/(?<=[.!?])\s+/).filter(x => !ADVICE.test(x)).join(' '); return t.replace(/,\s*,/g, ',').replace(/\s{2,}/g, ' ').trim(); } function deepClean(o) { if (typeof o === 'string') return clean(o); if (Array.isArray(o)) return o.map(deepClean); if (o && typeof o === 'object') { const r = {}; for (const [k, v] of Object.entries(o)) r[k] = deepClean(v); return r; } return o; } const hasBanned = s => BANNED.some(([re]) => { re.lastIndex = 0; return re.test(s); }) || /[\u2014\u2013]/.test(s); const SYSTEM = `You are a smart-contract risk analyst for WebWorthIt, writing for a non-technical crypto buyer. You get an evidence pack produced by read-only chain tools, and sometimes the text of the project's public website. Rules you must follow: - Use only the evidence. Never invent an address, a transaction, a number, a name or a date. If something is not in the evidence, say it is UNKNOWN. - Copy numbers exactly as the pack shows them. Use the "Precomputed counts" section for every count: never recount events or upgrades yourself. An Upgraded event inside the deployment transaction is not an upgrade. - If you compute a number (a sum, a difference, a share), show the arithmetic with the pack numbers, e.g. "3,632.30 of 32,690.00". - Tag every claim VERIFIED (read on chain: storage, eth_call, logs, transactions), INFERRED (from code names, decompiled or simulated behaviour, or the website text) or UNKNOWN. - Neutral, factual wording about code and records. You judge code and on-chain records, never people. No advice to act (never tell anyone to join, leave, buy, sell or withdraw). - Never use these words or phrases: scam, ponzi, rug pull, fraud, guaranteed, get rich, free money, passive income, 100% safe, double your. Never use em dashes or en dashes. - Wallet wording if needed: "SafePal or any other crypto wallet". - Scores follow the rubric: 0 = safest, 10 = worst. Anything hidden or unreadable counts against the project, and you say so.`; const SCORE_SHAPE = `"scores": {"control": {"score": 0-10, "why": "...", "tag": "VERIFIED|INFERRED|UNKNOWN"}, "custody": {...}, "economics": {...}, "insiders": {...}, "disclosure": {...}, "trajectory": {...}}, "critical_flags": ["only red flags from the rubric list that the evidence supports, each one short"]`; function taskFree(pack, site) { return `RUBRIC:\n${RUBRIC}\n\nEVIDENCE PACK:\n${pack}\n\n${site ? 'PROJECT WEBSITE (public page text, read by our browser):\n' + site + '\n\n' : ''}Write the FREE CHECK scorecard as JSON with exactly these keys: - "verdict": one plain sentence about what the code and records show (no advice) - ${SCORE_SHAPE} - "top_findings": [{"tag": "VERIFIED|INFERRED|UNKNOWN", "text": "one or two plain sentences, with the evidence address or tx where it helps"}] (3 to 5 items, most important first) - "site_vs_code": one or two sentences comparing what the website says with what the code does, or "" when there is no website text Return only the JSON.`; } function taskDeep(pack, site) { return `RUBRIC:\n${RUBRIC}\n\nEVIDENCE PACK:\n${pack}\n\n${site ? 'PROJECT WEBSITE (public page text, read by our browser):\n' + site + '\n\n' : ''}Write the DEEP REPORT as JSON with these keys: - "verdict": one plain sentence (no advice) - ${SCORE_SHAPE} - "top_findings": [{"tag", "text"}] (4 to 6 items) - "drain_capability": can any wallet move the money or change the rules in one transaction? who, how, evidence (object: {"answer", "who", "how", "evidence", "tag"}) - "exit_paths_ranked": [{"path", "who", "possible_now", "happened", "tag"}] - "money": {"summary", "balances_now", "total_in", "total_out", "where_out_went": [{"address", "amount", "note", "tag"}]} - "insiders": [{"address", "role", "received", "owns", "tag"}] (operator-controlled or deployment-set wallets the evidence names) - "refund_or_promise_math": if the website or code makes a refund or payout promise, can it be met? show the arithmetic from the pack, else say UNKNOWN - "approvals": what wallet approvals to this contract put holders at risk right now - "site_vs_code": what the website says vs what the code does - "unknowns": [what the evidence cannot answer] - "plain_summary": 150 to 250 words a member could read Return only the JSON.`; } async function callModel(kind, messages, key) { const body = { model: MODELS[kind], messages, max_tokens: kind === 'deep' ? 16000 : 3000, usage: { include: true }, temperature: 0.1 }; if (/deepseek/.test(MODELS[kind])) body.reasoning = { enabled: false }; let last; for (let attempt = 0; attempt < 3; attempt++) { try { const r = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', signal: AbortSignal.timeout(600000), headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json', 'X-Title': 'WebWorthIt staging', 'HTTP-Referer': 'https://wwi.saasy.top' }, body: JSON.stringify(body) }); const j = await r.json(); if (r.status >= 500 || r.status === 429) { last = new Error('openrouter ' + r.status); await new Promise(z => setTimeout(z, 4000 * (attempt + 1))); continue; } if (!r.ok || !j.choices) throw new Error('openrouter ' + r.status + ': ' + JSON.stringify(j.error || j).slice(0, 200)); const u = j.usage || {}; return { text: j.choices[0].message.content || '', cost: Number(u.cost) || 0, tin: u.prompt_tokens || 0, tout: u.completion_tokens || 0, model: j.model || MODELS[kind], finish: j.choices[0].finish_reason }; } catch (e) { last = e; if (/openrouter 4\d\d/.test(e.message)) throw e; await new Promise(z => setTimeout(z, 4000 * (attempt + 1))); } } throw last; } function parseJson(t) { t = String(t || '').trim().replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/, ''); const a = t.indexOf('{'), b = t.lastIndexOf('}'); if (a < 0 || b < a) throw new Error('no JSON object in the model reply'); return JSON.parse(t.slice(a, b + 1)); } // ---- fact check (port of D:/tmp/wwi-cost/factcheck.py, stricter: blocks instead of listing) ---- function numbersIn(s) { const out = []; const re = /(? { if (!isFinite(v)) return; for (const d of [0, 1, 2, 3, 4]) set.add(Number(v.toFixed(d))); }; for (const n of numbersIn(src)) add(n.v); const k = [...new Set(keyNums.filter(x => isFinite(x) && x !== 0))].slice(0, 350); for (let i = 0; i < k.length; i++) for (let j = 0; j < k.length; j++) { const a = k[i], b = k[j]; add(a + b); add(Math.abs(a - b)); if (b) { add(a / b); add(a / b * 100); } if (i <= j) add(a * b); } return set; } function stringsOf(o, skipKeys) { const out = []; const walk = (x, k) => { if (skipKeys.has(k)) return; if (typeof x === 'string') out.push(x); else if (Array.isArray(x)) x.forEach(y => walk(y, k)); else if (x && typeof x === 'object') for (const [kk, v] of Object.entries(x)) walk(v, kk); }; walk(o, ''); return out; } function factcheck(report, evidenceText, keyNums) { const src = evidenceText.toLowerCase() + '\n' + RUBRIC.toLowerCase(); const allowed = allowedSet(src, keyNums); const texts = stringsOf(report, new Set(['tag'])); const all = texts.join('\n'); const low = all.toLowerCase(); const bad = []; for (const a of new Set(low.match(/0x[0-9a-f]{64}(?![0-9a-f])/g) || [])) if (!src.includes(a)) bad.push({ kind: 'tx', item: a }); for (const a of new Set((low.replace(/0x[0-9a-f]{64}/g, '').match(/0x[0-9a-f]{40}(?![0-9a-f])/g) || []))) if (!src.includes(a)) bad.push({ kind: 'address', item: a }); for (const s of new Set(low.match(/0x[0-9a-f]{3,10}(?:\u2026|\.\.\.?)[0-9a-f]{3,10}/g) || [])) { const [a, b] = s.split(/\u2026|\.\.\.?/); if (!new RegExp(a + '[0-9a-f]*' + b + '(?![0-9a-f])').test(src)) bad.push({ kind: 'short address', item: s }); } const stripped = all.replace(/0x[0-9a-fA-F]+/g, ' ').replace(/\b\d{4}-\d{2}-\d{2}\b/g, ' ').replace(/\b\d{1,2}:\d{2}\b/g, ' '); for (const n of numbersIn(stripped)) { const v = n.v; if (!n.raw.includes('.') && !n.raw.includes(',') && v < 10) continue; // small counts and scores if (!n.raw.includes('.') && !n.raw.includes(',') && v >= 1990 && v <= 2035) continue; // years if (allowed.has(v) || allowed.has(Number(v.toFixed(2)))) continue; // a rounded form of an allowed value (3,632 for 3,632.30, 29.06k style excluded) let near = false; // integers: allowed already holds every allowed value rounded to 0 decimals (3,632 for 3,632.30) if (n.raw.includes('.')) { const d = n.raw.split('.')[1].length; for (const x of [v - Math.pow(10, -d), v + Math.pow(10, -d)]) if (allowed.has(Number(x.toFixed(d)))) near = true; } if (near) continue; const i = stripped.indexOf(n.raw); bad.push({ kind: 'number', item: n.raw, context: stripped.slice(Math.max(0, i - 60), i + 40).replace(/\s+/g, ' ') }); } const banned = texts.filter(hasBanned).length; return { ok: bad.length === 0 && banned === 0, problems: bad.slice(0, 40), problem_count: bad.length, banned_strings: banned, checked_strings: texts.length }; } // ---- opinion: overall from the six category scores (weights from the rubric) + forced High on any critical flag ---- function grade(report, E) { let total = 0, have = 0; for (const [k, , w] of CATS) { const s = report.scores && report.scores[k]; const v = s && Number(s.score); if (isFinite(v)) { total += Math.max(0, Math.min(10, v)) * w / 10; have += w; } } const overall = have ? Math.round(total * 100 / have) : null; const flags = []; const ctl = (E && E.controllers) || {}; const eoaUp = (E && E.can_upgrade || []).filter(a => /^EOA/.test((ctl[a] || {}).type || '')); if (eoaUp.length) flags.push({ text: 'One personal wallet can replace the code in a single transaction (' + eoaUp.join(', ') + ').', tag: 'VERIFIED', source: 'rubric red flag 1' }); const v = (E && E.verification) || {}; if (E && E.proxy && E.proxy.upgradeable && !(v.implementation && v.implementation.match)) flags.push({ text: 'The implementation behind the upgradeable proxy has no verified source on Sourcify.', tag: 'VERIFIED', source: 'rubric red flag 2' }); // the model often restates the deterministic red flags: keep one per issue, the deterministic VERIFIED one const has1 = flags.some(f => f.source === 'rubric red flag 1'), has2 = flags.some(f => f.source === 'rubric red flag 2'); const words = t => new Set(String(t).toLowerCase().match(/[a-z]{4,}/g) || []); const similar = (a, b) => { const A = words(a), B = words(b); let n = 0; for (const w of A) if (B.has(w)) n++; return n / Math.max(1, Math.min(A.size, B.size)) >= 0.5; }; for (const f of report.critical_flags || []) { if (typeof f !== 'string' || !f.trim()) continue; const t = f.trim(); if (has1 && /(upgrad|replace (the )?code|single[- ](eoa|wallet|key)|one (personal )?wallet|\beoa\b|owner key)/i.test(t)) continue; if (has2 && /(unverified|not verified|no verified|source)/i.test(t)) continue; if (flags.some(x => similar(x.text, t))) continue; flags.push({ text: t, tag: 'INFERRED', source: 'model, from the rubric list' }); } let band = overall == null ? null : overall <= 25 ? 'Low risk' : overall <= 50 ? 'Moderate risk' : overall <= 75 ? 'Elevated risk' : 'High risk'; const forced = flags.length > 0 && band !== 'High risk'; if (flags.length) band = 'High risk'; return { overall, grade: band, forced_by_flag: forced, flags }; } const TAGS = new Set(['VERIFIED', 'INFERRED', 'UNKNOWN']); function normalize(report) { const fixTag = o => { if (o && typeof o === 'object') { if ('tag' in o) { const t = String(o.tag || '').toUpperCase().split(/[^A-Z]/)[0]; o.tag = TAGS.has(t) ? t : 'UNKNOWN'; } for (const v of Object.values(o)) if (v && typeof v === 'object') fixTag(v); } }; fixTag(report); if (!Array.isArray(report.top_findings)) report.top_findings = []; return report; } async function write({ kind, pack, siteText, facts, evidence, key }) { const keyNums = []; const walk = x => { if (typeof x === 'number') keyNums.push(x); else if (Array.isArray(x)) x.forEach(walk); else if (x && typeof x === 'object') Object.values(x).forEach(walk); }; walk({ money: evidence.money, approvals: evidence.approvals, positions: evidence.positions, counts: evidence.counts, txs: evidence.txs, values: evidence.values, age: evidence.age_days, wallets: evidence.wallets, native: evidence.native_balance }); const site = siteText ? siteText.slice(0, kind === 'deep' ? 12000 : 6000) : ''; const evidenceText = pack + '\n' + site + '\n' + JSON.stringify(facts); const messages = [{ role: 'system', content: SYSTEM }, { role: 'user', content: (kind === 'deep' ? taskDeep : taskFree)(pack, site) }]; const runs = []; let cost = 0, tin = 0, tout = 0, model = MODELS[kind]; for (let attempt = 0; attempt < 2; attempt++) { let rep, fc, raw; try { const r = await callModel(kind, messages, key); cost += r.cost; tin += r.tin; tout += r.tout; model = r.model; raw = r.text; rep = normalize(deepClean(parseJson(r.text))); fc = factcheck(rep, evidenceText, keyNums); } catch (e) { fc = { ok: false, error: String(e.message).slice(0, 300), problems: [] }; } runs.push({ attempt: attempt + 1, ok: fc.ok, problems: fc.problems, error: fc.error, banned: fc.banned_strings }); if (fc.ok) return { ok: true, report: rep, grade: grade(rep, evidence), factcheck: { passed: true, runs }, cost, tin, tout, model }; if (attempt === 0 && raw) { messages.push({ role: 'assistant', content: raw }); messages.push({ role: 'user', content: 'Our fact check could not find these items in the evidence: ' + JSON.stringify((fc.problems || []).slice(0, 25)) + (fc.banned_strings ? ' Some text also used a banned word or a dash.' : '') + ' Rewrite the whole JSON. Use only addresses, transaction hashes and numbers that appear in the evidence pack, or show the arithmetic from pack numbers. Return only the JSON.' }); } } return { ok: false, report: null, grade: null, factcheck: { passed: false, runs, note: 'The written report did not pass our fact check twice, so it is not shown. Only facts read directly from the chain are shown below.' }, cost, tin, tout, model }; } module.exports = { write, factcheck, clean, deepClean, grade, CATS, MODELS, hasBanned };