bdb2aacf27
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
223 lines
14 KiB
JavaScript
223 lines
14 KiB
JavaScript
// On-chain reader + indexer for the Banner Line contract (pattern from InstantAdPay site/chain.js):
|
|
// RPC pool with rotation + circuit breaker, a resumable eth_getLogs tail persisted in DATA_DIR, and the
|
|
// price quote. Encoding/decoding goes through abi.js only, so the compiled ABI can drop in later.
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const http = require('http');
|
|
const https = require('https');
|
|
const { EventFragment, Interface } = require('ethers');
|
|
const { iface, feedIface, PRICE_CENTS } = require('./abi');
|
|
const cfgMod = require('./config');
|
|
|
|
const CHUNK = 5000;
|
|
let state = null, busy = false, onEvent = null, timer = null;
|
|
const stateFile = () => path.join(cfgMod.get().dataDir, 'chain-index.json');
|
|
|
|
// ---- JSON-RPC with fallback rotation (http for a local anvil, https for public nodes) ----
|
|
let rpcIdx = 0;
|
|
const RPC_BENCH_MS = 10 * 60 * 1000; const rpcBenched = new Map();
|
|
const benchable = e => /timeout|timed out|abort|ECONN|EAI_AGAIN|ENOTFOUND|EPIPE|socket|hang up|429|too many|rate.?limit|temporar|internal error|service unavailable|50[234]/i.test(String(e && e.message || e));
|
|
function rpcOnce(url, method, params, timeoutMs) {
|
|
return new Promise((resolve, reject) => {
|
|
const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
|
|
const u = new URL(url); const mod = u.protocol === 'http:' ? http : https;
|
|
const req = mod.request({ hostname: u.hostname, port: u.port || undefined, path: u.pathname + u.search, method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: timeoutMs || 15000 },
|
|
res => { let d = ''; res.on('data', c => d += c); res.on('end', () => {
|
|
try { const j = JSON.parse(d); if (j.error) { const er = new Error(j.error.message || 'rpc error'); er.data = j.error.data; reject(er); } else resolve(j.result); }
|
|
catch (e) { reject(e); } }); });
|
|
req.on('error', reject); req.on('timeout', () => req.destroy(new Error('rpc timeout')));
|
|
req.end(body);
|
|
});
|
|
}
|
|
async function rpc(method, params, timeoutMs) {
|
|
const urls = cfgMod.get().rpcs; let last;
|
|
for (let round = 0; round < 2; round++) {
|
|
const now = Date.now(); const order = [], benched = [];
|
|
for (let i = 0; i < urls.length; i++) { const url = urls[(rpcIdx + i) % urls.length]; ((rpcBenched.get(url) || 0) > now ? benched : order).push(url); }
|
|
order.push(...benched);
|
|
for (const url of order) {
|
|
try { const r = await rpcOnce(url, method, params, timeoutMs); rpcIdx = urls.indexOf(url); rpcBenched.delete(url); return r; }
|
|
catch (e) { last = e; if (/execution reverted|revert/i.test(String(e.message))) throw e; if (benchable(e)) rpcBenched.set(url, Date.now() + RPC_BENCH_MS); console.warn('rpc', method, 'failed on', url.replace(/\/\/([^/]+).*/, '//$1'), '->', String(e && e.message || e).slice(0, 80)); }
|
|
}
|
|
if (round < 1) await new Promise(r => setTimeout(r, 400));
|
|
}
|
|
throw last || new Error('all RPCs failed');
|
|
}
|
|
async function bestTip() {
|
|
const urls = cfgMod.get().rpcs; let best = { block: -1, url: urls[0] };
|
|
await Promise.all(urls.map(async u => { try { const b = parseInt(await rpcOnce(u, 'eth_blockNumber', [], 8000), 16); if (b > best.block) best = { block: b, url: u }; } catch (e) {} }));
|
|
if (best.block < 0) throw new Error('no RPC answered eth_blockNumber');
|
|
return best;
|
|
}
|
|
|
|
// ---- reads ----
|
|
async function read(fn, args, to) {
|
|
const data = (to ? feedIface : iface).encodeFunctionData(fn, args || []);
|
|
const r = await rpc('eth_call', [{ to: to || cfgMod.get().contract, data }, 'latest'], 5000);
|
|
if (!r || r === '0x') throw new Error('no such function ' + fn);
|
|
return (to ? feedIface : iface).decodeFunctionResult(fn, r);
|
|
}
|
|
async function tryRead(fn, args) { try { return (await read(fn, args))[0]; } catch (e) { return null; } }
|
|
|
|
// Required POL for one $5 spot. Order: contract quote view, else Chainlink feed math (wei = cents * 1e24 / answer,
|
|
// the InstantAdPay formula). Cached 20 s. Returns { wei, sendWei, source } or throws.
|
|
let quoteCache = null;
|
|
async function quote() {
|
|
if (quoteCache && Date.now() - quoteCache.at < 20000) return quoteCache.v;
|
|
const c = cfgMod.get(); let wei = null, source = '';
|
|
for (const fn of ['quoteWei', 'requiredWei']) { const v = await tryRead(fn); if (v && v > 0n) { wei = v; source = 'contract.' + fn; break; } }
|
|
if (!wei) {
|
|
let feed = c.priceFeed || await tryRead('priceFeed');
|
|
if (!feed) throw new Error('No price available (contract has no quote view and PRICE_FEED is not set)');
|
|
const r = await read('latestRoundData', [], feed);
|
|
const ans = BigInt(r[1]); const upd = Number(r[3]);
|
|
if (ans <= 0n) throw new Error('Price feed answer is not positive');
|
|
if (Math.floor(Date.now() / 1000) - upd > 3600 && !c.allowStaleFeed) throw new Error('Price feed is stale (older than 1 hour); buys pause until it updates');
|
|
wei = (BigInt(PRICE_CENTS) * 10n ** 24n) / ans; source = 'feed';
|
|
}
|
|
// the contract accepts [required, required * 1.02] and refunds the excess: send +1% for price drift
|
|
const v = { wei: wei.toString(), sendWei: (wei + wei / 100n).toString(), source };
|
|
quoteCache = { at: Date.now(), v };
|
|
return v;
|
|
}
|
|
|
|
// ---- event decode (tolerant of indexed-flag differences between the spec ABI and the compiled one) ----
|
|
const altCache = new Map();
|
|
function decodeLog(log) {
|
|
let parsed = null;
|
|
try { parsed = iface.parseLog(log); } catch (e) {}
|
|
if (!parsed) {
|
|
let ev; try { ev = iface.getEvent(log.topics[0]); } catch (e) { return null; }
|
|
if (!ev) return null;
|
|
const k = log.topics.length - 1, key = ev.name + ':' + k;
|
|
if (!altCache.has(key)) {
|
|
const sig = 'event ' + ev.name + '(' + ev.inputs.map((p, i) => p.type + (i < k ? ' indexed ' : ' ') + p.name).join(', ') + ')';
|
|
altCache.set(key, new Interface([EventFragment.from(sig)]));
|
|
}
|
|
try { parsed = altCache.get(key).parseLog(log); } catch (e) { return null; }
|
|
}
|
|
if (!parsed) return null;
|
|
const a = parsed.args, lc = x => String(x).toLowerCase();
|
|
const base = { type: parsed.name, block: parseInt(log.blockNumber, 16), tx: log.transactionHash, li: parseInt(log.logIndex, 16) };
|
|
switch (parsed.name) {
|
|
case 'SpotBought': return Object.assign(base, { id: Number(a[0]), owner: lc(a[1]), payer: lc(a[2]), sponsor: lc(a[3]), kind: Number(a[4]), valueWei: a[5].toString(), usdPrice: a[6].toString() });
|
|
case 'Paid': return Object.assign(base, { spotId: Number(a[0]), to: lc(a[1]), amount: a[2].toString(), role: Number(a[3]) });
|
|
case 'FundBuy': return Object.assign(base, { spotId: Number(a[0]), giftee: lc(a[1]) });
|
|
case 'MemberJoined': return Object.assign(base, { member: lc(a[0]), sponsor: lc(a[1]) });
|
|
case 'PaymentFailed': return Object.assign(base, { spotId: Number(a[0]), to: lc(a[1]), amount: a[2].toString(), role: Number(a[3]) });
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// ---- derived index ----
|
|
const ZERO = '0x0000000000000000000000000000000000000000';
|
|
function blank(c) { return { v: 1, key: c.chainId + ':' + String(c.contract).toLowerCase(), lastBlock: c.deployBlock - 1, events: [], blockTs: {} }; }
|
|
function derive() {
|
|
const d = { spots: new Map(), members: new Map(), wallets: new Map(), fundBuys: [], totals: { spots: 0, paidInWei: 0n, paidOutWei: 0n, members: 0, fundBuys: 0 } };
|
|
for (const ev of state.events) apply(d, ev);
|
|
state.d = d;
|
|
}
|
|
function wallet(d, a) { let w = d.wallets.get(a); if (!w) { w = { inWei: 0n, outWei: 0n, byRole: {}, payouts: 0 }; d.wallets.set(a, w); } return w; }
|
|
function apply(d, ev) {
|
|
const ts = state.blockTs[ev.block] ? state.blockTs[ev.block] * 1000 : (ev.ts || Date.now());
|
|
if (ev.type === 'SpotBought') {
|
|
d.spots.set(ev.id, { id: ev.id, owner: ev.owner, payer: ev.payer, sponsor: ev.sponsor, kind: ev.kind, valueWei: ev.valueWei, usdPrice: ev.usdPrice, boughtAt: ts, block: ev.block, tx: ev.tx });
|
|
d.totals.spots += 1;
|
|
if (ev.kind === 0 || ev.kind === 1) { d.totals.paidInWei += BigInt(ev.valueWei); wallet(d, ev.payer).inWei += BigInt(ev.valueWei); }
|
|
} else if (ev.type === 'Paid') {
|
|
const w = wallet(d, ev.to); w.outWei += BigInt(ev.amount); w.payouts += 1; w.byRole[ev.role] = (BigInt(w.byRole[ev.role] || 0) + BigInt(ev.amount)).toString();
|
|
if (ev.role !== 4 && ev.to !== String(cfgMod.get().contract).toLowerCase()) d.totals.paidOutWei += BigInt(ev.amount); // to == contract: credited to the fund
|
|
} else if (ev.type === 'PaymentFailed') {
|
|
wallet(d, ev.to).failed = (wallet(d, ev.to).failed || 0) + 1; // the amount went to the fund instead
|
|
} else if (ev.type === 'FundBuy') {
|
|
d.fundBuys.push({ spotId: ev.spotId, giftee: ev.giftee, at: ts, tx: ev.tx }); d.totals.fundBuys += 1;
|
|
} else if (ev.type === 'MemberJoined') {
|
|
if (!d.members.has(ev.member)) { d.members.set(ev.member, { address: ev.member, sponsor: ev.sponsor === ZERO ? null : ev.sponsor, joinedAt: ts }); d.totals.members += 1; }
|
|
}
|
|
}
|
|
function loadState() {
|
|
const c = cfgMod.get();
|
|
try { state = JSON.parse(fs.readFileSync(stateFile(), 'utf8')); } catch (e) { state = null; }
|
|
if (!state || state.v !== 1 || state.key !== c.chainId + ':' + String(c.contract).toLowerCase()) state = blank(c);
|
|
state.blockTs = state.blockTs || {};
|
|
derive();
|
|
}
|
|
function saveState() {
|
|
try { const { d, ...out } = state; const tmp = stateFile() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(out)); fs.renameSync(tmp, stateFile()); }
|
|
catch (e) { console.error('chain state save failed', e.message); }
|
|
}
|
|
async function blockTime(n) {
|
|
if (state.blockTs[n]) return state.blockTs[n];
|
|
const b = await rpc('eth_getBlockByNumber', ['0x' + n.toString(16), false]);
|
|
const t = b ? parseInt(b.timestamp, 16) : Math.floor(Date.now() / 1000);
|
|
state.blockTs[n] = t; return t;
|
|
}
|
|
async function tail() {
|
|
const c = cfgMod.get();
|
|
if (busy || !c.contract) return; busy = true;
|
|
try {
|
|
const tip = await bestTip();
|
|
const latest = tip.block - c.confirmations;
|
|
let changed = false;
|
|
while (state.lastBlock < latest) {
|
|
const from = state.lastBlock + 1, to = Math.min(from + CHUNK - 1, latest);
|
|
const q = [{ address: c.contract, fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }];
|
|
let logs; try { logs = await rpcOnce(tip.url, 'eth_getLogs', q); } catch (e) { logs = await rpc('eth_getLogs', q); }
|
|
logs.sort((x, y) => parseInt(x.blockNumber, 16) - parseInt(y.blockNumber, 16) || parseInt(x.logIndex, 16) - parseInt(y.logIndex, 16));
|
|
for (const lg of logs) {
|
|
const ev = decodeLog(lg); if (!ev) continue;
|
|
if (state.events.some(e => e.tx === ev.tx && e.li === ev.li)) continue;
|
|
await blockTime(ev.block); ev.ts = state.blockTs[ev.block] * 1000;
|
|
state.events.push(ev); apply(state.d, ev); changed = true;
|
|
if (onEvent) { try { onEvent(ev); } catch (e) { console.error('chain onEvent', e.message); } }
|
|
}
|
|
state.lastBlock = to; changed = true;
|
|
}
|
|
if (changed) saveState();
|
|
state.lastOk = Date.now();
|
|
} catch (e) { state.lastErr = e.message; console.error('chain tail', e.message); }
|
|
busy = false;
|
|
}
|
|
|
|
// ---- getters ----
|
|
const d = () => state.d;
|
|
function spots() { return [...d().spots.values()].sort((a, b) => b.id - a.id); }
|
|
function spot(id) { return d().spots.get(Number(id)) || null; }
|
|
function spotsOf(addr) { const a = String(addr).toLowerCase(); return spots().filter(s => s.owner === a); }
|
|
function member(addr) { return d().members.get(String(addr).toLowerCase()) || null; }
|
|
function allMembers() { return [...d().members.values()]; }
|
|
function isMember(addr) { const a = String(addr || '').toLowerCase(); if (a === String(cfgMod.get().contract).toLowerCase()) return false; return d().members.has(a) || spots().some(s => s.owner === a && s.kind !== 3); }
|
|
function directs(addr) { const a = String(addr).toLowerCase(); return [...d().members.values()].filter(m => m.sponsor === a); }
|
|
function walletTotals(addr) { const w = d().wallets.get(String(addr).toLowerCase()); return w ? { inWei: w.inWei.toString(), outWei: w.outWei.toString(), byRole: w.byRole, payouts: w.payouts } : { inWei: '0', outWei: '0', byRole: {}, payouts: 0 }; }
|
|
function paidOf(addr) { const a = String(addr).toLowerCase(); return state.events.filter(e => e.type === 'Paid' && e.to === a).slice(-200).reverse(); }
|
|
function fundBuys() { return d().fundBuys.slice(); }
|
|
function totals() { const t = d().totals; return { spots: t.spots, members: t.members, fundBuys: t.fundBuys, paidInWei: t.paidInWei.toString(), paidOutWei: t.paidOutWei.toString() }; }
|
|
function status() { return { lastBlock: state.lastBlock, events: state.events.length, lastOk: state.lastOk || null, lastErr: state.lastErr || null }; }
|
|
function recent(n) { return state.events.slice(-(n || 50)).reverse(); }
|
|
|
|
async function receipt(hash) {
|
|
const r = await rpc('eth_getTransactionReceipt', [hash]);
|
|
if (!r) return { found: false };
|
|
return { found: true, status: r.status, blockNumber: r.blockNumber };
|
|
}
|
|
async function suggestedFees() {
|
|
let tip = 0n, base = 0n;
|
|
try { tip = BigInt(await rpc('eth_maxPriorityFeePerGas', [])); } catch (e) {}
|
|
try { const blk = await rpc('eth_getBlockByNumber', ['latest', false]); base = BigInt((blk && blk.baseFeePerGas) || '0x0'); } catch (e) {}
|
|
const MIN_TIP = cfgMod.get().chainId === 31337 ? 1000000000n : 30000000000n; // 30 gwei clears Polygon's ~25 gwei floor
|
|
const priority = tip > MIN_TIP ? tip : MIN_TIP;
|
|
return { maxPriorityFeePerGas: '0x' + priority.toString(16), maxFeePerGas: '0x' + (base * 2n + priority).toString(16) };
|
|
}
|
|
|
|
function init(opts) {
|
|
if (opts && opts.onEvent) onEvent = opts.onEvent;
|
|
loadState();
|
|
if (!cfgMod.get().contract) { console.warn('CONTRACT_ADDRESS not set: chain index idle'); return; }
|
|
tail();
|
|
timer = setInterval(tail, cfgMod.get().pollMs); timer.unref && timer.unref();
|
|
}
|
|
|
|
module.exports = { init, tail, rpc, read, tryRead, quote, decodeLog, receipt, suggestedFees, spots, spot, spotsOf, member, isMember,
|
|
allMembers, directs, walletTotals, paidOf, fundBuys, totals, status, recent, ZERO };
|