Compare commits

..

2 Commits

Author SHA1 Message Date
martbost aee1ccc36a 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>
2026-11-14 09:47:58 -06:00
martbost a6a9b3cace Promo kit (Marty 2026-11-14: "get all the creatives built ... and put them in all the places they need to go"): promokit.js is the one source for the VBB kit, published as GET /api/promo-kit?u=<network username or wallet> (public, CORS open, read by /promote and InstantAdPay's promo center): personal links (?ref=), 21 creatives (3 angles: free daily post / every visitor pushes the loop / weekly prizes, in 125x125, 468x60, 728x90, 300x250, 160x600, 1200x630, 1080x1080) at /art/kit/vbb-<angle>-<shape>.png (ad-blocker-neutral names, rendered by tools/kit-art.mjs with Playwright), 5 lines, 3 headlines, 1 email, 2 posts built from config (perShift, viewsPerCycle, prize floor shown as "at least", never the cap). /promote page (kitpage.js + promote.js + kit.css): username from sign-in, ?u= or typed. Nav + footer link Promote. Network zones wired like DLB (common.js ZONES: footer wide/phone, Leaderboards, My Banners, How it works; 404 in server.js ZONE_404), never on the loop page; ids empty until the LinkSpin zones exist. CSP admits linkspin.app. common.js?v=2, vbb.css?v=3. Smoke 160/160 on this commit alone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 09:41:50 -06:00
53 changed files with 1374 additions and 83 deletions
+2
View File
@@ -30,6 +30,8 @@ SHOP_START_BLOCK= # the deploy block; the first scan starts here
SHOP_CONFIRMATIONS=10 # credit only this many blocks behind the head SHOP_CONFIRMATIONS=10 # credit only this many blocks behind the head
SHOP_POLL_MS=30000 SHOP_POLL_MS=30000
KEEPER_KEY= # private key of the contract's keeper (signs sponsor vouchers). Coolify secret only, never in git KEEPER_KEY= # private key of the contract's keeper (signs sponsor vouchers). Coolify secret only, never in git
PRIZE_KEY= # private key of the prize wallet (weekly payouts, sent only when an admin approves). Coolify secret only, never in git
PRIZE_WALLET= # default 0x167315726Fe50CFF97b8F4c91c8C606489397907; must equal VBBShop.prizeWallet()
VOUCHER_SECONDS=1800 # a voucher is good for 30 minutes VOUCHER_SECONDS=1800 # a voucher is good for 30 minutes
# Network hub report (hubreport.js): every VBBShop purchase reported by wallet (bind, then spend). Off unless HUB_ENABLED=1. # Network hub report (hubreport.js): every VBBShop purchase reported by wallet (bind, then spend). Off unless HUB_ENABLED=1.
HUB_URL= # https://hub.saasy.top HUB_URL= # https://hub.saasy.top
+10 -6
View File
@@ -1,6 +1,7 @@
// All runtime config comes from env (Coolify sets these). Read once. // All runtime config comes from env (Coolify sets these). Read once.
// VBB v1 takes no payments in the UI: planned prices show as "coming soon"; rewards are recorded, not credited yet. The VBBShop // Purchases are live through VBBShop (2026-11-14): the packages page and My Banners sell packs and banner looks from the member's
// contract hooks (shop.js: sponsor vouchers + purchase watcher) stay inert until CONTRACT_ADDRESS / CHAIN_RPC / KEEPER_KEY are set. // wallet; shop.js signs sponsor vouchers, builds the buy() call and credits from Purchase events. Inert until CONTRACT_ADDRESS /
// CHAIN_RPC / KEEPER_KEY are set. Weekly prize payouts: prize.js (two-step admin flow, PRIZE_KEY read there only).
const path = require('path'); const path = require('path');
let cfg = null; let cfg = null;
@@ -31,15 +32,18 @@ function get() {
freeCreditsPerDay: num(e.FREE_CREDITS_PER_DAY, 1, 0, 10), // Marty 2026-11-13: 1 free post credit a day on sign-in freeCreditsPerDay: num(e.FREE_CREDITS_PER_DAY, 1, 0, 10), // Marty 2026-11-13: 1 free post credit a day on sign-in
freeCreditCap: num(e.FREE_CREDIT_CAP, 7, 1, 365), // daily free credits bank up to this many freeCreditCap: num(e.FREE_CREDIT_CAP, 7, 1, 365), // daily free credits bank up to this many
maxQueuedPerMember: num(e.MAX_QUEUED_PER_MEMBER, 3, 1, 100), // banners one member may have waiting at once maxQueuedPerMember: num(e.MAX_QUEUED_PER_MEMBER, 3, 1, 100), // banners one member may have waiting at once
// ---- Marty's approved numbers (2026-11-13). v1 takes no payments: packages show as "coming soon" with these planned prices, // ---- Marty's approved numbers (2026-11-13), sold on chain through VBBShop since 2026-11-14 (the contract's SKUs hold the real
// prizes are displayed only (no payout code yet), the split is kept here for the contract step. // prices; these are the display copy and must match them). Pack n is SKU PACK_SKUS[n]; the banner look is LOOK_SKU.
packs: list(e.CREDIT_PACKS, '10:3,40:10').map(x => { const [credits, usd] = x.split(':').map(Number); return { credits, usd }; }).filter(x => x.credits > 0 && x.usd > 0), packs: list(e.CREDIT_PACKS, '10:3,40:10').map((x, i) => { const [credits, usd] = x.split(':').map(Number); return { credits, usd, sku: Number(list(e.PACK_SKUS, '1,2')[i]) || i + 1 }; }).filter(x => x.credits > 0 && x.usd > 0),
lookSku: num(e.LOOK_SKU, 3, 1, 1000),
lookUsd: Number(e.LOOK_USD || 2), // banner look (border + hover teaser), per banner, one-time lookUsd: Number(e.LOOK_USD || 2), // banner look (border + hover teaser), per banner, one-time
split: { sponsorPct: num(e.SPONSOR_PCT, 30, 0, 100), companyPct: 100 - num(e.SPONSOR_PCT, 30, 0, 100) }, // on-chain later, no line split: { sponsorPct: num(e.SPONSOR_PCT, 30, 0, 100), companyPct: 100 - num(e.SPONSOR_PCT, 30, 0, 100) }, // on-chain later, no line
// weekly prize pot (Marty 2026-11-13): 10% of the week's sales, never under the floor (the company tops it up), capped at $50. // weekly prize pot (Marty 2026-11-13): 10% of the week's sales, never under the floor (the company tops it up), capped at $50.
// Half the pot per leaderboard, split 50/30/20 across the top three. The cap is internal: the public page never shows it. // Half the pot per leaderboard, split 50/30/20 across the top three. The cap is internal: the public page never shows it.
prizePot: { pct: num(e.PRIZE_PCT, 10, 0, 100), floorUsd: num(e.PRIZE_FLOOR_USD, 20, 0, 100000), capUsd: num(e.PRIZE_CAP_USD, 50, 0, 100000), prizePot: { pct: num(e.PRIZE_PCT, 10, 0, 100), floorUsd: num(e.PRIZE_FLOOR_USD, 20, 0, 100000), capUsd: num(e.PRIZE_CAP_USD, 50, 0, 100000),
places: list(e.PRIZE_PLACES, '50,30,20').map(Number).filter(x => x >= 0) }, places: list(e.PRIZE_PLACES, '50,30,20').map(Number).filter(x => x >= 0),
wallet: /^0x[0-9a-fA-F]{40}$/.test(String(e.PRIZE_WALLET || '').trim()) ? String(e.PRIZE_WALLET).trim().toLowerCase() : '0x167315726fe50cff97b8f4c91c8c606489397907' },
explorer: String(e.EXPLORER || (Number(e.CHAIN_ID || 137) === 137 ? 'https://polygonscan.com' : '')).replace(/\/+$/, ''),
// VBBShop (../contracts). KEEPER_KEY is read by shop.js only, never kept here. // VBBShop (../contracts). KEEPER_KEY is read by shop.js only, never kept here.
contractAddress: /^0x[0-9a-fA-F]{40}$/.test(String(e.CONTRACT_ADDRESS || '').trim()) ? require('ethers').getAddress(String(e.CONTRACT_ADDRESS).trim()) : '', contractAddress: /^0x[0-9a-fA-F]{40}$/.test(String(e.CONTRACT_ADDRESS || '').trim()) ? require('ethers').getAddress(String(e.CONTRACT_ADDRESS).trim()) : '',
chainRpc: String(e.CHAIN_RPC || '').trim(), // the watcher's RPC (server side); '' = watcher off chainRpc: String(e.CHAIN_RPC || '').trim(), // the watcher's RPC (server side); '' = watcher off
+1
View File
@@ -16,6 +16,7 @@ services:
CHAIN_RPC: ${CHAIN_RPC:-} CHAIN_RPC: ${CHAIN_RPC:-}
SHOP_START_BLOCK: ${SHOP_START_BLOCK:-} SHOP_START_BLOCK: ${SHOP_START_BLOCK:-}
KEEPER_KEY: ${KEEPER_KEY:-} KEEPER_KEY: ${KEEPER_KEY:-}
PRIZE_KEY: ${PRIZE_KEY:-} # the prize wallet's key (weekly payouts, admin-approved); a Coolify secret
CHAIN_ID: ${CHAIN_ID:-137} CHAIN_ID: ${CHAIN_ID:-137}
RPC_URLS: ${RPC_URLS:-} RPC_URLS: ${RPC_URLS:-}
HUB_URL: ${HUB_URL:-} HUB_URL: ${HUB_URL:-}
+16 -9
View File
@@ -87,21 +87,25 @@ function verifiedVisit(o) {
} }
// ---- weekly leaderboards (Central time, Monday to Sunday) ---- // ---- weekly leaderboards (Central time, Monday to Sunday) ----
// Ties (Marty 2026-11-14): whoever reached the count first ranks higher. Visitors: the time of their latest counted visitor.
// Sources: the time their latest new source first appeared. Both are order-independent (rows may load in any order).
let lbCache = null; let lbCache = null;
function leaders(week, n) { function leaders(week, n) {
const wk = week || store.ctWeek(); n = n || 10; const wk = week || store.ctWeek(); n = n || 10;
if (lbCache && lbCache.wk === wk && Date.now() - lbCache.at < 15000 && lbCache.n === store.visits().length) return lbCache.out; if (lbCache && lbCache.wk === wk && lbCache.n0 === n && Date.now() - lbCache.at < 15000 && lbCache.n === store.visits().length) return lbCache.out;
const per = new Map(); const per = new Map();
for (const v of store.visits()) { for (const v of store.visits()) {
if (v.wk !== wk || !v.ref) continue; if (v.wk !== wk || !v.ref) continue;
const p = per.get(v.ref) || per.set(v.ref, { address: v.ref, visitors: 0, sources: new Set() }).get(v.ref); const p = per.get(v.ref) || per.set(v.ref, { address: v.ref, visitors: 0, vAt: 0, src: new Map() }).get(v.ref);
p.visitors++; if (v.src) p.sources.add(v.src); p.visitors++; if (v.at > p.vAt) p.vAt = v.at;
if (v.src) { const f = p.src.get(v.src); if (!f || v.at < f) p.src.set(v.src, v.at); }
} }
const rows = [...per.values()].map(p => { const m = store.member(p.address); return { address: p.address, username: (m && m.username) || null, visitors: p.visitors, sources: p.sources.size }; }); const rows = [...per.values()].map(p => { const m = store.member(p.address);
return { address: p.address, username: (m && m.username) || null, visitors: p.visitors, sources: p.src.size, visitorsAt: p.vAt, sourcesAt: p.src.size ? Math.max(...p.src.values()) : 0 }; });
const out = { week: wk, const out = { week: wk,
visitors: rows.slice().sort((a, b) => b.visitors - a.visitors || b.sources - a.sources).slice(0, n), visitors: rows.slice().sort((a, b) => b.visitors - a.visitors || a.visitorsAt - b.visitorsAt).slice(0, n),
sources: rows.filter(r => r.sources > 0).sort((a, b) => b.sources - a.sources || b.visitors - a.visitors).slice(0, n) }; sources: rows.filter(r => r.sources > 0).sort((a, b) => b.sources - a.sources || a.sourcesAt - b.sourcesAt).slice(0, n) };
lbCache = { wk, at: Date.now(), n: store.visits().length, out }; lbCache = { wk, n0: n, at: Date.now(), n: store.visits().length, out };
return out; return out;
} }
function memberWeek(addr) { function memberWeek(addr) {
@@ -111,7 +115,10 @@ function memberWeek(addr) {
} }
// ---- views for pages ---- // ---- views for pages ----
function tile(b) { const m = store.member(b.owner); return { id: b.id, img: b.img, href: '/go/' + b.id, owner: (m && m.username) ? '@' + m.username : null }; } // the banner look (bought per banner, SKU 3): a highlighted border and a hover teaser (the member's line, else the link's site)
const hostOf = l => { try { return new URL(l).hostname.replace(/^www\./, ''); } catch (e) { return ''; } };
function tile(b) { const m = store.member(b.owner); const t = { id: b.id, img: b.img, href: '/go/' + b.id, owner: (m && m.username) ? '@' + m.username : null };
if (b.look) { t.look = true; t.teaser = b.teaser || hostOf(b.link); } return t; }
function view(queueShow) { function view(queueShow) {
const S = store.state(); const S = store.state();
return { loopSize: C().loopSize, perShift: C().perShift, progress: S.progress, waiting: S.queue.length, return { loopSize: C().loopSize, perShift: C().perShift, progress: S.progress, waiting: S.queue.length,
@@ -127,4 +134,4 @@ function placeOf(b) {
return { state: b.state }; return { state: b.state };
} }
module.exports = { init, post, shift, verifiedVisit, canCount, rebuildIndex, leaders, memberWeek, view, placeOf, normalize }; module.exports = { hostOf, init, post, shift, verifiedVisit, canCount, rebuildIndex, leaders, memberWeek, view, placeOf, normalize };
+2 -1
View File
@@ -7,7 +7,8 @@
"scripts": { "scripts": {
"start": "node server.js", "start": "node server.js",
"dev": "node --watch server.js", "dev": "node --watch server.js",
"qa": "node qa/smoke.mjs" "qa": "node qa/smoke.mjs",
"qa:chain": "node qa/chain.mjs"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"
+187
View File
@@ -0,0 +1,187 @@
// Weekly prize payouts (Marty 2026-11-14). Two steps, money rule: the app PREPARES, an admin APPROVES, the app pays once.
// - The pot of a Central-time week (Monday 12:00 AM to Sunday) = 10% of that week's VBBShop sales (usdCents of the credited
// Purchase events, by block time; the prize wallet received exactly that share in POL), never under the floor (the company
// tops the prize wallet up), never over the cap (internal, never shown). Half the pot per leaderboard, 50/30/20 to the top 3.
// - Winners: the weekly leaderboards (loop.leaders): most verified visitors sent, most distinct traffic sources. Ties: the
// earlier to reach the count wins. Each VBB account IS a wallet, so the winner's wallet is their account address. A winner
// that cannot be paid (not a valid wallet, or the prize/company wallet itself) is skipped: everyone below moves up a place, and
// a place nobody fills is not paid (its share stays in the prize wallet for later weeks).
// - prepare(week): every 10 minutes the app prepares the last finished week if it has no plan yet (so Monday after midnight CT).
// A plan holds the winners, wallets and USD amounts. POL amounts are quoted live from the Chainlink POL/USD feed the contract
// uses (fresh answer only), and fixed at the moment of payment.
// - pay(week): admin only. Refuses unless PRIZE_KEY is set and is the contract's prize wallet, the feed is fresh, and the prize
// wallet holds the POL plus gas (says how much is missing). Once per week, across app copies and restarts (docstore.claim in
// MySQL, then the plan's own status). Sends one plain POL transfer per winner with consecutive nonces, records each hash at
// once, stops at the first error (never retried automatically: an unclear send must be checked on the explorer by a person),
// then watches the receipts. Posts nothing anywhere.
// Plans live in prizes.json (a MySQL document through docstore). PRIZE_KEY is read here only and never leaves this module.
'use strict';
const fs = require('fs');
const path = require('path');
const { Wallet, JsonRpcProvider, getAddress } = require('ethers');
const store = require('./store');
const loop = require('./loop');
const shop = require('./shop');
const docstore = require('./docstore');
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
const BOARDS = ['visitors', 'sources'];
const COMPANY = '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70';
let C = null, key = null, D = null, busy = false, timer = null;
const st = { prepared: 0, paid: 0, lastError: null };
const FILE = () => path.join(C.dataDir, 'prizes.json');
function init(cfg) {
C = cfg; key = null;
const k = String(process.env.PRIZE_KEY || '').trim();
if (k) { try { key = new Wallet(k.startsWith('0x') ? k : '0x' + k); } catch (e) { console.error('prize: PRIZE_KEY is not a valid private key; payouts off'); } }
try { D = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { D = null; }
D = Object.assign({ weeks: {} }, D || {});
// a payment interrupted by a restart: its receipts are watched again
for (const p of Object.values(D.weeks)) if (p.status === 'paying' || p.status === 'sent') watchReceipts(p.week);
if (timer) clearInterval(timer);
timer = setInterval(() => auto().catch(() => {}), 600000); timer.unref();
setTimeout(() => auto().catch(() => {}), 5000).unref();
}
function save() { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(D)); fs.renameSync(tmp, FILE()); }
const r2 = x => Math.round(x * 100) / 100;
const nameOf = (addr, username) => username ? '@' + username : addr.slice(0, 6) + '...' + addr.slice(-4);
// the Monday before `week` (both YYYY-MM-DD)
const prevWeek = week => new Date(Date.parse(week + 'T12:00:00Z') - 7 * 86400000).toISOString().slice(0, 10);
// the pot of a week from its sales
function pot(week) {
const z = C.prizePot; const s = shop.weekSales(week, store.ctWeek);
const raw = s.cents / 100 * z.pct / 100;
const usd = Math.min(z.capUsd, Math.max(z.floorUsd, raw));
const board = usd / 2;
return { salesUsd: r2(s.cents / 100), purchases: s.purchases, prizeShareWei: s.prizeWei, shareUsd: r2(raw), potUsd: r2(usd), atFloor: raw <= z.floorUsd, atCap: raw >= z.capUsd,
topUpUsd: r2(Math.max(0, usd - raw)), places: z.places.map(x => r2(board * x / 100)) };
}
// the payable winners of one board, in order
function winners(rows, max) {
const out = [], prizeW = C.prizePot.wallet;
for (const r of rows) {
if (out.length >= max) break;
const a = String(r.address || '').toLowerCase();
if (!ADDR_RE.test(a) || a === prizeW || a === COMPANY) continue; // skipped: everyone below moves up
out.push(r);
}
return out;
}
function prepare(week, force) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(String(week || ''))) return { error: 'week must be YYYY-MM-DD (that Monday)' };
if (week >= store.ctWeek()) return { error: 'That week has not finished yet (weeks end Sunday midnight, Central time).' };
const have = D.weeks[week];
if (have && !(force && (have.status === 'prepared' || have.status === 'nothing'))) return have;
const pz = pot(week); const lb = loop.leaders(week, 100);
const transfers = [];
for (const board of BOARDS) {
const list = winners(lb[board], pz.places.length);
list.forEach((r, i) => transfers.push({ board, place: i + 1, address: r.address.toLowerCase(), name: nameOf(r.address, r.username), count: r[board],
reachedAt: board === 'visitors' ? r.visitorsAt : r.sourcesAt, usd: pz.places[i], cents: Math.round(pz.places[i] * 100) }));
}
const unfilled = BOARDS.reduce((t, b) => t + pz.places.slice(transfers.filter(x => x.board === b).length).reduce((a, v) => a + v, 0), 0);
const plan = Object.assign({ week, preparedAt: Date.now(), status: transfers.length ? 'prepared' : 'nothing', transfers, unfilledUsd: r2(unfilled) }, pz,
{ payUsd: r2(transfers.reduce((t, x) => t + x.usd, 0)) });
D.weeks[week] = plan; save(); st.prepared++;
console.log('prize: week', week, 'prepared,', transfers.length, 'winners, $' + plan.payUsd, plan.status);
return plan;
}
// prepare the last finished week once (Monday after midnight CT); never touches a week that already has a plan
async function auto() { const w = prevWeek(store.ctWeek()); if (!D.weeks[w]) prepare(w); }
// ---- live numbers: the Chainlink POL/USD answer (8 decimals), the prize wallet balance, gas ----
async function price() {
const feed = (await shop.call('priceFeed', []))[0];
const r = await shop.call('latestRoundData', [], feed);
const answer = BigInt(r[1]), at = Number(r[3]);
if (answer <= 0n) throw new Error('The price feed answered zero.');
if (Math.floor(Date.now() / 1000) - at > 3600) throw new Error('The POL/USD price feed is older than 1 hour. Try again when it updates.');
return { answer, at, usd: Number(answer) / 1e8 };
}
const fmtPol = wei => { const s = (BigInt(wei) * 10000n / 10n ** 18n).toString().padStart(5, '0'); return s.slice(0, -4) + '.' + s.slice(-4); };
async function quotePlan(plan) {
const out = { keyOn: !!key, keyAddress: key ? key.address.toLowerCase() : null, prizeWallet: C.prizePot.wallet };
try {
const onChain = String((await shop.call('prizeWallet', []))[0]).toLowerCase(); out.contractPrizeWallet = onChain;
out.keyMatches = !!key && key.address.toLowerCase() === onChain;
const p = await price(); out.priceUsd = p.usd; out.priceAt = p.at;
const f = await shop.fees(); const maxFee = BigInt(f.maxFeePerGas);
let total = 0n; const lines = (plan.transfers || []).map(t => { const wei = BigInt(t.cents) * 10n ** 24n / p.answer; total += wei; return { board: t.board, place: t.place, wei: wei.toString(), pol: fmtPol(wei) }; });
const gas = BigInt(lines.length) * 30000n * maxFee; // 21,000 for a wallet, headroom for a contract wallet
const bal = BigInt(await shop.rpc('eth_getBalance', [onChain, 'latest']));
Object.assign(out, { lines, totalWei: total.toString(), totalPol: fmtPol(total), gasWei: gas.toString(), gasPol: fmtPol(gas), balanceWei: bal.toString(), balancePol: fmtPol(bal),
shortWei: (bal >= total + gas ? 0n : total + gas - bal).toString(), shortPol: fmtPol(bal >= total + gas ? 0n : total + gas - bal), maxFeePerGas: f.maxFeePerGas, maxPriorityFeePerGas: f.maxPriorityFeePerGas });
} catch (e) { out.error = String(e.message || e).slice(0, 200); }
return out;
}
async function pay(week) {
const plan = D.weeks[week];
if (!plan) return { error: 'No plan for that week. Prepare it first.' };
if (plan.status !== 'prepared') return { error: 'This week is ' + plan.status + '. A week is paid once.' , plan };
if (busy) return { error: 'A payout is already running.' };
if (!key) return { error: 'PRIZE_KEY is not set on the server.' };
busy = true;
try {
const q = await quotePlan(plan);
if (q.error) return { error: q.error };
if (!q.keyMatches) return { error: 'PRIZE_KEY is not the contract\'s prize wallet (' + q.contractPrizeWallet + '). Nothing sent.' };
if (BigInt(q.shortWei) > 0n) return { error: 'The prize wallet holds ' + q.balancePol + ' POL. This week needs ' + q.totalPol + ' POL plus about ' + q.gasPol + ' POL gas: send at least ' + q.shortPol + ' POL more to ' + q.contractPrizeWallet + '. Nothing sent.', quote: q };
// once per week, ever: the MySQL claim first (two app copies during a deploy), then the plan's own status
if (!(await docstore.claim('vbb-prize-pay:' + week))) { plan.status = 'claimed-elsewhere'; save(); return { error: 'This week was already claimed for payment (another app copy or an earlier attempt). Nothing sent; check /admin and the prize wallet on the explorer.' }; }
plan.status = 'paying'; plan.payment = { startedAt: Date.now(), priceUsd: q.priceUsd, priceAt: q.priceAt, from: q.contractPrizeWallet, totalWei: q.totalWei };
plan.transfers.forEach((t, i) => { t.wei = q.lines[i].wei; t.pol = q.lines[i].pol; t.status = 'pending'; });
save(); await docstore.drain(5000); // the 'paying' mark is in MySQL before the first POL moves
const provider = new JsonRpcProvider(C.chainRpc, C.chainId, { staticNetwork: true });
const w = key.connect(provider);
let nonce = await provider.getTransactionCount(w.address, 'pending');
for (const t of plan.transfers) {
try {
let gasLimit = 21000n;
try { gasLimit = await provider.estimateGas({ from: w.address, to: getAddress(t.address), value: BigInt(t.wei) }); gasLimit = gasLimit * 12n / 10n; if (gasLimit > 30000n) gasLimit = 30000n; if (gasLimit < 21000n) gasLimit = 21000n; } catch (e) {}
const tx = await w.sendTransaction({ to: getAddress(t.address), value: BigInt(t.wei), nonce, gasLimit, maxFeePerGas: BigInt(q.maxFeePerGas), maxPriorityFeePerGas: BigInt(q.maxPriorityFeePerGas), chainId: C.chainId, type: 2 });
t.tx = tx.hash; t.status = 'sent'; t.sentAt = Date.now(); nonce++; save();
console.log('prize: week', week, t.board, '#' + t.place, t.pol, 'POL to', t.address, tx.hash);
} catch (e) {
// unclear: the transfer may or may not have reached the network. Never resent automatically.
t.status = 'unknown'; t.error = String(e.shortMessage || e.message || e).slice(0, 200); st.lastError = t.error;
for (const r of plan.transfers) if (r.status === 'pending') r.status = 'not-sent';
save(); break;
}
}
plan.status = plan.transfers.every(t => t.status === 'sent') ? 'sent' : 'partial';
plan.payment.sentAt = Date.now(); save(); st.paid++;
watchReceipts(week);
return { ok: true, plan };
} finally { busy = false; }
}
// receipts: confirmed / reverted per transfer; the week is 'paid' when every transfer confirmed
const watching = new Set();
function watchReceipts(week) {
if (watching.has(week)) return; watching.add(week);
let tries = 0;
const tick = async () => {
const plan = D.weeks[week]; if (!plan) { watching.delete(week); return; }
for (const t of plan.transfers) {
if (t.status !== 'sent' || !t.tx) continue;
try { const r = await shop.receipt(t.tx); if (r.found) { t.status = r.status === '0x1' ? 'confirmed' : 'reverted'; t.block = parseInt(r.blockNumber, 16); save(); } } catch (e) {}
}
const open = plan.transfers.some(t => t.status === 'sent');
if (!open && (plan.status === 'sent' || plan.status === 'paying')) { plan.status = plan.transfers.every(t => t.status === 'confirmed') ? 'paid' : 'partial'; plan.payment.doneAt = Date.now(); save(); }
if (open && ++tries < 240) { const tm = setTimeout(tick, Number(process.env.PRIZE_RECEIPT_MS || 5000)); tm.unref(); } else watching.delete(week);
};
tick();
}
// public: weeks with transfers sent, newest first (names, places, USD, POL, transaction links)
function history(n) {
return Object.values(D.weeks).filter(p => p.payment && p.transfers.some(t => t.tx)).sort((a, b) => b.week.localeCompare(a.week)).slice(0, n || 12)
.map(p => ({ week: p.week, potUsd: p.potUsd, priceUsd: p.payment.priceUsd, paidAt: p.payment.sentAt || p.payment.startedAt, status: p.status,
winners: p.transfers.filter(t => t.tx).map(t => ({ board: t.board, place: t.place, name: t.name, count: t.count, usd: t.usd, pol: t.pol, tx: t.tx, confirmed: t.status === 'confirmed' })) }));
}
function plans() { return Object.values(D.weeks).sort((a, b) => b.week.localeCompare(a.week)); }
function view() { return Object.assign({ keyOn: !!key, keyAddress: key ? key.address.toLowerCase() : null, prizeWallet: C.prizePot.wallet, weeks: Object.keys(D.weeks).length }, st); }
module.exports = { init, pot, prepare, pay, quotePlan, history, plans, view, prevWeek, auto };
+106
View File
@@ -0,0 +1,106 @@
// Promo kit (Marty 2026-11-14): the ONE place the Viral Banner Blitz creatives and swipe copy live. Published as a small public JSON
// feed, GET /api/promo-kit?u=<network username or wallet>, read by this site's /promote page and by InstantAdPay's promo center
// ("Network sites"). Change a line or a creative here and every place that shows the kit updates.
// Facts come from config.js (free post credit per day for network members, visitors per shift, network ad views per cycle, prize
// floor). The prize pot is shown only as "at least" the floor: the cap is internal and never shown. Packages are coming soon, so
// nothing here sells anything. Copy rules: advertising, not income; no em dashes.
// Creatives: public/art/kit/vbb-<angle>-<shape>.png, rendered by tools/kit-art.mjs (neutral names: no IAB size tokens).
'use strict';
const fs = require('fs');
const path = require('path');
const C = require('./config').get();
const KIT_DIR = path.join(__dirname, 'public', 'art', 'kit');
const SHAPES = { tile: [125, 125, 'Square button (loop size)'], strip: [468, 60, 'Strip'], leader: [728, 90, 'Leaderboard'], box: [300, 250, 'Box'],
tower: [160, 600, 'Skyscraper'], social: [1200, 630, 'Social share'], square: [1080, 1080, 'Square post'] };
const ANGLES = { free: 'Free daily banner post', loop: 'Every visitor pushes the loop', prize: 'Weekly leaderboard prizes' };
function copy() {
const n = x => Number(x || 0).toLocaleString('en-US');
const floor = '$' + n(C.prizePot.floorUsd);
const shift = C.perShift === 1 ? 'Every verified visitor shifts' : 'Every ' + n(C.perShift) + ' verified visitors shift';
const views = n(C.viewsPerCycle) + ' network ad views';
return {
lines: [
'InstantAdPay or LinkSpin member? Post a 125x125 banner on Viral Banner Blitz free every day you sign in. {{LINK}}',
'Every real visitor pushes the Viral Banner Blitz loop forward. When your banner rides out, it earns network ad views. {{LINK}}',
'Weekly leaderboards for the most visitors sent. The prize pot is at least ' + floor + ' a week, paid in POL. {{LINK}}',
'No subscription. Sign in with InstantAdPay or LinkSpin, post your banner, share your link. {{LINK}}',
'One shared loop of 125x125 banners. Real visitors only, bots and repeat visits do not count. {{LINK}}'
],
headlines: ['Post a Banner Free Every Day', 'Every Visitor Pushes the Loop', 'Send Visitors, Climb the Weekly Leaderboard'],
email: {
subject: 'Post your banner free every day',
body: [
'Hi,',
'',
'Viral Banner Blitz is one shared loop of 125x125 banners, and every visitor moves it.',
'',
'If you are an InstantAdPay or LinkSpin member, you get a free post credit every day you sign in. Post a banner and a link and it joins the loop.',
'',
shift + ' every banner one place. When yours rides out the end, it has cycled and earns ' + views + '. Bots and repeat visits do not count.',
'',
'There are weekly leaderboards too, for the most visitors sent and the most traffic sources. The prize pot is at least ' + floor + ' a week, paid in POL to the top three on each board.',
'',
'It is advertising, not an income program, and there is no subscription.',
'',
'Here is my link:',
'{{LINK}}'
].join('\n')
},
posts: [
'If you are on InstantAdPay or LinkSpin, you can post a 125x125 banner on Viral Banner Blitz free every day. Real visitors push the loop, and when your banner rides out it earns network ad views.\n\n{{LINK}}',
'Viral Banner Blitz has weekly leaderboards: most visitors sent and most traffic sources. The prize pot is at least ' + floor + ' a week, paid in POL. Share your link and climb.\n\n{{LINK}}'
]
};
}
const NOTE = 'A banner that cycles earns advertising across the network, not cash. Nothing here is an income opportunity.';
const REF_RE = /^(?:[A-Za-z0-9_.-]{2,40}|0x[0-9a-fA-F]{40})$/;
const base = () => 'https://' + C.site;
let files = null;
function creatives() {
if (files) return files;
let names = []; try { names = fs.readdirSync(KIT_DIR).filter(f => /^vbb-[a-z]+-[a-z]+\.png$/.test(f)); } catch (e) {}
const out = [];
for (const angle of Object.keys(ANGLES)) for (const shape of Object.keys(SHAPES)) {
const f = 'vbb-' + angle + '-' + shape + '.png'; if (!names.includes(f)) continue;
const [w, h, label] = SHAPES[shape];
out.push({ key: angle + '-' + shape, angle, angleLabel: ANGLES[angle], shape, label, w, h, url: base() + '/art/kit/' + f });
}
return (files = out);
}
function kit(u) {
const ref = REF_RE.test(String(u || '')) ? String(u) : '';
const q = ref ? '?ref=' + encodeURIComponent(ref) : '';
const link = base() + '/' + q;
const fill = s => s.split('{{LINK}}').join(link);
const t = copy();
return {
v: 1, site: C.site, name: C.siteName, updated: '2026-11-14', username: ref || null,
tagline: 'One shared loop of 125x125 banners. Real visitors push it.',
links: [
{ key: 'home', label: 'Your link (the loop)', url: link },
{ key: 'how', label: 'How it works', url: base() + '/how' + q },
{ key: 'leaders', label: 'Weekly leaderboards', url: base() + '/leaders' + q }
],
linkTemplate: base() + '/?ref={username}',
creatives: creatives().map(c => Object.assign({}, c, { html: '<a href="' + link + '" target="_blank" rel="noopener"><img src="' + c.url + '" width="' + c.w + '" height="' + c.h + '" alt="Viral Banner Blitz"></a>' })),
lines: t.lines.map(fill), headlines: t.headlines, email: { subject: t.email.subject, body: fill(t.email.body) }, posts: t.posts.map(fill),
note: NOTE, promotePage: base() + '/promote'
};
}
// GET /api/promo-kit: public, CORS open (InstantAdPay reads it from the member's browser). /art/kit/* is served by the /art/ route.
// GET /promote: the member Promote page (public/promote.html).
function handle(req, res, u, sendFile) {
if (u.pathname === '/promote' && (req.method === 'GET' || req.method === 'HEAD') && sendFile) { sendFile(res, path.join(__dirname, 'public', 'promote.html')); return true; }
if (u.pathname !== '/api/promo-kit') return false;
const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type' };
if (req.method === 'OPTIONS') { res.writeHead(204, cors); res.end(); return true; }
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
res.writeHead(200, Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' }, cors));
res.end(JSON.stringify(kit(u.searchParams.get('u')))); return true;
}
module.exports = { kit, handle, creatives };
+5 -4
View File
@@ -22,20 +22,21 @@
<meta name="theme-color" content="#ffd400"> <meta name="theme-color" content="#ffd400">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png"> <link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap">
<link rel="stylesheet" href="/assets/vbb.css?v=2"> <link rel="stylesheet" href="/assets/vbb.css?v=4">
</head> </head>
<body> <body>
<main class="wrap"> <main class="wrap">
<section class="hero"><h1>Admin</h1><p class="lead">Loop status and the cycle reward ledger. Rewards are recorded only; nothing is credited yet.</p></section> <section class="hero"><h1>Admin</h1><p class="lead">Loop status, weekly prize payouts and the cycle reward ledger. Cycle rewards are recorded only; nothing is credited yet.</p></section>
<div class="card" id="tokCard"><div class="field"><label for="tok">Admin token</label><input id="tok" type="password" autocomplete="off"></div><button class="btn small" id="tokBtn">Open</button></div> <div class="card" id="tokCard"><div class="field"><label for="tok">Admin token</label><input id="tok" type="password" autocomplete="off"></div><button class="btn small" id="tokBtn">Open</button></div>
<div id="adm" hidden> <div id="adm" hidden>
<div class="card"><h2>Status</h2><div class="stats" id="aStats"></div><pre class="mono small scroll" id="aRaw" style="white-space:pre-wrap;max-height:320px"></pre></div> <div class="card"><h2>Status</h2><div class="stats" id="aStats"></div><pre class="mono small scroll" id="aRaw" style="white-space:pre-wrap;max-height:320px"></pre></div>
<div class="card" id="pzCard"><h2>Weekly prize payouts</h2><p class="muted small">Each Monday after midnight (Central) the app prepares last week's payout. Nothing is sent until you approve it here, and a week is paid once. Amounts in POL are quoted live and fixed when you approve.</p><div id="pzNow"></div><div id="pzWeeks"></div><div class="row"><button class="btn sec small" id="pzPrep">Prepare last week again</button></div></div>
<div class="card"><h2>Rewards by member</h2><div class="scroll" id="aMembers"></div></div> <div class="card"><h2>Rewards by member</h2><div class="scroll" id="aMembers"></div></div>
<div class="card"><h2>Ledger (newest first)</h2><div class="scroll" id="aLedger"></div></div> <div class="card"><h2>Ledger (newest first)</h2><div class="scroll" id="aLedger"></div></div>
</div> </div>
<div id="status" class="note" hidden></div> <div id="status" class="note" hidden></div>
</main> </main>
<script src="/assets/common.js?v=1"></script> <script src="/assets/common.js?v=3"></script>
<script src="/assets/admin.js?v=1"></script> <script src="/assets/admin.js?v=2"></script>
</body> </body>
</html> </html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+38
View File
@@ -13,12 +13,50 @@
['Shifts today', s.today.shifts], ['Cycles today', s.today.cycles], ['Visitors today', s.today.visits], ['Cycles total', s.totals.cycles], ['Views recorded', VBB.n(s.ledger.views)], ['Views credited', VBB.n(s.ledger.credited)], ['Members', s.members]] ['Shifts today', s.today.shifts], ['Cycles today', s.today.cycles], ['Visitors today', s.today.visits], ['Cycles total', s.totals.cycles], ['Views recorded', VBB.n(s.ledger.views)], ['Views credited', VBB.n(s.ledger.credited)], ['Members', s.members]]
.map(x => '<div class="stat"><b>' + esc(x[1]) + '</b><span>' + esc(x[0]) + '</span></div>').join(''); .map(x => '<div class="stat"><b>' + esc(x[1]) + '</b><span>' + esc(x[0]) + '</span></div>').join('');
$('aRaw').textContent = JSON.stringify(s, null, 2); $('aRaw').textContent = JSON.stringify(s, null, 2);
prizes(); setInterval(prizes, 30000);
const l = await get('/api/admin/ledger?n=300'); const l = await get('/api/admin/ledger?n=300');
const who = r => r.username ? '@' + r.username : VBB.short(r.address || r.owner); const who = r => r.username ? '@' + r.username : VBB.short(r.address || r.owner);
$('aMembers').innerHTML = l.members && l.members.length ? '<table class="t"><tr><th>Member</th><th class="n">Cycles</th><th class="n">Views</th></tr>' + l.members.map(m => '<tr><td>' + esc(who(m)) + '</td><td class="n">' + m.cycles + '</td><td class="n">' + VBB.n(m.views) + '</td></tr>').join('') + '</table>' : '<p class="muted">No cycles yet.</p>'; $('aMembers').innerHTML = l.members && l.members.length ? '<table class="t"><tr><th>Member</th><th class="n">Cycles</th><th class="n">Views</th></tr>' + l.members.map(m => '<tr><td>' + esc(who(m)) + '</td><td class="n">' + m.cycles + '</td><td class="n">' + VBB.n(m.views) + '</td></tr>').join('') + '</table>' : '<p class="muted">No cycles yet.</p>';
$('aLedger').innerHTML = l.entries && l.entries.length ? '<table class="t"><tr><th>When (CT)</th><th>Entry</th><th>Banner</th><th>Member</th><th class="n">Views</th><th>Status</th></tr>' $('aLedger').innerHTML = l.entries && l.entries.length ? '<table class="t"><tr><th>When (CT)</th><th>Entry</th><th>Banner</th><th>Member</th><th class="n">Views</th><th>Status</th></tr>'
+ l.entries.map(e => '<tr><td>' + esc(new Date(e.at).toLocaleString('en-US', { timeZone: 'America/Chicago' })) + '</td><td class="mono">' + esc(e.id) + '</td><td>#' + e.bannerId + '</td><td>' + esc(who(e)) + '</td><td class="n">' + VBB.n(e.views) + '</td><td>' + esc(e.status) + '</td></tr>').join('') + '</table>' : '<p class="muted">The ledger is empty.</p>'; + l.entries.map(e => '<tr><td>' + esc(new Date(e.at).toLocaleString('en-US', { timeZone: 'America/Chicago' })) + '</td><td class="mono">' + esc(e.id) + '</td><td>#' + e.bannerId + '</td><td>' + esc(who(e)) + '</td><td class="n">' + VBB.n(e.views) + '</td><td>' + esc(e.status) + '</td></tr>').join('') + '</table>' : '<p class="muted">The ledger is empty.</p>';
} }
// ---- weekly prize payouts: review, then "Approve and pay" (two clicks), once per week ----
const pst = { prepared: 'Waiting for approval', nothing: 'No winners', paying: 'Paying', sent: 'Sent, confirming', paid: 'Paid', partial: 'Partly paid: check below', 'claimed-elsewhere': 'Claimed elsewhere: check the wallet' };
async function prizes() {
const z = await get('/api/admin/prizes'); if (z.error) return;
const cur = z.current || {};
$('pzNow').innerHTML = '<p class="small">This week (' + esc(z.week) + '): sales $' + VBB.n(cur.salesUsd) + ' in ' + VBB.n(cur.purchases) + ' purchases, 10% = $' + VBB.n(cur.shareUsd) + ', pot $' + VBB.n(cur.potUsd)
+ (cur.topUpUsd > 0 ? ' (company top-up $' + VBB.n(cur.topUpUsd) + ')' : '') + (cur.atCap ? ' (at the cap)' : '') + '. Prize key: ' + (z.prize.keyOn ? esc(VBB.short(z.prize.keyAddress)) : 'not set') + '.</p>';
const tx = h => z.explorer ? '<a target="_blank" rel="noopener" href="' + esc(z.explorer + '/tx/' + h) + '">' + esc(h.slice(0, 10)) + '...</a>' : esc(h);
$('pzWeeks').innerHTML = (z.weeks || []).map(w => {
const q = w.quote || {};
const lines = w.transfers.map((t, i) => '<tr><td>' + esc(t.board) + '</td><td>' + t.place + '</td><td>' + esc(t.name) + '<br><span class="mono small">' + esc(t.address) + '</span></td><td class="n">' + VBB.n(t.count) + '</td><td class="n">$' + VBB.n(t.usd) + '</td><td class="n">'
+ esc(t.pol || (q.lines && q.lines[i] ? q.lines[i].pol : '')) + '</td><td>' + esc(t.status || '') + (t.tx ? ' ' + tx(t.tx) : '') + (t.error ? '<br><span class="small">' + esc(t.error) + '</span>' : '') + '</td></tr>').join('');
let foot = '';
if (w.status === 'prepared') {
foot = q.error ? '<p class="note err">' + esc(q.error) + '</p>'
: '<p class="small">POL at $' + Number(q.priceUsd).toFixed(4) + '. Needs ' + esc(q.totalPol) + ' POL + about ' + esc(q.gasPol) + ' POL gas. Prize wallet ' + esc(VBB.short(q.contractPrizeWallet || '')) + ' holds ' + esc(q.balancePol) + ' POL.'
+ (BigInt(q.shortWei || 0) > 0n ? ' <b>Short by ' + esc(q.shortPol) + ' POL.</b>' : '') + (q.keyMatches ? '' : ' <b>PRIZE_KEY is missing or is not the prize wallet.</b>') + '</p>'
+ '<button class="btn small" data-pay="' + esc(w.week) + '">Approve and pay</button>';
}
return '<div class="card" style="margin:12px 0"><h3>Week of ' + esc(w.week) + ': ' + esc(pst[w.status] || w.status) + '</h3><p class="small">Sales $' + VBB.n(w.salesUsd) + ', pot $' + VBB.n(w.potUsd) + ', paying $' + VBB.n(w.payUsd)
+ (w.unfilledUsd > 0 ? ', $' + VBB.n(w.unfilledUsd) + ' unfilled (stays in the prize wallet)' : '') + (w.payment && w.payment.priceUsd ? ', paid at $' + Number(w.payment.priceUsd).toFixed(4) + '/POL' : '') + '</p>'
+ (w.transfers.length ? '<div class="scroll"><table class="t"><tr><th>Board</th><th>#</th><th>Winner</th><th class="n">Count</th><th class="n">USD</th><th class="n">POL</th><th>Status</th></tr>' + lines + '</table></div>' : '<p class="muted">Nobody on the leaderboards that week.</p>') + foot + '</div>';
}).join('') || '<p class="muted">No weeks prepared yet.</p>';
document.querySelectorAll('[data-pay]').forEach(b => {
b.onclick = async () => {
const wk = b.dataset.pay;
if (!b.dataset.armed) { b.dataset.armed = '1'; b.textContent = 'Click again to send the POL for ' + wk; setTimeout(() => { if (b.isConnected) { delete b.dataset.armed; b.textContent = 'Approve and pay'; } }, 8000); return; }
b.disabled = true; b.textContent = 'Sending...';
const r = await VBB.getJSON('/api/admin/prizes/pay', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-admin-token': tok }, body: JSON.stringify({ week: wk, confirm: wk }) });
VBB.status(r.error || 'Payout sent for the week of ' + wk + '. Receipts confirm below.', r.error ? 'err' : 'ok'); prizes();
};
});
}
$('pzPrep').onclick = async () => {
const r = await VBB.getJSON('/api/admin/prizes/prepare', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-admin-token': tok }, body: '{}' });
VBB.status(r.error || 'Prepared the week of ' + r.week + '.', r.error ? 'err' : 'ok'); prizes();
};
$('tokBtn').onclick = () => { tok = $('tok').value.trim(); open(); }; $('tokBtn').onclick = () => { tok = $('tok').value.trim(); open(); };
$('tok').addEventListener('keydown', e => { if (e.key === 'Enter') $('tokBtn').click(); }); $('tok').addEventListener('keydown', e => { if (e.key === 'Enter') $('tokBtn').click(); });
if (tok) open(); if (tok) open();
+49
View File
@@ -0,0 +1,49 @@
// One-time purchases through VBBShop (Packages page + My Banners). The server builds the buy() call for the signed-in member
// (POST /api/my/order, with a fresh sponsor voucher when the network knows their sponsor); the member's own wallet sends it.
// The wallet that pays must be the member's VBB account: credits go to the paying wallet. After the transaction confirms the
// page waits for the purchase watcher to credit it (it reads only confirmed blocks).
window.VBBBuy = (function () {
const fmtPol = (wei, d) => { const s = (BigInt(wei) * 10n ** BigInt(d || 4) / 10n ** 18n).toString().padStart((d || 4) + 1, '0'); return s.slice(0, -(d || 4)) + '.' + s.slice(-(d || 4)); };
const short = a => VBB.short(a);
async function quote(sku, qty) { return VBB.getJSON('/api/quote?sku=' + sku + '&qty=' + (qty || 1)); }
// o: { sku, qty, ref, done(check) -> bool (credits arrived?), say(msg, cls) }
async function run(o) {
const say = o.say || VBB.status;
const c = await VBB.getConfig();
if (!c.shop || !c.shop.live) throw new Error('Purchases are not open right now.');
const me = await VBB.getJSON('/api/me');
if (!me.signedIn) throw new Error('Sign in first (My Banners), so the credits land on your account.');
say('Connecting your wallet...');
const addr = String(await VBBWallet.activeAddress(await VBBWallet.connect()) || '').toLowerCase();
if (!addr) throw new Error('No wallet connected. Tap Buy again and pick SafePal or any other crypto wallet.');
if (addr !== me.address) {
throw new Error('Your wallet is connected as ' + short(addr) + ', but your Viral Banner Blitz account is ' + short(me.address)
+ '. Purchases are credited to the wallet that pays, so switch your wallet app to ' + short(me.address)
+ ', or sign out and sign in with ' + short(addr) + '.');
}
const od = await VBB.post('/api/my/order', { sku: o.sku, qty: o.qty || 1, ref: o.ref || 0 });
if (od.error) throw new Error(od.error);
const value = BigInt(od.value);
try {
const bal = await VBBWallet.balance(addr);
if (bal < value) throw new Error('This wallet holds ' + fmtPol(bal) + ' POL. The purchase needs about ' + fmtPol(value) + ' POL plus a little gas. Add POL on Polygon and try again.');
} catch (e) { if (/holds/.test(e.message)) throw e; }
say('Confirm the payment in your wallet: about ' + fmtPol(value) + ' POL ($' + od.usd + '). Anything above the exact price comes straight back in the same transaction.');
const hash = await VBBWallet.sendTx(od.to, od.data, od.value);
const link = c.explorer ? c.explorer + '/tx/' + hash : '';
say('Payment sent. Waiting for the Polygon network to confirm it...');
const r = await VBBWallet.waitTx(hash);
if (r.status !== '0x1') throw new Error('The transaction did not go through, so nothing was charged except gas. ' + (link ? 'Details: ' + link : ''));
VBB.post('/api/my/paid', {}).catch(() => {});
say('Confirmed on Polygon. Your purchase shows up here within about a minute, once the network has a few more blocks on top of it.', 'ok');
// the watcher credits after its confirmations: poll the account
for (let i = 0; i < 72; i++) {
await new Promise(res => setTimeout(res, 5000));
if (i % 4 === 3) VBB.post('/api/my/paid', {}).catch(() => {});
try { if (await o.done()) return { hash, link, credited: true }; } catch (e) {}
}
return { hash, link, credited: false };
}
return { run, quote, fmtPol };
})();
+26 -3
View File
@@ -13,7 +13,7 @@ window.VBB = (function () {
function renderNav(active) { function renderNav(active) {
const nav = document.createElement('nav'); nav.className = 'top'; const nav = document.createElement('nav'); nav.className = 'top';
const links = [['/', 'The loop'], ['/leaders', 'Leaderboards'], ['/how', 'How it works'], ['/packages', 'Packages'], ['/my', 'My Banners']]; const links = [['/', 'The loop'], ['/leaders', 'Leaderboards'], ['/how', 'How it works'], ['/packages', 'Packages'], ['/promote', 'Promote'], ['/my', 'My Banners']];
nav.innerHTML = '<div class="wrap"><a class="brand" href="/"><img src="/art/mark.svg" alt="" width="36" height="36"><span><span class="wm">Viral Banner <b>Blitz</b></span>' nav.innerHTML = '<div class="wrap"><a class="brand" href="/"><img src="/art/mark.svg" alt="" width="36" height="36"><span><span class="wm">Viral Banner <b>Blitz</b></span>'
+ '<span class="by">Part of the Crypto Team Build Network</span></span></a><div class="links">' + '<span class="by">Part of the Crypto Team Build Network</span></span></a><div class="links">'
+ links.map(l => '<a href="' + l[0] + '"' + (l[0] === active ? ' class="on" aria-current="page"' : '') + '>' + l[1] + '</a>').join('') + '</div></div>'; + links.map(l => '<a href="' + l[0] + '"' + (l[0] === active ? ' class="on" aria-current="page"' : '') + '>' + l[1] + '</a>').join('') + '</div></div>';
@@ -21,11 +21,33 @@ window.VBB = (function () {
// inside a traffic-exchange frame, the member page opens in a new tab // inside a traffic-exchange frame, the member page opens in a new tab
if (framed) document.querySelectorAll('nav a[href="/my"]').forEach(a => { a.target = '_blank'; a.rel = 'noopener'; }); if (framed) document.querySelectorAll('nav a[href="/my"]').forEach(a => { a.target = '_blank'; a.rel = 'noopener'; });
} }
// network ad zones (Marty 2026-11-14, the Downline Banners pattern): LinkSpin zones on Marty's account, one per placement, each
// mounted once with a small 'Network' label. Footer (wide / phone), Leaderboards, My Banners, How it works; the 404 zone is in
// server.js. NEVER on the loop page (/) or admin. An empty id = that placement stays off.
const ZONES = { footWide: '', footPhone: '', leaders: '', my: '', how: '' };
function zone(el, key) {
if (!el || el.dataset.zoned || !ZONES[key]) return; el.dataset.zoned = '1'; el.classList.add('net-zone');
const lab = document.createElement('div'); lab.className = 'net-zone-label'; lab.textContent = 'Network';
const s = document.createElement('script'); s.async = true; s.src = 'https://linkspin.app/z.js'; s.setAttribute('data-zone', ZONES[key]);
el.appendChild(lab); el.appendChild(s);
}
function slot(after) { if (!after || !after.parentNode) return null; const d = document.createElement('div'); d.className = 'net-zone-slot'; after.parentNode.insertBefore(d, after.nextSibling); return d; }
function pageZones() {
const p = location.pathname.replace(/\/$/, '') || '/';
if (p === '/' || p === '/admin') return;
const card = id => { const el = $(id); return el ? el.closest('.card') : null; };
if (p === '/leaders') zone(slot(card('lbVisitors')), 'leaders');
if (p === '/my') zone(slot($('stats')), 'my');
if (p === '/how') zone(slot(document.querySelectorAll('main .card')[1]), 'how');
const za = document.createElement('div'); za.className = 'wrap net-zone-foot'; document.body.appendChild(za);
zone(za, window.innerWidth >= 760 ? 'footWide' : 'footPhone');
}
function renderFooter() { function renderFooter() {
pageZones();
const f = document.createElement('footer'); f.className = 'foot'; const f = document.createElement('footer'); f.className = 'foot';
f.innerHTML = '<div class="wrap"><p><b>Viral Banner Blitz</b>, part of the Crypto Team Build Network</p>' f.innerHTML = '<div class="wrap"><p><b>Viral Banner Blitz</b>, part of the Crypto Team Build Network</p>'
+ '<p>A banner that cycles earns advertising across the network, not cash. Nothing here is an income opportunity.</p>' + '<p>A banner that cycles earns advertising across the network, not cash. Nothing here is an income opportunity.</p>'
+ '<p><a href="/">The loop</a> &middot; <a href="/leaders">Leaderboards</a> &middot; <a href="/how">How it works</a> &middot; <a href="/packages">Packages</a> &middot; <a href="/my">My Banners</a></p></div>'; + '<p><a href="/">The loop</a> &middot; <a href="/leaders">Leaderboards</a> &middot; <a href="/how">How it works</a> &middot; <a href="/packages">Packages</a> &middot; <a href="/promote">Promote</a> &middot; <a href="/my">My Banners</a></p></div>';
document.body.appendChild(f); document.body.appendChild(f);
toasts(); toasts();
} }
@@ -50,10 +72,11 @@ window.VBB = (function () {
tick(); setInterval(tick, 25000); tick(); setInterval(tick, 25000);
} }
function tile(t, extra) { function tile(t, extra) {
const a = document.createElement('a'); a.className = 'tile' + (extra && extra.cls ? ' ' + extra.cls : ''); const a = document.createElement('a'); a.className = 'tile' + (t.look ? ' look' : '') + (extra && extra.cls ? ' ' + extra.cls : '');
a.href = t.href; a.target = '_blank'; a.rel = 'noopener'; a.href = t.href; a.target = '_blank'; a.rel = 'noopener';
a.innerHTML = '<img alt="' + esc(t.owner ? 'Banner by ' + t.owner : 'Member banner #' + t.id) + '" width="125" height="125" loading="lazy" referrerpolicy="no-referrer">' a.innerHTML = '<img alt="' + esc(t.owner ? 'Banner by ' + t.owner : 'Member banner #' + t.id) + '" width="125" height="125" loading="lazy" referrerpolicy="no-referrer">'
+ (extra && extra.pos ? '<span class="pos">' + esc(extra.pos) + '</span>' : '') + (t.owner ? '<span class="who">' + esc(t.owner) + '</span>' : ''); + (extra && extra.pos ? '<span class="pos">' + esc(extra.pos) + '</span>' : '') + (t.owner ? '<span class="who">' + esc(t.owner) + '</span>' : '');
if (t.look && t.teaser) { const s = document.createElement('span'); s.className = 'teaser'; s.textContent = t.teaser; a.appendChild(s); a.title = t.teaser; }
const img = a.querySelector('img'); img.src = t.img; img.onerror = () => { img.onerror = null; img.src = '/art/tile-fallback.svg'; }; const img = a.querySelector('img'); img.src = t.img; img.onerror = () => { img.onerror = null; img.src = '/art/tile-fallback.svg'; };
return a; return a;
} }
+21
View File
@@ -0,0 +1,21 @@
/* Promote page (2026-11-14), pop-art look. Neutral class names (kit-*), no ad/banner words. */
.kit-who{display:flex;gap:10px;flex-wrap:wrap;margin-top:10px}
.kit-who input{flex:1 1 220px;min-width:0;background:var(--bg2);border:var(--edge);border-radius:10px;padding:11px 12px;color:var(--ink);font:14px var(--mono)}
.kit-who input:focus{outline:3px solid var(--sky);outline-offset:1px}
.kit-row{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:10px 0;border-top:2px dashed var(--line)}
.kit-row:first-of-type{border-top:0}
.kit-l{flex:1 1 260px;min-width:0;display:flex;flex-direction:column;gap:3px}
.kit-lab{display:block;font:700 11px var(--mono);color:var(--muted);text-transform:uppercase;letter-spacing:.1em}
.kit-url{font-family:var(--mono);font-size:13.5px;overflow-wrap:anywhere;color:var(--sky);font-weight:700}
.kit-txt{flex:1 1 300px;margin:0;min-width:0}
.kit-pre{white-space:pre-wrap;font-family:var(--body);font-size:14.5px;line-height:1.55;margin:10px 0 0;padding:12px 14px;border-radius:12px;border:var(--edge);background:var(--bg2);overflow-wrap:anywhere}
.kit-tabs{display:flex;gap:8px;flex-wrap:wrap;margin:6px 0 16px}
.kit-tab{font:800 14px/1 var(--disp);padding:9px 13px;border-radius:999px;border:2.5px solid var(--ink);background:var(--panel);color:var(--ink);cursor:pointer;box-shadow:var(--shadow-sm)}
.kit-tab.on{background:var(--amber)}
.kit-set{display:flex;flex-wrap:wrap;gap:18px;align-items:flex-start}
.kit-fig{margin:0;display:flex;flex-direction:column;gap:8px;max-width:100%}
.kit-fig img{display:block;max-width:100%;height:auto;border-radius:6px}
.kit-social img{width:600px} .kit-square img{width:360px}
.kit-fig figcaption{font-size:13px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}
.kit-acts{display:flex;gap:6px;flex-wrap:wrap;width:100%}
.kit-note{margin:6px 0 24px}
+49
View File
@@ -0,0 +1,49 @@
// Promote page renderer (2026-11-14). Draws a promo kit (GET /api/promo-kit) into a container: links, creatives grouped by angle,
// swipe lines, headlines, an email and social posts, each with a copy button. Same file on Downline Banners and Viral Banner Blitz;
// the page script decides the username and the look comes from the site's own CSS (.card, .btn, .kit-*).
window.KitPage = (function () {
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
async function copy(text, btn) {
try { await navigator.clipboard.writeText(text); } catch (e) {
const t = document.createElement('textarea'); t.value = text; document.body.appendChild(t); t.select(); try { document.execCommand('copy'); } catch (e2) {} t.remove();
}
if (btn) { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => { btn.textContent = o; }, 1400); }
}
const TXT = [];
const cb = (text, label, cls) => { TXT.push(text); return '<button type="button" class="btn small ' + (cls || 'sec') + '" data-kc="' + (TXT.length - 1) + '">' + esc(label || 'Copy') + '</button>'; };
// on the kit's own site, show creatives from this origin (same files; the copied URL stays absolute)
function local(url, k) { try { const u = new URL(url); return u.hostname === k.site && location.hostname !== k.site ? u.pathname : url; } catch (e) { return url; } }
function render(root, k) {
TXT.length = 0;
const angles = []; const by = {};
(k.creatives || []).forEach(c => { if (!by[c.angle]) { by[c.angle] = []; angles.push(c); } by[c.angle].push(c); });
let h = '';
h += '<div class="card"><h3>Your links</h3>' + (k.username ? '<p class="muted small">Every link, creative and line below carries <b>' + esc(k.username) + '</b>.</p>' : '<p class="muted small">Add your network username above so these links carry it.</p>')
+ k.links.map(l => '<div class="kit-row"><div class="kit-l"><span class="kit-lab">' + esc(l.label) + '</span><code class="kit-url">' + esc(l.url) + '</code></div>' + cb(l.url, 'Copy link', '') + '</div>').join('') + '</div>';
h += '<div class="card"><h3>Creatives</h3><p class="muted small">Download them, or copy the HTML: it already links to you.</p><div class="kit-tabs" role="tablist">'
+ angles.map((c, i) => '<button type="button" class="kit-tab' + (i ? '' : ' on') + '" data-ka="' + esc(c.angle) + '">' + esc(c.angleLabel) + '</button>').join('') + '</div>';
angles.forEach((a, i) => {
h += '<div class="kit-set" data-ks="' + esc(a.angle) + '"' + (i ? ' hidden' : '') + '>' + by[a.angle].map(c =>
'<figure class="kit-fig kit-' + esc(c.shape) + '"><a href="' + esc(c.url) + '" target="_blank" rel="noopener"><img src="' + esc(local(c.url, k)) + '" alt="' + esc(k.name + ', ' + c.label) + '" width="' + c.w + '" height="' + c.h + '" loading="lazy"></a>'
+ '<figcaption><b>' + esc(c.label) + '</b> <span class="muted">' + c.w + 'x' + c.h + '</span><span class="kit-acts"><a class="btn small sec" href="' + esc(c.url) + '" download>Download</a>' + cb(c.url, 'Copy URL') + cb(c.html, 'Copy HTML') + '</span></figcaption></figure>').join('') + '</div>';
});
h += '</div>';
h += '<div class="card"><h3>Short lines</h3><p class="muted small">For chats, comments, text ads and signatures.</p>' + k.lines.map(t => '<div class="kit-row"><p class="kit-txt">' + esc(t) + '</p>' + cb(t) + '</div>').join('') + '</div>';
h += '<div class="card"><h3>Headlines</h3>' + k.headlines.map(t => '<div class="kit-row"><p class="kit-txt"><b>' + esc(t) + '</b></p>' + cb(t) + '</div>').join('') + '</div>';
h += '<div class="card"><h3>Email</h3><div class="kit-row"><p class="kit-txt"><span class="kit-lab">Subject</span>' + esc(k.email.subject) + '</p>' + cb(k.email.subject, 'Copy subject') + '</div>'
+ '<pre class="kit-pre">' + esc(k.email.body) + '</pre><div class="kit-row" style="justify-content:flex-end">' + cb(k.email.body, 'Copy email') + '</div></div>';
h += '<div class="card"><h3>Social posts</h3>' + k.posts.map(t => '<div class="kit-post"><pre class="kit-pre">' + esc(t) + '</pre><div class="kit-row" style="justify-content:flex-end">' + cb(t, 'Copy post') + '</div></div>').join('') + '</div>';
if (k.note) h += '<p class="muted small kit-note">' + esc(k.note) + '</p>';
root.innerHTML = h;
root.querySelectorAll('[data-kc]').forEach(b => b.addEventListener('click', () => copy(TXT[Number(b.dataset.kc)], b)));
root.querySelectorAll('[data-ka]').forEach(b => b.addEventListener('click', () => {
root.querySelectorAll('[data-ka]').forEach(x => x.classList.toggle('on', x === b));
root.querySelectorAll('[data-ks]').forEach(s => { s.hidden = s.dataset.ks !== b.dataset.ka; });
}));
}
async function load(root, u) {
const r = await fetch('/api/promo-kit' + (u ? '?u=' + encodeURIComponent(u) : ''), { cache: 'no-store' });
const k = await r.json(); render(root, k); return k;
}
return { render, load, copy };
})();
+13 -1
View File
@@ -2,7 +2,7 @@
(async function () { (async function () {
VBB.renderNav('/leaders'); VBB.renderFooter(); VBB.renderNav('/leaders'); VBB.renderFooter();
const $ = VBB.$, esc = VBB.esc; const $ = VBB.$, esc = VBB.esc;
// weekly prize pot (Marty 2026-11-13): grows with sales from a floor; displayed only, no payout code yet // weekly prize pot (Marty 2026-11-13): grows with sales from a floor; paid each Monday after an admin approves it (prize.js)
const c = await VBB.getConfig().catch(() => ({})); const c = await VBB.getConfig().catch(() => ({}));
const pz = c.prizes || {}; const place = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th']; const pz = c.prizes || {}; const place = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th'];
const plist = (title, arr) => '<div><h3>' + title + '</h3><ul class="pk-list">' + arr.map((v, i) => '<li>' + place[i] + ': $' + VBB.n(v) + ' in POL</li>').join('') + '</ul></div>'; const plist = (title, arr) => '<div><h3>' + title + '</h3><ul class="pk-list">' + arr.map((v, i) => '<li>' + place[i] + ': $' + VBB.n(v) + ' in POL</li>').join('') + '</ul></div>';
@@ -20,4 +20,16 @@
: '<p class="muted">Nobody yet this week. Share your link from <a href="/my">My Banners</a> and take the top spot.</p>'; : '<p class="muted">Nobody yet this week. Share your link from <a href="/my">My Banners</a> and take the top spot.</p>';
$('lbVisitors').innerHTML = table(d.visitors, 'visitors'); $('lbVisitors').innerHTML = table(d.visitors, 'visitors');
$('lbSources').innerHTML = table(d.sources, 'sources'); $('lbSources').innerHTML = table(d.sources, 'sources');
// past weeks: winners and their payment transactions
const pr = await VBB.getJSON('/api/prizes').catch(() => ({}));
if (pr.past && pr.past.length) {
const bn = { visitors: 'Most visitors sent', sources: 'Most traffic sources' };
$('past').innerHTML = pr.past.map(w => {
const day = new Date(w.week + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric', timeZone: 'UTC' });
const rows = w.winners.map(x => '<tr><td>' + esc(bn[x.board] || x.board) + '</td><td><span class="rank">' + x.place + '</span></td><td>' + esc(x.name) + '</td><td class="n">$' + VBB.n(x.usd) + '</td><td class="n">' + esc(x.pol) + ' POL</td><td>'
+ (pr.explorer ? '<a target="_blank" rel="noopener" href="' + esc(pr.explorer + '/tx/' + x.tx) + '">' + (x.confirmed ? 'Paid' : 'Sent') + '</a>' : esc(x.tx.slice(0, 10))) + '</td></tr>').join('');
return '<div class="wk"><h3>Week of ' + esc(day) + '</h3><p class="muted small">Prize pot $' + VBB.n(w.potUsd) + (w.priceUsd ? ', POL at $' + Number(w.priceUsd).toFixed(4) : '') + '</p><div class="scroll"><table class="t"><tr><th>Board</th><th>#</th><th>Member</th><th class="n">USD</th><th class="n">POL</th><th>Transaction</th></tr>' + rows + '</table></div></div>';
}).join('');
$('pastCard').hidden = false;
}
})(); })();
+29 -2
View File
@@ -45,7 +45,33 @@
const where = b => b.state === 'queued' ? '<span class="pill queued">Waiting</span><br>Number ' + b.position + ' of ' + b.of + ' in line' const where = b => b.state === 'queued' ? '<span class="pill queued">Waiting</span><br>Number ' + b.position + ' of ' + b.of + ' in line'
: b.state === 'loop' ? '<span class="pill loop">In the loop</span><br>Place ' + b.place + ' of ' + b.of + ', rides out in about ' + b.shiftsToRideOut + ' shift' + (b.shiftsToRideOut === 1 ? '' : 's') : b.state === 'loop' ? '<span class="pill loop">In the loop</span><br>Place ' + b.place + ' of ' + b.of + ', rides out in about ' + b.shiftsToRideOut + ' shift' + (b.shiftsToRideOut === 1 ? '' : 's')
: '<span class="pill cycled">Cycled</span><br>' + (b.cycledAt ? new Date(b.cycledAt).toLocaleString() : ''); : '<span class="pill cycled">Cycled</span><br>' + (b.cycledAt ? new Date(b.cycledAt).toLocaleString() : '');
// banner look (SKU 3): buy it for a banner that is waiting or in the loop; with the look, edit its hover teaser
let buying = false, editing = false;
function lookRow(row, b) {
if (b.look) {
row.innerHTML = '<span class="pill look">Banner look</span><input maxlength="40" aria-label="Hover teaser for banner #' + b.id + '"><button class="btn sec small">Save teaser</button>';
const inp = row.querySelector('input'); inp.value = b.teaser; inp.placeholder = b.teaserDefault || 'Your teaser line';
inp.addEventListener('focus', () => { editing = true; }); inp.addEventListener('blur', () => { editing = false; });
row.querySelector('button').onclick = async () => {
const r = await VBB.post('/api/my/banners/' + b.id + '/teaser', { teaser: inp.value });
editing = false; VBB.status(r.error || 'Teaser saved: "' + r.teaser + '" shows when someone points at your banner.', r.error ? 'err' : 'ok');
};
return;
}
if (b.state === 'cycled' || !shopLive) return;
row.innerHTML = '<button class="btn amber small">Add the banner look ($' + (c.lookUsd || 2) + ')</button>';
row.querySelector('button').onclick = async () => {
if (buying) return; buying = true; document.querySelectorAll('.look-row .btn.amber').forEach(x => { x.disabled = true; });
try {
const r = await VBBBuy.run({ sku: c.lookSku || 3, qty: 1, ref: b.id, done: async () => { const m = await VBB.getJSON('/api/my'); return (m.banners || []).some(x => x.id === b.id && x.look); } });
VBB.status(r.credited ? 'Banner #' + b.id + ' now has the look in the loop. Write its teaser line below the banner.' : 'Paid and confirmed. The look appears on banner #' + b.id + ' within a few minutes.', 'ok');
} catch (e) { VBB.status(String(e && e.message || e).slice(0, 400), 'err'); }
finally { buying = false; load(); }
};
}
const shopLive = !!(c.shop && c.shop.live);
async function load() { async function load() {
if (buying || editing) return;
const d = await VBB.getJSON('/api/my'); const d = await VBB.getJSON('/api/my');
if (d.error) return VBB.status(d.error, 'err'); if (d.error) return VBB.status(d.error, 'err');
$('dash').hidden = false; $('dash').hidden = false;
@@ -56,12 +82,13 @@
$('creditNote').textContent = !d.netVerified ? 'Free daily credits are for network members. Sign in through InstantAdPay or LinkSpin, or make a free InstantAdPay account with this wallet, and your free credit arrives each day you sign in. You can have up to ' + d.maxQueued + ' banners waiting at once.' : (d.grantedNow ? 'Your free credit for today was just added. ' : d.freeToday ? 'Today\'s free credit is in. ' : '') $('creditNote').textContent = !d.netVerified ? 'Free daily credits are for network members. Sign in through InstantAdPay or LinkSpin, or make a free InstantAdPay account with this wallet, and your free credit arrives each day you sign in. You can have up to ' + d.maxQueued + ' banners waiting at once.' : (d.grantedNow ? 'Your free credit for today was just added. ' : d.freeToday ? 'Today\'s free credit is in. ' : '')
+ 'One free credit arrives each day you sign in (they bank up to ' + d.freeCreditCap + '). You can have up to ' + d.maxQueued + ' banners waiting at once.'; + 'One free credit arrives each day you sign in (they bank up to ' + d.freeCreditCap + '). You can have up to ' + d.maxQueued + ' banners waiting at once.';
$('postBtn').disabled = d.credits < 1; $('postBtn').disabled = d.credits < 1;
if (d.credits < 1) VBB.status('You have used your credits. Come back tomorrow for a free one.'); if (d.credits < 1) $('creditNote').textContent += (shopLive ? ' Out of credits: get a pack on the Packages page, or come back tomorrow for a free one.' : '');
$('mine').innerHTML = d.banners.length ? '' : '<p class="muted">No banners yet. Post your first one above.</p>'; $('mine').innerHTML = d.banners.length ? '' : '<p class="muted">No banners yet. Post your first one above.</p>';
for (const b of d.banners) { for (const b of d.banners) {
const el = document.createElement('div'); el.className = 'item'; const el = document.createElement('div'); el.className = 'item';
el.innerHTML = '<img alt="Banner #' + b.id + '" width="72" height="72"><div class="s">' + where(b) + '<br><a target="_blank" rel="noopener"></a><br><span class="muted">' + VBB.n(b.clicks) + ' clicks</span></div>'; el.innerHTML = '<img alt="Banner #' + b.id + '" width="72" height="72"><div class="s">' + where(b) + '<br><a target="_blank" rel="noopener"></a><br><span class="muted">' + VBB.n(b.clicks) + ' clicks</span><div class="look-row"></div></div>';
el.querySelector('img').src = b.img; const a = el.querySelector('a'); a.href = b.link; a.textContent = b.link.replace(/^https:\/\//, '').slice(0, 60); el.querySelector('img').src = b.img; const a = el.querySelector('a'); a.href = b.link; a.textContent = b.link.replace(/^https:\/\//, '').slice(0, 60);
lookRow(el.querySelector('.look-row'), b);
$('mine').appendChild(el); $('mine').appendChild(el);
} }
$('share').value = d.share; $('share').value = d.share;
+49
View File
@@ -0,0 +1,49 @@
// Packages: live POL prices from the contract, Buy buttons for the post credit packs (one-time, never a subscription).
(async function () {
VBB.renderNav('/packages'); VBB.renderFooter();
const $ = VBB.$;
const c = await VBB.getConfig().catch(() => ({}));
const money = v => '$' + (Number.isInteger(v) ? v : Number(v).toFixed(2));
if (c.lookUsd) $('pkLook').textContent = money(c.lookUsd) + ' per banner';
const packs = (c.packs || []).slice(0, 2);
packs.forEach((p, i) => { const el = $('pkPack' + i); if (!el) return;
el.querySelector('[data-pk=credits]').textContent = VBB.n(p.credits); el.querySelector('[data-pk=usd]').textContent = money(p.usd); });
const live = !!(c.shop && c.shop.live);
let me = await VBB.getJSON('/api/me').catch(() => ({}));
function who() {
if (!live) { $('pkWho').textContent = 'Purchases are paused right now. Check back soon.'; return; }
if (me.signedIn) { $('pkWho').textContent = 'Signed in as ' + (me.username ? '@' + me.username : VBB.short(me.address)) + '. Pay from this same wallet (' + VBB.short(me.address) + ') and the credits land on your account.'; $('pkSign').hidden = true; }
else { $('pkWho').textContent = 'Sign in first, so your credits land on your account. Then pay from the same wallet.'; $('pkSign').hidden = false; }
}
who();
$('pkSignBtn').onclick = async () => {
try { VBB.status('Check your wallet for the sign-in message.'); await VBBWallet.signIn(); me = await VBB.getJSON('/api/me'); VBB.status('Signed in.', 'ok'); who(); }
catch (e) { VBB.status(String(e && e.message || e).slice(0, 300), 'err'); }
};
async function prices() {
if (!live) return;
for (let i = 0; i < packs.length; i++) {
const el = $('pkPack' + i); if (!el) continue;
const q = await VBBBuy.quote(packs[i].sku, 1).catch(() => ({ error: 'x' }));
el.querySelector('[data-pk=pol]').textContent = q.error ? 'price unavailable' : 'about ' + VBBBuy.fmtPol(q.wei, 2) + ' POL right now';
}
}
await prices(); setInterval(prices, 60000);
let busy = false;
packs.forEach((p, i) => {
const el = $('pkPack' + i); if (!el) return; const btn = el.querySelector('[data-pk=buy]');
btn.textContent = 'Buy ' + VBB.n(p.credits) + ' credits'; btn.disabled = !live;
btn.onclick = async () => {
if (busy) return; busy = true; document.querySelectorAll('[data-pk=buy]').forEach(b => { b.disabled = true; });
try {
const before = (await VBB.getJSON('/api/my')).credits;
if (before == null) throw new Error('Sign in first, so the credits land on your account.');
const r = await VBBBuy.run({ sku: p.sku, qty: 1, done: async () => { const d = await VBB.getJSON('/api/my'); return d.credits >= before + p.credits; } });
const tx = r.link ? ' Transaction: ' + r.link : '';
VBB.status(r.credited ? VBB.n(p.credits) + ' post credits added to your account. Post your banners on My Banners.' + tx
: 'Paid and confirmed. Your credits are on the way and appear on My Banners within a few minutes.' + tx, 'ok');
} catch (e) { VBB.status(String(e && e.message || e).slice(0, 400), 'err'); }
finally { busy = false; document.querySelectorAll('[data-pk=buy]').forEach(b => { b.disabled = !live; }); }
};
});
})();
+25
View File
@@ -0,0 +1,25 @@
// Promote page (2026-11-14): the promo kit from /api/promo-kit with the member's network username in every link.
// Username: ?u= first, then the signed-in member's (My Banners), then the last one typed here (this browser only).
(async function () {
VBB.renderNav('/promote'); VBB.renderFooter();
const $ = VBB.$; const RE = /^(?:[A-Za-z0-9_.-]{2,40}|0x[0-9a-fA-F]{40})$/;
let u = new URLSearchParams(location.search).get('u') || '';
let signed = false;
if (!RE.test(u)) {
u = '';
try { const me = await VBB.getJSON('/api/me'); if (me.signedIn) { u = me.username || me.address || ''; signed = true; } } catch (e) {}
}
if (!u) { try { u = localStorage.getItem('kit.u') || ''; } catch (e) {} if (!RE.test(u)) u = ''; }
$('whoIn').value = u;
if (signed) $('whoNote').textContent = 'Signed in: your links below use ' + (u.startsWith('0x') ? 'your wallet (no network username found yet)' : '@' + u) + '.';
async function show(name) {
try { await KitPage.load($('kit'), name); VBB.status(''); } catch (e) { VBB.status('Could not load the kit. Try again in a moment.', 'err'); }
}
$('whoForm').addEventListener('submit', e => {
e.preventDefault(); const v = $('whoIn').value.trim().replace(/^@/, '');
if (v && !RE.test(v)) return VBB.status('That does not look like a username: letters, numbers, dot, dash or underscore.', 'err');
try { localStorage.setItem('kit.u', v); } catch (e2) {}
show(v);
});
show(u);
})();
+1 -1
View File
@@ -15,7 +15,7 @@
const t = d.today || {}; const t = d.today || {};
$('today').textContent = VBB.n(t.shifts) + ' shifts and ' + VBB.n(t.cycles) + ' cycles today'; $('today').textContent = VBB.n(t.shifts) + ' shifts and ' + VBB.n(t.cycles) + ' cycles today';
// the loop // the loop
const ids = d.loop.map(x => x.id).join(','); const ids = d.loop.map(x => x.id + (x.look ? '*' + x.teaser : '')).join(','); // a new banner look repaints too
if (ids !== lastLoop) { if (ids !== lastLoop) {
lastLoop = ids; const g = $('loop'); g.innerHTML = ''; lastLoop = ids; const g = $('loop'); g.innerHTML = '';
const full = d.loop.length >= d.loopSize; const full = d.loop.length >= d.loopSize;
+1 -1
View File
@@ -7,7 +7,7 @@
if (c.perShift) set('perShift', c.perShift); if (c.perShift) set('perShift', c.perShift);
if (c.viewsPerCycle != null) set('views', VBB.n(c.viewsPerCycle)); if (c.viewsPerCycle != null) set('views', VBB.n(c.viewsPerCycle));
if (c.visitSeconds) set('secs', c.visitSeconds); if (c.visitSeconds) set('secs', c.visitSeconds);
// planned package prices from config (Marty 2026-11-13); still coming soon, nothing is sold here // package prices from config (the Packages page has its own script, packages.js, with the Buy buttons)
const money = v => '$' + (Number.isInteger(v) ? v : Number(v).toFixed(2)); const money = v => '$' + (Number.isInteger(v) ? v : Number(v).toFixed(2));
const pp = document.getElementById('pkPacks'); const pp = document.getElementById('pkPacks');
if (pp && c.packs && c.packs.length) pp.innerHTML = c.packs.map(p => '<li>' + VBB.n(p.credits) + ' post credits for ' + money(p.usd) + '</li>').join(''); if (pp && c.packs && c.packs.length) pp.innerHTML = c.packs.map(p => '<li>' + VBB.n(p.credits) + ' post credits for ' + money(p.usd) + '</li>').join('');
+17
View File
@@ -155,3 +155,20 @@ footer.foot a{color:var(--amber)} footer.foot p{margin:6px 0}
.toast.in{opacity:1;transform:rotate(-1deg)} .toast span{color:var(--muted);font-size:12.5px} .toast.in{opacity:1;transform:rotate(-1deg)} .toast span{color:var(--muted);font-size:12.5px}
[hidden]{display:none!important} [hidden]{display:none!important}
@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}} @media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
/* network zones (2026-11-14): neutral class names, centered, small label */
.net-zone{display:flex;flex-direction:column;align-items:center;gap:4px;margin:18px auto;max-width:100%;overflow:hidden}
.net-zone-label{font:700 10.5px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
/* banner look (SKU 3, 2026-11-14): a bright double border + a teaser line on hover (always shown on touch screens) */
.tile.look{border:3px solid var(--hot);box-shadow:0 0 0 3px var(--amber),5px 5px 0 3px var(--ink);animation:lookglow 2.4s ease-in-out infinite}
@keyframes lookglow{50%{box-shadow:0 0 0 3px var(--sky),5px 5px 0 3px var(--ink)}}
.tile.look::after{content:"\2605";position:absolute;right:4px;top:3px;font:700 13px/1 var(--body);color:var(--amber);-webkit-text-stroke:1px var(--ink)}
.tile .teaser{position:absolute;left:0;right:0;bottom:0;padding:6px 6px 7px;background:var(--hot);color:#fff;font:700 11px/1.25 var(--body);text-align:center;transform:translateY(100%);transition:transform .18s ease;white-space:normal;overflow:hidden;max-height:60%}
.tile.look:hover .teaser,.tile.look:focus-visible .teaser{transform:none}
.tile.look:hover .who,.tile.look:focus-visible .who{opacity:0}
@media (hover:none){.tile.look .teaser{transform:none;font-size:9.5px;padding:3px 4px}}
.pk-usd{margin:2px 0 8px}.pk-usd b{font:800 22px/1.1 var(--disp)}
.pk-intro{text-align:center}
.mine .item .look-row{display:flex;gap:6px;flex-wrap:wrap;align-items:center;margin-top:6px}
.mine .item .look-row input{flex:1;min-width:120px;background:var(--panel);border:2px solid var(--ink);border-radius:8px;padding:6px 8px;font:13px var(--body)}
.pill.look{background:var(--hot);color:#fff}
.past{display:grid;gap:12px}.past .wk{background:var(--bg2);border:var(--edge);border-radius:14px;padding:12px 14px}
+36 -2
View File
@@ -1,5 +1,6 @@
// Viral Banner Blitz wallet sign-in: Downline Banners' wallet.js (same AppKit build, chain guard, dead-session recovery) // Viral Banner Blitz wallet sign-in: Downline Banners' wallet.js (same AppKit build, chain guard, dead-session recovery)
// with the buy functions removed. VBB v1 only signs a free sign-in message; it never sends a transaction. // with its buy flow (2026-11-14): sendTx() hard-guards the chain, sets Polygon's fee floor from /api/gas and recovers a dead
// WalletConnect session once; waitTx() polls /api/tx; balance() is the pre-flight check. The page builds the call on the server.
window.VBBWallet = (function () { window.VBBWallet = (function () {
const pad = v => BigInt(v).toString(16).padStart(64, '0'); const pad = v => BigInt(v).toString(16).padStart(64, '0');
const padAddr = a => { if (!a) return pad(0); if (!/^0x[0-9a-fA-F]{40}$/.test(a)) throw new Error('Bad address: ' + a); return a.slice(2).toLowerCase().padStart(64, '0'); }; const padAddr = a => { if (!a) return pad(0); if (!/^0x[0-9a-fA-F]{40}$/.test(a)) throw new Error('Bad address: ' + a); return a.slice(2).toLowerCase().padStart(64, '0'); };
@@ -186,6 +187,39 @@ window.VBBWallet = (function () {
return r; return r;
} }
async function sendTx(to, data, valueHex) {
const c = await VBB.getConfig();
const addr = await connect();
const wantNum = Number(c.chainId);
let cur; try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) {}
if (!isNaN(chainNum(cur)) && chainNum(cur) !== wantNum) {
await ensureChain(c);
try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) {}
if (!isNaN(chainNum(cur)) && chainNum(cur) !== wantNum)
throw new Error('Your wallet is on the wrong network. Switch it to ' + (c.chainName || 'Polygon') + ', then try again.');
}
const tx = { from: await activeAddress(addr), to, data };
if (valueHex) tx.value = valueHex;
try { const g = await (await fetch('/api/gas')).json(); if (g && g.maxPriorityFeePerGas && g.maxFeePerGas) { tx.maxPriorityFeePerGas = g.maxPriorityFeePerGas; tx.maxFeePerGas = g.maxFeePerGas; } } catch (e) {}
try { return await eth().request({ method: 'eth_sendTransaction', params: [tx] }); }
catch (e) {
if (!isDead(e)) throw e;
tx.from = await freshConnect(c);
return eth().request({ method: 'eth_sendTransaction', params: [tx] });
}
}
async function waitTx(hash) {
for (let i = 0; i < 120; i++) {
try { const r = await (await fetch('/api/tx/' + hash)).json(); if (r.found) return r; } catch (e) { /* app switch on a phone: keep polling */ }
await new Promise(res => setTimeout(res, 2500));
}
throw new Error('Still waiting for the transaction. Check it on the explorer; your credits arrive once it confirms.');
}
async function balance(addr) {
await connect();
return BigInt(await eth().request({ method: 'eth_getBalance', params: [addr || currentAddress(), 'latest'] }));
}
async function disconnect() { async function disconnect() {
// AppKit's disconnect can hang on the WalletConnect relay (esp. mobile) — // AppKit's disconnect can hang on the WalletConnect relay (esp. mobile) —
// never block on it, so the UI can't get stuck "disconnecting". // never block on it, so the UI can't get stuck "disconnecting".
@@ -195,5 +229,5 @@ window.VBBWallet = (function () {
} }
function walletName() { try { const w = modal && modal.getWalletInfo && modal.getWalletInfo(); return (w && w.name) || ''; } catch (e) { return ''; } } function walletName() { try { const w = modal && modal.getWalletInfo && modal.getWalletInfo(); return (w && w.name) || ''; } catch (e) { return ''; } }
return { connect, signIn, disconnect, address: currentAddress, activeAddress, pickAccount, walletName }; return { connect, signIn, sendTx, waitTx, balance, disconnect, address: currentAddress, activeAddress, pickAccount, walletName };
})(); })();
+8 -2
View File
@@ -22,7 +22,7 @@
<meta name="theme-color" content="#ffd400"> <meta name="theme-color" content="#ffd400">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png"> <link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap">
<link rel="stylesheet" href="/assets/vbb.css?v=2"> <link rel="stylesheet" href="/assets/vbb.css?v=4">
</head> </head>
<body> <body>
<main class="wrap"> <main class="wrap">
@@ -45,11 +45,17 @@
<div class="card"> <div class="card">
<h2>Weekly leaderboards</h2> <h2>Weekly leaderboards</h2>
<p>Share your link (it ends in <span class="mono">?ref=</span> and your network username). The leaderboards count the verified visitors you send each week and how many different websites they came from.</p> <p>Share your link (it ends in <span class="mono">?ref=</span> and your network username). The leaderboards count the verified visitors you send each week and how many different websites they came from.</p>
<p>Each week the top three on each leaderboard share the prize pot, paid in POL to the wallet of their Viral Banner Blitz account the following Monday. Ties go to whoever reached the count first. Past winners and their payment transactions are on the leaderboard page.</p>
<div class="row"><a class="btn small" href="/my">Get my link</a><a class="btn quiet small" href="/leaders">See the leaders</a></div> <div class="row"><a class="btn small" href="/my">Get my link</a><a class="btn quiet small" href="/leaders">See the leaders</a></div>
</div> </div>
<div class="card">
<h2>Packages</h2>
<p>Want to post more than once a day? Post credit packs and the banner look (a bright border plus a teaser line) are one-time purchases in POL with SafePal or any other crypto wallet. Never a subscription.</p>
<div class="row"><a class="btn small" href="/packages">See the packages</a></div>
</div>
<div id="status" class="note" hidden></div> <div id="status" class="note" hidden></div>
</main> </main>
<script src="/assets/common.js?v=1"></script> <script src="/assets/common.js?v=3"></script>
<script src="/assets/static.js?v=1"></script> <script src="/assets/static.js?v=1"></script>
</body> </body>
</html> </html>
+3 -3
View File
@@ -23,7 +23,7 @@
<meta name="theme-color" content="#ffd400"> <meta name="theme-color" content="#ffd400">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png"> <link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap">
<link rel="stylesheet" href="/assets/vbb.css?v=2"> <link rel="stylesheet" href="/assets/vbb.css?v=4">
</head> </head>
<body> <body>
<main class="wrap"> <main class="wrap">
@@ -55,7 +55,7 @@
</div> </div>
<div id="status" class="note" hidden></div> <div id="status" class="note" hidden></div>
</main> </main>
<script src="/assets/common.js?v=1"></script> <script src="/assets/common.js?v=3"></script>
<script src="/assets/splash.js?v=1"></script> <script src="/assets/splash.js?v=2"></script>
</body> </body>
</html> </html>
+4 -3
View File
@@ -22,7 +22,7 @@
<meta name="theme-color" content="#ffd400"> <meta name="theme-color" content="#ffd400">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png"> <link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap">
<link rel="stylesheet" href="/assets/vbb.css?v=2"> <link rel="stylesheet" href="/assets/vbb.css?v=4">
</head> </head>
<body> <body>
<main class="wrap"> <main class="wrap">
@@ -30,9 +30,10 @@
<div class="card" id="prizes" hidden><h2>Weekly prizes</h2><p class="muted small" id="potLbl">Paid in POL to the top three on each leaderboard for the week (dollar value, converted to POL).</p><div class="pz" id="pz"></div></div> <div class="card" id="prizes" hidden><h2>Weekly prizes</h2><p class="muted small" id="potLbl">Paid in POL to the top three on each leaderboard for the week (dollar value, converted to POL).</p><div class="pz" id="pz"></div></div>
<div class="card"><h2>Most visitors sent</h2><div class="scroll" id="lbVisitors"></div></div> <div class="card"><h2>Most visitors sent</h2><div class="scroll" id="lbVisitors"></div></div>
<div class="card"><h2>Most traffic sources</h2><p class="muted small">Different websites your visitors came from (the referring site), so spreading your link widely counts.</p><div class="scroll" id="lbSources"></div></div> <div class="card"><h2>Most traffic sources</h2><p class="muted small">Different websites your visitors came from (the referring site), so spreading your link widely counts.</p><div class="scroll" id="lbSources"></div></div>
<div class="card" id="pastCard" hidden><h2>Past winners</h2><p class="muted small">Paid in POL from the prize wallet at the POL price at payout time. Every payment is a public Polygon transaction.</p><div class="past" id="past"></div></div>
<div id="status" class="note" hidden></div> <div id="status" class="note" hidden></div>
</main> </main>
<script src="/assets/common.js?v=1"></script> <script src="/assets/common.js?v=3"></script>
<script src="/assets/leaders.js?v=2"></script> <script src="/assets/leaders.js?v=3"></script>
</body> </body>
</html> </html>
+7 -6
View File
@@ -22,7 +22,7 @@
<meta name="theme-color" content="#ffd400"> <meta name="theme-color" content="#ffd400">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png"> <link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap">
<link rel="stylesheet" href="/assets/vbb.css?v=2"> <link rel="stylesheet" href="/assets/vbb.css?v=4">
</head> </head>
<body> <body>
<main class="wrap"> <main class="wrap">
@@ -48,7 +48,7 @@
<div class="card" id="postCard"> <div class="card" id="postCard">
<h2>Post a banner</h2> <h2>Post a banner</h2>
<p class="muted small">125x125 PNG, JPG or GIF, up to 100 KB (250x250 also works for sharp screens). Link: https, a page that loads and allows frames. One post uses one credit.</p> <p class="muted small">125x125 PNG, JPG or GIF, up to 100 KB (250x250 also works for sharp screens). Link: https, a page that loads and allows frames. One post uses one credit. Need more? <a href="/packages">Get a credit pack</a>.</p>
<div class="post-grid"> <div class="post-grid">
<div class="preview" id="preview">125 x 125<br>preview</div> <div class="preview" id="preview">125 x 125<br>preview</div>
<div> <div>
@@ -60,7 +60,7 @@
</div> </div>
</div> </div>
<div class="card"><h2>Your banners</h2><div class="mine" id="mine"></div></div> <div class="card"><h2>Your banners</h2><p class="muted small">Add the banner look to any banner that is waiting or in the loop: a bright border, plus a teaser line that shows when someone points at it. One-time, per banner.</p><div class="mine" id="mine"></div></div>
<div class="card"> <div class="card">
<h2>Your link</h2> <h2>Your link</h2>
@@ -73,8 +73,9 @@
</div> </div>
<div id="status" class="note" hidden></div> <div id="status" class="note" hidden></div>
</main> </main>
<script src="/assets/common.js?v=1"></script> <script src="/assets/common.js?v=3"></script>
<script src="/assets/wallet.js?v=1"></script> <script src="/assets/wallet.js?v=2"></script>
<script src="/assets/my.js?v=1"></script> <script src="/assets/buy.js?v=1"></script>
<script src="/assets/my.js?v=2"></script>
</body> </body>
</html> </html>
+18 -13
View File
@@ -3,12 +3,12 @@
<head> <head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"> <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Packages | Viral Banner Blitz</title> <title>Packages | Viral Banner Blitz</title>
<meta name="description" content="Viral Banner Blitz packages are coming soon: one-time purchases, never a subscription. Until then, post free once a day."> <meta name="description" content="Post credit packs and the banner look for Viral Banner Blitz: one-time purchases in POL, never a subscription. Network members also post free once a day.">
<link rel="canonical" href="https://viralbannerblitz.com/packages"> <link rel="canonical" href="https://viralbannerblitz.com/packages">
<meta property="og:type" content="website"> <meta property="og:type" content="website">
<meta property="og:site_name" content="Viral Banner Blitz"> <meta property="og:site_name" content="Viral Banner Blitz">
<meta property="og:title" content="Packages | Viral Banner Blitz"> <meta property="og:title" content="Packages | Viral Banner Blitz">
<meta property="og:description" content="Viral Banner Blitz packages are coming soon: one-time purchases, never a subscription. Until then, post free once a day."> <meta property="og:description" content="Post credit packs and the banner look for Viral Banner Blitz: one-time purchases in POL, never a subscription. Network members also post free once a day.">
<meta property="og:url" content="https://viralbannerblitz.com/packages"> <meta property="og:url" content="https://viralbannerblitz.com/packages">
<meta property="og:image" content="https://viralbannerblitz.com/art/og-share.png"> <meta property="og:image" content="https://viralbannerblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200"> <meta property="og:image:width" content="1200">
@@ -16,31 +16,36 @@
<meta property="og:image:alt" content="Viral Banner Blitz: a community banner loop that moves with every verified visitor"> <meta property="og:image:alt" content="Viral Banner Blitz: a community banner loop that moves with every verified visitor">
<meta name="twitter:card" content="summary_large_image"> <meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Packages | Viral Banner Blitz"> <meta name="twitter:title" content="Packages | Viral Banner Blitz">
<meta name="twitter:description" content="Viral Banner Blitz packages are coming soon: one-time purchases, never a subscription. Until then, post free once a day."> <meta name="twitter:description" content="Post credit packs and the banner look for Viral Banner Blitz: one-time purchases in POL, never a subscription. Network members also post free once a day.">
<meta name="twitter:image" content="https://viralbannerblitz.com/art/og-share.png"> <meta name="twitter:image" content="https://viralbannerblitz.com/art/og-share.png">
<meta name="theme-color" content="#ffd400"> <meta name="theme-color" content="#ffd400">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png"> <link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap">
<link rel="stylesheet" href="/assets/vbb.css?v=2"> <link rel="stylesheet" href="/assets/vbb.css?v=4">
</head> </head>
<body> <body>
<main class="wrap"> <main class="wrap">
<section class="hero"><h1>Packages</h1><p class="lead">Extra post credits and banner extras are on the way.</p></section> <section class="hero"><h1>Packages</h1><p class="lead">More post credits and a banner that stands out. Paid once in POL on Polygon, with SafePal or any other crypto wallet.</p></section>
<div class="soon"> <div class="card center pk-intro">
<div class="tag">Coming soon</div>
<h2>One-time purchases. Never a subscription.</h2> <h2>One-time purchases. Never a subscription.</h2>
<p class="muted">Every package will be a single purchase you make once. Nothing renews, nothing bills you again. Here is what is planned.</p> <p class="muted">Every package is a single purchase you make once. Nothing renews and nothing bills you again. The price is in dollars and paid in POL at the live price; anything you send above it comes straight back in the same transaction.</p>
<p class="small" id="pkWho"></p>
<div class="row" id="pkSign" hidden style="justify-content:center"><a class="btn sec small" href="/my">Sign in on My Banners</a><button class="btn small" id="pkSignBtn">Sign in with a wallet</button></div>
</div> </div>
<div class="pk" id="pk"> <div class="pk" id="pk">
<div class="card pk-item"><h3>Post credit packs</h3><ul class="pk-list" id="pkPacks"><li>10 post credits for $3</li><li>40 post credits for $10</li></ul><p class="muted small">Each credit posts one banner into the loop.</p><span class="tag-soon">Coming soon</span></div> <div class="card pk-item" id="pkPack0"><h3>Post credit pack</h3><p class="pk-price"><span data-pk="credits">10</span> post credits</p><p class="pk-usd"><b data-pk="usd">$3</b> <span class="muted small" data-pk="pol"></span></p><p class="muted small">Each credit posts one banner into the loop.</p><button class="btn" data-pk="buy" disabled>Buy</button></div>
<div class="card pk-item"><h3>Banner look</h3><p class="pk-price" id="pkLook">$2 per banner</p><p class="muted small">A border and a hover teaser that make your banner stand out in the loop.</p><span class="tag-soon">Coming soon</span></div> <div class="card pk-item" id="pkPack1"><h3>Post credit pack</h3><p class="pk-price"><span data-pk="credits">40</span> post credits</p><p class="pk-usd"><b data-pk="usd">$10</b> <span class="muted small" data-pk="pol"></span></p><p class="muted small">The better value: each credit posts one banner into the loop.</p><button class="btn" data-pk="buy" disabled>Buy</button></div>
<div class="card pk-item"><h3>Banner look</h3><p class="pk-price" id="pkLook">$2 per banner</p><p class="muted small">A bright border on your banner in the loop, plus a teaser line that shows when someone points at it. Buy it from My Banners, on the banner you want it on.</p><a class="btn sec" href="/my">Add it on My Banners</a></div>
<div class="card pk-item"><h3>Tokens</h3><p class="pk-price">Network visits</p><p class="muted small">Each token is a visit to your site from the network, at the InstantAdPay visit rate.</p><span class="tag-soon">Coming soon</span></div> <div class="card pk-item"><h3>Tokens</h3><p class="pk-price">Network visits</p><p class="muted small">Each token is a visit to your site from the network, at the InstantAdPay visit rate.</p><span class="tag-soon">Coming soon</span></div>
</div> </div>
<div class="card center"><p>Until packages open, every network member (InstantAdPay or LinkSpin) gets one free post credit each day they sign in.</p><a class="btn" href="/my">Use my free credit</a></div> <div class="card"><h3>Where your payment goes</h3><p class="muted small">Each purchase is split on the Polygon blockchain in the same transaction: 30% to the network member who introduced you (to Viral Banner Blitz if nobody did), 10% to the weekly leaderboard prize pot, 60% to Viral Banner Blitz. You buy advertising for your own banners, not an income opportunity.</p></div>
<div class="card center"><p>Every network member (InstantAdPay or LinkSpin) also gets one free post credit each day they sign in.</p><a class="btn sec" href="/my">Use my free credit</a></div>
<div id="status" class="note" hidden></div> <div id="status" class="note" hidden></div>
</main> </main>
<script src="/assets/common.js?v=1"></script> <script src="/assets/common.js?v=3"></script>
<script src="/assets/static.js?v=2"></script> <script src="/assets/wallet.js?v=2"></script>
<script src="/assets/buy.js?v=1"></script>
<script src="/assets/packages.js?v=1"></script>
</body> </body>
</html> </html>
+41
View File
@@ -0,0 +1,41 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Promote | Viral Banner Blitz</title>
<meta name="description" content="Promote Viral Banner Blitz: your personal links, ready-made creatives in every common size, short lines, headlines, an email and social posts.">
<link rel="canonical" href="https://viralbannerblitz.com/promote">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Viral Banner Blitz">
<meta property="og:title" content="Promote | Viral Banner Blitz">
<meta property="og:description" content="Promote Viral Banner Blitz: your personal links, ready-made creatives in every common size, short lines, headlines, an email and social posts.">
<meta property="og:url" content="https://viralbannerblitz.com/promote">
<meta property="og:image" content="https://viralbannerblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="Viral Banner Blitz: a community banner loop that moves with every verified visitor">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Promote | Viral Banner Blitz">
<meta name="twitter:description" content="Promote Viral Banner Blitz: your personal links, ready-made creatives in every common size, short lines, headlines, an email and social posts.">
<meta name="twitter:image" content="https://viralbannerblitz.com/art/og-share.png">
<meta name="theme-color" content="#ffd400">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@400;500;700&family=Space+Mono:wght@400;700&display=swap">
<link rel="stylesheet" href="/assets/vbb.css?v=4">
<link rel="stylesheet" href="/assets/kit.css?v=1">
</head>
<body>
<main class="wrap">
<section class="hero"><span class="eyebrow"><i></i>Share the loop</span><h1>Promote <em>Viral Banner Blitz</em></h1><p class="lead">Your links, creatives in every common size, and copy you can paste anywhere. Everything carries your network username.</p></section>
<div class="card" id="who"><h3>Your network username</h3>
<p class="muted small" id="whoNote">Your InstantAdPay or LinkSpin username works here. Sign in on <a href="/my">My Banners</a> and it fills in by itself.</p>
<form class="kit-who" id="whoForm"><input id="whoIn" autocomplete="off" spellcheck="false" maxlength="42" placeholder="your username"><button class="btn" type="submit">Use it</button></form></div>
<div id="status" class="note" hidden></div>
<div id="kit"><p class="muted">Loading the kit...</p></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/kitpage.js?v=1"></script>
<script src="/assets/promote.js?v=1"></script>
</body>
</html>
+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); });
+103 -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(); 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, // 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. // 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 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; 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); 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)); } 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(); 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 // 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(); 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(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(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(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); ok(!JSON.stringify(cfg).includes('capUsd') && !JSON.stringify(cfg).includes('"cap'), 'public config never shows the prize cap', cfg);
@@ -155,6 +161,34 @@ async function main() {
ok(sp.loopSize === 5 && sp.perShift === 3 && sp.progress === 0 && sp.loop.length === 0 && sp.waiting === 0, 'empty loop at start', sp); ok(sp.loopSize === 5 && sp.perShift === 3 && sp.progress === 0 && sp.loop.length === 0 && sp.waiting === 0, 'empty loop at start', sp);
for (const pth of ['/leaders', '/how', '/packages', '/robots.txt', '/sitemap.xml', '/art/mark.svg', '/assets/vbb.css', '/assets/splash.js']) { r = await anon.req(pth); ok(r.status === 200, 'GET ' + pth + ' 200', r.status); } for (const pth of ['/leaders', '/how', '/packages', '/robots.txt', '/sitemap.xml', '/art/mark.svg', '/assets/vbb.css', '/assets/splash.js']) { r = await anon.req(pth); ok(r.status === 200, 'GET ' + pth + ' 200', r.status); }
r = await anon.req('/my'); ok(r.status === 200 && r.headers.get('x-frame-options') === 'DENY', '/my served, never framed'); r = await anon.req('/my'); ok(r.status === 200 && r.headers.get('x-frame-options') === 'DENY', '/my served, never framed');
// promo kit (2026-11-14): one public feed read by /promote and by InstantAdPay's promo center
{
const kr = await anon.req('/api/promo-kit?u=smokeleader'); const k = await kr.json();
ok(kr.status === 200 && kr.headers.get('access-control-allow-origin') === '*', 'promo kit: GET /api/promo-kit 200 with CORS open', kr.status);
ok(k.username === 'smokeleader' && k.links.length === 3 && k.links.every(l => l.url.startsWith('https://viralbannerblitz.com/') && l.url.endsWith('?ref=smokeleader')), 'promo kit: every link carries ?ref=<username>', k.links);
ok(k.lines.length === 5 && k.headlines.length === 3 && k.posts.length === 2 && k.email && k.email.subject && k.email.body.includes('?ref=smokeleader'), 'promo kit: 5 lines, 3 headlines, 1 email, 2 posts, link filled in');
const words = JSON.stringify([k.lines, k.headlines, k.email, k.posts, k.note, k.tagline]);
ok(!/[—–]/.test(words) && !/\$50|passive income|guaranteed (income|returns|profit)|earn (cash|money)|make money/i.test(words) && /at least \$20/.test(words), 'promo kit copy: no dashes, no cap, no income promises, pot shown as at least $20');
ok(k.creatives.length === 21 && new Set(k.creatives.map(c => c.angle)).size === 3, 'promo kit: 21 creatives in 3 angles', k.creatives.length);
const badName = k.creatives.filter(c => /\d{2,4}x\d{2,4}|banner|[-_/]ads?[-_./]/i.test(c.url.replace('https://viralbannerblitz.com', '')));
ok(badName.length === 0, 'promo kit: creative paths are ad-blocker neutral (no size tokens, no banner/ad words)', badName.map(c => c.url));
let dimOk = true; const dimBad = [];
for (const c of k.creatives) {
const rr = await anon.req(new URL(c.url).pathname); const buf = Buffer.from(await rr.arrayBuffer());
const w = buf.readUInt32BE(16), h = buf.readUInt32BE(20);
if (rr.status !== 200 || rr.headers.get('content-type') !== 'image/png' || w !== c.w || h !== c.h) { dimOk = false; dimBad.push(c.key + ' ' + rr.status + ' ' + w + 'x' + h); }
if (!c.html.includes('href="https://viralbannerblitz.com/?ref=smokeleader"')) { dimOk = false; dimBad.push(c.key + ' html'); }
}
ok(dimOk, 'promo kit: every creative is served as PNG at its exact size, HTML links to the member', dimBad);
const k2 = await (await anon.req('/api/promo-kit?u=' + encodeURIComponent('<b>x</b>'))).json();
ok(k2.username === null && k2.links[0].url === 'https://viralbannerblitz.com/', 'promo kit: a bad username is ignored (plain links)', k2.links[0]);
r = await anon.req('/promote'); const ph = await r.text();
ok(r.status === 200 && /id="kit"/.test(ph) && /kitpage\.js/.test(ph), 'GET /promote serves the Promote page');
r = await anon.req('/no-such-page'); const nf = await r.text();
ok(r.status === 404 && /Back to the loop/.test(nf), '404 page served');
ok(/script-src[^;]*https:\/\/linkspin\.app/.test(r.headers.get('content-security-policy') || ''), 'CSP admits linkspin.app (network zones)');
r = await anon.req('/sitemap.xml'); ok((await r.text()).includes('/promote'), 'sitemap lists /promote');
}
r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in'); r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in');
console.log('4. members: wallet sign-in and network sign-in'); console.log('4. members: wallet sign-in and network sign-in');
@@ -341,16 +375,65 @@ async function main() {
// restart: the dedupe marks survive, the replaying RPC still credits nothing // restart: the dedupe marks survive, the replaying RPC still credits nothing
await sleep(1200); await stop(); await boot(); await sleep(900); 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); 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) ---- // ---- 12b. hub report: each purchase reported once, signed as vbb (first = bind with the sponsor, later = spend) ----
console.log('12b. hub report'); console.log('12b. hub report');
await sleep(1200); await sleep(1200);
const binds = HUB.got.filter(x => x.route === '/v1/contract-bind'), spends = HUB.got.filter(x => x.route === '/v1/contract-spend'); 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(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 }); 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 ---- // ---- 12c. old site links + health ----
console.log('12c. old site links + health'); console.log('12c. old site links + health');
@@ -397,14 +480,27 @@ 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'); 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); await pg.goto(BASE + '/packages', { waitUntil: 'domcontentloaded' }); await pg.waitForTimeout(400);
const pk = await pg.textContent('#pk'); 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)); await pg.waitForFunction(() => /POL right now/.test(document.getElementById('pk').textContent), null, { timeout: 6000 }).catch(() => {});
ok(!(await pg.$('#pk button, #pk form')), name + ': no purchase controls on the packages page'); 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 }); 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) // 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 }]); await ctx.addCookies([{ name: 'vbb.sid', value: L.jar['vbb.sid'], url: BASE }]);
await pg.goto(BASE + '/my', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 }); await pg.goto(BASE + '/my', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 });
ok((await pg.inputValue('#share')).endsWith('?ref=smokeleader'), name + ': My Banners shows the share link'); ok((await pg.inputValue('#share')).endsWith('?ref=smokeleader'), name + ': My Banners shows the share link');
await pg.screenshot({ path: path.join(OUT, 'my-' + name + '.png'), fullPage: true }); await pg.screenshot({ path: path.join(OUT, 'my-' + name + '.png'), fullPage: true });
// Promote page, signed in: the kit fills in the member's username
await pg.goto(BASE + '/promote', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#kit .kit-fig img', { timeout: 8000 });
ok((await pg.textContent('#kit')).includes('?ref=smokeleader') && (await pg.inputValue('#whoIn')) === 'smokeleader', name + ': Promote page shows the kit with the member links');
ok(!!(await pg.$('nav a[href="/promote"]')), name + ': nav links to Promote');
await pg.waitForTimeout(600); await pg.screenshot({ path: path.join(OUT, 'promote-' + name + '.png'), fullPage: true });
await pg.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await pg.waitForTimeout(300);
ok(!(await pg.$('script[src*="linkspin.app/z.js"]')), name + ': no network zone on the loop page');
await ctx.close(); await ctx.close();
} }
ok(errs.length === 0, 'no page errors', errs); ok(errs.length === 0, 'no page errors', errs);
+85 -15
View File
@@ -1,6 +1,7 @@
// Viral Banner Blitz web app (viralbannerblitz.com rebuild, "VBB"). Plain Node http server, no framework (the InstantAdPay and // Viral Banner Blitz web app (viralbannerblitz.com rebuild, "VBB"). Plain Node http server, no framework (the InstantAdPay and
// Downline Banners pattern). v1 is off-chain: no contract, no prices, no money. // Downline Banners pattern). Purchases are live through VBBShop (2026-11-14): POST /api/my/order builds the member's buy() call
// VBBShop hooks (shop.js): GET /api/my/voucher signs a sponsor voucher; the purchase watcher credits packs. Both inert until configured. // (with a fresh sponsor voucher when the hub knows their sponsor), the member's wallet sends it, the purchase watcher (shop.js)
// credits packs and banner looks. Weekly prize payouts: prize.js (prepared automatically, paid only on an admin's approval).
// Pages: / (splash: the loop, the next-shift bar, the queue), /my (My Banners), /leaders, /how, /packages, /admin. // Pages: / (splash: the loop, the next-shift bar, the queue), /my (My Banners), /leaders, /how, /packages, /admin.
// Engine: loop.js. Data: store.js on docstore.js (MySQL when DOCSTORE_URL is set). Checks: safety.js. Network sign-in: networksso.js. // Engine: loop.js. Data: store.js on docstore.js (MySQL when DOCSTORE_URL is set). Checks: safety.js. Network sign-in: networksso.js.
'use strict'; 'use strict';
@@ -19,7 +20,9 @@ const loop = require('./loop');
const safety = require('./safety'); const safety = require('./safety');
const networksso = require('./networksso'); const networksso = require('./networksso');
const shop = require('./shop'); const shop = require('./shop');
const promokit = require('./promokit'); // promo kit feed /api/promo-kit + the /promote page (2026-11-14)
const hubreport = require('./hubreport'); // network hub report by wallet (off unless HUB_ENABLED) const hubreport = require('./hubreport'); // network hub report by wallet (off unless HUB_ENABLED)
const prize = require('./prize');
const PUB = path.join(__dirname, 'public'); const PUB = path.join(__dirname, 'public');
const UPL = path.join(C.dataDir, 'uploads'); const UPL = path.join(C.dataDir, 'uploads');
@@ -37,8 +40,8 @@ const hash = s => crypto.createHmac('sha256', SECRET).update(s).digest('hex').sl
// ---- http helpers ---- // ---- http helpers ----
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg',
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' }; '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://linkspin.app; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
+ "img-src 'self' data: blob: https:; connect-src 'self' https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org " + "img-src 'self' data: blob: https:; connect-src 'self' https://linkspin.app https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org "
+ "https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; " + "https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; "
+ "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: 'self'"; + "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: 'self'";
function headers(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); } function headers(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); }
@@ -159,7 +162,8 @@ function grantDaily(m) {
} }
function myData(addr) { function myData(addr) {
const m = store.member(addr); const m = store.member(addr);
const banners = store.bannersOf(addr).slice().reverse().map(b => Object.assign({ id: b.id, img: b.img, link: b.link, createdAt: b.createdAt, cycledAt: b.cycledAt || null, clicks: b.clicks || 0 }, loop.placeOf(b))); const banners = store.bannersOf(addr).slice().reverse().map(b => Object.assign({ id: b.id, img: b.img, link: b.link, createdAt: b.createdAt, cycledAt: b.cycledAt || null, clicks: b.clicks || 0,
look: !!b.look, teaser: b.look ? (b.teaser || '') : '', teaserDefault: loop.hostOf(b.link) }, loop.placeOf(b)));
const rewards = store.ledger().filter(e => e.owner === m.address); const rewards = store.ledger().filter(e => e.owner === m.address);
const shareName = m.username || m.address; const shareName = m.username || m.address;
return { address: m.address, username: m.username, credits: m.credits, freeCreditCap: C.freeCreditCap, freeToday: m.freeDay === store.ctDay(), netVerified: netVerified(m), return { address: m.address, username: m.username, credits: m.credits, freeCreditCap: C.freeCreditCap, freeToday: m.freeDay === store.ctDay(), netVerified: netVerified(m),
@@ -207,6 +211,9 @@ function oldLink(u) {
return net ? '/?ref=' + encodeURIComponent(net) : '/'; return net ? '/?ref=' + encodeURIComponent(net) : '/';
} }
// network ad zone on the 404 page (LinkSpin zone on Marty's account, 300x250; the page zones live in public/assets/common.js ZONES). '' = none
const ZONE_404 = '';
const PAGES = { '/': 'index.html', '/my': 'my.html', '/leaders': 'leaders.html', '/how': 'how.html', '/packages': 'packages.html', '/admin': 'admin.html' }; const PAGES = { '/': 'index.html', '/my': 'my.html', '/leaders': 'leaders.html', '/how': 'how.html', '/packages': 'packages.html', '/admin': 'admin.html' };
const challenges = new Map(); const challenges = new Map();
const clickSeen = new Map(); const clickSeen = new Map();
@@ -217,6 +224,7 @@ const server = http.createServer(async (req, res) => {
if (C.isProd && host !== C.site && host.endsWith('.' + C.site)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } } if (C.isProd && host !== C.site && host.endsWith('.' + C.site)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } }
try { try {
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return; if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
if ((p === '/api/promo-kit' || p === '/promote') && promokit.handle(req, res, u, sendFile)) return;
if (req.method === 'GET' || req.method === 'HEAD') { if (req.method === 'GET' || req.method === 'HEAD') {
if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files' }); if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files' });
@@ -231,7 +239,7 @@ const server = http.createServer(async (req, res) => {
if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/?ref=' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); } if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/?ref=' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); }
if (p === '/sitemap.xml') { if (p === '/sitemap.xml') {
const day = new Date().toISOString().slice(0, 10); const day = new Date().toISOString().slice(0, 10);
const urls = ['/', '/leaders', '/how', '/packages'].map(x => '<url><loc>https://' + C.site + x + '</loc><lastmod>' + day + '</lastmod></url>').join(''); const urls = ['/', '/leaders', '/how', '/packages', '/promote'].map(x => '<url><loc>https://' + C.site + x + '</loc><lastmod>' + day + '</lastmod></url>').join('');
res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }));
return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>'); return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>');
} }
@@ -256,18 +264,30 @@ const server = http.createServer(async (req, res) => {
} }
} }
// this week's prize pot. v1 takes no payments, so week sales are 0 and the pot sits at the floor until the contract step. // this week's prize pot from this week's VBBShop sales (prize.js); the cap is never shown
function prizes(weekSalesUsd = 0) { function prizes() { const z = prize.pot(store.ctWeek()); return { pot: z.potUsd, atFloor: z.atFloor, visitors: z.places, sources: z.places }; }
const z = C.prizePot; const pot = Math.min(z.capUsd, Math.max(z.floorUsd, weekSalesUsd * z.pct / 100));
const board = pot / 2, r2 = x => Math.round(x * 100) / 100, per = z.places.map(x => r2(board * x / 100));
return { pot: r2(pot), atFloor: pot <= z.floorUsd, visitors: per, sources: per };
}
// -- public API // -- public API
if (p === '/api/config' && req.method === 'GET') { if (p === '/api/config' && req.method === 'GET') {
return json(res, 200, { site: C.site, siteName: C.siteName, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId, return json(res, 200, { site: C.site, siteName: C.siteName, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId,
loopSize: C.loopSize, perShift: C.perShift, viewsPerCycle: C.viewsPerCycle, visitSeconds: C.visitSeconds, freeCreditCap: C.freeCreditCap, maxQueued: C.maxQueuedPerMember, loopSize: C.loopSize, perShift: C.perShift, viewsPerCycle: C.viewsPerCycle, visitSeconds: C.visitSeconds, freeCreditCap: C.freeCreditCap, maxQueued: C.maxQueuedPerMember,
freeCreditsPerDay: C.freeCreditsPerDay, packs: C.packs, lookUsd: C.lookUsd, prizes: prizes(), sso: networksso.enabled() }); freeCreditsPerDay: C.freeCreditsPerDay, packs: C.packs, lookUsd: C.lookUsd, lookSku: C.lookSku, prizes: prizes(), sso: networksso.enabled(),
shop: { live: shop.watching(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer });
} }
// buying: the live price, gas fees for the wallet, and the confirmation wait (the Downline Banners endpoints)
if (p === '/api/quote' && req.method === 'GET') {
if (!shop.watching()) return json(res, 503, { error: 'Purchases are not open.' });
if (limited(req, 'quote', 600, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const sku = Number(u.searchParams.get('sku')), qty = Number(u.searchParams.get('qty') || 1);
if (!validSku(sku) || !Number.isInteger(qty) || qty < 1 || qty > (sku === C.lookSku ? 1 : 10)) return json(res, 400, { error: 'Unknown package.' });
try { return json(res, 200, Object.assign({ usd: skuUsd(sku) * qty }, await shop.quote(sku, qty))); } catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/gas' && req.method === 'GET') { try { return json(res, 200, shop.watching() ? await shop.fees() : {}); } catch (e) { return json(res, 200, {}); } }
if (/^\/api\/tx\/0x[0-9a-fA-F]{64}$/.test(p) && req.method === 'GET') {
if (!shop.watching() || limited(req, 'tx', 1200, 3600000)) return json(res, 200, { found: false });
try { return json(res, 200, await shop.receipt(p.slice(8))); } catch (e) { return json(res, 200, { found: false }); }
}
// past weeks' prize winners with their transactions (paid weeks only)
if (p === '/api/prizes' && req.method === 'GET') return json(res, 200, { current: prizes(), week: store.ctWeek(), past: prize.history(12), explorer: C.explorer }, { 'Cache-Control': 'public, max-age=30' });
if (p === '/api/splash' && req.method === 'GET') return json(res, 200, loop.view(24), { 'Cache-Control': 'no-store' }); if (p === '/api/splash' && req.method === 'GET') return json(res, 200, loop.view(24), { 'Cache-Control': 'no-store' });
if (p === '/api/leaders' && req.method === 'GET') { if (p === '/api/leaders' && req.method === 'GET') {
const out = loop.leaders(null, 10); const out = loop.leaders(null, 10);
@@ -350,6 +370,40 @@ const server = http.createServer(async (req, res) => {
if (!sp || sp === me) return json(res, 200, { voucher: null, why: 'no-sponsor' }); if (!sp || sp === me) return json(res, 200, { voucher: null, why: 'no-sponsor' });
return json(res, 200, { voucher: await shop.voucher(me, sp) }); return json(res, 200, { voucher: await shop.voucher(me, sp) });
} }
// a purchase: the buy() call for the member's own wallet. Packs: SKUs from config. Banner look: one of their own banners that
// is waiting or in the loop and has no look yet (ref = the banner id). A fresh sponsor voucher when the hub knows the sponsor.
if (p === '/api/my/order' && req.method === 'POST') {
if (!shop.watching()) return json(res, 503, { error: 'Purchases are not open yet.' });
if (limited(req, 'order', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const b = await readBody(req); const sku = Number(b.sku); const qty = Number(b.qty || 1); let ref = 0;
if (!validSku(sku)) return json(res, 400, { error: 'Unknown package.' });
if (sku === C.lookSku) {
const bn = store.banner(b.ref);
if (!bn || bn.owner !== me) return json(res, 400, { error: 'That banner is not yours.' });
if (bn.look) return json(res, 400, { error: 'That banner already has the look.' });
if (bn.state === 'cycled') return json(res, 400, { error: 'That banner has already cycled. Add the look to a banner that is waiting or in the loop.' });
if (qty !== 1) return json(res, 400, { error: 'One look per banner.' });
ref = bn.id;
} else if (!Number.isInteger(qty) || qty < 1 || qty > 10) return json(res, 400, { error: 'Pick 1 to 10 packs.' });
let v = null, why = null;
if (shop.voucherOn()) {
const h = await hubSponsorWallet(me).catch(() => ({ ok: false }));
if (!h.ok) why = 'hub-unavailable'; else if (!h.sponsor || h.sponsor === me) why = 'no-sponsor'; else v = await shop.voucher(me, h.sponsor);
} else why = 'off';
try { return json(res, 200, Object.assign({ buyer: me, usd: skuUsd(sku) * qty, sku, qty, ref, why }, await shop.order(me, sku, qty, ref, v))); }
catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
// the member's transaction confirmed: scan the chain now (credits still wait for the confirmations)
if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); }
// the hover teaser of a banner with the look: up to 40 characters of plain text ('' = the link's site)
const tm = /^\/api\/my\/banners\/(\d{1,9})\/teaser$/.exec(p);
if (tm && req.method === 'POST') {
const bn = store.banner(tm[1]); if (!bn || bn.owner !== me) return json(res, 404, { error: 'Not found' });
if (!bn.look) return json(res, 400, { error: 'Add the banner look first.' });
const t = String((await readBody(req)).teaser || '').replace(/[\u0000-\u001f\u007f<>]/g, '').replace(/\s+/g, ' ').trim();
if (t.length > 40) return json(res, 400, { error: 'Keep the teaser to 40 characters.' });
bn.teaser = t; store.saveBanner(bn); return json(res, 200, { ok: true, teaser: t || loop.hostOf(bn.link) });
}
if (p === '/api/my/upload' && req.method === 'POST') { if (p === '/api/my/upload' && req.method === 'POST') {
if (limited(req, 'upload', 40, 3600000)) return json(res, 429, { error: 'Too many uploads this hour.' }); if (limited(req, 'upload', 40, 3600000)) return json(res, 429, { error: 'Too many uploads this hour.' });
let buf; try { buf = await readRaw(req, safety.MAX_UPLOAD + 1); } catch (e) { return json(res, 400, { error: 'The file is over 100 KB.' }); } let buf; try { buf = await readRaw(req, safety.MAX_UPLOAD + 1); } catch (e) { return json(res, 400, { error: 'The file is over 100 KB.' }); }
@@ -391,7 +445,7 @@ const server = http.createServer(async (req, res) => {
queue: { length: S.queue.length, next: S.queue.slice(0, 20) }, progress: S.progress, held: S.progress >= C.perShift && !S.queue.length, queue: { length: S.queue.length, next: S.queue.slice(0, 20) }, progress: S.progress, held: S.progress >= C.perShift && !S.queue.length,
today: { visits: t.visits || 0, shifts: t.shifts || 0, cycles: t.cycles || 0, posts: t.posts || 0, clicks: t.clicks || 0 }, today: { visits: t.visits || 0, shifts: t.shifts || 0, cycles: t.cycles || 0, posts: t.posts || 0, clicks: t.clicks || 0 },
totals: S.totals, ledger: { entries: L.length, views: L.reduce((x, e) => x + e.views, 0), viewsByStatus: byStatus, credited: 0 }, totals: S.totals, ledger: { entries: L.length, views: L.reduce((x, e) => x + e.views, 0), viewsByStatus: byStatus, credited: 0 },
members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, shop: shop.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length }); members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, shop: shop.view(), prize: prize.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length });
} }
// old username -> network username map for the old-link redirects: { oldrefs: { old: network } } replaces the whole map // old username -> network username map for the old-link redirects: { oldrefs: { old: network } } replaces the whole map
if (p === '/api/admin/oldrefs' && req.method === 'POST') { if (p === '/api/admin/oldrefs' && req.method === 'POST') {
@@ -401,6 +455,18 @@ const server = http.createServer(async (req, res) => {
fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} }; fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} };
return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length }); return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length });
} }
// weekly prize payouts: plans (newest first) with a live quote for the ones waiting, prepare, approve and pay
if (p === '/api/admin/prizes' && req.method === 'GET') {
const list = prize.plans().slice(0, 20); const out = [];
for (const pl of list) out.push(Object.assign({}, pl, pl.status === 'prepared' ? { quote: await prize.quotePlan(pl) } : {}));
return json(res, 200, { week: store.ctWeek(), lastWeek: prize.prevWeek(store.ctWeek()), current: prize.pot(store.ctWeek()), weeks: out, prize: prize.view(), explorer: C.explorer });
}
if (p === '/api/admin/prizes/prepare' && req.method === 'POST') { const b = await readBody(req); const r = prize.prepare(String(b.week || prize.prevWeek(store.ctWeek())), true); return json(res, r.error ? 400 : 200, r); }
if (p === '/api/admin/prizes/pay' && req.method === 'POST') {
const b = await readBody(req); const wk = String(b.week || '');
if (!wk || b.confirm !== wk) return json(res, 400, { error: 'Send {week, confirm: week} to approve.' });
const r = await prize.pay(wk); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/ledger' && req.method === 'GET') { if (p === '/api/admin/ledger' && req.method === 'GET') {
const n = Math.min(2000, Math.max(1, Number(u.searchParams.get('n')) || 200)); const L = store.ledger(); const n = Math.min(2000, Math.max(1, Number(u.searchParams.get('n')) || 200)); const L = store.ledger();
const per = {}; for (const e of L) { const k = e.owner; const r = per[k] || (per[k] = { address: k, username: e.username, cycles: 0, views: 0 }); r.cycles++; r.views += e.views; if (e.username) r.username = e.username; } const per = {}; for (const e of L) { const k = e.owner; const r = per[k] || (per[k] = { address: k, username: e.username, cycles: 0, views: 0 }); r.cycles++; r.views += e.views; if (e.username) r.username = e.username; }
@@ -411,12 +477,15 @@ const server = http.createServer(async (req, res) => {
if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' }); if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });
res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' })); res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' }));
return res.end('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not found</title><body style="background:#fff4dc;color:#14121f;font-family:sans-serif;text-align:center;padding:40px 16px"><p>Not found. <a style="color:#ff2d87;font-weight:700" href="/">Back to the loop</a></p></body>'); return res.end('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not found</title><body style="background:#fff4dc;color:#14121f;font-family:sans-serif;text-align:center;padding:40px 16px"><p>Not found. <a style="color:#ff2d87;font-weight:700" href="/">Back to the loop</a></p>'
+ (ZONE_404 ? '<p style="color:#4d4862;font-size:11px;margin:24px 0 4px">Network</p><script async src="https://linkspin.app/z.js" data-zone="' + ZONE_404 + '"></script>' : '') + '</body>');
} catch (e) { } catch (e) {
console.error('request', p, e.message); console.error('request', p, e.message);
if (!res.headersSent) json(res, 500, { error: 'Server error' }); if (!res.headersSent) json(res, 500, { error: 'Server error' });
} }
}); });
const validSku = sku => sku === C.lookSku || C.packs.some(x => x.sku === sku);
const skuUsd = sku => sku === C.lookSku ? C.lookUsd : (C.packs.find(x => x.sku === sku) || {}).usd || 0;
function saveUpload(owner, buf, ext) { function saveUpload(owner, buf, ext) {
const name = owner.slice(2, 10) + '-' + crypto.randomBytes(6).toString('hex') + ext; const name = owner.slice(2, 10) + '-' + crypto.randomBytes(6).toString('hex') + ext;
fs.writeFileSync(path.join(UPL, name), buf); // uploads stay files on the volume (docstore keeps the uploads folder on disk) fs.writeFileSync(path.join(UPL, name), buf); // uploads stay files on the volume (docstore keeps the uploads folder on disk)
@@ -431,6 +500,7 @@ function saveUpload(owner, buf, ext) {
store.pruneVisits(); loop.rebuildIndex(); store.pruneVisits(); loop.rebuildIndex();
hubreport.init({ dataDir: C.dataDir, purchases: () => Object.entries((store.state() || {}).purchases || {}).map(([key, x]) => Object.assign({ key }, x)) }); hubreport.init({ dataDir: C.dataDir, purchases: () => Object.entries((store.state() || {}).purchases || {}).map(([key, x]) => Object.assign({ key }, x)) });
shop.init(C); // inert without CONTRACT_ADDRESS + CHAIN_RPC (watcher) / KEEPER_KEY (vouchers) shop.init(C); // inert without CONTRACT_ADDRESS + CHAIN_RPC (watcher) / KEEPER_KEY (vouchers)
prize.init(C); // prepares last week's payout plan; pays only on an admin's approval (PRIZE_KEY)
setInterval(() => { if (store.pruneVisits()) loop.rebuildIndex(); }, 3600000).unref(); setInterval(() => { if (store.pruneVisits()) loop.rebuildIndex(); }, 3600000).unref();
server.listen(C.port, () => console.log('Viral Banner Blitz on :' + C.port + ' loop ' + C.loopSize + ', ' + C.perShift + ' visitors per shift, store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)'))); server.listen(C.port, () => console.log('Viral Banner Blitz on :' + C.port + ' loop ' + C.loopSize + ', ' + C.perShift + ' visitors per shift, store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)')));
})().catch(e => { console.error('start failed:', e.message); process.exit(1); }); })().catch(e => { console.error('start failed:', e.message); process.exit(1); });
+65 -4
View File
@@ -3,7 +3,9 @@
// signed-in member whose network sponsor the hub knows. The contract binds that sponsor on the member's first purchase. // signed-in member whose network sponsor the hub knows. The contract binds that sponsor on the member's first purchase.
// (b) chain watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase logs (confirmed blocks only) and credits the buyer // (b) chain watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase logs (confirmed blocks only) and credits the buyer
// once per txHash:logIndex. The dedupe mark and the credits live in the same document (vbb.json), so they save together. // once per txHash:logIndex. The dedupe mark and the credits live in the same document (vbb.json), so they save together.
// The key never enters config or any API answer. Packages stay "coming soon" in the UI until Marty says go. // (c) buying (live 2026-11-14): quote() reads quoteWei, order() builds the member's buy() call (fresh voucher inside, else none),
// receipt() / fees() back the page's confirmation wait, nudge() polls right after a member's transaction confirms.
// The key never enters config or any API answer.
'use strict'; 'use strict';
const { Wallet, Interface, getAddress } = require('ethers'); const { Wallet, Interface, getAddress } = require('ethers');
const store = require('./store'); const store = require('./store');
@@ -11,6 +13,10 @@ const store = require('./store');
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
const IFACE = new Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 credits, uint256 usdCents, uint256 weiPaid, address sponsor, uint256 sponsorPaid)']); const IFACE = new Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 credits, uint256 usdCents, uint256 weiPaid, address sponsor, uint256 sponsorPaid)']);
const TOPIC = IFACE.getEvent('Purchase').topicHash; const TOPIC = IFACE.getEvent('Purchase').topicHash;
const CALLS = new Interface(['function quoteWei(uint256 sku, uint256 qty) view returns (uint256)',
'function buy(uint256 sku, uint256 qty, uint256 ref, address sponsor, uint256 deadline, bytes sig) payable returns (uint256 orderId)',
'function prizeWallet() view returns (address)', 'function priceFeed() view returns (address)',
'function latestRoundData() view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)']);
const TYPES = { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'sponsor', type: 'address' }, { name: 'deadline', type: 'uint256' }] }; const TYPES = { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'sponsor', type: 'address' }, { name: 'deadline', type: 'uint256' }] };
const st = { polls: 0, credited: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null }; const st = { polls: 0, credited: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null };
let C = null, keeper = null, busy = false, timer = null; let C = null, keeper = null, busy = false, timer = null;
@@ -44,7 +50,7 @@ function apply(ev) {
let applied = 'credits'; let applied = 'credits';
if (ev.credits > 0) m.credits += ev.credits; if (ev.credits > 0) m.credits += ev.credits;
else { const b = Number.isSafeInteger(Number(ev.ref)) ? store.banner(Number(ev.ref)) : null; if (b && b.owner === a) { b.look = true; store.saveBanner(b); applied = 'look'; } else applied = 'unmatched'; } else { const b = Number.isSafeInteger(Number(ev.ref)) ? store.banner(Number(ev.ref)) : null; if (b && b.owner === a) { b.look = true; store.saveBanner(b); applied = 'look'; } else applied = 'unmatched'; }
P[key] = { at: Date.now(), block: ev.block, orderId: ev.orderId, buyer: a, sku: ev.sku, qty: ev.qty, ref: ev.ref, credits: ev.credits, usdCents: ev.usdCents, P[key] = { at: Date.now(), blockAt: ev.blockAt || null, block: ev.block, orderId: ev.orderId, buyer: a, sku: ev.sku, qty: ev.qty, ref: ev.ref, credits: ev.credits, usdCents: ev.usdCents,
weiPaid: ev.weiPaid, sponsor: ev.sponsor, sponsorPaid: ev.sponsorPaid, applied }; weiPaid: ev.weiPaid, sponsor: ev.sponsor, sponsorPaid: ev.sponsorPaid, applied };
store.save(); st.credited++; store.save(); st.credited++;
console.log('shop: order', ev.orderId, 'sku', ev.sku, 'x' + ev.qty, a, applied === 'credits' ? '+' + ev.credits + ' credits' : applied); console.log('shop: order', ev.orderId, 'sku', ev.sku, 'x' + ev.qty, a, applied === 'credits' ? '+' + ev.credits + ' credits' : applied);
@@ -72,17 +78,72 @@ async function poll() {
while (sh.lastBlock < head) { while (sh.lastBlock < head) {
const from = sh.lastBlock + 1, to = Math.min(head, from + 999); const from = sh.lastBlock + 1, to = Math.min(head, from + 999);
const logs = await rpc('eth_getLogs', [{ address: C.contractAddress, topics: [TOPIC], fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }]); const logs = await rpc('eth_getLogs', [{ address: C.contractAddress, topics: [TOPIC], fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }]);
for (const l of logs || []) { const ev = decode(l); if (ev) apply(ev); else st.ignored++; } for (const l of logs || []) { const ev = decode(l); if (!ev) { st.ignored++; continue; } ev.blockAt = await blockTime(ev.block); apply(ev); }
sh.lastBlock = to; store.save(); sh.lastBlock = to; store.save();
} }
} catch (e) { st.errors++; st.lastError = String(e.message).slice(0, 200); } } catch (e) { st.errors++; st.lastError = String(e.message).slice(0, 200); }
finally { busy = false; } finally { busy = false; }
} }
// the block's timestamp (seconds), for the Central-time week a sale belongs to. null if the RPC does not answer (the credit time is used).
const btCache = new Map();
async function blockTime(n) {
if (btCache.has(n)) return btCache.get(n);
let t = null; try { const b = await rpc('eth_getBlockByNumber', ['0x' + n.toString(16), false]); t = b && b.timestamp ? parseInt(b.timestamp, 16) : null; } catch (e) {}
if (t) { btCache.set(n, t); if (btCache.size > 5000) btCache.clear(); }
return t;
}
function tick() { poll().finally(() => { if (watching()) { timer = setTimeout(tick, C.shopPollMs); timer.unref(); } }); } function tick() { poll().finally(() => { if (watching()) { timer = setTimeout(tick, C.shopPollMs); timer.unref(); } }); }
// ---- buying ----
async function call(fn, args, to) {
const r = await rpc('eth_call', [{ to: to || C.contractAddress, data: CALLS.encodeFunctionData(fn, args || []) }, 'latest']);
return CALLS.decodeFunctionResult(fn, r);
}
const qCache = new Map();
// POL wei for qty of sku now; sendWei adds 1% for price drift (the contract refunds anything above the price in the same tx)
async function quote(sku, qty) {
const k = sku + 'x' + qty; const hit = qCache.get(k); if (hit && Date.now() - hit.at < 15000) return hit.v;
const wei = (await call('quoteWei', [sku, qty]))[0];
const v = { sku, qty, wei: wei.toString(), sendWei: (wei + wei / 100n).toString() };
qCache.set(k, { at: Date.now(), v }); if (qCache.size > 200) qCache.clear();
return v;
}
// the buy() call for this member: to, data, value. voucher = shop.voucher() result or null (no sponsor bound by this purchase)
async function order(buyer, sku, qty, ref, v) {
const q = await quote(sku, qty);
const data = CALLS.encodeFunctionData('buy', [sku, qty, BigInt(ref || 0), v ? v.sponsor : '0x0000000000000000000000000000000000000000', v ? v.deadline : 0, v ? v.sig : '0x']);
return { to: C.contractAddress, chainId: C.chainId, data, value: '0x' + BigInt(q.sendWei).toString(16), wei: q.wei, sendWei: q.sendWei, sponsor: !!v };
}
async function receipt(hash) {
const r = await rpc('eth_getTransactionReceipt', [hash]);
if (!r) return { found: false };
return { found: true, status: r.status, blockNumber: r.blockNumber, to: r.to ? String(r.to).toLowerCase() : null, from: r.from ? String(r.from).toLowerCase() : null };
}
// Polygon's ~25 gwei priority-fee floor: wallets' own estimates miss it (the Downline Banners fix)
async function fees() {
let tip = 0n, base = 0n;
try { tip = BigInt(await rpc('eth_maxPriorityFeePerGas', [])); } catch (e) {}
try { const blk = await rpc('eth_getBlockByNumber', ['latest', false]); base = BigInt((blk && blk.baseFeePerGas) || '0x0'); } catch (e) {}
const MIN_TIP = C.chainId === 137 ? 30000000000n : 1000000000n;
const priority = tip > MIN_TIP ? tip : MIN_TIP;
return { maxPriorityFeePerGas: '0x' + priority.toString(16), maxFeePerGas: '0x' + (base * 2n + priority).toString(16) };
}
// a member's transaction just confirmed: scan now instead of waiting for the next poll (confirmations still apply)
let lastNudge = 0;
function nudge() { if (!watching() || Date.now() - lastNudge < 3000) return; lastNudge = Date.now(); poll().catch(() => {}); }
// sales of one Central-time week (key = that Monday): from the credited Purchase events, by block time
function weekSales(week, ctWeek) {
const P = ((store.state() || {}).purchases) || {}; let cents = 0, n = 0, prizeWei = 0n;
for (const x of Object.values(P)) {
if (ctWeek(x.blockAt ? x.blockAt * 1000 : x.at) !== week) continue;
n++; cents += Number(x.usdCents) || 0; try { prizeWei += BigInt(x.weiPaid || 0) * 1000n / 10000n; } catch (e) {}
}
return { purchases: n, cents, prizeWei: prizeWei.toString() };
}
function view() { function view() {
const P = (store.state() && store.state().purchases) || {}; const list = Object.values(P); const P = (store.state() && store.state().purchases) || {}; const list = Object.values(P);
return Object.assign({ contract: C ? C.contractAddress || null : null, watching: watching(), vouchers: voucherOn(), keeper: keeper ? keeper.address : null, return Object.assign({ contract: C ? C.contractAddress || null : null, watching: watching(), vouchers: voucherOn(), keeper: keeper ? keeper.address : null,
lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, purchases: list.length, creditsSold: list.reduce((t, x) => t + (x.credits || 0), 0), unmatched: list.filter(x => x.applied === 'unmatched').length }, st); lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, purchases: list.length, creditsSold: list.reduce((t, x) => t + (x.credits || 0), 0), unmatched: list.filter(x => x.applied === 'unmatched').length }, st);
} }
module.exports = { init, voucher, voucherOn, watching, apply, poll, view, TOPIC, IFACE, TYPES }; module.exports = { init, voucher, voucherOn, watching, apply, poll, view, quote, order, receipt, fees, nudge, call, rpc, weekSales, TOPIC, IFACE, TYPES, CALLS };
+196
View File
@@ -0,0 +1,196 @@
// Promo kit art for Downline Banners and Viral Banner Blitz (2026-11-14). Renders every creative from HTML with Playwright so
// the text is crisp, at the exact pixel size of each slot. Same file in both repos (banner-line/app/tools, vbb/app/tools).
// node tools/kit-art.mjs dlb|vbb|all
// Output: <app>/public/art/kit/<site>-<angle>-<shape>.png. Neutral names on purpose: no IAB size tokens, no "banner"/"ad"
// (EasyList hides those). The copy here must match the facts in each app (DLB SPEC.md + contract, VBB config.js + how.html).
import { pathToFileURL } from 'url';
import fs from 'fs';
import path from 'path';
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright/index.js';
const pwm = await import(pathToFileURL(PW).href); const chromium = pwm.chromium || (pwm.default && pwm.default.chromium);
const ROOT = 'D:/Projects/HighRisk';
const SHAPES = { tile: [125, 125], strip: [468, 60], leader: [728, 90], box: [300, 250], tower: [160, 600], social: [1200, 630], square: [1080, 1080] };
const SITES = {
dlb: {
out: ROOT + '/banner-line/app/public/art/kit', domain: 'downlinebanners.com', name: ['Downline', 'Banners'],
mark: fs.readFileSync(ROOT + '/banner-line/app/public/art/mark.svg', 'utf8'),
fonts: 'family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=Inter:wght@500;600;700',
angles: {
spot: { eyebrow: '$5 spot', h1: 'A $5 spot.', h2: '300 guaranteed views.', line: 'A $5 spot. 300 guaranteed views.', sub: 'Your banner on the board, paid on-chain on Polygon.', cta: 'Get a spot', tA: '$5 spot', tB: '300 views', chips: ['$5 spot', '300 guaranteed views', 'Paid on-chain'] },
line: { eyebrow: '10 levels', h1: '10 levels pay', h2: 'as spots sell after yours.', line: '10 levels pay as spots sell after yours', sub: 'Sponsor 30%. Each of 10 levels 5.5%. Fixed in the contract.', cta: 'See the line', tA: '10 levels', tB: 'paid on-chain', chips: ['Sponsor 30%', '10 levels x 5.5%', 'Splits fixed on-chain'] },
instant: { eyebrow: 'Nothing to withdraw', h1: 'No withdrawals.', h2: 'Paid in the same transaction.', line: 'No withdrawals. Paid in the same transaction.', sub: 'A Polygon contract splits every $5 spot the moment it sells.', cta: 'See how', tA: 'No withdrawals', tB: 'paid same tx', chips: ['Same-transaction payouts', 'Verified contract', '$5 spot'] }
}
},
vbb: {
out: ROOT + '/vbb/app/public/art/kit', domain: 'viralbannerblitz.com', name: ['Viral Banner', 'Blitz'],
mark: fs.readFileSync(ROOT + '/vbb/app/public/art/mark.svg', 'utf8'),
fonts: 'family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=DM+Sans:wght@500;700&family=Space+Mono:wght@700',
angles: {
free: { eyebrow: 'Free daily post', h1: 'Post a banner', h2: 'free every day.', line: 'Post a banner free every day', sub: 'InstantAdPay and LinkSpin members get a free post credit each day they sign in.', cta: 'Post yours', tA: 'FREE', tB: 'daily post', chips: ['125x125 banners', 'Free daily post', 'No subscription'] },
loop: { eyebrow: 'Real visitors only', h1: 'Every visitor', h2: 'pushes the loop.', line: 'Every visitor pushes the loop', sub: 'Real visitors move every banner forward. Ride out and earn network ad views.', cta: 'Join the loop', tA: 'Every visit', tB: 'moves it', chips: ['Verified visitors', 'Bots do not count', 'Network ad views'] },
prize: { eyebrow: 'Weekly leaderboards', h1: 'Send visitors.', h2: 'Climb the weekly board.', line: 'Weekly prizes, at least $20 a week', sub: 'Prize pot of at least $20 a week, paid in POL to the top three on each board.', cta: 'See the leaders', tA: 'Weekly', tB: 'prizes', chips: ['At least $20 a week', 'Paid in POL', 'Two leaderboards'] }
}
}
};
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
// shrink every .fit element until its text fits its box (one line or the box height)
const FIT = `<script>window.__fit=()=>{document.querySelectorAll('.fit').forEach(el=>{let s=parseFloat(getComputedStyle(el).fontSize);let n=0;while((el.scrollWidth>el.clientWidth+1||el.scrollHeight>el.clientHeight+s*0.2)&&s>6&&n++<200){s-=0.5;el.style.fontSize=s+'px';}});};</script>`;
function dlbCss() {
return `
:root{--bg:#0b0913;--ink:#f3f1fa;--muted:#a29cbc;--lime:#c6f432;--mint:#7ef0c8;--cyan:#6fd8ff;--vio:#9b7bff}
*{box-sizing:border-box;margin:0;padding:0}
html,body{width:var(--w);height:var(--h);overflow:hidden}
body{font-family:Inter,system-ui,sans-serif;color:var(--ink);background:
radial-gradient(55% 70% at 18% 20%,rgba(155,123,255,.32),transparent 70%),radial-gradient(45% 60% at 85% 85%,rgba(198,244,50,.16),transparent 70%),
linear-gradient(160deg,#1c1733 0%,#0b0913 70%);position:relative}
body::after{content:"";position:absolute;inset:0;border:1px solid rgba(155,123,255,.45);pointer-events:none}
.g{background:linear-gradient(92deg,var(--lime) 5%,var(--mint) 55%,var(--cyan));-webkit-background-clip:text;background-clip:text;color:transparent}
.disp{font-family:"Bricolage Grotesque",system-ui,sans-serif;font-weight:800;letter-spacing:-.03em;line-height:1.02}
.mark svg{width:100%;height:100%;display:block}
.wm{font-family:"Bricolage Grotesque";font-weight:800;letter-spacing:-.03em;white-space:nowrap}
.eb{display:inline-block;font-weight:700;text-transform:uppercase;letter-spacing:.12em;color:var(--lime);border:1.5px solid var(--lime);border-radius:999px;white-space:nowrap}
.cta{display:inline-flex;align-items:center;justify-content:center;font-family:"Bricolage Grotesque";font-weight:800;color:#0b0913;background:linear-gradient(92deg,var(--lime),var(--mint));border-radius:999px;white-space:nowrap}
.chip{display:inline-block;color:var(--muted);border:1.5px solid rgba(162,156,188,.35);border-radius:999px;font-weight:600;white-space:nowrap}
.chip:first-child{color:var(--lime);border-color:var(--lime)}
.sub{color:#cfc9e6}
.fit{white-space:nowrap;overflow:hidden;flex:none}
.h .g,.h .hot{width:fit-content;max-width:100%}`;
}
function vbbCss() {
return `
:root{--bg:#fff4dc;--ink:#14121f;--hot:#ff2d87;--sky:#2b59ff;--amber:#ffd400;--mint:#14d9a0;--muted:#4d4862}
*{box-sizing:border-box;margin:0;padding:0}
html,body{width:var(--w);height:var(--h);overflow:hidden}
body{font-family:"DM Sans",system-ui,sans-serif;color:var(--ink);background:var(--bg);position:relative;
background-image:radial-gradient(rgba(255,45,135,.18) 1.4px,transparent 1.6px),radial-gradient(rgba(43,89,255,.13) 1.4px,transparent 1.6px);
background-size:22px 22px,22px 22px;background-position:0 0,11px 11px}
body::after{content:"";position:absolute;inset:0;border:var(--edge,3px) solid var(--ink);pointer-events:none}
.disp{font-family:"Bricolage Grotesque",system-ui,sans-serif;font-weight:800;letter-spacing:-.03em;line-height:1}
.hot{color:var(--hot);-webkit-text-stroke:var(--stroke,1px) var(--ink);text-shadow:var(--ts,3px) var(--ts,3px) 0 var(--amber)}
.mark svg{width:100%;height:100%;display:block}
.wm{font-family:"Bricolage Grotesque";font-weight:800;letter-spacing:-.03em;white-space:nowrap}
.wm b{color:var(--hot);-webkit-text-stroke:.6px var(--ink)}
.eb{display:inline-block;font-family:"Space Mono",monospace;font-weight:700;text-transform:uppercase;letter-spacing:.1em;background:var(--mint);border:2.5px solid var(--ink);border-radius:999px;box-shadow:3px 3px 0 var(--ink);transform:rotate(-1.5deg);white-space:nowrap}
.cta{display:inline-flex;align-items:center;justify-content:center;font-family:"Bricolage Grotesque";font-weight:800;color:#fff;background:var(--hot);border:2.5px solid var(--ink);border-radius:12px;box-shadow:4px 4px 0 var(--ink);white-space:nowrap}
.chip{display:inline-block;font-weight:700;border:2.5px solid var(--ink);border-radius:999px;background:#fff;box-shadow:3px 3px 0 var(--ink);white-space:nowrap}
.chip:nth-child(1){background:var(--amber)} .chip:nth-child(2){background:#dbe4ff} .chip:nth-child(3){background:#c9f7e6}
.sub{color:var(--muted)}
.fit{white-space:nowrap;overflow:hidden}
.tiles{position:absolute;display:grid;grid-template-columns:repeat(3,1fr);gap:var(--tg,14px)}
.tiles i{display:block;aspect-ratio:1;border:3px solid var(--ink);border-radius:12px;box-shadow:5px 5px 0 var(--ink)}`;
}
const VBB_TILE_COLORS = ['#ff2d87', '#2b59ff', '#ffd400', '#14d9a0', '#ffffff', '#ff2d87', '#14d9a0', '#2b59ff', '#ffffff', '#ffd400', '#2b59ff', '#ff2d87'];
const vTiles = (n, rot) => '<div class="tiles">' + Array.from({ length: n }, (_, i) => '<i style="background:' + VBB_TILE_COLORS[i % 12] + ';transform:rotate(' + (((i * 37) % 7) - 3) * (rot || 1) + 'deg)"></i>').join('') + '</div>';
function body(site, a, shape) {
const S = SITES[site]; const m = '<div class="mark">' + S.mark + '</div>'; const d = site === 'dlb';
const wm = d ? '<span class="wm">Downline <span class="g">Banners</span></span>' : '<span class="wm">Viral Banner <b>Blitz</b></span>';
const h2 = d ? '<span class="g">' + esc(a.h2) + '</span>' : '<span class="hot">' + esc(a.h2) + '</span>';
const chips = a.chips.map(c => '<span class="chip">' + esc(c) + '</span>').join('');
switch (shape) {
case 'tile': return `<style>
.t{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:8px;gap:3px}
.t .mark{width:30px;height:30px;margin-bottom:3px}
.t .a{font-size:27px;width:109px;line-height:1.05} .t .b{font-size:15px;width:109px;font-weight:800;font-family:"Bricolage Grotesque"}
.t .c{font-size:9.5px;font-weight:700;width:109px;opacity:.85;margin-top:2px}
${d ? '' : 'body{--edge:3px} .t .a{color:var(--ink)} .t .b{display:inline-block;width:auto;background:var(--hot);color:#fff;border:2px solid var(--ink);border-radius:8px;padding:1px 7px;box-shadow:2px 2px 0 var(--ink);transform:rotate(-2deg)}'}
</style><div class="t">${m}<div class="a disp fit">${esc(a.tA)}</div><div class="b fit ${d ? 'g' : ''}">${esc(a.tB)}</div><div class="c fit">${esc(S.domain)}</div></div>`;
case 'strip': return `<style>
.s{position:absolute;inset:0;display:flex;align-items:center;gap:10px;padding:0 10px}
.s .mark{width:40px;height:40px;flex:none}
.s .mid{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}
.s .h{font-size:19px;width:100%} .s .w{font-size:11px;font-weight:600;opacity:.8;width:100%}
.s .cta{font-size:13px;padding:8px 12px;flex:none} ${d ? '' : 'body{--edge:2.5px} .s .cta{box-shadow:2px 2px 0 var(--ink);border-width:2px;border-radius:9px}'}
</style><div class="s">${m}<div class="mid"><div class="h disp fit">${esc(a.line)}</div><div class="w fit">${esc(S.name.join(' '))} &middot; ${esc(S.domain)}</div></div><span class="cta">${esc(a.cta)}</span></div>`;
case 'leader': return `<style>
.l{position:absolute;inset:0;display:flex;align-items:center;gap:16px;padding:0 18px}
.l .mark{width:58px;height:58px;flex:none}
.l .mid{flex:1;min-width:0;display:flex;flex-direction:column;gap:4px}
.l .h{font-size:28px;width:100%} .l .w{font-size:13.5px;width:100%}
.l .cta{font-size:17px;padding:12px 20px;flex:none} ${d ? '' : 'body{--edge:3px;--stroke:.6px;--ts:2px}'}
</style><div class="l">${m}<div class="mid"><div class="h disp fit">${esc(a.h1)} ${h2}</div><div class="w sub fit">${esc(a.sub)}</div></div><span class="cta">${esc(a.cta)}</span></div>`;
case 'box': return `<style>
.b{position:absolute;inset:0;display:flex;flex-direction:column;padding:16px 18px;gap:9px}
.b .top{display:flex;align-items:center;gap:8px} .b .mark{width:34px;height:34px;flex:none} .b .wm{font-size:17px}
.b .eb{font-size:10px;padding:4px 9px;align-self:flex-start}
.b .h{font-size:28px;width:100%;white-space:normal;max-height:62px} .b .h span{display:block;white-space:nowrap}
.b .sub{font-size:12.5px;line-height:1.35}
.b .cta{font-size:15px;padding:10px 16px;margin-top:auto;align-self:flex-start} ${d ? '' : 'body{--edge:3px;--stroke:.5px;--ts:1.5px}'}
</style><div class="b"><div class="top">${m}${wm}</div><span class="eb">${esc(a.eyebrow)}</span><div class="h disp fit"><span>${esc(a.h1)}</span>${h2.replace('<span class="', '<span class="') }</div><div class="sub">${esc(a.sub)}</div><span class="cta">${esc(a.cta)} &rarr;</span></div>`;
case 'tower': return `<style>
.v{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;text-align:center;padding:22px 12px 20px;gap:12px}
.v .mark{width:64px;height:64px} .v .wm{font-size:17px;white-space:normal;line-height:1.05}
.v .eb{font-size:9px;padding:4px 8px}
.v .h{font-size:30px;line-height:1.05;white-space:normal;width:140px;overflow-wrap:normal} .v .h span{display:block}
.v .sub{font-size:13px;line-height:1.4}
.v .cta{font-size:15px;padding:11px 14px;margin-top:auto} .v .dom{font-size:10.5px;font-weight:700;opacity:.8}
${d ? '' : 'body{--edge:3px;--stroke:.6px;--ts:2px} .v .wm b{display:block}'}
</style><div class="v">${m}${d ? '<span class="wm">Downline<br><span class="g">Banners</span></span>' : '<span class="wm">Viral Banner <b>Blitz</b></span>'}<span class="eb">${esc(a.eyebrow)}</span><div class="h disp fit"><span>${esc(a.h1)}</span>${h2}</div><div class="sub">${esc(a.sub)}</div><span class="cta">${esc(a.cta)}</span><div class="dom">${esc(S.domain)}</div></div>`;
case 'social': return d ? `<style>
.o{position:absolute;inset:0;padding:64px 80px;display:flex;flex-direction:column}
.o .top{display:flex;align-items:center;gap:26px} .o .mark{width:118px;height:118px} .o .wm{font-size:60px}
.o .eb{font-size:17px;padding:8px 16px;align-self:flex-start;margin:44px 0 18px}
.o .h{font-size:78px;width:1040px} .o .h span{display:block;white-space:nowrap}
.o .sub{font-size:27px;margin-top:20px;max-width:980px}
.o .chips{margin-top:auto;display:flex;gap:14px} .o .chip{font-size:22px;padding:10px 20px}
</style><div class="o"><div class="top">${m}${wm}</div><span class="eb">${esc(a.eyebrow)}</span><div class="h disp fit"><span>${esc(a.h1)}</span>${h2}</div><div class="sub">${esc(a.sub)}</div><div class="chips">${chips}<span class="chip">${esc(S.domain)}</span></div></div>`
: `<style>
body{--edge:0px}
.o{position:absolute;inset:0;padding:64px 0 56px 72px;display:flex;flex-direction:column;width:690px}
.o .eb{font-size:17px;padding:9px 18px;align-self:flex-start}
.o .h{font-size:76px;margin-top:30px;width:620px;white-space:normal;--stroke:2px;--ts:5px} .o .h span{display:block;white-space:nowrap}
.o .sub{font-size:26px;margin-top:24px;line-height:1.35;color:var(--ink)}
.o .bot{margin-top:auto;display:flex;align-items:center;gap:16px} .o .mark{width:62px;height:62px} .o .dom{font:800 32px "Bricolage Grotesque"}
.tiles{right:-30px;top:84px;width:430px;--tg:16px} .tiles i{border-radius:14px}
</style>${vTiles(12)}<div class="o"><span class="eb">${esc(a.eyebrow)}</span><div class="h disp fit"><span>${esc(a.h1)}</span>${h2}</div><div class="sub">${esc(a.sub)}</div><div class="bot">${m}<span class="dom">${esc(S.domain)}</span></div></div>`;
case 'square': return d ? `<style>
.q{position:absolute;inset:0;padding:84px 86px;display:flex;flex-direction:column}
.q .top{display:flex;align-items:center;gap:26px} .q .mark{width:120px;height:120px} .q .wm{font-size:60px}
.q .eb{font-size:22px;padding:10px 20px;align-self:flex-start;margin:96px 0 26px}
.q .h{font-size:104px;width:908px;white-space:normal} .q .h span{display:block}
.q .sub{font-size:34px;line-height:1.35;margin-top:34px}
.q .chips{margin-top:auto;display:flex;flex-wrap:wrap;gap:14px} .q .chip{font-size:26px;padding:12px 22px}
.q .dom{font:800 40px "Bricolage Grotesque";margin-top:26px}
</style><div class="q"><div class="top">${m}${wm}</div><span class="eb">${esc(a.eyebrow)}</span><div class="h disp"><span>${esc(a.h1)}</span>${h2}</div><div class="sub">${esc(a.sub)}</div><div class="chips">${chips}</div><div class="dom g">${esc(S.domain)}</div></div>`
: `<style>
body{--edge:0px}
.q{position:absolute;inset:0;padding:80px 84px;display:flex;flex-direction:column}
.q .top{display:flex;align-items:center;gap:20px} .q .mark{width:96px;height:96px} .q .wm{font-size:50px}
.q .eb{font-size:22px;padding:11px 22px;align-self:flex-start;margin-top:64px}
.q .h{font-size:104px;margin-top:36px;white-space:normal;--stroke:2.5px;--ts:6px} .q .h span{display:block}
.q .sub{font-size:33px;margin-top:30px;line-height:1.35;color:var(--ink);max-width:880px}
.q .chips{margin-top:auto;display:flex;flex-wrap:wrap;gap:16px} .q .chip{font-size:26px;padding:12px 22px}
.tiles{right:-50px;top:-40px;width:330px;--tg:14px;grid-template-columns:repeat(3,1fr)}
</style>${vTiles(6)}<div class="q"><div class="top">${m}${wm}</div><span class="eb">${esc(a.eyebrow)}</span><div class="h disp"><span>${esc(a.h1)}</span>${h2}</div><div class="sub">${esc(a.sub)}</div><div class="chips">${chips}<span class="chip" style="background:var(--hot);color:#fff">${esc(S.domain)}</span></div></div>`;
}
}
function page(site, angle, shape) {
const S = SITES[site]; const [w, h] = SHAPES[shape];
return `<!doctype html><html><head><meta charset="utf-8"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?${S.fonts}&display=block">
<style>:root{--w:${w}px;--h:${h}px}${site === 'dlb' ? dlbCss() : vbbCss()}</style>${FIT}</head><body>${body(site, S.angles[angle], shape)}</body></html>`;
}
const which = process.argv[2] || 'all';
const browser = await chromium.launch();
const made = []; let file0;
for (const site of Object.keys(SITES)) {
if (which !== 'all' && which !== site) continue;
const S = SITES[site]; fs.mkdirSync(S.out, { recursive: true });
for (const angle of Object.keys(S.angles)) for (const shape of Object.keys(SHAPES)) {
const [w, h] = SHAPES[shape];
const pg = await browser.newPage({ viewport: { width: w, height: h }, deviceScaleFactor: 1 });
await pg.setContent(page(site, angle, shape), { waitUntil: 'networkidle' });
if (process.env.DBG) console.log(file0 = shape, await pg.evaluate(async () => { await document.fonts.ready; return [...document.querySelectorAll('.fit')].map(el => [el.className, el.scrollWidth, el.clientWidth, el.scrollHeight, el.clientHeight]); }));
await pg.evaluate(async () => { await document.fonts.ready; window.__fit(); });
const file = path.join(S.out, site + '-' + angle + '-' + shape + '.png');
await pg.screenshot({ path: file, clip: { x: 0, y: 0, width: w, height: h } });
await pg.close(); made.push(file);
}
}
await browser.close();
console.log(made.length + ' files\n' + made.join('\n'));