From aee1ccc36a64b4154edf9baad4f5845ace6a5b96 Mon Sep 17 00:00:00 2001 From: martbost Date: Sat, 14 Nov 2026 09:47:58 -0600 Subject: [PATCH] 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/; /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 --- .env.example | 2 + config.js | 16 ++-- docker-compose.yml | 1 + loop.js | 25 +++-- package.json | 3 +- prize.js | 187 ++++++++++++++++++++++++++++++++++++++ public/admin.html | 9 +- public/assets/admin.js | 38 ++++++++ public/assets/buy.js | 49 ++++++++++ public/assets/common.js | 3 +- public/assets/leaders.js | 14 ++- public/assets/my.js | 31 ++++++- public/assets/packages.js | 49 ++++++++++ public/assets/splash.js | 2 +- public/assets/static.js | 2 +- public/assets/vbb.css | 14 +++ public/assets/wallet.js | 38 +++++++- public/how.html | 10 +- public/index.html | 6 +- public/leaders.html | 7 +- public/my.html | 13 +-- public/packages.html | 31 ++++--- public/promote.html | 4 +- qa/chain.mjs | 161 ++++++++++++++++++++++++++++++++ qa/smoke.mjs | 75 +++++++++++++-- server.js | 86 +++++++++++++++--- shop.js | 69 +++++++++++++- 27 files changed, 866 insertions(+), 79 deletions(-) create mode 100644 prize.js create mode 100644 public/assets/buy.js create mode 100644 public/assets/packages.js create mode 100644 qa/chain.mjs diff --git a/.env.example b/.env.example index 8970e0a..a59719a 100644 --- a/.env.example +++ b/.env.example @@ -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_POLL_MS=30000 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 # 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 diff --git a/config.js b/config.js index 3a1665f..89ee015 100644 --- a/config.js +++ b/config.js @@ -1,6 +1,7 @@ // 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 -// contract hooks (shop.js: sponsor vouchers + purchase watcher) stay inert until CONTRACT_ADDRESS / CHAIN_RPC / KEEPER_KEY are set. +// Purchases are live through VBBShop (2026-11-14): the packages page and My Banners sell packs and banner looks from the member's +// 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'); 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 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 - // ---- Marty's approved numbers (2026-11-13). v1 takes no payments: packages show as "coming soon" with these planned prices, - // prizes are displayed only (no payout code yet), the split is kept here for the contract step. - 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), + // ---- Marty's approved numbers (2026-11-13), sold on chain through VBBShop since 2026-11-14 (the contract's SKUs hold the real + // 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, 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 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. // 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), - 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. 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 diff --git a/docker-compose.yml b/docker-compose.yml index 09a28b4..f4713ec 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,6 +16,7 @@ services: CHAIN_RPC: ${CHAIN_RPC:-} SHOP_START_BLOCK: ${SHOP_START_BLOCK:-} 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} RPC_URLS: ${RPC_URLS:-} HUB_URL: ${HUB_URL:-} diff --git a/loop.js b/loop.js index 80646de..adbebb4 100644 --- a/loop.js +++ b/loop.js @@ -87,21 +87,25 @@ function verifiedVisit(o) { } // ---- 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; function leaders(week, n) { 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(); for (const v of store.visits()) { 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); - p.visitors++; if (v.src) p.sources.add(v.src); + 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.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, - visitors: rows.slice().sort((a, b) => b.visitors - a.visitors || b.sources - a.sources).slice(0, n), - sources: rows.filter(r => r.sources > 0).sort((a, b) => b.sources - a.sources || b.visitors - a.visitors).slice(0, n) }; - lbCache = { wk, at: Date.now(), n: store.visits().length, out }; + 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 || a.sourcesAt - b.sourcesAt).slice(0, n) }; + lbCache = { wk, n0: n, at: Date.now(), n: store.visits().length, out }; return out; } function memberWeek(addr) { @@ -111,7 +115,10 @@ function memberWeek(addr) { } // ---- 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) { const S = store.state(); 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 }; } -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 }; diff --git a/package.json b/package.json index 2b6f59e..fc62421 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,8 @@ "scripts": { "start": "node server.js", "dev": "node --watch server.js", - "qa": "node qa/smoke.mjs" + "qa": "node qa/smoke.mjs", + "qa:chain": "node qa/chain.mjs" }, "engines": { "node": ">=20" diff --git a/prize.js b/prize.js new file mode 100644 index 0000000..9889fd1 --- /dev/null +++ b/prize.js @@ -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 }; diff --git a/public/admin.html b/public/admin.html index fd19903..52dfdfe 100644 --- a/public/admin.html +++ b/public/admin.html @@ -22,20 +22,21 @@ - +
-

