Files
viraladblitz/wire.js
T
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

153 lines
11 KiB
JavaScript

// The engine: verified visitors, verified ad views, verified clicks, Boost delivery and what each page shows.
// - A page load gets a ticket listing the ads it showed (server side, never what the browser claims). After the page has been
// visible visitSeconds the browser redeems it: the visitor is verified (bots, early sends, the per-IP cap filtered, the VBB
// rules) and each ad shown gets one verified view, once per visitor per ad per 24 h. The ad owner's own views never count.
// - A Boost (the chain's Purchase event, shop.js) guarantees `views` verified views for one text ad. Its views are counted here
// and every one is kept as a row (vab_bviews: the delivery audit trail). Several Boosts on one ad fill oldest first.
// - Where Boost views come from: every ViralAdBlitz page (the ticker on every page, the "Top ads" board, member pages, whose
// Boosted places pick the Boosts furthest behind first). A Boost not delivered on-site within deliverDays (30) is finished
// through Network Ad Space as a text ad (vabnas.js); NAS impressions count toward the same guarantee.
// - Verified click: /go/<ad> with the visitor's verified token (issued when their visit verified), once per visitor per ad per
// 24 h, never the owner's own. The "Top ads this week" board ranks by verified clicks (Central-time week).
'use strict';
const crypto = require('crypto');
const cfgMod = require('./config');
const store = require('./store');
const C = () => cfgMod.get();
const H24 = 24 * 3600000;
let nasServed = () => 0; // vabnas.js: NAS impressions served for a Boost (by purchase key)
function init(o) { if (o && o.nasServed) nasServed = o.nasServed; rebuild(); }
// ---- indexes (rebuilt from rows at boot) ----
const lastVisitByVk = new Map(), ipVks = new Map(), viewSeen = new Map(), bviewSeen = new Map(), clickSeen = new Map();
function rebuild() {
lastVisitByVk.clear(); ipVks.clear(); bviewSeen.clear(); clickSeen.clear();
const cut = Date.now() - H24;
for (const v of store.visits()) if (v.at >= cut) { lastVisitByVk.set(v.vk, v.at); ipAdd(v.iph, v.vk, v.at); }
for (const b of store.bviews()) if (b.at >= cut) bviewSeen.set(b.vk + '|' + b.adId, b.at);
for (const c of store.clicks()) if (c.at >= cut && c.verified) clickSeen.set(c.vk + '|' + c.adId, c.at);
}
function ipAdd(iph, vk, at) { let m = ipVks.get(iph); if (!m) ipVks.set(iph, m = new Map()); m.set(vk, at); }
const fresh = (m, k) => { const t = m.get(k); return t && Date.now() - t < H24; };
// ---- Boosts ----
function purchases() { return Object.entries(store.state().purchases || {}).map(([key, x]) => Object.assign({ key }, x)); }
const delivered = b => (b.delivered || 0) + (nasServed(b.key) || 0);
const remaining = b => Math.max(0, (b.views || 0) - delivered(b));
function boostsOf(adId) { return purchases().filter(b => b.adId === Number(adId)).sort((a, b) => (a.at || 0) - (b.at || 0)); }
function activeBoost(adId) { return boostsOf(adId).find(b => remaining(b) > 0) || null; }
function activeBoosts() { const out = []; for (const b of purchases()) if (b.adId && remaining(b) > 0) { const a = store.ad(b.adId); if (a && a.status === 'live') out.push(b); } return out.sort((a, b) => (a.at || 0) - (b.at || 0)); }
function boostedAdIds() { return new Set(activeBoosts().map(b => b.adId)); }
// a newly credited Boost: which ad it is for (the ad named in `ref` if the buyer owns it, else the buyer's live ad; none = attached
// when they post one, see attachPending)
function attach(rec) {
const a = store.ad(Number(rec.ref)); const own = a && a.owner === rec.buyer && a.status !== 'removed' ? a : store.adOf(rec.buyer);
rec.adId = own ? own.id : null; rec.delivered = rec.delivered || 0; rec.dueAt = (rec.blockAt ? rec.blockAt * 1000 : rec.at) + C().deliverDays * 86400000;
return rec.adId;
}
function attachPending(owner, adId) {
let n = 0; for (const x of Object.values(store.state().purchases || {})) if (x.buyer === owner && !x.adId) { x.adId = adId; n++; }
if (n) store.save(); return n;
}
function boostView(b) {
const nas = nasServed(b.key) || 0;
return { key: b.key, tx: String(b.key).split(':')[0], orderId: b.orderId, at: (b.blockAt ? b.blockAt * 1000 : b.at) || null, adId: b.adId || null, qty: b.qty, views: b.views,
onSite: b.delivered || 0, nas, delivered: delivered(b), remaining: remaining(b), dueAt: b.dueAt || null, finishedAt: b.finishedAt || null,
status: remaining(b) === 0 ? 'delivered' : !b.adId ? 'waiting-for-ad' : (b.dueAt && Date.now() > b.dueAt ? 'finishing-in-network' : 'delivering') };
}
// pick k Boosted ads for limited places: furthest behind first (delivered share, then oldest), a little shuffle among the
// first 3k so two pages loaded together do not show the same ones
function pickBoosted(k, exclude) {
if (k <= 0) return [];
const ex = exclude || new Set(); const seen = new Set(); const list = [];
for (const b of activeBoosts()) { if (ex.has(b.adId) || seen.has(b.adId)) continue; seen.add(b.adId); list.push(b); }
list.sort((a, b) => delivered(a) / a.views - delivered(b) / b.views || (a.at || 0) - (b.at || 0));
const pool = list.slice(0, k * 3);
for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; }
return pool.slice(0, k).sort((a, b) => delivered(a) / a.views - delivered(b) / b.views).map(b => store.ad(b.adId)).filter(Boolean);
}
// ---- what pages show ----
function adCard(a, boosted) {
const m = store.member(a.owner);
return { id: a.id, headline: a.headline, line1: a.line1, line2: a.line2 || '', host: hostOf(a.link), href: '/go/' + a.id, owner: m && m.username ? '@' + m.username : short(a.owner), boosted: !!boosted };
}
const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : '';
const hostOf = l => { try { return new URL(l).hostname.replace(/^www\./, ''); } catch (e) { return ''; } };
// the live ticker on every page: Boosted ads (starred) woven between the newest ads
function ticker() {
const boosted = boostedAdIds();
const star = pickBoosted(C().tickerBoosts, null);
const starIds = new Set(star.map(a => a.id));
const newest = store.liveAds().slice().sort((a, b) => b.createdAt - a.createdAt).filter(a => !starIds.has(a.id)).slice(0, C().tickerNewest);
const out = []; let i = 0, j = 0;
while (i < star.length || j < newest.length) { if (i < star.length) out.push(adCard(star[i++], true)); if (j < newest.length) out.push(adCard(newest[j++], boosted.has(newest[j - 1].id))); if (j < newest.length) out.push(adCard(newest[j++], boosted.has(newest[j - 1].id))); }
return out;
}
// this week's verified clicks per ad (Central-time week). Ties: whoever reached the count first.
function board(week, n) {
const wk = week || store.ctWeek(); const per = new Map();
for (const c of store.clicks()) { if (!c.verified || c.wk !== wk) continue; const p = per.get(c.adId) || per.set(c.adId, { adId: c.adId, clicks: 0, lastAt: 0 }).get(c.adId); p.clicks++; if (c.at > p.lastAt) p.lastAt = c.at; }
const boosted = boostedAdIds();
const rows = [...per.values()].map(p => ({ p, a: store.ad(p.adId) })).filter(x => x.a && x.a.status === 'live')
.sort((x, y) => y.p.clicks - x.p.clicks || x.p.lastAt - y.p.lastAt).slice(0, n || C().boardSize);
return { week: wk, items: rows.map((x, i) => Object.assign(adCard(x.a, boosted.has(x.a.id)), { rank: i + 1, clicks: x.p.clicks })) };
}
function weekStats(week) {
const wk = week || store.ctWeek(); let vclicks = 0; for (const c of store.clicks()) if (c.verified && c.wk === wk) vclicks++;
let boosts = 0; for (const b of purchases()) if (store.ctWeek(b.blockAt ? b.blockAt * 1000 : b.at) === wk) boosts += Number(b.qty) || 1;
return { week: wk, boosts, vclicks, adsLive: store.liveAds().length };
}
// ---- verified visitors ----
// ok: a visitor already verified in the last 24 h, or a new one while the connection has fewer than perIpDay browsers
function canVisit(vk, iph) {
if (fresh(lastVisitByVk, vk)) return { ok: true, again: true };
const m = ipVks.get(iph); let n = 0; if (m) for (const [k, t] of m) { if (Date.now() - t < H24) n++; else m.delete(k); }
return n >= C().perIpDay ? { ok: false, why: 'ip' } : { ok: true };
}
// t = { vk, iph, page, ref, src, shown: [adId], viewer: address | null }. -> { verified, why?, views, boostViews }
function verify(t) {
const chk = canVisit(t.vk, t.iph); if (!chk.ok) return { verified: false, why: chk.why };
const now = Date.now(); const day = store.ctDay(now), wk = store.ctWeek(now);
if (!chk.again) { lastVisitByVk.set(t.vk, now); ipAdd(t.iph, t.vk, now); store.addVisit({ at: now, vk: t.vk, iph: t.iph, page: t.page, ref: t.ref || null, src: t.src || '', wk, day }); store.state().totals.visits++; store.bump('visits'); }
let views = 0, boostViews = 0;
for (const id of new Set(t.shown || [])) {
const a = store.ad(id); if (!a || a.status !== 'live' || (t.viewer && a.owner === t.viewer)) continue;
const k = t.vk + '|' + a.id;
if (!fresh(viewSeen, k)) { viewSeen.set(k, now); if (viewSeen.size > 300000) viewSeen.clear(); a.views = (a.views || 0) + 1; views++; store.saveAd(a); }
const b = activeBoost(a.id);
if (b && !fresh(bviewSeen, k)) {
bviewSeen.set(k, now); const rec = store.state().purchases[b.key];
rec.delivered = (rec.delivered || 0) + 1; if (remaining(Object.assign({ key: b.key }, rec)) === 0 && !rec.finishedAt) rec.finishedAt = now;
store.addBview({ at: now, vk: t.vk, adId: a.id, boost: b.key, page: t.page, day }); boostViews++;
}
}
if (views) { store.state().totals.views += views; store.bump('views', views); }
if (boostViews) { store.state().totals.boostViews += boostViews; store.bump('boostViews', boostViews); }
store.save();
return { verified: true, views, boostViews };
}
// a click on /go/<ad>. verifiedVisitor = the visitor's token checked out. -> { verified }
function click(a, vk, verifiedVisitor, viewer, placement) {
a.clicks = (a.clicks || 0) + 1; store.state().totals.clicks++; store.bump('clicks');
let verified = false;
if (verifiedVisitor && fresh(lastVisitByVk, vk) && !(viewer && viewer === a.owner)) {
const k = vk + '|' + a.id;
if (!fresh(clickSeen, k)) {
clickSeen.set(k, Date.now()); verified = true; a.vclicks = (a.vclicks || 0) + 1; store.state().totals.vclicks++; store.bump('vclicks');
store.addClick({ vk, adId: a.id, verified: true, p: String(placement || '').slice(0, 20), wk: store.ctWeek(), day: store.ctDay() });
}
}
store.saveAd(a); return { verified };
}
// the visitor's verified token (HMAC of the visitor key + the day): sent with clicks after their visit verified
let SECRET = crypto.randomBytes(16).toString('hex');
function setSecret(s) { SECRET = String(s); }
const vtoken = vk => crypto.createHmac('sha256', SECRET).update('vt|' + vk + '|' + store.ctDay()).digest('hex').slice(0, 24);
const vtokenOk = (vk, t) => typeof t === 'string' && t.length === 24 && crypto.timingSafeEqual(Buffer.from(t), Buffer.from(vtoken(vk)));
module.exports = { init, rebuild, purchases, activeBoost, activeBoosts, boostsOf, attach, attachPending, boostView, pickBoosted, adCard, ticker, board, weekStats,
canVisit, verify, click, vtoken, vtokenOk, setSecret, remaining, delivered, hostOf };