001878bdae
- Free text ad for network members (InstantAdPay / LinkSpin sign-in or wallet, membership through the hub), one per member - Member pages viraladblitz.com/<username>: own ad + the first 5 people above in the hub line with a live ad (by place) + 2 Boosted places - Front page: amber ticker (Boosted starred), Top ads this week by verified clicks, today's numbers, ledger, contract proof - Verified visitors / views / clicks (ticket + dwell + per-visitor dedupe + per-connection cap + bot filter, owner excluded) - Boost $5 = 500 guaranteed views through VABShop: keeper-signed EIP-712 line voucher from the hub line, watcher, delivery counted per verified view with an audit row each, Network Ad Space text-ad finishing after 30 days (vabnas.js) - Trust pack: /ledger, /contract, toasts, Telegram card per Boost (once), Terms / Earnings Disclaimer / Privacy (TrustClickz), network footer from the hub with tracked links, promo kit (21 creatives) + /promote, LinkSpin zone placeholders, hub report - Old YFW links via the oldrefs map (admin load route); docstore MySQL documents + row tables - qa/smoke.mjs 162/162 (stand-in hub, chain, Telegram, NAS; Playwright desktop + phone), qa/chain.mjs 20/20 (real VABShop on anvil) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
137 lines
13 KiB
JavaScript
137 lines
13 KiB
JavaScript
// ViralAdBlitz real-contract test on a local anvil chain (no fork, nothing leaves this machine, no real POL).
|
|
// Deploys the real VABShop (../contracts/out) with a mock Chainlink feed at $0.25, boots the app against it with a stand-in hub
|
|
// (line: B -> A1 -> A2 -> A3) and a stand-in Telegram API, and checks through the app's own order flow:
|
|
// 1. A3 (top, no line) boosts: nothing qualifies, 100% to the company.
|
|
// 2. A1 boosts with a voucher binding [A2, A3]: A2 never boosted and is passed over, A3 gets level 1 at place 2; company 90%.
|
|
// 3. B boosts 2 with the app's 1% overpay: the voucher binds B -> A1 and stops (A1 already bound); A1 level 1, A3 level 2;
|
|
// company 80%; the overpay comes back in the same transaction (buyer spent = price + gas, exact).
|
|
// Every amount exact to the wei; /api/ledger matches the receipts; one Telegram card per Boost, never twice; /api/contract live.
|
|
// 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 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 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 || 8571), PORT = Number(process.env.CHAIN_APP_PORT || 3331);
|
|
const RPC = 'http://127.0.0.1:' + APORT, BASE = 'http://127.0.0.1:' + PORT, ADMIN = 'chain-admin-token', HUB_SECRET = 'c'.repeat(40);
|
|
// anvil's public dev keys (local chain only)
|
|
const K = ['0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',
|
|
'0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a', '0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6',
|
|
'0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a', '0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba'];
|
|
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) {} });
|
|
const listen = (port, fn) => http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; await fn(q, r, b); }).listen(port, '127.0.0.1').unref();
|
|
|
|
// stand-in Telegram (never the real group)
|
|
const TG = []; listen(PORT + 2, async (q, r, b) => { TG.push({ method: q.url.split('/').pop(), body: JSON.parse(b || '{}') }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); });
|
|
// stand-in hub: wallet -> { id, username, sponsor wallet }
|
|
const people = new Map();
|
|
listen(PORT + 1, async (q, r, b) => {
|
|
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: w, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null } : null }));
|
|
});
|
|
|
|
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 [A3, A2, A1, B] = [K[2], K[3], K[4], K[5]].map(k => new ethers.Wallet(k, provider));
|
|
const company = ethers.Wallet.createRandom().address;
|
|
const lc = w => w.address.toLowerCase();
|
|
people.set(lc(A3), { id: 'h_' + '3'.repeat(16), username: 'athree' }); people.set(lc(A2), { id: 'h_' + '2'.repeat(16), username: 'atwo', sponsor: lc(A3) });
|
|
people.set(lc(A1), { id: 'h_' + '1'.repeat(16), username: 'aone', sponsor: lc(A2) }); people.set(lc(B), { id: 'h_' + 'b'.repeat(16), username: 'buyerb', sponsor: lc(A1) });
|
|
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
|
|
let nonce = await provider.getTransactionCount(deployer.address);
|
|
const fa = art('MockV3Aggregator'); const feed = await new ethers.ContractFactory(fa.abi, fa.bytecode.object, deployer).deploy(25000000n, { nonce: nonce++ }); await feed.waitForDeployment();
|
|
const sa = art('VABShop'); const shop = await new ethers.ContractFactory(sa.abi, sa.bytecode.object, deployer).deploy(company, keeper.address, await feed.getAddress(), { nonce: nonce++ }); await shop.waitForDeployment();
|
|
await (await shop.setSku(1, 500, 500, true, { nonce: nonce++ })).wait();
|
|
const SHOP = await shop.getAddress(); console.log('anvil', RPC, 'VABShop', SHOP);
|
|
|
|
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: '', NETWORK_SITES_HUB: '0',
|
|
CHAIN_ID: '31337', CONTRACT_ADDRESS: SHOP, CHAIN_RPC: RPC, KEEPER_KEY: K[1], SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '300', EXPLORER: 'https://explorer.invalid', COMPANY_WALLET: company,
|
|
HUB_URL: 'http://127.0.0.1:' + (PORT + 1), HUB_SECRET, HUB_SITE: 'viraladblitz', HUB_ENABLED: '0', HUB_CACHE_MS: '200',
|
|
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + (PORT + 2) });
|
|
const log = fs.openSync(path.join(OUT, 'chain-server.log'), 'w');
|
|
procs.push(spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', log, log] }));
|
|
for (let i = 0; i < 80; i++) { try { if ((await fetch(BASE + '/health')).ok) break; } catch (e) {} await sleep(150); }
|
|
|
|
// a member session through the app: wallet sign-in, post an ad
|
|
async function member(w, n) {
|
|
const jar = {}; const call = async (p, body) => { const r = await fetch(BASE + p, { method: body === undefined ? 'GET' : 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 ChainTest', Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, 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 ch = await call('/api/auth/challenge', { address: w.address }); await call('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) });
|
|
const a = await call('/api/my/ad', { headline: 'Chain ad ' + n, line1: 'A real text ad for ' + n, line2: '', link: 'https://chain-' + n + '.example-shop.com/' });
|
|
ok(a.ok, n + ' signs in and posts a text ad', a); return call;
|
|
}
|
|
const bal = a => provider.getBalance(a);
|
|
// one Boost through the app: order -> the member's wallet sends it -> the watcher records it
|
|
async function boost(w, call, qty) {
|
|
const od = await call('/api/my/order', { qty });
|
|
const tx = await w.sendTransaction({ to: od.to, data: od.data, value: BigInt(od.value) }); const rc = await tx.wait();
|
|
await call('/api/my/paid', {});
|
|
for (let i = 0; i < 60; i++) { const l = await call('/api/ledger'); const it = (l.items || []).find(x => x.tx === tx.hash.toLowerCase() && x.pays.every(p => p.to)); if (it) return { od, rc, it, tx }; await sleep(200); }
|
|
return { od, rc, it: null, tx };
|
|
}
|
|
const price = 500n * 10n ** 24n / 25000000n; // $5 at $0.25 = 20 POL
|
|
const share = q => q * 1000n / 10000n;
|
|
|
|
console.log('1. A3 boosts (top of the line): 100% company');
|
|
const c3 = await member(A3, 'athree'); let c0 = await bal(company);
|
|
let r = await boost(A3, c3, 1);
|
|
ok(r.rc.status === 1 && r.od.why === 'no-line' && r.od.line === 0, 'A3 has no line: no voucher, the Boost still goes through', r.od);
|
|
ok((await bal(company)) - c0 === price, 'company got the whole 20 POL (nobody to pay)', ((await bal(company)) - c0).toString());
|
|
ok(r.it && r.it.pays.length === 1 && r.it.pays[0].level === 0 && r.it.pays[0].wei === price.toString(), 'ledger: one company payment from the receipt', r.it);
|
|
|
|
console.log('2. A1 boosts: line [A2, A3], A2 passed over');
|
|
const c1 = await member(A1, 'aone'); c0 = await bal(company); const a3b = await bal(A3.address), a2b = await bal(A2.address);
|
|
r = await boost(A1, c1, 1);
|
|
ok(r.od.line === 2 && (await shop.sponsorOf(A1.address)) === A2.address && (await shop.sponsorOf(A2.address)) === A3.address, 'the voucher bound A1 -> A2 -> A3 on chain', r.od);
|
|
ok((await bal(A3.address)) - a3b === share(price) && (await bal(A2.address)) === a2b && (await bal(company)) - c0 === price - share(price), 'A3 got 10% (level 1, place 2), A2 nothing, company 90% (exact to the wei)');
|
|
ok(r.it.passedOver.length === 1 && r.it.passedOver[0].who === lc(A2) && r.it.passedOver[0].depth === 1 && r.it.pays.find(p => p.level === 1).depth === 2, 'ledger: A2 passed over at place 1, A3 paid at place 2', r.it);
|
|
|
|
console.log('3. B boosts 2 with the 1% overpay: binds B -> A1 only');
|
|
const cb = await member(B, 'buyerb'); c0 = await bal(company); const a1b = await bal(A1.address), a3b2 = await bal(A3.address), bb = await bal(B.address);
|
|
r = await boost(B, cb, 2);
|
|
const q2 = price * 2n; const gas = r.rc.gasUsed * r.rc.gasPrice;
|
|
ok(r.od.line === 3 && (await shop.sponsorOf(B.address)) === A1.address && (await shop.sponsorOf(A1.address)) === A2.address, 'B\'s voucher carried [A1, A2, A3]; only B -> A1 was new, A1\'s link unchanged');
|
|
ok((await bal(A1.address)) - a1b === share(q2) && (await bal(A3.address)) - a3b2 === share(q2) && (await bal(company)) - c0 === q2 - 2n * share(q2), 'A1 level 1 (4 POL), A3 level 2 (4 POL), company 80% (32 POL), exact');
|
|
ok(bb - (await bal(B.address)) === q2 + gas && BigInt(r.od.value) > q2, 'B sent price + 1% and spent exactly price + gas: the overpay came back in the same transaction');
|
|
ok(r.it.pays.filter(p => p.level > 0).map(p => [p.level, p.depth, p.name]).join('|') === '1,1,aone|2,3,athree', 'ledger: levels with places and names', r.it.pays);
|
|
ok(await provider.getBalance(SHOP) === 0n && (await shop.totalOwed()) === 0n, 'the contract holds nothing');
|
|
const my = await cb('/api/my'); ok(my.boosts.length === 1 && my.boosts[0].views === 1000 && my.boosts[0].qty === 2, 'B\'s My page: 2 Boosts = 1,000 guaranteed views', my.boosts);
|
|
const myA1 = await c1('/api/my'); ok(myA1.earned.wei === share(q2).toString(), 'A1\'s My page: the level share paid to them', myA1.earned);
|
|
|
|
console.log('4. trust pack');
|
|
for (let i = 0; i < 30 && TG.length < 3; i++) await sleep(200);
|
|
await sleep(1500);
|
|
ok(TG.length === 3 && TG.every(t => t.method === 'sendPhoto' && t.body.message_thread_id === 632242), 'Telegram: exactly one photo card per Boost (3), payments topic, none repeated', TG.map(t => t.method));
|
|
const capB = TG[2].body.caption;
|
|
ok(/@buyerb boosted "Chain ad buyerb": 2 Boosts \(1,000 guaranteed views\) · \$10\.00 \(40\.0000 POL\)/.test(capB) && /Level 1 10%: 4\.0000 POL → @aone/.test(capB) && /Level 2 10%: 4\.0000 POL → @athree \(place 3 in the line\)/.test(capB) && /ViralAdBlitz: 32\.0000 POL/.test(capB), 'B\'s card: buyer, ad, each level with POL and place, company', capB);
|
|
ok(/1 person in the line had not boosted yet and was passed over/.test(TG[1].body.caption) && /Nobody in this line has boosted yet/.test(TG[0].body.caption), 'cards say who was passed over / that nobody qualified');
|
|
const ct = await (await fetch(BASE + '/api/contract')).json();
|
|
ok(ct.live && ct.owner === lc(deployer) && ct.company === company.toLowerCase() && ct.keeper === lc(keeper) && ct.orderCount === 3 && ct.balanceWei === '0', '/api/contract reads the live contract', ct);
|
|
console.log('\nPOL/USD $0.25: Boost $5 = ' + ethers.formatEther(price) + ' POL, one level share = ' + ethers.formatEther(share(price)) + ' POL');
|
|
console.log(pass + ' passed, ' + fail + ' failed');
|
|
fs.writeFileSync(path.join(OUT, 'chain.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n');
|
|
process.exit(fail ? 1 : 0);
|
|
}
|
|
main().catch(e => { console.error('chain test crashed:', e.stack || e.message); process.exit(1); });
|