9408b7af8b
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
74 lines
5.3 KiB
JavaScript
74 lines
5.3 KiB
JavaScript
// Refuel spots (Marty 2026-11-13: "it will get paid from the company fee share ... the $50+"). A counted Monthly Refuel of $50 or
|
|
// more on InstantAdPay or LinkSpin (InstantAdPay decides, it keeps the one streak for both sites) earns the refueling member one
|
|
// Downline Banners spot: buyFor(member wallet, member's network sponsor wallet), paid by the engine wallet (KEEPER_KEY), which
|
|
// Marty tops up from the company fee share. InstantAdPay posts each one to /api/partner/refuel-spot signed with
|
|
// NETWORK_SSO_SECRET ('net.v1.' + ts + newline + raw body). One spot per refuel tx, ever (refuelspots.json is keyed by it).
|
|
// Never spends below RESERVE: with too little POL the spot waits in the queue ("engine wallet low") and is bought once topped up.
|
|
// Every buy is recorded with its cost, so the company's spend on refuel spots can be totalled exactly.
|
|
'use strict';
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { Wallet, JsonRpcProvider } = require('ethers');
|
|
const cfgMod = require('./config');
|
|
const chain = require('./chain');
|
|
const { iface } = require('./abi');
|
|
|
|
const RESERVE = 3n * 10n ** 18n; // POL kept for gas (the engine wallet also signs InstantAdPay credit burns and fund buys)
|
|
const ADDR = /^0x[0-9a-f]{40}$/;
|
|
let S = null, busy = false, lockFn = () => false;
|
|
const FILE = () => path.join(cfgMod.get().dataDir, 'refuelspots.json');
|
|
function load() { if (S) return S; try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = {}; } S.items = S.items || {}; return S; }
|
|
function save() { try { fs.writeFileSync(FILE() + '.tmp', JSON.stringify(load())); fs.renameSync(FILE() + '.tmp', FILE()); } catch (e) { console.error('refuelspots save', e.message); } }
|
|
|
|
// -> { ok, queued | repeat } or { error }
|
|
function enqueue(b) {
|
|
const tx = String(b.tx || '').toLowerCase(); const w = String(b.wallet || '').toLowerCase(); const sp = String(b.sponsorWallet || '').toLowerCase();
|
|
if (!/^0x[0-9a-f]{64}$/.test(tx)) return { error: 'tx' };
|
|
if (!ADDR.test(w)) return { error: 'wallet' };
|
|
if (!(Number(b.cents) >= 5000)) return { error: 'below $50' };
|
|
const s = load(); if (s.items[tx]) return { ok: true, repeat: true, status: s.items[tx].status };
|
|
s.items[tx] = { tx, site: String(b.site || '').slice(0, 10), wallet: w, sponsor: ADDR.test(sp) && sp !== w ? sp : null, cents: Number(b.cents), status: 'queued', at: Date.now(), tries: 0 };
|
|
save(); setTimeout(() => tick().catch(() => {}), 2000);
|
|
return { ok: true, queued: true };
|
|
}
|
|
|
|
async function tick() {
|
|
const c = cfgMod.get();
|
|
if (busy || lockFn() || !process.env.KEEPER_KEY || !c.contract) return;
|
|
const s = load(); const next = Object.values(s.items).find(x => x.status === 'queued' && (!x.retryAt || x.retryAt < Date.now()));
|
|
if (!next) return;
|
|
busy = true;
|
|
try {
|
|
const provider = new JsonRpcProvider(c.rpcs[0], c.chainId, { staticNetwork: true });
|
|
const signer = new Wallet(process.env.KEEPER_KEY, provider);
|
|
const q = await chain.quote(); const value = BigInt(q.sendWei || q.wei); // the contract refunds anything above the price
|
|
const bal = await provider.getBalance(signer.address);
|
|
if (bal < value + RESERVE) { next.why = 'engine wallet low: ' + (Number(bal / 10n ** 15n) / 1000) + ' POL, needs ' + (Number((value + RESERVE) / 10n ** 15n) / 1000); next.retryAt = Date.now() + 30 * 60000; save(); return; }
|
|
const fees = await chain.suggestedFees();
|
|
const sponsor = next.sponsor || chain.ZERO;
|
|
const tx = await signer.sendTransaction({ to: c.contract, value, data: iface.encodeFunctionData('buyFor', [next.wallet, sponsor]),
|
|
maxFeePerGas: BigInt(fees.maxFeePerGas), maxPriorityFeePerGas: BigInt(fees.maxPriorityFeePerGas) });
|
|
next.status = 'sent'; next.spotTx = tx.hash; next.sentWei = value.toString(); delete next.why; save();
|
|
console.log('refuel spot sent', tx.hash, 'for', next.wallet);
|
|
const r = await tx.wait(1, 180000).catch(() => null);
|
|
if (r && r.status === 1) {
|
|
next.status = 'bought'; next.boughtAt = Date.now(); next.gasWei = (BigInt(r.gasUsed) * BigInt(r.gasPrice || r.effectiveGasPrice || 0)).toString();
|
|
try { const ev = r.logs.map(l => { try { return iface.parseLog(l); } catch (e) { return null; } }).find(x => x && x.name === 'SpotBought'); if (ev) { next.spotId = Number(ev.args.id); next.costWei = String(ev.args.valueWei); } } catch (e) {}
|
|
} else { next.status = r ? 'reverted' : 'unconfirmed'; }
|
|
save(); await chain.tail().catch(() => {});
|
|
} catch (e) {
|
|
next.tries = (next.tries || 0) + 1; next.why = String(e && (e.shortMessage || e.message) || e).slice(0, 200);
|
|
if (next.status === 'queued') next.retryAt = Date.now() + Math.min(6 * 3600000, 5 * 60000 * 2 ** Math.min(next.tries, 6)); save();
|
|
console.error('refuel spot', next.why);
|
|
} finally { busy = false; }
|
|
}
|
|
|
|
function init(opts) { if (opts && opts.lock) lockFn = opts.lock; load(); const t = setInterval(() => tick().catch(e => console.error('refuelspots', e.message)), 120000); t.unref && t.unref(); }
|
|
function view() {
|
|
const items = Object.values(load().items).sort((a, b) => b.at - a.at);
|
|
const bought = items.filter(x => x.status === 'bought');
|
|
const sum = k => bought.reduce((t, x) => t + BigInt(x[k] || 0), 0n).toString();
|
|
return { queued: items.filter(x => x.status === 'queued').length, bought: bought.length, costWei: sum('costWei'), gasWei: sum('gasWei'), recent: items.slice(0, 20) };
|
|
}
|
|
module.exports = { init, enqueue, tick, view, busy: () => busy };
|