// Banner Line local smoke test. Everything runs on this machine: a throwaway anvil chain, the REAL BannerLine
// contract (compiled artifacts read from ../contracts/out, nothing written there) with its mock $2000 feed,
// the app server against that chain, HTTP checks of every API, and Playwright page renders + a full UI gate run.
// No real network, no real wallet, no real money. Keys used are anvil's public test keys.
//
// node qa/smoke.mjs (needs ~/.foundry/bin/anvil.exe and contracts/out built)
// SKIP_UI=1 node qa/smoke.mjs (API checks only)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import os from 'node:os';
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 });
// stand-in internet for the link check (2026-11-16): preloaded into the app (NODE_OPTIONS --require), it answers safety.js's https.get
// calls (the ones with a lookup) and the DNS lookups those make, so every edit gets the full check with nothing leaving this machine. Like Node 20,
// the request asks the lookup for every address (all: true) and needs an array back (the VBB/ViralAdBlitz bug of 2026-11-15).
// Hosts: private.* -> 10.0.0.5 (refused), down.* unreachable, e404.* answers 404, redir.* 302 to https://example.org/landed,
// redir-http.* 302 to an http address, small.* a 125x125 image, anything else 200 (an image path gets a real 468x60 PNG).
const PROBE_STUB = `const https = require('https'), dns = require('dns'), fs = require('fs'), zlib = require('zlib'), { EventEmitter } = require('events'), { PassThrough } = require('stream');
const LOG = process.env.PROBE_LOG;
let probing = false; const dnsLookup = dns.lookup; // only lookups made by a link check are answered here; the app's other traffic resolves as usual
dns.lookup = function (h, o, cb) { if (!probing) return dnsLookup.apply(this, arguments); if (typeof o === 'function') { cb = o; o = {}; } const list = [{ address: String(h).startsWith('private.') ? '10.0.0.5' : '93.184.216.34', family: 4 }]; setImmediate(() => o && o.all ? cb(null, list) : cb(null, list[0].address, 4)); };
function png(w, h) {
const T = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
const crc = b => { let c = 0xffffffff; for (const x of b) c = T[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
const ch = (t, d) => { const l = Buffer.alloc(4); l.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([l, td, c]); };
const ih = Buffer.alloc(13); ih.writeUInt32BE(w, 0); ih.writeUInt32BE(h, 4); ih[8] = 8; ih[9] = 2;
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), ch('IHDR', ih), ch('IDAT', zlib.deflateSync(Buffer.alloc((w * 3 + 1) * h))), ch('IEND', Buffer.alloc(0))]);
}
const orig = https.get;
https.get = function (url, opts, cb) {
if (!opts || typeof opts.lookup !== 'function') return orig.apply(this, arguments);
const u = new URL(url); const req = new EventEmitter(); req.destroy = () => {};
if (LOG) fs.appendFileSync(LOG, u.href + '\\n');
probing = true; try { opts.lookup(u.hostname, { all: true, family: 0 }, (err, list) => {
if (err) return req.emit('error', err);
if (!Array.isArray(list)) return req.emit('error', new Error('lookup answered ' + typeof list + ', not the array Node 20 asks for'));
const h = u.hostname; if (h.startsWith('down.')) return req.emit('error', new Error('ECONNREFUSED'));
const res = new PassThrough(); res.headers = {}; res.statusCode = 200; let body = Buffer.from('
ok');
if (h.startsWith('e404.')) res.statusCode = 404;
else if (h.startsWith('redir-http.')) { res.statusCode = 302; res.headers.location = 'http://plain-http.com/'; }
else if (h.startsWith('redir.')) { res.statusCode = 302; res.headers.location = 'https://example.org/landed'; }
else if (/\\.(png|gif|jpe?g)$/i.test(u.pathname)) { body = h.startsWith('small.') ? png(125, 125) : png(468, 60); res.headers['content-type'] = 'image/png'; }
res.location = res.headers.location; const destroy = res.destroy.bind(res); res.destroy = () => destroy();
cb(res); res.end(body);
}); } finally { probing = false; }
return req;
};`;
const PROBE_LOG = path.join(OUT, 'probe-' + Date.now() + '.log'); const PROBE_FILE = path.join(OUT, 'probe-stub.cjs'); fs.writeFileSync(PROBE_FILE, PROBE_STUB);
const ART = path.resolve(APP, '..', 'contracts', 'out');
const ANVIL = process.env.ANVIL || path.join(os.homedir(), '.foundry', 'bin', 'anvil.exe');
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const RPC_PORT = Number(process.env.SMOKE_RPC_PORT || 18645), APP_PORT = Number(process.env.SMOKE_APP_PORT || 3111), BASE = 'http://127.0.0.1:' + APP_PORT;
const ADMIN = 'smoke-admin';
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pass = 0, fail = 0; const procs = [];
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 300) : '')); } };
// stand-in network hub (POST /v1/resolve, signed as bannerline) and stand-in InstantAdPay member lookup (the fallback when the
// hub is unreachable). HUB.people: {id, username, wallet, sponsorId}; HUB.down makes every hub call fail with 503.
const HUB = { people: [], down: false, calls: 0, badSig: 0, got: [] }; const HUB_PORT = APP_PORT + 7, HUB_SECRET = 'b'.repeat(40);
const IAPNET = new Map(); const IAP_PORT = APP_PORT + 8;
const TG = []; const TG_PORT = APP_PORT + 9; // stand-in Telegram Bot API (trust pack 2026-11-14): never the real group
const hubView = p => p ? { id: p.id, username: p.username, wallet: p.wallet, sponsor: (x => x ? { id: x.id, username: x.username } : null)(HUB.people.find(y => y.id === p.sponsorId)), blocked: false, locked: false } : null;
function startStandIns() {
const http = require('node:http'); const crypto = require('node:crypto');
http.createServer((q, r) => { let b = ''; q.on('data', c => { b += c; }); q.on('end', () => { let j = {}; try { j = JSON.parse(b || '{}'); } catch (e) {}
TG.push({ method: q.url.split('/').pop(), token: q.url.split('/')[1], body: j }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); }); }).listen(TG_PORT, '127.0.0.1');
http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c;
r.setHeader('Content-Type', 'application/json');
// the real hub serves the footer's network list publicly, unsigned (GET /v1/network-sites)
if (q.method === 'GET' && q.url === '/v1/network-sites') return r.end(JSON.stringify([{ id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' }, { id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' },
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' }, { id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' }, { id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }, { id: 'newsite', name: 'Hub Test Site', url: 'https://example.org' }]));
HUB.calls++;
if (HUB.down) { r.statusCode = 503; return r.end('{"error":"superseded"}'); }
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'] !== 'bannerline') { HUB.badSig++; r.statusCode = 401; return r.end('{"error":"unauthorized"}'); }
if (q.url === '/v1/sso/signout') { HUB.got.push({ route: q.url, body: JSON.parse(b || '{}') }); return r.end('{"ok":true,"ended":1}'); } // Sign out everywhere (2026-11-16)
if (q.url !== '/v1/resolve') { r.statusCode = 404; return r.end('{"error":"not_found"}'); }
const j = JSON.parse(b || '{}'); const ref = String(j.ref || '').toLowerCase();
const p = j.id ? HUB.people.find(x => x.id === j.id) : j.wallet ? HUB.people.find(x => x.wallet === String(j.wallet).toLowerCase()) : ref ? HUB.people.find(x => x.username === ref || x.wallet === ref) : null;
r.end(JSON.stringify({ person: hubView(p) })); }).listen(HUB_PORT, '127.0.0.1').unref();
http.createServer((q, r) => { const u = new URL(q.url, 'http://x'); const un = (u.searchParams.get('u') || '').toLowerCase(), a = (u.searchParams.get('a') || '').toLowerCase();
const hit = [...IAPNET].find(([n, w]) => n === un || w === a); r.setHeader('Content-Type', 'application/json');
r.end(JSON.stringify(hit ? { address: hit[1], username: hit[0] } : {})); }).listen(IAP_PORT, '127.0.0.1').unref();
}
function cleanup() { for (const p of procs) { try { p.kill(); } catch (e) {} } }
process.on('exit', cleanup);
// ---- tiny cookie-jar HTTP client ----
function client(ua) {
const jar = {};
return {
jar,
async req(p, opts = {}) {
const headers = Object.assign({ 'User-Agent': ua || 'Mozilla/5.0 smoke', Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, opts.headers || {});
const r = await fetch(BASE + p, { method: opts.method || 'GET', headers, body: opts.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, extraHeaders) { const r = await this.req(p, body === undefined ? { headers: extraHeaders } : { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extraHeaders), body: JSON.stringify(body) }); return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); }
};
}
function png(w, h) {
const crcT = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
const crc = b => { let c = 0xffffffff; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
const chunk = (t, d) => { const len = Buffer.alloc(4); len.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const o = y * (w * 3 + 1) + 1 + x * 3; raw[o] = 40 + x % 200; raw[o + 1] = 120; raw[o + 2] = 90 + y * 2; }
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
}
async function main() {
// ---- 1. chain ----
console.log('1. anvil + contract');
// never talk to someone else's node: the port must be free before our anvil starts
const busy = await fetch('http://127.0.0.1:' + RPC_PORT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"jsonrpc":"2.0","id":1,"method":"eth_chainId","params":[]}' }).then(() => true, () => false);
if (busy) throw new Error('port ' + RPC_PORT + ' is already in use; set SMOKE_RPC_PORT');
const appBusy = await fetch('http://127.0.0.1:' + APP_PORT).then(() => true, () => false);
if (appBusy) throw new Error('port ' + APP_PORT + ' is already in use; set SMOKE_APP_PORT');
const anvil = spawn(ANVIL, ['--port', String(RPC_PORT), '--silent'], { stdio: 'ignore' }); procs.push(anvil);
const provider = new ethers.JsonRpcProvider('http://127.0.0.1:' + RPC_PORT, 31337, { staticNetwork: true, pollingInterval: 200 });
for (let i = 0; i < 50; i++) { try { await provider.getBlockNumber(); break; } catch (e) { await sleep(200); } }
const W = Array.from({ length: 10 }, (_, i) => new ethers.NonceManager(ethers.HDNodeWallet.fromPhrase('test test test test test test test test test test test junk', undefined, "m/44'/60'/0'/0/" + i).connect(provider)));
const addr = await Promise.all(W.map(w => w.getAddress()));
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
const feedA = art('MockV3Aggregator'), lineA = art('BannerLine');
const feed = await (await new ethers.ContractFactory(feedA.abi, feedA.bytecode.object, W[0]).deploy(200000000000n)).waitForDeployment();
const deployBlock = await provider.getBlockNumber();
const line = await (await new ethers.ContractFactory(lineA.abi, lineA.bytecode.object, W[0]).deploy(addr[8], addr[9], addr[7], await feed.getAddress())).waitForDeployment();
const CA = await line.getAddress();
const q = await line.quoteWei(); ok(q === 2500000000000000n, 'quoteWei = 0.0025 POL at $2000', q.toString());
const send = q + q / 100n;
const [A, B, Cc, D, E, F] = [1, 2, 3, 4, 5, 6];
const buy = async (i, sponsor) => (await line.connect(W[i]).buy(sponsor, { value: send })).wait();
await buy(A, ethers.ZeroAddress); await buy(B, addr[A]); await buy(Cc, addr[B]); await buy(D, addr[B]);
await (await line.connect(W[F]).buyFor(addr[E], addr[A], { value: send })).wait();
await buy(A, ethers.ZeroAddress); await buy(0, ethers.ZeroAddress); // no-sponsor buys feed the momentum fund enough for one keeper buy
ok(Number(await line.spotCount()) === 7, '7 spots bought on anvil');
const paidTo = async a => (await line.queryFilter(line.filters.Paid(null, a), deployBlock)).reduce((t, e) => t + e.args.amount, 0n);
// ---- 2. server ----
console.log('2. server');
const DATA = path.join(OUT, 'data-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
// house list for tests: reserved example domains only, so no real site sees test traffic
fs.writeFileSync(path.join(DATA, 'house.json'), JSON.stringify([{ key: 'one', title: 'Test house 1', img: '/art/house-iap.svg', link: 'https://example.com/' }, { key: 'two', title: 'Test house 2', img: '/art/house-linkspin.svg', link: 'https://example.net/' }]));
const env = Object.assign({}, process.env, { PORT: String(APP_PORT), DATA_DIR: DATA, CHAIN_ID: '31337', RPC_URLS: 'http://127.0.0.1:' + RPC_PORT, CONTRACT_ADDRESS: CA,
DEPLOY_BLOCK: String(deployBlock), POLL_MS: '1000', ADMIN_TOKEN: ADMIN, KEEPER_ENABLED: '1', KEEPER_KEY: W[7].signer.privateKey, KEEPER_STALL_HOURS: '0.01', KEEPER_EVERY_MIN: '0.25', NODE_ENV: 'development',
HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'bannerline', HUB_ENABLED: '0', NETKB: '0', HUB_DOWN_MS: '400', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + IAP_PORT + '/api/network/member',
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT,
PROBE_LOG, NODE_OPTIONS: '--require ' + JSON.stringify(PROBE_FILE).slice(1, -1) }); // the link check runs on every edit against the stand-in internet (probe-stub.cjs)
startStandIns();
const hid = n => 'h_' + String(n).padStart(16, '0');
const ZW = ethers.Wallet.createRandom().address.toLowerCase(); // a network member with no spot here
HUB.people.push({ id: hid(1), username: 'alpha', wallet: addr[A].toLowerCase(), sponsorId: null }, { id: hid(2), username: 'beta', wallet: addr[B].toLowerCase(), sponsorId: hid(1) },
{ id: hid(3), username: 'zed', wallet: ZW, sponsorId: hid(2) }, { id: hid(4), username: 'zeta', wallet: null, sponsorId: null });
IAPNET.set('iaponly', addr[Cc].toLowerCase()); IAPNET.set('iapfallback', addr[D].toLowerCase());
const srv = spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] }); procs.push(srv);
const log = fs.createWriteStream(path.join(OUT, 'server.log')); srv.stdout.pipe(log); srv.stderr.pipe(log);
const u = client();
for (let i = 0; i < 60; i++) { try { const s = await u.json('/api/stats'); if (s.totals && s.totals.spots >= 7) break; } catch (e) {} await sleep(300); }
const st = await u.json('/api/stats');
ok(st.totals && st.totals.spots === 7, 'index parsed 7 SpotBought', st.totals);
ok(st.totals && st.totals.members === 6, 'index parsed 6 MemberJoined (payer of a buyFor is not a member)', st.totals);
ok(BigInt(st.totals.paidInWei) === 7n * q, 'paid in = 7 x quote (refunds excluded)', st.totals.paidInWei);
const cfg = await u.json('/api/config'); ok(cfg.ready && cfg.sel.buy === '0xf088d547', '/api/config has contract + selectors');
// the site assistant (2026-11-15): widget on every page, canned answers without AI, account problems hand off, admin KB behind the token
{ const home = await (await u.req('/')).text();
ok(/