Files
vbb/qa/chain.mjs
T

208 lines
24 KiB
JavaScript

// VBB real-contract test on a local anvil chain (no fork, nothing leaves this machine, no real POL).
// Deploys the real VBBShop (../contracts/out) with a mock Chainlink feed at $0.25, boots the app against it, and checks:
// buying: wallet sign-in -> POST /api/my/order -> the member's wallet sends buy() -> Purchase event -> credits on /api/my;
// the sponsor voucher binds on chain and the split lands (30 / 10 / 60), overpay refunded; the banner look (SKU 3).
// prizes: last week's leaderboards (seeded visits) -> prepare -> refuse while the prize wallet is short (says how much) ->
// fund it -> approve and pay -> exact POL per winner at the feed price, ties to the earlier, the prize wallet itself
// skipped -> a second approval refused -> /api/prizes lists the winners with their transactions.
// trust pack (2026-11-14): /api/ledger (each purchase with its real split from the receipt, prize payouts), /api/contract (live
// facts), the pages, and a stand-in Telegram API: one photo card per purchase, one line per prize payout, never twice.
// 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 crypto from 'node:crypto';
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 || 8561), PORT = Number(process.env.CHAIN_APP_PORT || 3231), HPORT = PORT + 1;
const RPC = 'http://127.0.0.1:' + APORT, BASE = 'http://127.0.0.1:' + PORT, ADMIN = 'chain-admin-token';
// anvil's public dev keys (local chain only)
const K = ['0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',
'0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a', '0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6'];
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) {} });
// Central-time week helpers (same as store.js)
const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
function ctWeek(ts) { const p = Object.fromEntries(fmt.formatToParts(new Date(ts)).map(x => [x.type, x.value])); const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0;
return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)).toISOString().slice(0, 10); }
const THIS_WEEK = ctWeek(Date.now()); const LAST_WEEK = new Date(Date.parse(THIS_WEEK + 'T12:00:00Z') - 7 * 86400000).toISOString().slice(0, 10);
const LW_AT = Date.parse(LAST_WEEK + 'T18:00:00Z'); // Monday noon CT of last week
// ---- stand-in Telegram Bot API (never the real group): records every call ----
const TPORT = PORT + 2; const tgCalls = [];
require('node:http').createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; let j = {}; try { j = JSON.parse(b || '{}'); } catch (e) {}
tgCalls.push({ method: q.url.split('/').pop(), token: q.url.split('/')[1], body: j }); r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify({ ok: true, result: { message_id: tgCalls.length } })); }).listen(TPORT, '127.0.0.1').unref();
// ---- stand-in hub: M's network sponsor is S ----
const people = new Map(); // wallet -> { id, username, sponsorWallet }
const HUB_SECRET = 'c'.repeat(40);
require('node: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');
let w = j.wallet ? String(j.wallet).toLowerCase() : j.id ? [...people.keys()].find(x => people.get(x).id === j.id) : null;
const p = w && people.get(w); const sp = p && p.sponsorWallet && people.get(p.sponsorWallet);
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 })); }).listen(HPORT, '127.0.0.1').unref();
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 M = new ethers.Wallet(K[3], provider); // the buying member
const S = ethers.Wallet.createRandom().address.toLowerCase(); // M's network sponsor
const company = ethers.Wallet.createRandom().address;
const P = ethers.Wallet.createRandom(); // the prize wallet (starts empty)
people.set(M.address.toLowerCase(), { id: 'h_' + 'a'.repeat(16), username: 'buyerm', sponsorWallet: S }); people.set(S, { id: 'h_' + 'b'.repeat(16), username: 'sponsors' });
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
let nonce = await provider.getTransactionCount(deployer.address);
const feedA = art('MockV3Aggregator'); const feed = await new ethers.ContractFactory(feedA.abi, feedA.bytecode.object, deployer).deploy(25000000n, { nonce: nonce++ }); await feed.waitForDeployment();
const shopA = art('VBBShop'); const shopC = await new ethers.ContractFactory(shopA.abi, shopA.bytecode.object, deployer).deploy(company, P.address, keeper.address, await feed.getAddress(), { nonce: nonce++ }); await shopC.waitForDeployment();
for (const [id, c, cr] of [[1, 300, 10], [2, 1000, 40], [3, 200, 0]]) await (await shopC.setSku(id, c, cr, true, { nonce: nonce++ })).wait();
const SHOP = await shopC.getAddress();
console.log('anvil', RPC, 'VBBShop', SHOP, 'prize wallet', P.address, 'weeks', LAST_WEEK, THIS_WEEK);
// ---- seed last week: members, visits (leaderboards), one $3 sale ----
const W = Array.from({ length: 4 }, () => ethers.Wallet.createRandom().address.toLowerCase());
const members = {}; const mem = (a, u) => { members[a] = { address: a, username: u, joinedAt: LW_AT, credits: 0, freeDay: null, via: 'wallet' }; };
W.forEach((a, i) => mem(a, 'winner' + (i + 1))); mem(P.address.toLowerCase(), 'prizewallet');
const visits = []; let vid = 0; const at = h => LW_AT + h * 3600000;
const V = (ref, h, src) => visits.push({ id: 'v' + (++vid), at: at(h), vk: 'k' + vid, iph: 'i' + vid, ref, src: src || '', wk: LAST_WEEK, day: LAST_WEEK });
for (let i = 0; i < 9; i++) V(P.address.toLowerCase(), i, 'p' + i + '.example'); // the prize wallet tops both boards: skipped
for (let i = 0; i < 5; i++) V(W[0], 10 + i, i < 2 ? 'a' + i + '.example' : ''); // W1: 5 visitors, 2 sources
V(W[1], 20); V(W[1], 21); V(W[1], 40, 'b.example'); // W2: 3 visitors (3rd at h40), 1 source at h40
V(W[2], 22); V(W[2], 23); V(W[2], 30); // W3: 3 visitors (3rd at h30, earlier than W2)
V(W[3], 35, 'd.example'); // W4: 1 visitor, 1 source at h35 (earlier than W2)
const doc = { v: 1, seq: { banner: 0, ledger: 0, visit: vid }, loop: [], queue: [], progress: 0, totals: { shifts: 0, cycles: 0, visits: vid, posts: 0, views: 0 }, daily: {}, members, sessions: {},
banners: [], ledger: [], visits, purchases: { ['0x' + '99'.repeat(32) + ':0']: { at: at(50), blockAt: Math.floor(at(50) / 1000), block: 0, orderId: 0, buyer: W[0], sku: 1, qty: 1, ref: '0', credits: 10, usdCents: 300, weiPaid: '0', sponsor: ethers.ZeroAddress, sponsorPaid: '0', applied: 'credits' } } };
fs.writeFileSync(path.join(DATA, 'vbb.json'), JSON.stringify(doc));
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: '',
CHAIN_ID: '31337', CONTRACT_ADDRESS: SHOP, CHAIN_RPC: RPC, KEEPER_KEY: K[1], SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '300',
PRIZE_KEY: P.privateKey, PRIZE_WALLET: P.address, PRIZE_RECEIPT_MS: '300', EXPLORER: 'https://explorer.invalid',
HUB_URL: 'http://127.0.0.1:' + HPORT, HUB_SECRET, HUB_SITE: 'vbb', HUB_ENABLED: '0',
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TPORT });
const log = fs.openSync(path.join(OUT, 'chain-server.log'), 'w');
const srv = spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', log, log] }); procs.push(srv);
for (let i = 0; i < 80; i++) { try { if ((await fetch(BASE + '/health')).ok) break; } catch (e) {} await sleep(150); }
const jar = {}; const call = async (p, body, hdr) => { const r = await fetch(BASE + p, { method: body === undefined ? 'GET' : 'POST', headers: Object.assign({ 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 ChainTest', Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, hdr || {}), 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 adm = (p, body) => call(p, body, { 'x-admin-token': ADMIN });
console.log('1. buying on the real contract');
const ch = await call('/api/auth/challenge', { address: M.address }); const vr = await call('/api/auth/verify', { address: M.address, signature: await M.signMessage(ch.message) });
ok(vr.ok, 'member signs in with their wallet');
const q = await call('/api/quote?sku=1&qty=1');
ok(q._status === 200 && BigInt(q.wei) === 300n * 10n ** 24n / 25000000n, 'quote = quoteWei from the contract: $3 at $0.25 = 12 POL', q);
const before = (await call('/api/my')).credits;
const sBal0 = await provider.getBalance(S), pBal0 = await provider.getBalance(P.address), cBal0 = await provider.getBalance(company), mBal0 = await provider.getBalance(M.address);
const od = await call('/api/my/order', { sku: 1, qty: 1 });
ok(od._status === 200 && od.sponsor === true, 'order carries a sponsor voucher (the hub knows the sponsor)', od);
const tx = await M.sendTransaction({ to: od.to, data: od.data, value: BigInt(od.value) }); const rc = await tx.wait();
ok(rc.status === 1, 'the member\'s buy() transaction succeeds on chain');
const txr = await call('/api/tx/' + tx.hash); ok(txr.found && txr.status === '0x1', '/api/tx sees the receipt', txr);
await call('/api/my/paid', {});
let my; for (let i = 0; i < 40; i++) { my = await call('/api/my'); if (my.credits >= before + 10) break; await sleep(200); }
ok(my.credits === before + 10, 'the Purchase event credits 10 post credits', { before, after: my.credits });
const wei = BigInt(q.wei);
ok(await shopC.sponsorOf(M.address) === ethers.getAddress(S), 'the voucher bound the network sponsor on chain');
ok((await provider.getBalance(S)) - sBal0 === wei * 3000n / 10000n && (await provider.getBalance(P.address)) - pBal0 === wei * 1000n / 10000n
&& (await provider.getBalance(company)) - cBal0 === wei - wei * 3000n / 10000n - wei * 1000n / 10000n, 'split: 30% sponsor, 10% prize wallet, 60% company');
const gasPaid = rc.gasUsed * rc.gasPrice; ok(mBal0 - (await provider.getBalance(M.address)) === wei + gasPaid, 'the 1% overpay came back in the same transaction (paid exactly the price + gas)');
// banner look: M posts a banner then buys the look
const zlib = require('node:zlib'); 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(125, 0); ihdr.writeUInt32BE(125, 4); ihdr[8] = 8; ihdr[9] = 2; const raw = Buffer.alloc((125 * 3 + 1) * 125, 90);
for (let y = 0; y < 125; y++) raw[y * (125 * 3 + 1)] = 0;
const img = 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))]);
const up = await fetch(BASE + '/api/my/upload', { method: 'POST', headers: { 'Content-Type': 'application/octet-stream', 'User-Agent': 'Mozilla/5.0 ChainTest', Cookie: 'vbb.sid=' + jar['vbb.sid'] }, body: img }).then(r => r.json());
const pb = await call('/api/my/banners', { img: up.img, link: 'https://example-member.com/x' }); const bid = pb.banner && pb.banner.id;
ok(!!bid, 'member posts a banner with a bought credit', bid);
const lo = await call('/api/my/order', { sku: 3, ref: bid });
const ltx = await M.sendTransaction({ to: lo.to, data: lo.data, value: BigInt(lo.value) }); ok((await ltx.wait()).status === 1, 'banner look buy(3, 1, banner id) succeeds on chain');
let look = false; for (let i = 0; i < 40 && !look; i++) { const d = await call('/api/my'); look = (d.banners || []).some(b => b.id === bid && b.look); if (!look) await sleep(200); }
ok(look, 'the watcher gives that banner the look');
const spl = await call('/api/splash'); ok([...spl.loop, ...spl.queue].some(t => t.id === bid && t.look && t.teaser === 'example-member.com'), 'the loop shows it with the border + teaser');
console.log('1b. trust pack: ledger, contract, pages, Telegram cards');
const share = w => ({ sp: w * 3000n / 10000n, pz: w * 1000n / 10000n, co: w - w * 3000n / 10000n - w * 1000n / 10000n });
let led; for (let i = 0; i < 40; i++) { led = await call('/api/ledger?n=50'); const x = (led.items || []).find(y => y.tx === tx.hash.toLowerCase()); if (x && x.pays && x.pays.length === 3 && x.pays[0].role === 'sponsor') break; await sleep(200); }
const it1 = (led.items || []).find(x => x.tx === tx.hash.toLowerCase()); const sh = share(wei);
ok(it1 && it1.kind === 'purchase' && it1.what === '10 post credits' && it1.usdCents === 300, 'ledger lists the pack purchase', it1);
const pz = it1 && Object.fromEntries(it1.pays.map(x => [x.role, x]));
ok(pz && pz.sponsor && pz.sponsor.to === S && BigInt(pz.sponsor.wei) === sh.sp && BigInt(pz.prize.wei) === sh.pz && BigInt(pz.company.wei) === sh.co && pz.prize.to === P.address.toLowerCase(),
'ledger split from the receipt: 30% to the sponsor, 10% prize wallet, 60% company (exact wei)', it1 && it1.pays);
ok(led.totals && led.totals.purchases === 3 && BigInt(led.totals.sponsorWei) === BigInt(led.totals.weiPaid) * 3000n / 10000n, 'ledger totals: 3 purchases (seeded + 2), sponsor POL = 30% of both sponsored purchases', led.totals);
ok((led.items || []).some(x => x.kind === 'purchase' && x.what === 'the banner look'), 'ledger names the banner look purchase', led.items && led.items.map(x => x.what));
const cf = await call('/api/contract');
ok(cf.live === true && cf.owner === deployer.address.toLowerCase() && cf.prizeWallet === P.address.toLowerCase() && cf.company === company.toLowerCase() && cf.keeper === keeper.address.toLowerCase()
&& cf.paused === false && cf.orderCount === 2 && cf.balanceWei === '0' && cf.split.sponsorPct === 30 && cf.split.prizePct === 10 && cf.split.companyPct === 60 && cf.verified.sourcify === true,
'/api/contract reads the live facts (owner, prize wallet, company, keeper, 2 orders, holds 0)', cf);
for (const pg of ['/contract', '/ledger', '/terms', '/disclaimer', '/privacy']) { const r2 = await fetch(BASE + pg); const h = await r2.text();
ok(r2.status === 200 && /common\.js\?v=\d+/.test(h) && !h.includes('—'), pg + ' serves (no em dashes)'); }
const legal = (await (await fetch(BASE + '/terms')).text()) + (await (await fetch(BASE + '/disclaimer')).text()) + (await (await fetch(BASE + '/privacy')).text());
ok(legal.includes('TrustClickz, 615 Green Valley Drive, Moody, AL 35004') && /ever billed again/.test(legal) && /final once confirmed/.test(legal) && /not an investment/.test(legal) && /network hub/.test(legal) && !/\$50|cap/i.test(legal.replace(/capture|capital|escape/gi, '')),
'legal pages: TrustClickz, one-time purchases, no refunds on-chain, not an investment, the hub, no prize cap');
const ns = await call('/api/network-sites'); const nl = Object.keys(ns).filter(k => /^\d+$/.test(k)).map(k => ns[k]);
ok(nl.length === 6 && nl.map(x => x.name).join(',') === 'InstantAdPay,LinkSpin,Downline Banners,Viral Banner Blitz,Stack POL,Earners Corner', '/api/network-sites: the six network sites (fallback list when the hub has none)', nl.map(x => x.name));
let photos = []; for (let i = 0; i < 40; i++) { photos = tgCalls.filter(c => c.method === 'sendPhoto'); if (photos.length >= 2) break; await sleep(200); }
const c1 = photos.find(c => String(c.body.caption).includes(tx.hash.toLowerCase()));
ok(photos.length === 2 && photos.every(c => c.token === 'botstandin-token' && c.body.chat_id === '-100123' && c.body.message_thread_id === 632242 && c.body.parse_mode === 'HTML' && /\/art\/proof\/vbb-proof-(pink|blue|yellow)\.png$/.test(c.body.photo)),
'one Telegram photo card per purchase (2), to the payments topic, with a proof image', photos.map(c => [c.token, c.body.chat_id, c.body.message_thread_id, c.body.photo]));
ok(photos.length === 2 && photos[0].body.photo !== photos[1].body.photo, 'the card image rotates between posts');
ok(c1 && /@buyerm bought 10 post credits · \$3\.00 \(12\.0000 POL\)/.test(c1.body.caption) && c1.body.caption.includes('Sponsor 30%: 3.6000 POL → @sponsors') && c1.body.caption.includes('Weekly prize pot 10%: 1.2000 POL')
&& c1.body.caption.includes('Viral Banner Blitz: 7.2000 POL') && /This week: \d+ purchases?, \$[\d.]+ · prize pot \$[\d.]+/.test(c1.body.caption) && c1.body.caption.includes('https://explorer.invalid/tx/' + tx.hash.toLowerCase()) && !c1.body.caption.includes('—'),
'card caption: buyer, sponsor + prize + company split in POL, this week\'s stats, verify link', c1 && c1.body.caption);
await call('/api/my/paid', {}); await sleep(1500); // more watcher scans
ok(tgCalls.filter(c => c.method === 'sendPhoto').length === 2, 'rescans never post the same purchase twice');
console.log('2. weekly prize payout (last week: ' + LAST_WEEK + ')');
let ap, plan; for (let i = 0; i < 40; i++) { ap = await adm('/api/admin/prizes'); plan = (ap.weeks || []).find(w => w.week === LAST_WEEK); if (plan) break; await sleep(250); }
ok(plan && plan.status === 'prepared', 'the app prepared last week by itself', ap.weeks && ap.weeks.map(w => w.week + ':' + w.status));
const names = b => plan.transfers.filter(t => t.board === b).map(t => t.name + '=' + t.usd).join(',');
ok(plan && plan.salesUsd === 3 && plan.potUsd === 20 && plan.atFloor && plan.topUpUsd === 19.7, 'pot: $3 of sales, 10% = $0.30, floor $20 (company tops up $19.70)', plan && { s: plan.salesUsd, p: plan.potUsd, t: plan.topUpUsd });
ok(plan && names('visitors') === '@winner1=5,@winner3=3,@winner2=2', 'visitors board: the prize wallet skipped, tie 3-3 goes to whoever reached it first', plan && names('visitors'));
ok(plan && names('sources') === '@winner1=5,@winner4=3,@winner2=2', 'sources board: 2 sources first, then the 1-source tie by time', plan && names('sources'));
ok(plan && plan.quote && plan.quote.keyMatches === true && plan.quote.priceUsd === 0.25 && plan.quote.totalPol === '80.0000', 'quote: the key is the prize wallet, $0.25 POL, 80 POL to pay', plan && plan.quote);
ok(plan && BigInt(plan.quote.shortWei) > 0n, 'the prize wallet (1.2 POL from the sale) is short');
let pay = await adm('/api/admin/prizes/pay', { week: LAST_WEEK, confirm: LAST_WEEK });
ok(pay._status === 400 && /send at least [\d.]+ POL more to/.test(pay.error), 'paying refuses and says how much POL to send', pay.error);
ok((await provider.getTransactionCount(P.address)) === 0, 'nothing was sent');
await provider.send('anvil_setBalance', [P.address, '0x' + (100n * 10n ** 18n).toString(16)]);
const wb = await Promise.all(W.map(a => provider.getBalance(a)));
pay = await adm('/api/admin/prizes/pay', { week: LAST_WEEK, confirm: LAST_WEEK });
ok(pay._status === 200 && pay.ok && pay.plan.transfers.every(t => t.tx), 'approve and pay: 6 transfers sent', pay.error || pay.plan && pay.plan.status);
for (let i = 0; i < 40; i++) { ap = await adm('/api/admin/prizes'); plan = ap.weeks.find(w => w.week === LAST_WEEK); if (plan.status === 'paid') break; await sleep(250); }
ok(plan.status === 'paid' && plan.transfers.every(t => t.status === 'confirmed'), 'every transfer confirmed: the week is paid', plan.status);
const wa = await Promise.all(W.map(a => provider.getBalance(a))); const pol = n => BigInt(n) * 10n ** 18n;
ok(wa[0] - wb[0] === pol(40) && wa[2] - wb[2] === pol(12) && wa[1] - wb[1] === pol(16) && wa[3] - wb[3] === pol(12), 'exact POL at $0.25: winner1 $10 = 40, winner2 $4 = 16, winner3 $3 = 12, winner4 $3 = 12', wa.map((x, i) => ethers.formatEther(x - wb[i])));
pay = await adm('/api/admin/prizes/pay', { week: LAST_WEEK, confirm: LAST_WEEK }); ok(pay._status === 400 && /paid once/.test(pay.error), 'a second approval is refused: a week is paid once', pay.error);
const n6 = await provider.getTransactionCount(P.address); ok(n6 === 6, 'the prize wallet sent exactly 6 transactions', n6);
let r = await adm('/api/admin/prizes/prepare', { week: LAST_WEEK }); ok(r.status === 'paid', 'preparing a paid week again changes nothing', r.status);
const pub = await call('/api/prizes'); const lw = (pub.past || [])[0];
ok(lw && lw.week === LAST_WEEK && lw.winners.length === 6 && lw.winners.every(x => x.tx && x.confirmed && x.pol) && pub.explorer === 'https://explorer.invalid' && !JSON.stringify(pub).includes(P.privateKey.slice(2, 12)), 'public /api/prizes lists the winners with their transactions (never the key)', lw);
let lines = []; for (let i = 0; i < 40; i++) { lines = tgCalls.filter(c => c.method === 'sendMessage' && /weekly prize/.test(c.body.text)); if (lines.length >= 6) break; await sleep(200); }
ok(lines.length === 6 && lines.every(c => c.body.message_thread_id === 632242 && /POL \(\$\d+\.\d\d\)/.test(c.body.text) && /explorer\.invalid\/tx\/0x[0-9a-f]{64}/.test(c.body.text))
&& new Set(lines.map(c => c.body.text.match(/tx\/(0x[0-9a-f]{64})/)[1])).size === 6, 'one Telegram line per confirmed prize payout (6), each with its own transaction', lines.map(c => c.body.text.split('\n')[1]));
ok(lines.some(c => c.body.text.includes('@winner1 · 1st place, most verified visitors') && c.body.text.includes('20.0000 POL ($5.00)')), 'prize line names the winner, place, board and amount', lines.map(c => c.body.text.split('\n')[1]));
const led2 = await call('/api/ledger?n=50'); ok((led2.items || []).filter(x => x.kind === 'prize' && x.confirmed).length === 6 && led2.totals.prizePayouts === 6, 'the ledger lists the 6 prize payouts with their transactions', led2.totals);
const st = await adm('/api/admin/status'); ok(!JSON.stringify(st).includes(P.privateKey.slice(2, 12)) && st.prize && st.prize.keyAddress === P.address.toLowerCase(), 'admin status shows the prize wallet, never its key');
ok(st.proof && st.proof.telegram === true && st.proof.posted === 2 && st.proof.prizeLines === 6 && !JSON.stringify(st).includes('standin-token'), 'admin status shows the proof posts, never the bot token', st.proof);
srv.kill(); an.kill();
console.log('\n' + pass + ' passed, ' + fail + ' failed');
process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error('chain test crashed:', e.stack || e.message); process.exit(1); });