Files
vbb/shop.js
T

89 lines
6.5 KiB
JavaScript

// 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.
// The key never enters config or any API answer. Packages stay "coming soon" in the UI until Marty says go.
'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 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(), 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) apply(ev); else st.ignored++; }
sh.lastBlock = to; store.save();
}
} catch (e) { st.errors++; st.lastError = String(e.message).slice(0, 200); }
finally { busy = false; }
}
function tick() { poll().finally(() => { if (watching()) { timer = setTimeout(tick, C.shopPollMs); timer.unref(); } }); }
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, TOPIC, IFACE, TYPES };