// Trust pack (Marty 2026-11-14, standing for every network site): live ledger, contract proof, toasts, a Telegram photo card per sale. // - ledger(): every Spotlight (the Purchase events shop.js recorded) with its split read from the receipt: each sponsor level // (kinds 1..5, with the person's place in the compressed line) and the company; plus delivery (views so far). Never an email. // - contract(): live facts for /contract (owner, company, keeper, paused, split, SKU and any pending SKU change with its 48 h // eta), cached 5 minutes. Without a contract (staging) it answers the planned values marked as not deployed. // - Telegram: one photo card per Spotlight to TG_CHAT / TG_PAY_TOPIC (off unless TG_TOKEN and TG_CHAT are set; staging leaves them empty). 'use strict'; const store = require('./store'); const docstore = require('./docstore'); const hubpeople = require('./hubpeople'); const CARDS = ['/art/proof/ypb-proof-plate.png', '/art/proof/ypb-proof-bed.png']; const st = { posted: 0, skipped: 0, failed: 0, lastError: null }; let C = null, shop = null, wire = null; const sent = new Set(); 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; wire = deps.wire; } 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) : ''; // people paid in a Spotlight need not have signed in here (Marty 11-18: Biz Ventures showed as a wallet): fall back to the hub's username const hubNames = new Map(); function nameLocal(addr) { const m = store.member(lc(addr)); return m && m.username ? m.username : (hubNames.get(lc(addr)) || {}).name || null; } async function warmNames(addrs) { for (const a of new Set(addrs.map(lc).filter(Boolean))) { const m = store.member(a); if (m && m.username) continue; const h = hubNames.get(a); if (h && Date.now() - h.at < 3600000) continue; const r = await hubpeople.byWallet(a).catch(() => ({ ok: false })); if (!r.ok) return; if (hubNames.size > 5000) hubNames.clear(); hubNames.set(a, { at: Date.now(), name: r.person && r.person.username ? String(r.person.username) : null }); } } const who = a => nameLocal(a) ? '@' + nameLocal(a) : short(lc(a)); 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])); const KIND = k => k === 0 ? 'company' : 'level ' + k; function split(x) { if (Array.isArray(x.pays) && x.pays.length) return x.pays; return [{ kind: 0, depth: 0, to: lc(C.companyWallet), wei: String(x.companyPaid || '0') }]; } function rows() { return Object.entries((store.state() && store.state().purchases) || {}).map(([k, x]) => Object.assign({ key: k, tx: k.split(':')[0] }, x)); } function ledger(n) { const lim = Math.min(200, Math.max(1, Number(n) || 50)); warmNames(rows().flatMap(x => [x.buyer].concat(split(x).map(q => q.to)))).catch(() => {}); const list = rows().map(x => { const p = x.packetId ? store.packet(x.packetId) : null; const dv = wire.spotView(x); return { kind: 'spotlight', tx: x.tx, at: (x.blockAt ? x.blockAt * 1000 : x.at) || null, orderId: x.orderId, buyer: x.buyer, buyerName: nameLocal(x.buyer), qty: x.qty, views: x.views, usdCents: x.usdCents, weiPaid: x.weiPaid, packet: p ? { id: p.id, name: p.name } : null, delivery: { views: dv.views, delivered: dv.delivered, status: dv.status }, pays: split(x).map(q => ({ kind: q.kind, label: KIND(q.kind), depth: q.depth, to: q.to, name: q.to ? nameLocal(q.to) : null, wei: q.wei, failed: q.failed || undefined })) }; }).sort((a, b) => (b.at || 0) - (a.at || 0)); let wei = 0n, cents = 0, spots = 0, levels = 0n; for (const x of rows()) { spots += Number(x.qty) || 1; cents += Number(x.usdCents) || 0; try { wei += BigInt(x.weiPaid || 0); } catch (e) {} for (const q of split(x)) if (q.kind >= 1 && q.kind <= 5) { try { levels += BigInt(q.wei); } catch (e) {} } } return { contract: C.contractAddress || null, explorer: C.explorer, items: list.slice(0, lim), totals: { spotlights: spots, orders: list.length, usdCents: cents, weiPaid: wei.toString(), levelsWei: levels.toString() } }; } 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, deployed: false, planned: true, split: { levelBps: C.split.levelBps, maxDepth: C.split.maxDepth }, spotlight: { usd: C.spotlight.usd, views: C.spotlight.views }, skuDelayHours: 48, company: lc(C.companyWallet), verified: { sourcify: process.env.VERIFIED_SOURCIFY === '1', polygonscan: process.env.VERIFIED_POLYGONSCAN === '1' }, ownerNote: "Marty's Tangem hardware wallet", live: false }; if (shop && shop.watching()) { try { const one = f => shop.call(f).then(r => r[0]); const [owner, company, keeper, paused, totalOwed, orderCount, delay] = await Promise.all(['owner', 'company', 'keeper', 'paused', 'totalOwed', 'orderCount', 'SKU_DELAY'].map(one)); const r = await shop.liveRules(C.spotlight.sku); Object.assign(v, { owner: lc(owner), company: lc(company), keeper: lc(keeper), paused: !!paused, totalOwedWei: totalOwed.toString(), orderCount: Number(orderCount), skuDelayHours: Number(delay) / 3600, live: true, deployed: true, planned: false, readAt: Date.now() }); if (r) { v.split = { levelBps: r.levelBps, maxDepth: 20 }; v.sku = r.sku; v.pendingSku = r.pending; } } catch (e) { v.error = 'The chain did not answer just now. Try again in a minute.'; } } cCache = { at: Date.now(), v }; if (v.error) cCache.at = Date.now() - 240000; return v; } 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); return false; } return true; } function caption(x) { const w = wire.weekStats(); const p = x.packetId ? store.packet(x.packetId) : null; const lines = ['\u{1F331} YourProgramBuilder', '\u{2600}\u{FE0F} ' + esc(who(x.buyer)) + ' spotlighted ' + (p ? '"' + esc(p.name) + '"' : 'a packet') + ' · ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL) · ' + Number(x.views || 0).toLocaleString('en-US') + ' guaranteed views']; for (const q of split(x)) { if (q.kind === 0) lines.push('\u{1F3E6} YourProgramBuilder: ' + pol(q.wei) + ' POL'); else lines.push((q.failed ? '⚠️ ' : '\u{1F4B8} ') + 'Level ' + q.kind + ': ' + pol(q.wei) + ' POL → ' + esc(who(q.to)) + (q.failed ? ' (bounced, waits in the contract to claim)' : '')); } lines.push('Paid by the contract in this same transaction.'); lines.push('\u{1F4CA} This week: ' + w.spotlights + ' Spotlights · ' + w.saves + ' saved IDs · ' + w.vclicks + ' verified clicks'); lines.push('· Verify on Polygonscan · Live ledger'); return lines.join('\n'); } let card = 0; function onPurchase(rec, tx) { const x = Object.assign({ tx }, rec); (async () => { try { const sp = await shop.readSplit(tx, rec.orderId); if (sp) { const S = store.state(); const k = Object.keys(S.purchases || {}).find(k2 => k2.startsWith(lc(tx) + ':') && S.purchases[k2].orderId === rec.orderId); if (k) { Object.assign(S.purchases[k], { pays: sp.pays }); store.save(); } Object.assign(x, { pays: sp.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; } if (!once('p:' + lc(tx) + ':' + rec.orderId) || !(await docstore.claim('ypbtg:' + lc(tx) + ':' + rec.orderId))) return; const photo = (process.env.TG_PHOTO_BASE ? String(process.env.TG_PHOTO_BASE).replace(/\/+$/, '') : 'https://' + C.site) + CARDS[card++ % CARDS.length]; await warmNames([x.buyer].concat(split(x).map(q => q.to))); const text = caption(x); let ok = await tg('sendPhoto', { photo, caption: text }); if (!ok) ok = await tg('sendMessage', { text, disable_web_page_preview: true }); if (ok) st.posted++; })().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, caption, split, view, on, CARDS };