diff --git a/netsites.js b/netsites.js new file mode 100644 index 0000000..2536f92 --- /dev/null +++ b/netsites.js @@ -0,0 +1,40 @@ +// The network sites list for the footer's "Part of the network" line (Marty 2026-11-14 trust pack). +// One source: the hub's public GET /v1/network-sites (HUB_URL). Cached 10 minutes, refreshed in the background, never waits on a +// slow hub (2.5 s timeout), and falls back to the same built-in list. Never RM Circle, never the games. +// The same file lives in every network site (InstantAdPay, LinkSpin, Downline Banners, VBB, Stack POL). +const FALLBACK = [ + { id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' }, + { id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' }, + { id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' }, + { id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' }, + { id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' }, + { id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' } +]; +const TTL = 10 * 60 * 1000; +let cache = { at: 0, list: FALLBACK, from: 'fallback' }; +let inflight = null; + +const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, ''); +function clean(list) { + if (!Array.isArray(list)) return null; + const ok = list.filter(s => s && typeof s.name === 'string' && /^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(s.url || ''))) + .slice(0, 30).map(s => ({ id: String(s.id || s.name).toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 30), name: String(s.name).slice(0, 60), url: String(s.url).replace(/\/+$/, '') })); + return ok.length ? ok : null; +} +function refresh() { + if (inflight || process.env.NETWORK_SITES_HUB === '0') return inflight; + const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500); + inflight = fetch(hubUrl() + '/v1/network-sites', { signal: ac.signal }) + .then(r => (r.ok ? r.json() : null)) + .then(j => { const l = clean(j); if (l) cache = { at: Date.now(), list: l, from: 'hub' }; else cache.at = Date.now(); }) + .catch(() => { cache.at = Date.now() - TTL + 60 * 1000; }) // hub down: try again in a minute, keep the last good list + .finally(() => { clearTimeout(t); inflight = null; }); + return inflight; +} +function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list; } +// GET /api/network-sites: public, cacheable, the same answer on every page +function handle(req, res) { + res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' }); + res.end(JSON.stringify(list())); +} +module.exports = { list, handle, refresh, FALLBACK, _state: () => cache }; diff --git a/prize.js b/prize.js index 9889fd1..fff09d6 100644 --- a/prize.js +++ b/prize.js @@ -28,6 +28,8 @@ 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'); @@ -166,7 +168,7 @@ function watchReceipts(week) { 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) {} + 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(); } @@ -184,4 +186,4 @@ function history(n) { 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 }; +module.exports = { setHook, init, pot, prepare, pay, quotePlan, history, plans, view, prevWeek, auto }; diff --git a/proof.js b/proof.js new file mode 100644 index 0000000..f3ce3f4 --- /dev/null +++ b/proof.js @@ -0,0 +1,184 @@ +// Trust pack (Marty 2026-11-14: "all these sites need to show their live ledger and the contract for proof and trust, and toast +// notifications ... post a Telegram with some kind of image and stats, and payment notifications"). The Downline Banners pattern. +// - ledger(): every VBBShop purchase (from the Purchase events shop.js credited) with its split, and every weekly prize transfer, +// newest first, each with its transaction. Public, read by /ledger and the toasts. +// - contract(): the live contract facts for /contract (owner, prize wallet, company, keeper, paused, what it holds), read from the +// chain and cached 5 minutes; the split constants are the contract's own (30 / 10 / 60). +// - Telegram: one photo card per purchase (a prebuilt VBB proof image, rotated, + who bought what, the split paid in that same +// transaction, this week's numbers and the verify link) and one line per confirmed prize payout, in the group's payments topic +// (TG_CHAT / TG_PAY_TOPIC, the CTB Rewards bot TG_TOKEN, same as Downline Banners and the games). Sent once per transaction +// across app copies (docstore.claim). Never posts anything older than 2 hours (a re-index after downtime must not flood the +// topic). Off unless TG_TOKEN and TG_CHAT are set. TG_API (tests only) points at a stand-in. +'use strict'; +const store = require('./store'); +const docstore = require('./docstore'); + +const SPLIT = { sponsorBps: 3000, prizeBps: 1000, denom: 10000 }; // VBBShop SPONSOR_BPS / PRIZE_BPS (constants in the contract) +const ZERO = '0x0000000000000000000000000000000000000000'; +const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; +// Paid(uint256 indexed id, address indexed to, uint256 amount, uint8 role) / PaymentFailed(same): read from the purchase receipt +const { Interface } = require('ethers'); +const EV = new Interface(['event Paid(uint256 indexed id, address indexed to, uint256 amount, uint8 role)', 'event PaymentFailed(uint256 indexed id, address indexed to, uint256 amount, uint8 role)']); +const T_PAID = EV.getEvent('Paid').topicHash, T_FAIL = EV.getEvent('PaymentFailed').topicHash; +const ROLE = ['sponsor', 'prize', 'company']; +const CARDS = ['/art/proof/vbb-proof-pink.png', '/art/proof/vbb-proof-blue.png', '/art/proof/vbb-proof-yellow.png']; // rotated per post +const st = { posted: 0, prizeLines: 0, skipped: 0, failed: 0, lastError: null }; +let C = null, shop = null, prize = null, names = null; +const sent = new Set(); // this copy's own guard (docstore.claim covers app copies; without MySQL it always says yes) +const once = k => { if (sent.has(k)) return false; sent.add(k); if (sent.size > 5000) sent.clear(); return true; }; + +function init(cfg, deps) { C = cfg; shop = deps.shop; prize = deps.prize; names = deps.nameOf || null; } +const on = () => !!(process.env.TG_TOKEN && process.env.TG_CHAT); +const lc = a => String(a || '').toLowerCase(); +const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : ''; +function nameLocal(addr) { const m = store.member(lc(addr)); return m && m.username ? m.username : null; } +async function nameOf(addr) { + const a = lc(addr); const local = nameLocal(a); if (local) return local; + if (names) { try { const n = await names(a); if (n) return n; } catch (e) {} } + return null; +} +const who = (addr, name) => name ? '@' + name : short(lc(addr)); +const pol = wei => { const v = Number(BigInt(wei || 0) / 10n ** 12n) / 1e6; return v >= 100 ? v.toFixed(2) : v.toFixed(4); }; +const usd = cents => '$' + (Number(cents || 0) / 100).toFixed(2); +const esc = s => String(s == null ? '' : s).replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c])); + +// what a purchase bought, in words (SKUs from config: packs and the banner look) +function what(x) { + if (x.credits > 0) return x.credits + ' post credits'; + if (Number(x.sku) === Number(C.lookSku)) return 'the banner look'; + return 'package #' + x.sku; +} +// the split of one purchase. From the receipt's Paid / PaymentFailed events when read, else from the contract's fixed math +// (sponsorPaid from the Purchase event, prize = 10% of the price paid, company = the rest). +function split(x) { + if (Array.isArray(x.pays) && x.pays.length) return x.pays; + let paid = 0n, sp = 0n; try { paid = BigInt(x.weiPaid || 0); sp = BigInt(x.sponsorPaid || 0); } catch (e) {} + const prizeWei = paid * BigInt(SPLIT.prizeBps) / BigInt(SPLIT.denom); + const out = []; + if (x.sponsor && x.sponsor !== ZERO && sp > 0n) out.push({ role: 'sponsor', to: lc(x.sponsor), wei: sp.toString() }); + out.push({ role: 'prize', to: lc(C.prizePot.wallet), wei: prizeWei.toString() }); + out.push({ role: 'company', to: null, wei: (paid - sp - prizeWei).toString() }); + return out; +} +// the Paid / PaymentFailed events of one purchase, from its receipt (null if the RPC does not answer) +async function readPays(tx, orderId) { + const r = await shop.rpc('eth_getTransactionReceipt', [tx]); if (!r || !Array.isArray(r.logs)) return null; + const out = []; + for (const l of r.logs) { + if (lc(l.address) !== lc(C.contractAddress) || (l.topics[0] !== T_PAID && l.topics[0] !== T_FAIL)) continue; + const d = EV.parseLog({ topics: l.topics, data: l.data }).args; if (Number(d.id) !== Number(orderId)) continue; + out.push({ role: ROLE[Number(d.role)] || 'role' + Number(d.role), to: lc(d.to), wei: d.amount.toString(), failed: l.topics[0] === T_FAIL || undefined }); + } + return out.length ? out : null; +} + +// ---- public ledger ---- +function purchases() { + const P = (store.state() && store.state().purchases) || {}; + return Object.entries(P).map(([k, x]) => Object.assign({ tx: k.split(':')[0] }, x)); +} +function ledger(n) { + const lim = Math.min(200, Math.max(1, Number(n) || 50)); + const rows = purchases().map(x => { + const s = split(x); + return { kind: 'purchase', tx: x.tx, at: (x.blockAt ? x.blockAt * 1000 : x.at) || null, orderId: x.orderId, buyer: x.buyer, buyerName: nameLocal(x.buyer), what: what(x), + usdCents: x.usdCents, weiPaid: x.weiPaid, pays: s.map(p => ({ role: p.role, to: p.to, name: p.to ? nameLocal(p.to) : null, wei: p.wei, failed: p.failed || undefined })) }; + }); + for (const wk of (prize && prize.history ? prize.history(52) : [])) for (const w of wk.winners) { + if (!w.tx) continue; + rows.push({ kind: 'prize', tx: w.tx, at: wk.paidAt || null, week: wk.week, board: w.board, place: w.place, name: w.name, usd: w.usd, pol: w.pol, confirmed: !!w.confirmed }); + } + rows.sort((a, b) => (b.at || 0) - (a.at || 0)); + const P = purchases(); let wei = 0n, cents = 0, sponsors = 0n; + for (const x of P) { try { wei += BigInt(x.weiPaid || 0); sponsors += BigInt(x.sponsorPaid || 0); } catch (e) {} cents += Number(x.usdCents) || 0; } + const prizesPaid = rows.filter(r => r.kind === 'prize' && r.confirmed).length; + return { contract: C.contractAddress || null, explorer: C.explorer, items: rows.slice(0, lim), + totals: { purchases: P.length, usdCents: cents, weiPaid: wei.toString(), sponsorWei: sponsors.toString(), prizePayouts: prizesPaid } }; +} + +// ---- contract facts (cached 5 minutes) ---- +let cCache = null; +async function contract() { + if (cCache && Date.now() - cCache.at < 300000) return cCache.v; + const v = { address: C.contractAddress || null, chainId: C.chainId, explorer: C.explorer, split: { sponsorPct: 30, prizePct: 10, companyPct: 60 }, + // Marty 2026-11-14: source verified on Sourcify (exact match, 2026-11-13); Polygonscan's own verification is pending + verified: { sourcify: true, polygonscan: 'pending', sourcifyUrl: C.contractAddress ? 'https://repo.sourcify.dev/' + C.chainId + '/' + C.contractAddress : null }, + ownerNote: "Marty's Tangem hardware wallet", live: false }; + if (shop && shop.watching()) { + const I = new Interface(['function owner() view returns (address)', 'function company() view returns (address)', 'function keeper() view returns (address)', + 'function prizeWallet() view returns (address)', 'function paused() view returns (bool)', 'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)']); + const read = async fn => I.decodeFunctionResult(fn, await shop.rpc('eth_call', [{ to: C.contractAddress, data: I.encodeFunctionData(fn, []) }, 'latest']))[0]; + try { + const [owner, company, keeper, prizeWallet, paused, totalOwed, orderCount, bal] = await Promise.all(['owner', 'company', 'keeper', 'prizeWallet', 'paused', 'totalOwed', 'orderCount'].map(read) + .concat([shop.rpc('eth_getBalance', [C.contractAddress, 'latest'])])); + Object.assign(v, { owner: lc(owner), company: lc(company), keeper: lc(keeper), prizeWallet: lc(prizeWallet), paused: !!paused, totalOwedWei: totalOwed.toString(), + orderCount: Number(orderCount), balanceWei: BigInt(bal).toString(), live: true, readAt: Date.now() }); + } catch (e) { v.error = 'The chain did not answer just now. Try again in a minute.'; } + } + cCache = { at: Date.now(), v: v }; + if (v.error) cCache.at = Date.now() - 240000; // retry sooner + return v; +} + +// ---- Telegram ---- +async function tg(method, body) { + const base = String(process.env.TG_API || 'https://api.telegram.org').replace(/\/+$/, ''); + const b = Object.assign({ chat_id: process.env.TG_CHAT, parse_mode: 'HTML' }, body); + if (process.env.TG_PAY_TOPIC) b.message_thread_id = Number(process.env.TG_PAY_TOPIC); + const r = await fetch(base + '/bot' + process.env.TG_TOKEN + '/' + method, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(b), signal: AbortSignal.timeout(15000) }); + const j = await r.json().catch(() => ({})); + if (!j.ok) { st.failed++; st.lastError = String(j.description || r.status).slice(0, 160); console.error('proof: telegram', method, 'failed', r.status, st.lastError); return false; } + return true; +} +// this week's numbers (Central-time week): purchases and dollars from the credited events, the prize pot the site already shows +function weekLine() { + const wk = store.ctWeek(); const s = shop.weekSales(wk, store.ctWeek); let potUsd = null; + try { potUsd = prize.pot(wk).potUsd; } catch (e) {} + return '\u{1F4CA} This week: ' + s.purchases + ' purchase' + (s.purchases === 1 ? '' : 's') + ', ' + usd(s.cents) + (potUsd != null ? ' · prize pot $' + Number(potUsd).toFixed(2) : ''); +} +async function caption(x) { + const lines = ['\u{1F4A5} Viral Banner Blitz', '\u{1F9FE} ' + esc(who(x.buyer, await nameOf(x.buyer))) + ' bought ' + esc(what(x)) + ' · ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL)']; + for (const p of split(x)) { + if (p.failed) { lines.push('⚠️ ' + (p.role === 'sponsor' ? 'Sponsor' : p.role) + ' payment to ' + esc(who(p.to, await nameOf(p.to))) + ' bounced; it waits in the contract for them to claim'); continue; } + if (p.role === 'sponsor') lines.push('\u{1F4B8} Sponsor 30%: ' + pol(p.wei) + ' POL → ' + esc(who(p.to, await nameOf(p.to)))); + else if (p.role === 'prize') lines.push('\u{1F3C6} Weekly prize pot 10%: ' + pol(p.wei) + ' POL'); + else if (p.role === 'company') lines.push('\u{1F3E6} Viral Banner Blitz: ' + pol(p.wei) + ' POL'); + } + lines.push('Split by the contract in this same transaction. The contract keeps nothing and there is nothing to withdraw.'); + lines.push(weekLine()); + lines.push('· Verify on Polygonscan · Live ledger'); + return lines.join('\n'); +} +let card = 0; +// shop.js calls this once per newly credited purchase (rec = the stored purchase, tx = its transaction) +function onPurchase(rec, tx) { + const x = Object.assign({ tx }, rec); + (async () => { + // the real split from the receipt (a bounced push shows as owed), kept on the purchase for the ledger + try { const pays = await readPays(tx, rec.orderId); if (pays) { const S = store.state(); const k = Object.keys(S.purchases || {}).find(k2 => k2.startsWith(lc(tx) + ':') && S.purchases[k2].orderId === rec.orderId); if (k) { S.purchases[k].pays = pays; store.save(); } x.pays = pays; } } catch (e) {} + if (!on()) return; + const at = (rec.blockAt ? rec.blockAt * 1000 : rec.at) || Date.now(); + if (Date.now() - at > 2 * 3600000) { st.skipped++; return; } + const text = await caption(x); + if (!once('p:' + lc(tx) + ':' + rec.orderId) || !(await docstore.claim('vbbtg:' + lc(tx) + ':' + rec.orderId))) return; // another app copy already posted this purchase + const photo = 'https://' + C.site + CARDS[card++ % CARDS.length]; + let ok = await tg('sendPhoto', { photo: process.env.TG_PHOTO_BASE ? String(process.env.TG_PHOTO_BASE).replace(/\/+$/, '') + CARDS[(card - 1) % CARDS.length] : photo, caption: text }); + if (!ok) ok = await tg('sendMessage', { text, disable_web_page_preview: true }); // a photo the API cannot fetch still gets its proof line + if (ok) { st.posted++; console.log('proof: posted purchase', String(tx).slice(0, 12)); } + })().catch(e => { st.failed++; st.lastError = String(e.message).slice(0, 160); }); +} +// prize.js calls this when a prize transfer confirms on chain +function onPrize(plan, t) { + if (!on() || !t || !t.tx) return; + (async () => { + if (t.sentAt && Date.now() - t.sentAt > 2 * 3600000) { st.skipped++; return; } + if (!once('z:' + lc(t.tx)) || !(await docstore.claim('vbbtg-prize:' + lc(t.tx)))) return; + const board = t.board === 'sources' ? 'most traffic sources' : 'most verified visitors'; + const place = ['1st', '2nd', '3rd'][t.place - 1] || ('#' + t.place); + const text = '\u{1F3C6} Viral Banner Blitz weekly prize\n' + esc(t.name || short(t.address)) + ' · ' + place + ' place, ' + board + ' (week of ' + esc(plan.week) + '): ' + + esc(t.pol) + ' POL ($' + Number(t.usd).toFixed(2) + ')\n· Verify on Polygonscan · Live ledger'; + if (await tg('sendMessage', { text, disable_web_page_preview: true })) { st.prizeLines++; console.log('proof: posted prize', String(t.tx).slice(0, 12)); } + })().catch(e => { st.failed++; st.lastError = String(e.message).slice(0, 160); }); +} +function view() { return Object.assign({ telegram: on(), topic: process.env.TG_PAY_TOPIC || null }, st); } +module.exports = { init, ledger, contract, onPurchase, onPrize, caption, split, view, on, CARDS }; diff --git a/public/admin.html b/public/admin.html index 60bd5ab..8cfea7f 100644 --- a/public/admin.html +++ b/public/admin.html @@ -22,7 +22,7 @@ - +