// On-chain side (VASShop, ../contracts). Each job is inert until configured: // (a) orders: KEEPER_KEY (the keeper the contract trusts) signs EIP-712 Order(buyer, sku, qty, ref, line[], resharer, nonce, deadline). // line = the buyer's network sponsor line from the hub (wallets, nearest first, up to 20); resharer = the wallet of the member whose // reshare link the buyer came through (or zero). The contract pays the resharer's cut, the sponsor levels (pass-up over people // who never bought), the reward-pot slice and the company in the same transaction. A keeper signature is required for every buy. // (b) rewards: the keeper signs Reward(to, usdCents, unlockAt, nonce, deadline) for an L2 sign-up reward that passed every check. // The voucher is kept in the pending-rewards ledger. relayReward() sends claimReward() from RELAY_KEY's wallet (gas only) and is // called ONLY when REWARD_PAYOUTS=1 (OFF until Marty confirms the amounts). The contract enforces the per-reward cap, the // per-recipient daily cap, single-use nonces and that it never pays more than the pot holds. // (c) watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase and RewardPaid logs (confirmed blocks only) and records each once // per txHash:logIndex. // No key ever enters config or any API answer. 'use strict'; const crypto = require('crypto'); const { Wallet, Interface, getAddress, JsonRpcProvider } = require('ethers'); const store = require('./store'); const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; const ZERO = '0x0000000000000000000000000000000000000000'; const IFACE = new Interface([ 'event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 views, uint256 usdCents, uint256 weiPaid, address resharer, uint256 resharerPaid, uint256 potAdded, uint256 companyPaid)', 'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 kind, uint8 depth)', 'event PaymentFailed(uint256 indexed orderId, address indexed to, uint256 amount, uint8 kind, uint8 depth)', 'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)', 'event RewardPaid(uint256 indexed nonce, address indexed to, uint256 usdCents, uint256 weiPaid, uint256 day)']); const TOPIC = IFACE.getEvent('Purchase').topicHash, RTOPIC = IFACE.getEvent('RewardPaid').topicHash; const T = { paid: IFACE.getEvent('Paid').topicHash, fail: IFACE.getEvent('PaymentFailed').topicHash, over: IFACE.getEvent('PassedOver').topicHash }; const CALLS = new Interface(['function quoteWei(uint256 sku, uint256 qty) view returns (uint256)', 'function rewardWei(uint256 usdCents) view returns (uint256)', 'function buy(uint256 sku, uint256 qty, uint256 ref, address[] line, address resharer, uint256 nonce, uint256 deadline, bytes sig) payable returns (uint256 orderId)', 'function claimReward(address to, uint256 usdCents, uint256 unlockAt, uint256 nonce, uint256 deadline, bytes sig) returns (uint256 weiPaid)', 'function boostsBought(address) view returns (uint256)', 'function potBalance() view returns (uint256)', 'function potFunded() view returns (uint256)', 'function potPaid() view returns (uint256)', 'function rewardsToday(address) view returns (uint256)', 'function rewardNonceUsed(uint256) view returns (bool)', 'function resharerBps() view returns (uint256)', 'function potBps() view returns (uint256)', 'function levelBps() view returns (uint16[])', 'function rewardMaxCents() view returns (uint256)', 'function rewardDailyCap() view returns (uint256)', 'function potDailyMaxWei() view returns (uint256)', 'function owner() view returns (address)', 'function company() view returns (address)', 'function keeper() view returns (address)', 'function paused() view returns (bool)', 'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)', 'function skus(uint256) view returns (uint64 usdCents, uint64 views, bool active)']); const TYPES = { Order: [{ name: 'buyer', type: 'address' }, { name: 'sku', type: 'uint256' }, { name: 'qty', type: 'uint256' }, { name: 'ref', type: 'uint256' }, { name: 'line', type: 'address[]' }, { name: 'resharer', type: 'address' }, { name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint256' }], Reward: [{ name: 'to', type: 'address' }, { name: 'usdCents', type: 'uint256' }, { name: 'unlockAt', type: 'uint256' }, { name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint256' }] }; const MAX_LINE = 20; const st = { polls: 0, recorded: 0, rewardsSeen: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null, relayed: 0, relayFailed: 0 }; let C = null, keeper = null, relay = null, busy = false, timer = null; const hooks = { onPurchase: null, attach: null, onReward: null }; function setHook(fn) { hooks.onPurchase = typeof fn === 'function' ? fn : null; } function setAttach(fn) { hooks.attach = typeof fn === 'function' ? fn : null; } function setRewardHook(fn) { hooks.onReward = typeof fn === 'function' ? fn : null; } const keyOf = k => { k = String(k || '').trim(); if (!k) return null; try { return new Wallet(k.startsWith('0x') ? k : '0x' + k); } catch (e) { return null; } }; function init(cfg) { C = cfg; keeper = keyOf(process.env.KEEPER_KEY); relay = keyOf(process.env.RELAY_KEY); if (process.env.KEEPER_KEY && !keeper) console.error('shop: KEEPER_KEY is not a valid private key; orders off'); if (timer) { clearTimeout(timer); timer = null; } if (watching()) { console.log('shop: watching', C.contractAddress); tick(); } } const signerOn = () => !!(C && keeper && C.contractAddress); const watching = () => !!(C && C.contractAddress && C.chainRpc); const domain = () => ({ name: 'VASShop', version: '1', chainId: C.chainId, verifyingContract: C.contractAddress }); const nonce = () => BigInt('0x' + crypto.randomBytes(16).toString('hex')); // 128 random bits: single-use on chain either way function cleanLine(buyer, line) { const b = String(buyer).toLowerCase(); const seen = new Set([b]); const l = []; for (const w of line || []) { const x = String(w || '').toLowerCase(); if (!ADDR_RE.test(x) || x === ZERO || seen.has(x) || x === String(C.contractAddress).toLowerCase()) continue; seen.add(x); l.push(getAddress(x)); if (l.length >= MAX_LINE) break; } return l; } // the buy() call for `buyer`: signed order with the sponsor line and the resharer (zero when none or when it would be the buyer) async function order(buyer, sku, qty, ref, line, resharer) { if (!signerOn()) throw new Error('orders off'); const b = getAddress(String(buyer).toLowerCase()); let r = ADDR_RE.test(resharer || '') ? String(resharer).toLowerCase() : ZERO; if (r === b.toLowerCase()) r = ZERO; const o = { buyer: b, sku: BigInt(sku), qty: BigInt(qty), ref: BigInt(ref || 0), line: cleanLine(b, line), resharer: getAddress(r), nonce: nonce(), deadline: BigInt(Math.floor(Date.now() / 1000) + C.voucherSeconds) }; const sig = await keeper.signTypedData(domain(), { Order: TYPES.Order }, o); const q = await quote(sku, qty); const data = CALLS.encodeFunctionData('buy', [o.sku, o.qty, o.ref, o.line, o.resharer, o.nonce, o.deadline, sig]); return { to: C.contractAddress, chainId: C.chainId, data, value: '0x' + BigInt(q.sendWei).toString(16), wei: q.wei, sendWei: q.sendWei, line: o.line.length, resharer: o.resharer === getAddress(ZERO) ? null : o.resharer.toLowerCase() }; } // an L2 reward voucher (kept in the ledger; relayed only with payouts on) async function rewardVoucher(to, usdCents, unlockAt, days) { if (!signerOn()) return null; const v = { to: getAddress(String(to).toLowerCase()), usdCents: BigInt(usdCents), unlockAt: BigInt(Math.floor((unlockAt || 0) / 1000)), nonce: nonce(), deadline: BigInt(Math.floor(Date.now() / 1000) + (days || 30) * 86400) }; const sig = await keeper.signTypedData(domain(), { Reward: TYPES.Reward }, v); return { to: v.to.toLowerCase(), usdCents: Number(v.usdCents), unlockAt: Number(v.unlockAt), nonce: v.nonce.toString(), deadline: Number(v.deadline), sig, contract: C.contractAddress, chainId: C.chainId }; } // send claimReward() for a stored voucher from the relay wallet. ONLY called with payouts on. -> { tx } | { error } async function relayReward(v) { if (!C.reward.payouts) return { error: 'payouts off' }; if (!relay || !watching()) return { error: 'relay not configured' }; try { const w = relay.connect(new JsonRpcProvider(C.chainRpc, C.chainId, { staticNetwork: true })); const tx = await w.sendTransaction({ to: C.contractAddress, data: CALLS.encodeFunctionData('claimReward', [v.to, v.usdCents, v.unlockAt, BigInt(v.nonce), v.deadline, v.sig]) }); st.relayed++; return { tx: tx.hash }; } catch (e) { st.relayFailed++; const m = String((e && (e.shortMessage || e.reason || e.message)) || 'failed'); st.lastError = m.slice(0, 200); return { error: m.slice(0, 200) }; } } 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(); if (!store.member(a)) store.upsertMember(a, { via: 'wallet' }); const rec = { at: Date.now(), blockAt: ev.blockAt || null, block: ev.block, orderId: ev.orderId, buyer: a, sku: ev.sku, qty: ev.qty, ref: ev.ref, views: ev.views, usdCents: ev.usdCents, weiPaid: ev.weiPaid, resharer: ev.resharer, resharerPaid: ev.resharerPaid, potAdded: ev.potAdded, companyPaid: ev.companyPaid }; if (hooks.attach) { try { hooks.attach(rec); } catch (e) {} } P[key] = rec; store.save(); st.recorded++; if (hooks.onPurchase) { try { hooks.onPurchase(rec, String(ev.txHash).toLowerCase()); } catch (e) {} } console.log('shop: Boost order', ev.orderId, 'x' + ev.qty, a, rec.adId ? 'for ad #' + rec.adId : '(no ad yet)', rec.resharer ? 'via resharer ' + rec.resharer : ''); return true; } function decode(l) { if (!l || l.removed || String(l.address || '').toLowerCase() !== C.contractAddress.toLowerCase()) return null; const t0 = (l.topics || [])[0]; if (t0 === TOPIC) { const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; const r = String(d.resharer).toLowerCase(); return { kind: 'purchase', 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(), views: Number(d.views), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString(), resharer: r === ZERO ? null : r, resharerPaid: d.resharerPaid.toString(), potAdded: d.potAdded.toString(), companyPaid: d.companyPaid.toString() }; } if (t0 === RTOPIC) { const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; return { kind: 'reward', txHash: l.transactionHash, logIndex: parseInt(l.logIndex, 16), block: parseInt(l.blockNumber, 16), nonce: d.nonce.toString(), to: String(d.to).toLowerCase(), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString() }; } return null; } // the split of one order from its receipt: kind 0 company, 1..5 sponsor levels (with depth), 6 resharer; who was passed over async function readSplit(tx, orderId) { const r = await rpc('eth_getTransactionReceipt', [tx]); if (!r || !Array.isArray(r.logs)) return null; const pays = [], over = []; for (const l of r.logs) { if (String(l.address).toLowerCase() !== C.contractAddress.toLowerCase()) continue; const t0 = l.topics[0]; if (t0 !== T.paid && t0 !== T.fail && t0 !== T.over) continue; const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; if (Number(d.orderId) !== Number(orderId)) continue; if (t0 === T.over) over.push({ who: d.who.toLowerCase(), depth: Number(d.depth) }); else pays.push({ kind: Number(d.kind), depth: Number(d.depth), to: d.to.toLowerCase(), wei: d.amount.toString(), failed: t0 === T.fail || undefined }); } return { pays, over }; } 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); } } async function poll() { if (busy || !watching()) return; busy = true; st.polls++; try { const S = store.state(); const sh = S.shop || (S.shop = {}); sh.rewards = sh.rewards || {}; const head = parseInt(await rpc('eth_blockNumber', []), 16) - C.shopConfirmations; st.head = head; if (sh.lastBlock == null) { sh.lastBlock = (C.shopStartBlock || head + 1) - 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, RTOPIC]], fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }]); for (const l of logs || []) { const ev = decode(l); if (!ev) { st.ignored++; continue; } const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex; if (ev.kind === 'reward') { if (sh.rewards[key]) continue; sh.rewards[key] = { nonce: ev.nonce, to: ev.to, weiPaid: ev.weiPaid, at: Date.now() }; st.rewardsSeen++; if (hooks.onReward) { try { hooks.onReward(ev); } catch (e) {} } continue; } if ((S.purchases || {})[key]) { st.dupes++; 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; } } 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(); } }); } async function call(fn, args) { const r = await rpc('eth_call', [{ to: C.contractAddress, data: CALLS.encodeFunctionData(fn, args || []) }, 'latest']); return CALLS.decodeFunctionResult(fn, r); } const qCache = new Map(); 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 live split and reward rules from the contract (cached 5 minutes); null when the chain is not set or does not answer let rules = null; async function liveRules() { if (!watching()) return null; if (rules && Date.now() - rules.at < 300000) return rules.v; try { const [r, p, l, mx, cap, pot] = await Promise.all(['resharerBps', 'potBps', 'levelBps', 'rewardMaxCents', 'rewardDailyCap', 'potBalance'].map(f => call(f).then(x => x[0]))); const v = { resharerBps: Number(r), potBps: Number(p), levelBps: l.map(Number), rewardMaxCents: Number(mx), rewardDailyCap: Number(cap), potWei: pot.toString() }; rules = { at: Date.now(), v }; return v; } catch (e) { return rules ? rules.v : null; } } 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 }; } 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) }; } let lastNudge = 0; function nudge() { if (!watching() || Date.now() - lastNudge < 3000) return; lastNudge = Date.now(); poll().catch(() => {}); } function view() { const list = Object.values((store.state() && store.state().purchases) || {}); return Object.assign({ contract: C ? C.contractAddress || null : null, watching: watching(), orders: signerOn(), keeper: keeper ? keeper.address : null, relay: relay ? relay.address : null, payouts: !!(C && C.reward.payouts), lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, boosts: list.reduce((t, x) => t + (Number(x.qty) || 1), 0), orderCount: list.length }, st); } module.exports = { setHook, setAttach, setRewardHook, init, order, rewardVoucher, relayReward, signerOn, watching, apply, poll, view, quote, liveRules, receipt, fees, nudge, call, rpc, readSplit, TOPIC, RTOPIC, IFACE, TYPES, CALLS, MAX_LINE, ZERO };