Admin

Loop status and the cycle reward ledger. Rewards are recorded only; nothing is credited yet.

+

Admin

Loop status, weekly prize payouts and the cycle reward ledger. Cycle rewards are recorded only; nothing is credited yet.

- - + + diff --git a/public/assets/admin.js b/public/assets/admin.js index 593ebbc..96145fc 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -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]] .map(x => '
' + esc(x[1]) + '' + esc(x[0]) + '
').join(''); $('aRaw').textContent = JSON.stringify(s, null, 2); + prizes(); setInterval(prizes, 30000); const l = await get('/api/admin/ledger?n=300'); const who = r => r.username ? '@' + r.username : VBB.short(r.address || r.owner); $('aMembers').innerHTML = l.members && l.members.length ? '' + l.members.map(m => '').join('') + '
MemberCyclesViews
' + esc(who(m)) + '' + m.cycles + '' + VBB.n(m.views) + '
' : '

No cycles yet.

'; $('aLedger').innerHTML = l.entries && l.entries.length ? '' + l.entries.map(e => '').join('') + '
When (CT)EntryBannerMemberViewsStatus
' + esc(new Date(e.at).toLocaleString('en-US', { timeZone: 'America/Chicago' })) + '' + esc(e.id) + '#' + e.bannerId + '' + esc(who(e)) + '' + VBB.n(e.views) + '' + esc(e.status) + '
' : '

The ledger is empty.

'; } + // ---- 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 = '

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') + '.

'; + const tx = h => z.explorer ? '' + esc(h.slice(0, 10)) + '...' : esc(h); + $('pzWeeks').innerHTML = (z.weeks || []).map(w => { + const q = w.quote || {}; + const lines = w.transfers.map((t, i) => '' + esc(t.board) + '' + t.place + '' + esc(t.name) + '
' + esc(t.address) + '' + VBB.n(t.count) + '$' + VBB.n(t.usd) + '' + + esc(t.pol || (q.lines && q.lines[i] ? q.lines[i].pol : '')) + '' + esc(t.status || '') + (t.tx ? ' ' + tx(t.tx) : '') + (t.error ? '
' + esc(t.error) + '' : '') + '').join(''); + let foot = ''; + if (w.status === 'prepared') { + foot = q.error ? '

' + esc(q.error) + '

' + : '

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 ? ' Short by ' + esc(q.shortPol) + ' POL.' : '') + (q.keyMatches ? '' : ' PRIZE_KEY is missing or is not the prize wallet.') + '

' + + ''; + } + return '

Week of ' + esc(w.week) + ': ' + esc(pst[w.status] || w.status) + '

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' : '') + '

' + + (w.transfers.length ? '
' + lines + '
Board#WinnerCountUSDPOLStatus
' : '

Nobody on the leaderboards that week.

') + foot + '
'; + }).join('') || '

No weeks prepared yet.

'; + 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(); }; $('tok').addEventListener('keydown', e => { if (e.key === 'Enter') $('tokBtn').click(); }); if (tok) open(); diff --git a/public/assets/buy.js b/public/assets/buy.js new file mode 100644 index 0000000..90d6256 --- /dev/null +++ b/public/assets/buy.js @@ -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 }; +})(); diff --git a/public/assets/common.js b/public/assets/common.js index 1a33dc7..2fdf4f9 100644 --- a/public/assets/common.js +++ b/public/assets/common.js @@ -72,10 +72,11 @@ window.VBB = (function () { tick(); setInterval(tick, 25000); } 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.innerHTML = '' + esc(t.owner ? 'Banner by ' + t.owner : 'Member banner #' + t.id) + '' + (extra && extra.pos ? '' + esc(extra.pos) + '' : '') + (t.owner ? '' + esc(t.owner) + '' : ''); + 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'; }; return a; } diff --git a/public/assets/leaders.js b/public/assets/leaders.js index 869957c..f3d6a86 100644 --- a/public/assets/leaders.js +++ b/public/assets/leaders.js @@ -2,7 +2,7 @@ (async function () { VBB.renderNav('/leaders'); VBB.renderFooter(); 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 pz = c.prizes || {}; const place = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th']; const plist = (title, arr) => '

