Files
vbb/prize.js
martbost 2fe3d9e4c0 Trust pack (Marty 2026-11-14): contract proof, live ledger, proof toasts, Telegram sale cards, legal pages, network footer.
- proof.js: /api/ledger (each VBBShop purchase with its split read from the receipt's Paid/PaymentFailed events, else the contract's fixed 30/10/60 math; weekly prize transfers with their transactions), /api/contract (owner, prize wallet, company, keeper, paused, orders, balance and owed, read live and cached 5 min; Sourcify exact match, Polygonscan pending).
- Telegram (CTB Rewards bot, payments topic, TG_TOKEN/TG_CHAT/TG_PAY_TOPIC same as Downline Banners): one photo card per purchase (prebuilt VBB proof image rotated, buyer, sponsor/prize/company split in POL, this week's purchases + prize pot, Polygonscan + ledger links) and one line per confirmed prize payout. Hooks: shop.setHook (newly credited purchases only) and prize.setHook (confirmed transfers); once per tx via an in-process guard plus docstore.claim; nothing older than 2 hours.
- Pages /contract, /ledger, /terms, /disclaimer (Earnings Disclaimer), /privacy (TrustClickz, real mechanics: advertising not income, same-transaction split, prize wallet holds the 10% until Monday, no refunds on-chain, one-time purchases, crypto risk, data incl. hashed visit checks and the network hub); sitemap.
- Footer: Terms, Earnings Disclaimer, Privacy, Contract, Ledger, Support, company line, 'Part of the network' from the hub (netsites.js, /api/network-sites, fallback list), VBB marked current. Toasts add purchases and prize payouts.
- tools/proof-art.mjs renders public/art/proof/vbb-proof-{pink,blue,yellow}.png. common.js?v=5, vbb.css?v=6.
chain.mjs 49/49 (real contract on anvil + stand-in Telegram: exact split, 2 cards, no repost on rescans, 6 prize lines). smoke 241/241.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 10:38:40 -06:00

190 lines
14 KiB
JavaScript

// 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;
let onConfirmed = null; // proof.js: one Telegram line per confirmed prize transfer (2026-11-14); this module still posts nothing itself
function setHook(fn) { onConfirmed = typeof fn === 'function' ? fn : 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(); if (t.status === 'confirmed' && onConfirmed) { try { onConfirmed(plan, t); } catch (e) {} } } } 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 = { setHook, init, pot, prepare, pay, quotePlan, history, plans, view, prevWeek, auto };