Files
vbb/proof.js
T
martbost 2fe3d9e4c0 Trust pack (Marty 2026-11-14): contract proof, live ledger, proof toasts, Telegram sale cards, legal pages, network footer.
- proof.js: /api/ledger (each VBBShop purchase with its split read from the receipt's Paid/PaymentFailed events, else the contract's fixed 30/10/60 math; weekly prize transfers with their transactions), /api/contract (owner, prize wallet, company, keeper, paused, orders, balance and owed, read live and cached 5 min; Sourcify exact match, Polygonscan pending).
- Telegram (CTB Rewards bot, payments topic, TG_TOKEN/TG_CHAT/TG_PAY_TOPIC same as Downline Banners): one photo card per purchase (prebuilt VBB proof image rotated, buyer, sponsor/prize/company split in POL, this week's purchases + prize pot, Polygonscan + ledger links) and one line per confirmed prize payout. Hooks: shop.setHook (newly credited purchases only) and prize.setHook (confirmed transfers); once per tx via an in-process guard plus docstore.claim; nothing older than 2 hours.
- Pages /contract, /ledger, /terms, /disclaimer (Earnings Disclaimer), /privacy (TrustClickz, real mechanics: advertising not income, same-transaction split, prize wallet holds the 10% until Monday, no refunds on-chain, one-time purchases, crypto risk, data incl. hashed visit checks and the network hub); sitemap.
- Footer: Terms, Earnings Disclaimer, Privacy, Contract, Ledger, Support, company line, 'Part of the network' from the hub (netsites.js, /api/network-sites, fallback list), VBB marked current. Toasts add purchases and prize payouts.
- tools/proof-art.mjs renders public/art/proof/vbb-proof-{pink,blue,yellow}.png. common.js?v=5, vbb.css?v=6.
chain.mjs 49/49 (real contract on anvil + stand-in Telegram: exact split, 2 cards, no repost on rescans, 6 prize lines). smoke 241/241.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:38:40 -06:00

185 lines
14 KiB
JavaScript

// Trust pack (Marty 2026-11-14: "all these sites need to show their live ledger and the contract for proof and trust, and toast
// notifications ... post a Telegram with some kind of image and stats, and payment notifications"). The Downline Banners pattern.
// - ledger(): every VBBShop purchase (from the Purchase events shop.js credited) with its split, and every weekly prize transfer,
// newest first, each with its transaction. Public, read by /ledger and the toasts.
// - contract(): the live contract facts for /contract (owner, prize wallet, company, keeper, paused, what it holds), read from the
// chain and cached 5 minutes; the split constants are the contract's own (30 / 10 / 60).
// - Telegram: one photo card per purchase (a prebuilt VBB proof image, rotated, + who bought what, the split paid in that same
// transaction, this week's numbers and the verify link) and one line per confirmed prize payout, in the group's payments topic
// (TG_CHAT / TG_PAY_TOPIC, the CTB Rewards bot TG_TOKEN, same as Downline Banners and the games). Sent once per transaction
// across app copies (docstore.claim). Never posts anything older than 2 hours (a re-index after downtime must not flood the
// topic). Off unless TG_TOKEN and TG_CHAT are set. TG_API (tests only) points at a stand-in.
'use strict';
const store = require('./store');
const docstore = require('./docstore');
const SPLIT = { sponsorBps: 3000, prizeBps: 1000, denom: 10000 }; // VBBShop SPONSOR_BPS / PRIZE_BPS (constants in the contract)
const ZERO = '0x0000000000000000000000000000000000000000';
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
// Paid(uint256 indexed id, address indexed to, uint256 amount, uint8 role) / PaymentFailed(same): read from the purchase receipt
const { Interface } = require('ethers');
const EV = new Interface(['event Paid(uint256 indexed id, address indexed to, uint256 amount, uint8 role)', 'event PaymentFailed(uint256 indexed id, address indexed to, uint256 amount, uint8 role)']);
const T_PAID = EV.getEvent('Paid').topicHash, T_FAIL = EV.getEvent('PaymentFailed').topicHash;
const ROLE = ['sponsor', 'prize', 'company'];
const CARDS = ['/art/proof/vbb-proof-pink.png', '/art/proof/vbb-proof-blue.png', '/art/proof/vbb-proof-yellow.png']; // rotated per post
const st = { posted: 0, prizeLines: 0, skipped: 0, failed: 0, lastError: null };
let C = null, shop = null, prize = null, names = null;
const sent = new Set(); // this copy's own guard (docstore.claim covers app copies; without MySQL it always says yes)
const once = k => { if (sent.has(k)) return false; sent.add(k); if (sent.size > 5000) sent.clear(); return true; };
function init(cfg, deps) { C = cfg; shop = deps.shop; prize = deps.prize; names = deps.nameOf || null; }
const on = () => !!(process.env.TG_TOKEN && process.env.TG_CHAT);
const lc = a => String(a || '').toLowerCase();
const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : '';
function nameLocal(addr) { const m = store.member(lc(addr)); return m && m.username ? m.username : null; }
async function nameOf(addr) {
const a = lc(addr); const local = nameLocal(a); if (local) return local;
if (names) { try { const n = await names(a); if (n) return n; } catch (e) {} }
return null;
}
const who = (addr, name) => name ? '@' + name : short(lc(addr));
const pol = wei => { const v = Number(BigInt(wei || 0) / 10n ** 12n) / 1e6; return v >= 100 ? v.toFixed(2) : v.toFixed(4); };
const usd = cents => '$' + (Number(cents || 0) / 100).toFixed(2);
const esc = s => String(s == null ? '' : s).replace(/[&<>]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
// what a purchase bought, in words (SKUs from config: packs and the banner look)
function what(x) {
if (x.credits > 0) return x.credits + ' post credits';
if (Number(x.sku) === Number(C.lookSku)) return 'the banner look';
return 'package #' + x.sku;
}
// the split of one purchase. From the receipt's Paid / PaymentFailed events when read, else from the contract's fixed math
// (sponsorPaid from the Purchase event, prize = 10% of the price paid, company = the rest).
function split(x) {
if (Array.isArray(x.pays) && x.pays.length) return x.pays;
let paid = 0n, sp = 0n; try { paid = BigInt(x.weiPaid || 0); sp = BigInt(x.sponsorPaid || 0); } catch (e) {}
const prizeWei = paid * BigInt(SPLIT.prizeBps) / BigInt(SPLIT.denom);
const out = [];
if (x.sponsor && x.sponsor !== ZERO && sp > 0n) out.push({ role: 'sponsor', to: lc(x.sponsor), wei: sp.toString() });
out.push({ role: 'prize', to: lc(C.prizePot.wallet), wei: prizeWei.toString() });
out.push({ role: 'company', to: null, wei: (paid - sp - prizeWei).toString() });
return out;
}
// the Paid / PaymentFailed events of one purchase, from its receipt (null if the RPC does not answer)
async function readPays(tx, orderId) {
const r = await shop.rpc('eth_getTransactionReceipt', [tx]); if (!r || !Array.isArray(r.logs)) return null;
const out = [];
for (const l of r.logs) {
if (lc(l.address) !== lc(C.contractAddress) || (l.topics[0] !== T_PAID && l.topics[0] !== T_FAIL)) continue;
const d = EV.parseLog({ topics: l.topics, data: l.data }).args; if (Number(d.id) !== Number(orderId)) continue;
out.push({ role: ROLE[Number(d.role)] || 'role' + Number(d.role), to: lc(d.to), wei: d.amount.toString(), failed: l.topics[0] === T_FAIL || undefined });
}
return out.length ? out : null;
}
// ---- public ledger ----
function purchases() {
const P = (store.state() && store.state().purchases) || {};
return Object.entries(P).map(([k, x]) => Object.assign({ tx: k.split(':')[0] }, x));
}
function ledger(n) {
const lim = Math.min(200, Math.max(1, Number(n) || 50));
const rows = purchases().map(x => {
const s = split(x);
return { kind: 'purchase', tx: x.tx, at: (x.blockAt ? x.blockAt * 1000 : x.at) || null, orderId: x.orderId, buyer: x.buyer, buyerName: nameLocal(x.buyer), what: what(x),
usdCents: x.usdCents, weiPaid: x.weiPaid, pays: s.map(p => ({ role: p.role, to: p.to, name: p.to ? nameLocal(p.to) : null, wei: p.wei, failed: p.failed || undefined })) };
});
for (const wk of (prize && prize.history ? prize.history(52) : [])) for (const w of wk.winners) {
if (!w.tx) continue;
rows.push({ kind: 'prize', tx: w.tx, at: wk.paidAt || null, week: wk.week, board: w.board, place: w.place, name: w.name, usd: w.usd, pol: w.pol, confirmed: !!w.confirmed });
}
rows.sort((a, b) => (b.at || 0) - (a.at || 0));
const P = purchases(); let wei = 0n, cents = 0, sponsors = 0n;
for (const x of P) { try { wei += BigInt(x.weiPaid || 0); sponsors += BigInt(x.sponsorPaid || 0); } catch (e) {} cents += Number(x.usdCents) || 0; }
const prizesPaid = rows.filter(r => r.kind === 'prize' && r.confirmed).length;
return { contract: C.contractAddress || null, explorer: C.explorer, items: rows.slice(0, lim),
totals: { purchases: P.length, usdCents: cents, weiPaid: wei.toString(), sponsorWei: sponsors.toString(), prizePayouts: prizesPaid } };
}
// ---- contract facts (cached 5 minutes) ----
let cCache = null;
async function contract() {
if (cCache && Date.now() - cCache.at < 300000) return cCache.v;
const v = { address: C.contractAddress || null, chainId: C.chainId, explorer: C.explorer, split: { sponsorPct: 30, prizePct: 10, companyPct: 60 },
// Marty 2026-11-14: source verified on Sourcify (exact match, 2026-11-13); Polygonscan's own verification is pending
verified: { sourcify: true, polygonscan: 'pending', sourcifyUrl: C.contractAddress ? 'https://repo.sourcify.dev/' + C.chainId + '/' + C.contractAddress : null },
ownerNote: "Marty's Tangem hardware wallet", live: false };
if (shop && shop.watching()) {
const I = new Interface(['function owner() view returns (address)', 'function company() view returns (address)', 'function keeper() view returns (address)',
'function prizeWallet() view returns (address)', 'function paused() view returns (bool)', 'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)']);
const read = async fn => I.decodeFunctionResult(fn, await shop.rpc('eth_call', [{ to: C.contractAddress, data: I.encodeFunctionData(fn, []) }, 'latest']))[0];
try {
const [owner, company, keeper, prizeWallet, paused, totalOwed, orderCount, bal] = await Promise.all(['owner', 'company', 'keeper', 'prizeWallet', 'paused', 'totalOwed', 'orderCount'].map(read)
.concat([shop.rpc('eth_getBalance', [C.contractAddress, 'latest'])]));
Object.assign(v, { owner: lc(owner), company: lc(company), keeper: lc(keeper), prizeWallet: lc(prizeWallet), paused: !!paused, totalOwedWei: totalOwed.toString(),
orderCount: Number(orderCount), balanceWei: BigInt(bal).toString(), live: true, readAt: Date.now() });
} catch (e) { v.error = 'The chain did not answer just now. Try again in a minute.'; }
}
cCache = { at: Date.now(), v: v };
if (v.error) cCache.at = Date.now() - 240000; // retry sooner
return v;
}
// ---- Telegram ----
async function tg(method, body) {
const base = String(process.env.TG_API || 'https://api.telegram.org').replace(/\/+$/, '');
const b = Object.assign({ chat_id: process.env.TG_CHAT, parse_mode: 'HTML' }, body);
if (process.env.TG_PAY_TOPIC) b.message_thread_id = Number(process.env.TG_PAY_TOPIC);
const r = await fetch(base + '/bot' + process.env.TG_TOKEN + '/' + method, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(b), signal: AbortSignal.timeout(15000) });
const j = await r.json().catch(() => ({}));
if (!j.ok) { st.failed++; st.lastError = String(j.description || r.status).slice(0, 160); console.error('proof: telegram', method, 'failed', r.status, st.lastError); return false; }
return true;
}
// this week's numbers (Central-time week): purchases and dollars from the credited events, the prize pot the site already shows
function weekLine() {
const wk = store.ctWeek(); const s = shop.weekSales(wk, store.ctWeek); let potUsd = null;
try { potUsd = prize.pot(wk).potUsd; } catch (e) {}
return '\u{1F4CA} This week: ' + s.purchases + ' purchase' + (s.purchases === 1 ? '' : 's') + ', ' + usd(s.cents) + (potUsd != null ? ' · prize pot $' + Number(potUsd).toFixed(2) : '');
}
async function caption(x) {
const lines = ['\u{1F4A5} <b>Viral Banner Blitz</b>', '\u{1F9FE} ' + esc(who(x.buyer, await nameOf(x.buyer))) + ' bought ' + esc(what(x)) + ' · ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL)'];
for (const p of split(x)) {
if (p.failed) { lines.push('⚠️ ' + (p.role === 'sponsor' ? 'Sponsor' : p.role) + ' payment to ' + esc(who(p.to, await nameOf(p.to))) + ' bounced; it waits in the contract for them to claim'); continue; }
if (p.role === 'sponsor') lines.push('\u{1F4B8} Sponsor 30%: ' + pol(p.wei) + ' POL → ' + esc(who(p.to, await nameOf(p.to))));
else if (p.role === 'prize') lines.push('\u{1F3C6} Weekly prize pot 10%: ' + pol(p.wei) + ' POL');
else if (p.role === 'company') lines.push('\u{1F3E6} Viral Banner Blitz: ' + pol(p.wei) + ' POL');
}
lines.push('Split by the contract in this same transaction. The contract keeps nothing and there is nothing to withdraw.');
lines.push(weekLine());
lines.push('· <a href="' + esc(C.explorer) + '/tx/' + esc(x.tx) + '">Verify on Polygonscan</a> · <a href="https://' + esc(C.site) + '/ledger">Live ledger</a>');
return lines.join('\n');
}
let card = 0;
// shop.js calls this once per newly credited purchase (rec = the stored purchase, tx = its transaction)
function onPurchase(rec, tx) {
const x = Object.assign({ tx }, rec);
(async () => {
// the real split from the receipt (a bounced push shows as owed), kept on the purchase for the ledger
try { const pays = await readPays(tx, rec.orderId); if (pays) { const S = store.state(); const k = Object.keys(S.purchases || {}).find(k2 => k2.startsWith(lc(tx) + ':') && S.purchases[k2].orderId === rec.orderId); if (k) { S.purchases[k].pays = pays; store.save(); } x.pays = pays; } } catch (e) {}
if (!on()) return;
const at = (rec.blockAt ? rec.blockAt * 1000 : rec.at) || Date.now();
if (Date.now() - at > 2 * 3600000) { st.skipped++; return; }
const text = await caption(x);
if (!once('p:' + lc(tx) + ':' + rec.orderId) || !(await docstore.claim('vbbtg:' + lc(tx) + ':' + rec.orderId))) return; // another app copy already posted this purchase
const photo = 'https://' + C.site + CARDS[card++ % CARDS.length];
let ok = await tg('sendPhoto', { photo: process.env.TG_PHOTO_BASE ? String(process.env.TG_PHOTO_BASE).replace(/\/+$/, '') + CARDS[(card - 1) % CARDS.length] : photo, caption: text });
if (!ok) ok = await tg('sendMessage', { text, disable_web_page_preview: true }); // a photo the API cannot fetch still gets its proof line
if (ok) { st.posted++; console.log('proof: posted purchase', String(tx).slice(0, 12)); }
})().catch(e => { st.failed++; st.lastError = String(e.message).slice(0, 160); });
}
// prize.js calls this when a prize transfer confirms on chain
function onPrize(plan, t) {
if (!on() || !t || !t.tx) return;
(async () => {
if (t.sentAt && Date.now() - t.sentAt > 2 * 3600000) { st.skipped++; return; }
if (!once('z:' + lc(t.tx)) || !(await docstore.claim('vbbtg-prize:' + lc(t.tx)))) return;
const board = t.board === 'sources' ? 'most traffic sources' : 'most verified visitors';
const place = ['1st', '2nd', '3rd'][t.place - 1] || ('#' + t.place);
const text = '\u{1F3C6} <b>Viral Banner Blitz weekly prize</b>\n' + esc(t.name || short(t.address)) + ' · ' + place + ' place, ' + board + ' (week of ' + esc(plan.week) + '): '
+ esc(t.pol) + ' POL ($' + Number(t.usd).toFixed(2) + ')\n· <a href="' + esc(C.explorer) + '/tx/' + esc(t.tx) + '">Verify on Polygonscan</a> · <a href="https://' + esc(C.site) + '/ledger">Live ledger</a>';
if (await tg('sendMessage', { text, disable_web_page_preview: true })) { st.prizeLines++; console.log('proof: posted prize', String(t.tx).slice(0, 12)); }
})().catch(e => { st.failed++; st.lastError = String(e.message).slice(0, 160); });
}
function view() { return Object.assign({ telegram: on(), topic: process.env.TG_PAY_TOPIC || null }, st); }
module.exports = { init, ledger, contract, onPurchase, onPrize, caption, split, view, on, CARDS };