Files
viraladsource/qa/e2e.mjs
T
martbost 608ec6547b Approved launch numbers; members earn for free; Boost = a 7-day board spot (placement only)
- config: 5 sponsor levels x 10% (company 20%), approved numbers labelled as such, POT_DAILY_CENTS display (2500).
- Eligibility: a network member with a linked wallet earns a level or the resharer cut, Boost or not. /api/my/order drops line
  members with no wallet (compression); empty levels and the no-resharer cut go to the company.
- shop.js: VASShop ABI after the contract fix (Purchase.boardDays, skus().boardDays, potDailyMaxCents, potCentsToday); purchase days
  from the chain. wire.js keeps the on-chain days.
- Copy: removed "sponsor levels pay people who have bought a Boost / passed over / none qualified" and the proposal labels; Boost page,
  chatbot, contract page (split fixed forever, pot daily cap) say a Boost buys placement only. Assets ?v=2.
- qa/e2e.mjs: deploys the new VASShop (5 x 10%, pot cap 2500, SKU 7 days); a no-wallet hub member between buyer and sponsor is
  skipped and both sponsors get exactly 10% without a Boost. 61/61. Chatbot QA 108/108.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 05:19:56 -06:00

225 lines
22 KiB
JavaScript

// ViralAdSource end-to-end test on a local anvil chain (no fork, nothing leaves this machine, no real POL, no real people).
// Deploys the real VASShop (../contracts/out) with a mock Chainlink feed at $0.25, boots the app against it with a stand-in hub,
// and walks the whole product through the app's own HTTP API:
// sign-in by wallet; O posts an ad; R1 reshares it (step 1); R2 reshares through R1's link (step 2, same branch);
// a visitor through R2's link -> verified view booked to R2 + ad credits; a verified click carries the branch (s2/s3 on LinkSpin links);
// the family tree sums it up; sign-ups through R2's link: a clean one passes every check (pending reward + keeper voucher),
// a throwaway email is rejected, R2's own device is rejected, someone already in the network is rejected;
// B arrives through R1's link and buys a Boost: the contract pays R1 the resharer cut, the pot, the company, to the wei, and the
// sponsor levels with no Boost needed: B's hub line is B -> X (no wallet, not eligible) -> O -> S, so X is skipped (compression)
// and O gets level 1, S level 2; levels 3..5 have nobody and go to the company;
// rewards relay (payouts ON in this test only): claimReward pays R2 from the pot; a replay is refused by the contract;
// the staging test switch works on a staging host and is refused on the real domain.
// node qa/e2e.mjs (needs anvil ~/.foundry/bin 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 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 = 8581, PORT = 3341, HPORT = PORT + 1;
const RPC = 'http://127.0.0.1:' + APORT, BASE = 'http://127.0.0.1:' + PORT, ADMIN = 'e2e-admin-token-123', HUB_SECRET = 'e'.repeat(40);
const K = ['0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',
'0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a', '0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6',
'0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a', '0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba',
'0x92db14e403b83dfe3df233f83dfa3a0d7096f21ca9b0d6d6b8d88b2b4ec1564e', '0x4bbbf85ce3377467afe5d46f804f221813b2bb87f24d81f60f1fcdbf7cbf4356'];
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, 600) : '')); } };
process.on('exit', () => { for (const p of procs) try { p.kill(); } catch (e) {} });
// stand-in hub: resolve by wallet / ref / id / email; everyone else is unknown (brand new)
const people = new Map(); const knownEmails = new Set(['already@example.org']);
http.createServer(async (q, r) => {
let b = ''; for await (const c of q) b += c; const j = JSON.parse(b || '{}'); r.setHeader('Content-Type', 'application/json');
if (q.url === '/health') return r.end('{"ok":true}');
if (q.url !== '/v1/resolve') return r.end('{"ok":true}');
if (j.email) return r.end(JSON.stringify({ person: knownEmails.has(j.email) ? { id: 'h_' + 'e'.repeat(16), username: 'known', wallet: null, blocked: false } : null }));
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: p.noWallet ? null : w, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null } : null }));
}).listen(HPORT, '127.0.0.1').unref();
// a browser: its own cookie jar and user agent (so its own visitor key)
let ipN = 10;
function client(ua, ipAddr) {
const jar = {}; const xff = ipAddr || '198.51.100.' + (ipN++);
const req = async (method, p, body, headers) => {
const h = Object.assign({ 'User-Agent': ua, 'X-Forwarded-For': xff, Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, headers || {});
if (body !== undefined) h['Content-Type'] = 'application/json';
const r = await fetch(BASE + p, { method, headers: h, body: body !== undefined ? JSON.stringify(body) : undefined, redirect: 'manual' });
for (const sc of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv] = sc.split(';'); const i = kv.indexOf('='); const v = kv.slice(i + 1); if (v === '' || /Max-Age=0/.test(sc)) delete jar[kv.slice(0, i)]; else jar[kv.slice(0, i)] = v; }
let j = null; try { j = await r.json(); } catch (e) {}
return { status: r.status, j: j || {}, loc: r.headers.get('location') };
};
return { ua, jar, xff, get: (p, h) => req('GET', p, undefined, h), post: (p, b, h) => req('POST', p, b || {}, h) };
}
async function signIn(c, w) {
const ch = await c.post('/api/auth/challenge', { address: w.address });
const sig = await w.signMessage(ch.j.message);
return c.post('/api/auth/verify', { address: w.address, signature: sig });
}
const admin = (p, b) => fetch(BASE + p, { method: b ? 'POST' : 'GET', headers: { 'x-admin-token': ADMIN, 'Content-Type': 'application/json' }, body: b ? JSON.stringify(b) : undefined }).then(r => r.json());
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.NonceManager(new ethers.Wallet(K[0], provider)), keeper = new ethers.Wallet(K[1]), relay = new ethers.Wallet(K[7], provider);
const [S, O, R1, R2, B] = [K[2], K[3], K[4], K[5], K[6]].map(k => new ethers.Wallet(k, provider));
const company = ethers.Wallet.createRandom().address; const lc = w => w.address.toLowerCase();
people.set(lc(S), { id: 'h_' + '5'.repeat(16), username: 'sponsors' });
people.set(lc(O), { id: 'h_' + '0'.repeat(16), username: 'owner', sponsor: lc(S) });
people.set(lc(R1), { id: 'h_' + '1'.repeat(16), username: 'reshareone', sponsor: lc(S) });
people.set(lc(R2), { id: 'h_' + '2'.repeat(16), username: 'resharetwo', sponsor: lc(R1) });
people.set('x-no-wallet', { id: 'h_' + 'c'.repeat(16), username: 'nowallet', sponsor: lc(O), noWallet: true }); // a hub member with no linked wallet
people.set(lc(B), { id: 'h_' + 'b'.repeat(16), username: 'buyerb', sponsor: 'x-no-wallet' });
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
const feedA = art('MockV3Aggregator'), shopA = art('VASShop');
const feed = await new ethers.ContractFactory(feedA.abi, feedA.bytecode.object, deployer).deploy(25000000n); await feed.waitForDeployment();
const shopC = await new ethers.ContractFactory(shopA.abi, shopA.bytecode.object, deployer).deploy(company, keeper.address, await feed.getAddress(), 2000, 1000, [1000, 1000, 1000, 1000, 1000], 25, 10, 2500);
await shopC.waitForDeployment(); await (await shopC.setSku(1, 500, 7, true)).wait();
const CA = await shopC.getAddress(); console.log('VASShop at', CA);
await (await deployer.sendTransaction({ to: relay.address, value: ethers.parseEther('1') })).wait();
const DATA = path.join(OUT, 'e2e-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, SITE_HOST: 'vas.test.saasy.top', STAGING: '1', ADMIN_TOKEN: ADMIN, LINK_PROBE: '0', VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '50',
CREDITS_VIEWS: '1', CHAIN_ID: '31337', CHAIN_RPC: RPC, CONTRACT_ADDRESS: CA, KEEPER_KEY: K[1], RELAY_KEY: K[7], SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '300',
REWARD_PAYOUTS: '1', HUB_URL: 'http://127.0.0.1:' + HPORT, HUB_SECRET, HUB_SITE: 'viraladsource', HUB_ENABLED: '0', HUB_SSO: 'off', NETWORK_LOOKUP_URL: '', NODE_ENV: 'test', LS_TRACK: '0', OPENROUTER_KEY: '' });
delete env.DOCSTORE_URL;
const app = spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] }); procs.push(app);
let log = ''; app.stdout.on('data', d => { log += d; }); app.stderr.on('data', d => { log += d; });
for (let i = 0; i < 80; i++) { try { if ((await fetch(BASE + '/health')).ok) break; } catch (e) {} await sleep(150); }
console.log('\n-- pages');
for (const p of ['/', '/my', '/boost', '/rewards', '/join', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy', '/admin']) { const r = await fetch(BASE + p); const t = await r.text(); ok(r.status === 200 && !/[—–]/.test(t) && !/MetaMask/.test(t), 'page ' + p + ' 200, no dashes'); }
const cfg = await (await fetch(BASE + '/api/config')).json();
ok(cfg.split.resharerBps === 2000 && cfg.split.live === true && cfg.reward.cents === 25, 'config reads the live split from the contract', cfg.split);
console.log('\n-- sign-in, ad, reshares');
const cO = client('Mozilla/5.0 owner'), cR1 = client('Mozilla/5.0 r1'), cR2 = client('Mozilla/5.0 r2'), cB = client('Mozilla/5.0 buyer');
for (const [c, w] of [[cO, O], [cR1, R1], [cR2, R2], [cB, B]]) { const r = await signIn(c, w); ok(r.j.ok, 'wallet sign-in ' + w.address.slice(0, 8)); }
const me = await cO.get('/api/me'); ok(me.j.netVerified === true && me.j.username === 'owner', 'membership + username from the hub', me.j);
const bad = await cO.post('/api/my/ad', { headline: 'x', line1: 'y', link: 'https://example.com' }); ok(bad.status === 400, 'short headline refused');
const ad = await cO.post('/api/my/ad', { headline: 'Free traffic tool for your page', line1: 'Rotate every page you promote', link: 'https://example.com/offer' });
ok(ad.j.ok && /\/s\/[a-z0-9]{8}$/.test(ad.j.source), 'ad posted with a source link', ad.j);
const rootCode = ad.j.source.split('/s/')[1]; const adId = ad.j.ad.id;
let r = await cR1.get('/s/' + rootCode); ok(r.status === 200 && cR1.jar['vas.via'], 'opening a share link tags the visitor');
const s1 = await cR1.post('/api/my/reshare', { adId, from: rootCode }); ok(s1.j.ok && s1.j.step === 1 && s1.j.created, 'R1 reshare = step 1', s1.j);
const again = await cR1.post('/api/my/reshare', { adId }); ok(again.j.code === s1.j.code && !again.j.created, 'one unique link per member per ad');
await cR2.get('/s/' + s1.j.code);
const s2 = await cR2.post('/api/my/reshare', { adId, from: s1.j.code }); ok(s2.j.ok && s2.j.step === 2, 'R2 reshare through R1 = step 2', s2.j);
const own = await cO.post('/api/my/reshare', { adId }); ok(own.j.own && own.j.code === rootCode, 'the owner gets their source link back');
console.log('\n-- verified views, credits, clicks');
const cV = client('Mozilla/5.0 visitor one');
await cV.get('/s/' + s2.j.code);
const w1 = await cV.get('/api/wire?page=share&s=' + s2.j.code); ok(w1.j.ticket && w1.j.share.step === 2 && w1.j.share.resharer === 'resharetwo', 'share page data + ticket', w1.j.share);
const early = await cV.post('/api/visit/seen', { ticket: w1.j.ticket, visibleMs: 2500 }); ok(early.j.verified === false && early.j.why === 'early', 'an early send is refused');
await sleep(2100);
const seen = await cV.post('/api/visit/seen', { ticket: w1.j.ticket, visibleMs: 2500 }); ok(seen.j.verified && seen.j.views === 1 && seen.j.credited === 1, 'verified view booked to the branch', seen.j);
const self = await cR2.get('/api/wire?page=share&s=' + s2.j.code); await sleep(2100); const selfSeen = await cR2.post('/api/visit/seen', { ticket: self.j.ticket, visibleMs: 2500 });
ok(selfSeen.j.verified && selfSeen.j.credited === 0, 'a resharer viewing their own link earns nothing', selfSeen.j);
r = await cV.get('/go/' + adId + '?s=' + s2.j.code + '&p=share&v=' + seen.j.vt); ok(r.status === 302 && r.loc === 'https://example.com/offer', 'click relay to the ad link', r.loc);
const my2 = await cR2.get('/api/my'); ok(my2.j.credits.earned === 10 && my2.j.reshares[0].views === 1 && my2.j.reshares[0].clicks === 1, 'R2 credits + the share counts', { c: my2.j.credits, s: my2.j.reshares[0] });
console.log('\n-- L2 sign-ups through R2\'s link');
const join = async (c, email, waitMs) => { const f = await c.get('/api/join/form'); await sleep(waitMs); return c.post('/api/join', { email, form: f.j.form }); };
const cJ = client('Mozilla/5.0 newcomer'); await cJ.get('/s/' + s2.j.code);
const fast = await join(cJ, 'fresh.person@example.net', 0); ok(fast.j.ok, 'join accepted (no mail on staging)', fast.j);
let su = await admin('/api/admin/signups'); let row = su.signups.find(x => x.email === 'fresh.person@example.net');
ok(row && row.status === 'unconfirmed' && /\/confirm\?t=/.test(row.confirmLink || ''), 'staging admin sees the confirm link', row);
// a slow, clean join from another browser
const cJ2 = client('Mozilla/5.0 newcomer two'); await cJ2.get('/s/' + s2.j.code);
await join(cJ2, 'second.newcomer@example.net', 4300);
su = await admin('/api/admin/signups'); row = su.signups.find(x => x.email === 'second.newcomer@example.net');
const t = new URL(row.confirmLink).searchParams.get('t');
const cf = await cJ2.post('/api/confirm', { t }); ok(cf.j.ok && cf.j.status === 'passed', 'clean sign-up passes every check', cf.j);
su = await admin('/api/admin/signups'); row = su.signups.find(x => x.email === 'second.newcomer@example.net');
ok(/dry/.test(row.checks.hubNew) && row.checks.notSelf === 'pass' && row.checks.throwaway === 'pass', 'checks recorded (hub dry, not self, not throwaway)', row.checks);
let rw = await admin('/api/admin/rewards'); const rew = rw.rewards.find(x => x.signup === row.id);
ok(rew && rew.cents === 25 && rew.voucher && rew.voucher.signed, 'pending reward with a keeper voucher', rew);
// the fast one: fraud score holds it
row = (await admin('/api/admin/signups')).signups.find(x => x.email === 'fresh.person@example.net');
await cJ.post('/api/confirm', { t: new URL(row.confirmLink).searchParams.get('t') });
row = (await admin('/api/admin/signups')).signups.find(x => x.email === 'fresh.person@example.net');
ok(row.status === 'passed' || row.status === 'held', 'a form filled instantly scores high (' + row.status + ', score ' + (row.checks.fraud || {}).score + ')');
// throwaway, already-known and self
const cJ3 = client('Mozilla/5.0 throwaway'); await cJ3.get('/s/' + s2.j.code); await join(cJ3, 'abc@mailinator.com', 4300);
const cJ4 = client('Mozilla/5.0 known'); await cJ4.get('/s/' + s2.j.code); await join(cJ4, 'already@example.org', 4300);
const cSelf = client('Mozilla/5.0 r2', cR2.xff); // the same browser as R2 (same visitor key)
await cSelf.get('/s/' + s2.j.code); await join(cSelf, 'my.other.address@example.net', 4300);
su = await admin('/api/admin/signups');
for (const [e, want] of [['abc@mailinator.com', 'throwaway email'], ['already@example.org', 'already in the network'], ['my.other.address@example.net', "the resharer's own device"]]) {
const x = su.signups.find(y => y.email === e); await cJ.post('/api/confirm', { t: new URL(x.confirmLink).searchParams.get('t') });
const y = (await admin('/api/admin/signups')).signups.find(z => z.email === e); ok(y.status === 'rejected' && y.fail.includes(want), 'rejected: ' + want, y);
}
console.log('\n-- Boost through R1\'s branch, to the wei');
await cB.post('/api/my/ad', { headline: 'Buyer ad for testing here', line1: 'A line about it', link: 'https://example.org/b' });
await cB.get('/s/' + s1.j.code); // B came through R1's reshare link
const od = await cB.post('/api/my/order', { qty: 1 }); ok(od.j.to === CA && od.j.resharer === lc(R1) && od.j.line === 2 && od.j.resharerName === 'reshareone', 'signed order names R1 and the 2-wallet line (the no-wallet member is skipped)', od.j);
const rc = await (await B.sendTransaction({ to: od.j.to, data: od.j.data, value: od.j.value })).wait();
const bal = (a, t) => provider.getBalance(a, t == null ? rc.blockNumber : t);
const [c0, r10, o0, s0, b0] = await Promise.all([company, R1.address, O.address, S.address, B.address].map(a => bal(a, rc.blockNumber - 1)));
const price = BigInt(od.j.wei); const res = price * 2000n / 10000n, pot = price * 1000n / 10000n, lvl = price * 1000n / 10000n;
const [c1, r11, o1, s1b, b1] = await Promise.all([company, R1.address, O.address, S.address, B.address].map(a => bal(a)));
ok(r11 - r10 === res, 'R1 got exactly 20% (' + ethers.formatEther(res) + ' POL)', (r11 - r10).toString());
ok(o1 - o0 === lvl && s1b - s0 === lvl, 'O (level 1) and S (level 2) each got exactly 10% without ever buying a Boost (compression over the no-wallet member)', { o: (o1 - o0).toString(), s: (s1b - s0).toString() });
ok((await shopC.boostsBought(O.address)) === 0n && (await shopC.boostsBought(S.address)) === 0n, 'neither sponsor has bought a Boost');
ok(c1 - c0 === price - res - pot - 2n * lvl, 'company got 20% + the 3 empty levels (50% in all)', (c1 - c0).toString());
ok(b0 - b1 === price + rc.gasUsed * rc.gasPrice, 'the 1% overpay came back in the same transaction');
ok((await shopC.potBalance()) === pot, 'reward pot holds 10%');
for (let i = 0; i < 40; i++) { const L = await (await fetch(BASE + '/api/ledger')).json(); if (L.items.length && L.items[0].pays && L.items[0].pays.length) break; await sleep(250); }
const L = await (await fetch(BASE + '/api/ledger')).json();
ok(L.items.length === 1 && L.items[0].resharer && L.items[0].resharer.name === 'reshareone' && L.items[0].potWei === pot.toString(), 'ledger shows the resharer cut and the pot', L.items[0]);
const tr = await admin('/api/admin/tree?ad=' + adId);
ok(tr.totals.shares === 2 && tr.totals.reach === 2 && tr.branches.length === 1 && tr.branches[0].under === 1 && tr.branches[0].views === 1 && tr.branches[0].signups >= 1 && tr.branches[0].boosts === 1, 'family tree: 1 branch, 2 steps, views + sign-ups + the Boost roll up', tr);
console.log('\n-- reward relay (payouts ON here only, local chain)');
const before = await provider.getBalance(R2.address, await provider.getBlockNumber());
const pay = await admin('/api/admin/rewards/pay', {}); ok(pay.relayed >= 1, 'relayed claimReward', pay);
for (let i = 0; i < 40; i++) { rw = await admin('/api/admin/rewards'); if (rw.rewards.some(x => x.status === 'paid')) break; await sleep(250); }
for (let i = 0; i < 40; i++) { rw = await admin('/api/admin/rewards'); if (rw.rewards.filter(x => x.status === 'paid').length === rw.rewards.filter(x => x.to === lc(R2)).length) break; await sleep(250); }
const paidL = rw.rewards.filter(x => x.status === 'paid'); const paid = paidL[0]; const got = (await provider.getBalance(R2.address, await provider.getBlockNumber())) - before;
const one = await shopC.rewardWei(25);
ok(paidL.length >= 1 && got === paidL.reduce((t, x) => t + BigInt(x.weiPaid), 0n) && paidL.every(x => BigInt(x.weiPaid) === one), 'R2 got exactly $0.25 in POL per verified sign-up from the pot (' + paidL.length + ' x ' + ethers.formatEther(one) + ' POL)', { got: got.toString(), n: paidL.length });
const v = rw.rewards.find(x => x.id === paid.id);
const fullV = JSON.parse(fs.readFileSync(path.join(DATA, 'vas.json'), 'utf8')).rewards.find(x => x.id === v.id).voucher;
let replay = null; try { await shopC.connect(relay).claimReward.staticCall(fullV.to, fullV.usdCents, fullV.unlockAt, BigInt(fullV.nonce), fullV.deadline, fullV.sig); } catch (e) { replay = e.shortMessage || e.message; }
ok(/Nonce used/.test(String(replay)), 'the same voucher cannot be claimed twice', replay);
const lg = await (await fetch(BASE + '/api/ledger')).json(); ok(lg.rewards.some(x => x.status === 'paid' && x.tx), 'paid reward on the public ledger with its tx');
ok(!JSON.stringify(lg).includes('@example.net'), 'no emails on the public ledger');
console.log('\n-- staging switch + misc');
const tm = await admin('/api/admin/test-member', { address: ethers.Wallet.createRandom().address, username: 'tester1' }); ok(tm.ok && tm.member.netOk && tm.member.testMember, 'staging test switch marks a test member');
const rec = await (await fetch(BASE + '/api/recent')).json(); ok(rec.items.some(x => x.kind === 'reshare') && rec.items.some(x => x.kind === 'boost'), 'toasts carry reshares and Boosts');
const kit = await (await fetch(BASE + '/api/promo-kit?u=owner')).json(); ok(kit.links[0].url.endsWith('/owner') && !/[—–]/.test(JSON.stringify(kit)), 'promo kit with the username');
r = await cV.get('/owner'); ok(r.status === 302 && r.loc === '/s/' + rootCode, '/<username> opens their ad at its source');
r = await cV.get('/splashpg.php?pid=1&r=nobody'); ok(r.status === 301 && r.loc === '/', 'old *.php links go to the front page');
const chat = await (await fetch(BASE + '/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 chat' }, body: JSON.stringify({ message: 'Do I get paid for resharing?' }) })).json().catch(() => ({}));
ok(chat && /results/i.test(JSON.stringify(chat)), 'chatbot answers about resharing rewards', chat);
app.kill(); await sleep(300);
// the switch is refused on the real domain
const env2 = Object.assign({}, env, { SITE_HOST: 'viraladsource.com', PORT: String(PORT + 5), DATA_DIR: DATA + '-prod' }); fs.mkdirSync(env2.DATA_DIR, { recursive: true });
const app2 = spawn(process.execPath, ['server.js'], { cwd: APP, env: env2, stdio: 'ignore' }); procs.push(app2);
for (let i = 0; i < 80; i++) { try { if ((await fetch('http://127.0.0.1:' + (PORT + 5) + '/health')).ok) break; } catch (e) {} await sleep(150); }
const tm2 = await fetch('http://127.0.0.1:' + (PORT + 5) + '/api/admin/test-member', { method: 'POST', headers: { 'x-admin-token': ADMIN, 'Content-Type': 'application/json' }, body: JSON.stringify({ address: B.address }) });
ok(tm2.status === 403, 'test switch refused on viraladsource.com even with STAGING=1');
fs.writeFileSync(path.join(OUT, 'e2e-app.log'), log);
console.log('\n' + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error(e); process.exit(1); });