// On-chain purchases (VBBShop, ../contracts). Two jobs, each inert until it is configured: // (a) sponsor vouchers: KEEPER_KEY (the keeper the contract trusts) signs EIP-712 Voucher(buyer, sponsor, deadline) for a // signed-in member whose network sponsor the hub knows. The contract binds that sponsor on the member's first purchase. // (b) chain watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase logs (confirmed blocks only) and credits the buyer // once per txHash:logIndex. The dedupe mark and the credits live in the same document (vbb.json), so they save together. // (c) buying (live 2026-11-14): quote() reads quoteWei, order() builds the member's buy() call (fresh voucher inside, else none), // receipt() / fees() back the page's confirmation wait, nudge() polls right after a member's transaction confirms. // The key never enters config or any API answer. 'use strict'; const { Wallet, Interface, getAddress } = require('ethers'); const store = require('./store'); const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; const IFACE = new Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 credits, uint256 usdCents, uint256 weiPaid, address sponsor, uint256 sponsorPaid)']); const TOPIC = IFACE.getEvent('Purchase').topicHash; const CALLS = new Interface(['function quoteWei(uint256 sku, uint256 qty) view returns (uint256)', 'function buy(uint256 sku, uint256 qty, uint256 ref, address sponsor, uint256 deadline, bytes sig) payable returns (uint256 orderId)', 'function prizeWallet() view returns (address)', 'function priceFeed() view returns (address)', 'function latestRoundData() view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)']); const TYPES = { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'sponsor', type: 'address' }, { name: 'deadline', type: 'uint256' }] }; const st = { polls: 0, credited: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null }; let C = null, keeper = null, busy = false, timer = null; function init(cfg) { C = cfg; keeper = null; const k = String(process.env.KEEPER_KEY || '').trim(); if (k) { try { keeper = new Wallet(k.startsWith('0x') ? k : '0x' + k); } catch (e) { console.error('shop: KEEPER_KEY is not a valid private key; vouchers off'); } } if (timer) { clearTimeout(timer); timer = null; } if (watching()) { console.log('shop: watching', C.contractAddress, 'for purchases'); tick(); } } const voucherOn = () => !!(C && keeper && C.contractAddress); const watching = () => !!(C && C.contractAddress && C.chainRpc); const domain = () => ({ name: 'VBBShop', version: '1', chainId: C.chainId, verifyingContract: C.contractAddress }); // a voucher binding `sponsor` to `buyer`, or null (off, bad sponsor, self-sponsor) async function voucher(buyer, sponsor) { if (!voucherOn() || !ADDR_RE.test(buyer || '') || !ADDR_RE.test(sponsor || '')) return null; const b = getAddress(buyer), s = getAddress(sponsor); if (b === s) return null; const deadline = Math.floor(Date.now() / 1000) + C.voucherSeconds; const sig = await keeper.signTypedData(domain(), TYPES, { buyer: b, sponsor: s, deadline }); return { buyer: b, sponsor: s, deadline, sig, contract: C.contractAddress, chainId: C.chainId }; } // credit one Purchase log. false = already credited (or not ours). function apply(ev) { const S = store.state(); const P = S.purchases || (S.purchases = {}); const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex; if (P[key]) { st.dupes++; return false; } const a = ev.buyer.toLowerCase(); const m = store.member(a) || store.upsertMember(a, { via: 'wallet' }); let applied = 'credits'; if (ev.credits > 0) m.credits += ev.credits; else { const b = Number.isSafeInteger(Number(ev.ref)) ? store.banner(Number(ev.ref)) : null; if (b && b.owner === a) { b.look = true; store.saveBanner(b); applied = 'look'; } else applied = 'unmatched'; } P[key] = { at: Date.now(), blockAt: ev.blockAt || null, block: ev.block, orderId: ev.orderId, buyer: a, sku: ev.sku, qty: ev.qty, ref: ev.ref, credits: ev.credits, usdCents: ev.usdCents, weiPaid: ev.weiPaid, sponsor: ev.sponsor, sponsorPaid: ev.sponsorPaid, applied }; store.save(); st.credited++; console.log('shop: order', ev.orderId, 'sku', ev.sku, 'x' + ev.qty, a, applied === 'credits' ? '+' + ev.credits + ' credits' : applied); return true; } function decode(l) { if (!l || l.removed || String(l.address || '').toLowerCase() !== C.contractAddress.toLowerCase() || (l.topics || [])[0] !== TOPIC) return null; const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; return { txHash: l.transactionHash, logIndex: parseInt(l.logIndex, 16), block: parseInt(l.blockNumber, 16), orderId: Number(d.orderId), buyer: d.buyer, sku: Number(d.sku), qty: Number(d.qty), ref: d.ref.toString(), credits: Number(d.credits), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString(), sponsor: d.sponsor.toLowerCase(), sponsorPaid: d.sponsorPaid.toString() }; } async function rpc(method, params) { const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 10000); t.unref(); try { const j = await (await fetch(C.chainRpc, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), signal: ac.signal })).json(); if (j.error) throw new Error(method + ': ' + (j.error.message || JSON.stringify(j.error))); return j.result; } finally { clearTimeout(t); } } // confirmed blocks only, 1,000 blocks per getLogs (public RPC limits); the last scanned block is saved with the credits async function poll() { if (busy || !watching()) return; busy = true; st.polls++; try { const S = store.state(); const sh = S.shop || (S.shop = {}); const head = parseInt(await rpc('eth_blockNumber', []), 16) - C.shopConfirmations; st.head = head; if (sh.lastBlock == null) { sh.lastBlock = (C.shopStartBlock || head + 1) - 1; if (!C.shopStartBlock) console.log('shop: no SHOP_START_BLOCK, watching from block', head + 1); store.save(); } while (sh.lastBlock < head) { const from = sh.lastBlock + 1, to = Math.min(head, from + 999); const logs = await rpc('eth_getLogs', [{ address: C.contractAddress, topics: [TOPIC], fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }]); for (const l of logs || []) { const ev = decode(l); if (!ev) { st.ignored++; continue; } ev.blockAt = await blockTime(ev.block); apply(ev); } sh.lastBlock = to; store.save(); } } catch (e) { st.errors++; st.lastError = String(e.message).slice(0, 200); } finally { busy = false; } } // the block's timestamp (seconds), for the Central-time week a sale belongs to. null if the RPC does not answer (the credit time is used). const btCache = new Map(); async function blockTime(n) { if (btCache.has(n)) return btCache.get(n); let t = null; try { const b = await rpc('eth_getBlockByNumber', ['0x' + n.toString(16), false]); t = b && b.timestamp ? parseInt(b.timestamp, 16) : null; } catch (e) {} if (t) { btCache.set(n, t); if (btCache.size > 5000) btCache.clear(); } return t; } function tick() { poll().finally(() => { if (watching()) { timer = setTimeout(tick, C.shopPollMs); timer.unref(); } }); } // ---- buying ---- async function call(fn, args, to) { const r = await rpc('eth_call', [{ to: to || C.contractAddress, data: CALLS.encodeFunctionData(fn, args || []) }, 'latest']); return CALLS.decodeFunctionResult(fn, r); } const qCache = new Map(); // POL wei for qty of sku now; sendWei adds 1% for price drift (the contract refunds anything above the price in the same tx) async function quote(sku, qty) { const k = sku + 'x' + qty; const hit = qCache.get(k); if (hit && Date.now() - hit.at < 15000) return hit.v; const wei = (await call('quoteWei', [sku, qty]))[0]; const v = { sku, qty, wei: wei.toString(), sendWei: (wei + wei / 100n).toString() }; qCache.set(k, { at: Date.now(), v }); if (qCache.size > 200) qCache.clear(); return v; } // the buy() call for this member: to, data, value. voucher = shop.voucher() result or null (no sponsor bound by this purchase) async function order(buyer, sku, qty, ref, v) { const q = await quote(sku, qty); const data = CALLS.encodeFunctionData('buy', [sku, qty, BigInt(ref || 0), v ? v.sponsor : '0x0000000000000000000000000000000000000000', v ? v.deadline : 0, v ? v.sig : '0x']); return { to: C.contractAddress, chainId: C.chainId, data, value: '0x' + BigInt(q.sendWei).toString(16), wei: q.wei, sendWei: q.sendWei, sponsor: !!v }; } async function receipt(hash) { const r = await rpc('eth_getTransactionReceipt', [hash]); if (!r) return { found: false }; return { found: true, status: r.status, blockNumber: r.blockNumber, to: r.to ? String(r.to).toLowerCase() : null, from: r.from ? String(r.from).toLowerCase() : null }; } // Polygon's ~25 gwei priority-fee floor: wallets' own estimates miss it (the Downline Banners fix) async function fees() { let tip = 0n, base = 0n; try { tip = BigInt(await rpc('eth_maxPriorityFeePerGas', [])); } catch (e) {} try { const blk = await rpc('eth_getBlockByNumber', ['latest', false]); base = BigInt((blk && blk.baseFeePerGas) || '0x0'); } catch (e) {} const MIN_TIP = C.chainId === 137 ? 30000000000n : 1000000000n; const priority = tip > MIN_TIP ? tip : MIN_TIP; return { maxPriorityFeePerGas: '0x' + priority.toString(16), maxFeePerGas: '0x' + (base * 2n + priority).toString(16) }; } // a member's transaction just confirmed: scan now instead of waiting for the next poll (confirmations still apply) let lastNudge = 0; function nudge() { if (!watching() || Date.now() - lastNudge < 3000) return; lastNudge = Date.now(); poll().catch(() => {}); } // sales of one Central-time week (key = that Monday): from the credited Purchase events, by block time function weekSales(week, ctWeek) { const P = ((store.state() || {}).purchases) || {}; let cents = 0, n = 0, prizeWei = 0n; for (const x of Object.values(P)) { if (ctWeek(x.blockAt ? x.blockAt * 1000 : x.at) !== week) continue; n++; cents += Number(x.usdCents) || 0; try { prizeWei += BigInt(x.weiPaid || 0) * 1000n / 10000n; } catch (e) {} } return { purchases: n, cents, prizeWei: prizeWei.toString() }; } function view() { const P = (store.state() && store.state().purchases) || {}; const list = Object.values(P); return Object.assign({ contract: C ? C.contractAddress || null : null, watching: watching(), vouchers: voucherOn(), keeper: keeper ? keeper.address : null, lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, purchases: list.length, creditsSold: list.reduce((t, x) => t + (x.credits || 0), 0), unmatched: list.filter(x => x.applied === 'unmatched').length }, st); } module.exports = { init, voucher, voucherOn, watching, apply, poll, view, quote, order, receipt, fees, nudge, call, rpc, weekSales, TOPIC, IFACE, TYPES, CALLS };