VBB purchases live + weekly prize payouts (Marty 2026-11-14: "why does it say 'coming soon' on all the stuff in it? Shouldn't it all be live already?")

Buying (VBBShop 0x36F6...07D7): Packages page has live Buy buttons for the 10 and 40 credit packs (USD price + live POL from quoteWei, SafePal or any other crypto wallet, one-time, never a subscription, where the payment goes); My Banners has "Add the banner look ($2)" on each waiting or in-loop banner (SKU 3, ref = banner id) and a 40-character teaser editor once it has the look. POST /api/my/order builds the member's buy() call on the server (fresh keeper voucher when the hub knows their sponsor, else no sponsor); the page checks the connected wallet is the member's VBB account (explains how to switch if not), checks the balance, sends with Polygon's fee floor (/api/gas), waits on /api/tx, nudges the watcher (/api/my/paid) and polls until the credits or the look arrive. Public: /api/quote, /api/gas, /api/tx/<hash>; /api/config has shop {live, contract} + explorer. The banner look on the loop: double border + star, hover teaser (always shown on touch screens; default = the link's site). Only Tokens still says coming soon. wallet.js gains sendTx/waitTx/balance (DLB flow).

Weekly prize payouts (prize.js): each Central-time week's pot = 10% of its VBBShop sales (usdCents of Purchase events by block time), $20 floor (company top-up shown to admin), $50 cap internal, half per board, 50/30/20. Every Monday the app prepares last week's plan (winners, wallets, USD; POL quoted live from the Chainlink feed the contract uses). /admin "Approve and pay" (two clicks): refuses unless PRIZE_KEY is the contract's prizeWallet(), the feed is fresh and the wallet holds the POL + gas (says how much more to send); then once per week (docstore.claim in MySQL + plan status), consecutive nonces, each hash saved as sent, stops at the first unclear send (never auto-retried), receipts watched. Ties: earlier to reach the count wins (leaderboards use the same rule). A winner that cannot be paid (the prize or company wallet) is skipped and the rest move up; an unfilled place stays in the prize wallet. /leaders shows past winners with transaction links. Posts nothing anywhere. Compose passes PRIZE_KEY.

