aee1ccc36a
Buying (VBBShop 0x36F6...07D7): Packages page has live Buy buttons for the 10 and 40 credit packs (USD price + live POL from quoteWei, SafePal or any other crypto wallet, one-time, never a subscription, where the payment goes); My Banners has "Add the banner look ($2)" on each waiting or in-loop banner (SKU 3, ref = banner id) and a 40-character teaser editor once it has the look. POST /api/my/order builds the member's buy() call on the server (fresh keeper voucher when the hub knows their sponsor, else no sponsor); the page checks the connected wallet is the member's VBB account (explains how to switch if not), checks the balance, sends with Polygon's fee floor (/api/gas), waits on /api/tx, nudges the watcher (/api/my/paid) and polls until the credits or the look arrive. Public: /api/quote, /api/gas, /api/tx/<hash>; /api/config has shop {live, contract} + explorer. The banner look on the loop: double border + star, hover teaser (always shown on touch screens; default = the link's site). Only Tokens still says coming soon. wallet.js gains sendTx/waitTx/balance (DLB flow).
Weekly prize payouts (prize.js): each Central-time week's pot = 10% of its VBBShop sales (usdCents of Purchase events by block time), $20 floor (company top-up shown to admin), $50 cap internal, half per board, 50/30/20. Every Monday the app prepares last week's plan (winners, wallets, USD; POL quoted live from the Chainlink feed the contract uses). /admin "Approve and pay" (two clicks): refuses unless PRIZE_KEY is the contract's prizeWallet(), the feed is fresh and the wallet holds the POL + gas (says how much more to send); then once per week (docstore.claim in MySQL + plan status), consecutive nonces, each hash saved as sent, stops at the first unclear send (never auto-retried), receipts watched. Ties: earlier to reach the count wins (leaderboards use the same rule). A winner that cannot be paid (the prize or company wallet) is skipped and the rest move up; an unfilled place stays in the prize wallet. /leaders shows past winners with transaction links. Posts nothing anywhere. Compose passes PRIZE_KEY.
Tests: smoke 192/192 (stand-in chain answers quoteWei + receipts: quote, order calldata + voucher, look purchase, teaser, prizes API, UI Buy buttons). New qa/chain.mjs on a local anvil with the real VBBShop + mock feed: buy -> Purchase -> credits, voucher binds sponsor, 30/10/60 split, overpay refunded, banner look; prize prepare -> short refusal -> pay 6 transfers exact POL -> paid once: 29/29. common.js?v=3, vbb.css?v=4.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
188 lines
13 KiB
JavaScript
188 lines
13 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;
|
|
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 };
|