Files
banner-line/qa/smoke.mjs
T

234 lines
20 KiB
JavaScript

// 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 });
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) : '')); } };
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' });
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');
const qq = await u.json('/api/quote'); ok(qq.wei === q.toString() && qq.source === 'contract.quoteWei', '/api/quote reads quoteWei()', qq);
for (const p of ['/', '/board', '/join', '/my', '/how', '/assets/site.css', '/art/house-line.svg']) { const r = await u.req(p); ok(r.status === 200, 'GET ' + p + ' 200'); }
const r404 = await u.req('/nope'); ok(r404.status === 404, 'unknown path 404');
const myHdr = await u.req('/my'); ok(myHdr.headers.get('x-frame-options') === 'DENY' && !(await u.req('/')).headers.get('x-frame-options'), '/my not frameable, / frameable');
// ---- 3. gate (HTTP) ----
console.log('3. gate over HTTP (about 50 s of timers)');
const v = client(); await v.req('/?ref=' + addr[B]);
ok(!!v.jar['bl.ref'], 'ref cookie set from ?ref=');
const g = await v.json('/api/gate');
ok(!g.passed && g.steps && g.steps[0].role === 'sponsor', 'gate starts with the sponsor spot', g.steps && g.steps.map(s => s.role || s.type));
ok(g.steps && g.steps[1].type === 'board' && g.steps.filter(s => s.role === 'newest').length === 3, 'board step then 3 newest spots');
const early = await v.json('/api/gate/done', { gid: g.gid, i: 0 }); ok(early._status === 400, 'done before begin is refused');
let passedGate = false;
for (let i = 0; i < g.steps.length; i++) {
const s = g.steps[i];
await v.json('/api/gate/begin', { gid: g.gid, i });
if (s.type === 'visit') { const r = await v.req(s.open + '?g=' + g.gid + '&i=' + i); ok(r.status === 302, 'step ' + i + ' visit relays (302 to ' + r.headers.get('location') + ')'); }
if (i === 0) { const tooSoon = await v.json('/api/gate/done', { gid: g.gid, i }); ok(tooSoon._status === 400, 'done before the timer is refused'); }
await sleep(s.seconds * 1000);
const d = await v.json('/api/gate/done', { gid: g.gid, i });
if (d.passed) passedGate = true; else if (d.error) ok(false, 'step ' + i + ' done', d);
}
ok(passedGate && !!v.jar['bl.pass'], 'gate passed, pass cookie set');
ok((await v.json('/api/gate')).passed === true, 'gate reports passed on return');
const st2 = await u.json('/api/stats'); const day = Object.values(st2.daily || {}).pop() || {};
ok(day.views_gate >= 7 && day.clicks_gate >= 4, 'gate views + gate clicks stored apart', day);
const bot = client('Googlebot/2.1'); ok((await bot.json('/api/gate')).passed === true, 'bots skip the gate');
// ---- 4. organic board view ----
const bd = await v.json('/api/board'); ok(bd.tiles && bd.tiles.filter(t => t.t === 'spot').length >= 7 && bd.tiles[0].id > bd.tiles[1].id && bd.tiles.some(t => t.t === 'house'), 'board: all spots newest first + house fill', bd.tiles && bd.tiles.map(t => t.id || t.key));
const fast = await v.json('/api/board/seen', { token: bd.token }); ok(fast.counted === 0, 'board view before 5 s not counted');
const bd2 = await v.json('/api/board'); await sleep(5000);
const gateIds = new Set(g.steps[1].tiles.filter(t => t.t === 'spot').map(t => t.id)); const fresh = bd2.tiles.filter(t => t.t === 'spot' && !gateIds.has(t.id)).length; // a keeper spot may be new
const seen = await v.json('/api/board/seen', { token: bd2.token }); ok(seen.counted === fresh, 'same visitor within the hour: views not double counted', [seen, fresh]);
const v2 = client('Mozilla/5.0 other'); const bd3 = await v2.json('/api/board'); await sleep(5000);
const seen3 = await v2.json('/api/board/seen', { token: bd3.token }); ok(seen3.counted === bd3.tiles.filter(t => t.t === 'spot').length && seen3.counted > 0, 'new visitor organic views counted', seen3);
ok((await v2.json('/api/board/seen', { token: bd3.token })).counted === 0, 'board token is one-time');
// ---- 5. sign in + My Spots ----
console.log('5. sign-in + My Spots');
const m = client();
const ch = await m.json('/api/auth/challenge', { address: addr[A] });
const sig = await W[A].signer.signMessage(ch.message);
const bad = await m.json('/api/auth/verify', { address: addr[A], signature: await W[B].signer.signMessage(ch.message) }); ok(bad._status === 400, 'signature from another wallet refused');
const ch2 = await m.json('/api/auth/challenge', { address: addr[A] });
const ver = await m.json('/api/auth/verify', { address: addr[A], signature: await W[A].signer.signMessage(ch2.message) });
ok(ver.ok && !!m.jar['bl.sid'], 'wallet signature sign-in sets session', ver);
const my = await m.json('/api/my');
ok(my.spots && my.spots.length >= 2, 'A owns 2+ spots', my.spots && my.spots.length);
let my2 = my, onChain = await paidTo(addr[A]);
if (BigInt(my2.paidOutWei) !== onChain) { await sleep(2500); my2 = await m.json('/api/my'); onChain = await paidTo(addr[A]); } // a keeper buy may land in between
ok(BigInt(my2.paidOutWei) === onChain && onChain > 0n, 'A paid out matches Paid events on chain (' + ethers.formatEther(onChain) + ' POL)', my2.paidOutWei);
ok(BigInt(my.paidInWei) === 2n * q, 'A paid in = 2 spots', my.paidInWei);
ok(my.directs && my.directs.length === 2 && my.directs.some(x => x.address === addr[B].toLowerCase()), 'A directs = B and E (buyFor sponsor)', my.directs);
ok(my.share.endsWith('?ref=' + addr[A].toLowerCase()), 'share link');
const sid = my.spots[my.spots.length - 1].id;
ok((await m.json('/api/my/spot/' + sid, { link: 'http://example.org/' }))._status === 400, 'http link refused');
ok((await m.json('/api/my/spot/' + sid, { link: 'https://192.168.1.1/' }))._status === 400, 'IP link refused');
ok((await m.json('/api/my/spot/' + sid, { link: 'https://bit.ly/x' }))._status === 400, 'shortener refused');
ok((await m.json('/api/my/spot/' + sid, { link: 'javascript:alert(1)' }))._status === 400, 'javascript: refused');
ok((await m.json('/api/my/spot/' + sid, { link: 'https://example.org/landing' })).ok, 'https link saved');
const otherSpot = (await u.json('/api/stats')).recent.find(s => s.owner === addr[B].toLowerCase());
ok((await m.json('/api/my/spot/' + otherSpot.id, { link: 'https://example.org/' }))._status === 403, 'cannot edit someone else\'s spot');
const up = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(468, 60) })).json();
ok(up.ok && /^\/art\/u\//.test(up.img), 'PNG 468x60 upload saved', up);
ok((await m.req(up.img)).status === 200, 'uploaded image served');
const upBad = await (await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png(300, 250) })).json();
ok(!!upBad.error, 'wrong size refused', upBad);
const upBig = await m.req('/api/my/upload?for=' + sid, { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: Buffer.concat([png(468, 60), Buffer.alloc(160 * 1024)]) });
ok(upBig.status === 400, 'over 150 KB refused');
ok((await m.json('/api/my/default', { link: 'https://example.org/default' })).ok, 'default link saved');
const bd4 = await v.json('/api/board'); const t = bd4.tiles.find(x => x.id === sid);
ok(t && t.img === up.img, 'board shows the uploaded image for that spot');
const go = await v.req('/go/' + sid); ok(go.headers.get('location') === 'https://example.org/landing', 'click relay goes to the member link');
// ---- 6. keeper ----
console.log('6. keeper (stall set to 36 s for the test)');
const adm = await u.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(adm.keeper && adm.keeper.enabled && !JSON.stringify(adm).includes(W[7].signer.privateKey.slice(2, 20)), 'keeper on, key never in output');
let fb = null;
for (let i = 0; i < 40 && !fb; i++) { const s = await u.json('/api/stats'); fb = (s.recent || []).find(x => x.kind === 2 || x.kind === 3); if (!fb) await sleep(2000); }
ok(fb && fb.kind === 2 && fb.owner === addr[A].toLowerCase(), 'keeper fundBuy gifted a spot to A (builder, longest wait)', fb);
const adm2 = await u.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(adm2.keeper.log.some(e => e.status === 'mined'), 'keeper log shows the mined tx', adm2.keeper.log.slice(0, 3));
const logTxt = fs.readFileSync(path.join(OUT, 'server.log'), 'utf8');
ok(!logTxt.includes(W[7].signer.privateKey.slice(2)), 'keeper key not in server log');
// ---- 7. pages in a browser ----
if (!process.env.SKIP_UI) {
console.log('7. Playwright: page renders + full UI gate');
const { chromium } = require(PW);
const browser = await chromium.launch();
const errors = [];
const watch = (pg, name) => { pg.on('console', msg => { if (msg.type() === 'error') errors.push(name + ': ' + msg.text() + ' @ ' + ((msg.location() || {}).url || '')); }); pg.on('pageerror', e => errors.push(name + ': ' + e.message)); };
// member context: signed in, gate skipped
const ctxM = await browser.newContext(); await ctxM.addCookies([{ name: 'bl.sid', value: m.jar['bl.sid'], url: BASE }]);
for (const p of ['/', '/board', '/how', '/join', '/my']) {
const pg = await ctxM.newPage(); watch(pg, 'member ' + p);
await pg.goto(BASE + p, { waitUntil: 'networkidle' });
await pg.screenshot({ path: path.join(OUT, 'member' + (p === '/' ? '-home' : p.replace('/', '-')) + '.png'), fullPage: true });
const foot = await pg.textContent('footer').catch(() => ''); ok(/Part of the Crypto Team Build Network/.test(foot || ''), 'member ' + p + ' renders with footer');
if (p === '/my') { await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 }).catch(() => {}); ok(await pg.isVisible('#dash'), '/my dashboard visible'); ok((await pg.$$('.spot-ed')).length >= 3, '/my spot editors listed'); }
if (p === '/join') { await pg.waitForSelector('#buyCard:not([hidden])', { timeout: 8000 }).catch(() => {}); const price = await pg.textContent('#price'); ok(/^0\.0025/.test(price), '/join shows price ' + price); }
const em = await pg.evaluate(() => document.body.innerText.includes('\u2014')); ok(!em, p + ' has no em dash');
await pg.close();
}
// visitor context: full gate in the UI
const ctxV = await browser.newContext(); const pg = await ctxV.newPage(); watch(pg, 'visitor /');
await pg.goto(BASE + '/?ref=' + addr[B], { waitUntil: 'domcontentloaded' });
await pg.waitForSelector('#gate:not([hidden])');
for (let i = 0; i < 8; i++) {
await pg.waitForSelector('#gNext:not([hidden])', { timeout: 20000 });
const label = await pg.textContent('#gNext'); await pg.click('#gNext');
if (label === 'Continue') break;
}
await pg.waitForSelector('#open:not([hidden])', { timeout: 5000 }).catch(() => {});
ok(await pg.isVisible('#joinBtn'), 'UI gate completes and Join unlocks');
await pg.screenshot({ path: path.join(OUT, 'visitor-after-gate.png'), fullPage: true });
const pj = await ctxV.newPage(); watch(pj, 'visitor /join'); await pj.goto(BASE + '/join', { waitUntil: 'networkidle' });
ok(await pj.isVisible('#buyCard'), 'visitor /join unlocked after gate');
// fresh visitor: /join is locked
// visitor = IP + UA, so a fresh visitor needs its own UA
const ctxL = await browser.newContext({ userAgent: 'Mozilla/5.0 (fresh visitor) Chrome/130' }); const pl = await ctxL.newPage(); watch(pl, 'locked /join'); await pl.goto(BASE + '/join', { waitUntil: 'networkidle' });
ok(await pl.isVisible('#locked'), 'fresh visitor /join is locked');
const pm = await ctxL.newPage(); watch(pm, 'signed-out /my'); await pm.goto(BASE + '/my', { waitUntil: 'networkidle' }); ok(await pm.isVisible('#signin'), 'signed-out /my shows sign-in');
await browser.close();
// example.com pages inside the gate frame may log their own errors; only ours count
const ours = errors.filter(e => !/example\.(com|net|org)/.test(e)); // gate frames load example.* sites; their own 404s (favicon) are not ours
ok(ours.length === 0, 'no console errors on our pages', ours);
}
console.log('\n' + pass + ' passed, ' + fail + ' failed. Output in ' + OUT);
cleanup(); process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error(e); cleanup(); process.exit(1); });