From 87354e29b65b66caa414d47d65b5d2a3f434213d Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 13 Nov 2026 10:35:08 -0600 Subject: [PATCH] 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 --- docstore.js | 9 +++++- public/assets/common.js | 29 +++++++++++++++-- public/assets/contract.js | 23 ++++++++++++++ public/assets/ledger.js | 26 ++++++++++++++++ public/assets/line.css | 11 +++++++ public/board.html | 4 +-- public/contract.html | 26 ++++++++++++++++ public/how.html | 4 +-- public/index.html | 4 +-- public/join.html | 4 +-- public/ledger.html | 22 +++++++++++++ public/my.html | 4 +-- server.js | 43 ++++++++++++++++++++++++-- tgproof.js | 65 +++++++++++++++++++++++++++++++++++++++ 14 files changed, 259 insertions(+), 15 deletions(-) create mode 100644 public/assets/contract.js create mode 100644 public/assets/ledger.js create mode 100644 public/contract.html create mode 100644 public/ledger.html create mode 100644 tgproof.js diff --git a/docstore.js b/docstore.js index c3e9359..0bc07e4 100644 --- a/docstore.js +++ b/docstore.js @@ -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 }; diff --git a/public/assets/common.js b/public/assets/common.js index b254aba..c13539c 100644 --- a/public/assets/common.js +++ b/public/assets/common.js @@ -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 = ''; @@ -35,8 +35,9 @@ window.BL = (function () { f.className = 'bl-foot'; f.innerHTML = '

Part of the Crypto Team Build Network

' + '

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.

' - + '

How it works · Board · My Spots

'; + + '

How it works · Board · Live ledger · Contract proof · My Spots

'; 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 = '' + name + ' took spot #' + it.spotId + + (top ? '
' + (it.pays.length > 1 ? it.pays.length + ' members paid, ' : '') + (top.name ? '@' + esc(top.name) : 'a member') + ' got ' + fmtPol(top.wei, 2) + ' POL' : '
paid on-chain, $5'); + 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 }; })(); diff --git a/public/assets/contract.js b/public/assets/contract.js new file mode 100644 index 0000000..f67d30b --- /dev/null +++ b/public/assets/contract.js @@ -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 = '

' + esc(d.error) + '

'; return; } + const ex = d.explorer; + const addr = (a, label) => a ? '' + esc(a) + '' + (label ? ' ' + esc(label) + '' : '') : '-'; + const rows = [ + ['Contract', addr(d.address) + ' Verified source read the code'], + ['Network', esc(d.chain) + ' (chain ' + esc(d.chainId) + ')'], + ['Deployed', '' + esc(d.deployTx.slice(0, 18)) + '...' + (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 = '' + rows.map(r => '').join('') + '
' + r[0] + '' + r[1] + '
'; + $('split').innerHTML = 'ShareTo' + d.split.map(s => '' + esc(s.share) + '' + esc(s.to) + '').join(''); +})(); diff --git a/public/assets/ledger.js b/public/assets/ledger.js new file mode 100644 index 0000000..3047340 --- /dev/null +++ b/public/assets/ledger.js @@ -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) : '' + esc(short(addr)) + ''; + const usd = (wei, rate) => rate ? ' ($' + (Number(BigInt(wei) / 10n ** 12n) / 1e6 * rate).toFixed(2) + ')' : ''; + 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 => '
' + esc(x[1]) + '' + esc(x[0]) + '
').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 => '
  • ' + (p.failed ? 'Bounced (to the fund): ' : '') + (p.role === 'sponsor' ? 'Sponsor' : 'Line ' + p.level + ' (spot #' + (it.spotId - p.level) + ')') + + ': ' + fmtPol(p.wei) + ' POL' + usd(p.wei, it.usd) + ' to ' + who(p.name, p.to) + '
  • ').join(''); + return '
    Spot #' + it.spotId + ' ' + esc(KIND[it.kind] || '') + ' ' + who(it.ownerName, it.owner) + + ' $5 = ' + fmtPol(it.valueWei) + ' POL
    ' + esc(when) + '
    ' + + (pays ? '
      ' + pays + '
    ' : '

    No earlier spots or sponsor to pay yet.

    ') + + '

    Company + momentum fund: ' + fmtPol(it.houseWei) + ' POL' + usd(it.houseWei, it.usd) + + ' · Verify on Polygonscan

    '; + }).join('') : '

    No spot sales yet.

    '; + $('upd').textContent = 'Updated ' + new Date().toLocaleTimeString(); + } + await load(); setInterval(load, 20000); +})(); diff --git a/public/assets/line.css b/public/assets/line.css index e7b29bc..d4ea5be 100644 --- a/public/assets/line.css +++ b/public/assets/line.css @@ -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)}} diff --git a/public/board.html b/public/board.html index 240384a..256f48f 100644 --- a/public/board.html +++ b/public/board.html @@ -7,7 +7,7 @@ - +
    @@ -17,7 +17,7 @@

    The line so far

    - + diff --git a/public/contract.html b/public/contract.html new file mode 100644 index 0000000..b886837 --- /dev/null +++ b/public/contract.html @@ -0,0 +1,26 @@ + + + + +Contract proof | Downline Banners + + + + + + + +
    +

    Contract proof

    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. Live ledger

    +

    Reading the contract...

    +

    Where each $5 goes, in the same transaction

    +

    The contract holds nothing except the momentum fund, which can only buy spots. The split cannot be changed and there is no owner withdraw.

    +

    Check it yourself

      +
    1. Open the contract on Polygonscan (link above) and choose the Contract tab: the source code shows a green check for "verified".
    2. +
    3. Under Read Contract, compare owner, keeper, fee wallets and fund balance with this page.
    4. +
    5. Open any sale in the live ledger and look at its Logs: one SpotBought event, then one Paid event per payment.
    +
    + + + + diff --git a/public/how.html b/public/how.html index 385d4bf..5d9c2e3 100644 --- a/public/how.html +++ b/public/how.html @@ -7,7 +7,7 @@ - +
    @@ -24,7 +24,7 @@

    The momentum fund

    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.

    The rest of the network

    Open board slots show network sites such as InstantAdPay and LinkSpin. On InstantAdPay, ad credits buy advertising, not income.

    - + diff --git a/public/index.html b/public/index.html index 26acf84..eeeee6a 100644 --- a/public/index.html +++ b/public/index.html @@ -7,7 +7,7 @@ - +
    @@ -37,7 +37,7 @@
    - + diff --git a/public/join.html b/public/join.html index f533363..3e5c0d8 100644 --- a/public/join.html +++ b/public/join.html @@ -7,7 +7,7 @@ - +
    @@ -34,7 +34,7 @@
    - + diff --git a/public/ledger.html b/public/ledger.html new file mode 100644 index 0000000..458a50d --- /dev/null +++ b/public/ledger.html @@ -0,0 +1,22 @@ + + + + +Live ledger | Downline Banners + + + + + + + +
    +

    Live ledger

    Every spot sale and every payment, read from the Polygon blockchain. Each row links to the transaction so you can check it yourself. Contract proof

    +
    +

    Spot sales

    +

    Loading the ledger...

    +
    + + + + diff --git a/public/my.html b/public/my.html index fd3b11d..c979289 100644 --- a/public/my.html +++ b/public/my.html @@ -7,7 +7,7 @@ - +
    @@ -26,7 +26,7 @@
    - + diff --git a/server.js b/server.js index 6f05db9..e9cf6ee 100644 --- a/server.js +++ b/server.js @@ -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=
    ) ---- 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(); diff --git a/tgproof.js b/tgproof.js new file mode 100644 index 0000000..c554c16 --- /dev/null +++ b/tgproof.js @@ -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 => ({ '&': '&', '<': '<', '>': '>' }[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} Downline Banners', 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('· Verify on Polygonscan · Live ledger'); + return lines.join('\n'); +} +module.exports = { init, onEvent, send, compose, on };