' + title + '

    ' + arr.map((v, i) => '
  • ' + place[i] + ': $' + VBB.n(v) + ' in POL
  • ').join('') + '
'; @@ -20,4 +20,16 @@ : '

Nobody yet this week. Share your link from My Banners and take the top spot.

'; $('lbVisitors').innerHTML = table(d.visitors, 'visitors'); $('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 => '' + esc(bn[x.board] || x.board) + '' + x.place + '' + esc(x.name) + '$' + VBB.n(x.usd) + '' + esc(x.pol) + ' POL' + + (pr.explorer ? '' + (x.confirmed ? 'Paid' : 'Sent') + '' : esc(x.tx.slice(0, 10))) + '').join(''); + return '

Week of ' + esc(day) + '

Prize pot $' + VBB.n(w.potUsd) + (w.priceUsd ? ', POL at $' + Number(w.priceUsd).toFixed(4) : '') + '

' + rows + '
Board#MemberUSDPOLTransaction
'; + }).join(''); + $('pastCard').hidden = false; + } })(); diff --git a/public/assets/my.js b/public/assets/my.js index 558bf9d..abb9e9a 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -45,7 +45,33 @@ const where = b => b.state === 'queued' ? 'Waiting
Number ' + b.position + ' of ' + b.of + ' in line' : b.state === 'loop' ? 'In the loop
Place ' + b.place + ' of ' + b.of + ', rides out in about ' + b.shiftsToRideOut + ' shift' + (b.shiftsToRideOut === 1 ? '' : 's') : 'Cycled
' + (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 = 'Banner look'; + 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 = ''; + 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() { + if (buying || editing) return; const d = await VBB.getJSON('/api/my'); if (d.error) return VBB.status(d.error, 'err'); $('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. ' : '') + '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; - 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 ? '' : '

No banners yet. Post your first one above.

'; for (const b of d.banners) { const el = document.createElement('div'); el.className = 'item'; - el.innerHTML = 'Banner #' + b.id + '
' + where(b) + '

' + VBB.n(b.clicks) + ' clicks
'; + el.innerHTML = 'Banner #' + b.id + '
' + where(b) + '

