Files
banner-line/keeper.js
T

97 lines
5.7 KiB
JavaScript

// Keeper engine: momentum-fund buys (SPEC "Momentum fund"). OFF unless KEEPER_ENABLED=1 and KEEPER_KEY is set.
// Every 15 min: if no spot has SOLD (kind 0 paid / 1 bought-for) for 4 h and fewer than 12 fund buys happened
// today (US Central), call fundBuy(giftee). Giftee = an active member (signed in or bought within 7 days) who owns
// a paid spot and had no gift in 7 days; builders (sponsored someone in the last 30 days) first, then the longest
// wait; nobody eligible -> address(0) (the fund keeps the spot). The contract enforces the money + 7-day rules.
// KEEPER_KEY is read from env only at signing time and is never logged, stored or returned.
const { Wallet, JsonRpcProvider } = require('ethers');
const cfgMod = require('./config');
const chain = require('./chain');
const store = require('./store');
const { iface } = require('./abi');
const DAY = 86400000;
let running = false, timer = null, lastDecision = null;
function centralDay(ms) { return new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(ms)); }
function lastGiftMap() { const m = new Map(); for (const f of chain.fundBuys()) if (f.giftee !== chain.ZERO) m.set(f.giftee, Math.max(m.get(f.giftee) || 0, f.at)); return m; }
function candidates(now) {
now = now || Date.now();
const spots = chain.spots(); const gifts = lastGiftMap();
const owners = new Map();
for (const s of spots) { if (!owners.has(s.owner)) owners.set(s.owner, []); owners.get(s.owner).push(s); }
const out = [];
for (const [addr, list] of owners) {
if (addr === chain.ZERO || addr === String(cfgMod.get().contract).toLowerCase()) continue;
const paid = list.filter(s => s.kind === 0);
if (!paid.length) continue;
const boughtRecently = list.some(s => (s.kind === 0 || s.kind === 1) && now - s.boughtAt < 7 * DAY);
const seenRecently = now - store.lastSeen(addr) < 7 * DAY;
if (!boughtRecently && !seenRecently) continue;
const lastGift = gifts.get(addr) || 0;
if (lastGift && now - lastGift < 7 * DAY) continue;
const builder = chain.directs(addr).some(m => now - m.joinedAt < 30 * DAY);
const waitingSince = lastGift || Math.min(...paid.map(s => s.boughtAt));
out.push({ address: addr, builder, waitingSince });
}
out.sort((a, b) => (b.builder - a.builder) || (a.waitingSince - b.waitingSince));
return out;
}
function decide(now) {
now = now || Date.now(); const c = cfgMod.get();
const sold = chain.spots().filter(s => s.kind === 0 || s.kind === 1);
const lastSale = sold.length ? Math.max(...sold.map(s => s.boughtAt)) : 0;
const today = centralDay(now);
const fundToday = chain.fundBuys().filter(f => centralDay(f.at) === today).length
+ store.keeperEntries().filter(e => e.status === 'sent' && centralDay(e.at) === today && !chain.fundBuys().some(f => f.tx === e.tx)).length;
if (!chain.spots().length) return { act: false, why: 'no spots in the line yet' };
if (now - lastSale < c.keeperStallHours * 3600000) return { act: false, why: 'a spot sold in the last ' + c.keeperStallHours + ' h' };
if (fundToday >= c.keeperMaxPerDay) return { act: false, why: fundToday + ' fund buys today (Central), limit ' + c.keeperMaxPerDay };
const cands = candidates(now);
return { act: true, giftee: cands.length ? cands[0].address : chain.ZERO, candidates: cands.length, fundToday };
}
async function tick() {
const c = cfgMod.get();
if (running || !c.keeperEnabled || !process.env.KEEPER_KEY || !c.contract) return;
running = true;
try {
await chain.tail(); // decide on fresh data
const d = decide(); lastDecision = Object.assign({ at: Date.now() }, d);
if (!d.act) return;
let giftee = d.giftee;
// the contract's own 7-day check is authoritative: re-read it when the view exists
if (giftee !== chain.ZERO) { const lg = await chain.tryRead('lastGiftAt', [giftee]); if (lg && Date.now() / 1000 - Number(lg) < 7 * 86400) giftee = chain.ZERO; }
const q = await chain.quote();
const fb = await chain.tryRead('fundBalance');
if (fb !== null && BigInt(fb) < BigInt(q.wei)) { store.keeperLog({ status: 'skipped', why: 'fund balance below one spot', giftee }); return; }
const provider = new JsonRpcProvider(c.rpcs[0], c.chainId, { staticNetwork: true });
const signer = new Wallet(process.env.KEEPER_KEY, provider);
const fees = await chain.suggestedFees();
const tx = await signer.sendTransaction({ to: c.contract, data: iface.encodeFunctionData('fundBuy', [giftee]),
maxFeePerGas: BigInt(fees.maxFeePerGas), maxPriorityFeePerGas: BigInt(fees.maxPriorityFeePerGas) });
store.keeperLog({ status: 'sent', tx: tx.hash, giftee });
console.log('keeper fundBuy sent', tx.hash, 'giftee', giftee);
const r = await tx.wait(1, 180000).catch(e => null);
store.keeperLog({ status: r && r.status === 1 ? 'mined' : 'unconfirmed', tx: tx.hash, giftee });
await chain.tail();
} catch (e) {
const msg = String(e && (e.shortMessage || e.message) || e).slice(0, 200);
store.keeperLog({ status: 'error', why: msg }); console.error('keeper', msg);
} finally { running = false; }
}
function init() {
const c = cfgMod.get();
if (!c.keeperEnabled || !process.env.KEEPER_KEY) { console.log('keeper: off (needs KEEPER_ENABLED=1 and KEEPER_KEY)'); return; }
console.log('keeper: on, every ' + Math.round(c.keeperEveryMs / 60000) + ' min');
setTimeout(tick, 15000).unref();
timer = setInterval(tick, c.keeperEveryMs); timer.unref && timer.unref();
}
function statusInfo() { const c = cfgMod.get(); return { enabled: c.keeperEnabled && !!process.env.KEEPER_KEY, last: lastDecision, preview: decide(), log: store.keeperEntries().slice(-20).reverse() }; }
module.exports = { init, tick, decide, candidates, statusInfo, centralDay };