Files
yourprogrambuilder/proof.js
T
martbost a8a1a8eec7 YourProgramBuilder, the Seed Bed (Marty 2026-11-17: "keep fleshing it out"): STAGING build
Plant a program free (referral link with {id}, link check green / yellow / red, daily recheck, reports), members save their
referral IDs in its packet, a sponsor-first link (member page / ?r= / the hub sponsor line, then the planter), the sprout meter
to REVIEW_SAVES (DEFAULT 25) -> Marty's review queue -> approved packets exported for the CTB builder / DownlineHydra wild heads
with every saved ID. Dormant old programs confirmed by their owner, old-link redirects (oldrefs), Spotlight on YPBShop (NOT
deployed; DEFAULT $10 / 1,000 views, 20/5/5/5/5, company 60), verified views with Spotlight delivery, trust pack (ledger,
contract, toasts, Telegram card, terms / disclaimer / privacy, TrustClickz only), network footer row, chatbot, promo kit,
Guides, PolHunter slot, LinkSpin tracked-link and zone hooks, AI writer through the hub. Seed-catalog look from the approved
mockup. Tests: qa/unit.test.cjs 33/33, qa/e2e.mjs 121/121 on a local anvil chain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:30:59 -06:00

107 lines
8.2 KiB
JavaScript

// 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 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) : '';
function nameLocal(addr) { const m = store.member(lc(addr)); return m && m.username ? m.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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[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));
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} <b>YourProgramBuilder</b>', '\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('· <a href="' + esc(C.explorer) + '/tx/' + esc(x.tx) + '">Verify on Polygonscan</a> · <a href="https://' + esc(C.site) + '/ledger">Live ledger</a>');
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];
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 };