' + VBB.n(b.clicks) + ' clicks
'; 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); } $('share').value = d.share; diff --git a/public/assets/packages.js b/public/assets/packages.js new file mode 100644 index 0000000..41ec9f9 --- /dev/null +++ b/public/assets/packages.js @@ -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; }); } + }; + }); +})(); diff --git a/public/assets/splash.js b/public/assets/splash.js index 7f34fd6..898556d 100644 --- a/public/assets/splash.js +++ b/public/assets/splash.js @@ -15,7 +15,7 @@ const t = d.today || {}; $('today').textContent = VBB.n(t.shifts) + ' shifts and ' + VBB.n(t.cycles) + ' cycles today'; // 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) { lastLoop = ids; const g = $('loop'); g.innerHTML = ''; const full = d.loop.length >= d.loopSize; diff --git a/public/assets/static.js b/public/assets/static.js index a2d32f4..e989f89 100644 --- a/public/assets/static.js +++ b/public/assets/static.js @@ -7,7 +7,7 @@ if (c.perShift) set('perShift', c.perShift); if (c.viewsPerCycle != null) set('views', VBB.n(c.viewsPerCycle)); 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 pp = document.getElementById('pkPacks'); if (pp && c.packs && c.packs.length) pp.innerHTML = c.packs.map(p => '
  • ' + VBB.n(p.credits) + ' post credits for ' + money(p.usd) + '
  • ').join(''); diff --git a/public/assets/vbb.css b/public/assets/vbb.css index 760da56..019c97e 100644 --- a/public/assets/vbb.css +++ b/public/assets/vbb.css @@ -158,3 +158,17 @@ footer.foot a{color:var(--amber)} footer.foot p{margin:6px 0} /* 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} diff --git a/public/assets/wallet.js b/public/assets/wallet.js index 7bb8fbe..57420c9 100644 --- a/public/assets/wallet.js +++ b/public/assets/wallet.js @@ -1,5 +1,6 @@ // 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 () { 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'); }; @@ -186,6 +187,39 @@ window.VBBWallet = (function () { 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() { // AppKit's disconnect can hang on the WalletConnect relay (esp. mobile) — // 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 ''; } } - return { connect, signIn, disconnect, address: currentAddress, activeAddress, pickAccount, walletName }; + return { connect, signIn, sendTx, waitTx, balance, disconnect, address: currentAddress, activeAddress, pickAccount, walletName }; })(); diff --git a/public/how.html b/public/how.html index c452678..fe40d84 100644 --- a/public/how.html +++ b/public/how.html @@ -22,7 +22,7 @@ - +
    @@ -45,11 +45,17 @@

    Weekly leaderboards

    Share your link (it ends in ?ref= and your network username). The leaderboards count the verified visitors you send each week and how many different websites they came from.

    +

    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.

    +
    +

    Packages

    +

    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.

    + +
    - + diff --git a/public/index.html b/public/index.html index 2caebc6..47659e1 100644 --- a/public/index.html +++ b/public/index.html @@ -23,7 +23,7 @@ - +
    @@ -55,7 +55,7 @@
    - - + + diff --git a/public/leaders.html b/public/leaders.html index c84a110..72304f4 100644 --- a/public/leaders.html +++ b/public/leaders.html @@ -22,7 +22,7 @@ - +
    @@ -30,9 +30,10 @@

    Most visitors sent

    Most traffic sources

    Different websites your visitors came from (the referring site), so spreading your link widely counts.

    +
    - - + + diff --git a/public/my.html b/public/my.html index 80ad67a..c5a0340 100644 --- a/public/my.html +++ b/public/my.html @@ -22,7 +22,7 @@ - +
    @@ -48,7 +48,7 @@

    Post a banner

    -

    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.

    +

    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? Get a credit pack.

    125 x 125
    preview
    @@ -60,7 +60,7 @@
    -

    Your banners

    +

    Your banners

    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.

    Your link

    @@ -73,8 +73,9 @@
    - - - + + + + diff --git a/public/packages.html b/public/packages.html index dd4476f..95d949d 100644 --- a/public/packages.html +++ b/public/packages.html @@ -3,12 +3,12 @@ Packages | Viral Banner Blitz - + - + @@ -16,31 +16,36 @@ - + - +
    -

    Packages

    Extra post credits and banner extras are on the way.

    -
    -
    Coming soon
    +

    Packages

    More post credits and a banner that stands out. Paid once in POL on Polygon, with SafePal or any other crypto wallet.

    +

    One-time purchases. Never a subscription.

    -

    Every package will be a single purchase you make once. Nothing renews, nothing bills you again. Here is what is planned.

    +

    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.

    +

    +
    -

    Post credit packs

    • 10 post credits for $3
    • 40 post credits for $10

    Each credit posts one banner into the loop.

    Coming soon
    -

    Banner look

    $2 per banner

    A border and a hover teaser that make your banner stand out in the loop.

    Coming soon
    +

    Post credit pack

    10 post credits

    $3

    Each credit posts one banner into the loop.

    +

    Post credit pack

    40 post credits

    $10

    The better value: each credit posts one banner into the loop.

    +

    Banner look

    $2 per banner

    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.

    Add it on My Banners

    Tokens

    Network visits

    Each token is a visit to your site from the network, at the InstantAdPay visit rate.

    Coming soon
    -

    Until packages open, every network member (InstantAdPay or LinkSpin) gets one free post credit each day they sign in.

    Use my free credit
    +

    Where your payment goes

    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.

    +

    Every network member (InstantAdPay or LinkSpin) also gets one free post credit each day they sign in.

    Use my free credit
    - - + + + + diff --git a/public/promote.html b/public/promote.html index aaaee08..d626c63 100644 --- a/public/promote.html +++ b/public/promote.html @@ -22,7 +22,7 @@ - + @@ -34,7 +34,7 @@

    Loading the kit...

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