1112a8c589
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
183 lines
15 KiB
JavaScript
183 lines
15 KiB
JavaScript
// Trust pack (Marty 2026-11-14: live ledger, contract proof, toasts, a Telegram post per sale with an image + stats, payment
|
|
// notifications). The ViralAdBlitz / Downline Banners pattern, with the 5xYourTeam split:
|
|
// - ledger(): every position purchase (the Purchase events shop.js recorded) with its split read from the receipt: the sponsor
|
|
// share (level 1, 25%), levels 2-5 (5% each) with each person's place in the buyer's line, who was passed over, the Best Coach
|
|
// prize pot (10%), the company. Plus the Best Coach pot payouts recorded by the admin (tx hashes).
|
|
// - contract(): live facts for /contract (owner, company, prize wallet, keeper, paused, orders, what it holds), cached 5 minutes.
|
|
// - Telegram: (1) a sale card per purchase (a prebuilt 5xYourTeam proof image, rotated; the coach, every share paid in the same
|
|
// transaction with its POL, this week's numbers, the verify link); (2) the Draft Day card after each draft (results image +
|
|
// picks); (3) one line per Best Coach payout. PHASE 1: nothing is sent unless TG_LIVE=1 with TG_TOKEN + TG_CHAT; otherwise every
|
|
// post goes to the document tg-outbox.json (shown on /admin) so the wording can be checked. Once per key across app copies
|
|
// (in-process guard + docstore.claim), never a sale older than 2 hours. TG_API (tests) = a stand-in.
|
|
'use strict';
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const store = require('./store');
|
|
const docstore = require('./docstore');
|
|
|
|
const SPLIT = { sponsorBps: 2500, levelBps: 500, potBps: 1000, denom: 10000, potLevel: 6 }; // DraftPosition constants
|
|
const CARDS = ['/art/proof/fx-proof-navy.png', '/art/proof/fx-proof-gold.png', '/art/proof/fx-proof-field.png']; // rotated per post
|
|
const st = { posted: 0, queued: 0, skipped: 0, failed: 0, lastError: null };
|
|
let C = null, shop = null, names = null, weekStats = () => ({});
|
|
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; names = deps.nameOf || null; if (deps.weekStats) weekStats = deps.weekStats; }
|
|
const live = () => process.env.TG_LIVE === '1' && !!(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 local = nameLocal(addr); if (local) return local; if (names) { try { const n = await names(lc(addr)); 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]));
|
|
const what = x => (Number(x.qty) > 1 ? x.qty + ' positions' : 'a position');
|
|
|
|
// the split of one order: from the receipt when read, else from the Purchase event (who got each level is then unknown)
|
|
function split(x) {
|
|
if (Array.isArray(x.pays) && x.pays.length) return x.pays;
|
|
let paid = 0n; try { paid = BigInt(x.weiPaid || 0); } catch (e) {}
|
|
const out = [];
|
|
for (let i = 1; i <= Number(x.levelsPaid || 0); i++) out.push({ level: i, depth: null, to: null, wei: (paid * BigInt(i === 1 ? SPLIT.sponsorBps : SPLIT.levelBps) / BigInt(SPLIT.denom)).toString() });
|
|
out.push({ level: SPLIT.potLevel, depth: 0, to: lc(C.prizeWallet), wei: String(x.prizePaid != null ? x.prizePaid : paid * BigInt(SPLIT.potBps) / BigInt(SPLIT.denom)) });
|
|
out.push({ level: 0, depth: 0, to: lc(C.companyWallet), wei: String(x.companyPaid || 0) });
|
|
return out;
|
|
}
|
|
// the contract's pass-up split as a pure model (preview + tests): line = [{ who, qualified }] nearest first, wei = POL kept.
|
|
// Mirrors DraftPosition._split exactly: first qualified 25%, next four 5%, within 20 places; pot 10%; company the remainder.
|
|
function model(line, wei) {
|
|
const W = BigInt(wei); const sp = W * BigInt(SPLIT.sponsorBps) / BigInt(SPLIT.denom), lv = W * BigInt(SPLIT.levelBps) / BigInt(SPLIT.denom), pot = W * BigInt(SPLIT.potBps) / BigInt(SPLIT.denom);
|
|
const pays = [], over = [], seen = new Set(); let total = 0n;
|
|
for (let i = 0; i < Math.min(line.length, 20) && pays.length < 5; i++) {
|
|
const x = line[i]; if (!x.qualified) { over.push({ who: x.who, depth: i + 1 }); continue; }
|
|
if (seen.has(x.who)) continue; seen.add(x.who);
|
|
const amt = pays.length === 0 ? sp : lv; pays.push({ level: pays.length + 1, depth: i + 1, to: x.who, wei: amt.toString() }); total += amt;
|
|
}
|
|
return { pays, over, pot: pot.toString(), company: (W - total - pot).toString() };
|
|
}
|
|
const label = p => p.level === 0 ? 'company' : p.level === SPLIT.potLevel ? 'pot' : p.level === 1 ? 'sponsor' : 'level ' + p.level;
|
|
|
|
// ---- public ledger ----
|
|
function rows() { return store.purchases().map(x => Object.assign({ tx: x.key.split(':')[0] }, x)); }
|
|
function ledger(n) {
|
|
const lim = Math.min(200, Math.max(1, Number(n) || 50));
|
|
const list = rows().map(x => ({ kind: 'position', 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), qty: x.qty,
|
|
usdCents: x.usdCents, weiPaid: x.weiPaid,
|
|
pays: split(x).map(p => ({ level: p.level, label: label(p), depth: p.depth, to: p.to, name: p.to ? nameLocal(p.to) : null, wei: p.wei, failed: p.failed || undefined })),
|
|
passedOver: (x.over || []).map(o => ({ depth: o.depth, name: nameLocal(o.who) || null, who: o.who })) })).sort((a, b) => (b.at || 0) - (a.at || 0));
|
|
let wei = 0n, pot = 0n, cents = 0, positions = 0;
|
|
for (const x of rows()) { positions += Number(x.qty) || 1; cents += Number(x.usdCents) || 0; try { wei += BigInt(x.weiPaid || 0); pot += BigInt(x.prizePaid || 0); } catch (e) {} }
|
|
const payouts = Object.entries(store.state().payouts || {}).flatMap(([week, l]) => l.map(p => Object.assign({ week }, p))).sort((a, b) => (b.at || 0) - (a.at || 0));
|
|
return { contract: C.contractAddress || null, explorer: C.explorer, prizeWallet: C.prizeWallet || null, items: list.slice(0, lim), payouts: payouts.slice(0, 50),
|
|
totals: { positions, orders: list.length, usdCents: cents, weiPaid: wei.toString(), potWei: pot.toString() } };
|
|
}
|
|
// the week's pot: 10% of every position sold that Central week (from the Purchase events)
|
|
function potOf(from, to) {
|
|
let w = 0n; for (const x of rows()) { const t = (x.blockAt ? x.blockAt * 1000 : x.at) || 0; if (t >= from && t < to) { try { w += BigInt(x.prizePaid || 0); } catch (e) {} } }
|
|
return w.toString();
|
|
}
|
|
|
|
// ---- 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: C.split, position: { usd: C.position.usd },
|
|
verified: { sourcify: /sourcify/i.test(process.env.CONTRACT_VERIFIED || ''), polygonscan: /polygonscan/i.test(process.env.CONTRACT_VERIFIED || '') ? 'done' : 'pending', // CONTRACT_VERIFIED=sourcify,polygonscan once each match is confirmed
|
|
sourcifyUrl: C.contractAddress ? 'https://repo.sourcify.dev/' + C.chainId + '/' + C.contractAddress : null },
|
|
ownerNote: "Marty's Tangem hardware wallet", prizeWallet: C.prizeWallet || null, live: false };
|
|
if (shop && shop.watching()) {
|
|
const { Interface } = require('ethers');
|
|
const I = new Interface(['function owner() view returns (address)', 'function company() view returns (address)', 'function prizeWallet() view returns (address)', 'function keeper() view returns (address)',
|
|
'function paused() view returns (bool)', 'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)', 'function priceCents() 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, prize, keeper, paused, totalOwed, orderCount, cents, bal] = await Promise.all(['owner', 'company', 'prizeWallet', 'keeper', 'paused', 'totalOwed', 'orderCount', 'priceCents'].map(read)
|
|
.concat([shop.rpc('eth_getBalance', [C.contractAddress, 'latest'])]));
|
|
Object.assign(v, { owner: lc(owner), company: lc(company), prizeWallet: lc(prize), keeper: lc(keeper), paused: !!paused, totalOwedWei: totalOwed.toString(), orderCount: Number(orderCount),
|
|
priceCents: Number(cents), 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 };
|
|
if (v.error) cCache.at = Date.now() - 240000;
|
|
return v;
|
|
}
|
|
|
|
// ---- Telegram (phase 1: the outbox) ----
|
|
const OUTBOX = () => path.join(C.dataDir, 'tg-outbox.json');
|
|
function outbox() { try { return JSON.parse(fs.readFileSync(OUTBOX(), 'utf8')); } catch (e) { return []; } }
|
|
async function tg(method, body, key) {
|
|
if (!live()) {
|
|
const l = outbox(); l.push({ at: Date.now(), key, method, body }); fs.writeFileSync(OUTBOX(), JSON.stringify(l.slice(-100))); st.queued++; return true;
|
|
}
|
|
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; }
|
|
st.posted++; return true;
|
|
}
|
|
const photoUrl = p => (process.env.TG_PHOTO_BASE ? String(process.env.TG_PHOTO_BASE).replace(/\/+$/, '') : 'https://' + C.site) + p;
|
|
function weekLine() {
|
|
const w = weekStats();
|
|
return '\u{1F4CA} This week: ' + (w.positions || 0) + ' position' + (w.positions === 1 ? '' : 's') + ' · ' + (w.coaches || 0) + ' coaches · ' + (w.started || 0) + ' picks started · pot ' + pol(w.potWei || 0) + ' POL';
|
|
}
|
|
async function caption(x) {
|
|
const lines = ['\u{1F3C8} <b>5xYourTeam</b>', '\u{1F4DD} ' + esc(who(x.buyer, await nameOf(x.buyer))) + ' joined The Draft: ' + esc(what(x)) + ' · ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL)'];
|
|
const s = split(x); let levels = 0;
|
|
for (const p of s) {
|
|
if (p.level === 0) { lines.push('\u{1F3E6} 5xYourTeam: ' + pol(p.wei) + ' POL'); continue; }
|
|
if (p.level === SPLIT.potLevel) { lines.push('\u{1F3C6} Best Coach pot 10%: ' + pol(p.wei) + ' POL'); continue; }
|
|
levels++;
|
|
const where = p.depth && p.depth !== p.level ? ' (place ' + p.depth + ' in the line)' : '';
|
|
const pct = p.level === 1 ? 'Sponsor 25%' : 'Level ' + p.level + ' 5%';
|
|
if (p.failed) lines.push('⚠️ ' + pct + ' payment to ' + esc(who(p.to, await nameOf(p.to))) + ' bounced; it waits in the contract for them to claim');
|
|
else lines.push('\u{1F4B8} ' + pct + ': ' + pol(p.wei) + ' POL → ' + (p.to ? esc(who(p.to, await nameOf(p.to))) : 'sponsor') + where);
|
|
}
|
|
if (levels === 0) lines.push('Nobody in this line holds a position yet, so the level shares went to 5xYourTeam.');
|
|
if ((x.over || []).length) lines.push(x.over.length === 1 ? '1 person in the line holds no position yet and was passed over; their share went up the line.' : x.over.length + ' people in the line hold no position yet and were passed over; their shares went up the line.');
|
|
lines.push('Paid by the contract in this same transaction. It keeps nothing and there is nothing to withdraw.');
|
|
lines.push(weekLine());
|
|
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;
|
|
// shop.js calls this once per newly recorded purchase (rec = the stored purchase, tx = its transaction)
|
|
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, over: sp.over, bound: sp.bound }); store.save(); } Object.assign(x, { pays: sp.pays, over: sp.over }); }
|
|
} catch (e) {}
|
|
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);
|
|
const key = 'fxtg:' + lc(tx) + ':' + rec.orderId;
|
|
if (!once(key) || !(await docstore.claim(key))) return; // never the same sale twice
|
|
const photo = photoUrl(CARDS[card++ % CARDS.length]);
|
|
let ok = await tg('sendPhoto', { photo, caption: text }, key);
|
|
if (!ok) ok = await tg('sendMessage', { text, disable_web_page_preview: true }, key);
|
|
})().catch(e => { st.failed++; st.lastError = String(e.message).slice(0, 160); });
|
|
}
|
|
// the Draft Day card: d = the finished draft, rows = [{ slot, coach, person }], stats = { players, coaches, potWei }
|
|
async function draftDay(d, rows, stats) {
|
|
const key = 'fxdraft:' + d.week;
|
|
if (!once(key) || !(await docstore.claim(key))) return false;
|
|
const top = rows.slice(0, 12).map(r => '<b>' + esc(r.slot) + '</b> ' + esc('@' + (r.coach || '?')) + ' takes ' + esc('@' + (r.person || '?'))).join('\n');
|
|
const text = ['\u{1F3C8} <b>5xYourTeam · Draft Day results, week of ' + esc(d.week) + '</b>', top, (rows.length > 12 ? '...and ' + (rows.length - 12) + ' more picks' : ''),
|
|
'\u{1F465} ' + stats.players + ' players drafted · ' + stats.coaches + ' coaches', '\u{1F3C6} Best Coach pot this week: ' + pol(stats.potWei) + ' POL',
|
|
'Draft order next Monday is earned: get your picks started. · <a href="https://' + esc(C.site) + '/">The draft board</a>'].filter(Boolean).join('\n');
|
|
return tg('sendPhoto', { photo: photoUrl('/art/draftday/week-' + d.week + '.png'), caption: text }, key);
|
|
}
|
|
// one line per Best Coach payout (recorded by the admin with its tx hash)
|
|
async function payoutLine(week, p) {
|
|
const key = 'fxpot:' + week + ':' + p.rank;
|
|
if (!once(key) || !(await docstore.claim(key))) return false;
|
|
return tg('sendMessage', { text: '\u{1F3C6} <b>5xYourTeam</b> Best Coach, week of ' + esc(week) + ': #' + p.rank + ' ' + esc('@' + (p.username || short(p.coach))) + ' got ' + pol(p.wei) + ' POL from the pot · <a href="' + esc(C.explorer) + '/tx/' + esc(p.tx) + '">Verify</a>', disable_web_page_preview: true }, key);
|
|
}
|
|
function view() { return Object.assign({ telegram: live() ? 'live' : 'outbox (phase 1: nothing is sent)', topic: process.env.TG_PAY_TOPIC || null, outbox: outbox().slice(-10) }, st); }
|
|
module.exports = { model, init, ledger, potOf, contract, onPurchase, draftDay, payoutLine, caption, split, view, live, outbox, CARDS, SPLIT };
|