Files
passivedrip-engine/engine.js
T

149 lines
13 KiB
JavaScript

// PassiveDrip Polygon payout engine (2026-09-30).
//
// The site (PHP on cPanel) queues withdrawals; it never holds a key. This engine, on core, holds the hot wallet and:
// every PD_POLL_SEC: GET <bridge>?a=pending (HMAC-signed) -> rows {id, address, usd, coins, username}
// pay each row ONCE in POL at the live rate -> POST ?a=paid {id, tx, pol} or ?a=failed {id, reason}
// Idempotency: a local ledger keyed by withdrawal id records every send with its tx hash before the bridge is told;
// a row already in the ledger is never sent again, even after a restart; an unconfirmed send is settled from its receipt.
// Safety: PD_DRY_RUN=1 logs what it would pay and sends nothing; PD_DAILY_CAP_USD caps a day's total; a dry wallet leaves
// rows queued and alerts once a day; a failed send is reported to the site (row stays queued) and retried on later ticks
// only if it never produced a hash.
//
// env: PD_BRIDGE_URL, PD_BRIDGE_SECRET, PD_WALLET_KEY, PD_RPC (comma list), PD_CHAIN_ID (137), PD_DRY_RUN (1|0),
// PD_POLL_SEC (120), PD_DAILY_CAP_USD (50), PD_LOW_BALANCE_POL (5), PD_TELEGRAM_TOKEN, PD_TELEGRAM_CHAT, DATA_DIR, PORT
'use strict';
const fs = require('fs'), path = require('path'), http = require('http'), https = require('https'), crypto = require('crypto');
const { ethers } = require('ethers');
const polusd = require('./polusd');
const ENV = k => (process.env[k] || '').trim();
const BRIDGE = ENV('PD_BRIDGE_URL'), SECRET = ENV('PD_BRIDGE_SECRET'), KEY = ENV('PD_WALLET_KEY');
const RPCS = ENV('PD_RPC').split(',').map(s => s.trim()).filter(Boolean);
const CHAIN_ID = Number(ENV('PD_CHAIN_ID') || 137);
const DRY = ENV('PD_DRY_RUN') !== '0'; // dry-run unless explicitly switched off
const POLL = Math.max(30, Number(ENV('PD_POLL_SEC') || 120));
const CAP_USD = Number(ENV('PD_DAILY_CAP_USD') || 50);
const LOW_POL = Number(ENV('PD_LOW_BALANCE_POL') || 5);
const DATA_DIR = ENV('DATA_DIR') || path.join(__dirname, 'data');
const PORT = Number(process.env.PORT || 3000);
fs.mkdirSync(DATA_DIR, { recursive: true });
// ---- ledger: one entry per withdrawal id, written BEFORE anything is told to the site
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);
// ---- bridge client (HMAC over ts, method, action, raw body)
function bridge(action, method, body) {
return new Promise((resolve, reject) => {
const raw = body ? JSON.stringify(body) : '';
const ts = Math.floor(Date.now() / 1000);
const sig = crypto.createHmac('sha256', SECRET).update(ts + '\n' + method + '\n' + action + '\n' + raw).digest('hex');
const u = new URL(BRIDGE); u.searchParams.set('a', action);
const req = (u.protocol === 'http:' ? http : https).request(u, { method, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw), 'X-PD-Ts': String(ts), 'X-PD-Sig': sig, 'User-Agent': 'passivedrip-engine' }, timeout: 20000 }, res => {
let d = ''; res.on('data', c => d += c); res.on('end', () => { try { const j = JSON.parse(d); if (res.statusCode !== 200 || j.error) return reject(new Error('bridge ' + action + ': HTTP ' + res.statusCode + ' ' + (j.error || d.slice(0, 120)))); resolve(j); } catch (e) { reject(new Error('bridge ' + action + ': bad response ' + d.slice(0, 120))); } });
});
req.on('error', reject); req.on('timeout', () => req.destroy(new Error('bridge timeout'))); req.end(raw);
});
}
// ---- chain
let provider = null, wallet = null, rpcAt = 0;
function connect() { provider = new ethers.JsonRpcProvider(RPCS[rpcAt % RPCS.length], CHAIN_ID); wallet = new ethers.Wallet(KEY, provider); }
const TRANSIENT = /socket hang up|ECONNABORTED|EPIPE|EHOSTUNREACH|ENETUNREACH|network error|fetch failed|UND_ERR|other side closed|server response 5\d\d|timeout|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|429|rate limit|missing response|could not detect network|bad response|SERVER_ERROR|NETWORK_ERROR/i; // + connection-level failures (PolHunter #7, 2026-10-09)
function rotate(why) { if (RPCS.length > 1) { rpcAt = (rpcAt + 1) % RPCS.length; connect(); log('rpc rotated after', why.slice(0, 80)); } }
async function balance() { return Number(ethers.formatEther(await provider.getBalance(wallet.address))); }
// ---- telegram (optional)
function tg(text) {
const tok = ENV('PD_TELEGRAM_TOKEN'), chat = ENV('PD_TELEGRAM_CHAT'); if (!tok || !chat) return Promise.resolve();
return new Promise(resolve => { const raw = JSON.stringify({ chat_id: chat, text, disable_web_page_preview: true }); const req = https.request({ host: 'api.telegram.org', path: '/bot' + tok + '/sendMessage', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw) } }, res => { res.resume(); res.on('end', resolve); }); req.on('error', () => resolve()); req.end(raw); });
}
const log = (...a) => console.log(new Date().toISOString(), ...a);
const alertOnce = async (key, text) => { const d = dayKey(); if (L.alerts[key] === d) return; L.alerts[key] = d; save(); log('ALERT', text); await tg('PassiveDrip engine: ' + text); };
// ---- the tick
let ticking = false, last = { at: 0, pending: 0, paid: 0, note: '' };
async function tick() {
if (ticking) return; ticking = true;
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 && 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[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), 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[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
try { const c = await bridge('claim', 'POST', { id: row.id }); if (!c.updated) { log('row', id, 'was not claimable (already processing?)'); continue; } }
catch (err) { log('claim failed', id, err.message); t.note = 'claim failed'; break; }
// 4) send, record the hash BEFORE anything else, then wait for the receipt
let tx;
try {
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[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[key]; save(); t.note = 'rpc trouble'; break; } // no hash was produced: safe to retry later
continue;
}
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[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; }
}
async function settle(e, rc) {
if (rc.status === 1) { e.status = 'paid'; e.paidAt = Date.now(); L.days[dayKey()] = (L.days[dayKey()] || 0) + e.usd; save(); await tellPaid(e); }
else { e.status = 'failed'; e.error = 'reverted'; save(); await bridge('failed', 'POST', { id: Number(e.id), reason: 'transaction reverted ' + e.tx }).catch(() => {}); await tg('PassiveDrip engine: payout row ' + e.id + ' reverted, tx ' + e.tx); }
}
async function tellPaid(e) { try { await bridge('paid', 'POST', { id: Number(e.id), tx: e.tx, pol: e.pol }); e.told = true; save(); log('paid recorded on site', e.id, e.tx); } catch (err) { log('could not tell the site yet', e.id, err.message); } }
// ---- status page (no secrets)
http.createServer((req, res) => {
if (req.url === '/health') { res.writeHead(200); return res.end('ok'); }
balance().catch(() => null).then(bal => {
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 => ({ 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));
// ---- boot
const missing = ['PD_BRIDGE_URL', 'PD_BRIDGE_SECRET', 'PD_WALLET_KEY', 'PD_RPC'].filter(k => !ENV(k));
if (missing.length) { log('not started: missing', missing.join(', ')); }
else { connect(); log('engine up', DRY ? 'DRY RUN' : 'LIVE', 'wallet', wallet.address, 'chain', CHAIN_ID, 'bridge', BRIDGE.replace(/\?.*$/, ''), 'every', POLL + 's'); tick(); setInterval(tick, POLL * 1000); }