// 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 / VBB pattern.
// - ledger(): every Boost (from the Purchase events shop.js recorded) with its split read from the receipt: each level paid
// (with the person's place in the buyer's line), who was passed over, the company, and Boost delivery (views delivered so far).
// - contract(): live facts for /contract (owner, company, keeper, paused, orders, what it holds), cached 5 minutes.
// - Telegram: one photo card per Boost (a prebuilt ViralAdBlitz proof image, rotated, the buyer, every level paid in that same
// transaction with its POL, this week's numbers and the verify link) in the payments topic (TG_CHAT / TG_PAY_TOPIC, the CTB
// Rewards bot TG_TOKEN, same as Downline Banners and VBB). Once per transaction across app copies (in-process guard +
// docstore.claim), never anything older than 2 hours. Off unless TG_TOKEN and TG_CHAT are set. TG_API (tests) = a stand-in.
'use strict';
const store = require('./store');
const docstore = require('./docstore');
const SPLIT = { levelBps: 1000, levels: 5, denom: 10000 }; // VABShop LEVEL_BPS / LEVELS (constants in the contract)
const CARDS = ['/art/proof/vab-proof-royal.png', '/art/proof/vab-proof-daylight.png', '/art/proof/vab-proof-navy.png']; // rotated per post
const st = { posted: 0, skipped: 0, failed: 0, lastError: null };
let C = null, shop = null, wire = null, names = null;
const sent = new Set();
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; wire = deps.wire; 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 local = nameLocal(addr); if (local) return local; if (names) { try { const n = await names(lc(addr)); 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 => ({ '&': '&', '<': '<', '>': '>' }[c]));
const what = x => (Number(x.qty) > 1 ? x.qty + ' Boosts' : 'a Boost') + ' (' + Number(x.views || 0).toLocaleString('en-US') + ' guaranteed views)';
// the split of one Boost: from the receipt when read, else from the Purchase event (levels paid x 10%, the rest company; who
// got each level is then unknown until the receipt is read)
function split(x) {
if (Array.isArray(x.pays) && x.pays.length) return x.pays;
let paid = 0n; try { paid = BigInt(x.weiPaid || 0); } catch (e) {}
const share = paid * BigInt(SPLIT.levelBps) / BigInt(SPLIT.denom); const out = [];
for (let i = 1; i <= Number(x.levelsPaid || 0); i++) out.push({ level: i, depth: null, to: null, wei: share.toString() });
out.push({ level: 0, depth: 0, to: lc(C.companyWallet), wei: x.companyPaid != null ? String(x.companyPaid) : (paid - share * BigInt(x.levelsPaid || 0)).toString() });
return out;
}
// ---- public ledger ----
function rows() { return Object.entries((store.state() && store.state().purchases) || {}).map(([k, x]) => Object.assign({ key: k, tx: k.split(':')[0] }, x)); }
function ledger(n) {
const lim = Math.min(200, Math.max(1, Number(n) || 50));
const list = rows().map(x => {
const dv = wire ? wire.boostView(x) : null; const a = x.adId ? store.ad(x.adId) : null;
return { kind: 'boost', 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), qty: x.qty,
usdCents: x.usdCents, weiPaid: x.weiPaid, ad: a ? { id: a.id, headline: a.headline } : null,
pays: split(x).map(p => ({ level: p.level, depth: p.depth, to: p.to, name: p.to ? nameLocal(p.to) : null, wei: p.wei, failed: p.failed || undefined })),
passedOver: (x.over || []).map(o => ({ depth: o.depth, name: nameLocal(o.who) || null, who: o.who })),
delivery: dv ? { views: dv.views, delivered: dv.delivered, status: dv.status } : null };
}).sort((a, b) => (b.at || 0) - (a.at || 0));
let wei = 0n, levels = 0n, cents = 0, boosts = 0;
for (const x of rows()) { boosts += Number(x.qty) || 1; cents += Number(x.usdCents) || 0; try { wei += BigInt(x.weiPaid || 0); levels += BigInt(x.weiPaid || 0) - BigInt(x.companyPaid || 0); } catch (e) {} }
return { contract: C.contractAddress || null, explorer: C.explorer, items: list.slice(0, lim), totals: { boosts, orders: list.length, usdCents: cents, weiPaid: wei.toString(), levelsWei: levels.toString() } };
}
// ---- 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: { levels: 5, levelPct: 10, companyPct: 50, maxDepth: 20 },
boost: { usd: C.boost.usd, views: C.boost.views }, verified: { sourcify: process.env.VERIFIED_SOURCIFY === '1', polygonscan: process.env.VERIFIED_POLYGONSCAN === '1' ? true : '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 { Interface } = require('ethers');
const I = new Interface(['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)']);
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, paused, totalOwed, orderCount, bal] = await Promise.all(['owner', 'company', 'keeper', '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), 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 };
if (v.error) cCache.at = Date.now() - 240000;
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;
}
function weekLine() {
const w = wire.weekStats();
return '\u{1F4CA} This week: ' + w.boosts + ' Boost' + (w.boosts === 1 ? '' : 's') + ' · ' + w.adsLive + ' ads live · ' + w.vclicks + ' verified click' + (w.vclicks === 1 ? '' : 's');
}
async function caption(x) {
const lines = ['\u{1F4F0} ViralAdBlitz', '\u{26A1} ' + esc(who(x.buyer, await nameOf(x.buyer))) + ' boosted ' + (x.adId && store.ad(x.adId) ? '"' + esc(store.ad(x.adId).headline) + '"' : 'a text ad') + ': ' + esc(what(x)) + ' · ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL)'];
const s = split(x); let levels = 0;
for (const p of s) {
if (p.level === 0) { lines.push('\u{1F3E6} ViralAdBlitz: ' + pol(p.wei) + ' POL'); continue; }
levels++;
const where = p.depth && p.depth !== p.level ? ' (place ' + p.depth + ' in the line)' : '';
if (p.failed) lines.push('⚠️ Level ' + p.level + ' payment to ' + esc(who(p.to, await nameOf(p.to))) + ' bounced; it waits in the contract for them to claim');
else lines.push('\u{1F4B8} Level ' + p.level + ' 10%: ' + pol(p.wei) + ' POL → ' + (p.to ? esc(who(p.to, await nameOf(p.to))) : 'sponsor') + where);
}
if (levels === 0) lines.push('Nobody in this line has boosted yet, so the level shares went to ViralAdBlitz.');
if ((x.over || []).length) lines.push(x.over.length === 1 ? '1 person in the line had not boosted yet and was passed over; their share went up the line.' : x.over.length + ' people in the line had not boosted yet and were passed over; their shares went up the line.');
lines.push('Paid by the contract in this same transaction. It keeps nothing and there is nothing to withdraw.');
lines.push(weekLine());
lines.push('· Verify on Polygonscan · Live ledger');
return lines.join('\n');
}
let card = 0;
// shop.js calls this once per newly recorded Boost (rec = the stored purchase, tx = its transaction)
function onPurchase(rec, tx) {
const x = Object.assign({ tx }, rec);
(async () => {
try {
const sp = await shop.readSplit(tx, rec.orderId);
if (sp) { const S = store.state(); const k = Object.keys(S.purchases || {}).find(k2 => k2.startsWith(lc(tx) + ':') && S.purchases[k2].orderId === rec.orderId);
if (k) { Object.assign(S.purchases[k], { pays: sp.pays, over: sp.over, bound: sp.bound }); store.save(); } Object.assign(x, { pays: sp.pays, over: sp.over }); }
} 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('vabtg:' + lc(tx) + ':' + rec.orderId))) return; // never the same Boost twice
const pick = CARDS[card++ % CARDS.length];
const photo = (process.env.TG_PHOTO_BASE ? String(process.env.TG_PHOTO_BASE).replace(/\/+$/, '') : 'https://' + C.site) + pick;
let ok = await tg('sendPhoto', { photo, caption: text });
if (!ok) ok = await tg('sendMessage', { text, disable_web_page_preview: true });
if (ok) { st.posted++; console.log('proof: posted Boost', String(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, caption, split, view, on, CARDS };