Files
yourprogrambuilder/qa/e2e.mjs
T
martbost a8a1a8eec7 YourProgramBuilder, the Seed Bed (Marty 2026-11-17: "keep fleshing it out"): STAGING build
Plant a program free (referral link with {id}, link check green / yellow / red, daily recheck, reports), members save their
referral IDs in its packet, a sponsor-first link (member page / ?r= / the hub sponsor line, then the planter), the sprout meter
to REVIEW_SAVES (DEFAULT 25) -> Marty's review queue -> approved packets exported for the CTB builder / DownlineHydra wild heads
with every saved ID. Dormant old programs confirmed by their owner, old-link redirects (oldrefs), Spotlight on YPBShop (NOT
deployed; DEFAULT $10 / 1,000 views, 20/5/5/5/5, company 60), verified views with Spotlight delivery, trust pack (ledger,
contract, toasts, Telegram card, terms / disclaimer / privacy, TrustClickz only), network footer row, chatbot, promo kit,
Guides, PolHunter slot, LinkSpin tracked-link and zone hooks, AI writer through the hub. Seed-catalog look from the approved
mockup. Tests: qa/unit.test.cjs 33/33, qa/e2e.mjs 121/121 on a local anvil chain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:30:59 -06:00

281 lines
30 KiB
JavaScript

