Ledger keyed by bridge host + withdrawal id (staging and live number rows independently); receipts settled only for the current site; legacy bare keys migrated to the current host
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -32,6 +32,13 @@ fs.mkdirSync(DATA_DIR, { recursive: true });
|
||||
const LEDGER = path.join(DATA_DIR, 'ledger.json');
|
||||
let L = { entries: {}, days: {}, alerts: {} };
|
||||
try { L = Object.assign(L, JSON.parse(fs.readFileSync(LEDGER, 'utf8'))); } catch (e) {}
|
||||
// entries are keyed by SITE + '#' + withdrawal id (2026-10-01): staging and live number their withdrawals independently, so a
|
||||
// bare id from one site could block the same number on the other ('never twice'). Legacy bare keys belong to the bridge host the
|
||||
// engine was pointed at when they were written, which is the current one at the moment of migration.
|
||||
const SITE = (() => { try { return new URL(BRIDGE).host; } catch (e) { return 'unknown'; } })();
|
||||
const K = id => SITE + '#' + String(id);
|
||||
for (const k of Object.keys(L.entries)) if (k.indexOf('#') === -1) { const e = L.entries[k]; e.site = e.site || SITE; L.entries[e.site + '#' + k] = e; delete L.entries[k]; }
|
||||
for (const e of Object.values(L.entries)) e.site = e.site || SITE;
|
||||
const save = () => { const tmp = LEDGER + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(L)); fs.renameSync(tmp, LEDGER); };
|
||||
const dayKey = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
const paidTodayUsd = () => (L.days[dayKey()] || 0);
|
||||
@@ -72,27 +79,27 @@ async function tick() {
|
||||
const t = { at: Date.now(), pending: 0, paid: 0, note: '' };
|
||||
try {
|
||||
// 1) settle sends that never got their receipt (restart mid-wait, slow node): ask the chain, never re-send
|
||||
for (const e of Object.values(L.entries).filter(x => x.status === 'sent' && x.tx)) {
|
||||
for (const e of Object.values(L.entries).filter(x => x.status === 'sent' && x.tx && x.site === SITE)) { // only this site's rows: a receipt is reported to the bridge we are pointed at
|
||||
try { const rc = await provider.getTransactionReceipt(e.tx); if (rc) await settle(e, rc); } catch (err) { if (TRANSIENT.test(String(err.message))) rotate(err.message); }
|
||||
}
|
||||
// 2) what the site has queued; rows stuck in `processing` with no hash in our ledger need a human, never a re-send
|
||||
const r = await bridge('pending', 'GET');
|
||||
const rows = r.pending || []; t.pending = rows.length;
|
||||
const stuck = (r.stuck || []).filter(s => { const e = L.entries[String(s.id)]; return !e || !e.tx; });
|
||||
const stuck = (r.stuck || []).filter(s => { const e = L.entries[K(s.id)]; return !e || !e.tx; });
|
||||
if (stuck.length) await alertOnce('stuck:' + stuck.map(s => s.id).join(','), stuck.length + ' payout row(s) stuck in processing with no transaction on record: ' + stuck.map(s => '#' + s.id + ' ' + s.username + ' $' + s.usd).join(', ') + '. Check the wallet history before releasing them.');
|
||||
if (!rows.length) { t.note = 'nothing queued'; return; }
|
||||
const usdPerPol = await polusd.usdPerPol(); if (!(usdPerPol > 0)) { t.note = 'no POL price'; await alertOnce('price', 'no POL price available; payouts held'); return; }
|
||||
let bal = null; try { bal = await balance(); } catch (err) { if (TRANSIENT.test(String(err.message))) rotate(err.message); }
|
||||
if (bal != null && bal < LOW_POL) await alertOnce('low', 'hot wallet ' + wallet.address + ' holds ' + bal.toFixed(3) + ' POL (below ' + LOW_POL + '); ' + rows.length + ' payout(s) queued');
|
||||
for (const row of rows) {
|
||||
const id = String(row.id);
|
||||
const e = L.entries[id];
|
||||
const id = String(row.id), key = K(row.id);
|
||||
const e = L.entries[key];
|
||||
if (e && (e.status === 'sent' || e.status === 'paid')) { if (e.status === 'paid' && !e.told) await tellPaid(e); continue; } // never twice
|
||||
if (e && e.status === 'failed' && e.tx) continue; // produced a hash then reverted: a human looks
|
||||
const usd = Number(row.usd); const pol = Math.round((usd / usdPerPol) * 1e6) / 1e6;
|
||||
if (!(usd > 0) || !(pol > 0) || !/^0x[0-9a-fA-F]{40}$/.test(row.address)) { await bridge('failed', 'POST', { id: row.id, reason: 'bad amount or address' }).catch(() => {}); continue; }
|
||||
if (paidTodayUsd() + usd > CAP_USD) { t.note = 'daily cap reached'; await alertOnce('cap', 'daily cap $' + CAP_USD + ' reached; ' + rows.length + ' still queued'); break; }
|
||||
if (DRY) { L.entries[id] = { id, status: 'dryrun', usd, pol, to: row.address, user: row.username, at: Date.now() }; save(); log('DRY RUN would pay', pol, 'POL ($' + usd + ') to', row.address, 'for', row.username, 'row', id); t.paid++; continue; }
|
||||
if (DRY) { L.entries[key] = { id, site: SITE, status: 'dryrun', usd, pol, to: row.address, user: row.username, at: Date.now() }; save(); log('DRY RUN would pay', pol, 'POL ($' + usd + ') to', row.address, 'for', row.username, 'row', id); t.paid++; continue; }
|
||||
if (bal != null && bal < pol + 0.01) { t.note = 'wallet too low'; break; }
|
||||
// 3) claim the row on the site first (status 4 = processing): a crash between send and callback can then never
|
||||
// make a fresh process pay the same row again; the site lists such rows as `stuck` for a human instead
|
||||
@@ -104,15 +111,15 @@ async function tick() {
|
||||
tx = await wallet.sendTransaction({ to: row.address, value: ethers.parseEther(String(pol)) });
|
||||
} catch (err) {
|
||||
const msg = String(err.message || err).slice(0, 200);
|
||||
L.entries[id] = { id, status: 'failed', usd, pol, to: row.address, user: row.username, at: Date.now(), error: msg }; save();
|
||||
L.entries[key] = { id, site: SITE, status: 'failed', usd, pol, to: row.address, user: row.username, at: Date.now(), error: msg }; save();
|
||||
await bridge('failed', 'POST', { id: row.id, reason: msg.slice(0, 200) }).catch(() => {}); // row goes back to queued on the site
|
||||
if (TRANSIENT.test(msg)) { rotate(msg); delete L.entries[id]; save(); t.note = 'rpc trouble'; break; } // no hash was produced: safe to retry later
|
||||
if (TRANSIENT.test(msg)) { rotate(msg); delete L.entries[key]; save(); t.note = 'rpc trouble'; break; } // no hash was produced: safe to retry later
|
||||
continue;
|
||||
}
|
||||
L.entries[id] = { id, status: 'sent', usd, pol, to: row.address, user: row.username, at: Date.now(), tx: tx.hash }; save();
|
||||
L.entries[key] = { id, site: SITE, status: 'sent', usd, pol, to: row.address, user: row.username, at: Date.now(), tx: tx.hash }; save();
|
||||
log('sent', pol, 'POL ($' + usd + ') to', row.address, 'row', id, 'tx', tx.hash);
|
||||
let rc = null; try { rc = await tx.wait(1, 90000); } catch (err) { log('receipt wait', id, String(err.message).slice(0, 80)); }
|
||||
if (rc) { await settle(L.entries[id], rc); if (L.entries[id].status === 'paid') { t.paid++; bal = bal == null ? null : bal - pol; } }
|
||||
if (rc) { await settle(L.entries[key], rc); if (L.entries[key].status === 'paid') { t.paid++; bal = bal == null ? null : bal - pol; } }
|
||||
}
|
||||
} catch (err) { t.note = 'error: ' + String(err.message).slice(0, 160); log('tick error', err.message); }
|
||||
finally { last = t; ticking = false; }
|
||||
@@ -130,7 +137,7 @@ http.createServer((req, res) => {
|
||||
const entries = Object.values(L.entries);
|
||||
const body = { dryRun: DRY, chainId: CHAIN_ID, wallet: wallet ? wallet.address : null, balancePol: bal, bridge: BRIDGE.replace(/\?.*$/, ''), pollSec: POLL, dailyCapUsd: CAP_USD, paidTodayUsd: paidTodayUsd(),
|
||||
counts: { paid: entries.filter(e => e.status === 'paid').length, sent: entries.filter(e => e.status === 'sent').length, failed: entries.filter(e => e.status === 'failed').length, dryrun: entries.filter(e => e.status === 'dryrun').length },
|
||||
lastTick: last, recent: entries.sort((a, b) => b.at - a.at).slice(0, 20).map(e => ({ id: e.id, user: e.user, usd: e.usd, pol: e.pol, status: e.status, tx: e.tx || null, at: e.at, error: e.error || null })) };
|
||||
lastTick: last, recent: entries.sort((a, b) => b.at - a.at).slice(0, 20).map(e => ({ site: e.site, id: e.id, user: e.user, usd: e.usd, pol: e.pol, status: e.status, tx: e.tx || null, at: e.at, error: e.error || null })) };
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body, null, 2));
|
||||
});
|
||||
}).listen(PORT, () => log('status on :' + PORT));
|
||||
|
||||
Reference in New Issue
Block a user