Files

89 lines
7.1 KiB
JavaScript

// The faucet: pays due payouts from the dedicated hot wallet (PolHunter's sender, trimmed).
//
// DR_WALLET_KEY the hot wallet's private key (env only, never on disk)
// DR_RPC comma list of RPC urls; a transient node error rotates to the next
// DR_CHAIN_ID 137 (mainnet) or 80002 (Amoy)
// DR_DRY_RUN anything but 'off' means no transaction is ever sent; rows stay due and the
// tick reports what it would have paid (the trial starts here)
//
// One plain POL transfer per payout row, hash recorded before the wait, settled from the receipt
// on a later tick if the wait times out or the process restarts. Never sent twice.
'use strict';
const { ethers } = require('ethers');
const ledger = require('./ledger');
const store = require('./store');
let provider = null, wallet = null, ticking = false, rpcs = [], rpcAt = 0;
const dry = () => String(process.env.DR_DRY_RUN || 'on').toLowerCase() !== 'off';
function enabled() { return !!(process.env.DR_WALLET_KEY && process.env.DR_RPC); }
function init() { if (!enabled()) return false; rpcs = String(process.env.DR_RPC).split(',').map(s => s.trim()).filter(Boolean); rpcAt = 0; connect(); return true; }
function connect() { provider = new ethers.JsonRpcProvider(rpcs[rpcAt % rpcs.length], Number(process.env.DR_CHAIN_ID) || undefined); wallet = new ethers.Wallet(process.env.DR_WALLET_KEY.trim(), 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|403|Forbidden|401|Unauthorized/i; // + connection-level failures (PolHunter #7, 2026-10-09)
function rotate(reason) { if (rpcs.length > 1) { rpcAt = (rpcAt + 1) % rpcs.length; connect(); console.warn('faucet: RPC rotated after', reason.slice(0, 80)); } }
// Nonce (2026-11-09, after Turkey Drop's week prizes collided with "replacement fee too low"): publicnode is a load-balanced pool, so
// asking it for the next nonce right after a confirmed send can return the SAME nonce again. Sends read the nonce once per tick, keep
// the highest one ever used in faucet-state.nextNonce, and count up locally. A nonce clash is a retry (row back to due), never a failure.
const NONCE_ERR = /replacement fee too low|replacement transaction underpriced|nonce too low|nonce has already been used|already known|NONCE_EXPIRED|REPLACEMENT_UNDERPRICED/i;
async function nextNonce() { const n = await provider.getTransactionCount(wallet.address, 'pending'); return Math.max(n, Number(store.read('faucet-state', {}).nextNonce) || 0); }
const keepNonce = n => store.update('faucet-state', {}, x => Object.assign(x, { nextNonce: Math.max(n, Number(x.nextNonce) || 0) }));
const DROP_MS = 10 * 60000; // a "sent" row whose tx no node knows after this long was dropped: back to due (its nonce slot is reused, so it can never pay twice)
function address() { return wallet ? wallet.address : null; }
async function balance() { if (!provider || !wallet) return null; return Number(ethers.formatEther(await provider.getBalance(wallet.address))); }
function state() { return Object.assign({ dryRun: dry(), address: address(), enabled: enabled() }, store.read('faucet-state', {})); }
async function settle(p, rc, notify) {
const ok = rc && rc.status === 1;
ledger.mark(p.id, { status: ok ? 'paid' : 'failed', paidAt: Date.now(), error: ok ? null : 'reverted' });
if (notify) await notify(ok ? 'paid' : 'failed', Object.assign({}, p, ok ? {} : { error: 'reverted' }));
return ok;
}
async function tick(notify) {
if (!wallet || ticking) return { paid: 0 };
ticking = true; let paid = 0, would = 0;
try {
for (const p of store.read('payouts', []).filter(x => x.status === 'sent' && x.tx)) {
try { const rc = await provider.getTransactionReceipt(p.tx); if (rc) { if (await settle(p, rc, notify)) paid++; } else if (Date.now() - (p.sentAt || p.ts || 0) > DROP_MS && !(await provider.getTransaction(p.tx))) ledger.mark(p.id, { status: 'due', tx: null, error: 'dropped ' + String(p.tx).slice(0, 12) + ', resending' }); } catch (e) { if (TRANSIENT.test(String(e.message || e))) { rotate(String(e.message || e)); break; } } // a node refusing us (403) must not freeze the check
}
const due = ledger.payable();
let bal = null; try { bal = await balance(); } catch (e) {}
if (dry()) {
would = due.reduce((n, p) => n + p.pol, 0);
if (due.length) console.log('faucet DRY RUN: would pay', due.length, 'payout(s),', would, 'POL; balance', bal);
store.update('faucet-state', {}, x => Object.assign(x, { balance: bal, checkedAt: Date.now(), lastTick: { due: due.length, would } }));
return { paid: 0, dryRun: true, due: due.length, would, balance: bal };
}
let nonce = null; if (due.length) { try { nonce = await nextNonce(); } catch (e) { if (TRANSIENT.test(String(e.message || e))) rotate(String(e.message || e)); return { paid }; } }
for (const p of due) {
if (bal != null && bal < p.pol + 0.005) { await lowOnce(notify, bal, p.pol); break; }
try {
const tx = await wallet.sendTransaction({ to: p.wallet, value: ethers.parseEther(String(p.pol)), nonce });
ledger.mark(p.id, { status: 'sent', tx: tx.hash, sentAt: Date.now() }); nonce++; keepNonce(nonce);
let rc = null;
try { rc = await tx.wait(1, 90000); } catch (e) { if (e && e.code === 'TIMEOUT') continue; throw e; }
if (await settle(Object.assign({}, p, { tx: tx.hash }), rc, notify)) { paid++; if (bal != null) bal -= p.pol; }
} catch (e) {
const msg = String(e.message || e);
if (/insufficient funds/i.test(msg)) { ledger.mark(p.id, { status: 'due', error: null }); break; }
if (NONCE_ERR.test(msg) || NONCE_ERR.test(String(e && e.code))) { ledger.mark(p.id, { status: 'due', error: 'nonce clash, retrying' }); try { keepNonce(await provider.getTransactionCount(wallet.address, 'latest')); } catch (x) {} break; }
const cur = store.read('payouts', []).find(x => x.id === p.id);
if (cur && cur.status === 'sent' && cur.tx) continue;
if (TRANSIENT.test(msg)) { ledger.mark(p.id, { status: 'due', error: 'node: ' + msg.slice(0, 120) }); rotate(msg); break; }
ledger.mark(p.id, { status: 'failed', error: msg.slice(0, 200) });
if (notify) await notify('failed', Object.assign({}, p, { error: msg.slice(0, 200) }));
}
}
const b2 = await balance();
if (b2 != null) { if (b2 < Number(ledger.settings().lowBalancePol)) await lowOnce(notify, b2, ledger.settings().lowBalancePol); store.update('faucet-state', {}, x => Object.assign(x, { balance: b2, checkedAt: Date.now(), lastTick: { paid } })); }
} finally { ticking = false; }
return { paid };
}
async function lowOnce(notify, bal, need) {
const day = ledger.ctDay(); const st = store.read('faucet-state', {});
if (st.lowAlertDay === day || !notify) return;
st.lowAlertDay = day; store.write('faucet-state', st);
await notify('low', { balance: bal, threshold: need, address: wallet.address });
}
module.exports = { enabled, init, address, balance, tick, state, dry };