ViralAdSource app (Marty approved 2026-11-16): free text ads that spread by reshares, each ad with its own family tree

Watershed look from the approved mockup (hero, topo pattern, icons). Network sign-in through the hub, hub membership, activity ping.
Reshare links per member per ad with branch/step tracking; family-tree dashboard (branch, step, reshares, views, clicks, sign-ups, Boosts).
Verified views earn ad credits for the branch's resharer (L3). L2 sign-up pipeline (hub-new, confirmed email, not self device/IP,
throwaway block, daily cap, fraud score) with keeper-signed reward vouchers and a pending-rewards ledger; payouts OFF (REWARD_PAYOUTS).
L1 Boosts through VASShop with signed orders naming the sponsor line and the resharer. Trust pack, chatbot, promo kit, PolHunter embed.
All numbers are PROPOSALS until Marty sets them. qa/e2e.mjs 59/59 on a local anvil chain, chatbot test 108/108.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Marty Bostick
2026-11-16 09:19:34 -06:00
commit edaf98c8f6
103 changed files with 6229 additions and 0 deletions
+121
View File
@@ -0,0 +1,121 @@
// Trust pack (Marty 2026-11-14, standing for every network site): live ledger, contract proof, toasts, a Telegram photo card per sale.
// - ledger(): every Boost (the Purchase events shop.js recorded) with its split read from the receipt: the resharer's cut (kind 6),
// each sponsor level (kinds 1..5, with the person's place in the line), who was passed over, the reward pot slice and the company;
// plus the sign-up rewards ledger (signup.js publicRows: name, amount, status, tx; never an email).
// - contract(): live facts for /contract (owner, company, keeper, paused, split, pot, reward rules), cached 5 minutes.
// - Telegram: one photo card per Boost to TG_CHAT / TG_PAY_TOPIC (off unless TG_TOKEN and TG_CHAT are set; staging leaves them empty).
'use strict';
const store = require('./store');
const docstore = require('./docstore');
const CARDS = ['/art/proof/vas-proof-river.png', '/art/proof/vas-proof-ink.png'];
const st = { posted: 0, skipped: 0, failed: 0, lastError: null };
let C = null, shop = null, wire = null, signup = 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; signup = deps.signup; }
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; }
const who = a => nameLocal(a) ? '@' + nameLocal(a) : short(lc(a));
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]));
const KIND = k => k === 0 ? 'company' : k === 6 ? 'resharer' : 'level ' + k;
// the split of one Boost: from its receipt when read, else from the Purchase event totals
function split(x) {
if (Array.isArray(x.pays) && x.pays.length) return x.pays;
const out = [];
if (x.resharer && x.resharerPaid && x.resharerPaid !== '0') out.push({ kind: 6, depth: 0, to: x.resharer, wei: x.resharerPaid });
out.push({ kind: 0, depth: 0, to: lc(C.companyWallet), wei: String(x.companyPaid || '0') });
return out;
}
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 a = x.adId ? store.ad(x.adId) : null; const dv = wire.boostView(x);
let levelsWei = 0n; for (const p of split(x)) if (p.kind >= 1 && p.kind <= 5) { try { levelsWei += BigInt(p.wei); } catch (e) {} }
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), qty: x.qty, days: dv.days,
usdCents: x.usdCents, weiPaid: x.weiPaid, potWei: x.potAdded || '0', ad: a ? { id: a.id, headline: a.headline } : null,
resharer: x.resharer ? { to: x.resharer, name: nameLocal(x.resharer), wei: x.resharerPaid } : null,
pays: split(x).map(p => ({ kind: p.kind, label: KIND(p.kind), 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 })) };
}).sort((a, b) => (b.at || 0) - (a.at || 0));
let wei = 0n, pot = 0n, resh = 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); pot += BigInt(x.potAdded || 0); resh += BigInt(x.resharerPaid || 0); } catch (e) {} }
const rw = signup ? signup.publicRows(lim) : [];
return { contract: C.contractAddress || null, explorer: C.explorer, items: list.slice(0, lim), rewards: rw.map(r => Object.assign(r, { to: short(r.to) })),
payoutsOn: C.reward.payouts, totals: { boosts, orders: list.length, usdCents: cents, weiPaid: wei.toString(), potWei: pot.toString(), resharerWei: resh.toString() } };
}
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, proposal: true,
split: { resharerBps: C.split.resharerBps, potBps: C.split.potBps, levelBps: C.split.levelBps, maxDepth: C.split.maxDepth },
reward: { cents: C.reward.cents, dailyCap: C.reward.dailyCap, payouts: C.reward.payouts }, boost: { usd: C.boost.usd, days: C.boost.days },
verified: { sourcify: process.env.VERIFIED_SOURCIFY === '1', polygonscan: process.env.VERIFIED_POLYGONSCAN === '1' }, ownerNote: "Marty's Tangem hardware wallet", live: false };
if (shop && shop.watching()) {
try {
const one = f => shop.call(f).then(r => r[0]);
const [owner, company, keeper, paused, totalOwed, orderCount, potBalance, potFunded, potPaid] = await Promise.all(['owner', 'company', 'keeper', 'paused', 'totalOwed', 'orderCount', 'potBalance', 'potFunded', 'potPaid'].map(one));
const r = await shop.liveRules();
Object.assign(v, { owner: lc(owner), company: lc(company), keeper: lc(keeper), paused: !!paused, totalOwedWei: totalOwed.toString(), orderCount: Number(orderCount),
pot: { balanceWei: potBalance.toString(), fundedWei: potFunded.toString(), paidWei: potPaid.toString() }, live: true, proposal: false, readAt: Date.now() });
if (r) { v.split = { resharerBps: r.resharerBps, potBps: r.potBps, levelBps: r.levelBps, maxDepth: 20 }; v.reward.maxCents = r.rewardMaxCents; v.reward.chainDailyCap = r.rewardDailyCap; }
} 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;
}
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); return false; }
return true;
}
function caption(x) {
const w = wire.weekStats(); const a = x.adId ? store.ad(x.adId) : null;
const lines = ['\u{1F30A} <b>ViralAdSource</b>', '\u{26A1} ' + esc(who(x.buyer)) + ' boosted ' + (a ? '"' + esc(a.headline) + '"' : 'a text ad') + ' · ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL)'];
for (const p of split(x)) {
if (p.kind === 0) lines.push('\u{1F3E6} ViralAdSource: ' + pol(p.wei) + ' POL');
else if (p.kind === 6) lines.push('\u{1F33F} Resharer ' + esc(who(p.to)) + ': ' + pol(p.wei) + ' POL (the branch that sold it)');
else lines.push((p.failed ? '⚠️ ' : '\u{1F4B8} ') + 'Level ' + p.kind + ': ' + pol(p.wei) + ' POL → ' + esc(who(p.to)) + (p.failed ? ' (bounced, waits in the contract to claim)' : ''));
}
if (x.potAdded && x.potAdded !== '0') lines.push('\u{1F4A7} Reward pot: +' + pol(x.potAdded) + ' POL');
lines.push('Paid by the contract in this same transaction.');
lines.push('\u{1F4CA} This week: ' + w.boosts + ' Boosts · ' + w.reshares + ' reshares · ' + w.vclicks + ' verified clicks');
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;
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 }); store.save(); } Object.assign(x, { pays: sp.pays, over: sp.over }); }
// the branch that sold it
if (rec.resharer) { const S = store.state(); const ov = (S.orderVia || {})[rec.buyer]; const s = ov ? store.share(ov.code) : null;
if (s && s.owner === rec.resharer) { s.boosts = (s.boosts || 0) + (Number(rec.qty) || 1); store.saveShare(s); rec.share = s.id; store.save(); } }
} 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; }
if (!once('p:' + lc(tx) + ':' + rec.orderId) || !(await docstore.claim('vastg:' + lc(tx) + ':' + rec.orderId))) return;
const photo = (process.env.TG_PHOTO_BASE ? String(process.env.TG_PHOTO_BASE).replace(/\/+$/, '') : 'https://' + C.site) + CARDS[card++ % CARDS.length];
const text = caption(x);
let ok = await tg('sendPhoto', { photo, caption: text }); if (!ok) ok = await tg('sendMessage', { text, disable_web_page_preview: true });
if (ok) st.posted++;
})().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 };