Files
Marty Bostick 001878bdae ViralAdBlitz v1 (viraladblitz.com rebuild, Marty approved 2026-11-14): the network's text-ad home, local build, not deployed
- Free text ad for network members (InstantAdPay / LinkSpin sign-in or wallet, membership through the hub), one per member
- Member pages viraladblitz.com/<username>: own ad + the first 5 people above in the hub line with a live ad (by place) + 2 Boosted places
- Front page: amber ticker (Boosted starred), Top ads this week by verified clicks, today's numbers, ledger, contract proof
- Verified visitors / views / clicks (ticket + dwell + per-visitor dedupe + per-connection cap + bot filter, owner excluded)
- Boost $5 = 500 guaranteed views through VABShop: keeper-signed EIP-712 line voucher from the hub line, watcher, delivery
  counted per verified view with an audit row each, Network Ad Space text-ad finishing after 30 days (vabnas.js)
- Trust pack: /ledger, /contract, toasts, Telegram card per Boost (once), Terms / Earnings Disclaimer / Privacy (TrustClickz),
  network footer from the hub with tracked links, promo kit (21 creatives) + /promote, LinkSpin zone placeholders, hub report
- Old YFW links via the oldrefs map (admin load route); docstore MySQL documents + row tables
- qa/smoke.mjs 162/162 (stand-in hub, chain, Telegram, NAS; Playwright desktop + phone), qa/chain.mjs 20/20 (real VABShop on anvil)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:52:03 -06:00

174 lines
13 KiB
JavaScript

// On-chain Boosts (VABShop, ../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 Boost 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 Boost once
// per txHash:logIndex (the dedupe mark and the Boost 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 indexed sku, uint256 qty, uint256 ref, uint256 views, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, 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 sku, uint256 qty) view returns (uint256)',
'function buy(uint256 sku, uint256 qty, uint256 ref, address[] line, uint256 deadline, bytes sig) payable returns (uint256 orderId)',
'function sponsorOf(address) view returns (address)', 'function boostsBought(address) view returns (uint256)',
'function payeesOf(address buyer) view returns (address[] to, uint8[] depth)', 'function skus(uint256) view returns (uint64 usdCents, uint64 views, bool active)']);
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 Boosts'); tick(); }
}
const voucherOn = () => !!(C && keeper && C.contractAddress);
const watching = () => !!(C && C.contractAddress && C.chainRpc);
const domain = () => ({ name: 'VABShop', 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, sku: ev.sku, qty: ev.qty, ref: ev.ref, views: ev.views,
usdCents: ev.usdCents, weiPaid: ev.weiPaid, levelsPaid: ev.levelsPaid, companyPaid: ev.companyPaid, sponsor: ev.sponsor || null, delivered: 0 };
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, ev.views + ' views', rec.adId ? 'for ad #' + rec.adId : '(no ad yet)');
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(), views: Number(d.views), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString(), levelsPaid: Number(d.levelsPaid), companyPaid: d.companyPaid.toString() };
}
// the split of one order from its receipt: level payouts (with their place in the line), 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 Boosts 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;
}
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.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, boosts: list.reduce((t, x) => t + (Number(x.qty) || 1), 0), orders: list.length,
viewsSold: list.reduce((t, x) => t + (x.views || 0), 0), noAd: list.filter(x => !x.adId).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 };