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>
This commit is contained in:
Marty Bostick
2026-11-14 13:52:03 -06:00
commit 001878bdae
79 changed files with 4813 additions and 0 deletions
+136
View File
@@ -0,0 +1,136 @@
// ViralAdBlitz real-contract test on a local anvil chain (no fork, nothing leaves this machine, no real POL).
// Deploys the real VABShop (../contracts/out) with a mock Chainlink feed at $0.25, boots the app against it with a stand-in hub
// (line: B -> A1 -> A2 -> A3) and a stand-in Telegram API, and checks through the app's own order flow:
// 1. A3 (top, no line) boosts: nothing qualifies, 100% to the company.
// 2. A1 boosts with a voucher binding [A2, A3]: A2 never boosted and is passed over, A3 gets level 1 at place 2; company 90%.
// 3. B boosts 2 with the app's 1% overpay: the voucher binds B -> A1 and stops (A1 already bound); A1 level 1, A3 level 2;
// company 80%; the overpay comes back in the same transaction (buyer spent = price + gas, exact).
// Every amount exact to the wei; /api/ledger matches the receipts; one Telegram card per Boost, never twice; /api/contract live.
// node qa/chain.mjs (needs anvil: ~/.foundry/bin/anvil(.exe), and forge build output in ../contracts/out)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const { ethers } = require('ethers');
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
const DATA = path.join(OUT, 'chain-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
const ANVIL = process.env.ANVIL || path.join(os.homedir(), '.foundry', 'bin', process.platform === 'win32' ? 'anvil.exe' : 'anvil');
const ART = path.resolve(APP, '..', 'contracts', 'out');
const APORT = Number(process.env.CHAIN_ANVIL_PORT || 8571), PORT = Number(process.env.CHAIN_APP_PORT || 3331);
const RPC = 'http://127.0.0.1:' + APORT, BASE = 'http://127.0.0.1:' + PORT, ADMIN = 'chain-admin-token', HUB_SECRET = 'c'.repeat(40);
// anvil's public dev keys (local chain only)
const K = ['0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',
'0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a', '0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6',
'0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a', '0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba'];
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pass = 0, fail = 0; const procs = [];
const ok = (c, what, extra) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra, (k, v) => typeof v === 'bigint' ? v.toString() : v).slice(0, 500) : '')); } };
process.on('exit', () => { for (const p of procs) try { p.kill(); } catch (e) {} });
const listen = (port, fn) => http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; await fn(q, r, b); }).listen(port, '127.0.0.1').unref();
// stand-in Telegram (never the real group)
const TG = []; listen(PORT + 2, async (q, r, b) => { TG.push({ method: q.url.split('/').pop(), body: JSON.parse(b || '{}') }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); });
// stand-in hub: wallet -> { id, username, sponsor wallet }
const people = new Map();
listen(PORT + 1, async (q, r, b) => {
const j = JSON.parse(b || '{}'); r.setHeader('Content-Type', 'application/json');
if (q.url !== '/v1/resolve') return r.end('{"ok":true}');
const all = [...people.entries()];
const w = j.wallet ? String(j.wallet).toLowerCase() : j.id ? (all.find(([, p]) => p.id === j.id) || [])[0] : j.ref ? (all.find(([a, p]) => a === String(j.ref).toLowerCase() || p.username === String(j.ref).toLowerCase()) || [])[0] : null;
const p = w && people.get(w); const sp = p && p.sponsor && people.get(p.sponsor);
r.end(JSON.stringify({ person: p ? { id: p.id, username: p.username, wallet: w, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null } : null }));
});
async function main() {
if (!fs.existsSync(ANVIL)) throw new Error('anvil not found at ' + ANVIL);
const an = spawn(ANVIL, ['--port', String(APORT), '--silent', '--chain-id', '31337'], { stdio: 'ignore' }); procs.push(an);
const provider = new ethers.JsonRpcProvider(RPC, 31337, { staticNetwork: true });
for (let i = 0; i < 60; i++) { try { await provider.getBlockNumber(); break; } catch (e) { await sleep(200); } }
const deployer = new ethers.Wallet(K[0], provider), keeper = new ethers.Wallet(K[1]);
const [A3, A2, A1, B] = [K[2], K[3], K[4], K[5]].map(k => new ethers.Wallet(k, provider));
const company = ethers.Wallet.createRandom().address;
const lc = w => w.address.toLowerCase();
people.set(lc(A3), { id: 'h_' + '3'.repeat(16), username: 'athree' }); people.set(lc(A2), { id: 'h_' + '2'.repeat(16), username: 'atwo', sponsor: lc(A3) });
people.set(lc(A1), { id: 'h_' + '1'.repeat(16), username: 'aone', sponsor: lc(A2) }); people.set(lc(B), { id: 'h_' + 'b'.repeat(16), username: 'buyerb', sponsor: lc(A1) });
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
let nonce = await provider.getTransactionCount(deployer.address);
const fa = art('MockV3Aggregator'); const feed = await new ethers.ContractFactory(fa.abi, fa.bytecode.object, deployer).deploy(25000000n, { nonce: nonce++ }); await feed.waitForDeployment();
const sa = art('VABShop'); const shop = await new ethers.ContractFactory(sa.abi, sa.bytecode.object, deployer).deploy(company, keeper.address, await feed.getAddress(), { nonce: nonce++ }); await shop.waitForDeployment();
await (await shop.setSku(1, 500, 500, true, { nonce: nonce++ })).wait();
const SHOP = await shop.getAddress(); console.log('anvil', RPC, 'VABShop', SHOP);
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '', LINK_PROBE: '0', NETWORK_LOOKUP_URL: '', NETWORK_SITES_HUB: '0',
CHAIN_ID: '31337', CONTRACT_ADDRESS: SHOP, CHAIN_RPC: RPC, KEEPER_KEY: K[1], SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '300', EXPLORER: 'https://explorer.invalid', COMPANY_WALLET: company,
HUB_URL: 'http://127.0.0.1:' + (PORT + 1), HUB_SECRET, HUB_SITE: 'viraladblitz', HUB_ENABLED: '0', HUB_CACHE_MS: '200',
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + (PORT + 2) });
const log = fs.openSync(path.join(OUT, 'chain-server.log'), 'w');
procs.push(spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', log, log] }));
for (let i = 0; i < 80; i++) { try { if ((await fetch(BASE + '/health')).ok) break; } catch (e) {} await sleep(150); }
// a member session through the app: wallet sign-in, post an ad
async function member(w, n) {
const jar = {}; const call = async (p, body) => { const r = await fetch(BASE + p, { method: body === undefined ? 'GET' : 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 ChainTest', Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, body: body === undefined ? undefined : JSON.stringify(body) });
for (const c of r.headers.getSetCookie()) { const [kv] = c.split(';'); const i = kv.indexOf('='); jar[kv.slice(0, i)] = kv.slice(i + 1); } return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); };
const ch = await call('/api/auth/challenge', { address: w.address }); await call('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) });
const a = await call('/api/my/ad', { headline: 'Chain ad ' + n, line1: 'A real text ad for ' + n, line2: '', link: 'https://chain-' + n + '.example-shop.com/' });
ok(a.ok, n + ' signs in and posts a text ad', a); return call;
}
const bal = a => provider.getBalance(a);
// one Boost through the app: order -> the member's wallet sends it -> the watcher records it
async function boost(w, call, qty) {
const od = await call('/api/my/order', { qty });
const tx = await w.sendTransaction({ to: od.to, data: od.data, value: BigInt(od.value) }); const rc = await tx.wait();
await call('/api/my/paid', {});
for (let i = 0; i < 60; i++) { const l = await call('/api/ledger'); const it = (l.items || []).find(x => x.tx === tx.hash.toLowerCase() && x.pays.every(p => p.to)); if (it) return { od, rc, it, tx }; await sleep(200); }
return { od, rc, it: null, tx };
}
const price = 500n * 10n ** 24n / 25000000n; // $5 at $0.25 = 20 POL
const share = q => q * 1000n / 10000n;
console.log('1. A3 boosts (top of the line): 100% company');
const c3 = await member(A3, 'athree'); let c0 = await bal(company);
let r = await boost(A3, c3, 1);
ok(r.rc.status === 1 && r.od.why === 'no-line' && r.od.line === 0, 'A3 has no line: no voucher, the Boost still goes through', r.od);
ok((await bal(company)) - c0 === price, 'company got the whole 20 POL (nobody to pay)', ((await bal(company)) - c0).toString());
ok(r.it && r.it.pays.length === 1 && r.it.pays[0].level === 0 && r.it.pays[0].wei === price.toString(), 'ledger: one company payment from the receipt', r.it);
console.log('2. A1 boosts: line [A2, A3], A2 passed over');
const c1 = await member(A1, 'aone'); c0 = await bal(company); const a3b = await bal(A3.address), a2b = await bal(A2.address);
r = await boost(A1, c1, 1);
ok(r.od.line === 2 && (await shop.sponsorOf(A1.address)) === A2.address && (await shop.sponsorOf(A2.address)) === A3.address, 'the voucher bound A1 -> A2 -> A3 on chain', r.od);
ok((await bal(A3.address)) - a3b === share(price) && (await bal(A2.address)) === a2b && (await bal(company)) - c0 === price - share(price), 'A3 got 10% (level 1, place 2), A2 nothing, company 90% (exact to the wei)');
ok(r.it.passedOver.length === 1 && r.it.passedOver[0].who === lc(A2) && r.it.passedOver[0].depth === 1 && r.it.pays.find(p => p.level === 1).depth === 2, 'ledger: A2 passed over at place 1, A3 paid at place 2', r.it);
console.log('3. B boosts 2 with the 1% overpay: binds B -> A1 only');
const cb = await member(B, 'buyerb'); c0 = await bal(company); const a1b = await bal(A1.address), a3b2 = await bal(A3.address), bb = await bal(B.address);
r = await boost(B, cb, 2);
const q2 = price * 2n; const gas = r.rc.gasUsed * r.rc.gasPrice;
ok(r.od.line === 3 && (await shop.sponsorOf(B.address)) === A1.address && (await shop.sponsorOf(A1.address)) === A2.address, 'B\'s voucher carried [A1, A2, A3]; only B -> A1 was new, A1\'s link unchanged');
ok((await bal(A1.address)) - a1b === share(q2) && (await bal(A3.address)) - a3b2 === share(q2) && (await bal(company)) - c0 === q2 - 2n * share(q2), 'A1 level 1 (4 POL), A3 level 2 (4 POL), company 80% (32 POL), exact');
ok(bb - (await bal(B.address)) === q2 + gas && BigInt(r.od.value) > q2, 'B sent price + 1% and spent exactly price + gas: the overpay came back in the same transaction');
ok(r.it.pays.filter(p => p.level > 0).map(p => [p.level, p.depth, p.name]).join('|') === '1,1,aone|2,3,athree', 'ledger: levels with places and names', r.it.pays);
ok(await provider.getBalance(SHOP) === 0n && (await shop.totalOwed()) === 0n, 'the contract holds nothing');
const my = await cb('/api/my'); ok(my.boosts.length === 1 && my.boosts[0].views === 1000 && my.boosts[0].qty === 2, 'B\'s My page: 2 Boosts = 1,000 guaranteed views', my.boosts);
const myA1 = await c1('/api/my'); ok(myA1.earned.wei === share(q2).toString(), 'A1\'s My page: the level share paid to them', myA1.earned);
console.log('4. trust pack');
for (let i = 0; i < 30 && TG.length < 3; i++) await sleep(200);
await sleep(1500);
ok(TG.length === 3 && TG.every(t => t.method === 'sendPhoto' && t.body.message_thread_id === 632242), 'Telegram: exactly one photo card per Boost (3), payments topic, none repeated', TG.map(t => t.method));
const capB = TG[2].body.caption;
ok(/@buyerb boosted "Chain ad buyerb": 2 Boosts \(1,000 guaranteed views\) · \$10\.00 \(40\.0000 POL\)/.test(capB) && /Level 1 10%: 4\.0000 POL → @aone/.test(capB) && /Level 2 10%: 4\.0000 POL → @athree \(place 3 in the line\)/.test(capB) && /ViralAdBlitz: 32\.0000 POL/.test(capB), 'B\'s card: buyer, ad, each level with POL and place, company', capB);
ok(/1 person in the line had not boosted yet and was passed over/.test(TG[1].body.caption) && /Nobody in this line has boosted yet/.test(TG[0].body.caption), 'cards say who was passed over / that nobody qualified');
const ct = await (await fetch(BASE + '/api/contract')).json();
ok(ct.live && ct.owner === lc(deployer) && ct.company === company.toLowerCase() && ct.keeper === lc(keeper) && ct.orderCount === 3 && ct.balanceWei === '0', '/api/contract reads the live contract', ct);
console.log('\nPOL/USD $0.25: Boost $5 = ' + ethers.formatEther(price) + ' POL, one level share = ' + ethers.formatEther(share(price)) + ' POL');
console.log(pass + ' passed, ' + fail + ' failed');
fs.writeFileSync(path.join(OUT, 'chain.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n');
process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error('chain test crashed:', e.stack || e.message); process.exit(1); });
+432
View File
@@ -0,0 +1,432 @@
// ViralAdBlitz local smoke test. Boots the app in prototype mode (no DOCSTORE_URL: files in a throwaway data dir under qa/out)
// against local stand-ins, then checks: copy rules, pages, the promo kit, sign-in (wallet + network), the one free text ad, member
// pages built from the hub line (first 5 with an ad, by place), verified visits / views / clicks, the weekly board, Boost orders
// (line voucher signed by the keeper, already-bound line, hub down), Boost recording from the chain (ledger split, passed over,
// Telegram card once, hub report), Boost delivery (views counted, starred while active, finished), Network Ad Space finishing,
// old-link redirects, admin, a restart, and Playwright renders on desktop + phone.
// Nothing leaves this machine: hub, InstantAdPay lookup, chain RPC, Telegram and NAS are local stand-ins. No real wallet, no money.
// node qa/smoke.mjs (Playwright renders too, if installed at PLAYWRIGHT)
// SKIP_UI=1 node qa/smoke.mjs (HTTP checks only)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import http from 'node:http';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const { ethers } = require('ethers');
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
const DATA = path.join(OUT, 'data-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const PORT = Number(process.env.SMOKE_APP_PORT || 3317), BASE = 'http://127.0.0.1:' + PORT;
const ADMIN = 'smoke-admin-token', SSO_SECRET = crypto.randomBytes(32).toString('hex'), HUB_SECRET = 'h'.repeat(40);
const KEEPER_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d'; // anvil's public test key #1
const KEEPER = new ethers.Wallet(KEEPER_PK).address;
const SHOP = '0x00000000000000000000000000000000000Ab0B5';
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pass = 0, fail = 0; let srv = null;
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra, (k, v) => typeof v === 'bigint' ? v.toString() : v).slice(0, 500) : '')); } };
const listen = (port, fn) => http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; try { await fn(q, r, b); } catch (e) { r.statusCode = 500; r.end(String(e.message)); } }).listen(port, '127.0.0.1').unref();
// ---- stand-in network hub: people = wallet|id -> { id, username, wallet|null, sponsorId, blocked }. Signed as viraladblitz. ----
const HUB = { people: new Map(), down: false, badSig: 0, resolves: 0, got: [] };
function person(username, wallet, sponsorId) { const id = 'h_' + crypto.createHash('sha1').update(username).digest('hex').slice(0, 16); HUB.people.set(id, { id, username, wallet: wallet ? wallet.toLowerCase() : null, sponsorId: sponsorId || null }); return id; }
const hubView = p => { if (!p) return null; const sp = p.sponsorId && HUB.people.get(p.sponsorId); return { id: p.id, username: p.username, wallet: p.wallet, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null }; };
const HUB_PORT = PORT + 1;
listen(HUB_PORT, async (q, r, b) => {
r.setHeader('Content-Type', 'application/json');
if (HUB.down) { r.statusCode = 503; return r.end('{"error":"down"}'); }
const want = crypto.createHmac('sha256', HUB_SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
if (q.headers['x-hub-sig'] !== want || q.headers['x-hub-site'] !== 'viraladblitz') { HUB.badSig++; r.statusCode = 401; return r.end('{}'); }
const j = JSON.parse(b || '{}');
if (q.url === '/v1/resolve') {
HUB.resolves++; const all = [...HUB.people.values()]; let p = null;
if (j.id) p = HUB.people.get(j.id); else if (j.wallet) p = all.find(x => x.wallet === String(j.wallet).toLowerCase());
else if (j.ref) { const ref = String(j.ref).toLowerCase(); p = all.find(x => x.wallet === ref || x.username.toLowerCase() === ref); }
else if (j.email) p = all.find(x => x.email === j.email);
return r.end(JSON.stringify({ person: hubView(p) }));
}
HUB.got.push({ route: q.url, body: j }); r.end('{"ok":true}');
});
// ---- stand-in InstantAdPay member lookup (only used while the hub is down) ----
const IAP_KNOWS = new Set(); const LOOKUP_PORT = PORT + 2;
listen(LOOKUP_PORT, async (q, r) => { const a = (new URL(q.url, 'http://x').searchParams.get('a') || '').toLowerCase(); r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify(IAP_KNOWS.has(a) ? { address: a, username: 'iap' + a.slice(2, 8) } : {})); });
// ---- stand-in Polygon JSON-RPC: quoteWei at POL $0.25 (1 cent = 0.04 POL), sponsorOf from BOUND, contract facts, logs + receipts ----
const IFACE = new ethers.Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 views, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, uint256 companyPaid)',
'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)', 'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)',
'event SponsorBound(address indexed member, address indexed sponsor)',
'function quoteWei(uint256 sku, uint256 qty) view returns (uint256)', 'function sponsorOf(address) view returns (address)',
'function buy(uint256 sku, uint256 qty, uint256 ref, address[] line, uint256 deadline, bytes sig) payable returns (uint256)',
'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 CHAIN = { head: 1, logs: [], receipts: {}, bound: new Map(), replayAll: false, down: false, times: {} };
const TANGEM = '0x7627Fc78876948AC9d95C1C9eB061E7D6d647b70';
const CHAIN_PORT = PORT + 3;
listen(CHAIN_PORT, async (q, r, b) => {
const j = JSON.parse(b || '{}'); let result = null; r.setHeader('Content-Type', 'application/json');
if (CHAIN.down) return r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, error: { code: -1, message: 'down' } }));
if (j.method === 'eth_blockNumber') result = '0x' + CHAIN.head.toString(16);
if (j.method === 'eth_call') {
const d = j.params[0].data; const tx = IFACE.parseTransaction({ data: d });
const enc = (fn, v) => IFACE.encodeFunctionResult(fn, v);
if (tx.name === 'quoteWei') result = enc('quoteWei', [500n * tx.args[1] * 4n * 10n ** 16n]);
if (tx.name === 'sponsorOf') result = enc('sponsorOf', [CHAIN.bound.get(tx.args[0].toLowerCase()) || ethers.ZeroAddress]);
if (tx.name === 'owner' || tx.name === 'company') result = enc(tx.name, [TANGEM]);
if (tx.name === 'keeper') result = enc('keeper', [KEEPER]);
if (tx.name === 'paused') result = enc('paused', [false]);
if (tx.name === 'totalOwed') result = enc('totalOwed', [0n]);
if (tx.name === 'orderCount') result = enc('orderCount', [BigInt(CHAIN.logs.length)]);
}
if (j.method === 'eth_getBalance') result = '0x0';
if (j.method === 'eth_getTransactionReceipt') result = CHAIN.receipts[j.params[0]] || null;
if (j.method === 'eth_maxPriorityFeePerGas') result = '0x' + (40n * 10n ** 9n).toString(16);
if (j.method === 'eth_getBlockByNumber') { const n = j.params[0] === 'latest' ? CHAIN.head : parseInt(j.params[0], 16); result = { number: '0x' + n.toString(16), timestamp: '0x' + (CHAIN.times[n] || Math.floor(Date.now() / 1000)).toString(16), baseFeePerGas: '0x' + (30n * 10n ** 9n).toString(16) }; }
if (j.method === 'eth_getLogs') { const f = j.params[0], lo = parseInt(f.fromBlock, 16), hi = parseInt(f.toBlock, 16); result = CHAIN.logs.filter(l => CHAIN.replayAll || (parseInt(l.blockNumber, 16) >= lo && parseInt(l.blockNumber, 16) <= hi)); }
r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, result }));
});
// a Boost on the stand-in chain: Purchase log + a receipt with SponsorBound / PassedOver / Paid logs, like VABShop emits
let orderId = 0;
function chainBoost(o) {
const id = ++orderId; const block = ++CHAIN.head; const tx = '0x' + crypto.randomBytes(32).toString('hex');
if (o.blockAt) CHAIN.times[block] = o.blockAt;
const weiPaid = 500n * BigInt(o.qty || 1) * 4n * 10n ** 16n; const share = weiPaid / 10n;
const mk = (name, args, li) => { const e = IFACE.encodeEventLog(name, args); return { address: SHOP.toLowerCase(), topics: e.topics, data: e.data, blockNumber: '0x' + block.toString(16), transactionHash: tx, logIndex: '0x' + li.toString(16), removed: false }; };
const logs = []; let li = 0;
for (const [m, s] of o.bound || []) { logs.push(mk('SponsorBound', [m, s], li++)); CHAIN.bound.set(m.toLowerCase(), s.toLowerCase()); }
for (const [w, d] of o.over || []) logs.push(mk('PassedOver', [id, w, d], li++));
(o.pays || []).forEach(([w, d], i) => logs.push(mk('Paid', [id, w, share, i + 1, d], li++)));
const company = weiPaid - share * BigInt((o.pays || []).length);
logs.push(mk('Paid', [id, TANGEM, company, 0, 0], li++));
const purchase = mk('Purchase', [id, o.buyer, 1, o.qty || 1, o.ref || 0, o.views || 500, 500 * (o.qty || 1), weiPaid, (o.pays || []).length, company], li++);
logs.push(purchase); CHAIN.logs.push(purchase);
CHAIN.receipts[tx] = { status: '0x1', blockNumber: '0x' + block.toString(16), to: SHOP.toLowerCase(), from: o.buyer.toLowerCase(), logs };
return { tx, id, weiPaid, share, company };
}
// ---- stand-in Telegram Bot API ----
const TG = []; const TG_PORT = PORT + 4;
listen(TG_PORT, async (q, r, b) => { TG.push({ method: q.url.split('/').pop(), token: q.url.split('/')[1], body: JSON.parse(b || '{}') }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); });
const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '',
VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '2', LINK_PROBE: '0', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + LOOKUP_PORT + '/api/network/member',
NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid', NETWORK_SITES_HUB: '0',
CONTRACT_ADDRESS: SHOP, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200', EXPLORER: 'https://explorer.invalid',
HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'viraladblitz', HUB_TICK_MS: '300', HUB_DOWN_MS: '300', HUB_CACHE_MS: '200',
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT });
process.on('exit', () => { try { srv && srv.kill(); } catch (e) {} });
let nextIp = 10;
function client(opts = {}) {
const jar = {}; const ip = opts.ip || ('203.0.113.' + (nextIp++)); const ua = opts.ua || ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) SmokeBrowser/' + ip);
return { jar, ip, ua,
async req(p, o = {}) {
const headers = Object.assign({ 'User-Agent': ua, 'X-Forwarded-For': ip, Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, o.headers || {});
const r = await fetch(BASE + p, { method: o.method || 'GET', headers, body: o.body, redirect: 'manual' });
for (const c of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv] = c.split(';'); const i = kv.indexOf('='); jar[kv.slice(0, i)] = kv.slice(i + 1); }
return r;
},
async json(p, body, extra) { const r = await this.req(p, body === undefined ? { headers: extra } : { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extra), body: JSON.stringify(body) }); return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); } };
}
async function boot() {
const log = fs.openSync(path.join(OUT, 'server.log'), 'a');
srv = spawn(process.execPath, ['server.js'], { cwd: APP, env: ENV, stdio: ['ignore', log, log] });
for (let i = 0; i < 80; i++) { try { const r = await fetch(BASE + '/health'); if (r.ok) return; } catch (e) {} await sleep(150); }
throw new Error('server did not start; see qa/out/server.log');
}
async function stop() { const p = srv; srv = null; if (!p) return; const done = new Promise(r => p.once('exit', r)); p.kill('SIGINT'); await Promise.race([done, sleep(3000)]); }
// a member signed in by wallet signature. hub: { username, sponsorId } puts them in the hub; iap: InstantAdPay knows the wallet
async function walletMember(o = {}) {
const w = o.wallet || ethers.Wallet.createRandom(); const c = client(); const a = w.address.toLowerCase();
if (o.hub) c.hubId = person(o.hub.username, a, o.hub.sponsorId);
if (o.iap) IAP_KNOWS.add(a);
const ch = await c.json('/api/auth/challenge', { address: w.address });
const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) });
c.address = a; c.wallet = w; c.ok = v.ok === true && !!c.jar['vab.sid'];
return c;
}
const adBody = (n, extra) => Object.assign({ headline: 'Headline number ' + n, line1: 'First line for ad ' + n + ', plain text', line2: 'Second line ' + n, link: 'https://member-' + n + '.example-shop.com/offer?id=' + n }, extra || {});
// one page load + its verified visit
async function view(c, page, u, wait) {
const d = await c.json('/api/wire?page=' + page + (u ? '&u=' + encodeURIComponent(u) : ''));
if (!d.ticket) return { d, r: { verified: false, why: 'no-ticket' } };
await sleep(wait != null ? wait : 2100);
return { d, r: await c.json('/api/visit/seen', { ticket: d.ticket, visibleMs: wait != null ? wait : 2100 }) };
}
async function main() {
if (await fetch(BASE).then(() => true, () => false)) throw new Error('port ' + PORT + ' is already in use; set SMOKE_APP_PORT');
console.log('data dir', DATA);
console.log('1. copy rules');
const pub = path.join(APP, 'public');
const files = fs.readdirSync(pub).filter(f => f.endsWith('.html')).map(f => path.join(pub, f)).concat(fs.readdirSync(path.join(pub, 'assets')).filter(f => /\.(js|css)$/.test(f) && f !== 'wallet.js').map(f => path.join(pub, 'assets', f)));
const texts = files.map(f => [path.basename(f), fs.readFileSync(f, 'utf8')]).concat(['promokit.js', 'proof.js', 'server.js', 'tools/pages.mjs', 'tools/art.mjs'].map(f => [f, fs.readFileSync(path.join(APP, f), 'utf8')]));
ok(texts.every(([, t]) => !/[\u2014\u2013]/.test(t)), 'no em or en dashes in any page, script or copy source', texts.filter(([, t]) => /[\u2014\u2013]/.test(t)).map(x => x[0]));
const html = texts.filter(([n]) => n.endsWith('.html')).map(x => x[1]).join('\n');
ok(!/metamask/i.test(html), 'pages never name MetaMask');
ok(/SafePal or any other crypto wallet/.test(html), 'wallet copy says "SafePal or any other crypto wallet"');
ok(!/passive income|guaranteed (income|returns|profit)|earn (cash|money)|make money|get rich|up to \$?\d+ (a|per)|maximum (you|earn)/i.test(html), 'no income promises and no earnings caps in page copy');
ok(/never a subscription/i.test(html) && /A Boost buys advertising, not income\. Nothing is promised\./.test(html), 'Boost copy: one-time, never a subscription; "advertising, not income. Nothing is promised."');
ok(/TrustClickz/.test(html) && /615 Green Valley Drive, Moody, AL 35004/.test(html), 'legal pages name TrustClickz, 615 Green Valley Drive, Moody, AL 35004');
console.log('2. boot (prototype mode, temp data dir)');
await boot();
const cfg = await (await fetch(BASE + '/api/config')).json();
ok(cfg.boost.usd === 5 && cfg.boost.views === 500 && cfg.boost.sku === 1 && cfg.split.levels === 5 && cfg.split.levelPct === 10 && cfg.split.companyPct === 50, 'config: Boost $5 = 500 views, 5 levels x 10% + 50% company', cfg.boost);
ok(cfg.shop.live === true && cfg.shop.contract.toLowerCase() === SHOP.toLowerCase(), 'shop live against the stand-in contract');
ok(fs.readFileSync(path.join(OUT, 'server.log'), 'utf8').includes('files (prototype mode)'), 'server says prototype mode (no DOCSTORE_URL)');
console.log('3. pages');
const anon = client();
for (const p of ['/', '/my', '/boost', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy', '/admin', '/robots.txt', '/sitemap.xml', '/art/mark.svg', '/art/og-share.png', '/assets/vab.css', '/assets/common.js']) { const r = await anon.req(p); ok(r.status === 200, 'GET ' + p + ' 200', r.status); }
let r = await anon.req('/'); const home = await r.text();
ok(/Your ad runs on your whole team's pages\. Five levels deep\./.test(home) && /id="boardCards"/.test(home) && /og:image" content="https:\/\/viraladblitz\.com\/art\/og-share\.png/.test(home), 'front page: headline, board, Open Graph');
ok(!r.headers.get('x-frame-options'), 'front page stays frameable (traffic exchanges)');
r = await anon.req('/my'); ok(r.headers.get('x-frame-options') === 'DENY', '/my is never framed');
ok(/script-src[^;]*https:\/\/linkspin\.app/.test(r.headers.get('content-security-policy') || ''), 'CSP admits linkspin.app (network zones)');
r = await anon.req('/nobody-at-all'); ok(r.status === 404 && /Back to the wire/.test(await r.text()), 'a username the hub does not know: 404');
r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in');
console.log('4. promo kit');
{ const kr = await anon.req('/api/promo-kit?u=smokeleader'); const k = await kr.json();
ok(kr.status === 200 && kr.headers.get('access-control-allow-origin') === '*', 'GET /api/promo-kit 200 with CORS open');
ok(k.links[0].url === 'https://viraladblitz.com/smokeleader' && k.links.slice(1).every(l => l.url.endsWith('?ref=smokeleader')), 'kit links: the member page + ?ref=', k.links.map(l => l.url));
ok(k.links.every(l => /^https:\/\/linkspin\.app\/r\/nwvab\?src=viraladblitz&s1=smokeleader/.test(l.tracked)), 'every link has a LinkSpin-tracked twin (nwvab, source viraladblitz)', k.links.map(l => l.tracked));
const words = JSON.stringify([k.lines, k.headlines, k.email, k.posts, k.note, k.tagline]);
ok(!/[\u2014\u2013]/.test(words) && !/passive income|guaranteed (income|returns|profit)|make money|metamask/i.test(words) && /\$5 one-time Boost buys 500 guaranteed network views/.test(words) && /SafePal or any other crypto wallet/.test(words), 'kit copy: no dashes, no income promises, Boost facts from config, SafePal wording');
ok(k.creatives.length === 21 && new Set(k.creatives.map(c => c.angle)).size === 3, 'kit: 21 creatives in 3 angles', k.creatives.length);
const bad = k.creatives.filter(c => /\d{2,4}x\d{2,4}|banner|[-_/]ads?[-_./]/i.test(c.url.replace('https://viraladblitz.com', ''))); ok(!bad.length, 'kit: creative paths are ad-blocker neutral', bad.map(c => c.url));
let dimOk = true; const dimBad = [];
for (const c of k.creatives) { const rr = await anon.req(new URL(c.url).pathname); const buf = Buffer.from(await rr.arrayBuffer()); const w = buf.readUInt32BE(16), h = buf.readUInt32BE(20);
if (rr.status !== 200 || w !== c.w || h !== c.h || !c.html.includes('href="https://viraladblitz.com/smokeleader"')) { dimOk = false; dimBad.push(c.key + ' ' + w + 'x' + h); } }
ok(dimOk, 'kit: every creative is a PNG at its exact size and its HTML links to the member page', dimBad);
const pr = await anon.req('/art/proof/vab-proof-amber.png'); ok(pr.status === 200 && pr.headers.get('content-type') === 'image/png', 'Telegram proof card image served'); }
console.log('5. sign-in and network membership');
// the hub line used through the test (nearest first above OWNER): L1 (ad) <- L2 (NO ad) <- L3 (ad, NO wallet in hub) <- L4 (ad) <- L5 (ad) <- L6 (ad) <- L7 (ad) <- TOP
const W = n => ethers.Wallet.createRandom();
const wTop = W(), w7 = W(), w6 = W(), w5 = W(), w4 = W(), w2 = W(), w1 = W(), wOwner = W(), wDown = W();
const idTop = person('topdog', wTop.address), id7 = person('seven', w7.address, idTop), id6 = person('six', w6.address, id7), id5 = person('five', w5.address, id6), id4 = person('four', w4.address, id5);
const id3 = person('three', null, id4); const id2 = person('two', w2.address, id3), id1 = person('one', w1.address, id2);
const idOwner = person('owner', wOwner.address, id1);
const STR = await walletMember({ iap: false }); let my = await STR.json('/api/my');
ok(STR.ok && my.netVerified === false, 'a wallet the network does not know: signed in, not a network member', my);
let pa = await STR.json('/api/my/ad', adBody(0)); ok(pa._status === 403 && /network members/.test(pa.error), 'a non-member cannot post a text ad', pa);
const M1 = await walletMember({ wallet: w1 }); my = await M1.json('/api/my');
ok(my.netVerified === true && my.username === 'one', 'a wallet the hub knows: network member, username from the hub', my);
const bad = client(); const x0 = ethers.Wallet.createRandom(), x1 = ethers.Wallet.createRandom();
const ch0 = await bad.json('/api/auth/challenge', { address: x0.address }); const v0 = await bad.json('/api/auth/verify', { address: x0.address, signature: await x1.signMessage(ch0.message) });
ok(v0._status === 400 && !bad.jar['vab.sid'], 'a signature from another wallet is refused');
// network sign-in from InstantAdPay: /sso/start -> IAP mints a token -> /sso/in
const L = client(); r = await L.req('/sso/start?mode=go&via=iap&to=%2Fmy'); const loc = r.headers.get('location') || '';
ok(r.status === 302 && loc.startsWith('https://iap.invalid/sso/check?st=') && loc.includes('&r=viraladblitz'), 'network sign-in hops to InstantAdPay with r=viraladblitz', loc);
const nsso = require(path.join(APP, 'networksso.js')); process.env.NETWORK_SSO_SECRET = SSO_SECRET;
const tok = nsso.mint({ iss: 'iap', aud: 'viraladblitz', email: 'owner@example.org', wallet: wOwner.address.toLowerCase(), name: 'owner', st: new URL(loc).searchParams.get('st'), to: '/my' });
r = await L.req('/sso/in?t=' + encodeURIComponent(tok));
ok(r.status === 302 && r.headers.get('location') === '/my' && !!L.jar['vab.sid'], 'the network token signs the member in', { s: r.status, l: r.headers.get('location') });
r = await L.req('/sso/in?t=' + encodeURIComponent(tok)); ok(!/vab\.sid=[0-9a-f]{64}/.test(String(r.headers.get('set-cookie') || '')), 'a network token works only once');
const OWN = L; OWN.address = wOwner.address.toLowerCase();
my = await OWN.json('/api/my'); ok(my.username === 'owner' && my.netVerified && my.page === 'https://viraladblitz.com/owner', 'network member keeps the network username; page = viraladblitz.com/<username>', my);
ok(HUB.resolves > 0 && HUB.badSig === 0, 'hub lookups are signed as viraladblitz with HUB_SECRET', HUB.badSig);
HUB.down = true; const FB = await walletMember({ iap: true }); my = await FB.json('/api/my');
ok(my.netVerified === true, 'hub unreachable: InstantAdPay verifies the wallet (fallback)', my); HUB.down = false; await sleep(400);
console.log('6. the free text ad');
pa = await M1.json('/api/my/ad', adBody(1, { headline: 'ab' })); ok(pa._status === 400 && /headline/.test(pa.error), 'a 2-character headline is refused', pa);
pa = await M1.json('/api/my/ad', adBody(1, { headline: 'x'.repeat(61) })); ok(pa._status === 400, 'a 61-character headline is refused');
pa = await M1.json('/api/my/ad', adBody(1, { line1: '' })); ok(pa._status === 400 && /first line/.test(pa.error), 'the first line is required', pa);
pa = await M1.json('/api/my/ad', adBody(1, { link: 'http://plain.com/' })); ok(pa._status === 400 && /https/.test(pa.error), 'an http link is refused', pa);
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://bit.ly/x' })); ok(pa._status === 400 && /shortener/.test(pa.error), 'a link shortener is refused', pa);
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://10.0.0.1/' })); ok(pa._status === 400, 'an IP-address link is refused');
pa = await M1.json('/api/my/ad', adBody(1, { headline: 'Line <b>one</b> \u2014 deal', link: 'https://member-1.example-shop.com/o?c={clickid}&p={placement}' }));
ok(pa.ok && pa.created === true, 'a member posts their free text ad', pa);
const ad1 = pa.ad.id;
my = await M1.json('/api/my'); ok(my.ad.headline === 'Line b one /b - deal', 'markup and long dashes are stripped from ad text', my.ad.headline);
pa = await M1.json('/api/my/ad', adBody(1)); ok(pa.ok && pa.created === false && pa.ad.id === ad1, 'posting again edits the same ad (one ad per member)', pa);
// the rest of the line posts ads (L2 never does; L3 has no wallet in the hub but signs in with one the hub does not tie to them)
const M = { 1: M1 };
for (const [k, w] of [[4, w4], [5, w5], [6, w6], [7, w7], ['top', wTop]]) { M[k] = await walletMember({ wallet: w }); const q = await M[k].json('/api/my/ad', adBody(k, k === 5 ? { link: 'https://member-5.example-shop.com/o?c={clickid}&p={placement}' } : {})); ok(q.ok, 'line member ' + k + ' posts an ad'); }
const OWNAD = (await OWN.json('/api/my/ad', adBody('own'))).ad.id;
const DOWN = await walletMember({ wallet: wDown, hub: { username: 'downline', sponsorId: idOwner } }); await DOWN.json('/api/my/ad', adBody('down'));
console.log('7. member page from the hub line');
r = await anon.req('/owner'); ok(r.status === 200 && /member\.js/.test(await r.text()) && /vab\.ref=owner/.test(String(r.headers.get('set-cookie'))), 'GET /owner serves the member page and remembers the referrer');
let mp = await anon.json('/api/wire?page=member&u=owner');
ok(mp.page && mp.page.ad && mp.page.ad.id === OWNAD && mp.page.username === 'owner', 'member page: the owner\'s own ad', mp.page && mp.page.ad);
const lv = (mp.page.line || []).map(x => [x.level, x.owner]);
ok(JSON.stringify(lv) === JSON.stringify([[1, '@one'], [4, '@four'], [5, '@five'], [6, '@six'], [7, '@seven']]), 'five upline ads, by place in the line: L2 (no ad) and L3 (no wallet) skipped, the 6th with an ad (topdog) not shown', lv);
ok(mp.page.joinUrl === 'https://instantadpay.com/?ref=owner', 'join link: InstantAdPay under the page owner', mp.page.joinUrl);
mp = await anon.json('/api/wire?page=member&u=nobody-here'); ok(mp._status === 404, 'unknown member: 404 from the page API');
console.log('8. verified visits, views and clicks');
const botC = client({ ua: 'Mozilla/5.0 (compatible; Googlebot/2.1)' }); let wd = await botC.json('/api/wire?page=front'); ok(!wd.ticket, 'bots get no visit ticket');
const early = client(); let vv = await view(early, 'front', null, 300); ok(!vv.r.verified && vv.r.why === 'early', 'a visit sent before the timer is not verified', vv.r);
const V1 = client(); vv = await view(V1, 'member', 'owner');
ok(vv.r.verified && vv.r.views === 8 && /^[0-9a-f]{24}$/.test(vv.r.vt), 'a verified visit on a member page: every ad shown gets a view (own + 5 line + the rest on the ticker: 8 ads), verified token issued', vv.r);
const v2 = await view(V1, 'member', 'owner'); ok(v2.r.verified && v2.r.views === 0, 'the same visitor again: no second view of the same ads in 24 h', v2.r);
my = await OWN.json('/api/my'); ok(my.ad.views === 1, 'the owner\'s ad has 1 verified view', my.ad.views);
const ownView = await view(OWN, 'member', 'owner'); my = await OWN.json('/api/my'); ok(ownView.r.verified && my.ad.views === 1, 'the owner viewing their own page never counts for their own ad', my.ad.views);
const shared = '198.51.100.7'; const sv = [0, 1, 2].map(i => client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/' + i }));
const svr = []; for (const c of sv) svr.push((await view(c, 'front')).r);
ok(svr.filter(x => x.verified).length === 2 && svr[2].why === 'ip', 'only 2 browsers per connection are verified per day', svr);
// clicks
r = await anon.req('/go/' + ad1 + '?p=ticker'); const gl = new URL(r.headers.get('location'));
ok(r.status === 302 && gl.hostname === 'member-1.example-shop.com', '/go/<ad> sends to the ad link', r.headers.get('location'));
{ const a5 = (await M[5].json('/api/my')).ad.id; const r5 = await anon.req('/go/' + a5 + '?p=ticker'); const g5 = new URL(r5.headers.get('location'));
ok(/^[0-9a-f]{16}$/.test(g5.searchParams.get('c')) && g5.searchParams.get('p') === 'ticker', 'tracking macros: {clickid} and {placement} filled on every click', r5.headers.get('location')); }
r = await V1.req('/go/' + ad1 + '?p=level1&v=' + vv.r.vt); ok(r.status === 302, 'a verified visitor clicks');
r = await V1.req('/go/' + ad1 + '?p=level1&v=' + vv.r.vt); r = await V1.req('/go/' + ad1 + '?p=level1&v=' + 'f'.repeat(24));
const bc = client({ ua: 'curl/8' }); await bc.req('/go/' + ad1);
my = await M1.json('/api/my'); ok(my.ad.vclicks === 1 && my.ad.clicks >= 4, 'clicks: 1 verified (repeat, bad token and unverified ones are raw only, bots not counted)', { v: my.ad.vclicks, c: my.ad.clicks });
const Vb = client(); const vb = await view(Vb, 'front'); await Vb.req('/go/' + ad1 + '?v=' + vb.r.vt); const Vc = client(); const vcv = await view(Vc, 'front'); const ad4 = (await M[4].json('/api/my')).ad.id; await Vc.req('/go/' + ad4 + '?v=' + vcv.r.vt);
await OWN.req('/go/' + OWNAD + '?v=' + ownView.r.vt);
let fr = await anon.json('/api/wire?page=front');
ok(fr.board.items[0].id === ad1 && fr.board.items[0].clicks === 2 && fr.board.items[0].rank === 1 && fr.board.items.length === 2, 'Top ads this week: ranked by verified clicks (the owner\'s own click never counts)', fr.board.items.map(x => [x.id, x.clicks]));
ok(fr.today.vclicks === 3 && fr.today.ads >= 8, 'today on the wire: verified clicks + ads live', fr.today);
console.log('9. Boost orders (line voucher)');
let q = await OWN.json('/api/quote?qty=1'); ok(q.usd === 5 && q.views === 500 && BigInt(q.wei) === 20n * 10n ** 18n, 'quote: $5 at $0.25 = 20 POL (from the contract)', q);
q = await OWN.json('/api/quote?qty=11'); ok(q._status === 400, '11 Boosts refused (1 to 10)');
const NOAD = await walletMember({ wallet: w2 }); let od = await NOAD.json('/api/my/order', { qty: 1 }); ok(od._status === 400 && /text ad first/.test(od.error), 'no ad: no Boost', od);
od = await OWN.json('/api/my/order', { qty: 2 });
const call = IFACE.parseTransaction({ data: od.data, value: od.value });
const line = call.args[3].map(a => a.toLowerCase());
ok(od._status === 200 && call.name === 'buy' && Number(call.args[0]) === 1 && Number(call.args[1]) === 2 && Number(call.args[2]) === OWNAD, 'order = buy(sku 1, qty 2, ref = the owner\'s ad id)', od);
ok(JSON.stringify(line) === JSON.stringify([w1, w2, w4, w5, w6, w7, wTop].map(w => w.address.toLowerCase())), 'the voucher line = the hub line\'s wallets nearest first (L3 without a wallet left out)', line);
const rec = ethers.verifyTypedData({ name: 'VABShop', version: '1', chainId: 137, verifyingContract: ethers.getAddress(SHOP.toLowerCase()) }, { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'line', type: 'address[]' }, { name: 'deadline', type: 'uint256' }] },
{ buyer: ethers.getAddress(OWN.address), line: call.args[3], deadline: call.args[4] }, call.args[5]);
ok(rec === KEEPER, 'the voucher is signed by the keeper (EIP-712 VABShop v1)', rec);
ok(BigInt(od.value) === 40n * 10n ** 18n * 101n / 100n && Number(call.args[4]) > Date.now() / 1000 + 1700, 'value = quote + 1% (refunded by the contract), deadline 30 minutes', od.value);
CHAIN.bound.set(M1.address, w2.address.toLowerCase());
od = await M1.json('/api/my/order', { qty: 1 }); const c2 = IFACE.parseTransaction({ data: od.data, value: od.value });
ok(od.why === 'bound' && c2.args[3].length === 0 && c2.args[5] === '0x', 'a member whose line is already bound on chain: no voucher (the chain\'s binding wins)', od.why);
CHAIN.bound.delete(M1.address); HUB.down = true; await sleep(350);
od = await M[4].json('/api/my/order', { qty: 1 }); ok(od._status === 503 && /sponsor line/.test(od.error), 'hub unreachable: the Boost waits (the line is never signed partial)', od);
HUB.down = false; await sleep(350);
CHAIN.down = true; od = await OWN.json('/api/my/order', { qty: 1 }); ok(od._status === 503, 'chain unreachable: no order'); CHAIN.down = false;
console.log('10. a Boost recorded from the chain');
// the owner's 2 Boosts: line bound; one, four, five, six, seven paid; two passed over (place 2)
const b1 = chainBoost({ buyer: wOwner.address, qty: 2, ref: OWNAD, views: 6, bound: [[wOwner.address, w1.address], [w1.address, w2.address], [w2.address, w4.address]],
over: [[w2.address, 2]], pays: [[w1.address, 1], [w4.address, 3], [w5.address, 4], [w6.address, 5], [w7.address, 6]] });
let led; for (let i = 0; i < 40; i++) { led = await anon.json('/api/ledger'); if (led.items && led.items.length && led.items[0].pays.length > 1 && led.items[0].pays[0].to) break; await sleep(150); }
const it = led.items[0];
ok(led.items.length === 1 && it.tx === b1.tx && it.qty === 2 && it.buyerName === 'owner' && it.ad && it.ad.id === OWNAD, 'the ledger shows the Boost (buyer, ad)', it);
ok(it.pays.filter(p => p.level > 0).map(p => [p.level, p.depth, p.name, p.wei]).every((x, i) => x[0] === i + 1 && x[3] === b1.share.toString()) && it.pays.find(p => p.level === 0).wei === b1.company.toString(), 'the ledger split from the receipt: 5 levels x 10% with their places, company 50%', it.pays);
ok(it.passedOver.length === 1 && it.passedOver[0].depth === 2 && it.passedOver[0].name === 'two', 'passed over: @two at place 2 (never boosted)', it.passedOver);
for (let i = 0; i < 20 && !TG.length; i++) await sleep(150);
ok(TG.length === 1 && TG[0].method === 'sendPhoto' && TG[0].token === 'botstandin-token' && TG[0].body.message_thread_id === 632242 && /\/art\/proof\/vab-proof-[a-z]+\.png$/.test(TG[0].body.photo), 'Telegram: one photo card in the payments topic', TG.map(t => t.method));
const cap = TG[0].body.caption || '';
ok(/@owner boosted "Headline number own"/.test(cap) && /Level 1 10%: 4\.0000 POL → @one/.test(cap) && /Level 2 10%: 4\.0000 POL → @four \(place 3 in the line\)/.test(cap) && /ViralAdBlitz: 20\.0000 POL/.test(cap), 'card: buyer, ad, every level with POL and place, company', cap);
ok(/1 person in the line had not boosted yet and was passed over/.test(cap) && /This week: 2 Boosts · \d+ ads live · \d+ verified clicks/.test(cap) && /explorer\.invalid\/tx\/0x[0-9a-f]{64}/.test(cap) && /viraladblitz\.com\/ledger/.test(cap) && !/[\u2014\u2013]/.test(cap), 'card: passed-over line, week stats, verify + ledger links, no dashes', cap);
my = await OWN.json('/api/my'); ok(my.boosts.length === 1 && my.boosts[0].views === 6 && my.boosts[0].delivered === 0 && my.boosts[0].status === 'delivering', 'My page: the Boost with its guaranteed views', my.boosts);
my = await M[4].json('/api/my'); ok(my.earned.items.length === 1 && my.earned.items[0].level === 2 && my.earned.wei === b1.share.toString(), 'My page for @four: the level 2 share paid to them', my.earned);
const rc = await anon.json('/api/recent'); ok(rc.items.some(x => x.kind === 'boost' && x.name === 'owner' && x.levels === 5), 'toasts: the Boost with 5 sponsors paid', rc.items);
for (let i = 0; i < 30 && !HUB.got.length; i++) await sleep(150);
ok(HUB.got.length === 1 && HUB.got[0].route === '/v1/contract-bind' && HUB.got[0].body.contract === 'viraladblitz' && HUB.got[0].body.wallet === OWN.address && HUB.got[0].body.sponsorRef === w1.address.toLowerCase() && HUB.got[0].body.spentCents === 1000, 'hub report: contract-bind for the buyer with their direct sponsor', HUB.got);
CHAIN.replayAll = true; await sleep(800); CHAIN.replayAll = false;
led = await anon.json('/api/ledger'); ok(led.items.length === 1 && TG.length === 1, 'a flaky RPC re-sending old logs: no second record, no second Telegram post');
// an old Boost (block 3 hours ago) is recorded but never posted
const old = chainBoost({ buyer: w4.address, qty: 1, ref: 0, views: 500, blockAt: Math.floor(Date.now() / 1000) - 3 * 3600, pays: [[w5.address, 1]] });
for (let i = 0; i < 30; i++) { led = await anon.json('/api/ledger'); if (led.items.length === 2) break; await sleep(150); } await sleep(500);
ok(led.items.length === 2 && TG.length === 1, 'a Boost older than 2 hours is recorded but never posted to Telegram', TG.length);
my = await M[4].json('/api/my'); ok(my.boosts.length === 1 && my.boosts[0].adId === (await M[4].json('/api/my')).ad.id, 'a Boost with ref 0 attaches to the buyer\'s live ad', my.boosts);
console.log('11. Boost delivery');
fr = await anon.json('/api/wire?page=front');
ok(fr.ticker.some(t => t.id === OWNAD && t.boosted), 'the Boosted ad is starred on the ticker', fr.ticker.map(t => [t.id, t.boosted]));
mp = await anon.json('/api/wire?page=member&u=downline');
const mtop = await anon.json('/api/wire?page=member&u=topdog');
ok(mp.page.line[0] && mp.page.line[0].id === OWNAD && mp.page.line[0].boosted, 'downline page: the owner at level 1, starred', mp.page.line[0]);
{ const onPage = new Set([mp.page.ad.id].concat(mp.page.line.map(x => x.id))); ok(mp.page.boosted.every(x => !onPage.has(x.id)), 'downline page: a Boosted place never repeats an ad already on the page', mp.page.boosted.map(x => x.id)); }
ok(mtop.page.line.length === 0 && mtop.page.boosted.length === 2 && mtop.page.boosted.every(x => x.boosted) && mtop.page.boosted.some(x => x.id === OWNAD), 'top of the line (no upline): the 2 Boosted places show Boosted ads', mtop.page.boosted.map(x => x.id));
let delivered = 0; const views = [];
for (let i = 0; i < 7; i++) { const c = client(); const x = await view(c, 'front'); views.push(x.r.boostViews); }
my = await OWN.json('/api/my'); delivered = my.boosts[0].delivered;
ok(delivered === 6 && my.boosts[0].status === 'delivered' && my.boosts[0].remaining === 0, 'every verified visitor delivers one view; the Boost finishes at its 6 guaranteed views', { delivered, s: my.boosts[0].status, views });
const st = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(st.rows.boostViews >= 6 + 7 && st.boosts.delivered >= 6, 'every counted Boost view is kept as an audit row', st.rows);
fr = await anon.json('/api/wire?page=front'); ok(!fr.ticker.some(t => t.id === OWNAD && t.boosted), 'a delivered Boost is no longer starred');
console.log('12. Network Ad Space finishing (stand-in NAS database)');
{
process.env.DATA_DIR = path.join(DATA, 'nas'); fs.mkdirSync(process.env.DATA_DIR, { recursive: true }); require(path.join(APP, 'config.js')).reset();
const vabnas = require(path.join(APP, 'vabnas.js')); const NAS = { rows: [], pays: [] };
const query = async (sql, args) => {
if (/^INSERT INTO payments/.test(sql)) { NAS.pays.push(args); return { insertId: NAS.pays.length }; }
if (/^INSERT INTO sponsorads/.test(sql)) { NAS.rows.push({ ID: NAS.rows.length + 100, sql, args, assigned: args[4], remaining: args[5] }); return { insertId: NAS.rows.length + 99 }; }
if (/^SELECT assigned, remaining/.test(sql)) { const x = NAS.rows.find(y => y.ID === args[0]); return x ? [{ assigned: x.assigned, remaining: x.remaining }] : []; }
return [];
};
const ad = { id: 9, status: 'live', headline: 'Late Boost ad', line1: 'Line one', line2: 'Line two' };
const boosts = [{ key: 'tx1:0', adId: 9, views: 500, delivered: 120, dueAt: Date.now() - 1000 }, { key: 'tx2:0', adId: 9, views: 500, delivered: 10, dueAt: Date.now() + 86400000 }, { key: 'tx3:0', adId: 9, views: 500, delivered: 500, dueAt: Date.now() - 1000 }];
vabnas.init({ boosts: () => boosts, remaining: b => Math.max(0, b.views - b.delivered - vabnas.boostServed(b.key)), ad: () => ad }, { query });
const t1 = await vabnas.tick();
ok(t1.placed === 1 && NAS.rows.length === 1 && NAS.rows[0].assigned === 380, 'a Boost past 30 days with 380 views owed gets one NAS text ad for exactly 380; one still in its window and one delivered are left alone', { t1, rows: NAS.rows.map(r2 => r2.assigned) });
const a0 = NAS.rows[0].args; ok(a0[1] === 'Late Boost ad' && a0[2] === 'Line one Line two' && a0[3] === 'https://viraladblitz.com/go/9?p=nas' && /,1,0,\?\)$/.test(NAS.rows[0].sql.replace(/\s+/g, '')), 'NAS text ad: headline = subject, lines = body, link through /go/<ad>?p=nas (clicks count here), pid 1 (text)', a0.slice(0, 4));
NAS.rows[0].remaining = 380 - 150; await vabnas.tick();
ok(vabnas.boostServed('tx1:0') === 150 && NAS.rows.length === 1, 'NAS impressions read back (assigned - remaining) count toward the Boost; no second NAS ad', vabnas.boostServed('tx1:0'));
NAS.rows[0].remaining = -40; await vabnas.tick(); ok(vabnas.boostServed('tx1:0') === 380, 'NAS counter drift above assigned is clamped');
}
console.log('13. old site links');
r = await anon.req('/api/admin/oldrefs', { method: 'POST', headers: { 'x-admin-token': ADMIN }, body: JSON.stringify({ oldrefs: { janie23: 'owner', 'bad key!': 'x', frank: '<b>' } }) });
const or = await r.json(); ok(or.ok && or.total === 1 && or.skipped === 2, 'admin loads the old-username map (bad rows skipped)', or);
for (const [from, to] of [['/?janie23', '/owner'], ['/?janie23&fbclid=x', '/owner'], ['/splashpg.php?pid=4&r=janie23', '/owner'], ['/lcp.php?pid=2&r=JANIE23', '/owner'], ['/?nobodyold', '/'], ['/members.php', '/'], ['/splashpg.php?pid=4&r=nobody', '/']]) {
r = await anon.req(from); ok(r.status === 301 && r.headers.get('location') === to, 'old link ' + from + ' -> ' + to, r.headers.get('location')); }
r = await anon.req('/?ref=owner'); ok(r.status === 200, '/?ref=<name> is not an old link');
console.log('14. admin');
r = await anon.req('/api/admin/status'); ok(r.status === 401, 'admin needs the token');
const sj = JSON.stringify(st);
ok(st.shop.vouchers && st.shop.keeper === KEEPER && !sj.includes(KEEPER_PK.slice(2)) && !sj.includes(HUB_SECRET) && !sj.includes('standin-token') && !sj.includes(SSO_SECRET), 'admin status: keeper address only, no key or secrets', st.shop);
const lk = await anon.json('/api/admin/member-lookup?q=four', undefined, { 'x-admin-token': ADMIN }); ok(lk.address === w4.address.toLowerCase() && lk.earned.items.length === 1 && lk.paidBy.length === 1, 'member lookup: earnings and who paid them', lk.earned);
const rm = await anon.json('/api/admin/ad', { id: (await M[7].json('/api/my')).ad.id, status: 'removed', note: 'smoke' }, { 'x-admin-token': ADMIN }); ok(rm.ok, 'admin removes an ad');
mp = await anon.json('/api/wire?page=member&u=owner'); ok(!mp.page.line.some(x => x.owner === '@seven') && mp.page.line.some(x => x.owner === '@topdog'), 'a removed ad leaves the member pages; the next one up (place 8) moves in', mp.page.line.map(x => [x.level, x.owner]));
console.log('15. restart');
await stop(); await boot(); await sleep(500);
my = await OWN.json('/api/my'); ok(my.ad && my.ad.id === OWNAD && my.boosts[0].delivered === 6, 'after a restart: ads, Boosts and delivery are kept', my.boosts);
led = await anon.json('/api/ledger'); ok(led.items.length === 2 && TG.length === 1, 'after a restart: no re-record, no repost');
const again = await view(client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/9' }), 'front'); ok(!again.r.verified && again.r.why === 'ip', 'after a restart: the per-connection cap still holds (rebuilt from the visit rows)', again.r);
if (!process.env.SKIP_UI && fs.existsSync(PW)) {
console.log('16. Playwright renders (desktop 1280 + phone 390)');
const { chromium } = require(PW); const browser = await chromium.launch();
for (const [label, vp] of [['desktop', { width: 1280, height: 900 }], ['phone', { width: 390, height: 844 }]]) {
const ctx = await browser.newContext({ viewport: vp, isMobile: label === 'phone', userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36 SmokeUI-' + label });
await ctx.route(/^https:\/\//, rt => rt.abort()); // nothing leaves this machine (Google Fonts too: the pages fall back to Georgia + system fonts here)
const errs = []; const pg = await ctx.newPage(); pg.on('pageerror', e => errs.push(e.message));
for (const [p, sel] of [['/', '#boardCards .paper'], ['/owner', '#levels .lvl'], ['/boost', '#bQty option'], ['/ledger', '#rows tbody tr'], ['/contract', '#facts th'], ['/promote', '#kit .card'], ['/terms', '.legal .card'], ['/disclaimer', '.legal .card'], ['/privacy', '.legal .card']]) {
await pg.goto(BASE + p, { waitUntil: 'domcontentloaded' }); await pg.waitForSelector(sel, { timeout: 8000 }).catch(() => {});
const found = await pg.$$eval(sel, els => els.length);
const wide = await pg.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
ok(found > 0 && wide <= 1, label + ' ' + p + ': renders (' + sel + ') with no sideways scroll', { found, wide });
await pg.screenshot({ path: path.join(OUT, label + '-' + (p === '/' ? 'front' : p.slice(1)) + '.png'), fullPage: true });
}
await pg.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#ticker .run a', { timeout: 8000 }).catch(() => {});
ok((await pg.$$eval('#ticker .run a', els => els.length)) > 0 && (await pg.textContent('footer')).includes('TrustClickz') && /Part of the network/.test(await pg.textContent('footer')), label + ': ticker runs; footer has the company line and the network line');
await pg.goto(BASE + '/owner', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#levels .lvl a[data-go]', { timeout: 8000 }).catch(() => {});
await pg.waitForFunction(() => [...document.querySelectorAll('a[data-go]')].some(a => /[?&]v=[0-9a-f]{24}/.test(a.href)), null, { timeout: 9000 }).catch(() => {});
ok(await pg.evaluate(() => [...document.querySelectorAll('a[data-go]')].every(a => /[?&]v=[0-9a-f]{24}/.test(a.href))), label + ': after the dwell the visit verifies and every ad link carries the verified token');
ok(/LEVEL 1/.test(await pg.textContent('#levels')) && /Join free under @owner/.test(await pg.textContent('#join')), label + ': member page shows level rows and "Join free under @owner"');
await ctx.addCookies([{ name: 'vab.sid', value: OWN.jar['vab.sid'], url: BASE }]);
await pg.goto(BASE + '/my', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 }).catch(() => {});
const mt = await pg.textContent('#dash').catch(() => '');
ok(/@owner/.test(mt) && /viraladblitz\.com\/owner/.test(mt) && /6 of 6 delivered/.test(mt) && (await pg.inputValue('#fHead')) === 'Headline number own', label + ': My page (signed in): page link, ad form filled, Boost delivery');
await pg.screenshot({ path: path.join(OUT, label + '-my.png'), fullPage: true });
await pg.goto(BASE + '/boost', { waitUntil: 'domcontentloaded' }); await pg.waitForFunction(() => /about d/.test(document.getElementById('bPol').textContent), null, { timeout: 8000 }).catch(() => {});
ok(/about 20\.00 POL at today/.test(await pg.textContent('#bPol')) && !(await pg.isDisabled('#bBuy')), label + ': Boost page shows the live POL price and an open Buy button', await pg.textContent('#bPol'));
ok(errs.length === 0, label + ': no page errors', errs);
await ctx.close();
}
await browser.close();
} else console.log('16. (Playwright renders skipped)');
await stop();
console.log('\n' + pass + ' passed, ' + fail + ' failed');
fs.writeFileSync(path.join(OUT, 'smoke.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n');
process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error('smoke crashed:', e.stack || e.message); fail++; process.exit(1); });