PassiveDrip payout engine: signed bridge client, one-payment-per-row ledger, dry-run, daily cap, low-balance alerts, status page
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,8 @@
|
|||||||
|
FROM node:22-alpine
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json ./
|
||||||
|
RUN npm install --omit=dev --no-audit --no-fund
|
||||||
|
COPY . .
|
||||||
|
ENV NODE_ENV=production PORT=3000
|
||||||
|
EXPOSE 3000
|
||||||
|
CMD ["node", "engine.js"]
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# PassiveDrip payout engine
|
||||||
|
|
||||||
|
Pays queued PassiveDrip withdrawals in POL on Polygon from a dedicated hot wallet. The site (PHP on cPanel) only queues rows and never holds a key.
|
||||||
|
|
||||||
|
Loop, every `PD_POLL_SEC` seconds:
|
||||||
|
|
||||||
|
1. `GET <bridge>?a=pending` (HMAC-signed): rows queued on the site with the member's Polygon address and the USD value.
|
||||||
|
2. Pay each row once, at the live POL rate (read from the InstantAdPay contract's own quote, no third-party feed).
|
||||||
|
3. `POST ?a=paid {id, tx, pol}` so the site marks the row paid with the transaction hash, or `?a=failed {id, reason}` so it stays queued.
|
||||||
|
|
||||||
|
A local ledger keyed by withdrawal id is written before the site is told, so a restart can never pay a row twice; an unconfirmed send is settled from its receipt on the next tick.
|
||||||
|
|
||||||
|
Environment: `PD_BRIDGE_URL`, `PD_BRIDGE_SECRET`, `PD_WALLET_KEY`, `PD_RPC` (comma list), `PD_CHAIN_ID` (137), `PD_DRY_RUN` (defaults to on), `PD_POLL_SEC`, `PD_DAILY_CAP_USD`, `PD_LOW_BALANCE_POL`, `PD_TELEGRAM_TOKEN`, `PD_TELEGRAM_CHAT`, `DATA_DIR`.
|
||||||
|
|
||||||
|
Status: `GET /` on the service port shows wallet, balance, counts and the last tick; `GET /health` for Coolify.
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
// 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) {}
|
||||||
|
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 = /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;
|
||||||
|
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)) {
|
||||||
|
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
|
||||||
|
const r = await bridge('pending', 'GET');
|
||||||
|
const rows = r.pending || []; t.pending = rows.length;
|
||||||
|
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];
|
||||||
|
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 (bal != null && bal < pol + 0.01) { t.note = 'wallet too low'; break; }
|
||||||
|
// 3) 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);
|
||||||
|
if (TRANSIENT.test(msg)) { rotate(msg); t.note = 'rpc trouble'; break; }
|
||||||
|
L.entries[id] = { id, 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(() => {}); continue;
|
||||||
|
}
|
||||||
|
L.entries[id] = { id, 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; } }
|
||||||
|
}
|
||||||
|
} 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 => ({ 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); }
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"name": "passivedrip-engine",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "PassiveDrip Polygon payout engine: polls the site's signed bridge for queued withdrawals, pays them in POL from a dedicated hot wallet, posts the transaction hash back. One payment per withdrawal row, ever.",
|
||||||
|
"main": "engine.js",
|
||||||
|
"scripts": { "start": "node engine.js" },
|
||||||
|
"dependencies": { "ethers": "^6.13.0" },
|
||||||
|
"engines": { "node": ">=20" }
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
// What a dollar is worth in POL right now.
|
||||||
|
//
|
||||||
|
// Mission blocks are priced in dollars ($30 entry, $10 listing) because that is how Marty thinks
|
||||||
|
// about them and how a buyer judges them. The faucet pays in POL. So something has to convert,
|
||||||
|
// and it has to be a rate nobody can argue with.
|
||||||
|
//
|
||||||
|
// It is read from the InstantAdPay contract's own quote: the contract stores each package's price
|
||||||
|
// in cents and quotes the POL to pay right now, so priceCents / quoteWei IS the rate members are
|
||||||
|
// already paying at today. No third-party price feed, no oracle to trust, no disagreement between
|
||||||
|
// what a mission costs here and what a package costs there.
|
||||||
|
//
|
||||||
|
// Cached for a few minutes and fail-soft: a purchase is refused rather than priced off a stale or
|
||||||
|
// missing rate, because getting this wrong silently means selling delivery below cost.
|
||||||
|
'use strict';
|
||||||
|
const https = require('https');
|
||||||
|
|
||||||
|
const IAP = '0xbe1eca72aff47d13d8e907e523f55eb9e2d365e0';
|
||||||
|
const RPCS = ['https://polygon-bor-rpc.publicnode.com', 'https://1rpc.io/matic'];
|
||||||
|
const SEL_COUNT = '0xe0f6ef87'; // productCount()
|
||||||
|
const SEL_PRODUCT = '0xbf712fd6'; // products(uint32) -> priceCents is word 0, active word 3
|
||||||
|
const SEL_QUOTE = '0x7de85694'; // quoteWei(uint32)
|
||||||
|
const TTL = 5 * 60000;
|
||||||
|
|
||||||
|
let cache = { usdPerPol: 0, at: 0 };
|
||||||
|
|
||||||
|
function rpc(method, params) {
|
||||||
|
const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let i = 0;
|
||||||
|
const attempt = () => {
|
||||||
|
const u = new URL(RPCS[i]);
|
||||||
|
const rq = https.request({ hostname: u.hostname, path: u.pathname, method: 'POST', timeout: 12000,
|
||||||
|
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } }, res => {
|
||||||
|
let d = ''; res.on('data', c => d += c);
|
||||||
|
res.on('end', () => {
|
||||||
|
try { const j = JSON.parse(d); if (j.error) throw new Error(j.error.message); resolve(j.result); }
|
||||||
|
catch (e) { if (++i < RPCS.length) attempt(); else reject(e); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
rq.on('error', () => { if (++i < RPCS.length) attempt(); else reject(new Error('rpc unreachable')); });
|
||||||
|
rq.on('timeout', () => { rq.destroy(); });
|
||||||
|
rq.end(body);
|
||||||
|
};
|
||||||
|
attempt();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const call = data => rpc('eth_call', [{ to: IAP, data }, 'latest']);
|
||||||
|
const enc = n => BigInt(n).toString(16).padStart(64, '0');
|
||||||
|
const word = (r, i) => r.slice(2 + i * 64, 2 + (i + 1) * 64);
|
||||||
|
|
||||||
|
// Walk the catalogue until a product quotes a non-zero POL cost, then take cents / POL from it.
|
||||||
|
async function fetchRate() {
|
||||||
|
const n = parseInt(word(await call(SEL_COUNT), 0), 16);
|
||||||
|
for (let id = 1; id <= Math.min(n, 12); id++) {
|
||||||
|
let wei = 0n, cents = 0;
|
||||||
|
try { wei = BigInt('0x' + word(await call(SEL_QUOTE + enc(id)), 0)); } catch (e) { continue; }
|
||||||
|
if (wei <= 0n) continue;
|
||||||
|
try {
|
||||||
|
const p = await call(SEL_PRODUCT + enc(id));
|
||||||
|
cents = parseInt(word(p, 0), 16); // priceCents
|
||||||
|
const active = parseInt(word(p, 3), 16) === 1;
|
||||||
|
const exists = parseInt(word(p, 4), 16) === 1;
|
||||||
|
if (!active || !exists) cents = 0;
|
||||||
|
} catch (e) { /* fall through */ }
|
||||||
|
if (!cents) continue;
|
||||||
|
const pol = Number(wei / 10n ** 12n) / 1e6;
|
||||||
|
if (pol > 0) return (cents / 100) / pol; // dollars per POL
|
||||||
|
}
|
||||||
|
throw new Error('no product quoted a usable price');
|
||||||
|
}
|
||||||
|
|
||||||
|
// dollars per POL, e.g. 0.1019
|
||||||
|
async function usdPerPol(force) {
|
||||||
|
if (!force && cache.usdPerPol > 0 && Date.now() - cache.at < TTL) return cache.usdPerPol;
|
||||||
|
const r = await fetchRate();
|
||||||
|
if (!(r > 0) || !isFinite(r)) throw new Error('rate came back unusable');
|
||||||
|
cache = { usdPerPol: r, at: Date.now() };
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
// POL needed for a price in cents. Throws rather than guessing: a purchase priced off a rate we
|
||||||
|
// could not read is a purchase that might sell delivery below cost.
|
||||||
|
async function polForCents(cents) {
|
||||||
|
const rate = await usdPerPol();
|
||||||
|
const pol = (Number(cents) / 100) / rate;
|
||||||
|
return Math.round(pol * 10000) / 10000;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { usdPerPol, polForCents, _cache: () => cache };
|
||||||
Reference in New Issue
Block a user