// On-chain positions (DraftPosition, ../contracts). Each job is inert until it is configured: // (a) line vouchers: KEEPER_KEY (the keeper the contract trusts) signs EIP-712 Voucher(buyer, address[] line, deadline), line = // the buyer's network sponsor line from the hub (wallets, nearest first, up to 20). On the buyer's first position the contract // binds every unbound link along it; a bound link never changes (the contract's binding wins, Marty 2026-11-14). // (b) chain watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase logs (confirmed blocks only) and records each position purchase once // per txHash:logIndex (the dedupe mark and the purchase live in the same document, so they save together). // (c) buying: quote() reads quoteWei, order() builds the member's buy() call, receipt() / fees() back the page's wait. // 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 ZERO = '0x0000000000000000000000000000000000000000'; const IFACE = new Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 qty, uint256 ref, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, uint256 prizePaid, uint256 companyPaid)', 'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)', 'event PaymentFailed(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)', 'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)', 'event SponsorBound(address indexed member, address indexed sponsor)']); const TOPIC = IFACE.getEvent('Purchase').topicHash; const T = { paid: IFACE.getEvent('Paid').topicHash, fail: IFACE.getEvent('PaymentFailed').topicHash, over: IFACE.getEvent('PassedOver').topicHash, bound: IFACE.getEvent('SponsorBound').topicHash }; const CALLS = new Interface(['function quoteWei(uint256 qty) view returns (uint256)', 'function buy(uint256 qty, uint256 ref, address[] line, uint256 deadline, bytes sig) payable returns (uint256 orderId)', 'function sponsorOf(address) view returns (address)', 'function positionsHeld(address) view returns (uint256)', 'function payeesOf(address buyer) view returns (address[] to, uint8[] depth)', 'function priceCents() view returns (uint256)']); const TYPES = { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'line', type: 'address[]' }, { name: 'deadline', type: 'uint256' }] }; const MAX_LINE = 20; const st = { polls: 0, recorded: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null }; let C = null, keeper = null, busy = false, timer = null; const hooks = { onPurchase: null, attach: null }; function setHook(fn) { hooks.onPurchase = typeof fn === 'function' ? fn : null; } function setAttach(fn) { hooks.attach = typeof fn === 'function' ? fn : 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 positions'); tick(); } } const voucherOn = () => !!(C && keeper && C.contractAddress); const watching = () => !!(C && C.contractAddress && C.chainRpc); const domain = () => ({ name: 'DraftPosition', version: '1', chainId: C.chainId, verifyingContract: C.contractAddress }); // a voucher binding `line` (wallets, nearest first) above `buyer`, or null (off, empty, bad) async function voucher(buyer, line) { if (!voucherOn() || !ADDR_RE.test(buyer || '')) return null; const b = getAddress(buyer); const seen = new Set([b.toLowerCase()]); const l = []; for (const w of line || []) { if (!ADDR_RE.test(w || '') || seen.has(w.toLowerCase()) || w === ZERO) continue; seen.add(w.toLowerCase()); l.push(getAddress(w)); if (l.length >= MAX_LINE) break; } if (!l.length) return null; const deadline = Math.floor(Date.now() / 1000) + C.voucherSeconds; const sig = await keeper.signTypedData(domain(), TYPES, { buyer: b, line: l, deadline }); return { buyer: b, line: l, deadline, sig, contract: C.contractAddress, chainId: C.chainId }; } // record one Purchase log. false = already recorded (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(); 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, qty: ev.qty, ref: ev.ref, usdCents: ev.usdCents, weiPaid: ev.weiPaid, levelsPaid: ev.levelsPaid, prizePaid: ev.prizePaid, companyPaid: ev.companyPaid, sponsor: ev.sponsor || null }; 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: position order', ev.orderId, 'x' + ev.qty, a); 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, qty: Number(d.qty), ref: d.ref.toString(), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString(), levelsPaid: Number(d.levelsPaid), prizePaid: d.prizePaid.toString(), companyPaid: d.companyPaid.toString() }; } // the split of one order from its receipt: level payouts (with their place in the line), the prize pot (level 6), the company, who was passed over and // which links of the line this purchase bound. null if the RPC does not answer. async function readSplit(tx, orderId) { const r = await rpc('eth_getTransactionReceipt', [tx]); if (!r || !Array.isArray(r.logs)) return null; const pays = [], over = [], bound = []; for (const l of r.logs) { if (String(l.address).toLowerCase() !== C.contractAddress.toLowerCase()) continue; const t0 = l.topics[0]; if (t0 === T.bound) { const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; bound.push({ member: d.member.toLowerCase(), sponsor: d.sponsor.toLowerCase() }); continue; } 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({ level: Number(d.level), depth: Number(d.depth), to: d.to.toLowerCase(), wei: d.amount.toString(), failed: t0 === T.fail || undefined }); } return { pays, over, bound }; } 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 = {}); 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; } const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex; if ((S.purchases || {})[key]) { st.dupes++; continue; } ev.blockAt = await blockTime(ev.block); try { ev.sponsor = String((await call('sponsorOf', [ev.buyer]))[0]).toLowerCase(); if (ev.sponsor === ZERO) ev.sponsor = null; } catch (e) {} 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(); } }); } // ---- 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 positions now; sendWei adds 1% for price drift (the contract refunds anything above the price in the same tx) async function quote(qty) { const k = 'x' + qty; const hit = qCache.get(k); if (hit && Date.now() - hit.at < 15000) return hit.v; const wei = (await call('quoteWei', [qty]))[0]; const v = { qty, wei: wei.toString(), sendWei: (wei + wei / 100n).toString() }; qCache.set(k, { at: Date.now(), v }); if (qCache.size > 200) qCache.clear(); return v; } async function order(buyer, qty, ref, v) { const q = await quote(qty); const data = CALLS.encodeFunctionData('buy', [qty, BigInt(ref || 0), v ? v.line : [], 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, line: v ? v.line.length : 0 }; } // is the buyer's line already bound on chain? (then no voucher is needed: the contract ignores it) async function boundSponsor(buyer) { try { const s = String((await call('sponsorOf', [buyer]))[0]).toLowerCase(); return s === ZERO ? null : s; } catch (e) { return undefined; } } async function payees(buyer) { try { const r = await call('payeesOf', [buyer]); return r[0].map((a, i) => ({ to: String(a).toLowerCase(), depth: Number(r[1][i]) })); } catch (e) { return 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 }; } // 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) }; } 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(), vouchers: voucherOn(), keeper: keeper ? keeper.address : null, lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, positions: list.reduce((t, x) => t + (Number(x.qty) || 1), 0), orders: list.length }, st); } module.exports = { setHook, setAttach, init, voucher, voucherOn, watching, apply, poll, view, quote, order, receipt, fees, nudge, call, rpc, readSplit, boundSponsor, payees, TOPIC, IFACE, TYPES, CALLS, MAX_LINE };