// YourProgramBuilder end-to-end test on a local anvil chain (no fork, nothing leaves this machine, no real POL, no real people).
// Deploys the real YPBShop (../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:
// pages (no dashes, no street address); sign-in by wallet, membership + usernames from the hub; planting rules (needs {id}, the
// CTB builder and network sites refused, quota, twin, a yellow packet held for the queue); saved IDs (an ID, a pasted whole link,
// a bad ID, the planter, unsigned, not a member); the sponsor-first link (anonymous -> planter, a member page / ?r= -> that member,
// a signed-in member -> nearest saved ID up their hub line); the sprout meter reaching REVIEW_SAVES -> Marty's review queue ->
// approve -> the export carries every saved ID in the builder's {affiliateid} form; reports hold a packet, admin shows it again;
// verified visits; a Spotlight bought on chain: level 1 + level 2 to the wei with compression over a no-wallet and a blocked
// member, the 3 empty levels to the company (75% in all), the overpay refunded; the watcher, the ledger, the contract page,
// Spotlight delivery counted only in the Spotlight places; old links; dormant old programs confirmed by their owner; the chatbot.
// 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 = 8583, PORT = 3361, 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',
'0xdbda1821b80551c9d65939329250298aa3472ba22feea921c0cf5d620ea67b97'];
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, 700) : '')); } };
process.on('exit', () => { for (const p of procs) try { p.kill(); } catch (e) {} });
// stand-in hub: resolve by wallet / ref / id
const people = new Map();
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 !== '/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: p.noWallet ? null : w, blocked: !!p.blocked, sponsor: sp ? { id: sp.id, username: sp.username } : null } : null }));
}).listen(HPORT, '127.0.0.1').unref();
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 });
return c.post('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.j.message) });
}
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 verifiedVisit(c, page, q) {
const w = await c.get('/api/wire?page=' + page + (q || '')); if (!w.j.ticket) return { w, v: null };
await sleep(2100); const v = await c.post('/api/visit/seen', { ticket: w.j.ticket, visibleMs: 2200 }); return { w, v: v.j };
}
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]);
const [S, O, M1, M2, M3, B, N] = [K[2], K[3], K[4], K[5], K[6], K[7], K[8]].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: 'planter', sponsor: lc(S) });
people.set(lc(M1), { id: 'h_' + '1'.repeat(16), username: 'memberone', sponsor: lc(S) });
people.set(lc(M2), { id: 'h_' + '2'.repeat(16), username: 'membertwo', sponsor: lc(M1) });
people.set(lc(M3), { id: 'h_' + '3'.repeat(16), username: 'memberthree', sponsor: lc(M2) });
const BL = ethers.Wallet.createRandom().address.toLowerCase();
people.set(BL, { id: 'h_' + 'd'.repeat(16), username: 'blockedone', sponsor: lc(O), blocked: true });
people.set('x-no-wallet', { id: 'h_' + 'c'.repeat(16), username: 'nowallet', sponsor: BL, noWallet: true });
people.set(lc(B), { id: 'h_' + 'b'.repeat(16), username: 'buyerb', sponsor: 'x-no-wallet' });
// N is not a network member (unknown to the hub)
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
const feedA = art('MockV3Aggregator'), shopA = art('YPBShop');
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, 500, 500, 500, 500], 1000, 1000);
await shopC.waitForDeployment();
const CA = await shopC.getAddress(); console.log('YPBShop at', CA);
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: 'ypb.test.saasy.top', STAGING: '1', ADMIN_TOKEN: ADMIN, LINK_PROBE: '0', VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '50',
REVIEW_SAVES: '3', REPORT_HOLD: '2', CHAIN_ID: '31337', CHAIN_RPC: RPC, CONTRACT_ADDRESS: CA, KEEPER_KEY: K[1], SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '300', SPOTLIGHT_VIEWS: '1000',
HUB_URL: 'http://127.0.0.1:' + HPORT, HUB_SECRET, HUB_SITE: 'yourprogrambuilder', HUB_ENABLED: '0', HUB_SSO: 'off', NETWORK_LOOKUP_URL: '', NODE_ENV: 'test', LS_TRACK: '0', NETKB: '0', NETWORK_SITES_HUB: '0', AI_WRITER: '0', SWEEP_FIRST_MS: '600000' });
delete env.DOCSTORE_URL; delete env.OPENROUTER_API_KEY;
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 ['/', '/guides', '/guides/how-it-works', '/guides/is-it-legit', '/guides/free-account', '/guides/planting', '/guides/faq', '/my', '/spotlight', '/transplanted', '/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|Green Valley|Moody|35004|RM Circle|rmcircle/i.test(t), 'page ' + p + ' 200, no dashes, no address');
}
ok(/Disallow: \//.test(await (await fetch(BASE + '/robots.txt')).text()), 'staging robots.txt disallows everything');
const nf = await fetch(BASE + '/nothing/here'); ok(nf.status === 404 && /Nothing has sprouted here/.test(await nf.text()), 'not-found page in the site look');
const cfg = await (await fetch(BASE + '/api/config')).json();
ok(cfg.split.live === true && cfg.split.levelBps.join() === '2000,500,500,500,500' && cfg.spotlight.live === true && cfg.spotlight.usd === 10 && cfg.spotlight.views === 1000, 'config reads the live split and SKU from the contract', { split: cfg.split, sp: cfg.spotlight });
ok(cfg.reviewSaves === 3 && cfg.shop.live === true, 'config: review threshold and the shop is open on the local chain');
console.log('\n-- sign-in and membership');
const cO = client('Mozilla/5.0 planter'), cM1 = client('Mozilla/5.0 m1'), cM2 = client('Mozilla/5.0 m2'), cM3 = client('Mozilla/5.0 m3'), cB = client('Mozilla/5.0 buyer'), cN = client('Mozilla/5.0 nonmember'), cS = client('Mozilla/5.0 sponsor');
for (const [c, w] of [[cO, O], [cM1, M1], [cM2, M2], [cM3, M3], [cB, B], [cN, N], [cS, S]]) { 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 === 'planter', 'membership + username from the hub', me.j);
const meN = await cN.get('/api/me'); ok(meN.j.netVerified === false, 'a wallet the hub does not know is not a network member');
console.log('\n-- planting');
const base = { name: 'Harbor Lead Mailer', desc: 'A credit-based safelist mailer, free to join.', cost: 'free', cat: '13' };
let r = await cN.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref={id}', myId: 'nnn' }));
ok(r.status === 403, 'not a network member: planting refused', r.j);
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref=planter1' }));
ok(r.status === 400 && /\{id\}/.test(r.j.error), 'a link without {id} is refused', r.j);
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://www.adsearnltc.com/?r={id}', myId: 'p1' }));
ok(r.status === 400 && r.j.wild === true && /DownlineHydra/.test(r.j.error), 'a program already in the CTB builder is refused (save it on DownlineHydra)', r.j);
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://instantadpay.com/join/{id}', myId: 'p1' }));
ok(r.status === 400 && /network site/.test(r.j.error), 'a network site is refused', r.j);
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://bit.ly/{id}', myId: 'p1' }));
ok(r.status === 400 && /shortener/.test(r.j.error), 'a link shortener is refused', r.j);
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref={id}', myId: 'planter1', cost: 'paid' }));
ok(r.status === 400 && r.j.field === 'costText', 'a paid program needs its cost', r.j);
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref={id}', myId: 'planter1', contract: '0x123' }));
ok(r.status === 400 && r.j.field === 'contract', 'a bad contract address is refused', r.j);
r = await cO.post('/api/my/plant', Object.assign({}, base, { url: 'https://harbor.example.net/?ref={id}', myId: 'planter1' }));
ok(r.j.ok && r.j.created && r.j.packet.check === 'green' && r.j.packet.status === 'live', 'planted: link check green, live', r.j);
const P1 = r.j.packet.id;
r = await cO.post('/api/my/plant', Object.assign({}, base, { name: 'Second Program', url: 'https://other.example.net/r/{id}', myId: 'x' }));
ok(r.status === 400 && /most for one member/.test(r.j.error), 'quota: one packet per member at a time', r.j);
r = await cM1.post('/api/my/plant', Object.assign({}, base, { name: 'Harbor again', url: 'https://harbor.example.net/?ref={id}', myId: 'm1' }));
ok(r.status === 409 && r.j.packet === P1, 'the same program planted again points to the existing packet', r.j);
r = await cM3.post('/api/my/plant', { name: 'Orchard Ad Credits', desc: 'Guaranteed daily profit on every credit you buy, really.', cost: 'paid', costText: '$10 one-time', contract: '0x' + 'ab'.repeat(20), url: 'https://orchard.example.org/join/{id}', myId: 'm3', cat: '0' });
ok(r.j.ok && r.j.packet.check === 'yellow' && r.j.packet.status === 'held', 'income-claim words: planted but yellow, held for the queue', r.j);
const P3 = r.j.packet.id;
console.log('\n-- the Seed Bed and saved IDs');
let w = await cN.get('/api/wire?page=front');
ok(w.j.bed.length === 1 && w.j.bed[0].id === P1 && w.j.bed[0].saves === 1 && w.j.bed[0].need === 3, 'the bed shows the green packet only (the planter\'s ID counts as 1)', w.j.bed);
ok((await fetch(BASE + '/p/' + P3, { redirect: 'manual' })).status === 302, 'a held packet page is not public');
r = await cM1.post('/api/my/save', { packetId: P1, refId: 'not ok id!' }); ok(r.status === 400, 'a bad ID is refused');
r = await cO.post('/api/my/save', { packetId: P1, refId: 'x' }); ok(r.status === 400, 'the planter cannot save a second ID');
r = await cN.post('/api/my/save', { packetId: P1, refId: 'nn' }); ok(r.status === 403, 'not a network member: save refused');
r = await client('Mozilla/5.0 anon').post('/api/my/save', { packetId: P1, refId: 'nn' }); ok(r.status === 401, 'not signed in: save refused');
r = await cM1.post('/api/my/save', { packetId: P1, refId: 'memberone99' });
ok(r.j.ok && r.j.link === 'https://harbor.example.net/?ref=memberone99' && r.j.saves === 2 && !r.j.review, 'M1 saved an ID (2 of 3)', r.j);
console.log('\n-- the sponsor-first link');
let g = await client('Mozilla/5.0 anon2').get('/go/' + P1); ok(g.status === 302 && g.loc === 'https://harbor.example.net/?ref=planter1', 'anonymous visitor: the planter\'s link', g.loc);
const cV = client('Mozilla/5.0 visitor-of-m1');
const mp = await cV.get('/memberone'); ok(mp.status === 200 && cV.jar['ypb.ref'] === 'memberone', 'member page sets the ref tag', mp.status);
g = await cV.get('/go/' + P1); ok(g.loc === 'https://harbor.example.net/?ref=memberone99', 'a visitor through M1\'s page gets M1\'s link', g.loc);
g = await client('Mozilla/5.0 anon3').get('/go/' + P1 + '?r=memberone'); ok(g.loc === 'https://harbor.example.net/?ref=memberone99', '?r=memberone on the click link gives M1\'s link', g.loc);
g = await cM3.get('/go/' + P1); ok(g.loc === 'https://harbor.example.net/?ref=memberone99', 'M3 (line M2 -> M1) gets M1\'s link: M2 has not saved one', g.loc);
r = await cM2.post('/api/my/save', { packetId: P1, refId: 'https://www.harbor.example.net/?ref=twoTwo' });
ok(r.j.ok && r.j.refId === 'twoTwo' && r.j.saves === 3 && r.j.review === true, 'M2 pasted a whole link: the ID is taken from it; 3 of 3 -> review', r.j);
g = await cM3.get('/go/' + P1); ok(g.loc === 'https://harbor.example.net/?ref=twoTwo', 'now M3 gets M2\'s link (the nearest saved ID up the line)', g.loc);
w = await cM2.get('/api/wire?page=packet&id=' + P1);
ok(w.j.packet.stage === 'review' && w.j.mySave.refId === 'twoTwo' && w.j.packet.recent.includes('membertwo'), 'packet page: stage review, my saved ID, recent savers', w.j.packet);
const mw = await cV.get('/api/wire?page=member&u=memberone'); ok(mw.j.member && mw.j.member.packets.length === 1 && mw.j.member.packets[0].id === P1, 'member page lists M1\'s saved packets', mw.j.member);
r = await cM2.post('/api/my/save', { packetId: P1, refId: '' }); ok(r.j.removed && r.j.saves === 2, 'an ID can be removed (meter back to 2)', r.j);
r = await cM2.post('/api/my/save', { packetId: P1, refId: 'twoTwo' }); ok(r.j.saves === 3, 'saved again (3)');
console.log('\n-- review queue, transplant, export');
let q = await admin('/api/admin/queue');
ok(q.review.length === 1 && q.review[0].id === P1 && q.held.length === 1 && q.held[0].id === P3 && q.held[0].flags.includes('income claim words'), 'queue: P1 in review, P3 held with its flag', { review: q.review.map(x => x.id), held: q.held.map(x => [x.id, x.flags]) });
r = await admin('/api/admin/packet', { id: P3, action: 'approve' }); ok(r.error && /review/.test(r.error), 'only a packet in review can be approved');
r = await admin('/api/admin/packet', { id: P1, action: 'approve', note: 'Good fit for Mailers and Traffic' }); ok(r.ok && r.packet.stage === 'approved', 'P1 approved (transplanted)', r);
const ex = await admin('/api/admin/export?mark=1');
const e1 = ex.packets && ex.packets[0];
ok(ex.packets.length === 1 && e1.url === 'https://harbor.example.net/?ref={affiliateid}' && e1.ids.length === 3 && e1.ids.some(x => x.planter && x.refId === 'planter1' && x.hubId === 'h_' + '0'.repeat(16)) && e1.ids.some(x => x.username === 'memberone' && x.refId === 'memberone99') && e1.ids.some(x => x.username === 'membertwo' && x.refId === 'twoTwo'),
'export: the builder link with {affiliateid} and all 3 saved IDs with hub ids', e1);
ok((await admin('/api/admin/export')).packets.length === 0 && (await admin('/api/admin/export?all=1')).packets.length === 1, 'mark=1 stamps it exported; all=1 lists it again');
const tp = await (await fetch(BASE + '/api/transplanted')).json(); ok(tp.items.length === 1 && tp.items[0].id === P1, '/transplanted lists it');
r = await cO.post('/api/my/packet/remove', { id: P1 }); ok(r.status === 400, 'a transplanted packet cannot be removed by its planter');
r = await admin('/api/admin/packet', { id: P3, action: 'show' }); ok(r.ok && r.packet.status === 'live', 'Marty shows the yellow packet (approved for this exact text)');
r = await cM3.post('/api/my/plant', { id: P3, name: 'Orchard Ad Credits', desc: 'Guaranteed daily profit on every credit you buy, now more.', cost: 'paid', costText: '$10 one-time', contract: '0x' + 'ab'.repeat(20), url: 'https://orchard.example.org/join/{id}', myId: 'm3', cat: '0' });
ok(r.j.ok && r.j.packet.status === 'held', 'an edit of a shown yellow packet sends it back to the queue', r.j);
await admin('/api/admin/packet', { id: P3, action: 'show' });
console.log('\n-- reports');
r = await cM1.post('/api/report', { packetId: P3, reason: 'scam' }); ok(r.j.ok, 'M1 reported P3');
r = await cM1.post('/api/report', { packetId: P3, reason: 'scam' }); ok(r.j.already, 'a second report from the same member counts once');
r = await cM3.post('/api/report', { packetId: P3, reason: 'broken' }); ok(r.status === 400, 'a planter cannot report their own packet');
r = await cM2.post('/api/report', { packetId: P3, reason: 'broken', note: 'page 404' }); ok(r.j.ok, 'M2 reported P3');
q = await admin('/api/admin/queue'); ok(q.held.some(x => x.id === P3 && x.heldWhy === 'reported' && x.reports.length === 2), 'REPORT_HOLD reports hold the packet', q.held);
r = await admin('/api/admin/packet', { id: P3, action: 'show' }); ok(r.packet.status === 'live' && (await admin('/api/admin/queue')).held.length === 0, 'Marty clears the reports and shows it again');
console.log('\n-- verified visits');
const cF = client('Mozilla/5.0 fresh visitor');
let vv = await verifiedVisit(cF, 'front'); ok(vv.v && vv.v.verified === true && vv.v.views === 2 && vv.v.spotViews === 0, 'a verified front-page visit: 2 packet views, no Spotlight yet', vv.v);
const early = await cF.get('/api/wire?page=front'); const ev = await cF.post('/api/visit/seen', { ticket: early.j.ticket, visibleMs: 100 }); ok(ev.j.verified === false && ev.j.why === 'early', 'an early send is not verified');
const bot = await fetch(BASE + '/api/wire?page=front', { headers: { 'User-Agent': 'curl/8' } }).then(x => x.json()); ok(!bot.ticket, 'a bot gets no ticket');
console.log('\n-- a Spotlight on chain, to the wei');
r = await cB.post('/api/my/order', { qty: 1, packetId: 9999 }); ok(r.status === 400, 'a Spotlight needs a packet in the bed');
const od = await cB.post('/api/my/order', { qty: 1, packetId: P3 });
ok(od.j.to === CA && od.j.line === 2 && od.j.packetId === P3 && od.j.views === 1000, 'signed order for P3 with a 2-wallet line (no-wallet and blocked members 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, o0, s0, b0] = await Promise.all([company, O.address, S.address, B.address].map(a => bal(a, rc.blockNumber - 1)));
const [c1, o1, s1, b1] = await Promise.all([company, O.address, S.address, B.address].map(a => bal(a)));
const price = BigInt(od.j.wei); const l1 = price * 2000n / 10000n, l2 = price * 500n / 10000n;
ok(o1 - o0 === l1, 'O (level 1, the nearest eligible sponsor) got exactly 20% without buying anything', (o1 - o0).toString());
ok(s1 - s0 === l2, 'S (level 2) got exactly 5%', (s1 - s0).toString());
ok((await provider.getBalance(BL)) === 0n, 'the blocked member got nothing');
ok(c1 - c0 === price - l1 - l2, 'company got 60% + the 3 empty levels (75% in all)', (c1 - c0).toString());
ok(b0 - b1 === price + rc.gasUsed * rc.gasPrice, 'the 1% overpay came back in the same transaction');
ok((await provider.getBalance(CA)) === 0n, 'the contract holds nothing');
const replay = await B.sendTransaction({ to: od.j.to, data: od.j.data, value: od.j.value }).then(t => t.wait()).then(() => 'mined', e => 'reverted');
ok(replay === 'reverted', 'the same signed order cannot be used twice');
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 > 1) break; await sleep(250); }
const L = await (await fetch(BASE + '/api/ledger')).json(); const it = L.items[0];
ok(L.items.length === 1 && it.packet.id === P3 && it.pays.length === 3 && it.pays.some(p => p.kind === 1 && p.name === 'planter') && it.pays.some(p => p.kind === 2 && p.name === 'sponsors') && it.delivery.views === 1000, 'ledger: the split from the receipt and the delivery', it);
const ct = await (await fetch(BASE + '/api/contract')).json();
ok(ct.deployed && ct.live && ct.skuDelayHours === 48 && ct.split.levelBps.join() === '2000,500,500,500,500' && ct.sku.usdCents === 1000 && ct.company === company.toLowerCase(), 'contract page reads the chain (48 h SKU delay, split, SKU, company)', ct);
const my0 = await cO.get('/api/my'); ok(BigInt(my0.j.earned.wei) === l1 && my0.j.earned.items[0].kind === 1, 'O sees the level-1 payment on My packets', my0.j.earned);
console.log('\n-- Spotlight delivery (only the Spotlight places count)');
const cG = client('Mozilla/5.0 spotlight viewer');
vv = await verifiedVisit(cG, 'front'); ok(vv.w.j.spotlights.length === 1 && vv.w.j.spotlights[0].id === P3 && vv.v.spotViews === 1, 'the front page Spotlight row shows P3; a verified visit delivers 1 view', { s: vv.w.j.spotlights, v: vv.v });
const again = await verifiedVisit(cG, 'front'); ok(again.v.spotViews === 0, 'the same visitor again within 24 h: no second view');
const cQ = client('Mozilla/5.0 packet visitor');
vv = await verifiedVisit(cQ, 'packet', '&id=' + P3); ok(vv.v.spotViews === 0, 'P3\'s own packet page is not a Spotlight place (no delivery there)', vv.v);
vv = await verifiedVisit(cO, 'front'); ok(vv.v.spotViews === 1, 'a different member (not P3\'s planter) on the front page delivers a view');
vv = await verifiedVisit(cM3, 'front'); ok(vv.v.spotViews === 0, 'P3\'s planter never counts their own views');
const L2 = await (await fetch(BASE + '/api/ledger')).json(); ok(L2.items[0].delivery.delivered === 2, 'ledger delivery: 2 of 1,000', L2.items[0].delivery);
const pk = await (await fetch(BASE + '/api/packets')).json(); ok(pk.items.length === 2, '/api/packets (the Spotlight picker) lists the bed without a ticket');
const sf = await (await fetch(BASE + '/api/spotlight-feed')).json(); ok(sf.items.length === 1 && sf.items[0].id === P3, 'the DownlineHydra feed lists the delivering Spotlight');
console.log('\n-- old links and dormant old programs');
r = await admin('/api/admin/oldrefs', { oldrefs: { oldmember: 'memberone', 'bad key!': 'x' } }); ok(r.total === 1 && r.skipped === 1, 'oldrefs loaded (a bad key skipped)', r);
for (const [from, to] of [['/?oldmember', '/memberone'], ['/index.php?oldmember', '/memberone'], ['/splashpg.php?r=oldmember', '/memberone'], ['/lcp.php?r=oldmember', '/memberone'], ['/join.php?r=oldmember', '/memberone'], ['/login.php', '/my'], ['/faq.php', '/guides/faq'], ['/whatever.php', '/'], ['/?nobody', '/']]) {
const x = await fetch(BASE + from, { redirect: 'manual' }); ok(x.status === 301 && x.headers.get('location') === to, 'old link ' + from + ' -> ' + to, x.headers.get('location'));
}
r = await admin('/api/admin/dormant', { packets: [{ oldId: '10010', oldUsername: 'oldm2', hubId: 'h_' + '2'.repeat(16), name: 'Team Build Machine', url: 'https://teambuildmachine.example.com/oldm2', added: '2022-04-21' }, { oldId: 'x', hubId: 'h_1', name: 'bad', url: 'nope' }] });
ok(r.created === 1 && r.skipped === 1, 'dormant import: 1 created, a bad row skipped', r);
const my2 = await cM2.get('/api/my'); const dm = my2.j.dormant && my2.j.dormant[0];
ok(dm && dm.name === 'Team Build Machine', 'M2 (matched by hub id) sees the dormant old program', my2.j.dormant);
ok((await cM1.get('/api/my')).j.dormant.length === 0, 'nobody else sees it');
ok(!(await cN.get('/api/wire?page=front')).j.bed.some(x => x.name === 'Team Build Machine'), 'a dormant packet is not in the bed');
r = await cM1.post('/api/my/plant', { dormant: dm.id, name: 'Team Build Machine', desc: 'A team builder for any program you promote.', cost: 'free', url: 'https://teambuildmachine.example.com/{id}', myId: 'm1' });
ok(r.status === 404, 'someone else cannot confirm it');
r = await cM2.post('/api/my/plant', { dormant: dm.id, name: 'Team Build Machine', desc: 'A team builder for any program you promote.', cost: 'free', url: 'https://teambuildmachine.example.com/{id}', myId: 'oldm2' });
ok(r.j.ok && r.j.packet.id === dm.id && r.j.packet.status === 'live', 'M2 confirms it with a {id} link: live in the bed', r.j);
console.log('\n-- trust pack, chatbot, promo kit');
const rec = await (await fetch(BASE + '/api/recent')).json(); ok(['plant', 'save', 'review', 'spotlight'].every(k => rec.items.some(x => x.kind === k)), 'toasts feed: plants, saves, review and the Spotlight', rec.items.map(x => x.kind));
const ch = await (await fetch(BASE + '/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'How do I plant a program?' }) })).json();
ok(ch.reply && /\{id\}/.test(ch.reply) && !/[—–]/.test(ch.reply), 'chatbot answers planting from its canned knowledge', ch);
const ch2 = await (await fetch(BASE + '/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'What is a Spotlight?' }) })).json();
ok(ch2.reply && /SafePal or any other crypto wallet/.test(ch2.reply) && /20%/.test(ch2.reply), 'chatbot: Spotlight answer (wallet wording, split)', ch2.reply);
const kit = await (await fetch(BASE + '/api/promo-kit?u=memberone')).json(); ok(kit.links[0].url.endsWith('/memberone') && kit.lines.every(l => !/[—–]/.test(l)), 'promo kit: the member page link, no dashes');
const sm = await (await fetch(BASE + '/sitemap.xml')).text(); ok(sm.includes('/p/' + P1) && sm.includes('/guides/planting'), 'sitemap lists the guides and the packets');
console.log('\n-- staging test switch + admin');
r = await admin('/api/admin/test-member', { address: ethers.Wallet.createRandom().address, username: 'tester1' }); ok(r.ok && r.member.netOk && r.member.testMember, 'staging test switch marks a test network member');
ok((await fetch(BASE + '/api/admin/status')).status === 401, 'admin needs the token');
const st = await admin('/api/admin/status'); ok(st.packets.approved === 1 && st.packets.shown === 3 && st.shop.watching && st.oldrefs === 1, 'admin status', st.packets);
console.log('\n' + pass + ' passed, ' + fail + ' failed');
if (fail) { fs.writeFileSync(path.join(OUT, 'e2e-app.log'), log); console.log('app log: qa/out/e2e-app.log'); }
process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error(e); process.exit(1); });