Payment proof + transparency (Marty 2026-11-13): every spot sale posts ONE message to the group's payments topic (tgproof.js: buyer, each member paid with POL and $ at the contract's price, company + fund line, Polygonscan verify + live ledger links; once across app copies via docstore.claim; never older than 2 h). New /ledger (every sale and payout, live, verify links) and /contract (verified source, owner, keeper, fee wallets, price feed, live reads, fixed split, how to check). Live sale toasts bottom-left on every page (real ledger rows only, newest 30 min). Nav + footer links. common.js?v=3, line.css?v=5. Smoke 76/76.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-13 10:35:08 -06:00
parent c6ca40a241
commit 87354e29b6
14 changed files with 259 additions and 15 deletions
+8 -1
View File
@@ -177,8 +177,15 @@ async function runRows() {
const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) });
const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); };
function isOn() { return ready && !!pool; }
// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true.
async function claim(key) {
if (!pool) return true;
await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB');
const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]);
return r.affectedRows === 1;
}
// SIGTERM during a deploy: write what is pending, then exit
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn };
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };
+27 -2
View File
@@ -17,7 +17,7 @@ window.BL = (function () {
async function renderNav(active) {
const c = await getConfig().catch(() => ({}));
const n = document.createElement('nav');
const links = [['/', 'Home'], ['/board', 'Board'], ['/how', 'How it works'], ['/join', 'Get a spot'], ['/my', 'My Spots']];
const links = [['/', 'Home'], ['/board', 'Board'], ['/how', 'How it works'], ['/ledger', 'Ledger'], ['/join', 'Get a spot'], ['/my', 'My Spots']];
n.innerHTML = '<div class="wrap"><a class="brand" href="/"><img src="/art/mark.svg" alt="" width="38" height="38"><span class="logo-wrap"><span class="logo">Downline <b>Banners</b></span>'
+ '<span class="byline">Part of the <b>Crypto Team Build</b> Network</span></span></a><div class="links">'
+ links.map(l => '<a href="' + l[0] + '"' + (l[0] === active ? ' class="active"' : '') + '>' + l[1] + '</a>').join('') + '</div></div>';
@@ -35,8 +35,9 @@ window.BL = (function () {
f.className = 'bl-foot';
f.innerHTML = '<div class="wrap"><p>Part of the Crypto Team Build Network</p>'
+ '<p class="muted small">A spot buys 300 guaranteed views on the board and a place in the line. Nothing is promised: you are paid only when spots sell after yours, and a spot can earn back less than it cost.</p>'
+ '<p class="small"><a href="/how">How it works</a> &middot; <a href="/board">Board</a> &middot; <a href="/my">My Spots</a></p></div>';
+ '<p class="small"><a href="/how">How it works</a> &middot; <a href="/board">Board</a> &middot; <a href="/ledger">Live ledger</a> &middot; <a href="/contract">Contract proof</a> &middot; <a href="/my">My Spots</a></p></div>';
document.body.appendChild(f);
toasts();
}
// one spot tile; href goes through the /go relay, which counts the click
function tile(t, opts) {
@@ -50,6 +51,30 @@ window.BL = (function () {
if (opts && opts.meta) { const m = document.createElement('span'); m.className = 'lot-meta'; m.textContent = t.t === 'spot' ? '#' + t.id : 'network'; a.appendChild(m); }
return a;
}
// live sale toasts (Marty 2026-11-13): real sales from the ledger only, bottom-left, one at a time, never older than 30 minutes
let toastsOn = false;
async function toasts() {
if (toastsOn) return; toastsOn = true;
const seen = new Set(); let first = true;
const box = document.createElement('div'); box.className = 'bl-toasts'; box.setAttribute('aria-live', 'polite'); document.body.appendChild(box);
const show = it => {
const top = it.pays.filter(p => !p.failed).sort((a, b) => (BigInt(b.wei) > BigInt(a.wei) ? 1 : -1))[0];
const name = it.ownerName ? '@' + esc(it.ownerName) : 'A member';
const el = document.createElement('a'); el.className = 'bl-toast'; el.href = '/ledger';
el.innerHTML = '<b>' + name + '</b> took spot #' + it.spotId
+ (top ? '<br><span>' + (it.pays.length > 1 ? it.pays.length + ' members paid, ' : '') + (top.name ? '@' + esc(top.name) : 'a member') + ' got ' + fmtPol(top.wei, 2) + ' POL</span>' : '<br><span>paid on-chain, $5</span>');
box.appendChild(el); requestAnimationFrame(() => el.classList.add('in'));
setTimeout(() => { el.classList.remove('in'); setTimeout(() => el.remove(), 400); }, 7000);
};
const tick = async () => {
let d; try { d = await getJSON('/api/ledger?n=5'); } catch (e) { return; } if (!d || !d.items) return;
const fresh = d.items.filter(it => !seen.has(it.tx) && (!it.at || Date.now() - it.at < 30 * 60000));
d.items.forEach(it => seen.add(it.tx));
const list = first ? fresh.slice(0, 1) : fresh.reverse(); first = false;
list.forEach((it, i) => setTimeout(() => show(it), 1500 + i * 8000));
};
tick(); setInterval(tick, 25000);
}
function withRef(href, sponsor) { if (!sponsor) return href; return href + (href.includes('?') ? '&' : '?') + 'ref=' + encodeURIComponent(sponsor); }
return { $, esc, getConfig, fmtPol, short, framed, status, getJSON, post, renderNav, renderFooter, tile, withRef };
})();
+23
View File
@@ -0,0 +1,23 @@
// Contract proof (Marty 2026-11-13): /api/contract answers straight from the live contract.
(async () => {
BL.renderNav('/contract'); BL.renderFooter();
const { $, esc, fmtPol } = BL;
const d = await BL.getJSON('/api/contract');
if (d.error) { $('facts').innerHTML = '<p class="note err">' + esc(d.error) + '</p>'; return; }
const ex = d.explorer;
const addr = (a, label) => a ? '<a class="mono" target="_blank" rel="noopener" href="' + esc(ex + '/address/' + a) + '">' + esc(a) + '</a>' + (label ? ' <span class="muted small">' + esc(label) + '</span>' : '') : '-';
const rows = [
['Contract', addr(d.address) + ' <span class="badge-ok">Verified source</span> <a class="small" target="_blank" rel="noopener" href="' + esc(ex + '/address/' + d.address + '#code') + '">read the code</a>'],
['Network', esc(d.chain) + ' (chain ' + esc(d.chainId) + ')'],
['Deployed', '<a class="mono" target="_blank" rel="noopener" href="' + esc(ex + '/tx/' + d.deployTx) + '">' + esc(d.deployTx.slice(0, 18)) + '...</a>' + (d.deployBlock ? ' block ' + esc(d.deployBlock) : '')],
['Owner', addr(d.owner, 'can pause new sales and change the keeper; cannot move funds or change the split')],
['Keeper', addr(d.keeper, 'the only wallet allowed to make momentum-fund buys')],
['Company A', addr(d.feeA)], ['Company B', addr(d.feeB)],
['Price feed', addr(d.priceFeed, 'Chainlink POL/USD')],
['Spot price now', d.quoteWei ? fmtPol(d.quoteWei) + ' POL ($5)' : '-'],
['Spots sold', esc(d.spotCount || '0')],
['Momentum fund', d.fundBalance ? fmtPol(d.fundBalance) + ' POL' : '-'],
['Sales', d.paused === 'true' ? 'paused' : 'open']];
$('facts').innerHTML = '<table class="tbl">' + rows.map(r => '<tr><th style="width:160px">' + r[0] + '</th><td style="word-break:break-all">' + r[1] + '</td></tr>').join('') + '</table>';
$('split').innerHTML = '<tr><th>Share</th><th>To</th></tr>' + d.split.map(s => '<tr><td>' + esc(s.share) + '</td><td>' + esc(s.to) + '</td></tr>').join('');
})();
+26
View File
@@ -0,0 +1,26 @@
// Live ledger (Marty 2026-11-13): /api/ledger, refreshed every 20 s. One row per spot sale: buyer, every member paid, company + fund.
(async () => {
BL.renderNav('/ledger'); BL.renderFooter();
const { $, esc, fmtPol, short } = BL;
const who = (name, addr) => name ? '@' + esc(name) : '<span class="mono">' + esc(short(addr)) + '</span>';
const usd = (wei, rate) => rate ? ' <span class="muted">($' + (Number(BigInt(wei) / 10n ** 12n) / 1e6 * rate).toFixed(2) + ')</span>' : '';
const KIND = { 0: 'bought by', 1: 'bought for', 2: 'gifted by the momentum fund to', 3: 'kept by the momentum fund' };
async function load() {
const d = await BL.getJSON('/api/ledger?n=100'); if (d.error) return;
const t = d.totals || {};
$('totals').innerHTML = [['Spots sold', t.spots || 0], ['Members', t.members || 0], ['POL paid out', fmtPol(t.paidOutWei || '0', 2)], ['Momentum fund', t.fundWei ? fmtPol(t.fundWei, 2) + ' POL' : '-']]
.map(x => '<div class="stat"><b>' + esc(x[1]) + '</b><span>' + esc(x[0]) + '</span></div>').join('');
$('rows').innerHTML = d.items.length ? d.items.map(it => {
const when = it.at ? new Date(it.at).toLocaleString() : '';
const pays = it.pays.map(p => '<li>' + (p.failed ? 'Bounced (to the fund): ' : '') + (p.role === 'sponsor' ? 'Sponsor' : 'Line ' + p.level + ' (spot #' + (it.spotId - p.level) + ')')
+ ': <b>' + fmtPol(p.wei) + ' POL</b>' + usd(p.wei, it.usd) + ' to ' + who(p.name, p.to) + '</li>').join('');
return '<div class="ledger-row"><div class="row" style="justify-content:space-between"><div><b>Spot #' + it.spotId + '</b> ' + esc(KIND[it.kind] || '') + ' ' + who(it.ownerName, it.owner)
+ ' <span class="muted">$5 = ' + fmtPol(it.valueWei) + ' POL</span></div><span class="muted small">' + esc(when) + '</span></div>'
+ (pays ? '<ul class="pays">' + pays + '</ul>' : '<p class="muted small">No earlier spots or sponsor to pay yet.</p>')
+ '<p class="small muted">Company + momentum fund: ' + fmtPol(it.houseWei) + ' POL' + usd(it.houseWei, it.usd)
+ ' &middot; <a target="_blank" rel="noopener" href="' + esc(d.explorer + '/tx/' + it.tx) + '">Verify on Polygonscan</a></p></div>';
}).join('') : '<p class="muted">No spot sales yet.</p>';
$('upd').textContent = 'Updated ' + new Date().toLocaleTimeString();
}
await load(); setInterval(load, 20000);
})();
+11
View File
@@ -49,3 +49,14 @@ nav .links a.active{color:var(--mint-ink);background:var(--mint)}
.brand img{flex:none;filter:drop-shadow(0 4px 14px rgba(155,123,255,.35))}
.brand .logo{letter-spacing:-.02em}
.ls-pick{margin:6px 0 4px}.ls-pick .row{gap:8px}
.ledger-row{border-top:1px solid var(--line);padding:12px 0}
.ledger-row:first-child{border-top:0}
.ledger-row .pays{margin:6px 0 4px;padding-left:18px;font-size:14px}
.badge-ok{display:inline-block;font-size:11.5px;font-weight:700;padding:2px 8px;border-radius:999px;background:var(--mint-soft);color:var(--mint);border:1px solid var(--mint-line);margin-left:6px}
.bl-toasts{position:fixed;left:max(16px,env(safe-area-inset-left,0px));bottom:max(16px,env(safe-area-inset-bottom,0px));z-index:50;display:flex;flex-direction:column;gap:8px;pointer-events:none}
.bl-toast{pointer-events:auto;display:block;max-width:300px;background:var(--panel-solid);border:1px solid var(--mint-line);border-radius:14px;padding:10px 14px;color:var(--ink);font-size:13.5px;line-height:1.35;
box-shadow:0 12px 30px -12px rgba(0,0,0,.8);opacity:0;transform:translateY(10px);transition:opacity .35s ease,transform .35s ease;text-decoration:none!important}
.bl-toast.in{opacity:1;transform:none}
.bl-toast span{color:var(--muted);font-size:12.5px}
@media (prefers-reduced-motion:reduce){.bl-toast{transition:none}}
@media (max-width:520px){.bl-toast{max-width:calc(100vw - 32px)}}
+2 -2
View File
@@ -7,7 +7,7 @@
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
<link rel="stylesheet" href="/assets/site.css?v=2">
<link rel="stylesheet" href="/assets/line.css?v=4">
<link rel="stylesheet" href="/assets/line.css?v=5">
</head>
<body>
<main class="wrap">
@@ -17,7 +17,7 @@
<div class="card"><h3>The line so far</h3><div id="stats" class="grid2"></div></div>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=2"></script>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/board.js?v=1"></script>
</body>
</html>
+26
View File
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Contract proof | Downline Banners</title>
<meta name="description" content="The Downline Banners smart contract on Polygon: address, verified source, owner, fee wallets and the fixed split, read live.">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
<link rel="stylesheet" href="/assets/site.css?v=2">
<link rel="stylesheet" href="/assets/line.css?v=5">
</head>
<body>
<main class="wrap">
<section class="hero"><h1>Contract proof</h1><p class="lead">Downline Banners runs on one smart contract on Polygon. Its source code is verified on Polygonscan, the split is fixed in the code, and every number below is read live from the contract. <a href="/ledger">Live ledger</a></p></section>
<div class="card" id="facts"><p class="muted">Reading the contract...</p></div>
<div class="card"><h3>Where each $5 goes, in the same transaction</h3><table class="tbl" id="split"></table>
<p class="muted small">The contract holds nothing except the momentum fund, which can only buy spots. The split cannot be changed and there is no owner withdraw.</p></div>
<div class="card"><h3>Check it yourself</h3><ol class="small">
<li>Open the contract on Polygonscan (link above) and choose the <b>Contract</b> tab: the source code shows a green check for "verified".</li>
<li>Under <b>Read Contract</b>, compare owner, keeper, fee wallets and fund balance with this page.</li>
<li>Open any sale in the <a href="/ledger">live ledger</a> and look at its <b>Logs</b>: one SpotBought event, then one Paid event per payment.</li></ol></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/contract.js?v=1"></script>
</body>
</html>
+2 -2
View File
@@ -7,7 +7,7 @@
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
<link rel="stylesheet" href="/assets/site.css?v=2">
<link rel="stylesheet" href="/assets/line.css?v=4">
<link rel="stylesheet" href="/assets/line.css?v=5">
</head>
<body>
<main class="wrap">
@@ -24,7 +24,7 @@
<div class="card"><h3>The momentum fund</h3><p>When no spot has sold for 4 hours, the fund buys one (at most 12 a day). It gifts the spot to an active member who owns a paid spot and has not had a gift in 7 days, members who referred someone recently first. If nobody qualifies, the fund keeps the spot and its line money goes back into the fund.</p></div>
<div class="card"><h3>The rest of the network</h3><p>Open board slots show network sites such as InstantAdPay and LinkSpin. On InstantAdPay, ad credits buy advertising, not income.</p></div>
</main>
<script src="/assets/common.js?v=2"></script>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/how.js?v=1"></script>
</body>
</html>
+2 -2
View File
@@ -7,7 +7,7 @@
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
<link rel="stylesheet" href="/assets/site.css?v=2">
<link rel="stylesheet" href="/assets/line.css?v=4">
<link rel="stylesheet" href="/assets/line.css?v=5">
</head>
<body>
<main class="wrap">
@@ -37,7 +37,7 @@
</section>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=2"></script>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/gate.js?v=1"></script>
</body>
</html>
+2 -2
View File
@@ -7,7 +7,7 @@
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
<link rel="stylesheet" href="/assets/site.css?v=2">
<link rel="stylesheet" href="/assets/line.css?v=4">
<link rel="stylesheet" href="/assets/line.css?v=5">
</head>
<body>
<main class="wrap">
@@ -34,7 +34,7 @@
<div id="status" class="note" hidden></div>
<div class="card" id="doneCard" hidden><h3>Your spot is in the line</h3><p>Next: add your image and link in My Spots. One free signature signs you in (it cannot move funds).</p><div class="row"><button class="btn" id="toMyBtn">Open My Spots</button></div><p class="small mono" id="txLink"></p></div>
</main>
<script src="/assets/common.js?v=2"></script>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/wallet.js?v=1"></script>
<script src="/assets/join.js?v=2&o=1"></script>
</body>
+22
View File
@@ -0,0 +1,22 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Live ledger | Downline Banners</title>
<meta name="description" content="Every Downline Banners spot sale and every payment the contract made, live from the Polygon blockchain.">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
<link rel="stylesheet" href="/assets/site.css?v=2">
<link rel="stylesheet" href="/assets/line.css?v=5">
</head>
<body>
<main class="wrap">
<section class="hero"><h1>Live ledger</h1><p class="lead">Every spot sale and every payment, read from the Polygon blockchain. Each row links to the transaction so you can check it yourself. <a href="/contract">Contract proof</a></p></section>
<div class="grid2" id="totals"></div>
<div class="card"><div class="row" style="justify-content:space-between"><h3 style="margin:0">Spot sales</h3><span class="muted small" id="upd"></span></div>
<div id="rows"><p class="muted">Loading the ledger...</p></div></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/ledger.js?v=1"></script>
</body>
</html>
+2 -2
View File
@@ -7,7 +7,7 @@
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/logo-icon.png">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700;12..96,800&family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap">
<link rel="stylesheet" href="/assets/site.css?v=2">
<link rel="stylesheet" href="/assets/line.css?v=4">
<link rel="stylesheet" href="/assets/line.css?v=5">
</head>
<body>
<main class="wrap">
@@ -26,7 +26,7 @@
</div>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=2"></script>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/wallet.js?v=1"></script>
<script src="/assets/my.js?v=5"></script>
</body>
+41 -2
View File
@@ -14,6 +14,7 @@ const safety = require('./safety');
const keeper = require('./keeper');
const { iface } = require('./abi');
const refuelspots = require('./refuelspots'); // refuel spots: $50+ Monthly Refuels earn a spot, engine wallet pays (2026-11-13)
const tgproof = require('./tgproof'); // payment proof in the Telegram payments topic, one message per spot sale (2026-11-13)
const hubreport = require('./hubreport'); // network hub, shadow mode: members reported by wallet (2026-11-13), off unless HUB_ENABLED
const networksso = require('./networksso'); // network sign-in: arrive signed in from InstantAdPay or LinkSpin (2026-11-13), see networksso.js
const SEL = { buy: iface.getFunction('buy').selector, buyFor: iface.getFunction('buyFor').selector }; // the browser builds calldata from these (ABI stays in abi.js)
@@ -103,6 +104,27 @@ async function lsSpins(body) {
const j = await r.json().catch(() => ({})); return r.ok ? j : { error: j.error || 'LinkSpin did not answer.' };
} catch (e) { return { error: 'LinkSpin did not answer. Try again in a minute.' }; } finally { clearTimeout(t); }
}
// ---- live ledger: chain events grouped into one row per spot sale ----
async function ledgerData(n) {
const evs = chain.recent(5000); const byTx = new Map();
for (const e of evs.slice().reverse()) { if (!['SpotBought', 'Paid', 'PaymentFailed', 'FundBuy'].includes(e.type)) continue; if (!byTx.has(e.tx)) byTx.set(e.tx, []); byTx.get(e.tx).push(e); }
const fee = new Set(['0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', String(C.contract).toLowerCase()]);
const items = [];
for (const [tx, list] of [...byTx].reverse()) {
const sb = list.find(e => e.type === 'SpotBought'); if (!sb) continue;
let level = 0, house = 0n; const pays = [];
for (const e of list) {
if (e.type !== 'Paid' && e.type !== 'PaymentFailed') continue;
if (e.role === 1) level++;
if (e.type === 'Paid' && (fee.has(e.to) || e.role >= 2)) { house += BigInt(e.amount); continue; }
pays.push({ role: e.role === 0 ? 'sponsor' : 'line', level: e.role === 1 ? level : null, to: e.to, name: await nameOf(e.to).catch(() => null), wei: e.amount, failed: e.type === 'PaymentFailed' });
}
items.push({ tx, at: sb.ts || null, spotId: sb.id, kind: sb.kind, owner: sb.owner, ownerName: await nameOf(sb.owner).catch(() => null), valueWei: sb.valueWei, usd: Number(sb.usdPrice) / 1e8, pays, houseWei: house.toString() });
if (items.length >= n) break;
}
let fund = null; try { const f = await chain.tryRead('fundBalance'); fund = f == null ? null : f.toString(); } catch (e) {}
return { items, totals: Object.assign(chain.totals(), { fundWei: fund }), explorer: C.explorer, contract: C.contract };
}
// ---- sponsor ref (?ref=<address or network username>) ----
async function resolveRef(raw) {
const r = String(raw || '').trim();
@@ -195,7 +217,7 @@ const server = http.createServer(async (req, res) => {
// -- pages
if (req.method === 'GET' || req.method === 'HEAD') {
const PAGES = { '/': 'index.html', '/board': 'board.html', '/join': 'join.html', '/my': 'my.html', '/how': 'how.html' };
const PAGES = { '/': 'index.html', '/board': 'board.html', '/join': 'join.html', '/my': 'my.html', '/how': 'how.html', '/ledger': 'ledger.html', '/contract': 'contract.html' };
if (PAGES[p]) {
const set = [];
if (setVid) set.push(setVid);
@@ -237,6 +259,21 @@ const server = http.createServer(async (req, res) => {
return json(res, 200, { site: C.site, chainId: C.chainId, chainName: C.chainName, contract: C.contract, rpc: C.publicRpc, explorer: C.explorer,
walletConnectProjectId: C.walletConnectProjectId, viewsOwed: C.viewsOwed, spotDays: C.spotDays, priceUsd: 5, ready: !!C.contract, sel: SEL }, extra);
}
// live ledger (Marty 2026-11-13): every spot sale as one row with its payouts, straight from the chain index; the toasts read it too
if (p === '/api/ledger' && req.method === 'GET') {
const n = Math.min(200, Math.max(1, Number(u.searchParams.get('n')) || 50));
return json(res, 200, await ledgerData(n), { 'Cache-Control': 'public, max-age=10' });
}
// contract proof: the live contract's own answers, so anyone can compare them with Polygonscan
if (p === '/api/contract' && req.method === 'GET') {
const r = async f => { const v = await chain.tryRead(f); return v == null ? null : (typeof v === 'bigint' ? v.toString() : String(v).toLowerCase()); };
const [owner, keeper, feeA, feeB, priceFeed, paused, spotCount, fundBalance, quoteWei] = await Promise.all(['owner', 'keeper', 'feeA', 'feeB', 'priceFeed', 'paused', 'spotCount', 'fundBalance', 'quoteWei'].map(r));
return json(res, 200, { address: C.contract, chain: C.chainName, chainId: C.chainId, explorer: C.explorer, verified: true,
deployTx: '0xbe0c76a0999af2b81cd73b69afbe168f08003afdb27dd4ed7be026943e23046d', deployBlock: Number(process.env.START_BLOCK) || null,
owner, keeper, feeA, feeB, priceFeed, paused, spotCount, fundBalance, quoteWei,
split: [{ share: '30%', to: "the buyer's sponsor (none: the momentum fund)" }, { share: '55%', to: '5.5% to each of the 10 spots bought just before (a missing spot: company A)' },
{ share: '5%', to: 'company A' }, { share: '5%', to: 'company B' }, { share: '5%', to: 'the momentum fund (can only buy spots)' }] }, { 'Cache-Control': 'public, max-age=30' });
}
if (p === '/api/quote' && req.method === 'GET') {
try { return json(res, 200, await chain.quote()); } catch (e) { return json(res, 503, { error: e.message }); }
}
@@ -389,7 +426,9 @@ const server = http.createServer(async (req, res) => {
await docstore.init({}); // before anything reads its data
process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); });
store.load();
chain.init();
tgproof.init({ nameOf, contract: C.contract, explorer: C.explorer || 'https://polygonscan.com', site: C.site,
feeWallets: ['0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2'] }); // contract feeA / feeB
chain.init({ onEvent: tgproof.onEvent }); // every spot sale -> one payment-proof message in the payments topic
hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() });
refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy());
keeper.init();
+65
View File
@@ -0,0 +1,65 @@
// Payment proof on Telegram (Marty 2026-11-13: "anytime members are paid in Downline Banners ... put all those back together in one
// message", with the verify link). One message per spot sale, in the group's shared payments topic (TG_CHAT / TG_PAY_TOPIC, the
// CTB Rewards bot TG_TOKEN, same as the games): who bought, then every member paid (sponsor, then each line level) in POL with the
// dollar value at the contract's own price, then one line for the company + momentum fund share, then the Polygonscan link.
// Built from the chain events of the transaction (SpotBought first, then Paid / PaymentFailed in contract order). Sent once across
// app copies (docstore.claim). Never posts events older than 2 hours (a re-index after downtime must not flood the topic).
'use strict';
const docstore = require('./docstore');
const ROLE = { SPONSOR: 0, LEVEL: 1, FEE_A: 2, FEE_B: 3, FUND: 4 };
let X = null; const buf = new Map();
const on = () => !!(process.env.TG_TOKEN && process.env.TG_CHAT);
const esc = s => String(s == null ? '' : s).replace(/[&<>]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
const pol = wei => { const v = Number(BigInt(wei) / 10n ** 12n) / 1e6; return v >= 100 ? v.toFixed(2) : v.toFixed(4); };
function init(deps) { X = deps; } // { nameOf(addr) -> username|null, contract, explorer, site }
function onEvent(ev) {
if (!on() || !ev || !ev.tx || !['SpotBought', 'Paid', 'PaymentFailed'].includes(ev.type)) return;
if (ev.ts && Date.now() - ev.ts > 2 * 3600000) return;
let b = buf.get(ev.tx); if (!b) { b = { evs: [], t: null }; buf.set(ev.tx, b); }
b.evs.push(ev); clearTimeout(b.t); b.t = setTimeout(() => { buf.delete(ev.tx); send(ev.tx, b.evs).catch(e => console.error('tgproof', e.message)); }, 3000);
}
async function who(addr) {
const a = String(addr || '').toLowerCase();
let n = null; try { n = await X.nameOf(a); } catch (e) {}
return n ? '@' + esc(n) : esc(a.slice(0, 6) + '...' + a.slice(-4));
}
async function send(tx, evs) {
const text = await compose(tx, evs); if (!text) return;
if (!(await docstore.claim('tgproof:' + tx))) return; // another app copy already posted this sale
const body = { chat_id: process.env.TG_CHAT, text, parse_mode: 'HTML', disable_web_page_preview: true };
if (process.env.TG_PAY_TOPIC) body.message_thread_id = Number(process.env.TG_PAY_TOPIC);
const r = await fetch('https://api.telegram.org/bot' + process.env.TG_TOKEN + '/sendMessage', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(15000) });
const j = await r.json().catch(() => ({}));
if (!j.ok) console.error('tgproof send failed', r.status, String(j.description || '').slice(0, 120));
else console.log('tgproof posted', String(tx).slice(0, 12));
}
// the message text for one sale (also used to preview it without sending)
async function compose(tx, evs) {
const sb = evs.find(e => e.type === 'SpotBought'); if (!sb) return null;
const price = Number(sb.usdPrice) / 1e8; // the Chainlink POL/USD answer the contract priced this spot with
const usd = wei => price ? ' ($' + (Number(BigInt(wei) / 10n ** 12n) / 1e6 * price).toFixed(2) + ')' : '';
const contract = String(X.contract || '').toLowerCase();
const head = sb.kind === 2 ? '\u{1F381} The momentum fund gifted spot #' + sb.id + ' to ' + await who(sb.owner)
: sb.kind === 1 ? '\u{1F9FE} Spot #' + sb.id + ' bought for ' + await who(sb.owner) + (sb.payer !== sb.owner ? ' (refuel spot)' : '')
: '\u{1F9FE} Spot #' + sb.id + ' bought by ' + await who(sb.owner);
const lines = ['\u{1F7E3} <b>Downline Banners</b>', head + ' · $5 (' + pol(sb.valueWei) + ' POL)'];
let level = 0, house = 0n;
for (const e of evs) {
if (e.type !== 'Paid' && e.type !== 'PaymentFailed') continue;
if (e.role === ROLE.LEVEL) level++;
const toCompany = e.to === contract || e.role === ROLE.FEE_A || e.role === ROLE.FEE_B || e.role === ROLE.FUND
|| (X.feeWallets || []).includes(e.to);
if (e.type === 'PaymentFailed') { lines.push('⚠️ ' + (e.role === ROLE.SPONSOR ? 'Sponsor' : 'Line ' + level) + ' payment to ' + await who(e.to) + ' bounced, ' + pol(e.amount) + ' POL went to the momentum fund'); continue; }
if (toCompany) { house += BigInt(e.amount); continue; }
if (e.role === ROLE.SPONSOR) lines.push('\u{1F4B8} Sponsor: ' + pol(e.amount) + ' POL' + usd(e.amount) + ' → ' + await who(e.to));
else if (e.role === ROLE.LEVEL) lines.push('\u{1F4B8} Line ' + level + ' (spot #' + (sb.id - level) + '): ' + pol(e.amount) + ' POL' + usd(e.amount) + ' → ' + await who(e.to));
}
if (house > 0n) lines.push('\u{1F3E6} Company + momentum fund: ' + pol(house.toString()) + ' POL' + usd(house.toString()));
lines.push('· <a href="' + esc(X.explorer) + '/tx/' + esc(tx) + '">Verify on Polygonscan</a> · <a href="https://' + esc(X.site) + '/ledger">Live ledger</a>');
return lines.join('\n');
}
module.exports = { init, onEvent, send, compose, on };