Files
Marty Bostick edaf98c8f6 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>
2026-11-16 09:19:34 -06:00

157 lines
10 KiB
JavaScript

// ViralAdSource data. One document (vas.json) holds members, sessions, Boost purchases (the chain's Purchase events), the watcher
// position, ad credits, daily counters and the reward nonces. The growing collections are row tables when the app runs on MySQL
// (docstore splits): text ads, reshares (the family tree), verified visits, verified clicks, sign-ups and the pending-rewards ledger.
// Without DOCSTORE_URL (local prototype + tests only) everything stays in the one file, written atomically.
// Marty's rule (2026-11-13): MySQL is the standard; never launch on files.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const cfgMod = require('./config');
const docstore = require('./docstore');
const DOC = 'vas.json';
const SPLITS = [
{ doc: DOC, field: 'ads', table: 'vas_ads', key: 'id', ts: 'createdAt' },
{ doc: DOC, field: 'shares', table: 'vas_shares', key: 'id', ts: 'createdAt' },
{ doc: DOC, field: 'visits', table: 'vas_visits', key: 'id', ts: 'at' },
{ doc: DOC, field: 'clicks', table: 'vas_clicks', key: 'id', ts: 'at' },
{ doc: DOC, field: 'signups', table: 'vas_signups', key: 'id', ts: 'createdAt' },
{ doc: DOC, field: 'rewards', table: 'vas_rewards', key: 'id', ts: 'createdAt' }
];
const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s]));
let S = null, saveT = null, rowMode = false;
const adById = new Map(), adByOwner = new Map(), shareById = new Map(), shareByKey = new Map(), sharesByAd = new Map(), signupById = new Map(), rewardById = new Map();
const FILE = () => path.join(cfgMod.get().dataDir, DOC);
function index() {
adById.clear(); adByOwner.clear(); shareById.clear(); shareByKey.clear(); sharesByAd.clear(); signupById.clear(); rewardById.clear();
for (const a of S.ads) { adById.set(a.id, a); if (a.status !== 'removed') adByOwner.set(a.owner, a); }
for (const s of S.shares) indexShare(s);
for (const x of S.signups) signupById.set(x.id, x);
for (const r of S.rewards) rewardById.set(r.id, r);
}
function indexShare(s) { shareById.set(s.id, s); shareByKey.set(s.adId + '|' + s.owner, s); let l = sharesByAd.get(s.adId); if (!l) sharesByAd.set(s.adId, l = []); if (!l.includes(s)) l.push(s); }
function load() {
try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; }
S = Object.assign({ v: 1, seq: { ad: 0, visit: 0, click: 0, signup: 0, reward: 0 }, daily: {}, totals: { visits: 0, views: 0, vclicks: 0, clicks: 0, creditViews: 0 },
members: {}, sessions: {}, purchases: {}, shop: {}, credits: {}, rewardDays: {}, ads: [], shares: [], visits: [], clicks: [], signups: [], rewards: [] }, S || {});
rowMode = docstore.isOn();
if (rowMode) for (const sp of SPLITS) S[sp.field] = (docstore.rows(sp.table) || []).slice();
index();
const now = Date.now();
for (const [k, s] of Object.entries(S.sessions)) if (s.expires < now) delete S.sessions[k];
}
function save(now) {
if (saveT && !now) return;
const run = () => {
saveT = null;
try {
const out = rowMode ? Object.assign({}, S, Object.fromEntries(SPLITS.map(sp => [sp.field, []]))) : S;
const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 }); fs.renameSync(tmp, FILE());
} catch (e) { console.error('store save failed', e.message); }
};
if (now) { clearTimeout(saveT); run(); } else saveT = setTimeout(run, 800);
}
function flush() { save(true); }
const state = () => S;
function putRow(field, item) {
if (rowMode) { const sp = TABLE[field]; docstore.rowPut(sp.table, item[sp.key], item[sp.ts], item); }
save();
}
function dropRows(field, ids) {
if (!ids.length) return;
const set = new Set(ids); S[field] = S[field].filter(x => !set.has(x[TABLE[field].key]));
if (rowMode) docstore.rowDel(TABLE[field].table, ids);
save();
}
function nextId(kind) { S.seq[kind] = (S.seq[kind] || 0) + 1; return S.seq[kind]; }
// ---- Central time (Marty: everything on US Central) ----
const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
function ctDay(ts) { const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value])); return p.year + '-' + p.month + '-' + p.day; }
function ctWeek(ts) {
const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value]));
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0;
return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)).toISOString().slice(0, 10);
}
function bump(k, n) { const day = ctDay(); const d = S.daily[day] || (S.daily[day] = {}); d[k] = (d[k] || 0) + (n || 1); save(); }
function today() { return S.daily[ctDay()] || {}; }
// ---- text ads (one active ad per member) ----
function ad(id) { return adById.get(Number(id)) || null; }
function adOf(owner) { return adByOwner.get(String(owner || '').toLowerCase()) || null; }
function addAd(a) { a.id = nextId('ad'); a.createdAt = Date.now(); a.updatedAt = a.createdAt; S.ads.push(a); adById.set(a.id, a); adByOwner.set(a.owner, a); putRow('ads', a); return a; }
function saveAd(a) { a.updatedAt = Date.now(); if (a.status === 'removed') { if (adByOwner.get(a.owner) === a) adByOwner.delete(a.owner); } else adByOwner.set(a.owner, a); putRow('ads', a); }
function ads() { return S.ads; }
function liveAds() { return S.ads.filter(a => a.status === 'live'); }
// ---- reshares: one unique link per member per ad. code = the public id in /s/<code> ----
const newCode = () => { let c; do { c = crypto.randomBytes(6).toString('base64').replace(/[^a-zA-Z0-9]/g, '').slice(0, 8).toLowerCase(); } while (c.length < 8 || shareById.has(c)); return c; };
function share(code) { return shareById.get(String(code || '').toLowerCase()) || null; }
function shareOf(adId, owner) { return shareByKey.get(Number(adId) + '|' + String(owner || '').toLowerCase()) || null; }
function sharesOf(adId) { return sharesByAd.get(Number(adId)) || []; }
function sharesBy(owner) { const o = String(owner || '').toLowerCase(); return S.shares.filter(s => s.owner === o); }
function addShare(s) { s.id = newCode(); s.createdAt = Date.now(); Object.assign(s, { views: 0, clicks: 0, vclicks: 0, signups: 0, boosts: 0 }); S.shares.push(s); indexShare(s); putRow('shares', s); return s; }
function saveShare(s) { putRow('shares', s); }
// ---- verified visits / clicks ----
function addVisit(v) { v.id = 'v' + nextId('visit'); v.at = v.at || Date.now(); S.visits.push(v); putRow('visits', v); return v; }
function addClick(c) { c.id = 'k' + nextId('click'); c.at = c.at || Date.now(); S.clicks.push(c); putRow('clicks', c); return c; }
const visits = () => S.visits, clicks = () => S.clicks;
function prune() {
const now = Date.now(); let n = 0;
for (const [f, days] of [['visits', 15], ['clicks', 15]]) { const cut = now - days * 86400000; const old = S[f].filter(x => x.at < cut).map(x => x.id); dropRows(f, old); n += old.length; }
// unconfirmed sign-ups older than 7 days carry nothing: dropped
const cut = now - 7 * 86400000; const stale = S.signups.filter(x => x.status === 'unconfirmed' && x.createdAt < cut).map(x => x.id);
if (stale.length) { stale.forEach(id => signupById.delete(id)); dropRows('signups', stale); n += stale.length; }
return n;
}
// ---- sign-ups (L2) and the pending-rewards ledger ----
function addSignup(x) { x.id = 'u' + nextId('signup'); x.createdAt = Date.now(); S.signups.push(x); signupById.set(x.id, x); putRow('signups', x); return x; }
function saveSignup(x) { putRow('signups', x); }
function signup(id) { return signupById.get(String(id)) || null; }
function signups() { return S.signups; }
function addReward(r) { r.id = 'r' + nextId('reward'); r.createdAt = Date.now(); S.rewards.push(r); rewardById.set(r.id, r); putRow('rewards', r); return r; }
function saveReward(r) { putRow('rewards', r); }
function reward(id) { return rewardById.get(String(id)) || null; }
function rewards() { return S.rewards; }
// ---- ad credits (L3): { earned, spent, views (verified branch views counted so far) } per member ----
function credits(addr) { const a = String(addr || '').toLowerCase(); return S.credits[a] || (S.credits[a] = { earned: 0, spent: 0, views: 0 }); }
const creditBalance = addr => { const c = S.credits[String(addr || '').toLowerCase()]; return c ? Math.max(0, c.earned - c.spent) : 0; };
// ---- members ----
function member(addr) { return S.members[String(addr || '').toLowerCase()] || null; }
function upsertMember(addr, patch) {
const a = String(addr).toLowerCase();
const m = S.members[a] || (S.members[a] = { address: a, username: null, joinedAt: Date.now(), via: null, netOk: false });
Object.assign(m, patch || {}); m.lastSeen = Date.now(); save(); return m;
}
function memberByName(name) {
const n = String(name || '').toLowerCase(); if (!n) return null;
for (const m of Object.values(S.members)) if (m.username && m.username.toLowerCase() === n) return m;
return null;
}
function members() { return Object.values(S.members); }
// the device / connection keys a member has been seen on (the L2 "not the resharer's own device or IP" check): last 50 of each
function seenOn(addr, vk, iph) {
const m = member(addr); if (!m) return;
const add = (k, v) => { if (!v) return; const l = m[k] || (m[k] = []); const i = l.indexOf(v); if (i >= 0) l.splice(i, 1); l.push(v); if (l.length > 50) l.shift(); };
add('vks', vk); add('iphs', iph); save();
}
// ---- sessions ----
const SESSION_TTL = 7 * 24 * 3600000;
function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: address.toLowerCase(), expires: Date.now() + SESSION_TTL }; save(); return token; }
function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; }
function dropSession(token) { delete S.sessions[token]; save(); }
function endSessions(match, before) { let n = 0; for (const [k, x] of Object.entries(S.sessions)) if (x.expires - SESSION_TTL <= before && match(x)) { delete S.sessions[k]; n++; } if (n) save(); return n; }
module.exports = { SPLITS, load, flush, save, state, ctDay, ctWeek, bump, today, ad, adOf, addAd, saveAd, ads, liveAds,
share, shareOf, sharesOf, sharesBy, addShare, saveShare, addVisit, addClick, visits, clicks, prune,
addSignup, saveSignup, signup, signups, addReward, saveReward, reward, rewards, credits, creditBalance,
member, upsertMember, memberByName, members, seenOn, mintSession, session, dropSession, endSessions, SESSION_TTL };