Tests: smoke 192/192 (stand-in chain answers quoteWei + receipts: quote, order calldata + voucher, look purchase, teaser, prizes API, UI Buy buttons). New qa/chain.mjs on a local anvil with the real VBBShop + mock feed: buy -> Purchase -> credits, voucher binds sponsor, 30/10/60 split, overpay refunded, banner look; prize prepare -> short refusal -> pay 6 transfers exact POL -> paid once: 29/29. common.js?v=3, vbb.css?v=4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-14 09:47:58 -06:00
parent a6a9b3cace
commit aee1ccc36a
27 changed files with 866 additions and 79 deletions
+161
View File
@@ -0,0 +1,161 @@
// 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.
// 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 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' });
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('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);
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');
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); });
+68 -7
View File
@@ -30,10 +30,16 @@ require('node:http').createServer((q, r) => { const a = (new URL(q.url, 'http://
r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify(NET.has(a) ? { address: a, username: 'net' + a.slice(2, 10), sponsor: NETSP.get(a) || null } : {})); }).listen(LOOKUP_PORT, '127.0.0.1').unref();
// stand-in Polygon JSON-RPC for the purchase watcher: CHAIN.logs are served by block range (or all of them when replayAll is on,
// like a flaky RPC re-sending old logs). Nothing here is a real chain.
const CHAIN = { head: 1, logs: [], replayAll: false }; const CHAIN_PORT = PORT + 2;
const CHAIN = { head: 1, logs: [], replayAll: false, receipts: {} };
const QUOTE_SEL = ethers.id('quoteWei(uint256,uint256)').slice(0, 10); const CHAIN_PORT = PORT + 2;
const SHOP = '0x00000000000000000000000000000000000B0B05', KEEPER_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d'; // anvil's public test key #1
require('node:http').createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; const j = JSON.parse(b || '{}'); let result = null;
if (j.method === 'eth_blockNumber') result = '0x' + CHAIN.head.toString(16);
// quoteWei(sku, qty): $ cents x qty at a stand-in POL price of $0.25 (1 cent = 0.04 POL); a receipt for any hash in CHAIN.receipts
if (j.method === 'eth_call') { const d = j.params[0].data || ''; if (d.startsWith(QUOTE_SEL)) { const sku = Number(BigInt('0x' + d.slice(10, 74))), qty = Number(BigInt('0x' + d.slice(74, 138)));
const cents = { 1: 300, 2: 1000, 3: 200 }[sku] || 0; result = '0x' + (BigInt(cents * qty) * 4n * 10n ** 16n).toString(16).padStart(64, '0'); } }
if (j.method === 'eth_getTransactionReceipt') result = CHAIN.receipts[j.params[0]] || null;
if (j.method === 'eth_maxPriorityFeePerGas') result = '0x' + (40n * 10n ** 9n).toString(16);
if (j.method === 'eth_getLogs') { const f = j.params[0], lo = parseInt(f.fromBlock, 16), hi = parseInt(f.toBlock, 16); result = CHAIN.logs.filter(l => CHAIN.replayAll || (parseInt(l.blockNumber, 16) >= lo && parseInt(l.blockNumber, 16) <= hi)); }
r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, result })); }).listen(CHAIN_PORT, '127.0.0.1').unref();
// stand-in network hub: records the signed reports (contract-bind / contract-spend), checks each signature, and answers
@@ -140,7 +146,7 @@ async function main() {
const cfg = await (await fetch(BASE + '/api/config')).json();
ok(cfg.loopSize === 5 && cfg.perShift === 3 && cfg.viewsPerCycle === 150 && cfg.visitSeconds === 2, 'config from env', cfg);
ok(fs.readFileSync(path.join(OUT, 'server.log'), 'utf8').includes('files (prototype mode)'), 'server says prototype mode (no DOCSTORE_URL)');
ok(JSON.stringify(cfg.packs) === '[{"credits":10,"usd":3},{"credits":40,"usd":10}]' && cfg.lookUsd === 2 && cfg.freeCreditsPerDay === 1, 'approved defaults: packs 10 for $3 + 40 for $10, look $2, 1 free credit a day', cfg);
ok(JSON.stringify(cfg.packs) === '[{"credits":10,"usd":3,"sku":1},{"credits":40,"usd":10,"sku":2}]' && cfg.lookUsd === 2 && cfg.lookSku === 3 && cfg.freeCreditsPerDay === 1, 'approved defaults: packs 10 for $3 + 40 for $10, look $2, 1 free credit a day', cfg);
ok(cfg.prizes && cfg.prizes.pot === 20 && JSON.stringify(cfg.prizes.visitors) === '[5,3,2]' && JSON.stringify(cfg.prizes.sources) === '[5,3,2]', 'prize pot: $20 floor with no sales, $5/$3/$2 per board', cfg.prizes);
ok(!JSON.stringify(cfg).includes('capUsd') && !JSON.stringify(cfg).includes('"cap'), 'public config never shows the prize cap', cfg);
@@ -369,16 +375,65 @@ async function main() {
// restart: the dedupe marks survive, the replaying RPC still credits nothing
await sleep(1200); await stop(); await boot(); await sleep(900);
my = await V.json('/api/my'); ok(my.credits === credits0 + 60, 'after a restart the replayed logs still credit nothing', my.credits);
const cfgNow = await (await fetch(BASE + '/api/config')).json(); ok(!JSON.stringify(cfgNow).toLowerCase().includes(SHOP.slice(2).toLowerCase()), 'public config does not offer the contract yet (packages stay coming soon)');
const cfgNow = await (await fetch(BASE + '/api/config')).json(); ok(cfgNow.shop && cfgNow.shop.live === true && cfgNow.shop.contract === ethers.getAddress(SHOP), 'public config offers the shop (purchases live)', cfgNow.shop);
// ---- 12a. buying: quote, the member's buy() call, the banner look, the teaser ----
console.log('12a. buying: quote, order, banner look, teaser');
const BUY_IF = new ethers.Interface(['function buy(uint256 sku, uint256 qty, uint256 ref, address sponsor, uint256 deadline, bytes sig) payable returns (uint256)']);
let qt = await anon.json('/api/quote?sku=1&qty=1');
ok(qt._status === 200 && qt.wei === (300n * 4n * 10n ** 16n).toString() && qt.sendWei === (BigInt(qt.wei) + BigInt(qt.wei) / 100n).toString() && qt.usd === 3, 'quote: quoteWei from the contract, +1% to send, $3', qt);
qt = await anon.json('/api/quote?sku=9&qty=1'); ok(qt._status === 400, 'quote: unknown package refused');
qt = await anon.json('/api/quote?sku=3&qty=2'); ok(qt._status === 400, 'quote: one banner look at a time');
r = await anon.req('/api/my/order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"sku":1}' }); ok(r.status === 401, 'order needs sign-in');
let od = await V.json('/api/my/order', { sku: 2, qty: 1 });
let dec = od.data ? BUY_IF.decodeFunctionData('buy', od.data) : null;
ok(od._status === 200 && od.to === ethers.getAddress(SHOP) && od.buyer === V.address && BigInt(od.value) === BigInt(od.sendWei) && od.sponsor === true && dec && Number(dec[0]) === 2 && Number(dec[1]) === 1 && Number(dec[2]) === 0 && dec[3].toLowerCase() === spW,
'order: buy(2, 1, 0, sponsor, deadline, sig) for the member, with the hub sponsor', od);
ok(dec && ethers.verifyTypedData(vdom, vt, { buyer: ethers.getAddress(V.address), sponsor: dec[3], deadline: dec[4] }, dec[5]) === keeperAddr, 'order: the voucher inside the call is the keeper\'s EIP-712 signature');
od = await A.json('/api/my/order', { sku: 1, qty: 1 }); dec = od.data ? BUY_IF.decodeFunctionData('buy', od.data) : null;
ok(od._status === 200 && od.sponsor === false && od.why === 'no-sponsor' && dec && dec[3] === ethers.ZeroAddress && dec[5] === '0x', 'order: no network sponsor = buy without a voucher (zero sponsor, empty sig)', od);
od = await V.json('/api/my/order', { sku: 1, qty: 11 }); ok(od._status === 400, 'order: at most 10 packs');
// banner look: V posts a banner, orders the look for it; a stranger's banner and a cycled banner are refused
const vb = await postBanner(V, 7); const vbId = vb.banner && vb.banner.id;
od = await V.json('/api/my/order', { sku: 3, ref: vbId }); dec = od.data ? BUY_IF.decodeFunctionData('buy', od.data) : null;
ok(od._status === 200 && dec && Number(dec[0]) === 3 && Number(dec[2]) === vbId && od.usd === 2, 'order: banner look = buy(3, 1, banner id)', od);
od = await A.json('/api/my/order', { sku: 3, ref: vbId }); ok(od._status === 400 && /not yours/.test(od.error), 'order: a look for someone else\'s banner is refused', od);
r = await V.json('/api/my/banners/' + vbId + '/teaser', { teaser: 'Hello' }); ok(r._status === 400, 'teaser needs the look first', r);
CHAIN.replayAll = false;
CHAIN.logs.push(mkLog({ orderId: 3, buyer: V.address, sku: 3, qty: 1, ref: vbId, credits: 0, usdCents: 200, wei: 8n * 10n ** 18n, sponsor: spW, sponsorPaid: 24n * 10n ** 17n, block: 14, tx: '0x' + 'ef'.repeat(32), logIndex: 1 }));
CHAIN.head = 15; await sleep(900);
my = await V.json('/api/my'); const lkb = (my.banners || []).find(x => x.id === vbId);
ok(lkb && lkb.look === true && lkb.teaser === "" && lkb.teaserDefault === "example-member.com", "a banner-look Purchase gives that banner the look", lkb);
od = await V.json('/api/my/order', { sku: 3, ref: vbId }); ok(od._status === 400 && /already/.test(od.error), 'order: a second look for the same banner is refused', od);
let spl = await anon.json('/api/splash'); let lt = [...spl.loop, ...spl.queue].find(x => x.id === vbId);
ok(lt && lt.look === true && lt.teaser === 'example-member.com', 'the loop shows the look, teaser = the link\'s site until the member writes one', lt);
r = await V.json('/api/my/banners/' + vbId + '/teaser', { teaser: ' Free <b>traffic</b> tools\n inside ' });
ok(r.ok && r.teaser === 'Free btraffic/b tools inside', 'teaser saved as plain text (no tags, one line)', r);
r = await V.json('/api/my/banners/' + vbId + '/teaser', { teaser: 'x'.repeat(41) }); ok(r._status === 400, 'teaser: 40 characters at most');
r = await A.json('/api/my/banners/' + vbId + '/teaser', { teaser: 'mine now' }); ok(r._status === 404, 'teaser: only the owner');
spl = await anon.json('/api/splash'); lt = [...spl.loop, ...spl.queue].find(x => x.id === vbId); ok(lt && lt.teaser === 'Free btraffic/b tools inside', 'the loop shows the member\'s teaser', lt);
CHAIN.receipts['0x' + '12'.repeat(32)] = { status: '0x1', blockNumber: '0xe', to: SHOP, from: V.address };
r = await anon.json('/api/tx/0x' + '12'.repeat(32)); ok(r.found === true && r.status === '0x1', '/api/tx answers a receipt', r);
r = await anon.json('/api/tx/0x' + '34'.repeat(32)); ok(r.found === false, '/api/tx: not mined yet = found false');
r = await anon.json('/api/gas'); ok(BigInt(r.maxPriorityFeePerGas || 0) >= 30n * 10n ** 9n, 'gas: at least the 30 gwei Polygon tip floor', r);
r = await V.json('/api/my/paid', {}); ok(r.ok === true, 'paid nudge answers');
// this week's pot now counts the sales: 600 + 1000 + 200 cents = $18, 10% = $1.80, so still the $20 floor
const pzn = await anon.json('/api/prizes'); ok(pzn.current && pzn.current.pot === 20 && pzn.current.atFloor === true && Array.isArray(pzn.past) && pzn.past.length === 0, 'prizes: this week at the $20 floor, no past winners yet', pzn);
const apz = await anon.json('/api/admin/prizes', undefined, { 'x-admin-token': ADMIN });
ok(apz.current && apz.current.salesUsd === 18 && apz.current.purchases === 3 && apz.current.shareUsd === 1.8 && apz.current.topUpUsd === 18.2 && apz.prize && apz.prize.keyOn === false, 'admin prizes: week sales $18 from 3 purchases, 10% $1.80, top-up $18.20, no prize key here', apz.current);
r = await anon.json('/api/admin/prizes/prepare', { week: apz.week }, { 'x-admin-token': ADMIN }); ok(r._status === 400 && /not finished/.test(r.error), 'prizes: the current week cannot be prepared', r);
r = await anon.json('/api/admin/prizes/pay', { week: apz.lastWeek }, { 'x-admin-token': ADMIN }); ok(r._status === 400 && /confirm/.test(r.error), 'prizes: paying needs {week, confirm: week}', r);
r = await anon.json('/api/admin/prizes/pay', { week: apz.lastWeek, confirm: apz.lastWeek }, { 'x-admin-token': ADMIN }); ok(r._status === 400 && !r.ok, 'prizes: without a prepared plan with winners (and without PRIZE_KEY) nothing is paid', r);
r = await anon.json('/api/admin/prizes/pay', { week: apz.lastWeek, confirm: apz.lastWeek }); ok(r._status === 401, 'prizes: paying needs the admin token');
// ---- 12b. hub report: each purchase reported once, signed as vbb (first = bind with the sponsor, later = spend) ----
console.log('12b. hub report');
await sleep(1200);
const binds = HUB.got.filter(x => x.route === '/v1/contract-bind'), spends = HUB.got.filter(x => x.route === '/v1/contract-spend');
ok(HUB.badSig === 0 && binds.length === 1 && binds[0].body.contract === 'viralbannerblitz' && binds[0].body.wallet === V.address && binds[0].body.sponsorRef === spW && binds[0].body.spentCents === 600 && binds[0].body.tx === tx1, 'hub: the first purchase is a signed contract-bind with the sponsor wallet and 600 cents', HUB);
ok(spends.length === 1 && spends[0].body.wallet === V.address && spends[0].body.cents === 1000, 'hub: the second purchase is a contract-spend of 1000 cents', spends);
ok(spends.length === 2 && spends[0].body.wallet === V.address && spends[0].body.cents === 1000 && spends[1].body.cents === 200, 'hub: later purchases are contract-spends (1000 cents, then the 200-cent banner look)', spends);
const adh = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(adh.hub && adh.hub.enabled && adh.hub.sent === 2 && adh.hub.site === 'vbb' && !JSON.stringify(adh).includes(HUB_SECRET), 'admin status shows the hub report (2 sent), never the secret', adh.hub);
ok(adh.hub && adh.hub.enabled && adh.hub.sent === 3 && adh.hub.site === 'vbb' && !JSON.stringify(adh).includes(HUB_SECRET), 'admin status shows the hub report (3 sent), never the secret', adh.hub);
// ---- 12c. old site links + health ----
console.log('12c. old site links + health');
@@ -425,8 +480,14 @@ async function main() {
ok(/1st: \$5 in POL/.test(await pg.textContent('#pz')) && /at least \$20, and it grows with sales/.test(await pg.textContent('#prizes')) && !/50/.test(await pg.textContent('#prizes')), name + ': leaderboard page shows the pot, never the cap');
await pg.goto(BASE + '/packages', { waitUntil: 'domcontentloaded' }); await pg.waitForTimeout(400);
const pk = await pg.textContent('#pk');
ok(/10 post credits for \$3/.test(pk) && /40 post credits for \$10/.test(pk) && /\$2 per banner/.test(pk) && /Coming soon/i.test(pk), name + ': packages page shows the planned prices as coming soon', pk.slice(0, 200));
ok(!(await pg.$('#pk button, #pk form')), name + ': no purchase controls on the packages page');
await pg.waitForFunction(() => /POL right now/.test(document.getElementById('pk').textContent), null, { timeout: 6000 }).catch(() => {});
const pkt = await pg.textContent('#pk');
ok(/10 post credits/.test(pkt) && /\$3/.test(pkt) && /40 post credits/.test(pkt) && /\$10/.test(pkt) && /\$2 per banner/.test(pkt) && /about 12\.00 POL right now/.test(pkt) && /about 40\.00 POL right now/.test(pkt), name + ': packages page shows USD prices and the live POL price', pkt.slice(0, 300));
const buys = await pg.$$eval('#pk button[data-pk=buy]', els => els.map(b => [b.textContent, b.disabled]));
ok(buys.length === 2 && buys[0][0] === 'Buy 10 credits' && buys[1][0] === 'Buy 40 credits' && buys.every(b => !b[1]), name + ': two live Buy buttons', buys);
const soon = (await pg.textContent('main')).match(/coming soon/gi) || [];
ok(soon.length === 1 && /Tokens[\s\S]*Coming soon/i.test(pkt), name + ': only Tokens still says coming soon', soon.length);
ok(/SafePal or any other crypto wallet/.test(await pg.textContent('main')) && /Never a subscription/i.test(await pg.textContent('main')), name + ': packages copy: SafePal or any other crypto wallet, never a subscription');
await pg.screenshot({ path: path.join(OUT, 'packages-' + name + '.png'), fullPage: true });
// My Banners, signed in as the network member (cookie copied from the HTTP client)
await ctx.addCookies([{ name: 'vbb.sid', value: L.jar['vbb.sid'], url: BASE }]);