# Telegram Bot — Brain On BNB AI # Buy alerts, burn alerts, price, whale tracking, captcha. # # This is the complete telegram-bot bundle as a single file, so it can be read in # one fetch. 12 files, 5907 lines. # Download as a zip: https://brainonbnb.com/code/telegram-bot.zip # Everything else: https://brainonbnb.com/code/index.txt # # No secrets are present: they are supplied at runtime through the environment. # MIT licensed. ============================================================================== === FILE: scripts/tg/tg-create-saga-pack.js ============================================================================== #!/usr/bin/env node // Build the "BOBAI Saga" Telegram sticker SET (weekend-vibes look, wise-master // meme captions) via the bobai-tg-bot worker. Mirrors tg-create-stickerset.js. // // Usage: node tg-create-saga-pack.js require('dotenv').config(); const fs = require('fs'); const path = require('path'); const BASE = (process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast') .replace(/\/broadcast$/, ''); const SECRET = process.env.BROADCAST_SECRET || ''; if (!SECRET) { console.error('Missing BROADCAST_SECRET in .env'); process.exit(1); } const OWNER_USER_ID = 7334850816; const PREFIX = 'bobai_saga_pack'; const TITLE = 'BOBAI Saga — May the Pump Be With You'; const STICKERS = [ ['saga-pump', '🧙'], ['saga-patience', '⏳'], ['saga-nosell', '✋'], ['saga-hodl', '✊'], ['saga-fear', '🧘'], ]; const HDR = { 'x-broadcast-secret': SECRET }; async function postJson(endpoint, body) { const r = await fetch(`${BASE}${endpoint}`, { method: 'POST', headers: { ...HDR, 'content-type': 'application/json' }, body: JSON.stringify(body), }); return r.json().catch(() => ({ ok: false, error: 'invalid json response' })); } async function uploadOne(filePath) { const buf = fs.readFileSync(filePath); const form = new FormData(); form.append('user_id', String(OWNER_USER_ID)); form.append('sticker', new Blob([buf], { type: 'video/webm' }), path.basename(filePath)); const r = await fetch(`${BASE}/stickerset/upload`, { method: 'POST', headers: HDR, body: form }); return r.json().catch(() => ({ ok: false, error: 'invalid json response' })); } (async () => { const me = await fetch(`${BASE}/stickerset/getbot`, { headers: HDR }).then(r => r.json()); if (!me.ok || !me.username) { console.error('[!] getbot failed:', JSON.stringify(me)); process.exit(1); } const setName = `${PREFIX}_by_${me.username}`; console.log(`[*] set name: ${setName}`); const items = STICKERS.map(([slug, emoji]) => { const fp = path.join(__dirname, 'stickers', 'out', `bobai-${slug}.webm`); if (!fs.existsSync(fp)) { console.error(`[!] missing: ${fp}`); process.exit(1); } return { slug, emoji, fp }; }); for (const it of items) { const j = await uploadOne(it.fp); if (!j.ok) { console.error(`[!] upload ${it.slug} failed:`, JSON.stringify(j)); process.exit(1); } it.file_id = j.result.file_id; console.log(`[+] uploaded ${it.slug} ${it.emoji} ${it.file_id.slice(0, 24)}…`); } const first = items[0]; const c = await postJson('/stickerset/create', { user_id: OWNER_USER_ID, name: setName, title: TITLE, file_id: first.file_id, emoji: first.emoji, }); if (!c.ok) { console.error('[!] create failed:', JSON.stringify(c)); process.exit(1); } console.log(`[+] set created (${first.slug} ${first.emoji})`); for (let i = 1; i < items.length; i++) { const it = items[i]; const a = await postJson('/stickerset/add', { user_id: OWNER_USER_ID, name: setName, file_id: it.file_id, emoji: it.emoji, }); if (!a.ok) { console.error(`[!] add ${it.slug} failed:`, JSON.stringify(a)); process.exit(1); } console.log(`[+] added ${it.slug} ${it.emoji}`); await new Promise(r => setTimeout(r, 300)); } console.log(`\n✅ Done.\nInstall: https://t.me/addstickers/${setName}`); })(); ============================================================================== === FILE: scripts/tg/tg-create-stickerset.js ============================================================================== #!/usr/bin/env node // Build a Telegram sticker SET from local .webm files via the bobai-tg-bot worker. // // Usage: // node tg-create-stickerset.js // // Reads the config block below — owner user_id, set prefix, title, and // (slug, emoji) pairs — uploads each webm via the worker, creates the set // with the first sticker, then adds the remaining nine. Prints the // t.me/addstickers/ install link on success. require('dotenv').config(); const fs = require('fs'); const path = require('path'); const BASE = (process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast') .replace(/\/broadcast$/, ''); const SECRET = process.env.BROADCAST_SECRET || ''; if (!SECRET) { console.error('Missing BROADCAST_SECRET in .env'); process.exit(1); } const OWNER_USER_ID = 7334850816; const PREFIX = 'bobai_meme_pack'; const TITLE = 'BOBAI Meme Pack'; const STICKERS = [ ['thunder-buy', '⚡'], ['kraken-buy', '🐙'], ['supernova-burn', '🔥'], ['rocket', '🚀'], ['diamond', '💎'], ['laser', '👁️'], ['bull', '🐂'], ['hodl', '✊'], ['gigabrain', '🧠'], ['wagmi', '❤️'], ]; const HDR = { 'x-broadcast-secret': SECRET }; async function postJson(endpoint, body) { const r = await fetch(`${BASE}${endpoint}`, { method: 'POST', headers: { ...HDR, 'content-type': 'application/json' }, body: JSON.stringify(body), }); return r.json().catch(() => ({ ok: false, error: 'invalid json response' })); } async function uploadOne(filePath) { const buf = fs.readFileSync(filePath); const form = new FormData(); form.append('user_id', String(OWNER_USER_ID)); form.append('sticker', new Blob([buf], { type: 'video/webm' }), path.basename(filePath)); const r = await fetch(`${BASE}/stickerset/upload`, { method: 'POST', headers: HDR, body: form }); return r.json().catch(() => ({ ok: false, error: 'invalid json response' })); } (async () => { // 1. resolve bot username for set-name suffix const me = await fetch(`${BASE}/stickerset/getbot`, { headers: HDR }).then(r => r.json()); if (!me.ok || !me.username) { console.error('[!] getbot failed:', JSON.stringify(me)); process.exit(1); } const setName = `${PREFIX}_by_${me.username}`; console.log(`[*] set name: ${setName}`); // 2. verify all files exist before uploading anything const items = STICKERS.map(([slug, emoji]) => { const fp = path.join(__dirname, 'stickers', 'out', `bobai-${slug}.webm`); if (!fs.existsSync(fp)) { console.error(`[!] missing: ${fp}`); process.exit(1); } return { slug, emoji, fp }; }); // 3. upload all → collect file_ids for (const it of items) { const j = await uploadOne(it.fp); if (!j.ok) { console.error(`[!] upload ${it.slug} failed:`, JSON.stringify(j)); process.exit(1); } it.file_id = j.result.file_id; console.log(`[+] uploaded ${it.slug} ${it.emoji} ${it.file_id.slice(0, 24)}…`); } // 4. create set with first sticker const first = items[0]; const c = await postJson('/stickerset/create', { user_id: OWNER_USER_ID, name: setName, title: TITLE, file_id: first.file_id, emoji: first.emoji, }); if (!c.ok) { console.error('[!] create failed:', JSON.stringify(c)); process.exit(1); } console.log(`[+] set created (${first.slug} ${first.emoji})`); // 5. add the rest sequentially (small delay to stay friendly to TG rate limits) for (let i = 1; i < items.length; i++) { const it = items[i]; const a = await postJson('/stickerset/add', { user_id: OWNER_USER_ID, name: setName, file_id: it.file_id, emoji: it.emoji, }); if (!a.ok) { console.error(`[!] add ${it.slug} failed:`, JSON.stringify(a)); process.exit(1); } console.log(`[+] added ${it.slug} ${it.emoji}`); await new Promise(r => setTimeout(r, 300)); } console.log(`\n✅ Done.\nInstall: https://t.me/addstickers/${setName}`); })(); ============================================================================== === FILE: scripts/tg/tg-delete-message.js ============================================================================== #!/usr/bin/env node // Delete a message (e.g. a preview sticker) via the bobai-tg-bot Worker. // // Usage: // node tg-delete-message.js // // POSTs to the worker's /deletemessage endpoint (auth: BROADCAST_SECRET); the // worker calls Telegram deleteMessage with its own BOT_TOKEN. Note: Telegram only // lets bots delete messages younger than 48h. require('dotenv').config(); const BASE = (process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast') .replace(/\/broadcast$/, ''); const SECRET = process.env.BROADCAST_SECRET || ''; const [chatId, messageId] = process.argv.slice(2); if (!SECRET) { console.error('Missing BROADCAST_SECRET in .env'); process.exit(1); } if (!chatId || !messageId) { console.error('Usage: node tg-delete-message.js '); process.exit(1); } (async () => { const res = await fetch(`${BASE}/deletemessage`, { method: 'POST', headers: { 'x-broadcast-secret': SECRET, 'content-type': 'application/json' }, body: JSON.stringify({ chat_id: String(chatId), message_id: Number(messageId) }), }); const json = await res.json().catch(() => ({})); if (res.ok && json.ok) { console.log('🗑️ deleted message', messageId); } else { console.error('❌ failed:', res.status, JSON.stringify(json)); process.exit(1); } })(); ============================================================================== === FILE: scripts/tg/tg-extend-stickerset.js ============================================================================== #!/usr/bin/env node // Append additional stickers to an EXISTING Telegram sticker set via the // bobai-tg-bot worker. Mirrors tg-create-stickerset.js but skips the // /stickerset/create step — uploads each webm, then /stickerset/add. // // Usage: // node tg-extend-stickerset.js require('dotenv').config(); const fs = require('fs'); const path = require('path'); const BASE = (process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast') .replace(/\/broadcast$/, ''); const SECRET = process.env.BROADCAST_SECRET || ''; if (!SECRET) { console.error('Missing BROADCAST_SECRET in .env'); process.exit(1); } const OWNER_USER_ID = 7334850816; const SET_NAME = 'bobai_meme_pack_by_bobai_official_bot'; const STICKERS = [ ['gm', '☀️'], ['pump', '📈'], ['dip', '🩸'], ['builder', '🧱'], ['shield', '🛡️'], ]; const HDR = { 'x-broadcast-secret': SECRET }; async function postJson(endpoint, body) { const r = await fetch(`${BASE}${endpoint}`, { method: 'POST', headers: { ...HDR, 'content-type': 'application/json' }, body: JSON.stringify(body), }); return r.json().catch(() => ({ ok: false, error: 'invalid json response' })); } async function uploadOne(filePath) { const buf = fs.readFileSync(filePath); const form = new FormData(); form.append('user_id', String(OWNER_USER_ID)); form.append('sticker', new Blob([buf], { type: 'video/webm' }), path.basename(filePath)); const r = await fetch(`${BASE}/stickerset/upload`, { method: 'POST', headers: HDR, body: form }); return r.json().catch(() => ({ ok: false, error: 'invalid json response' })); } (async () => { const items = STICKERS.map(([slug, emoji]) => { const fp = path.join(__dirname, 'stickers', 'out', `bobai-${slug}.webm`); if (!fs.existsSync(fp)) { console.error(`[!] missing: ${fp}`); process.exit(1); } return { slug, emoji, fp }; }); for (const it of items) { const j = await uploadOne(it.fp); if (!j.ok) { console.error(`[!] upload ${it.slug} failed:`, JSON.stringify(j)); process.exit(1); } it.file_id = j.result.file_id; console.log(`[+] uploaded ${it.slug} ${it.emoji} ${it.file_id.slice(0, 24)}…`); } for (const it of items) { const a = await postJson('/stickerset/add', { user_id: OWNER_USER_ID, name: SET_NAME, file_id: it.file_id, emoji: it.emoji, }); if (!a.ok) { console.error(`[!] add ${it.slug} failed:`, JSON.stringify(a)); process.exit(1); } console.log(`[+] added ${it.slug} ${it.emoji}`); await new Promise(r => setTimeout(r, 300)); } console.log(`\n✅ Done.\nSet: https://t.me/addstickers/${SET_NAME}`); })(); ============================================================================== === FILE: scripts/tg/tg-get-media.js ============================================================================== #!/usr/bin/env node // Download the last reference media the owner sent the bot in private chat. // // Usage: // node tg-get-media.js [output-path] // // Architecture (mirrors tg-send-sticker.js): the worker webhook stores the last // owner-sent file (animation/video/document/photo/sticker) in KV. This script // hits GET /media/download (auth'd with BROADCAST_SECRET) and saves the bytes. // BOT_TOKEN never leaves Cloudflare. // // .env requires: // BROADCAST_SECRET — shared secret between this script and the worker // BROADCAST_URL — optional; defaults to the production worker origin require('dotenv').config(); const fs = require('fs'); const path = require('path'); const BASE = (process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast') .replace(/\/broadcast$/, ''); const SECRET = process.env.BROADCAST_SECRET || ''; if (!SECRET) { console.error('Missing BROADCAST_SECRET in .env'); process.exit(1); } const outArg = process.argv[2]; (async () => { const metaRes = await fetch(`${BASE}/media/last`, { headers: { 'x-broadcast-secret': SECRET } }); const meta = await metaRes.json().catch(() => ({})); if (!metaRes.ok || !meta.ok) { console.error('❌ no media available:', metaRes.status, JSON.stringify(meta)); process.exit(1); } console.log(`📥 last media: type=${meta.type} name=${meta.name} ts=${new Date(meta.ts).toISOString()}`); const res = await fetch(`${BASE}/media/download`, { headers: { 'x-broadcast-secret': SECRET } }); if (!res.ok) { const err = await res.text().catch(() => ''); console.error('❌ download failed:', res.status, err); process.exit(1); } const name = decodeURIComponent(res.headers.get('x-media-name') || meta.name || 'ref.bin'); const out = outArg || path.join('stickers', 'incoming', name); fs.mkdirSync(path.dirname(out), { recursive: true }); fs.writeFileSync(out, Buffer.from(await res.arrayBuffer())); console.log(`✅ saved → ${out} (${fs.statSync(out).size} bytes)`); })(); ============================================================================== === FILE: scripts/tg/tg-photo.js ============================================================================== #!/usr/bin/env node // Send an image announcement (report card + caption) to the BOBAI Telegram group. // // Usage: // node tg-photo.js --photo --caption-file [--internal] [--no-brain] // node tg-photo.js --photo --caption "" // // Architecture: like tg-update.js, this never talks to Telegram directly. It POSTs a // multipart form to the bobai-tg-bot Worker's /broadcastphoto endpoint, authenticated // with BROADCAST_SECRET. The worker forwards it to sendPhoto with its own BOT_TOKEN, // which never leaves Cloudflare. // // --internal targets the private BOBAI Intern chat — use it to preview before the // public group sees anything. require('dotenv').config(); const fs = require('fs'); const path = require('path'); const BASE = (process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast') .replace(/\/broadcast$/, ''); const BROADCAST_SECRET = process.env.BROADCAST_SECRET || ''; if (!BROADCAST_SECRET) { console.error('Missing BROADCAST_SECRET in .env'); process.exit(1); } const args = process.argv.slice(2); const flag = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : null; }; const photoPath = flag('--photo'); const captionFile = flag('--caption-file'); const captionArg = flag('--caption'); const internal = args.includes('--internal'); const noBrain = args.includes('--no-brain'); if (!photoPath) { console.error('Usage: node tg-photo.js --photo [--caption-file | --caption ""] [--internal] [--no-brain]'); process.exit(1); } if (!fs.existsSync(photoPath)) { console.error('Photo not found: ' + photoPath); process.exit(1); } const caption = captionFile ? fs.readFileSync(captionFile, 'utf8').trim() : (captionArg || '').trim(); if (caption.length > 1024) { console.error(`Caption too long: ${caption.length}/1024 characters (Telegram limit). Shorten it.`); process.exit(1); } (async () => { const bytes = fs.readFileSync(photoPath); const form = new FormData(); form.append('photo', new Blob([bytes], { type: 'image/png' }), path.basename(photoPath)); if (caption) form.append('caption', caption); if (internal) form.append('target', 'internal'); if (noBrain) form.append('prefixBrain', '0'); const r = await fetch(BASE + '/broadcastphoto', { method: 'POST', headers: { 'x-broadcast-secret': BROADCAST_SECRET }, body: form, }); const j = await r.json().catch(() => ({})); if (!r.ok || !j.ok) { console.error('Failed:', r.status, JSON.stringify(j)); process.exit(1); } console.log(`Sent to ${internal ? 'INTERNAL' : 'PUBLIC group'}: message_id = ${j.message_id}` + ` (${(bytes.length / 1024).toFixed(0)} KB, caption ${caption.length}/1024)`); })().catch((err) => { console.error('Failed:', err.message); process.exit(1); }); ============================================================================== === FILE: scripts/tg/tg-saga-add-rest.js ============================================================================== #!/usr/bin/env node // One-off: add the remaining 4 saga stickers to the freshly created set // (createNewStickerSet → addStickerToSet race needs retries). require('dotenv').config(); const fs = require('fs'); const path = require('path'); const BASE = (process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast') .replace(/\/broadcast$/, ''); const SECRET = process.env.BROADCAST_SECRET || ''; const OWNER_USER_ID = 7334850816; const NAME = 'bobai_saga_pack_by_bobai_official_bot'; // slugs+emojis via CLI pairs (node tg-saga-add-rest.js ...), // falls back to the original batch-2 list. const argPairs = []; for (let i = 2; i + 1 < process.argv.length; i += 2) { argPairs.push([process.argv[i], process.argv[i + 1]]); } const STICKERS = argPairs.length ? argPairs : [ ['saga-patience', '⏳'], ['saga-nosell', '✋'], ['saga-hodl', '✊'], ['saga-fear', '🧘'], ]; const HDR = { 'x-broadcast-secret': SECRET }; async function uploadOne(filePath) { const buf = fs.readFileSync(filePath); const form = new FormData(); form.append('user_id', String(OWNER_USER_ID)); form.append('sticker', new Blob([buf], { type: 'video/webm' }), path.basename(filePath)); const r = await fetch(`${BASE}/stickerset/upload`, { method: 'POST', headers: HDR, body: form }); return r.json(); } (async () => { for (const [slug, emoji] of STICKERS) { const fp = path.join(__dirname, 'stickers', 'out', `bobai-${slug}.webm`); const up = await uploadOne(fp); if (!up.ok) { console.error(`[!] upload ${slug}:`, JSON.stringify(up)); process.exit(1); } let done = false; for (let att = 1; att <= 6 && !done; att++) { const r = await fetch(`${BASE}/stickerset/add`, { method: 'POST', headers: { ...HDR, 'content-type': 'application/json' }, body: JSON.stringify({ user_id: OWNER_USER_ID, name: NAME, file_id: up.result.file_id, emoji }), }).then(x => x.json()); if (r.ok) { console.log(`[+] added ${slug} ${emoji}`); done = true; break; } console.log(`[~] ${slug} attempt ${att}: ${r.description || JSON.stringify(r)} — retrying`); await new Promise(res => setTimeout(res, 4000)); } if (!done) { console.error(`[!] gave up on ${slug}`); process.exit(1); } } const g = await fetch(`${BASE}/stickerset/get?name=${NAME}`, { headers: HDR }).then(x => x.json()); const count = g.result?.stickers?.length ?? '?'; console.log(`\n✅ set now has ${count} stickers\nInstall: https://t.me/addstickers/${NAME}`); })(); ============================================================================== === FILE: scripts/tg/tg-saga-replace.js ============================================================================== #!/usr/bin/env node // Replace one sticker in the live saga set (same position) with a fresh webm. // Usage: node tg-saga-replace.js require('dotenv').config(); const fs = require('fs'); const path = require('path'); const BASE = (process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast') .replace(/\/broadcast$/, ''); const SECRET = process.env.BROADCAST_SECRET || ''; const OWNER_USER_ID = 7334850816; const NAME = 'bobai_saga_pack_by_bobai_official_bot'; const HDR = { 'x-broadcast-secret': SECRET }; const [slug, emoji] = process.argv.slice(2); if (!slug || !emoji) { console.error('Usage: node tg-saga-replace.js '); process.exit(1); } (async () => { const g = await fetch(`${BASE}/stickerset/get?name=${NAME}`, { headers: HDR }).then(x => x.json()); if (!g.ok) { console.error('[!] get set failed:', JSON.stringify(g).slice(0, 300)); process.exit(1); } const old = g.result.stickers.find(s => (s.emoji || '') === emoji); if (!old) { console.error(`[!] no sticker with emoji ${emoji} in set`); process.exit(1); } const buf = fs.readFileSync(path.join(__dirname, 'stickers', 'out', `bobai-${slug}.webm`)); const form = new FormData(); form.append('user_id', String(OWNER_USER_ID)); form.append('sticker', new Blob([buf], { type: 'video/webm' }), `${slug}.webm`); const up = await fetch(`${BASE}/stickerset/upload`, { method: 'POST', headers: HDR, body: form }).then(x => x.json()); if (!up.ok) { console.error('[!] upload failed:', JSON.stringify(up)); process.exit(1); } const r = await fetch(`${BASE}/stickerset/replace`, { method: 'POST', headers: { ...HDR, 'content-type': 'application/json' }, body: JSON.stringify({ user_id: OWNER_USER_ID, name: NAME, old_sticker: old.file_id, file_id: up.result.file_id, emoji }), }).then(x => x.json()); if (!r.ok) { console.error('[!] replace failed:', JSON.stringify(r)); process.exit(1); } console.log(`✅ replaced ${emoji} ${slug} in ${NAME}`); })(); ============================================================================== === FILE: scripts/tg/tg-send-sticker.js ============================================================================== #!/usr/bin/env node // Send an animated .webm sticker via the bobai-tg-bot Cloudflare Worker. // // Usage: // node tg-send-sticker.js // // Architecture (mirrors tg-update.js): this script does NOT talk to Telegram // directly. It POSTs the file as multipart/form-data to the worker's /sendsticker // endpoint, authenticated with the shared BROADCAST_SECRET. The worker forwards it // to Telegram sendSticker using its own BOT_TOKEN (a CF secret that never leaves CF). // // .env requires: // BROADCAST_SECRET — shared secret between this script and the worker // BROADCAST_URL — optional; defaults to the production worker origin require('dotenv').config(); const fs = require('fs'); const BASE = (process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast') .replace(/\/broadcast$/, ''); const SECRET = process.env.BROADCAST_SECRET || ''; const [chatId, filePath] = process.argv.slice(2); if (!SECRET) { console.error('Missing BROADCAST_SECRET in .env'); process.exit(1); } if (!chatId) { console.error('Usage: node tg-send-sticker.js '); process.exit(1); } if (!filePath || !fs.existsSync(filePath)) { console.error('webm file not found:', filePath); process.exit(1); } (async () => { const buf = fs.readFileSync(filePath); const form = new FormData(); form.append('chat_id', String(chatId)); form.append('sticker', new Blob([buf], { type: 'video/webm' }), 'sticker.webm'); const res = await fetch(`${BASE}/sendsticker`, { method: 'POST', headers: { 'x-broadcast-secret': SECRET }, body: form, }); const json = await res.json().catch(() => ({})); if (res.ok && json.ok) { console.log('✅ sent — message_id', json.result?.message_id); } else { console.error('❌ failed:', res.status, JSON.stringify(json)); process.exit(1); } })(); ============================================================================== === FILE: scripts/tg/tg-update.js ============================================================================== #!/usr/bin/env node // Send a "brain update" announcement to the BOBAI Telegram group. // // Usage: // node tg-update.js "" // node tg-update.js --file (preferred for multi-line) // // Architecture: // This script does NOT talk to Telegram directly. It POSTs the announcement to // the bobai-tg-bot Cloudflare Worker's /broadcast endpoint, authenticated with a // shared BROADCAST_SECRET. The worker then sends two messages via its own // BOT_TOKEN (a CF secret that never leaves Cloudflare): // 1) A lone 🧠 — Telegram renders 1-3 emoji-only messages as JUMBO, which // acts as the visual "this is an update" header for every announcement. // 2) The actual text with parse_mode=HTML. // // .env requires: // BROADCAST_SECRET — shared secret between this script and the worker // (set on CF with: npx wrangler secret put BROADCAST_SECRET // --config worker-tg-bot/wrangler.toml) // BROADCAST_URL — optional override; defaults to the production worker URL require('dotenv').config(); const BROADCAST_URL = process.env.BROADCAST_URL || 'https://bobai-tg-bot.bobbuildonbnb.workers.dev/broadcast'; const BROADCAST_SECRET = process.env.BROADCAST_SECRET || ''; if (!BROADCAST_SECRET) { console.error('Missing BROADCAST_SECRET in .env'); process.exit(1); } const args = process.argv.slice(2); let text; const fileIdx = args.indexOf('--file'); if (fileIdx >= 0) { const path = args[fileIdx + 1]; if (!path) { console.error('--file requires a path'); process.exit(1); } text = require('fs').readFileSync(path, 'utf8').trim(); } else { text = args.join(' ').trim(); } if (!text) { console.error('Usage: node tg-update.js "" | node tg-update.js --file '); process.exit(1); } (async () => { const r = await fetch(BROADCAST_URL, { method: 'POST', headers: { 'content-type': 'application/json', 'x-broadcast-secret': BROADCAST_SECRET, }, body: JSON.stringify({ text, prefixBrain: true }), }); const j = await r.json().catch(() => ({})); if (!r.ok || !j.ok) { console.error('Failed:', r.status, JSON.stringify(j)); process.exit(1); } console.log('Sent: message_id =', j.message_id); })().catch(err => { console.error('Failed:', err.message); process.exit(1); }); ============================================================================== === FILE: worker-tg-bot/index.js ============================================================================== // BOBAI Telegram Bot — Cloudflare Worker // Combined: Buy Alert Bot + Burn Alert Bot + Anti-Spam Guard Bot // Runs 24/7 via cron (every minute) + Telegram Webhook let TG_BOT_TOKEN = ''; let TG_INTERNAL_CHAT_ID = ''; // The operator's own private chat with this bot (a private chat's id is the // user's id). Target 'operator' on /broadcast goes here and nowhere else // (2026-09-08: "nur hier für mich und niemand anderem"; the trading agent // that used it was retired 2026-09-10). The same id guards the // reference-media pickup below. const OPERATOR_CHAT_ID = '7334850816'; const TG_CHAT_ID = '-1003791636543'; const BOBAI_PAIR = '0x6eadd4cb786898b34929444988380ed0cc6fd9a6'; const BOBAI_TOKEN = '0x245c386dcfed896f5c346107596141e5edcbffff'; const DEAD = '0x000000000000000000000000000000000000dead'; // NFT Buy Drops — auto-minted to buyer wallets on every BOBAI buy ≥ $100 const NFT_CONTRACT = '0xd56226b3b8297a57f4361fca28aa43babdc9789d'; // idx → [emoji, label, threshold USD] const NFT_TIERS = [ ['💰', 'NICE', 100], ['💎', 'BIG', 150], ['🚀', 'HUGE', 250], ['🐋', 'WHALE', 500], ['⚡️', 'THUNDER', 1000], ['🦑', 'KRAKEN', 2500], ]; // idx → [emoji, label] — matches drop matrix in worker-nft-mint // 7-step rarity gradient (cool → warm): 🤍 🩵 💙 💜 🩷 ❤️ 💛 const NFT_RARITIES = [ ['🤍', 'Common'], ['🩵', 'Uncommon'], ['💙', 'Rare'], ['💜', 'Mythical'], ['🩷', 'Legendary'], ['❤️', 'Ancient'], ['💛', 'Immortal'], ]; // Fetch via Pages route (brainonbnb.com), NOT bobai-nft-mint.workers.dev — // worker-to-worker on the same *.workers.dev subdomain 404s (CF loopback). const NFT_STATE_URL = 'https://brainonbnb.com/api/nft/state'; const NFT_DASHBOARD_URL = 'https://brainonbnb.com/nft'; const CAPTCHA_TIMEOUT = 60; // PancakeSwap V2 Swap event topic. In this pair BOBAI is token0, WBNB is token1, // so a BUY = WBNB in (amount1In > 0) & BOBAI out (amount0Out > 0). const SWAP_TOPIC = '0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822'; const TAXSWAP_TOPIC = '0x4ecbb010c79223623fc0a5fd2d955ed432e0d426d06c525f5a1bf8e344753bae'; // the token's SwapTax log (data: the BOBAI swapped) // ERC20 Transfer(address indexed from, address indexed to, uint256 value) const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; // GeckoTerminal API const GECKO_POOL_URL = `https://api.geckoterminal.com/api/v2/networks/bsc/pools/${BOBAI_PAIR}`; // Worldcup tipgame (Supabase — public anon key, RLS-protected) const WORLDCUP_URL = 'https://brainonbnb.com/worldcup'; const SUPABASE_URL = 'https://aerffjhdsbxpvuulkryr.supabase.co'; const SUPABASE_ANON_KEY = 'sb_publishable_ne0MFzyCQb6MvFWur2X-Vw_vG9JH76_'; // Multiple BSC RPC endpoints for burn queries const RPC_ENDPOINTS = [ 'https://bsc-dataseed1.binance.org', 'https://bsc-dataseed2.binance.org', 'https://bsc-dataseed3.binance.org', 'https://bsc-dataseed4.binance.org', 'https://bsc-dataseed1.bnbchain.org', ]; // getLogs-capable endpoints. The Binance dataseed nodes above reject eth_getLogs // ("limit exceeded"), so on-chain buy detection uses these instead. A browser-like // User-Agent is required (publicnode blocks default/bot user-agents). // 2026-06-19: free publicnode/pokt endpoints tightened getLogs to <100 blocks // ("Archive requests require a personal token"). Keyed primary via NodeReal // (env.BSC_RPC_KEYED_URL) prepended at call time; freebies kept as fallback. const LOGS_RPC_ENDPOINTS = [ 'https://bsc-rpc.publicnode.com', 'https://bsc-pokt.nodies.app', 'https://bsc.publicnode.com', ]; const LOGS_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'; // URL_2 (Allnodes/PublicNode personal token) is asked first, URL (NodeReal // MegaNode) second. Both answer the same query identically; the order only // decides whose meter runs. NodeReal bills per request against a monthly CU // quota that dropped below 20% on 2026-08-23, the PublicNode token does not // meter at all, so the metered provider is kept as the reserve rather than // spent on routine polling. If URL_2 fails for any reason, NodeReal serves the // call exactly as before. function keyedEndpoints(env) { return env ? [env.BSC_RPC_KEYED_URL_2, env.BSC_RPC_KEYED_URL].filter(Boolean) : []; } // HOW FAR BACK THE ALERT SCANS LOOK (2026-09-18). It was 300 blocks under a // comment that took a block for 0.75-1.5 s; BSC clears one in ~0.45 s, so the // window was 135 seconds over a one-minute cron with no remembered last block: // two missed ticks and a buy or a whale move was gone for good (the minter // keeps `last_block` and minted all the same — an NFT without an alert). 1,600 // blocks is about twelve minutes, the same reach as a ledger bucket; the // posted-tx sets keep a transaction from being told twice. const SCAN_BLOCKS = 1600; // Free endpoints cap getLogs at ~50 blocks since 2026-06-19. If the keyed // providers fail and the free ones refuse the full range, the range is cut to // the most recent ~50 blocks — counted from the HEAD, which is read, not // guessed from the start of the range. Strictly better than silence. Pure. const FREE_LOGS_BLOCKS = 50; export function narrowedFrom(fromBlock, latest, maxBlocks = FREE_LOGS_BLOCKS) { const from = parseInt(fromBlock, 16); return '0x' + Math.max(0, from, latest - maxBlocks).toString(16); } // Photo file_ids (uploaded once via bot, reusable) const PHOTO_WELCOME = 'AgACAgQAAyEGAATh_8g_AAPfadI1EORIV-4JDTPKnQmo3il3NPsAAkYNaxtDCplSMrzv51Lm4QEBAAMCAAN4AAM7BA'; const PHOTO_BIGBUY = 'AgACAgQAAyEGAATh_8g_AAPgadI1EEm5Qa4VhE6mqWf0m6PuFMYAAkcNaxtDCplSLzBgWf5z1mMBAAMCAAN4AAM7BA'; const PHOTO_BURN = 'AgACAgQAAyEGAATh_8g_AAIB0mnWDmHKwNjMTlDUC3WLJRO30ii_AAKBDGsbUeywUgNqPnsGFkssAQADAgADeAADOwQ'; // Known bot/system wallets to ignore in buy alerts const IGNORED_WALLETS = new Set([ '0xdefc0e900dfc83e207902cf22265ae63f94c01ce', // buyback bot '0x15ba17075ef5e0736292b030e3715d9100fe3d38', // dev buyback bot '0xbfaa69233741924ed5b9d5daa9b4bf7b84567f0a', // DeFi agent (a third of its fees buys $BOBAI, since 14.10.) '0xbfb4b49787ce948c1ee304f6c197a0e8b038ddb2', // NFT relayer (tops wallets up to 808.41) ]); // A NAME SOMEBODY ELSE CHOSE IS TEXT, NOT MARKUP (2026-09-18). Posts go out // with parse_mode HTML; a joining member's first name, or a leaderboard // username, went into them as it stood. A name with a `<` made Telegram refuse // the captcha post AFTER the member had been muted — no question to answer, // kicked after 60 seconds — and a name that is an was a clickable link // in the public chat, under the bot's name. Pure; pinned by smoke-whale. export function escHtml(s) { return String(s == null ? '' : s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } // Shown as a name: escaped, and no longer than a name is (Telegram allows 64). export function shownName(s) { const t = String(s == null ? '' : s).trim(); return escHtml(t.length > 64 ? t.slice(0, 64) + '…' : t) || 'User'; } // ==================== TELEGRAM API ==================== // A deadline on every call (2026-10-07): one hung request held the every-minute tick past the next one, which then // read posted_txs / last_burned before the first had written them. Telegram's own 5xx pages are HTML: read as // {ok:false} instead of throwing out of the caller. async function tg(method, body) { let j; try { const res = await fetch(`https://api.telegram.org/bot${TG_BOT_TOKEN}/${method}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(10000), }); j = await res.json().catch(() => ({ ok: false, error_code: res.status, description: `HTTP ${res.status}, not JSON` })); } catch (e) { j = { ok: false, description: e?.name === 'TimeoutError' ? 'no answer within 10 s' : String(e?.message || e).slice(0, 120) }; } if (j && j.ok === false && /^send/.test(method)) await noteSendError(method, body, j); else if (j && j.ok && /^send/.test(method) && SEND_ERR_SET && OUR_CHATS.has(String(body?.chat_id ?? ''))) await clearSendError(); return j; } // NOBODY SAW A BOT THAT COULD NOT POST (2026-10-07): a kicked or muted bot, a dead photo id, showed only in the // console; /health said "can post" from the token alone. A failed send is written down (a KV write only when // something failed) and /health serves it; the morning check turns red on a lasting cause. const SEND_LASTING = /forbidden|kicked|not enough rights|chat not found|bot was blocked|unauthorized|have no rights|need administrator/i; async function noteSendError(method, body, j) { try { if (!WHALE_ENV || !WHALE_ENV.KV) return; // LASTING ONLY WHERE IT MATTERS (2026-10-09 review): a user who blocked the bot refuses its private reply with the // same "bot was blocked" — that is his choice, not a bot that cannot post. Only the group, the operator's and the internal chat count. const chat = String(body?.chat_id ?? ''), ours = OUR_CHATS.has(chat); const rec = { at: new Date().toISOString(), method, chat: chat.slice(-6), ours, code: j.error_code ?? null, description: String(j.description || '').slice(0, 160), lasting: ours && SEND_LASTING.test(String(j.description || '')) }; if (!ours && SEND_LASTING.test(rec.description)) { console.error('[TG SEND REFUSED, other chat]', method, rec.code, rec.description); return; } // not written: it must not cover a real one console.error('[TG SEND FAILED]', method, rec.code, rec.description); await WHALE_ENV.KV.put('last_send_error', JSON.stringify(rec)); SEND_ERR_SET = true; } catch { /* the trace itself must never break a send */ } } // a good send to the group or the operator after a failure clears it (this isolate wrote it; otherwise it ages out in 24 h) const OUR_CHATS = { has: (c) => c === TG_CHAT_ID || c === OPERATOR_CHAT_ID || (!!WHALE_ENV?.TG_INTERNAL_CHAT_ID && c === String(WHALE_ENV.TG_INTERNAL_CHAT_ID)) }; // group, operator, internal chat let SEND_ERR_SET = false; async function clearSendError() { SEND_ERR_SET = false; try { if (WHALE_ENV && WHALE_ENV.KV) await WHALE_ENV.KV.delete('last_send_error'); } catch { /* never break a send */ } } // ==================== RPC HELPERS ==================== async function rpcCall(method, params) { for (const rpc of RPC_ENDPOINTS) { try { const res = await fetch(rpc, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), signal: AbortSignal.timeout(6000), }); const data = await res.json(); if (data.result !== undefined && data.result !== null) return data.result; } catch {} } return null; } async function tryGetLogs(rpc, fromBlock, address, topic, tag, toBlock = 'latest') { const params = [{ address, topics: [topic], fromBlock, toBlock }]; try { const res = await fetch(rpc, { method: 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': LOGS_UA }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getLogs', params }), signal: AbortSignal.timeout(8000), }); if (!res.ok) return null; const data = await res.json(); if (!Array.isArray(data.result)) return null; console.log(`[${tag}] getLogs ok via`, rpc, '-', data.result.length, 'logs'); return data.result; } catch (e) { console.error(`[${tag}] getLogs error via`, rpc, '-', e.message || e); return null; } } // eth_getLogs, keyed first, free as the fallback. Every endpoint is asked for // the FULL range first — a free one that still serves it is worth more than a // cut. Only then is the range cut to the free endpoints' cap. A caller that // books what it reads as complete (the swap ledger) passes narrow:false and // gets null instead of a part: a gap it re-reads, not a day counted short. async function getLogsKeyedThenFree(fromBlock, address, topic, tag, env, { narrow = true } = {}) { for (const rpc of keyedEndpoints(env)) { const r = await tryGetLogs(rpc, fromBlock, address, topic, tag); if (r !== null) return r; } for (const rpc of LOGS_RPC_ENDPOINTS) { const r = await tryGetLogs(rpc, fromBlock, address, topic, tag + '-free'); if (r !== null) return r; } if (!narrow) return null; const latestHex = await rpcCall('eth_blockNumber', []); if (!latestHex) return null; const latest = parseInt(latestHex, 16); const cut = narrowedFrom(fromBlock, latest); if (parseInt(cut, 16) <= parseInt(fromBlock, 16)) return null; // the full range was already that small return walkDegraded(fromBlock, latest, address, topic, tag, env); } // A DEGRADED READ WALKS ON FROM WHERE IT STOPPED (2026-10-09). The cut above read only the newest 50 blocks: about // 22 seconds of chain under a one-minute cron, so on a degraded hour roughly two buys in three were never seen. Now a // cursor per scan (KV `logs_cursor:`, written only on a degraded tick — a healthy tick writes nothing) remembers // the last block read, and each degraded tick reads up to DEGRADED_WINDOWS windows of 50 blocks from there: 400 // blocks a tick against the ~133 the chain makes in a minute, so it catches up instead of skipping. The walk stops at // the first window no endpoint serves; the cursor stays before it. Never further back than the caller's own reach // (`fromBlock`); the posted-tx sets keep a transaction from being told twice. Pure part exported for the pins. const DEGRADED_WINDOWS = 8; export function degradedWindows(fromBlock, latest, cursor, maxBlocks = FREE_LOGS_BLOCKS, windows = DEGRADED_WINDOWS) { const from = parseInt(fromBlock, 16); let start = Number.isFinite(cursor) ? Math.max(from, cursor + 1) : from; const out = []; while (start <= latest && out.length < windows) { const end = Math.min(latest, start + maxBlocks - 1); out.push([start, end]); start = end + 1; } return out; } // An episode is one run of degraded ticks; a gap of ten minutes without one ends it. export function nextCursorRecord(prev, block, now = Date.now()) { const same = prev && Number.isFinite(prev.at) && now - prev.at < 10 * 60 * 1000; return { block, since: same && prev.since ? prev.since : now, at: now }; } async function walkDegraded(fromBlock, latest, address, topic, tag, env) { const key = 'logs_cursor:' + tag; let prev = null; try { prev = env && env.KV ? await env.KV.get(key, 'json') : null; } catch { prev = null; } const plan = degradedWindows(fromBlock, latest, prev && Number.isFinite(prev.block) ? prev.block : NaN); if (!plan.length) return []; // the cursor already stands at the head: nothing new, not a failure const logs = []; let readTo = null, rpcs = [...LOGS_RPC_ENDPOINTS]; for (const [a, b] of plan) { let r = null; for (const rpc of rpcs) { r = await tryGetLogs(rpc, '0x' + a.toString(16), address, topic, tag + '-fb', '0x' + b.toString(16)); if (r !== null) { rpcs = [rpc, ...rpcs.filter((x) => x !== rpc)]; break; } } if (r === null) break; logs.push(...r); readTo = b; } console.error(`[${tag}] degraded read: ${plan.length ? `${plan[0][0]}-${readTo ?? 'none'}` : 'nothing to read'} of ${fromBlock}-${latest}`); if (env && env.KV) { try { await env.KV.put(key, JSON.stringify(nextCursorRecord(prev, readTo ?? (prev && prev.block) ?? plan[0][0] - 1))); } catch (e) { console.error('[LOGS CURSOR]', e.message || e); } } return readTo === null ? null : logs; } async function getSwapLogs(fromBlock, env, opts) { const r = await getLogsKeyedThenFree(fromBlock, BOBAI_PAIR, SWAP_TOPIC, 'BUY', env, opts); if (r === null) console.error('[BUY] getLogs failed on ALL endpoints'); return r; } function hexToBigInt(hex) { return BigInt(hex || '0x0'); } // ==================== WHALE WATCHER HELPERS ==================== function addrToTopic(addr) { return '0x' + '0'.repeat(24) + addr.slice(2).toLowerCase(); } function topicToAddr(topic) { return '0x' + topic.slice(-40).toLowerCase(); } // Addresses we never want to alert ON. A wallet→pair transfer is a sell and is // worth an alert; the pair and the dead address themselves are not holders and // must never end up on the tracked list. Our own wallets are NOT on this list // (operator, 2026-10-22: "even at 1M, 5M, 10M it must be treated like a normal // wallet"): they cross the 5M / 10M lines and are watched like anyone's. const WHALE_NEVER_TRACK = new Set([ BOBAI_PAIR.toLowerCase(), DEAD.toLowerCase(), BOBAI_TOKEN.toLowerCase(), // BOBAI contract '0x0000000000000000000000000000000000000000', // null ]); // Initial Seed: Whale Main + 5 recipients geseedet 2026-06-17. const DEFAULT_TRACKED = [ '0x1afa5725f77b64f7a75882ffe94b1bdf1a5174f4', // Whale Main (36% Cluster) '0x71e5de5a4720fa438c50261c6023a89f766b382b', // Recipient 1 (57M @ 2026-06-17) '0x7fbb2e47ce5b3f653e4d079b5380897b1f81c792', // Recipient 2 (41M @ 2026-06-17) '0xdfd2d0eacf78706f5f004d8b715cd510a8a6c719', // Recipient 3 (64M @ 2026-06-17) '0xfc3ee9b7928e0ecc6d9c446c343766d5c299594e', // Recipient 4 (44M @ 2026-06-17) '0x7f473820b854ed3959e59934af617929ebf06331', // Recipient 5 (42M @ 2026-06-17) ]; // Whale-Threshold in raw wei (10M BOBAI). Adresses that cross this via any // incoming transfer are auto-added to the watch-set. const WHALE_THRESHOLD_WEI = 10_000_000n * 10n ** 18n; // FROM 5M A HOLDER IS WATCHED (2026-10-06). A full scan of every transfer found // 15 people holding 5-10M, 120.8M BOBAI together (12% of supply), watched by // nobody. 10M stays the whale line (NEW/EX-WHALE, the 🐋 count); 5M is where a // holder enters the watch-set — and since every holder above it is watched, a // holder's rank among them is exact (the LP and the burn address not counted). const WATCH_THRESHOLD_WEI = 5_000_000n * 10n ** 18n; const WATCH_THRESHOLD_TOKENS = 5_000_000; // eth_getLogs for EVERY BOBAI transfer in the fromBlock window, unfiltered by // address. Keyed endpoint first, free endpoints as fallback — same arrangement // as getSwapLogs above, and for the same reasons. async function getAllRecentTransfers(fromBlock, env) { return (await getLogsKeyedThenFree(fromBlock, BOBAI_TOKEN, TRANSFER_TOPIC, 'WHALE', env)) || []; } // balanceOf(addr) → raw wei BigInt async function getBobaiBalance(addr) { const data = '0x70a08231' + '0'.repeat(24) + addr.slice(2).toLowerCase(); const r = await rpcCall('eth_call', [{ to: BOBAI_TOKEN, data }, 'latest']); if (!r) return 0n; try { return BigInt(r); } catch { return 0n; } } // True if addr is a contract (eth_getCode returns non-empty bytecode). On RPC // failure we conservatively return `true` so cascade-adds skip rather than risk // adding an aggregator router (1inch / OKX DEX / 0x). EOAs always return `false`. // A PERSON'S WALLET CAN CARRY CODE (2026-09-18). Since EIP-7702 an ordinary // wallet can delegate to a smart-account implementation; eth_getCode then // answers the delegation designator, 0xef0100 followed by the implementation's // address — 23 bytes, and nothing else looks like it. Read as "has code, so a // contract", eleven of the last forty-five big-buy recipients were invisible to // the whale tracker, one of them holding 10.02M $BOBAI; /whaleadd refused such // a wallet and /whalecleanup would have deleted a tracked whale the day it // switched a smart account on. Pure; pinned by scripts/smoke-whale.mjs. export function codeIsContract(code) { if (code === null || code === undefined) return true; // unknown: stay careful const c = String(code).toLowerCase(); if (c === '0x' || c === '0x0' || c === '0x00') return false; // no code: a plain wallet if (c.startsWith('0xef0100') && c.length === 2 + 23 * 2) return false; // a 7702 delegation: still a person's wallet return true; } async function isContract(addr) { if (!/^0x[a-f0-9]{40}$/i.test(addr)) return true; try { return codeIsContract(await rpcCall('eth_getCode', [addr, 'latest'])); } catch { return true; } } function formatNumber(n) { // A loss is a number too: the recap's 7d trend printed "-33541652.00". if (n < 0) return '-' + formatNumber(-n); if (n >= 1_000_000) return (n / 1_000_000).toFixed(2) + 'M'; if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K'; return n.toFixed(2); } function formatUsd(n) { if (n < 0) return '-' + formatUsd(-n); if (n >= 1_000_000) return '$' + (n / 1_000_000).toFixed(2) + 'M'; if (n >= 1_000) return '$' + (n / 1_000).toFixed(1) + 'K'; return '$' + n.toFixed(2); } function shortenAddress(addr) { return addr.slice(0, 6) + '...' + addr.slice(-4); } function priceChangeArrow(pct) { const n = parseFloat(pct); if (n > 0) return `🟢 +${n.toFixed(1)}%`; if (n < 0) return `🔴 ${n.toFixed(1)}%`; return `⚪ 0%`; } // ==================== PRICE DATA (Gecko → DexScreener → On-Chain) ==================== // Chainlink BNB/USD feed on BSC (8 decimals) const CHAINLINK_BNB_USD = '0x0567F2323251f0Aab15c8dFb1967E4e8A7D42aeE'; // BOBAI realistic USD range — protects against absurd values if any source goes haywire const PRICE_MIN_USD = 1e-7; const PRICE_MAX_USD = 1e-2; function isSanePrice(p) { return Number.isFinite(p) && p >= PRICE_MIN_USD && p <= PRICE_MAX_USD; } // On-chain BOBAI/USD: pair reserves × Chainlink BNB/USD. Last-resort fallback when // both Gecko and DexScreener are down. BOBAI is token0 in this pair (verified on-chain). // Reads the pair reserves and the Chainlink feed in one go. Returns the USD price, // the BNB price and the BNB side of the pool, or null when either read fails. async function readPairOnchain() { try { // getReserves() selector = 0x0902f1ac → packed (uint112 r0, uint112 r1, uint32 ts) const rHex = await rpcCall('eth_call', [{ to: BOBAI_PAIR, data: '0x0902f1ac' }, 'latest']); if (!rHex) return null; const rBOBAI = BigInt('0x' + rHex.slice(2, 66)); const rWBNB = BigInt('0x' + rHex.slice(66, 130)); if (rBOBAI === 0n || rWBNB === 0n) return null; // Chainlink latestAnswer() selector = 0x50d25bcd → int256 (8 decimals) const aHex = await rpcCall('eth_call', [{ to: CHAINLINK_BNB_USD, data: '0x50d25bcd' }, 'latest']); if (!aHex) return null; const bnbUsd = Number(BigInt(aHex)) / 1e8; if (!(bnbUsd > 0)) return null; const priceInBnb = Number(rWBNB) / Number(rBOBAI); const price = priceInBnb * bnbUsd; if (!isSanePrice(price)) return null; return { price, priceInBnb, bnbUsd, wbnbReserve: Number(rWBNB) / 1e18 }; } catch (e) { console.log('[price] onchain error:', e.message || e); return null; } } // BNB/USD from the Chainlink feed (8 decimals). Used to value on-chain buys. async function getBnbUsd() { try { const aHex = await rpcCall('eth_call', [{ to: CHAINLINK_BNB_USD, data: '0x50d25bcd' }, 'latest']); if (!aHex) return null; const v = Number(BigInt(aHex)) / 1e8; return v > 0 ? v : null; } catch { return null; } } // Indexer figures (24h change, volume, trade counts) plus the indexer's own // price, mapped into GeckoTerminal's attribute shape. DexScreener first: // GeckoTerminal answers this Worker's shared Cloudflare egress with 429 for // most of the day, DexScreener does not. Null when neither answers — the // caller must never depend on it for the price itself, that comes from the // chain. The last good answer is kept in KV for half an hour, so one refused // minute prints "as of 05:40 UTC" rather than n/a; older than that is n/a, // because a stale figure without a time on it is a wrong figure. const INDEXER_CACHE_KEY = 'price_24h'; const INDEXER_CACHE_MAX_AGE_MS = 30 * 60 * 1000; async function fetchIndexerStats(env = null) { let attrs = null; try { const res = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${BOBAI_TOKEN}`); if (res.ok) { const data = await res.json(); const p = (data?.pairs || []).find(x => x.pairAddress?.toLowerCase() === BOBAI_PAIR.toLowerCase()) || (data?.pairs || [])[0]; if (p && isSanePrice(parseFloat(p.priceUsd))) { attrs = { source: 'DexScreener', base_token_price_usd: p.priceUsd, base_token_price_native_currency: p.priceNative, fdv_usd: p.fdv, reserve_in_usd: p.liquidity?.usd, volume_usd: { h24: p.volume?.h24 }, price_change_percentage: p.priceChange || {}, transactions: { h24: p.txns?.h24 || {} }, }; } else { console.log('[price] dexscreener unusable:', JSON.stringify(p?.priceUsd), (data?.pairs || []).length, 'pairs'); } } else { console.log('[price] dexscreener status', res.status, (await res.text()).slice(0, 200)); } } catch (e) { console.log('[price] dexscreener error:', e.message || e); } if (!attrs) { try { const res = await fetch(`${GECKO_POOL_URL}?_=${Date.now()}`, { headers: { 'Accept': 'application/json' } }); if (res.ok) { const data = await res.json(); const a = data?.data?.attributes; if (a && isSanePrice(parseFloat(a.base_token_price_usd))) attrs = { source: 'GeckoTerminal', ...a }; else console.log('[price] gecko unusable:', JSON.stringify(a?.base_token_price_usd)); } else { console.log('[price] gecko status', res.status, (await res.text()).slice(0, 200)); } } catch (e) { console.log('[price] gecko error:', e.message || e); } } if (attrs) { if (env?.KV) { try { await env.KV.put(INDEXER_CACHE_KEY, JSON.stringify({ at: Date.now(), attrs }), { expirationTtl: 3600 }); } catch (e) { console.log('[price] cache write failed:', e.message || e); } } return attrs; } if (env?.KV) { try { const raw = await env.KV.get(INDEXER_CACHE_KEY); const c = raw ? JSON.parse(raw) : null; if (c && Date.now() - c.at < INDEXER_CACHE_MAX_AGE_MS) { console.log('[price] indexers refused, using figures from', new Date(c.at).toISOString()); return { ...c.attrs, as_of: c.at }; } } catch (e) { console.log('[price] cache read failed:', e.message || e); } } return null; } // ==================== THE BOT'S OWN 24-HOUR LEDGER ==================== // /price used to take its 24h volume, trade counts and price change from // GeckoTerminal or DexScreener. GeckoTerminal answers this Worker with 429 // for most of the day and DexScreener has its minutes too, and on those // minutes the command printed n/a — to the person who had just typed it. // A figure that depends on somebody else's rate limiter is not a figure. // // So the bot keeps its own record. Every tenth minute the cron reads the // pair's Swap events since the last bucket (the same keyed endpoints the // buy alerts already use), counts buys and sells, sums the BNB that moved, // reads the pool price from the reserves, and appends one bucket. Buckets // older than a day are dropped. /price then reads one KV key and computes // everything from it: 24h volume and trades from the buckets, price change // from the bucket price nearest to an hour, six hours and a day ago. The // first day it says how many hours it has. Nothing here can be rate-limited // by a third party; a missed tick shows as a gap, not as a wrong number. const SWAP_LEDGER_KEY = 'swap_buckets'; const LEDGER_HOURS = 24; // Kept for a week since 2026-09-26: the Brain Terminal's 7D chart reads the same buckets (/candles). The figures of // /price still cover exactly LEDGER_HOURS (ledgerStats cuts its own window); the key only grows from ~145 to ~1,010 // buckets (~150 KB), written as often as before. const LEDGER_KEEP_HOURS = 168; const BUCKET_MINUTES = 10; // BSC clears a block every ~0.45 s in 2026: ten minutes is ~1,330 blocks. // 1,600 leaves headroom so a late tick never opens a hole; a bucket carries // its block range, so overlaps are cut on read, never counted twice. const BUCKET_BLOCKS = 1600; async function readSwapLedger(env) { try { const raw = await env.KV.get(SWAP_LEDGER_KEY); return raw ? JSON.parse(raw) : []; } catch { return []; } } // One tick of the ledger. Reads the Swap events from the block after the last // bucket (or the last ten minutes, if there is no bucket or the gap is too // wide to read in one call), and appends what it found. async function recordSwapBucket(env) { const latestHex = await rpcCall('eth_blockNumber', []); if (!latestHex) throw new Error('no block number'); const latest = parseInt(latestHex, 16); const ledger = await readSwapLedger(env); const last = ledger[ledger.length - 1]; let from = last && latest - last.to <= BUCKET_BLOCKS * 2 ? last.to + 1 : latest - BUCKET_BLOCKS; if (from > latest) return { added: false, why: 'no new blocks' }; // narrow:false — a bucket says "these blocks, all of them"; a cut read booked // under the full range counted the day short. No full read, no bucket: the // next tick reads from the same block again. const logs = await getSwapLogs('0x' + from.toString(16), env, { narrow: false }); if (!Array.isArray(logs)) throw new Error('swap logs unavailable'); // buy_bnb / sell_bnb (2026-10-09): the BNB each side moved, for the daily market card's buys-vs-sells in dollars. let buys = 0, sells = 0, volWei = 0n, buyWei = 0n, sellWei = 0n, ownWei = 0n, hi = 0, lo = 0; // THE BIG TRADES BY NAME (2026-10-05, operator: a $9.5K sell stood in its candle only as "6 sells, 17 BNB in all" once // the page's own read of the chain, about an hour, had passed it). Each transaction's swaps of one side are one trade; // the ones worth $100 or more are kept with the bucket, the six largest at most: [buy 1/0, BNB, BOBAI, tx, the swap's recipient] — the recipient tells a bot of ours from a trader. const byTx = new Map(); // THE TOKEN'S OWN TAX SWAP IS NO TRADER (2026-10-09 review: the market card's "Largest sell" could be it — the router // is the recipient of every sell, so the recipient does not tell). The token logs each tax swap with its BOBAI amount; // a sell of exactly that amount in that transaction is the tax swap: counted in the volume, kept out of the big trades. // An unread tax-swap log only means nothing is told apart, as before. const taxSw = new Map(); for (const l of (await getLogsKeyedThenFree('0x' + from.toString(16), BOBAI_TOKEN, TAXSWAP_TOPIC, 'TAXSWAP', env, { narrow: false }).catch(() => null)) || []) { try { taxSw.set(String(l.transactionHash || '').toLowerCase(), BigInt('0x' + l.data.slice(2, 66))); } catch {} } for (const log of logs) { const b = parseInt(log.blockNumber, 16); if (b < from || b > latest) continue; const d = log.data.slice(2); if (d.length < 256) continue; const amount0In = BigInt('0x' + d.slice(0, 64)), amount1In = BigInt('0x' + d.slice(64, 128)); const amount0Out = BigInt('0x' + d.slice(128, 192)), amount1Out = BigInt('0x' + d.slice(192, 256)); const isBuy = amount1In > 0n && amount0Out > 0n; if (isBuy) buys++; else if (amount0In > 0n && amount1Out > 0n) sells++; else continue; volWei += amount1In + amount1Out; if (isBuy) buyWei += amount1In; else sellWei += amount1Out; const sw = !isBuy && taxSw.get(String(log.transactionHash || '').toLowerCase()); const isTax = !!sw && (amount0In > sw ? amount0In - sw : sw - amount0In) * 1000000n <= sw; // OUR OWN SWAPS, SEPARATELY (2026-10-10): the tax swap and a buy into one of our bots' wallets are in the volume, // but they are not traders — the terminal's "next buyback at the last 24 h pace" takes them out (own_bnb, row `o`). if (isTax || (isBuy && IGNORED_WALLETS.has('0x' + String((log.topics || [])[2] || '').slice(26).toLowerCase()))) ownWei += amount1In + amount1Out; if (!isTax) { const k = (log.transactionHash || '') + (isBuy ? ':b' : ':s'), e = byTx.get(k) || { buy: isBuy ? 1 : 0, bnb: 0n, bobai: 0n, tx: log.transactionHash || '', to: '0x' + String((log.topics || [])[2] || '').slice(26).toLowerCase() }; e.bnb += amount1In + amount1Out; e.bobai += amount0In + amount0Out; byTx.set(k, e); } // the swap's own price, BNB per BOBAI: the candle's wick (the bucket's close is the reserves after it) const px = Number(amount1In + amount1Out) / Number(amount0In + amount0Out); if (px > 0 && Number.isFinite(px)) { hi = Math.max(hi, px); lo = lo ? Math.min(lo, px) : px; } } const pair = await readPairOnchain(); const bucket = { t: Date.now(), from, to: latest, buys, sells, vol_bnb: Number(volWei) / 1e18, ...(ownWei > 0n ? { own_bnb: Number(ownWei) / 1e18 } : {}),buy_bnb: Number(buyWei) / 1e18, sell_bnb: Number(sellWei) / 1e18, price_bnb: pair ? pair.priceInBnb : null, price_usd: pair ? pair.price : null, bnb_usd: pair ? pair.bnbUsd : null, ...(hi ? { hi_bnb: hi, lo_bnb: lo } : {}) }; if (pair && pair.bnbUsd > 0) { const big = [...byTx.values()].map((e) => [e.buy, Number(e.bnb) / 1e18, Number(e.bobai) / 1e18, e.tx, e.to]).filter((e) => e[1] * pair.bnbUsd >= 100).sort((a, b) => b[1] - a[1]).slice(0, 6); if (big.length) bucket.big = big; } const cutoff = Date.now() - LEDGER_KEEP_HOURS * 3600 * 1000; const kept = ledger.filter((x) => x.t >= cutoff).concat(bucket); await env.KV.put(SWAP_LEDGER_KEY, JSON.stringify(kept)); console.log('[LEDGER] bucket', from, '-', latest, buys, 'buys', sells, 'sells', bucket.vol_bnb.toFixed(4), 'BNB'); return { added: true, buys, sells, buckets: kept.length }; } // What the ledger says right now. `priceNow` is today's pool price in BNB; // the change over a window is against the bucket whose age is nearest to // that window, and only if one exists within half the window — a "24h // change" measured against a nine-hour-old price would be a lie with a // label on it. function ledgerStats(ledger, priceNowBnb) { const now = Date.now(); const cutoff = now - LEDGER_HOURS * 3600 * 1000; const rows = (ledger || []).filter((x) => x.t >= cutoff).sort((a, b) => a.t - b.t); if (!rows.length) return null; let buys = 0, sells = 0, volBnb = 0, lastTo = 0; for (const r of rows) { if (r.to <= lastTo) continue; // an overlapping re-read is one observation buys += r.buys; sells += r.sells; volBnb += r.vol_bnb; lastTo = r.to; } const hours = Math.min(LEDGER_HOURS, (now - rows[0].t) / 36e5 + BUCKET_MINUTES / 60); const change = (h) => { const target = now - h * 36e5; let best = null; for (const r of rows) { if (!(r.price_bnb > 0)) continue; if (!best || Math.abs(r.t - target) < Math.abs(best.t - target)) best = r; } if (!best || Math.abs(best.t - target) > (h * 36e5) / 2 || !(priceNowBnb > 0)) return null; return (priceNowBnb / best.price_bnb - 1) * 100; }; return { hours, buys, sells, trades: buys + sells, vol_bnb: volBnb, h1: change(1), h6: change(6), h24: change(24), first_at: rows[0].t, last_at: rows[rows.length - 1].t }; } // ==================== BUY CONTEXT, POSTED EVIDENCE, DAILY MARKET CARD (2026-10-09) ==================== const DAY_MS = 24 * 3600 * 1000; // One entry per buy alert that went out (KV `alerted_buys`): {since, buys: [{tx, buyer, usd, ts}]}. Written only in // a tick that sent an alert, one write for all of them; a week kept, 300 at most. const ALERTED_BUYS_KEY = 'alerted_buys'; const ALERTED_KEEP_MS = 7 * DAY_MS, ALERTED_MAX = 300; export function addAlertedBuys(rec, add, now = Date.now()) { const since = rec && Number.isFinite(rec.since) ? rec.since : now; const buys = [...((rec && Array.isArray(rec.buys)) ? rec.buys : []), ...add].filter((b) => b && now - b.ts < ALERTED_KEEP_MS).slice(-ALERTED_MAX); return { since, buys }; } // ONE ALERT PER BUY, WHATEVER THE TICKS DO (2026-10-23). The $328 buy of 22.10. 20:37 UTC went out twice, the same // photo in the same minute: two every-minute ticks both read `pending_nft_buys` before either had written it back // (KV is eventually consistent across locations, up to 60 s, and a tick can run longer than a minute). A Durable // Object is one instance worldwide with ordered storage, so a claim is atomic: the first tick to claim a tx sends, // every other one skips it. A send that fails releases the claim, so the next tick can retry. Claims are kept 7 days. export class AlertGate { constructor(state) { this.state = state; } async fetch(request) { const u = new URL(request.url); const key = u.searchParams.get('k'); if (!key) return new Response('{"error":"no key"}', { status: 400 }); const now = Date.now(); if (u.pathname === '/claim') { const at = await this.state.storage.get(key); if (at && now - at < ALERTED_KEEP_MS) return Response.json({ claimed: false, at }); await this.state.storage.put(key, now); // prune now and then: one list in a hundred claims if (Math.random() < 0.01) { const all = await this.state.storage.list(); const old = [...all].filter(([, t]) => now - t >= ALERTED_KEEP_MS).map(([k]) => k); if (old.length) await this.state.storage.delete(old.slice(0, 128)); } return Response.json({ claimed: true }); } if (u.pathname === '/release') { await this.state.storage.delete(key); return Response.json({ released: true }); } return new Response('{"error":"unknown"}', { status: 404 }); } } // true: this tick may send. No gate bound (tests, a local run): true, the KV dedup as before. A gate that cannot be // asked: true as well — a buy told twice is better than a buy never told (the health check counts untold buys). export async function claimAlert(env, kind, id) { if (!env || !env.GATE) return true; try { const stub = env.GATE.get(env.GATE.idFromName('alerts')); const r = await stub.fetch(`https://gate/claim?k=${encodeURIComponent(kind + ':' + String(id).toLowerCase())}`); const j = await r.json(); if (j.claimed !== true) console.log('[GATE] already sent by another tick', kind, id); return j.claimed === true; } catch (e) { console.error('[GATE] claim failed, sending anyway', kind, id, e.message || e); return true; } } export async function releaseAlert(env, kind, id) { if (!env || !env.GATE) return; try { await env.GATE.get(env.GATE.idFromName('alerts')).fetch(`https://gate/release?k=${encodeURIComponent(kind + ':' + String(id).toLowerCase())}`); } catch (e) { console.error('[GATE] release failed', kind, id, e.message || e); } } export const ordinal = (n) => { const t = n % 100, u = n % 10; return n + (t >= 11 && t <= 13 ? 'th' : u === 1 ? 'st' : u === 2 ? 'nd' : u === 3 ? 'rd' : 'th'); }; const shortDay = (ms) => new Date(ms).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); // The ledger's own trades of $100 and more, one per transaction: [{tx, buy, bnb, usd, to, t}]. The project's own // wallets (IGNORED_WALLETS, read from the swap's recipient) are left out. export function ledgerBigTrades(ledger, sinceMs) { const byTx = new Map(); for (const r of ledger || []) { if (!r || r.t < sinceMs || !Array.isArray(r.big) || !(r.bnb_usd > 0)) continue; for (const e of r.big) { const to = String(e[4] || '').toLowerCase(); if (IGNORED_WALLETS.has(to)) continue; const k = String(e[3] || '').toLowerCase() + (e[0] === 1 ? ':b' : ':s'); if (!byTx.has(k)) byTx.set(k, { tx: String(e[3] || ''), buy: e[0] === 1, bnb: e[1], usd: e[1] * r.bnb_usd, to, t: r.t }); } } return [...byTx.values()]; } // THE BUY ALERT SAYS WHO THIS IS (operator, 2026-10-09). One line under the buyer: what the wallet holds now (read // from the chain; a failed read leaves the part out, it never says 0), whether it bought before this week (from the // alert record above — said only when a prior alert is on record, and "since " while the record is younger than // a week), and whether it is the largest buy the ledger has seen in its window (the ledger keeps seven days; said in // days it really covers, never fewer than one). Nothing to say: no line. Pure; pinned by scripts/tg-alerts-regressions.mjs. export function buyContextLine({ usd, buyer, tx, now = Date.now(), alerted = null, ledger = [], holdTokens = null, price = 0 }) { const parts = []; if (Number.isFinite(holdTokens) && holdTokens > 0) parts.push(`holds ${formatNumber(holdTokens)} BOBAI${price > 0 ? ` (≈${formatUsd(holdTokens * price)})` : ''}`); const me = String(buyer || '').toLowerCase(), txl = String(tx || '').toLowerCase(); const recent = alerted && Array.isArray(alerted.buys) ? alerted.buys.filter((b) => b && String(b.buyer).toLowerCase() === me && String(b.tx).toLowerCase() !== txl && now - b.ts < ALERTED_KEEP_MS) : []; if (recent.length) { const whole = Number.isFinite(alerted.since) && now - alerted.since >= ALERTED_KEEP_MS; parts.push(`${ordinal(recent.length + 1)} buy from this wallet ${whole ? 'this week' : 'since ' + shortDay(alerted.since)}`); } const rows = (ledger || []).filter((r) => r && Number.isFinite(r.t)); if (rows.length && usd > 0) { const first = Math.min(...rows.map((r) => r.t)); const days = Math.min(7, Math.floor((now - first) / DAY_MS)); const others = ledgerBigTrades(rows, now - days * DAY_MS).filter((e) => e.buy && e.tx.toLowerCase() !== txl); if (days >= 1 && others.every((e) => e.usd < usd)) parts.push(days === 1 ? 'largest buy in 24 hours' : `largest buy in ${days} days`); } if (!parts.length) return ''; const s = parts.join(' · '); return `\n📊 ${s[0].toUpperCase()}${s.slice(1)}`; } // WAS EVERY BIG BUY TOLD (2026-10-09). The ledger's buys of $100+ over the last day against what the alert scan // marked (posted_txs: told, queued for its NFT, or one of ours) and the alert record. Missing = not marked and older // than a quarter hour (the alert scan reads every minute; the NFT wait is five). $101, not $100: the ledger prices a // trade with the BNB price of its tick, the alert with its own — a buy at $100.40 may fall either side. Pure. export function postedBuyEvidence(ledger, marked, pending, now = Date.now()) { const big = ledgerBigTrades(ledger, now - DAY_MS).filter((e) => e.buy && e.usd >= 100); const has = (tx) => marked.has(String(tx).toLowerCase()); const missing = big.filter((e) => !has(e.tx) && e.usd >= 101 && e.t <= now - 15 * 60 * 1000).map((e) => e.tx); const ages = (pending || []).map((p) => (now - (p && p.queuedAt)) / 60000).filter(Number.isFinite); return { buys_100_24h: big.length, posted: big.filter((e) => has(e.tx)).length, missing_count: missing.length, missing: missing.slice(0, 5), pending: { count: (pending || []).length, oldest_min: ages.length ? Math.round(Math.max(...ages)) : null }, }; } // THE DAY ON THE POOL, ONCE A DAY (operator, 2026-10-09). A plain card for the group from the bot's own ledger (the // pool's Swap events, read every ten minutes) and the buyback bot's own log: buys and sells by count and dollars, the // BNB that went in or out net, the largest buy and sell, and what the bot burned. Every swap counts, the project's // own bots included (the ledger cannot tell them apart below $100); the largest two leave ours out. A window the // ledger does not cover whole says its hours. Null when there is nothing to report. Pure. export function formatMarketCard(ledger, burns, { now = Date.now(), priceUsd = 0, bnbUsd = 0 } = {}) { const rows = (ledger || []).filter((r) => r && r.t >= now - DAY_MS && Number.isFinite(r.buy_bnb) && Number.isFinite(r.sell_bnb)).sort((a, b) => a.t - b.t); if (!rows.length) return null; let buys = 0, sells = 0, buyBnb = 0, sellBnb = 0, buyUsd = 0, sellUsd = 0, lastTo = 0; for (const r of rows) { if (r.to <= lastTo) continue; // an overlapping re-read is one observation lastTo = r.to; const px = r.bnb_usd > 0 ? r.bnb_usd : bnbUsd; buys += r.buys; sells += r.sells; buyBnb += r.buy_bnb; sellBnb += r.sell_bnb; buyUsd += r.buy_bnb * px; sellUsd += r.sell_bnb * px; } const hours = Math.min(24, Math.round((now - rows[0].t) / 36e5 + 1 / 6)); const big = ledgerBigTrades(rows, now - DAY_MS); const top = (buy) => big.filter((e) => e.buy === buy).sort((a, b) => b.usd - a.usd)[0]; const tb = top(true), ts = top(false); const tradeLine = (e, word) => e ? `${formatUsd(e.usd)} (${e.bnb.toFixed(3)} BNB) · TX` : `no ${word} of $100 or more`; const net = buyBnb - sellBnb; const netLine = Math.abs(net) < 0.0005 ? 'about even' : `${net > 0 ? '+' : '−'}${Math.abs(net).toFixed(3)} BNB${bnbUsd > 0 ? ` (≈${formatUsd(Math.abs(net) * bnbUsd)})` : ''} ${net > 0 ? 'into the pool' : 'out of the pool'}`; let burnLine; if (!Array.isArray(burns)) burnLine = 'the bot log did not answer, not counted'; else { const day = burns.filter((b) => b && Date.parse(b.time) >= now - DAY_MS); const amt = day.reduce((a, b) => a + (parseFloat(b.bobaiBurned) || 0), 0); burnLine = amt > 0 ? `${formatNumber(amt)} BOBAI${priceUsd > 0 ? ` (≈${formatUsd(amt * priceUsd)})` : ''} in ${day.length} run${day.length === 1 ? '' : 's'}` : 'nothing in this window'; } return `📊 $BOBAI — the last ${hours} hours on the pool 📈 Buys: ${buys} · ${formatUsd(buyUsd)} 📉 Sells: ${sells} · ${formatUsd(sellUsd)} 💎 Net: ${netLine} 💰 Largest buy: ${tradeLine(tb, 'buy')} 💰 Largest sell: ${tradeLine(ts, 'sell')} 🔥 Burned by the bot: ${burnLine} From the pool's own Swap events, read every ten minutes. Every Swap event counts, the token's own tax swap and the project's bots included, and a trade split over several swaps once per swap; the largest two leave the bots and the tax swap out.`; } async function postDailyMarketCard(env, now = Date.now()) { const today = new Date(now).toISOString().slice(0, 10); if ((await env.KV.get('market_card_date')) === today) return false; let burns = null; try { const r = await fetch('https://logs.brainonbnb.com/logs/burns.json', { cf: { cacheTtl: 120 } }); if (r.ok) burns = await r.json(); } catch { /* said on the card */ } const pair = await readPairOnchain(); const text = formatMarketCard(await readSwapLedger(env), burns, { now, priceUsd: pair ? pair.price : 0, bnbUsd: pair ? pair.bnbUsd : 0 }); if (!text) { console.log('[MARKET CARD] skipped: the ledger has no buckets with the buy/sell split'); return false; } const sent = await tg('sendMessage', { chat_id: TG_CHAT_ID, text, parse_mode: 'HTML', disable_web_page_preview: true }); if (!sent || sent.ok !== true) { console.error('[MARKET CARD] Telegram refused:', sent && sent.description); return false; } await env.KV.put('market_card_date', today); return true; } // WHAT /health SHOWS BEYOND THE HEARTBEAT (2026-10-09). A running cron said nothing about whether the buys were // told: buy_alerts (postedBuyEvidence; marked = posted_txs plus the alert record), burn_alerts (the dead address // against the last burn told, and since when an owed one could not go out), and whether the log scans run degraded // (scan_degraded_since: the oldest open episode, null when every scan read whole in the last five minutes). Reads // only; one chain read (the dead balance). async function healthEvidence(env, now = Date.now()) { const json = async (k) => { try { return await env.KV.get(k, 'json'); } catch { return null; } }; const out = {}; try { const [ledger, posted, pending, alerted] = await Promise.all([readSwapLedger(env), json('posted_txs'), json('pending_nft_buys'), json(ALERTED_BUYS_KEY)]); const marked = new Set([...(Array.isArray(posted) ? posted : []), ...((alerted && Array.isArray(alerted.buys)) ? alerted.buys.map((b) => b && b.tx) : [])].map((t) => String(t || '').toLowerCase())); out.buy_alerts = postedBuyEvidence(ledger, marked, Array.isArray(pending) ? pending : [], now); // TOLD ONCE (2026-10-25, operator: "irgendetwas stimmt nicht mehr mit den buy alerts und nft minter"): a transaction // the alert record holds twice in its week was told twice — the morning report reads this, not only "none missing" { const seen = new Map(); for (const b of (alerted && Array.isArray(alerted.buys) ? alerted.buys : [])) { const t = String(b && b.tx || '').toLowerCase(); if (t) seen.set(t, (seen.get(t) || 0) + 1); } const twice = [...seen].filter(([, n]) => n > 1).map(([t]) => t); out.buy_alerts.told_twice_7d = twice.length; out.buy_alerts.told_twice = twice.slice(0, 5); } } catch (e) { out.buy_alerts = { error: String(e && e.message || e).slice(0, 120) }; } try { const [lastRaw, stuck] = await Promise.all([env.KV.get('last_burned'), env.KV.get('burn_stuck_since')]); let dead = null; try { dead = await getBurnedTokens(); } catch { dead = null; } const last = lastRaw != null && Number.isFinite(parseFloat(lastRaw)) ? parseFloat(lastRaw) : null; out.burn_alerts = { last_burned: last, dead_balance: dead, gap: dead != null && last != null ? dead - last : null, stuck_since: stuck || null }; } catch (e) { out.burn_alerts = { error: String(e && e.message || e).slice(0, 120) }; } const cur = await Promise.all(['BUY', 'WHALE'].map((t) => json('logs_cursor:' + t))); const open = cur.filter((c) => c && Number.isFinite(c.at) && now - c.at < 5 * 60 * 1000 && Number.isFinite(c.since)).map((c) => c.since); out.scan_degraded_since = open.length ? new Date(Math.min(...open)).toISOString() : null; out.scan_cursor = { buys: cur[0] || null, whale: cur[1] || null }; return out; } // BOBAI/USD for alerts that only need a number. The chain is the source: pair // reserves times the Chainlink BNB feed, the same maths as the dashboard. An // indexer price is only a stand-in when the RPC endpoints are all down. async function fetchBobaiPriceUsd() { const pair = await readPairOnchain(); if (pair) return pair.price; const ix = await fetchIndexerStats(); const p = ix ? parseFloat(ix.base_token_price_usd) : NaN; if (isSanePrice(p)) { console.log('[price] chain unreadable, using indexer price'); return p; } return null; } // ==================== WORLDCUP TIPGAME ==================== // ISO country code → flag emoji. Special-cased UK constituents (ENG/SCT/WAL). function isoToFlag(iso) { if (!iso) return '🏳️'; if (iso === 'ENG') return '🏴󠁧󠁢󠁥󠁮󠁧󠁿'; if (iso === 'SCT') return '🏴󠁧󠁢󠁳󠁣󠁴󠁿'; if (iso === 'WAL') return '🏴󠁧󠁢󠁷󠁬󠁳󠁿'; if (iso.length !== 2) return '🏳️'; return iso.toUpperCase() .split('') .map(c => String.fromCodePoint(0x1F1E6 + c.charCodeAt(0) - 65)) .join(''); } async function sbSelect(table, query) { try { const url = `${SUPABASE_URL}/rest/v1/${table}?${query}`; const res = await fetch(url, { headers: { apikey: SUPABASE_ANON_KEY, Authorization: `Bearer ${SUPABASE_ANON_KEY}` }, }); if (!res.ok) return []; return await res.json(); } catch (e) { console.error('[SB]', e.message || e); return []; } } async function fetchWorldcupPool() { const rows = await sbSelect('wc_pool', 'id=eq.1&select=total_bobai,group_pot,endpool,crypto_pot,bobai_price_usd,updated_at'); return rows[0] || null; } async function fetchWorldcupLeaderboard(n = 10) { return sbSelect('wc_leaderboard', `select=username,avatar_country,total_points,has_wallet&order=total_points.desc&limit=${n}`); } // Total registered players = row count of the wc_leaderboard view (1 row per wc_users row). // Uses PostgREST exact-count via the Content-Range header (no full table fetch). async function fetchWorldcupPlayerCount() { try { const url = `${SUPABASE_URL}/rest/v1/wc_leaderboard?select=user_id&limit=1`; const res = await fetch(url, { headers: { apikey: SUPABASE_ANON_KEY, Authorization: `Bearer ${SUPABASE_ANON_KEY}`, Prefer: 'count=exact', Range: '0-0', }, }); if (!res.ok) return null; const cr = res.headers.get('content-range'); // e.g. "0-0/142" const total = cr ? parseInt(cr.split('/')[1], 10) : NaN; return Number.isFinite(total) ? total : null; } catch (e) { console.error('[SB count]', e.message || e); return null; } } // Returns last N rows; `taxOnly` true → TAX only, false → BNB+USDT (donations), null → both. async function fetchWorldcupDonations(n = 3, taxOnly = null) { let tokenFilter = ''; if (taxOnly === true) tokenFilter = '&token=eq.TAX'; if (taxOnly === false) tokenFilter = '&token=in.(BNB,USDT)'; return sbSelect('wc_donations', `select=token,amount_in,amount_bobai,swap_tx_hash,created_at${tokenFilter}&order=created_at.desc&limit=${n}`); } // ==================== BURN STATS ==================== async function getBurnedTokens() { const balanceData = '0x70a08231' + DEAD.slice(2).padStart(64, '0'); const burnedHex = await rpcCall('eth_call', [{ to: BOBAI_TOKEN, data: balanceData }, 'latest']); // A FAILED READ IS NOT ZERO (2026-10-09): hexToBigInt(null) is 0n, so a refused call read as "nothing burned". if (!burnedHex || burnedHex === '0x') throw new Error('dead balance unreadable'); return Number(hexToBigInt(burnedHex)) / 1e18; } async function getTotalSupply() { const totalData = '0x18160ddd'; const totalHex = await rpcCall('eth_call', [{ to: BOBAI_TOKEN, data: totalData }, 'latest']); if (!totalHex || totalHex === '0x') throw new Error('total supply unreadable'); return Number(hexToBigInt(totalHex)) / 1e18; } async function getBurnStats() { try { const [burnedTokens, totalSupply] = await Promise.all([getBurnedTokens(), getTotalSupply()]); const percent = totalSupply > 0 ? (burnedTokens / totalSupply * 100).toFixed(1) : '?'; return { burnedTokens, percent }; } catch { return { burnedTokens: null, percent: '?' }; } } // ==================== LIQUIDITY DEPTH ==================== // Same maths as the dashboard's liquidity block: every number is derived from the live // pair reserves, nothing is hardcoded. PancakeSwap V2 (factory verified on-chain) keeps // 0.25% of the input inside the pool; the 3% BOBAI tax never touches the reserves. const LP_FEE = 0.9975; const TAX_KEEP = 0.97; // Deliberately the same steps as the buy-alert tiers and the dashboard bars. const DEPTH_SIZES = [100, 150, 250, 500, 1000, 2500]; // Trade size that moves the price by (k - 1). Closed form of // (r + x)(r + FEE*x) = k*r^2 -> FEE*x^2 + r*(1 + FEE)*x + r^2*(1 - k) = 0. // Mirrors onePctV2() in dashboard/scanner-chain.js — change both together. function onePctSize(r, k) { const b = 1 + LP_FEE; const disc = b * b - 4 * LP_FEE * (1 - k); return r * (Math.sqrt(disc) - b) / (2 * LP_FEE); } async function fetchLiquidityStats() { const balDead = '0x70a08231' + DEAD.slice(2).padStart(64, '0'); const [rHex, lpTotalHex, lpDeadHex, supplyHex, burnedHex, bnbUsd, blockHex] = await Promise.all([ rpcCall('eth_call', [{ to: BOBAI_PAIR, data: '0x0902f1ac' }, 'latest']), rpcCall('eth_call', [{ to: BOBAI_PAIR, data: '0x18160ddd' }, 'latest']), rpcCall('eth_call', [{ to: BOBAI_PAIR, data: balDead }, 'latest']), rpcCall('eth_call', [{ to: BOBAI_TOKEN, data: '0x18160ddd' }, 'latest']), rpcCall('eth_call', [{ to: BOBAI_TOKEN, data: balDead }, 'latest']), getBnbUsd(), rpcCall('eth_blockNumber', []), ]); if (!rHex || !bnbUsd) return null; // BOBAI is token0 in this pair (verified on-chain) const rTok = Number(BigInt('0x' + rHex.slice(2, 66))) / 1e18; const rBnb = Number(BigInt('0x' + rHex.slice(66, 130))) / 1e18; if (!(rTok > 0) || !(rBnb > 0)) return null; const price = (rBnb / rTok) * bnbUsd; const bnbSide = rBnb * bnbUsd; // hard BNB backing — the half that isn't our own token const tvl = bnbSide * 2; const supply = Number(hexToBigInt(supplyHex)) / 1e18; const burned = Number(hexToBigInt(burnedHex)) / 1e18; const mcap = supply > 0 ? (supply - burned) * price : null; const lpTotal = Number(hexToBigInt(lpTotalHex)) / 1e18; const lpDead = Number(hexToBigInt(lpDeadHex)) / 1e18; const lpBurnedPct = lpTotal > 0 ? (lpDead / lpTotal) * 100 : null; // "What does one percent cost" — the reverse of the impact bars. A buy needs no tax // correction (incoming BNB is untaxed); a sell does, because only 97% of the tokens // sent ever reach the reserves. const up1 = onePctSize(rBnb, 1.01) * bnbUsd; const dn1 = (onePctSize(rTok, 1 / 0.99) / TAX_KEEP) * price; // Two different things per size, the way the dashboard splits them: // impact = how far this trade alone moves the price. The 3% tax is taken from the // tokens, never from the reserves, so it moves nothing; the 0.25% fee stays // in the pool and counts. A sell moves less — the pair only sees 97%. // cost = what the trader gives up against spot (fill + fee + tax). Not symmetric: // on a buy the tax hits the tokens leaving, on a sell the ones going in. // Both tend to 1 - TAX*FEE = 3.24% as the size goes to zero. const depth = DEPTH_SIZES.map(usd => { const dBnb = usd / bnbUsd; const dTok = usd / price; const sTok = dTok * TAX_KEEP; return { usd, impactBuy: ((rBnb + dBnb) * (rBnb + LP_FEE * dBnb) / (rBnb * rBnb) - 1) * 100, impactSell: (rTok * rTok / ((rTok + sTok) * (rTok + LP_FEE * sTok)) - 1) * 100, costBuy: (1 - TAX_KEEP * LP_FEE * rBnb / (rBnb + LP_FEE * dBnb)) * 100, costSell: (1 - TAX_KEEP * LP_FEE * rTok / (rTok + TAX_KEEP * LP_FEE * dTok)) * 100, }; }); // The block this was read at. A chat message stays in the group forever, so it // has to say which state of the chain it describes — otherwise a reader three // hours later compares it against a pool that has moved since. let block = null; try { block = parseInt(blockHex, 16) || null; } catch { } return { price, rBnb, rTok, bnbSide, tvl, mcap, lpBurnedPct, up1, dn1, depth, block }; } // ==================== BUY BOT ==================== // EVERY BRAIN IS DRAWN (2026-09-21). Each 🧠 = $10, each 🔥 = $2. Both bars // used to stop at 60 and spell the rest ("×141") — on exactly the alerts the // row is there for: the THUNDER buy of that night arrived as sixty brains and // a number. The sixty was a guess at Telegram's limit; the limit was then // MEASURED against Telegram with /previewbuy: a photo caption holds 1024 // characters counted as CODE POINTS after the HTML is parsed (a caption of // 1024 went out with its picture, one of 1025 came back "message caption is // too long"; in UTF-16 units that same caption was 1,859 long, so it is not // units). A 🧠 or 🔥 is one. The rest of the alert is known when the bar is // made, so the bar takes the room that is really left — about 750 brains (a // $7,500 buy) and about 850 flames (a $1,700 burn). Past that it draws what // fits and stops: the picture always comes with the alert, and the amount is // in the text below anyway — no "×N". Pure, exported for the pins. const CAPTION_CHARS = 1024, BAR_MARGIN = 4; const visibleText = (html) => String(html).replace(/<[^>]+>/g, '').replace(/&(amp|lt|gt|quot);/g, '&'); const codePoints = (s) => [...s].length; // The row IS the amount, at every size: $3,000 is 300 brains, a $400 burn is // 200 flames. The room is only the ceiling — it matters from the top tiers on // (a KRAKEN buy past about $7,500, a SUPERNOVA burn past about $1,700), where // the row stops at the last one that fits. (100ae40 filled the caption from // the top tier on whatever the size; that was a misreading of the operator's // sentence, corrected the same day.) export function emojiBar(emoji, count, restHtml) { const room = Math.max(1, Math.floor((CAPTION_CHARS - codePoints(visibleText(restHtml)) - 1 - BAR_MARGIN) / codePoints(emoji))); return emoji.repeat(Math.min(count, room)); } const KRAKEN_USD = 2500, SUPERNOVA_USD = 250; export const buyBar = (usdValue, restHtml) => emojiBar('🧠', Math.max(Math.floor(usdValue / 10), 1), restHtml); // the count exact below $2 as well (2026-10-29, the post fact-check: a $0.35 burn drew one flame; the rule is 1 per $2) export const burnBar = (usdValue, restHtml) => emojiBar('🔥', Math.max(Math.floor(usdValue / 2), 0), restHtml); function getBuyEmojis(usdValue) { let icon; if (usdValue >= KRAKEN_USD) icon = '🦑 KRAKEN BUY!'; else if (usdValue >= 1000) icon = '⚡ THUNDER BUY!'; else if (usdValue >= 500) icon = '🐋 WHALE BUY!'; else if (usdValue >= 250) icon = '🚀 HUGE BUY!'; else if (usdValue >= 150) icon = '💎 BIG BUY!'; else icon = '💰 NICE BUY!'; return { icon }; } function getBurnEmojis(usdValue) { let icon; if (usdValue >= SUPERNOVA_USD) icon = '💥 SUPERNOVA BURN!'; else if (usdValue >= 150) icon = '☄️ APOCALYPSE BURN!'; else if (usdValue >= 50) icon = '💀 MEGA BURN!'; else if (usdValue >= 15) icon = '🌋 BIG BURN!'; else if (usdValue >= 5) icon = '🕯️ NICE BURN!'; else icon = '♻️ BURN'; return { icon }; } // One-shot fetch of the full NFT state (tiers + drops) from the dashboard API. // Returns { minted, cap, drops } or null on failure. async function fetchNftState() { try { const res = await fetch(NFT_STATE_URL, { cf: { cacheTtl: 0, cacheEverything: false } }); if (!res.ok) { console.error('[NFT state] non-ok', res.status); return null; } const body = await res.json(); return { minted: Array.isArray(body.minted) ? body.minted : null, cap: Array.isArray(body.cap) ? body.cap : null, drops: Array.isArray(body.drops) ? body.drops : [], holders: typeof body.holders === 'number' ? body.holders : null, }; } catch (e) { console.error('[NFT state] err', e.message || e); return null; } } // 10-char ▰░ progress bar // ONE TRANSACTION, ONE BUY (2026-09-18). An aggregator splits an order into // several swaps on this pair inside one transaction (0x531f2bfb…: two swaps of // 0.2436 + 0.2427 WBNB, $366 together). Read log by log with the transaction // marked done after its first log, that buy was a $184 one — alerted as half // of itself and given the NFT of the tier below. The logs of one pair are // folded per transaction first: WBNB in and BOBAI out summed over its buy // swaps, in the order the transactions appeared. Sells (the opposite // direction) carry nothing in these two fields and fold to nothing. Pure. export function foldBuysByTx(logs) { const byTx = new Map(); for (const log of logs || []) { const d = String(log.data || '').slice(2); if (d.length < 256) continue; const amount1In = BigInt('0x' + d.slice(64, 128)); // WBNB in const amount0Out = BigInt('0x' + d.slice(128, 192)); // BOBAI out if (!(amount1In > 0n && amount0Out > 0n)) continue; const tx = log.transactionHash; const b = byTx.get(tx) || { transactionHash: tx, blockNumber: log.blockNumber, amount1In: 0n, amount0Out: 0n, swaps: 0 }; b.amount1In += amount1In; b.amount0Out += amount0Out; b.swaps += 1; byTx.set(tx, b); } return [...byTx.values()]; } // WHO BOUGHT (2026-09-18). The alert named the transaction's sender; the // minter follows the tokens to the wallet that ends up holding them // (resolveBuyer). Through a relayer or an aggregator the two differ — 8 of the // last 100 drops, a $1,390 buy among them: the alert pointed at a relayer while // the NFT went to the buyer. Once the drop is known, its recipient is the buyer // the alert names; without a drop (sold out, mint pending) the sender stays. export function alertTrade(pending, drop) { const to = drop && typeof drop.to === 'string' && /^0x[a-fA-F0-9]{40}$/.test(drop.to) ? drop.to : null; return to ? { ...pending, buyer: to } : pending; } // A TRACKED WALLET'S BUY IS ONE MESSAGE (operator, 2026-10-15: a buy of $100+ by a wallet the whale watcher tracks came // into the official group twice — the buy alert with its picture, then the watcher's text of the same buy). The buy // alert tells it, with one line saying who the buyer is to the watcher; the watcher's text of that buy stays internal. // Both sides read the same transaction receipt: the BNB that went into the pair and who got BOBAI out of it. Pure. export function pairBuyOfReceipt(receipt) { if (!receipt || !Array.isArray(receipt.logs)) return null; const low = (s) => String(s || '').toLowerCase(); const topicAddr = (t) => '0x' + low(t).slice(26); const swaps = receipt.logs.filter((l) => low(l.address) === BOBAI_PAIR && low((l.topics || [])[0]) === SWAP_TOPIC); const fold = foldBuysByTx(swaps)[0]; const recipients = new Set(); for (const l of receipt.logs) { const t = l.topics || []; if (low(l.address) === low(BOBAI_TOKEN) && low(t[0]) === TRANSFER_TOPIC && topicAddr(t[1]) === BOBAI_PAIR) recipients.add(topicAddr(t[2])); } return { from: low(receipt.from), bnbIn: fold ? fold.amount1In : 0n, recipients }; } // The buy alert's own rule: $100+ of BNB into the pair, the sender not one of our wallets. Pure. export function buyAlertTells(pb, bnbUsd) { return !!pb && pb.bnbIn > 0n && !IGNORED_WALLETS.has(pb.from) && bnbUsd > 0 && Number(pb.bnbIn) / 1e18 * bnbUsd >= 100; } // The line under the buyer: what the watcher calls the wallet, and its place from 5M up (exact there). Pure. // A wallet under 5M says which cluster it belongs to, as the watcher's text does (operator, 2026-10-15): `cluster` is // its label, '' for a wallet on its own, undefined when unknown (nothing said). export function trackedBuyLine({ addr, buyer, bal = null, rank = null, contract = false, cluster }) { const eyes = !contract && !(bal >= 5_000_000); const who = (contract ? '🏦 Tracked contract' : bal >= 10_000_000 ? '🐋 Tracked whale' : bal >= 5_000_000 ? '🐬 Tracked holder 5M+' : '👀 Tracked wallet') + (eyes && cluster !== undefined ? (cluster ? ` · 🔗 Cluster ${cluster}` : ' · 🔸 Solo') : ''); const other = addr && buyer && String(addr).toLowerCase() !== String(buyer).toLowerCase() ? ` ${shortenAddress(addr)}` : ''; return `\n${who}${other}${rank && bal >= 5_000_000 ? ` · 🏅 #${rank} holder` : ''}`; } function nftProgressBar(minted, cap) { if (cap <= 0) return '░░░░░░░░░░'; const filled = Math.min(10, Math.round((minted / cap) * 10)); return '▰'.repeat(filled) + '░'.repeat(10 - filled); } // `chatId` is the group, always — except for /previewbuy, which shows the // operator privately what an alert of a given size looks like. // THE PICTURE IS NEVER GIVEN UP FOR THE ROW. The row is sized to the measured // limit, so this should never fire; it is the net under it. If Telegram ever // calls a caption too long all the same (its counting changed, a character // this code counts as one and Telegram as two), the alert is sent again with // half the row, and again with a quarter, before the text-only fallback is // even considered. Any other refusal goes straight to that fallback, as before. export async function sendPhotoWithRow(chatId, photo, row, rest, retry = true) { let chars = [...row], shortened = false; for (let attempt = 0; attempt < 3; attempt++) { const res = await tg('sendPhoto', { chat_id: chatId, photo, caption: `${chars.join('')}\n${rest}`, parse_mode: 'HTML' }); if (res?.ok === true) return { ok: true, row: chars.join(''), shortened }; lastPhotoRefusal = res?.description || 'refused'; if (!retry || !/caption is too long/i.test(lastPhotoRefusal) || chars.length <= 1) break; chars = chars.slice(0, Math.floor(chars.length / 2)); shortened = true; } return { ok: false, row: chars.join(''), shortened }; } // `uncapped` is the preview's alone: it draws every brain whatever the room, // to show what Telegram does with a caption past its limit. // `ctxLine` (2026-10-09): buyContextLine's one line under the buyer. It is part of `rest`, so the brain row is sized // with it in — the count stays right; only past the caption's room does the row stop earlier. let lastPhotoRefusal = null, lastCaption = null; async function postBuyAlert(trade, burnedPct, nftLine = '', chatId = TG_CHAT_ID, uncapped = false, ctxLine = '') { const { bnbAmount, bobaiAmount, usdValue, buyer, txHash } = trade; const { icon } = getBuyEmojis(usdValue); const pricePerToken = bobaiAmount > 0 ? usdValue / bobaiAmount : 0; const rest = `${icon} 🪙 ${formatNumber(bobaiAmount * 0.97)} BOBAI 💎 ${bnbAmount.toFixed(4)} BNB (${formatUsd(usdValue)}) 💵 Price: $${pricePerToken.toFixed(8)} 👤 ${shortenAddress(buyer)}${ctxLine}${nftLine} 🔗 TX · Chart · Four.Meme ${burnedPct && burnedPct !== '?' ? `🔥 Burned: ${burnedPct}% of supply` : ''}`.trimEnd(); // One alert, one message: every brain that fits the caption, the count // spelled out only past that. const bar = uncapped ? '🧠'.repeat(Math.max(Math.floor(usdValue / 10), 1)) : buyBar(usdValue, rest); let message = `${bar}\n${rest}`; lastPhotoRefusal = null; lastCaption = { code_points: [...visibleText(message)].length, utf16_units: visibleText(message).length }; // 1) Try the rich photo alert try { const sent = await sendPhotoWithRow(chatId, PHOTO_BIGBUY, bar, rest, !uncapped); if (sent.ok) { console.log('[BUY] photo alert sent', txHash, sent.shortened ? '(row shortened)' : ''); return 'photo'; } message = `${sent.row}\n${rest}`; console.error('[BUY] sendPhoto failed, falling back to text:', lastPhotoRefusal); } catch (err) { console.error('[BUY] sendPhoto threw, falling back to text:', err.message || err); } // 2) Fallback: text-only alert so a buy alert ALWAYS goes out, even if the // photo file_id is ever rejected by Telegram. Same content, no image. try { const textRes = await tg('sendMessage', { chat_id: chatId, text: message, parse_mode: 'HTML', disable_web_page_preview: true, }); if (textRes?.ok === true) { console.log('[BUY] text fallback sent', txHash); return 'text'; } console.error('[BUY] text fallback failed:', JSON.stringify(textRes)); } catch (err) { console.error('[BUY] text fallback threw:', err.message || err); } return false; } // ==================== BURN BOT ==================== async function postBurnAlert(newBurned, prevBurned, totalSupply, tokenPrice, chatId = TG_CHAT_ID) { try { const burnedDelta = newBurned - prevBurned; const hasPrice = tokenPrice && tokenPrice > 0; // NO PRICE, NO ALERT (2026-10-09): without it the bar showed one flame for any burn and "(n/a)". Nothing is // stored as told, so the next minute tells it with its price. if (!hasPrice) return false; const burnedUsd = hasPrice ? burnedDelta * tokenPrice : 0; const burnedUsdStr = hasPrice ? formatUsd(burnedUsd) : 'n/a'; const percent = totalSupply > 0 ? (newBurned / totalSupply * 100).toFixed(1) : '?'; // When price unavailable, fall back to the smallest burn emoji bucket const { icon } = getBurnEmojis(burnedUsd); const rest = `${icon} 🪙 +${formatNumber(burnedDelta)} BOBAI burned (${burnedUsdStr}) 📊 Total burned: ${formatNumber(newBurned)} BOBAI (≈${formatUsd(newBurned * tokenPrice)}) 🔥 ${percent}% of total supply 🔗 View Burns · Chart`; const bar = burnBar(burnedUsd, rest); let message = `${bar}\n${rest}`; lastPhotoRefusal = null; lastCaption = { code_points: [...visibleText(message)].length, utf16_units: visibleText(message).length }; // 1) The photo alert try { const sent = await sendPhotoWithRow(chatId, PHOTO_BURN, bar, rest); if (sent.ok) return 'photo'; message = `${sent.row}\n${rest}`; console.error('[BURN] sendPhoto failed, falling back to text:', lastPhotoRefusal); } catch (err) { console.error('[BURN] sendPhoto threw, falling back to text:', err.message || err); } // 2) Text only, like the buy alert: a burn is always told, even on a day // Telegram refuses the picture. const textRes = await tg('sendMessage', { chat_id: chatId, text: message, parse_mode: 'HTML', disable_web_page_preview: true, }); if (textRes?.ok !== true) console.error('[BURN] text fallback failed:', JSON.stringify(textRes)); return textRes?.ok === true ? 'text' : false; } catch (err) { console.error('[POST BURN ERROR]', err.message || err); return false; } } // ==================== WHALE ADMIN COMMANDS ==================== const ADDR_RE = /0x[a-fA-F0-9]{40}/; const ADDR_REG = /0x[a-fA-F0-9]{40}/g; async function loadTrackedWallets(env) { try { const raw = await env.KV.get('tracked_wallets'); if (raw) { // Self-heal: filter never-track on read so addresses added to the never-track // set in later deploys (e.g. the BOBAI contract) drop out automatically. return JSON.parse(raw).filter(a => !WHALE_NEVER_TRACK.has(a)); } } catch {} return [...DEFAULT_TRACKED]; } async function saveTrackedWallets(env, list) { // Dedup + lowercase, exclude never-track const cleaned = [...new Set(list.map(a => a.toLowerCase()))] .filter(a => /^0x[a-f0-9]{40}$/.test(a) && !WHALE_NEVER_TRACK.has(a)); await env.KV.put('tracked_wallets', JSON.stringify(cleaned)); return cleaned; } // CONTRACTS THAT HOLD LIKE A WHALE (2026-10-06). The watch-set took people only, // so a contract that buys and holds was invisible: a full scan of every BOBAI // transfer found 0xa399…9d9c, an unnamed contract owned by 0xffc4…f56c, with // 26.3M BOBAI (2.6% of supply) bought straight from the pair in 41 buys and // one sale — none of them ever alerted. A contract that HOLDS 10M+ is a holder; // a router passes tokens through in one transaction and holds dust, and a pool // (it answers token0()) is a market, never a holder. Kept apart from the // wallets so /whalecleanup and the 10M rule for people stay as they are. const DEFAULT_CONTRACTS = [ '0xa3996b9977cdbf77c6f7717894d58a66a6789d9c', // unnamed trading/vault contract, owner 0xffc4…f56c — 26.3M on 2026-10-06 ]; async function loadTrackedContracts(env) { try { const raw = await env.KV.get('tracked_contracts'); if (raw) return JSON.parse(raw).filter(a => !WHALE_NEVER_TRACK.has(a)); } catch {} return [...DEFAULT_CONTRACTS]; } async function saveTrackedContracts(env, list) { const cleaned = [...new Set(list.map(a => a.toLowerCase()))] .filter(a => /^0x[a-f0-9]{40}$/.test(a) && !WHALE_NEVER_TRACK.has(a)); await env.KV.put('tracked_contracts', JSON.stringify(cleaned)); return cleaned; } // A pool answers token0() with an address; anything else (no such function, // a revert, an empty answer) is not a pool. Pure on the eth_call result. export function answersAsPool(ret) { return typeof ret === 'string' && /^0x0{24}[0-9a-f]{40}$/i.test(ret) && !/^0x0{64}$/.test(ret); } async function isPool(addr) { try { return answersAsPool(await rpcCall('eth_call', [{ to: addr, data: '0x0dfe1681' }, 'latest'])); } catch { return true; } // unknown: never take a market for a holder } async function loadWalletEdges(env) { try { const raw = await env.KV.get('wallet_edges'); if (raw) return JSON.parse(raw); } catch {} return {}; } async function saveWalletEdges(env, edges) { await env.KV.put('wallet_edges', JSON.stringify(edges)); } // ---- Daily whale balance snapshots (holdings history + trend) ---- // One snapshot per UTC day: live balanceOf() of every tracked wallet, stored in // KV so 1d/7d/30d holdings-trends can be computed without an archive node. // Correctness rules: // - Deltas compare only wallets present in BOTH snapshots — the watchlist grows // over time, comparing raw totals would fake an "inflow" whenever a new whale // gets tracked. // - A delta window is only reported when a snapshot of that actual age exists // (±12h) — a 2-day-old history never masquerades as a "7d" trend. // - If any balanceOf fails, the whole snapshot is aborted (retried next run) — // a failed call must never be recorded as balance 0. const WHALE_SNAPSHOTS_MAX = 120; // Two rules for a quieter, self-tidying watch-set (the operator, 2026-09-10: // "übersichtlicher"). Both are pure so a script can pin them. // // Quiet floor: a tracked wallet's buy, sell, burn, transfer-in or internal // move under $5 is logged for the recap but not posted as an alert. One // member's wallet had produced 84 alerts for $257 in total, most under a // dollar. A transfer-out to a fresh wallet is never quiet: dust there is the // pre-funding signal the cascade exists for. A move with no price (usd 0) is // posted — the floor never hides what it cannot price. const WHALE_QUIET_USD = 5; const WHALE_QUIET_KINDS = new Set(['BUY', 'SELL', 'BURN', 'TRANSFER_IN', 'INTERNAL_T']); export function isQuietMove(kind, usdValue) { return WHALE_QUIET_KINDS.has(kind) && usdValue > 0 && usdValue < WHALE_QUIET_USD; } // Retire rule: a wallet at zero in each of the last N daily snapshots leaves // the watch-set at the daily recap. Its edges stay in KV, and the cascade or // the 10M crossing brings it back the moment it moves again — so a spent // cluster wallet costs nothing to drop and nothing to miss. Eight wallets had // been empty for 37–58 days on 2026-09-10. const WHALE_RETIRE_EMPTY_DAYS = 7; export function walletsEmptyFor(snaps, days = WHALE_RETIRE_EMPTY_DAYS) { if (!Array.isArray(snaps) || snaps.length < days) return []; const tail = snaps.slice(-days); const last = tail[tail.length - 1]; return Object.keys(last.wallets || {}).filter((a) => tail.every((s) => s.wallets && s.wallets[a] !== undefined && Number(s.wallets[a]) <= 0)); } // What a move does to the wallet's own bag (2026-10-06): "sold 37M" says // little until it says "sold all of it" or "a tenth of the bag". `balAfter` is // the balance read after the move; an outflow came from balAfter + amount, // an inflow went onto balAfter - amount. Null when it cannot be told. Pure. export function positionNote(kind, amount, balAfter) { if (balAfter == null || !(amount > 0)) return null; const out = kind === 'SELL' || kind === 'BURN' || kind === 'TRANSFER_OUT' || kind === 'INTERNAL_T'; const pct = (x) => (x >= 10 ? Math.round(x) : Math.round(x * 10) / 10) + '%'; if (out) { const before = balAfter + amount; if (balAfter < 1) return 'the whole bag — wallet now empty'; return `${pct(amount / before * 100)} of the bag`; } const before = balAfter - amount; if (before < 1) return 'a new position — the wallet held none before'; return `bag +${pct(amount / before * 100)}`; } // A holder's place among everybody the watcher follows (all holders of 5M+, // so the place is exact from there up; the LP and the burn address are no // holders). `bal` is the balance to rank — before or after a move. Pure. export function holderRank(balByAddr, addr, bal) { let above = 0; for (const [a, b] of balByAddr) if (a !== addr && Number(b) > bal) above++; return above + 1; } // PATTERNS (2026-10-06): three moves of one kind by one wallet inside 24 h are // one story — a whale buying in, selling in pieces, or handing its bag out to // fresh wallets. The first two post as ever; the third posts ONE alert that // tells the whole run; later ones that day fold into it (logged, in the recap) // unless a single one is big on its own ($1,000+ or a tenth of the bag). const PATTERNS = { BUY: { name: 'ACCUMULATING', icon: '📈', word: 'buy' }, SELL: { name: 'SELLING IN PIECES', icon: '📉', word: 'sell' }, TRANSFER_OUT: { name: 'DISTRIBUTING', icon: '📦', word: 'transfer out' } }; const PATTERN_AT = 3; export function moverOf(e) { return e.kind === 'SELL' || e.kind === 'BURN' || e.kind === 'TRANSFER_OUT' || e.kind === 'INTERNAL_T' || e.kind === 'EX_WHALE' ? e.from : e.to; } // The earlier moves of this kind by this wallet in the last 24 h (quiet ones // do not count: under $5 is no story). `n` counts the move at hand too. export function patternStep(events, addr, kind, now = Date.now()) { const prior = (events || []).filter((e) => e.kind === kind && !e.quiet && moverOf(e) === addr && (e.ts || 0) >= now - 24 * 3600e3); return { n: prior.length + 1, prior }; } export function foldMove(n, usd, bagShare) { if (n < PATTERN_AT) return 'post'; if (n === PATTERN_AT) return 'pattern'; return usd >= 1000 || bagShare >= 0.1 ? 'post' : 'fold'; } // Who entered and who left the ten largest holders between the last two daily // snapshots (the people and contracts the watcher follows). Pure. export function top10Shift(snaps) { if (!Array.isArray(snaps) || snaps.length < 2) return null; const top = (s) => Object.entries(s.wallets || {}).sort((x, y) => Number(y[1]) - Number(x[1])).slice(0, 10).map(([a]) => a); const before = top(snaps[snaps.length - 2]), now = top(snaps[snaps.length - 1]); return { entered: now.filter((a) => !before.includes(a)), left: before.filter((a) => !now.includes(a)), leader: now[0] || null, leaderBal: now[0] ? Number(snaps[snaps.length - 1].wallets[now[0]]) : 0 }; } // Days a wallet's balance stood still before this move, read from the daily // snapshots (2026-10-06): a whale that wakes after two months is news, a // trader's tenth move today is not. The balance before the move must match // the latest snapshot (a move since the snapshot means it was not asleep), // no logged event may touch it since the still stretch began, and only a // stretch of `minDays` or more counts. The days are a floor ("66+"): the // snapshot says when the change was seen, not the hour it happened. Pure. export function dormantDays(snaps, addr, balBefore, events = [], now = Date.now(), minDays = 7) { if (!Array.isArray(snaps) || !snaps.length || balBefore == null) return null; const a = String(addr).toLowerCase(); const val = (s) => (s && s.wallets && s.wallets[a] !== undefined ? Number(s.wallets[a]) : undefined); const last = val(snaps[snaps.length - 1]); if (last === undefined || Math.abs(last - balBefore) > Math.max(1, balBefore * 0.001)) return null; let i = snaps.length - 1; while (i > 0 && val(snaps[i - 1]) !== undefined && Math.abs(val(snaps[i - 1]) - last) <= Math.max(1, last * 0.001)) i--; const since = snaps[i].ts; if ((events || []).some((e) => (e.ts || 0) >= since && (e.from === a || e.to === a))) return null; const days = Math.floor((now - since) / 86400e3); return days >= minDays ? days : null; } async function retireEmptyWallets(env, snaps, tracked, save = saveTrackedWallets) { const empty = new Set(walletsEmptyFor(snaps)); const dropped = tracked.filter((a) => empty.has(a)); if (!dropped.length) return []; await save(env, tracked.filter((a) => !empty.has(a))); console.log('[WHALE] retired', dropped.length, 'wallets empty for', WHALE_RETIRE_EMPTY_DAYS, 'days:', dropped.map((a) => a.slice(0, 10)).join(' ')); return dropped; } async function loadWhaleSnapshots(env) { try { const raw = await env.KV.get('whale_snapshots'); if (raw) return JSON.parse(raw); } catch {} return []; } async function getBobaiBalanceStrict(addr) { const data = '0x70a08231' + '0'.repeat(24) + addr.slice(2).toLowerCase(); const r = await rpcCall('eth_call', [{ to: BOBAI_TOKEN, data }, 'latest']); if (r === null) throw new Error('balanceOf failed for ' + addr); return BigInt(r); } async function takeWhaleSnapshotIfDue(env, tracked) { const snaps = await loadWhaleSnapshots(env); const today = new Date().toISOString().slice(0, 10); if (snaps.length && snaps[snaps.length - 1].date === today) return snaps; const wallets = {}; let total = 0; for (let i = 0; i < tracked.length; i += 8) { const chunk = tracked.slice(i, i + 8); const bals = await Promise.all(chunk.map(a => getBobaiBalanceStrict(a))); // throws on any failure → abort chunk.forEach((a, j) => { const t = Number(bals[j] / 10n ** 18n); wallets[a] = t; total += t; }); } snaps.push({ date: today, ts: Date.now(), total, wallets }); const trimmed = snaps.slice(-WHALE_SNAPSHOTS_MAX); await env.KV.put('whale_snapshots', JSON.stringify(trimmed)); console.log('[WHALE-SNAP] snapshot', today, '-', tracked.length, 'wallets,', total, 'BOBAI'); return trimmed; } // Change vs. the snapshot closest to `days` ago (±12h), intersection basis. function snapshotDelta(snaps, days) { if (snaps.length < 2) return null; const last = snaps[snaps.length - 1]; const target = last.ts - days * 86400e3; let ref = null; for (const s of snaps.slice(0, -1)) { if (Math.abs(s.ts - target) <= 12 * 3600e3 && (!ref || Math.abs(s.ts - target) < Math.abs(ref.ts - target))) ref = s; } if (!ref) return null; let before = 0, after = 0, n = 0; for (const a of Object.keys(last.wallets)) { if (ref.wallets[a] === undefined) continue; before += ref.wallets[a]; after += last.wallets[a]; n++; } if (!n) return null; return { window_days: days, wallets_compared: n, bobai_change: after - before, percent_change: before > 0 ? Math.round((after - before) / before * 10000) / 100 : null, }; } // `tracked`, when given, narrows the split to wallets still on the watch-set: // the day's snapshot is taken before the retire rule drops the empty ones, // so until the next snapshot it would still count them (2026-09-10 06:07: // 26 tracked, "8 empty"). export function snapshotHoldings(snaps, tracked = null) { if (!snaps.length) return null; const last = snaps[snaps.length - 1]; const keep = tracked ? new Set(tracked.map((a) => String(a).toLowerCase())) : null; const wallets = Object.fromEntries(Object.entries(last.wallets || {}).filter(([a]) => !keep || keep.has(a.toLowerCase()))); const vals = Object.values(wallets); const total = keep ? vals.reduce((s, v) => s + Number(v), 0) : last.total; return { as_of_date: last.date, tracked_total_bobai: total, percent_of_total_supply: Math.round(total / 1e9 * 10000) / 100, // The watchlist keeps a wallet after it sells or moves out (a cluster's // spent wallets tell where the whale went), so "tracked" is not "whales": // the split says how many still hold the threshold, and how many are empty. wallets_tracked: vals.length, wallets_at_or_above_threshold: vals.filter((v) => Number(v) >= 10_000_000).length, wallets_below_threshold: vals.filter((v) => Number(v) > 0 && Number(v) < 10_000_000).length, wallets_empty: vals.filter((v) => Number(v) <= 0).length, change_1d: snapshotDelta(snaps, 1), change_7d: snapshotDelta(snaps, 7), change_30d: snapshotDelta(snaps, 30), top10: top10Shift(snaps), method: 'Daily balanceOf() snapshot of every tracked wallet. Deltas compare only wallets present in both snapshots, so watchlist growth never fakes an inflow; a window is only reported once history of that actual age exists.', }; } // ---- Whale event log (for 24h summaries) ---- // Keeps the last 500 alert-worthy events (raw, with timestamp) so we can render // rolling 24h breakdowns without re-scanning the chain. const WHALE_EVENTS_MAX = 500; async function loadWhaleEvents(env) { try { const raw = await env.KV.get('whale_events'); if (raw) return JSON.parse(raw); } catch {} return []; } async function saveWhaleEvents(env, events) { await env.KV.put('whale_events', JSON.stringify(events.slice(-WHALE_EVENTS_MAX))); } function recentEvents(events, hours = 24) { const cutoff = Date.now() - hours * 60 * 60 * 1000; return events.filter(e => (e.ts || 0) >= cutoff); } // addrs of wallets that moved (sent OR received) in the last `hours` function activeAddrSet(events, hours = 24) { const r = recentEvents(events, hours); const s = new Set(); for (const e of r) { if (e.from) s.add(e.from); if (e.to) s.add(e.to); } return s; } // 24h activity summary for a single cluster (set of addresses). Returns net // USD flow + event count, considering only events where at least one side is // in the cluster. Internal moves count as 1 event, no net change. function summarizeClusterActivity(events, clusterSet, hours = 24) { const r = recentEvents(events, hours); let count = 0, usdIn = 0, usdOut = 0, internal = 0; for (const e of r) { const fromIn = e.from && clusterSet.has(e.from); const toIn = e.to && clusterSet.has(e.to); if (!fromIn && !toIn) continue; count++; const u = e.usdValue || 0; if (e.kind === 'INTERNAL_T') { if (fromIn && toIn) internal++; // intra-cluster, neutral else if (fromIn) usdOut += u; // crossed to another cluster else usdIn += u; // crossed from another cluster continue; } if (e.kind === 'BUY' || e.kind === 'TRANSFER_IN') { if (toIn) usdIn += u; } else if (e.kind === 'SELL' || e.kind === 'BURN' || e.kind === 'TRANSFER_OUT') { if (fromIn) usdOut += u; } } return { count, usdIn, usdOut, netUsd: usdIn - usdOut, internal }; } function summarize24h(events) { const r = recentEvents(events, 24); const counts = { BUY: 0, SELL: 0, BURN: 0, INTERNAL_T: 0, TRANSFER_OUT: 0, TRANSFER_IN: 0, NEW_WHALE: 0, EX_WHALE: 0, }; let usdIn = 0, usdOut = 0; let amtIn = 0, amtOut = 0; let quiet = 0, folded = 0; const patterns = []; for (const e of r) { counts[e.kind] = (counts[e.kind] || 0) + 1; if (e.folded) folded++; if (e.pattern) patterns.push(e); // Events logged before the floor existed carry no flag; judge them by // the same rule so the recap reads the same across the change. if (e.quiet || isQuietMove(e.kind, e.usdValue || 0)) quiet++; const u = e.usdValue || 0; const a = e.amount || 0; if (e.kind === 'BUY' || e.kind === 'TRANSFER_IN') { usdIn += u; amtIn += a; } if (e.kind === 'SELL' || e.kind === 'BURN' || e.kind === 'TRANSFER_OUT') { usdOut += u; amtOut += a; } } // Top 3 movers ranked by USD impact (any kind with amount, ignore NEW/EX which are balance snapshots) // Quiet moves (under the floor) are counted above but never top anything. const movers = r.filter(e => !e.quiet && !isQuietMove(e.kind, e.usdValue || 0) && ['BUY','SELL','BURN','TRANSFER_OUT','TRANSFER_IN','INTERNAL_T'].includes(e.kind)) .slice() .sort((a, b) => (b.usdValue || 0) - (a.usdValue || 0)) .slice(0, 3); return { total: r.length, counts, quiet, folded, patterns, usdIn, usdOut, netUsd: usdIn - usdOut, amtIn, amtOut, netAmt: amtIn - amtOut, movers, }; } function netEmoji(net) { if (net > 0) return '🟢'; if (net < 0) return '🔴'; return '⚪'; } function netStr(net) { const sign = net > 0 ? '+' : (net < 0 ? '-' : ''); return `${sign}${formatUsd(Math.abs(net))}`; } const KIND_LABEL = { BUY: { icon: '🟢', label: 'Buy' }, SELL: { icon: '🔴', label: 'Sell' }, BURN: { icon: '🔥', label: 'Burn' }, TRANSFER_OUT: { icon: '🟠', label: 'Out' }, TRANSFER_IN: { icon: '⚪', label: 'In' }, INTERNAL_T: { icon: '🟣', label: 'Internal' }, NEW_WHALE: { icon: '💡', label: 'New whale' }, EX_WHALE: { icon: '💀', label: 'Ex-whale' }, }; // Compact "who is this wallet" descriptor for alert FROM/TO lines. // Special wallets get a human label; tracked wallets get cluster tag + balance + USD. function describeAddr(addr, clusterTag, balTokens, priceUsd) { const a = addr.toLowerCase(); if (a === BOBAI_PAIR.toLowerCase()) return 'PancakeSwap LP'; if (a === DEAD.toLowerCase()) return '💀 DEAD'; if (a === BOBAI_TOKEN.toLowerCase()) return 'BOBAI contract'; if (a === '0xdefc0e900dfc83e207902cf22265ae63f94c01ce') return 'Buyback bot (tax collector)'; if (a === '0x15ba17075ef5e0736292b030e3715d9100fe3d38') return 'Dev-buyback bot'; if (a === '0x5e4102520a71b2aa18a1208330d4848dea4bd105') return 'WC26 prize pool'; if (a === '0x5c82d2f12ee6ac09297784f94ebf9331277bdc3c') return 'Dev personal'; const tag = clusterTag ? `🔗${clusterTag}` : 'Solo'; if (balTokens == null) return tag; const usdPart = priceUsd ? ` · ${formatUsd(balTokens * priceUsd)}` : ''; return `${tag} · ${formatNumber(balTokens)} BOBAI${usdPart}`; } // The wallets of a group that hold under 5M, on one line: address (first // and last characters, like every other line) and balance in millions, a 🟢 when the wallet moved in the last 24 h. Empty // wallets read "0" until the retire rule drops them. export function renderSmallWalletsLine(addrs, balByAddr, active = new Set()) { const m = (t) => (t >= 1e6 ? (t / 1e6).toFixed(t >= 1e7 ? 0 : 1) + 'M' : t > 0 ? (t / 1e3).toFixed(0) + 'K' : '0'); const sorted = addrs.slice().sort((x, y) => (balByAddr.get(y) || 0) - (balByAddr.get(x) || 0)); const parts = sorted.map((a) => `${shortenAddress(a)} ${m(balByAddr.get(a) || 0)}${active.has(a) ? '🟢' : ''}`); return `💀 below 5M (${addrs.length}): ${parts.join(' · ')}`; } function describeMover(e) { const k = KIND_LABEL[e.kind] || { icon: '·', label: e.kind }; const amt = formatNumber(e.amount || 0); const usd = e.usdValue ? formatUsd(e.usdValue) : 'n/a'; const who = shortenAddress(e.kind === 'SELL' || e.kind === 'BURN' || e.kind === 'TRANSFER_OUT' ? e.from : e.to); const link = `${who}`; return `${k.icon} ${link} · ${amt} BOBAI (${usd})`; } // Full daily recap — used by /whales24h AND by the auto-posted daily summary. // `withDateStamp` true → header reads "Daily Recap · YYYY-MM-DD" (auto-post). // One screen (the operator, 2026-09-10): holdings first, then the day's flow // as one line per kind, the top moves, and what the watch-set did to itself. // `holdings` is snapshotHoldings(); `retired` the wallets dropped today. export function renderDailyRecap(events, tracked, price, withDateStamp, holdings = null, retired = [], contracts = 0) { const sum = summarize24h(events); const c = sum.counts; const head = withDateStamp ? `📅 Daily Whale Recap · ${new Date().toISOString().slice(0, 10)}` : `📅 Whale Watcher · Last 24h`; const lines = [head]; // Holdings: what the watch-set holds and where it is going. if (holdings) { const d = holdings.change_7d || holdings.change_1d; const trend = d ? ` · ${d.window_days}d ${d.bobai_change >= 0 ? '+' : ''}${formatNumber(d.bobai_change)} (${d.percent_change >= 0 ? '+' : ''}${d.percent_change}%)` : ''; lines.push(`💼 ${formatNumber(holdings.tracked_total_bobai)} BOBAI tracked · ${holdings.percent_of_total_supply}% of supply${trend}`); const parts = [`${holdings.wallets_at_or_above_threshold} hold 10M+`]; if (holdings.wallets_below_threshold) parts.push(`${holdings.wallets_below_threshold} below`); if (holdings.wallets_empty) parts.push(`${holdings.wallets_empty} empty`); const cn = contracts ? ` + ${contracts} contract${contracts === 1 ? '' : 's'}` : ''; lines.push(`🐋 ${tracked.length} wallet${tracked.length === 1 ? '' : 's'}${cn} · ${parts.join(' · ')}`); } else { lines.push(`🐋 ${tracked.length} wallet${tracked.length === 1 ? '' : 's'}${contracts ? ` + ${contracts} contract${contracts === 1 ? '' : 's'}` : ''} tracked`); } lines.push(''); // The day's flow. if (sum.total === 0) { lines.push('😴 No whale move in the last 24 hours.'); } else { const usdBy = (k) => sumKindUsd(events, k); const amtBy = (k) => sumKindAmt(events, k); const caption = sum.netUsd > 0 ? 'accumulating' : sum.netUsd < 0 ? 'offloading' : 'flat'; lines.push(`⚖️ 24h net ${netEmoji(sum.netUsd)} ${netStr(sum.netUsd)} · ${sum.total} move${sum.total === 1 ? '' : 's'} · ${caption}`); const row = (icon, n, word, k, sign) => n ? `${icon} ${n} ${word}${n === 1 ? '' : 's'} ${sign}${formatUsd(usdBy(k))} (${formatNumber(amtBy(k))} BOBAI)` : null; for (const r of [ row('🟢', c.BUY, 'buy', 'BUY', '+'), row('⚪', c.TRANSFER_IN, 'transfer in', 'TRANSFER_IN', '+'), row('🔴', c.SELL, 'sell', 'SELL', '−'), row('🔥', c.BURN, 'burn', 'BURN', '−'), row('🟠', c.TRANSFER_OUT, 'cascade out', 'TRANSFER_OUT', '−'), c.INTERNAL_T ? `🟣 ${c.INTERNAL_T} internal move${c.INTERNAL_T === 1 ? '' : 's'} · ${formatNumber(amtBy('INTERNAL_T'))} BOBAI (neutral)` : null, ]) if (r) lines.push(r); if (c.NEW_WHALE) lines.push(`💡 ${c.NEW_WHALE} new holder${c.NEW_WHALE === 1 ? '' : 's'} crossed 5M`); if (c.EX_WHALE) lines.push(`💀 ${c.EX_WHALE} ex-whale${c.EX_WHALE === 1 ? '' : 's'} dropped below 10M`); if (sum.quiet) lines.push(`🔕 ${sum.quiet} under $${WHALE_QUIET_USD} — logged, not alerted`); if (sum.folded) lines.push(`🧩 ${sum.folded} more folded into a pattern alert`); for (const e of sum.patterns) { const P = PATTERNS[e.kind]; if (!P) continue; lines.push(`${P.icon} ${shortenAddress(moverOf(e))} ${P.name.toLowerCase()} — ${PATTERN_AT}+ ${P.word}s in 24h`); } if (sum.movers.length) { lines.push(''); lines.push('🏆 Top moves'); sum.movers.forEach((e, i) => lines.push(`${i + 1}. ${describeMover(e)}`)); } } // The ten largest holders since yesterday's snapshot. const shift = holdings && holdings.top10; if (shift && (shift.entered.length || shift.left.length)) { lines.push(''); const parts = []; if (shift.entered.length) parts.push(`in: ${shift.entered.map(shortenAddress).join(', ')}`); if (shift.left.length) parts.push(`out: ${shift.left.map(shortenAddress).join(', ')}`); lines.push(`🏅 Top 10 changed · ${parts.join(' · ')}`); } // What the watch-set did to itself today. if (retired && retired.length) { lines.push(''); lines.push(`🧹 Retired ${retired.length} wallet${retired.length === 1 ? '' : 's'} empty for ${WHALE_RETIRE_EMPTY_DAYS} days: ${retired.map(shortenAddress).join(', ')} — back on the list when one crosses 5M again or receives from a watched wallet`); } lines.push(''); lines.push(`${price ? `BOBAI $${price.toFixed(8)} · ` : ''}/whales for the list`); return lines.join('\n'); } function sumKindUsd(events, kind) { return recentEvents(events, 24) .filter(e => e.kind === kind) .reduce((s, e) => s + (e.usdValue || 0), 0); } function sumKindAmt(events, kind) { return recentEvents(events, 24) .filter(e => e.kind === kind) .reduce((s, e) => s + (e.amount || 0), 0); } // Add bi-directional edge a↔b to the edges map. function addEdgeInMemory(edges, a, b) { if (a === b) return false; edges[a] = edges[a] || []; edges[b] = edges[b] || []; let changed = false; if (!edges[a].includes(b)) { edges[a].push(b); changed = true; } if (!edges[b].includes(a)) { edges[b].push(a); changed = true; } return changed; } // Connected components over the tracked subset. Returns array of Set. function computeClusters(addrs, edges) { const inSet = new Set(addrs); const visited = new Set(); const clusters = []; for (const start of addrs) { if (visited.has(start)) continue; const cluster = new Set(); const queue = [start]; while (queue.length) { const cur = queue.shift(); if (visited.has(cur)) continue; visited.add(cur); cluster.add(cur); for (const n of (edges[cur] || [])) { if (inSet.has(n) && !visited.has(n)) queue.push(n); } } clusters.push(cluster); } return clusters; } // Map address → cluster label ('A','B',...) for clusters of size >= 2. function labelClusters(clusters) { const labels = new Map(); let letter = 0; // Sort biggest first so the "main" whale cluster is A const sorted = clusters.slice().sort((a, b) => b.size - a.size); for (const c of sorted) { if (c.size < 2) continue; const tag = String.fromCharCode(65 + (letter % 26)); for (const addr of c) labels.set(addr, tag); letter++; } return labels; } async function handleWhaleAdmin(rawText, cmd, chatId, opts = {}) { const env = WHALE_ENV; // captured at scheduled/fetch entry if (!env) return; let reply; if (cmd === '/whalehelp') { reply = `🐋 Whale Watcher — Admin Commands /whales — tracked wallets (grouped by cluster, with 24h dots) /whales24h — full breakdown of the last 24 hours /whaleadd 0x... — add wallet(s) to the watch-set /whalerm 0x... — remove wallet(s) /whalecleanup — drop any contract addresses that slipped in /whalehelp — this help How it works: • Scans every minute. Groups all BOBAI transfers per tx so aggregator hops (1inch / OKX DEX / 0x) collapse into ONE clean alert against the LP, DEAD, or the real end-EOA. • Classifies: 🟢 Buy · 🔴 Sell · 🔥 Burn · 🟠 Transfer-Out · ⚪ Transfer-In · 🟣 Internal · 🟡 Dust (< $50). • 🔕 Quiet floor — a tracked wallet's move under $5 is logged for the recap, not posted (transfer-out to a fresh wallet always posts). • Daily Recap posted here every morning at 06:00 UTC (08:00 CEST). Auto-tracking: • 💡 NEW HOLDER 5M+ / NEW WHALE — a holder crosses 5M (🐬) or 10M (🐋), auto-added. Every holder of 5M+ is watched, so 🏅 #n is an exact place. • 📈📉📦 Patterns — 3 buys, 3 sells or 3 transfers out by one wallet in 24h: ONE alert tells the run; more small ones that day fold into it. • 🏊 Buys and sells name their share of the pool's BOBAI. • 💀 EX-WHALE — tracked wallet drops below 10M (stays in set while it holds anything). • 🧹 Retired — a wallet empty for 7 daily snapshots leaves the set at the recap; it is re-added the moment it moves. • 🟠 Cascade (Hop 1) — fresh EOAs a tracked wallet sends to are auto-added. • 🏦 Contract holders — a contract that holds 5M+ (never a pool, never a router) is watched on its own list; /whaleadd takes one from 1M. • 🤖 Routers blocked — contracts that only pass tokens through are never tracked. • ⏰ Alerts name the share of the bag a move takes, and a wallet's first move after 7+ still days. Never tracked (always excluded): • PancakeSwap LP · DEAD burn · BOBAI contract (tax collector) • Buyback bot & Dev-Buyback bot · Pools and routers Internal-only. Alerts post to this chat, never public.`; } else if (cmd === '/whales') { const list = await loadTrackedWallets(env); const cList = await loadTrackedContracts(env); if (!list.length && !cList.length) { reply = '🐋 No wallets currently tracked.\nUse /whaleadd 0x... to start.'; } else { const [balances, price, edges, events, totalSupply, snaps, cBalances] = await Promise.all([ Promise.all(list.map(a => getBobaiBalance(a).catch(() => 0n))), fetchBobaiPriceUsd().catch(() => null), loadWalletEdges(env), loadWhaleEvents(env), getTotalSupply().catch(() => 0), loadWhaleSnapshots(env).catch(() => []), Promise.all(cList.map(a => getBobaiBalance(a).catch(() => 0n))), ]); const tokens = balances.map(b => Number(b / 10n ** 18n)); const cTokens = cBalances.map(b => Number(b / 10n ** 18n)); const balByAddr = new Map([...list.map((a, i) => [a, tokens[i]]), ...cList.map((a, i) => [a, cTokens[i]])]); const totalTokens = tokens.reduce((s, t) => s + t, 0) + cTokens.reduce((s, t) => s + t, 0); const totalUsd = price ? totalTokens * price : null; // %-share is computed against TOTAL SUPPLY (more meaningful than vs. tracked). const supplyBase = totalSupply > 0 ? totalSupply : totalTokens || 1; const clusters = computeClusters(list, edges); const clusterTag = labelClusters(clusters); const active = activeAddrSet(events, 24); const sum = summarize24h(events); // Sort clusters: size desc (biggest first), but solo wallets aggregated separately const labeled = clusters.filter(c => c.size >= 2).sort((a, b) => b.size - a.size); const solo = clusters.filter(c => c.size === 1).flatMap(c => [...c]); // --- Header --- const totalUsdStr = totalUsd != null ? formatUsd(totalUsd) : 'n/a'; const totalPctOfSupply = ((totalTokens / supplyBase) * 100).toFixed(1); const header = `🐋 Whale Watcher ${list.length} wallets${cList.length ? ` + ${cList.length} contract${cList.length === 1 ? '' : 's'}` : ''} · ${formatNumber(totalTokens)} BOBAI · ${totalUsdStr} ${totalPctOfSupply}% of total supply`; // --- 24h inline summary --- const c = sum.counts; const has24h = sum.total > 0; const flagLine = (c.NEW_WHALE || c.EX_WHALE) ? ` 💡 ${c.NEW_WHALE} new whale${c.NEW_WHALE === 1 ? '' : 's'} · 💀 ${c.EX_WHALE} ex-whale${c.EX_WHALE === 1 ? '' : 's'}` : ''; const summary24h = has24h ? ` 📅 Last 24h · ${sum.total} events 📥 +${formatUsd(sum.usdIn)} in · 📤 -${formatUsd(sum.usdOut)} out ⚖️ Net: ${netEmoji(sum.netUsd)} ${netStr(sum.netUsd)}${flagLine}` : ` 📅 No whale activity in the last 24h.`; // --- Cluster + Solo sections --- const WHALE_THRESHOLD_TOKENS = 10_000_000; const renderWallet = (addr) => { const bal = balByAddr.get(addr) || 0; const usd = price ? bal * price : null; const usdStr = usd != null ? formatUsd(usd) : 'n/a'; const pct = ((bal / supplyBase) * 100).toFixed(2); // Size marker (💀 below 10M) and activity marker (🟢 active 24h / 💤 dormant) are independent. // Small + active → 💀🟢 so cascade-hop traffic on sub-10M wallets stays visible. // 🐋 a whale (10M+), 🐬 a holder of 5-10M (watched, not yet a whale); under 5M (a contract's line) no mark const dolphin = bal >= WHALE_THRESHOLD_TOKENS ? '🐋' : bal >= WATCH_THRESHOLD_TOKENS ? '🐬' : ''; const isActive = active.has(addr); // A dormant wallet says for how long (from the daily snapshots). const still = isActive ? null : dormantDays(snaps, addr, bal, events, Date.now(), 2); const dot = dolphin + (isActive ? '🟢' : `💤${still ? still + 'd' : ''}`); // the holder's place among everybody watched (exact from 5M up), not its place in the group const rank = String(holderRank(balByAddr, addr, bal)).padStart(2, ' '); return `${rank}. ${shortenAddress(addr)} · ${formatNumber(bal)} (${usdStr}) · ${pct}% ${dot}`; }; const renderActivity = (act) => { if (act.count === 0) return '💤 quiet (24h)'; const parts = []; if (act.netUsd !== 0) parts.push(`${netEmoji(act.netUsd)} net ${netStr(act.netUsd)}`); else if (act.usdIn || act.usdOut) parts.push(`⚪ flat`); if (act.usdIn) parts.push(`+${formatUsd(act.usdIn)} in`); if (act.usdOut) parts.push(`-${formatUsd(act.usdOut)} out`); if (act.internal) parts.push(`🟣 ${act.internal} internal`); // Fallback: events touched the cluster but contributed no USD flow // (typically historical status events or zero-value transfers). if (!parts.length) parts.push(`${act.count} event${act.count === 1 ? '' : 's'}`); return `24h: ${parts.join(' · ')}`; }; // A group lists its 5M+ holders one per line; the wallets under 5M // (spent cluster wallets, ex-holders) share one line, so the list is a // screen, not a scroll (the operator, 2026-09-10). const renderGroup = (addrs) => { const big = addrs.filter((a) => (balByAddr.get(a) || 0) >= WATCH_THRESHOLD_TOKENS); const small = addrs.filter((a) => (balByAddr.get(a) || 0) < WATCH_THRESHOLD_TOKENS); const out = big.map((a) => renderWallet(a)); if (small.length) out.push(renderSmallWalletsLine(small, balByAddr, active)); return out.join('\n'); }; const sections = []; for (const cluster of labeled) { const tag = clusterTag.get([...cluster][0]) || '?'; const addrs = [...cluster].sort((a, b) => (balByAddr.get(b) || 0) - (balByAddr.get(a) || 0)); const sumTokens = addrs.reduce((s, a) => s + (balByAddr.get(a) || 0), 0); const sharePct = ((sumTokens / supplyBase) * 100).toFixed(2); const act = summarizeClusterActivity(events, cluster, 24); const head = `🔗 Cluster ${tag} · ${addrs.length} wallets · ${sharePct}% of supply ${renderActivity(act)}`; sections.push(head + '\n' + renderGroup(addrs)); } if (solo.length) { const sorted = solo.slice().sort((a, b) => (balByAddr.get(b) || 0) - (balByAddr.get(a) || 0)); const sumTokens = sorted.reduce((s, a) => s + (balByAddr.get(a) || 0), 0); const sharePct = ((sumTokens / supplyBase) * 100).toFixed(2); const soloSet = new Set(sorted); const act = summarizeClusterActivity(events, soloSet, 24); const head = `🔘 Solo · ${sorted.length} wallets · ${sharePct}% of supply ${renderActivity(act)}`; sections.push(head + '\n' + renderGroup(sorted)); } // Contracts that hold like a whale: one line each, apart from the people. if (cList.length) { const sorted = cList.slice().sort((a, b) => (balByAddr.get(b) || 0) - (balByAddr.get(a) || 0)); const sumTokens = sorted.reduce((s, a) => s + (balByAddr.get(a) || 0), 0); const act = summarizeClusterActivity(events, new Set(sorted), 24); sections.push(`🏦 Contracts · ${sorted.length} · ${((sumTokens / supplyBase) * 100).toFixed(2)}% of supply\n${renderActivity(act)}\n` + sorted.map((a) => renderWallet(a)).join('\n')); } reply = `${header} ${summary24h} ${sections.join('\n\n')} #n = place among all holders (LP and burn not counted) · % = share of total supply · 🟢 active (24h) · 💤 dormant (12d = balance unchanged 12+ days) · 🐋 10M+ · 🐬 5-10M · 💀 below 5M, one line per group · 🔗 linked cluster · 🏦 a contract holding BOBAI (never a pool) ${opts.public ? `ℹ️ Every whale alert the internal group gets, and a daily recap at 06:00 UTC, here in the group` : 'ℹ️ /whales24h for the daily breakdown · /whalehelp'}`; } } else if (cmd === '/whales24h') { const [events, tracked, price, snaps, contracts] = await Promise.all([ loadWhaleEvents(env), loadTrackedWallets(env), fetchBobaiPriceUsd().catch(() => null), loadWhaleSnapshots(env).catch(() => []), loadTrackedContracts(env), ]); reply = renderDailyRecap(events, tracked, price, /*withDateStamp=*/ false, snapshotHoldings(snaps, [...tracked, ...contracts]), [], contracts.length); } else if (cmd === '/whaleadd') { const matches = rawText.match(ADDR_REG); if (!matches || !matches.length) { reply = '❌ Need at least one valid address.\nUsage: /whaleadd 0x...\nBatch: paste multiple 0x... in one message.'; } else { const list = await loadTrackedWallets(env); const cList = await loadTrackedContracts(env); const before = new Set([...list, ...cList]); const candidates = [...new Set(matches.map(a => a.toLowerCase()))]; // Block aggregator routers / contracts upfront — they're never wallets. const contractFlags = await Promise.all(candidates.map(a => WHALE_NEVER_TRACK.has(a) ? Promise.resolve(false) : isContract(a) )); const isContractMap = new Map(candidates.map((a, i) => [a, contractFlags[i]])); const added = [], dup = [], skipped = [], contracts = [], holders = []; for (const addr of candidates) { if (WHALE_NEVER_TRACK.has(addr)) skipped.push(addr); else if (before.has(addr)) dup.push(addr); else if (isContractMap.get(addr)) { // A contract that HOLDS 1M+ and is not a pool is a holder; a router holds dust. const bal = await getBobaiBalance(addr).catch(() => 0n); if (bal >= 1_000_000n * 10n ** 18n && !(await isPool(addr))) { holders.push(addr); cList.push(addr); } else contracts.push(addr); } else { added.push(addr); list.push(addr); } } const cleaned = await saveTrackedWallets(env, list); if (holders.length) await saveTrackedContracts(env, cList); const blocks = []; if (added.length) { blocks.push(`✅ Added ${added.length}:\n` + added.map(a => `• ${shortenAddress(a)}`).join('\n')); } if (dup.length) { blocks.push(`ℹ️ Already tracked (${dup.length}):\n` + dup.map(a => `• ${shortenAddress(a)}`).join('\n')); } if (holders.length) { blocks.push(`🏦 Added as contract holder${holders.length === 1 ? '' : 's'} (${holders.length}):\n` + holders.map(a => `• ${shortenAddress(a)}`).join('\n')); } if (contracts.length) { blocks.push(`🤖 Skipped (contract — router/pool, or under 1M) — ${contracts.length}:\n` + contracts.map(a => `• ${shortenAddress(a)}`).join('\n')); } if (skipped.length) { blocks.push(`🚫 Skipped (never-track: LP/DEAD/Bot) — ${skipped.length}:\n` + skipped.map(a => `• ${shortenAddress(a)}`).join('\n')); } blocks.push(`\n📊 Now tracking ${cleaned.length} wallets${cList.length ? ` + ${cList.length} contract${cList.length === 1 ? '' : 's'}` : ''}.`); reply = blocks.join('\n\n'); } } else if (cmd === '/whalecleanup') { const list = await loadTrackedWallets(env); if (!list.length) { reply = '🐋 No wallets to clean up.'; } else { const flags = await Promise.all(list.map(isContract)); const contracts = list.filter((_, i) => flags[i]); const eoas = list.filter((_, i) => !flags[i]); if (!contracts.length) { reply = `✅ All ${list.length} tracked addresses are EOAs. Nothing to clean.`; } else { const cleaned = await saveTrackedWallets(env, eoas); // Prune edges referencing the removed contracts. const edges = await loadWalletEdges(env); let edgesPruned = false; const rmSet = new Set(contracts); for (const a of contracts) { if (edges[a]) { delete edges[a]; edgesPruned = true; } } for (const k of Object.keys(edges)) { const before = edges[k].length; edges[k] = edges[k].filter(x => !rmSet.has(x)); if (edges[k].length !== before) edgesPruned = true; if (edges[k].length === 0) delete edges[k]; } if (edgesPruned) await saveWalletEdges(env, edges); reply = `🧹 Cleanup done\n\nRemoved ${contracts.length} contract address${contracts.length === 1 ? '' : 'es'} (routers/aggregators):\n` + contracts.map(a => `• ${shortenAddress(a)}`).join('\n') + `\n\n📊 Now tracking ${cleaned.length} EOA wallet${cleaned.length === 1 ? '' : 's'}.`; } } } else if (cmd === '/whalerm') { const matches = rawText.match(ADDR_REG); if (!matches || !matches.length) { reply = '❌ Need at least one valid address.\nUsage: /whalerm 0x...'; } else { const list = await loadTrackedWallets(env); const cList = await loadTrackedContracts(env); const before = new Set([...list, ...cList]); const rmSet = new Set(matches.map(a => a.toLowerCase())); const removed = [], notFound = []; for (const addr of rmSet) { if (before.has(addr)) removed.push(addr); else notFound.push(addr); } const cleaned = await saveTrackedWallets(env, list.filter(a => !rmSet.has(a))); if (cList.some(a => rmSet.has(a))) await saveTrackedContracts(env, cList.filter(a => !rmSet.has(a))); const blocks = []; if (removed.length) { blocks.push(`🗑️ Removed ${removed.length}:\n` + removed.map(a => `• ${shortenAddress(a)}`).join('\n')); } if (notFound.length) { blocks.push(`ℹ️ Not in set (${notFound.length}):\n` + notFound.map(a => `• ${shortenAddress(a)}`).join('\n')); } blocks.push(`\n📊 Now tracking ${cleaned.length} wallets total.`); reply = blocks.join('\n\n'); } } if (reply) { await tg('sendMessage', { chat_id: chatId, text: reply, parse_mode: 'HTML', disable_web_page_preview: true, }); } } // Captured at top of fetch() / scheduled() so handleWhaleAdmin has KV access. let WHALE_ENV = null; // ==================== WHALE WATCHER POSTER ==================== // Auto-posted to BOBAI Intern once per day at 06:00 UTC (08:00 CEST). async function postDailyWhaleRecap(env) { if (!TG_INTERNAL_CHAT_ID) return false; try { const [events, tracked0, price, contracts0] = await Promise.all([ loadWhaleEvents(env), loadTrackedWallets(env), fetchBobaiPriceUsd().catch(() => null), loadTrackedContracts(env), ]); // Holdings from the daily snapshot (silent until history exists), then // the retire rule on that snapshot: the recap names what it dropped. let tracked = tracked0, contracts = contracts0, holdings = null, retired = []; try { const snaps = await takeWhaleSnapshotIfDue(env, [...tracked0, ...contracts0]); retired = await retireEmptyWallets(env, snaps, tracked0); const retiredC = await retireEmptyWallets(env, snaps, contracts0, saveTrackedContracts); retired = retired.concat(retiredC); if (retired.length) { const gone = new Set(retired); tracked = tracked0.filter((a) => !gone.has(a)); contracts = contracts0.filter((a) => !gone.has(a)); } holdings = snapshotHoldings(snaps, [...tracked, ...contracts]); } catch (e) { console.error('[WHALE-SNAP RECAP ERROR]', e.message || e); } const text = renderDailyRecap(events, tracked, price, /*withDateStamp=*/ true, holdings, retired, contracts.length); const r = await tg('sendMessage', { chat_id: TG_INTERNAL_CHAT_ID, text, parse_mode: 'HTML', disable_web_page_preview: true, }); // the same recap in the official group (operator, 2026-10-12); the internal send decides "posted", so the official copy // goes only with it (2026-10-29: a failed internal send is retried every minute, and each retry posted it again) if (r?.ok === true) await tg('sendMessage', { chat_id: TG_CHAT_ID, text, parse_mode: 'HTML', disable_web_page_preview: true }).catch(() => {}); return r?.ok === true; } catch (e) { console.error('[WHALE DAILY ERROR]', e.message || e); return false; } } // Mover-first alert layout: who moved, in which cluster, how much, what's their // position now. Each alert focuses on the tracked wallet — the LP/DEAD or fresh // counterparty is shown as a one-line context, not as a co-equal "FROM/TO" row. // THE OTHER SIDE OF A WHALE'S TRANSFER (2026-09-18). The watcher looked for a // person on the other side and, finding only contracts, said nothing at all: a // tracked whale moving into a locker, a bridge or ANOTHER pool — a sale the // pair never sees — was silent, and the transaction was marked done. A person // is still preferred (the largest first); with none, the largest contract is // the other side and the alert says so. A contract is never added to the // watch-set. `candidates` is [[address, net]…] largest first. Pure. export function pickOtherSide(candidates, isContractOf) { const list = (candidates || []).map(([a]) => a); if (!list.length) return null; const person = list.find((a) => isContractOf(a) === false); return person ? { addr: person, viaContract: false } : { addr: list[0], viaContract: true }; } // A retried transaction tells nobody twice: what has been told is in the event log. export function toldAlready(events, txHash, kind, from, to) { return (events || []).some((e) => e.txHash === txHash && e.kind === kind && e.from === from && e.to === to); } // The alert's text, or false for a kind that is not told (pure: pinned by scripts/smoke-whale.mjs). export function renderWhaleAlert(data) { const { kind, from, to, amount, usdValue, txHash } = data; const DUST_USD = 50; const isDust = usdValue > 0 && usdValue < DUST_USD; const usdStr = usdValue ? formatUsd(usdValue) : 'n/a'; const txLink = `View TX`; // moverAddr = the tracked wallet at the center of this alert. // Inflows (BUY / TRANSFER_IN): mover = `to`, counterparty = `from`. // Outflows (SELL / BURN / TRANSFER_OUT): mover = `from`, counterparty = `to`. // INTERNAL_T: mover = sender (from), counterparty = recipient (to). const isInflowKind = (kind === 'BUY' || kind === 'TRANSFER_IN'); const moverAddr = isInflowKind ? to : from; const otherAddr = isInflowKind ? from : to; const moverTag = isInflowKind ? data.toTag : data.fromTag; const moverBal = isInflowKind ? data.toBal : data.fromBal; const otherTag = isInflowKind ? data.fromTag : data.toTag; const otherBal = isInflowKind ? data.fromBal : data.toBal; const priceUsd = data.priceUsd; const moverLink = `${shortenAddress(moverAddr)}`; const otherLink = `${shortenAddress(otherAddr)}`; const moverCluster = data.moverIsContract ? '🏦 Contract' : moverTag ? `🔗 Cluster ${moverTag}` : '🔸 Solo'; const moverHolds = moverBal != null ? `${formatNumber(moverBal)} BOBAI${priceUsd ? ` · ${formatUsd(moverBal * priceUsd)}` : ''}` : null; const otherDesc = describeAddr(otherAddr, otherTag, otherBal, priceUsd); // NEW_WHALE & EX_WHALE keep their own focused layouts. if (kind === 'NEW_WHALE') { const whale = amount >= 10_000_000; const what = data.moverIsContract ? '🏦 A contract (not a pool)' : whale ? '🐋' : '🐬'; const rankLine = data.rank ? ` · 🏅 #${data.rank} holder` : ''; const msg = `💡 NEW ${whale ? 'WHALE' : 'HOLDER 5M+'}${data.moverIsContract ? ' · CONTRACT' : ''} · auto-tracked ${what} ${moverLink} just crossed ${whale ? '10M' : '5M'} BOBAI. 📊 Holds: ${formatNumber(amount)} BOBAI · ${usdStr}${rankLine} Added to watch-set: its moves of $5 or more are alerted (a run of the same move in a day is folded unless it is big). 🔗 ${txLink}`; return msg; } if (kind === 'EX_WHALE') { const moverDownLink = `${shortenAddress(from)}`; const msg = `💀 EX-WHALE · dropped below 10M 📉 ${moverDownLink} 📊 Balance now: ${formatNumber(amount)} BOBAI · ${usdStr} Still in the watch-set. 🔗 ${txLink}`; return msg; } // Where the holder stands now, and where it stood before the move (exact from 5M up). const rankStr = data.rank ? `🏅 #${data.rank} holder${data.rankBefore && data.rankBefore !== data.rank ? ` (was #${data.rankBefore})` : ''}` : null; // A buy or sale against the pool it trades in: its share of the pool's BOBAI before the trade. const poolPct = data.poolShare ? data.poolShare * 100 : 0; const poolStr = poolPct ? ` · ${poolPct >= 1 ? poolPct.toFixed(1) : poolPct.toFixed(2)}% of the pool's BOBAI` : ''; // A PATTERN: three moves of a kind in 24 h told as one story. if (data.pattern) { const P = PATTERNS[kind]; const pt = data.pattern; const sign = kind === 'BUY' ? '+' : '−'; const lines = [ `${P.icon} ${P.name} · ${pt.n} ${P.word}s in 24h · ${formatUsd(pt.usd)}`, `${moverCluster} · ${moverLink}`, ]; if (moverHolds) lines.push(`📊 Now holds: ${moverHolds}`); if (rankStr) lines.push(rankStr); lines.push('', `🪙 ${sign}${formatNumber(pt.amount)} BOBAI in 24h${pt.bag ? ` · ${pt.bag}` : ''}`); lines.push(`↳ latest: ${sign}${formatNumber(amount)} BOBAI · ${usdStr}`); if (kind === 'TRANSFER_OUT' && pt.recipients && pt.recipients.length) { lines.push(`→ to ${pt.recipients.length} wallet${pt.recipients.length === 1 ? '' : 's'}: ${pt.recipients.slice(0, 5).map((a) => `${shortenAddress(a)}`).join(', ')}${pt.recipients.length > 5 ? ' …' : ''}`); } lines.push('', `More of the same today is folded into this (big single moves still alert).`, `🔗 ${txLink}`); return lines.join('\n'); } // Action verb + headline icon, by kind. let headline, contextLine; switch (kind) { case 'BUY': headline = `🟢 BUY · ${usdStr}`; contextLine = `↩ from PancakeSwap LP${poolStr}`; break; case 'SELL': headline = `🔴 SELL · ${usdStr}`; contextLine = `↪ into PancakeSwap LP${poolStr}`; break; case 'BURN': headline = `🔥 BURN · ${usdStr}`; contextLine = `↪ to 💀 DEAD address`; break; case 'INTERNAL_T': headline = `🟣 INTERNAL MOVE · ${usdStr}`; contextLine = `→ ${otherLink} · ${otherDesc}`; break; case 'TRANSFER_OUT': if (data.otherIsContract) { headline = `🟠 TRANSFER OUT · ${usdStr}`; contextLine = `→ ${otherLink} · a contract — a locker, a bridge or another pool; not added to the watch-set`; } else if (isDust) { headline = `🟡 PRE-FUNDING · ${usdStr} (dust)`; contextLine = `→ ${otherLink} · a wallet not on the watch list; a dust send often comes before a bigger one`; } else { headline = `🟠 TRANSFER OUT · ${usdStr}`; contextLine = `→ ${otherLink} · not on the watch list yet, auto-added to the watch-set`; } break; case 'TRANSFER_IN': headline = `⚪ RECEIVED · ${usdStr}`; contextLine = data.otherIsContract ? `← ${otherLink} · from a contract` : `← ${otherLink} · ${otherDesc}`; break; default: return false; } const lines = [ headline, `${moverCluster} · ${moverLink}`, ]; if (moverHolds) lines.push(`📊 Now holds: ${moverHolds}`); if (rankStr) lines.push(rankStr); if (data.dormant) lines.push(`⏰ First move in ${data.dormant}+ days`); const sign = (kind === 'SELL' || kind === 'BURN' || kind === 'TRANSFER_OUT') ? '−' : (kind === 'BUY' || kind === 'TRANSFER_IN') ? '+' : ''; // INTERNAL_T → neutral (intra-cluster redistribution) const note = positionNote(kind, amount, moverBal); lines.push('', `🪙 ${sign}${formatNumber(amount)} BOBAI · ${usdStr}${note ? ` · ${note}` : ''}`); lines.push(contextLine); lines.push('', `🔗 ${txLink}`); return lines.join('\n'); } // THE OFFICIAL GROUP SEES THE WHALES TOO (operator, 2026-10-12: "alerts and the daily whale recap in the internal AND // the official group; /whales in the official bot"). Internal keeps every alert from the $5 quiet line; the group gets // the ones of $50 and more (operator's choice) — a move without a USD value stays internal. // EXACTLY AS INTERNAL (operator, 2026-10-13: a $12.70 whale buy showed in the internal group only — "exactly the same // as internal"): every whale alert the internal group gets, the official group gets too, word for word. The $5 quiet // line and the folding of small repeated moves still decide what is posted at all, for both. // ONE EXCEPTION (operator, 2026-10-15): a tracked wallet's buy that the buy alert tells ($100+) is told there, once, // with the watcher's line in it — `official` false; internal still gets the watcher's text. export const WHALE_PUBLIC_USD = 0; export const whaleAlertIsPublic = () => true; async function postWhaleAlert(data, official = true) { if (!TG_INTERNAL_CHAT_ID) return false; const text = renderWhaleAlert(data); if (!text) return false; // one alert per move (2026-10-23), as the buy alert: two overlapping ticks rescan the same blocks from the same cursor const gateKey = `${data.txHash}:${data.kind}:${data.from || ''}:${data.to || ''}`; if (!(await claimAlert(WHALE_ENV, 'whale', gateKey))) return true; // another tick told it const ok = await tgSend(text); if (!ok) { await releaseAlert(WHALE_ENV, 'whale', gateKey); return false; } if (official && whaleAlertIsPublic(data)) await tgSend(text, TG_CHAT_ID); return ok; } async function tgSend(text, chatId = TG_INTERNAL_CHAT_ID) { try { const r = await tg('sendMessage', { chat_id: chatId, text, parse_mode: 'HTML', disable_web_page_preview: true, }); return r?.ok === true; } catch (e) { console.error('[WHALE ALERT ERROR]', e.message || e); return false; } } // ==================== GUARD BOT ==================== function generateCaptcha() { const a = Math.floor(Math.random() * 10) + 1; const b = Math.floor(Math.random() * 10) + 1; return { question: `${a} + ${b}`, answer: (a + b).toString() }; } function generateButtons(correctAnswer) { const correct = parseInt(correctAnswer); const options = new Set([correct]); while (options.size < 4) { const wrong = correct + Math.floor(Math.random() * 7) - 3; if (wrong > 0 && wrong !== correct) options.add(wrong); } const shuffled = [...options].sort(() => Math.random() - 0.5); return [shuffled.map(n => ({ text: n.toString(), callback_data: `cap_${n}` }))]; } // ==================== CAPTCHA INDEX HELPERS ==================== async function getCaptchaIndex(env) { const raw = await env.KV.get('captcha_index'); return raw ? JSON.parse(raw) : []; } async function addToCaptchaIndex(env, userId) { const index = await getCaptchaIndex(env); if (!index.includes(userId)) { index.push(userId); await env.KV.put('captcha_index', JSON.stringify(index)); } } async function removeFromCaptchaIndex(env, userId) { const index = await getCaptchaIndex(env); const filtered = index.filter(id => id !== userId); await env.KV.put('captcha_index', JSON.stringify(filtered)); } // ==================== GUARD BOT HANDLERS ==================== async function handleNewMember(msg, env) { // Captcha belongs to the official chat only. A join anywhere else (the Intern // chat) used to mute + kick that person in the official chat. if (String(msg.chat?.id) !== TG_CHAT_ID) return; const members = msg.new_chat_members || []; for (const member of members) { if (member.is_bot) continue; const userId = member.id; const name = member.first_name || 'User'; const { question, answer } = generateCaptcha(); await tg('restrictChatMember', { chat_id: TG_CHAT_ID, user_id: userId, permissions: { can_send_messages: false, can_send_media_messages: false, can_send_other_messages: false }, }); const result = await tg('sendPhoto', { chat_id: TG_CHAT_ID, photo: PHOTO_WELCOME, caption: `👋 Welcome ${shownName(name)} to BOBAI!\n\n🛡 Quick verification — solve this:\n\n🧮 ${question} = ?\n\n⏱ You have 60 seconds`, parse_mode: 'HTML', reply_markup: { inline_keyboard: generateButtons(answer) }, }); await env.KV.put(`captcha_${userId}`, JSON.stringify({ answer, messageId: result.result?.message_id, name, timestamp: Date.now(), }), { expirationTtl: 600 }); await addToCaptchaIndex(env, userId); } } async function handleCallback(callback, env) { const userId = callback.from.id; const data = callback.data; if (!data.startsWith('cap_')) return; const stored = await env.KV.get(`captcha_${userId}`); if (!stored) { await tg('answerCallbackQuery', { callback_query_id: callback.id, text: 'Expired or not for you.' }); return; } const entry = JSON.parse(stored); const selected = data.replace('cap_', ''); if (selected === entry.answer) { await env.KV.delete(`captcha_${userId}`); await removeFromCaptchaIndex(env, userId); await tg('restrictChatMember', { chat_id: TG_CHAT_ID, user_id: userId, permissions: { can_send_messages: true, can_send_media_messages: true, can_send_other_messages: true, can_add_web_page_previews: true }, }); await tg('answerCallbackQuery', { callback_query_id: callback.id, text: '✅ Verified! Welcome!' }); if (entry.messageId) { await tg('deleteMessage', { chat_id: TG_CHAT_ID, message_id: entry.messageId }); } await tg('sendMessage', { chat_id: TG_CHAT_ID, text: `✅ ${shownName(entry.name)} joined the BOBAI community! Welcome! 🚀`, parse_mode: 'HTML', }); } else { await env.KV.delete(`captcha_${userId}`); await removeFromCaptchaIndex(env, userId); await tg('answerCallbackQuery', { callback_query_id: callback.id, text: '❌ Wrong answer. Try joining again.' }); await tg('banChatMember', { chat_id: TG_CHAT_ID, user_id: userId }); await tg('unbanChatMember', { chat_id: TG_CHAT_ID, user_id: userId }); if (entry.messageId) { await tg('deleteMessage', { chat_id: TG_CHAT_ID, message_id: entry.messageId }); } } } async function cleanupExpiredCaptchas(env) { // Uses captcha_index (KV.get = read) instead of KV.list (= write-category) const index = await getCaptchaIndex(env); const remaining = []; for (const userId of index) { const data = await env.KV.get(`captcha_${userId}`); if (!data) { // Already expired via TTL or handled — skip continue; } const entry = JSON.parse(data); if (Date.now() - entry.timestamp > CAPTCHA_TIMEOUT * 1000) { await env.KV.delete(`captcha_${userId}`); try { if (entry.messageId) { await tg('deleteMessage', { chat_id: TG_CHAT_ID, message_id: entry.messageId }); } await tg('sendMessage', { chat_id: TG_CHAT_ID, text: `👋 ${shownName(entry.name)} didn't verify in time. Bye bye!`, parse_mode: 'HTML', }); await tg('banChatMember', { chat_id: TG_CHAT_ID, user_id: parseInt(userId) }); await tg('unbanChatMember', { chat_id: TG_CHAT_ID, user_id: parseInt(userId) }); } catch {} } else { remaining.push(userId); } } // Update index to only keep active captchas if (remaining.length !== index.length) { await env.KV.put('captcha_index', JSON.stringify(remaining)); } } // ==================== BOT COMMAND MENU SETUP ==================== const BOT_COMMANDS = [ { command: 'alerts', description: 'Buy & burn alert tiers' }, { command: 'bot', description: 'What the bot does — the 3% split now & upcoming' }, { command: 'burn', description: 'Burned by the bot & at the dead address, BOBAI and BOB, in USD' }, { command: 'buy', description: 'How to buy BOBAI' }, { command: 'ca', description: 'Contract address' }, { command: 'defi', description: 'The DeFi agent as a portfolio: put in, worth, P&L, last 24 h' }, { command: 'giggle', description: 'Giggle Academy pot — countdown & BNB collected' }, { command: 'help', description: 'Show all commands' }, { command: 'liq', description: 'Liquidity depth, price impact & trade cost' }, { command: 'nft', description: 'Buy Drops NFT — tier progress & latest mints' }, { command: 'pop', description: 'Brain Pop: the top 3 of today, the season leader, the prize pool, play' }, { command: 'price', description: 'Live price, volume & market stats' }, { command: 'security', description: 'Anti-scam reminder & official links' }, { command: 'social', description: 'All project links' }, { command: 'tax', description: 'Tax live: next buyback charge, last buyback, last 24 h (also /buyback)' }, { command: 'whales', description: 'The BOBAI whales: holdings, 24 h activity' }, { command: 'worldcup', description: "Worldcup '26 tipgame — final results" }, ]; // Whale watcher menu — only registered for the BOBAI Intern chat (scope=chat). // Overrides the public BOT_COMMANDS list inside that chat, so the "/" menu shows // only these four entries. const WHALE_COMMANDS = [ { command: 'help', description: 'Whale watcher help' }, { command: 'whales', description: 'Tracked wallets (clustered, with 24h dots)' }, { command: 'whales24h', description: 'Detailed last-24h breakdown' }, { command: 'whaleadd', description: 'Add wallet(s) to watch-set' }, { command: 'whalerm', description: 'Remove wallet(s) from watch-set' }, { command: 'whalecleanup', description: 'Drop contract addresses from watch-set' }, ]; const COMMANDS_VERSION = 'v20-pop'; // Telegram can sign every webhook call with a secret it sends back in the // X-Telegram-Bot-Api-Secret-Token header. Without it, anyone who knows the // Worker URL can post a fake update and make the bot answer into any chat it // sits in. The secret is a Worker secret (TG_WEBHOOK_SECRET); this registers // it with Telegram once per value, keeping the webhook URL Telegram already // has, so the token never leaves Cloudflare and no script needs it. async function ensureWebhookSecret(env) { const secret = env.TG_WEBHOOK_SECRET || ''; if (!secret) return; const want = 'v1:' + secret.slice(0, 8); const have = await env.KV.get('webhook_secret_version'); if (have === want) return; const info = await tg('getWebhookInfo', {}); const url = info?.result?.url; if (!url) { console.error('[WEBHOOK] no webhook url registered, cannot attach secret'); return; } const res = await tg('setWebhook', { url, secret_token: secret, allowed_updates: info.result.allowed_updates || [] }); if (res?.ok) { await env.KV.put('webhook_secret_version', want); console.log('[WEBHOOK] secret attached to', url); } else { console.error('[WEBHOOK] setWebhook failed:', JSON.stringify(res)); } } async function ensureCommandsRegistered(env) { const current = await env.KV.get('commands_version'); if (current === COMMANDS_VERSION) return; const res1 = await tg('setMyCommands', { commands: BOT_COMMANDS }); let res2 = { ok: true }; if (TG_INTERNAL_CHAT_ID) { res2 = await tg('setMyCommands', { commands: WHALE_COMMANDS, scope: { type: 'chat', chat_id: TG_INTERNAL_CHAT_ID }, }); } if (res1?.ok && res2?.ok) { await env.KV.put('commands_version', COMMANDS_VERSION); console.log('[COMMANDS] Registered', COMMANDS_VERSION); } else { console.error('[COMMANDS] Failed:', JSON.stringify({ res1, res2 })); } } // ==================== BRAIN PLAZA LISTINGS ==================== // Reads agent.brainonbnb.com/listings every tenth minute; a listing it has not announced (KV listing_announced) and that // is at most 7 days old is posted once to the group. The ids are remembered before the post is checked, so a listing is // never announced twice even when Telegram refuses one (the internal log says so). export function renderListingAnnouncement(L) { const esc = (t) => String(t ?? '').replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c])); const desc = L.description ? esc(String(L.description).slice(0, 220)) + (String(L.description).length > 220 ? '…' : '') : ''; return [`🏛 New on Brain Plaza`, ``, `${esc(L.name || 'Agent #' + L.id)} · ERC-8004 #${esc(L.id)}`, desc, ``, L.badge ? `✅ Verified & maintained: it answered our check, and we check it every day.` : `⏸ Listed; the badge shows once it answers our daily check.`, L.house ? `🧠 Our own agent, the first on the list — not a paid listing. The same daily check applies.` : ``, ``, `🔗 Its page · Brain Plaza · List yours`] .filter((x, i, a) => !(x === '' && a[i - 1] === '')).join('\n'); } async function announceListings(env) { const r = await fetch('https://agent.brainonbnb.com/listings', { signal: AbortSignal.timeout(10000) }); if (!r.ok) return; const list = (await r.json())?.listings || []; const done = new Set(JSON.parse((await env.KV.get('listing_announced')) || '[]')); const fresh = list.filter((L) => !done.has(String(L.id)) && Date.now() - Date.parse(L.since) < 7 * 86400e3); if (!fresh.length) return; for (const L of fresh) done.add(String(L.id)); await env.KV.put('listing_announced', JSON.stringify([...done])); for (const L of fresh) { const sent = await tg('sendMessage', { chat_id: TG_CHAT_ID, text: renderListingAnnouncement(L), parse_mode: 'HTML', disable_web_page_preview: true }).catch(() => null); if (!sent?.ok) console.error('[LISTING ANNOUNCE] Telegram refused #' + L.id, JSON.stringify(sent)); } } // ==================== BRAIN POP CHAMPION (/api/pop, daily) ==================== // Operator, 2026-11-06: "make the telegram post every day". Each day of the Brain Pop season (6 to 30 Nov) the game's // daily winner, posted once into the public group shortly after 00:00 UTC: the day's top 3, how many played, the prize // (nothing — the operator's joke), the season leader who is on course for the ONE $BOBAI, and the link to play today. // The board is the bobai-pop worker's (brainonbnb.com/api/pop/top); names there are random or the player's own, // brainrotted, letters/digits/_ only, so nothing in them can break the HTML. A day nobody played posts nothing. const POP_FIRST = '2026-11-06', POP_LAST = '2026-11-30'; // /pop (7.11., operator: "ecosystem number one, nothing forgotten"): the game's live state in the chat — today's top 3, // the season leader, the prize pool against its $10 goal, the way in. Pure: the boards, the pool and the price in, HTML out. export function renderPopNow(today, d, all, pool, priceUsd) { const esc = (t) => String(t ?? '').replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c])); const p7 = (v) => Number(v || 0).toLocaleString('en-US', { minimumFractionDigits: 7, maximumFractionDigits: 7 }), medal = ['🥇', '🥈', '🥉']; const over = today > POP_LAST, rows = (d && d.rows) || [], leader = all && all.rows && all.rows[0]; const bobai = pool && pool.bobai != null ? Number(pool.bobai) : null, usd = bobai != null && priceUsd ? bobai * priceUsd : null; return [ over ? '🧠 BRAIN POP · SEASON OVER' : `🧠 BRAIN POP · DAY ${d && d.no ? d.no : ''} · LIVE`, '', ...(over ? [] : rows.length ? rows.slice(0, 3).map((r, i) => `${medal[i]} ${esc(r.name)} · ${p7(r.score)} ROT`) : ['Nobody on today\'s board yet. The first run takes the crown.']), over ? '' : `${Number((d && d.players) || 0).toLocaleString('en-US')} player${(d && d.players) === 1 ? '' : 's'} today`, leader ? `👑 ${over ? 'Champion' : 'Season leader'}: ${esc(leader.name)} · ${p7(leader.score)} ROT` : '', bobai != null ? `🏆 Prize pool: ${bobai.toLocaleString('en-US', { maximumFractionDigits: 2 })} $BOBAI${usd != null ? ' ≈ $' + usd.toFixed(2) : ''} · goal $10 · the overall #1 on 30 Nov takes it all` : '', '', over ? 'Thanks for rotting with us 🪩' : '▶️ Play (free, 60 s): https://brainonbnb.com/m/pop?from=tg', ].filter((l, i, a) => l !== '' || (a[i - 1] !== '' && i > 0)).join('\n').trim(); } // 8.11. (operator): "17 players" says how many played THAT day, plus the season's players overall; the joke prize is // named the DAILY prize; the season leader (only the #1) comes with the prize pool he is on course for export function renderPopChampion(day, no, rows, players, leader, allPlayers, pool, priceUsd) { const esc = (t) => String(t ?? '').replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c])); const n = (v) => Number(v || 0).toLocaleString('en-US'), p7 = (v) => Number(v || 0).toLocaleString('en-US', { minimumFractionDigits: 7, maximumFractionDigits: 7 }), medal = ['🥇', '🥈', '🥉']; // 6.9: scores with seven decimals const last = day === POP_LAST; const bobai = pool && pool.bobai != null ? Number(pool.bobai) : null, usd = bobai != null && priceUsd ? bobai * priceUsd : null; return [ `🧠 BRAIN POP · DAY ${no} CHAMPION`, '', ...rows.slice(0, 3).map((r, i) => `${medal[i]} ${esc(r.name)} · ${p7(r.score)} ROT`), '', `👥 ${n(players)} player${players === 1 ? '' : 's'} played on day ${no}${allPlayers ? ` · ${n(allPlayers)} overall` : ''}`, `🎁 Daily prize: NOOOOOOOTHING`, '', leader ? (last ? `👑 Season over. Overall champion: ${esc(leader.name)} · ${p7(leader.score)} ROT` : `👑 Season leader: ${esc(leader.name)} · ${p7(leader.score)} ROT`) : '', bobai != null ? `🏆 Prize pool: ${bobai.toLocaleString('en-US', { maximumFractionDigits: 2 })} $BOBAI${usd != null ? ' ≈ $' + usd.toFixed(2) : ''} · ${last ? 'goes to the champion' : 'the season leader on 30 Nov takes it all'}` : '', '', last ? 'Thanks for rotting with us 🪩' : '▶️ Play today: https://brainonbnb.com/m/pop?from=tg', ].filter((l, i, a) => l !== '' || (a[i - 1] !== '' && i > 0)).join('\n').trim(); } async function popChampionText(day) { const get = (q) => fetch('https://brainonbnb.com/api/pop/top?' + q, { signal: AbortSignal.timeout(10000) }).then((r) => (r.ok ? r.json() : null)); const [d, all] = await Promise.all([get('scope=day&d=' + day), get('scope=all')]); if (!d || !Array.isArray(d.rows)) return undefined; // the board did not answer: try again at the next tick if (!d.rows.length) return null; const side = (u) => fetch(u, { signal: AbortSignal.timeout(10000) }).then((r) => (r.ok ? r.json() : null)).catch(() => null); // pool + price: a line less if they fail const [pool, px] = await Promise.all([side('https://brainonbnb.com/api/pop/pool'), side('https://brainonbnb.com/api/price')]); return renderPopChampion(day, d.no, d.rows, d.players, all && all.rows && all.rows[0], all && all.players, pool, px && px.price_usd); } export async function postPopChampion(env, tick) { const day = new Date(Date.UTC(tick.getUTCFullYear(), tick.getUTCMonth(), tick.getUTCDate()) - 86400e3).toISOString().slice(0, 10); if (day < POP_FIRST || day > POP_LAST) return; const flag = 'pop_champ:' + day; if (await env.KV.get(flag)) return; // ON CHAIN FIRST (10.11., operator): the closed day is written on BNB Chain from 00:15 UTC (worker-agent pop-chain.js); // the post waits for that transaction and links it. Until 00:45 it waits; after that it goes out without the line. const chainTx = await popChainTx(day); if (!chainTx && tick.getUTCMinutes() < 45) return; let text = await popChampionText(day); if (text && chainTx) text = text.replace('\n\n▶️ Play today:', `\n⛓ On BNB Chain: https://bscscan.com/tx/${chainTx}\n\n▶️ Play today:`); if (text === undefined) return; if (!text) { await env.KV.put(flag, 'nobody', { expirationTtl: 3 * 86400 }); return; } // once, also when nobody played // MARKED ONLY WHEN SENT (15.11., the A-Z pass): the day was marked before Telegram answered, so one refused send lost the // post (on 1 Dec: the season-over post). Now a refusal is tried again next minute, at most 5 times a day. const tryKey = flag + ':try', tries = Number(await env.KV.get(tryKey)) || 0; if (tries >= 5) return; await env.KV.put(tryKey, String(tries + 1), { expirationTtl: 3 * 86400 }); const done = () => env.KV.put(flag, 'sent', { expirationTtl: 3 * 86400 }); // THE CHAMPION'S CARD (7.11., operator: "ecosystem number one"): the post is the champion's own run card (name, score, // place — bobai-og /pop/.png) with the text as its caption and a line into the challenge; text alone if it fails const champ = await popChampionRun(day); if (champ) { const caption = text.replace('▶️ Play today: https://brainonbnb.com/m/pop?from=tg', '⚔️ Beat the champion: https://brainonbnb.com/m/pop/' + champ + '?from=tg'); const ph = await tg('sendPhoto', { chat_id: TG_CHAT_ID, photo: 'https://brainonbnb.com/og/pop/' + champ + '.png?d=' + day, caption, parse_mode: 'HTML' }).catch(() => null); if (ph?.ok) return done(); console.error('[POP CHAMPION] photo refused, text instead ' + day, JSON.stringify(ph)); } const sent = await tg('sendMessage', { chat_id: TG_CHAT_ID, text, parse_mode: 'HTML', disable_web_page_preview: true }).catch(() => null); if (sent?.ok) return done(); console.error('[POP CHAMPION] Telegram refused ' + day + ' (try ' + (tries + 1) + ' of 5)', JSON.stringify(sent)); } // the day's record on BNB Chain (agent.brainonbnb.com/pop/chain?day=): its transaction, or null while not written async function popChainTx(day) { try { const r = await fetch('https://agent.brainonbnb.com/pop/chain?day=' + day, { signal: AbortSignal.timeout(10000) }); if (!r.ok) return null; const j = await r.json(); return /^0x[0-9a-f]{64}$/.test(j && j.tx || '') ? j.tx : null; } catch { return null; } } // the day's #1 run id (its card and its challenge link) async function popChampionRun(day) { try { const r = await fetch('https://brainonbnb.com/api/pop/top?scope=day&d=' + day, { signal: AbortSignal.timeout(10000) }); if (!r.ok) return null; const j = await r.json(); const id = j && j.rows && j.rows[0] && j.rows[0].run; return /^[a-z0-9]{1,12}$/.test(id || '') ? id : null; } catch { return null; } } // ==================== GIGGLE ACADEMY POT (/giggle) ==================== // The pot's windows — the same instants the buyback worker switches on // (worker/index.js LP_SHARE_START / GIGGLE_START / GIGGLE_END), so the bot, // the page and the bot's own split never disagree about when. const GG_LP_START = Date.parse('2026-09-09T05:30:00Z'); const GG_START = Date.parse('2026-09-17T00:01:00Z'); const GG_END = Date.parse('2026-11-20T00:01:00Z'); const GG_POT_WALLET = '0x5E4102520A71B2AA18a1208330d4848dea4BD105'; const GG_DONATE_URL = 'https://giggleacademy.com/support-us'; // One card, /price-shaped: what it is, where the clock stands, what has been // collected (from burns.json — giggleBnb/giggleTx per bot run, the same log // the page reads), the last send, and where the donation goes. Pure. // the donation itself (2026-11-09): read from brainonbnb.com/giggle-donation.json; only a transaction there makes the card say donated export function formatGiggleCard(burns, nowMs = Date.now(), bnbUsd = null, donation = null) { const done = donation && /^0x[0-9a-fA-F]{64}$/.test(donation.tx || '') && +donation.bnb > 0 ? donation : null; const sends = (Array.isArray(burns) ? burns : []).filter((x) => x && x.giggleTx); const total = sends.reduce((a, x) => a + (parseFloat(x.giggleBnb) || 0), 0); const last = sends.length ? sends[sends.length - 1] : null; const span = (ms) => { const d = Math.floor(ms / 86400000), h = Math.floor((ms % 86400000) / 3600000), m = Math.floor((ms % 3600000) / 60000); return d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`; }; let clock; if (nowMs < GG_START) clock = `⏳ Collecting starts in ${span(GG_START - nowMs)} · Sep 17, 00:01 UTC`; else if (nowMs < GG_END) clock = `⏳ Collecting ends in ${span(GG_END - nowMs)} · Nov 20, 00:01 UTC`; else clock = done ? `✅ Donated to Giggle Academy · ${done.bnb} BNB · tx` : `✅ Collecting ended Nov 20 · the donation is on its way`; const lastLine = last ? `🕐 Last send: ${parseFloat(last.giggleBnb).toFixed(5)} BNB · ${String(last.time).slice(0, 16).replace('T', ' ')} UTC · tx` : '🕐 Last send: none yet'; // the window over (2026-11-04, the A-Z pass): the card stops saying "fills" and "so far" once nothing is sent any more const over = nowMs >= GG_END; return [ '☀️ Giggle Academy Community Pot', '', '📅 Window', '🗓 Sep 17 → Nov 20, 2026 · 64 days', clock, '', over ? '⚙️ How it filled' : '⚙️ How it fills', over ? '♻️ 0.3% of every trade — a tenth of each tax slice — was sent as BNB by the buyback bot, Sep 17 to Nov 20' : '♻️ 0.3% of every trade — a tenth of each tax slice — sent as BNB by the buyback bot', '🎁 One donation on UN World Children’s Day, in BNB, through Giggle Academy’s own page', '', over ? '💰 Collected' : '💰 Collected so far', `🪙 ${total.toFixed(4)} BNB${bnbUsd > 0 ? ` (≈$${(total * bnbUsd).toFixed(2)})` : ''} · ${sends.length} send${sends.length === 1 ? '' : 's'}`, lastLine, '', `🏦 Pot wallet · 🎓 giggleacademy.com/support-us · 📊 brainonbnb.com`, ].filter((l, i, a) => l !== '' || a[i - 1] !== '').join('\n'); } // ==================== WHAT THE BOT DOES (/bot) ==================== // The split as the buyback worker pays it — the same windows as worker/index.js // and the schedule on the page. Only the windows still ahead or running are // listed; the finished campaigns live on the page's schedule. const BB3_START = Date.parse('2026-09-19T18:00:00Z'); // 2026-09-20 06:00 UTC: Liq Boost III raised from 0.3% to 0.5%, the 0.2% out of the BOB burn — the page's schedule (app.js BB3R_START) tells it as two windows, so does this table. const BB3R_START = Date.parse('2026-09-20T06:00:00Z'); // 2026-10-28 (operator): from Dec 1 00:01 UTC the BOB-burn 1% is BOBAI liquidity + LP burn, for good (worker BOBAI_LIQ_PHASE_START). const LIQ_FOREVER_START = Date.parse('2026-12-01T00:01:00Z'); const BOT_WALLET = '0xdeFC0e900Dfc83e207902cF22265Ae63f94c01ce'; const TAX_PHASES_TG = [ { from: GG_START, until: BB3_START, when: 'Sep 17 → Sep 19, 18:00 UTC, 2026', name: 'Giggle Academy pot + DeFi Agent', slices: [ ['👤', '0.8%', 'Creator', '−0.1% → DeFi Agent, −0.1% → Giggle pot'], ['👷', '0.8%', 'Burn $BOB (Build On BNB)', '−0.1% → DeFi Agent, −0.1% → Giggle pot'], ['🧠', '0.8%', 'Burn $BOBAI', '−0.1% → DeFi Agent, −0.1% → Giggle pot'], ['💧', '0.3%', 'DeFi Agent', ''], ['☀️', '0.3%', 'Giggle Academy pot', ''], ] }, { from: BB3_START, until: BB3R_START, when: 'Sep 19, 18:00 UTC → Sep 20, 06:00 UTC, 2026', name: '$BOBAI Liq Boost III + Giggle Academy pot + DeFi Agent', slices: [ ['👤', '0.8%', 'Creator', '−0.1% → DeFi Agent, −0.1% → Giggle pot'], ['👷', '0.5%', 'Burn $BOB (Build On BNB)', '−0.3% → Liq Boost III, −0.1% → DeFi Agent, −0.1% → Giggle pot'], ['🧠', '0.8%', 'Burn $BOBAI', '−0.1% → DeFi Agent, −0.1% → Giggle pot'], ['🔒', '0.3%', 'BOBAI liq add + LP burn', ''], ['💧', '0.3%', 'DeFi Agent', ''], ['☀️', '0.3%', 'Giggle Academy pot', ''], ] }, { from: BB3R_START, until: GG_END, when: 'Sep 20, 06:00 UTC → Nov 20, 2026', name: '$BOBAI Liq Boost III raised to 0.5% + Giggle Academy pot + DeFi Agent', slices: [ ['👤', '0.8%', 'Creator', '−0.1% → DeFi Agent, −0.1% → Giggle pot'], ['👷', '0.3%', 'Burn $BOB (Build On BNB)', '−0.5% → Liq Boost III, −0.1% → DeFi Agent, −0.1% → Giggle pot'], ['🧠', '0.8%', 'Burn $BOBAI', '−0.1% → DeFi Agent, −0.1% → Giggle pot'], ['🔒', '0.5%', 'BOBAI liq add + LP burn', ''], ['💧', '0.3%', 'DeFi Agent', ''], ['☀️', '0.3%', 'Giggle Academy pot', ''], ] }, { from: GG_END, until: LIQ_FOREVER_START, when: 'Nov 20 → Dec 1, 00:01 UTC, 2026', name: 'Standard — the last days of the $BOB burn', slices: [ ['👤', '1%', 'Creator', ''], ['👷', '1%', 'Burn $BOB (Build On BNB)', ''], ['🧠', '1%', 'Burn $BOBAI', ''], ] }, { from: LIQ_FOREVER_START, until: null, when: 'from Dec 1, 2026, 00:01 UTC — for good', name: '$BOBAI liquidity for good', slices: [ ['👤', '1%', 'Creator', ''], ['🧠', '1%', 'Burn $BOBAI', ''], ['🔒', '1%', 'BOBAI liq add + LP burn', 'the whole former $BOB burn'], ] }, ]; // One card: what the bot is, the split it pays right now — the tax-split box of // the page, line for line — and the window(s) that follow. Pure. export function formatBotCard(nowMs = Date.now()) { const span = (ms) => { const d = Math.floor(ms / 86400000), h = Math.floor((ms % 86400000) / 3600000), m = Math.floor((ms % 3600000) / 60000); return d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`; }; const idx = TAX_PHASES_TG.findIndex((p) => nowMs >= p.from && (p.until === null || nowMs < p.until)); const now = idx >= 0 ? TAX_PHASES_TG[idx] : null; const later = idx >= 0 ? TAX_PHASES_TG.slice(idx + 1) : TAX_PHASES_TG; const lines = (p) => p.slices.map(([e, pct, what, note]) => `${e} ${pct} ${what}${note ? ` (${note})` : ''}`); const out = [ '⚙️ What the BOBAI bot does', '', `🤖 One Cloudflare Worker on wallet ${BOT_WALLET.slice(0, 6)}…${BOT_WALLET.slice(-4)}, every 10 minutes: trade → 3% tax collects in the token, which swaps it to BNB and sends it to that wallet → the bot splits it → ${nowMs < GG_END ? 'burns, liquidity, creator, agent, pot' : 'burns, liquidity, creator'}. No hand on the switch.`, '', ]; if (now) { out.push('💸 3% Tax Split — now', `📅 ${now.when} · ${now.name}`, ...lines(now)); if (now.until !== null) out.push(`⏳ this split ends in ${span(now.until - nowMs)}`); out.push(''); } if (later.length) { out.push('📆 Upcoming'); for (const p of later) out.push(`📅 ${p.when} · ${p.name}`, ...lines(p), ''); } out.push('🔗 Full schedule · 🔥 /burn · ☀️ /giggle · 🤖 /defi'); return out.filter((l, i, a) => l !== '' || a[i - 1] !== '').join('\n'); } // The burn card's figures: what the bot itself burned (its log), what sits at // the dead address (chain), and what both are worth today (pair reserves × // Chainlink). BOB is token0 in its pair, verified on-chain 2026-09-19. const BOB_TOKEN = '0x51363f073b1e4920fda7aa9e9d84ba97ede1560e'; const BOB_PAIR = '0x3c79593e01A7f7FeD5d0735B16621e2D52A6bC58'; async function readBobOnchain() { try { const balanceData = '0x70a08231' + DEAD.slice(2).padStart(64, '0'); const [deadHex, rHex, bnbUsd] = await Promise.all([ rpcCall('eth_call', [{ to: BOB_TOKEN, data: balanceData }, 'latest']), rpcCall('eth_call', [{ to: BOB_PAIR, data: '0x0902f1ac' }, 'latest']), getBnbUsd(), ]); const burned = deadHex ? Number(hexToBigInt(deadHex)) / 1e18 : null; let price = null; if (rHex && bnbUsd) { const rBob = BigInt('0x' + rHex.slice(2, 66)), rWbnb = BigInt('0x' + rHex.slice(66, 130)); if (rBob > 0n && rWbnb > 0n) price = (Number(rWbnb) / Number(rBob)) * bnbUsd; } return { burned, price }; } catch (e) { console.log('[bob] onchain error:', e.message || e); return { burned: null, price: null }; } } // Sums of the bot's own burns out of its log. The BOB figure sat under two // names over time ('bob' first, 'bobBurned' since the Worker) — both count. export function botBurnsFromLog(burns) { const list = Array.isArray(burns) ? burns : []; const n = (v) => parseFloat(v) || 0; return { runs: list.length, bobai: list.reduce((a, x) => a + n(x && x.bobaiBurned), 0), bob: list.reduce((a, x) => a + n(x && (x.bob || x.bobBurned)), 0), }; } // Billions read as B; the shared formatNumber stops at M because no BOBAI figure reaches 1e9. const fmtAmt = (n) => n >= 1e9 ? (n / 1e9).toFixed(2) + 'B' : formatNumber(n); const approxUsd = (amount, price) => price ? ` (≈${formatUsd(amount * price)})` : ''; // ==================== TAX STATUS (/tax, /buyback) ==================== // THE TAX, LIVE (operator, 2026-10-05: "a buyback command where you see the tax status — numbers must be right, USD // too"). The same figures as the website's tax tile (dashboard/app.js): the token queues its 3% as BOBAI in itself and // sends it on once it holds minDispatch(); the buyback wallet splits what it holds above its 0.003 BNB gas reserve once // that is more than 0.004 BNB (worker/index.js GAS_RESERVE + MIN_BNB), every 10 minutes. The last runs come from the // bot's own log (burns.json). The split itself stays on /bot. const TAX_GAS_RESERVE = 0.003, TAX_MIN_SPLIT = 0.004; const WBNB_TOKEN = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c'; async function readTaxOnchain() { const balOf = (a) => '0x70a08231' + a.slice(2).toLowerCase().padStart(64, '0'); const [qHex, mdHex, nHex, wHex, pair] = await Promise.all([ rpcCall('eth_call', [{ to: BOBAI_TOKEN, data: balOf(BOBAI_TOKEN) }, 'latest']), rpcCall('eth_call', [{ to: BOBAI_TOKEN, data: '0x110395bd' }, 'latest']), // minDispatch() rpcCall('eth_getBalance', [BOT_WALLET, 'latest']), rpcCall('eth_call', [{ to: WBNB_TOKEN, data: balOf(BOT_WALLET) }, 'latest']), readPairOnchain(), ]); const u18 = (h) => (h ? Number(hexToBigInt(h)) / 1e18 : null); const native = u18(nHex), wrapped = u18(wHex); return { queued: u18(qHex), minDispatch: u18(mdHex), walletBnb: native === null ? null : native + (wrapped || 0), price: pair ? pair.price : null, bnbUsd: pair ? pair.bnbUsd : await getBnbUsd() }; } export function formatTaxCard(t, burns = [], nowMs = Date.now()) { const span = (ms) => { const d = Math.floor(ms / 86400000), h = Math.floor((ms % 86400000) / 3600000), m = Math.floor((ms % 3600000) / 60000); return d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`; }; const usd = (n) => (n > 0 ? ` (≈${formatUsd(n)})` : ''); const out = ['💸 BOBAI Tax — live', '']; if (t.queued !== null && t.minDispatch > 0) { const pct = Math.min(t.queued / t.minDispatch * 100, 100), full = Math.floor(pct / 10); // 97% is not a full bar out.push(`🔋 Next buyback: ${pct < 10 ? pct.toFixed(1) : pct.toFixed(0)}% charged`, '▰'.repeat(full) + '▱'.repeat(10 - full), `🧠 ${fmtAmt(t.queued)} of ${fmtAmt(t.minDispatch)} BOBAI tax queued in the token${usd(t.queued * (t.price || 0))}`); } else { out.push('🔋 Next buyback: could not read the token right now'); } const split = t.walletBnb !== null && t.walletBnb > TAX_MIN_SPLIT ? t.walletBnb - TAX_GAS_RESERVE : 0; if (split > 0) out.push(`💰 + ${split.toFixed(4)} BNB in the bot wallet, split on its next run${usd(split * (t.bnbUsd || 0))}`); out.push('⚡ At 100% the token sends the tax on; the bot splits it within 10 minutes.', ''); const runs = (Array.isArray(burns) ? burns : []).filter((e) => e && Date.parse(e.time) > 0).sort((a, b) => Date.parse(a.time) - Date.parse(b.time)); const last = runs[runs.length - 1]; if (last) { const bnb = +last.totalBnb || 0, bobai = +last.bobaiBurned || 0, bob = +last.bobBurned || 0; out.push(`🔥 Last buyback: ${span(nowMs - Date.parse(last.time))} ago`, `${bnb.toFixed(4)} BNB${usd(bnb * (t.bnbUsd || 0))} → ${fmtAmt(bobai)} BOBAI${bob > 0 ? ` + ${fmtAmt(bob)} BOB` : ''} burned`); const day = runs.filter((e) => Date.parse(e.time) >= nowMs - 86400000), b24 = day.reduce((a, e) => a + (+e.bobaiBurned || 0), 0); out.push(`📊 Last 24h: ${day.length} buyback${day.length === 1 ? '' : 's'}${day.length ? ` · ${fmtAmt(b24)} BOBAI burned${usd(b24 * (t.price || 0))}` : ''}`); } else { out.push('🔥 Last buyback: the bot log did not answer'); } out.push('', `⚙️ Who gets what → /bot · 🔥 /burn · Bot wallet`); return out.join('\n'); } // ==================== LP AGENT DAILY REPORT ==================== // Once a day, after the 04:23 run. The numbers are the series' own summary // (agent.brainonbnb.com/lp/series — the same figures /defi opens with), // so the channel and the page never disagree; only the shape differs. The // one-sentence form of 2026-09-07 was asked away on 2026-09-09 for a sorted // card with lines and emojis, the essentials only ("das gleiche beim lp // agent im öffentlichen chat"). Pure, so it can be rendered against a real // series without posting. // THE DeFi CARD, from the portfolio model (agent.brainonbnb.com/lp/portfolio, // built by worker-agent/lp-portfolio.js). The same card answers /defi and // is posted at 05:00 UTC; the /defi page renders the same JSON. The bot // computes no number of its own here — the operator's rule: one source. // // Shape since 2026-09-12 (the operator: "einfacher, uebersichtlicher, // klarer"): four blocks with a blank line between, one figure per line. // Money in four decimals, dollars whole; the three lines under the result // add up to it (result = price + fees − gas). Details a reader does not // need for the picture — position id, the re-sets' realised loss, what a // width nets a day — stay in the record the card links to. // THE RANGE, DRAWN (2026-10-07, operator: "make the DeFi range visual in the // TG bot — so one sees how it stands"). Read from the chain at the moment of // the answer, not from the agent's last run: the pool's current tick // (slot0) and the position's own edges (positions(tokenId) on the V3 // position manager). token0 is CAKE, token1 WBNB, so a tick is the price of // one CAKE in BNB (1.0001^tick). Null when the chain does not answer — the // card then shows what it showed before. const V3_PM = '0x46a15b0b27311cedf172ab29e4f4766fbe7f4364'; const int24At = (hex, word) => Number(BigInt.asIntN(256, BigInt('0x' + hex.slice(2 + word * 64, 2 + (word + 1) * 64)))); async function readTicks(id) { const r = await rpcCall('eth_call', [{ to: V3_PM, data: '0x99fbab88' + BigInt(id).toString(16).padStart(64, '0') }, 'latest']); return r && r.length >= 2 + 64 * 7 ? { lower: int24At(r, 5), upper: int24At(r, 6) } : null; } export async function readDefiRange(pool) { try { if (!pool || !pool.address || !pool.position) return null; const [s0, main, res] = await Promise.all([rpcCall('eth_call', [{ to: pool.address, data: '0x3850c7bd' }, 'latest']), readTicks(pool.position), pool.reserve_position ? readTicks(pool.reserve_position) : null]); if (!s0 || s0.length < 2 + 128 || !main) return null; return { tick: int24At(s0, 1), main, reserve: res }; } catch { return null; } } // The range as one bar line, the edge prices under it (operator, 2026-10-07, third pass: "the prices under the bar, // | the rectangles | and the dot inside or outside — use the one line"): |▱▱▱●▱▱| with the dot where the price // stands, ● before or after the bar when the price has left it; then "lower ↔ upper BNB"; then the price itself. // 16 cells: wide enough to read, narrow enough for one line on a phone. Plain text — no
 and no box-drawing
// glyphs, which Telegram drew differently per device (the right edge came out as "<\>"). Pure: rendered in tests.
export function formatRangeBar(r) {
  if (!r || !r.main || !(r.main.upper > r.main.lower)) return [];
  const N = 16, px = (t) => Math.pow(1.0001, t), p = (t) => { const v = px(t); return v.toPrecision(4); };
  const { lower, upper } = r.main, t = r.tick, at = (t - lower) / (upper - lower);
  const i = Math.max(0, Math.min(N - 1, Math.floor(at * N)));
  const bar = at < 0 ? `● |${'▱'.repeat(N)}|` : at > 1 ? `|${'▱'.repeat(N)}| ●` : `|${'▱'.repeat(i)}●${'▱'.repeat(N - 1 - i)}|`;
  const where = at < 0 ? `${((1 - px(t - lower)) * 100).toFixed(1)}% below the range`
    : at > 1 ? `${((px(t - upper) - 1) * 100).toFixed(1)}% above the range`
    : `${Math.round(at * 100)}% up the range`;
  // the edge prices under the bar as "lower   -   upper" (operator, 2026-10-08: the 27-space gap wrapped onto two
  // lines on a small iPhone — "number, 3 spaces, -, 3 spaces, number")
  const lines = [bar, `${p(lower)}   -   ${p(upper)}`, `1 CAKE = ${p(t)} BNB · ${where}`];
  if (r.reserve && r.reserve.upper > r.reserve.lower) lines.push(`Reserve range: ${p(r.reserve.lower)} – ${p(r.reserve.upper)} BNB`);
  return lines;
}

export function formatDefiCard(m, { title = 'DeFi Agent', range = null } = {}) {
  if (!m || !m.put_in || !m.pnl) return null;
  const n = (x) => Number(x || 0);
  const bnb = (x) => n(x).toFixed(4) + ' BNB';
  const signed = (x) => (n(x) > 0 ? '+' : n(x) < 0 ? '−' : '') + n(Math.abs(n(x))).toFixed(4) + ' BNB';
  const usd = (x) => (x == null ? null : (n(x) < 0 ? '−' : '') + '$' + (Math.abs(n(x)) >= 20 ? Math.round(Math.abs(n(x))).toLocaleString('en-US') : Math.abs(n(x)).toFixed(2)));
  const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  const day = (iso, year) => { const s = String(iso || ''); const dd = Number(s.slice(8, 10)), mm = Number(s.slice(5, 7)); return dd && mm ? `${dd} ${MON[mm - 1]}${year ? ' ' + s.slice(0, 4) : ''}` : s.slice(0, 10); };
  const h = m.holdings, p = m.pnl, d = m.day || {};
  const arrow = n(p.profit_bnb) > 0 ? '▲' : n(p.profit_bnb) < 0 ? '▼' : '•';
  const pct = (n(p.change_pct) > 0 ? '+' : n(p.change_pct) < 0 ? '−' : '') + Math.abs(n(p.change_pct)).toFixed(1) + '%';
  // the chain's own answer wins over the agent's last check (that one may be an hour old)
  const inNow = range && range.main ? range.tick >= range.main.lower && range.tick < range.main.upper : m.pool.in_range;
  const rangeTxt = inNow == null ? '' : inNow ? '✅ in range' : `⏳ out of range${!range && m.pool.outside_hours != null ? ` for ${m.pool.outside_hours} h` : ''}`;
  const pool = [m.pool.label || 'the pool', m.pool.width_pct != null ? `±${m.pool.width_pct}%` : '', rangeTxt].filter(Boolean).join(' · ');
  const counts = [];
  if (d.resets) counts.push(`${d.resets} re-set${d.resets === 1 ? '' : 's'}`);
  if (d.top_ups) counts.push(`${d.top_ups} top-up${d.top_ups === 1 ? '' : 's'}`);
  if (d.collects) counts.push(`${d.collects} collect${d.collects === 1 ? '' : 's'}`);
  if (d.sweeps) counts.push(`${d.sweeps} sweep${d.sweeps === 1 ? '' : 's'}`);
  if (d.reserve_moves) counts.push(`${d.reserve_moves} reserve move${d.reserve_moves === 1 ? '' : 's'}`);
  if (d.errors) counts.push(`⚠️ ${d.errors} failed`);
  const join = (...xs) => xs.filter((x) => x != null && x !== '').join(' · ');
  const blocks = [
    // Dated by the newest check, not the last daily run: a /defi at 02:50
    // UTC shows this morning's worth, so it must not carry yesterday's date.
    [`💧 ${title} · ${day(m.checked_at || m.date, true)}`],
    [
      `📥 Put in: ${bnb(m.put_in.bnb)}${m.put_in.usd != null ? ' · ' + usd(m.put_in.usd) : ''}`,
      `💼 Worth now: ${bnb(m.worth.bnb)}${m.worth.usd != null ? ' · ' + usd(m.worth.usd) : ''}`,
      // What the position produced and no longer holds ($BOBAI at cost, fees
      // owed, kept fees waiting): worth + this − put in − gas = the result.
      ...(m.worth.beside_bnb > 0 ? [`➕ Beside it: ${bnb(m.worth.beside_bnb)} · $BOBAI held + fees`] : []),
      `💰 Result: ${arrow} ${signed(p.profit_bnb)} · ${join(p.profit_usd != null ? usd(p.profit_usd) : null, p.change_text || `${pct} on the capital since ${day(p.since)}`)}`,   // one wording, from the model (the page prints the same string)
      // the range standing now, right under the total, as on /defi since 7.11. (the total carries the narrow September ranges)
      ...(p.since_range && p.since_range.vs_holding_pct != null ? [(() => { const r = p.since_range, v = Number(r.vs_holding_pct);
        return `🎯 This range vs holding: ${v > 0 ? '+' : v < 0 ? '−' : ''}${Math.abs(v).toFixed(2)}% · ${signed(r.vs_holding_bnb)}${m.bnb_usd ? ' · ' + usd(r.vs_holding_bnb * m.bnb_usd) : ''} · ${r.width_pct ? '±' + r.width_pct + '%' : 'this range'} since ${day(r.since)}, ${r.days} days`; })()] : []),
    ],
    [
      ...(p.from_market_bnb != null && p.from_range_bnb != null
        ? ['Result = market + range + fees − gas', `📈 Market (held 50/50): ${signed(p.from_market_bnb)}`, `📈 Range, before fees: ${signed(p.from_range_bnb)}`] /* the page's own words (7.11.: "Range vs holding" here stood beside "This range vs holding" and read as its opposite) */
        : ['Result = price + fees − gas', `📈 Price: ${signed(p.from_price_bnb)}`]),
      `🧾 Fees: ${signed(p.from_fees_bnb)}`,
      `⛽ Gas: ${n(p.gas_bnb) > 0 ? '−' + bnb(p.gas_bnb) : '0 BNB'}`,
      ...(p.vs_holding && p.vs_holding.vs_holding_bnb != null ? [`⚖️ Vs. holding 50/50: ${signed(p.vs_holding.vs_holding_bnb)}`] : []),
      // the range standing now: its headline stands under the total since 7.11.; here what makes it, fees and price
      ...(p.since_range && p.since_range.fees_bnb != null ? [`🎯 This range: fees ${signed(p.since_range.fees_bnb)} · price ${signed(p.since_range.price_bnb)}`] : []),
    ],
    [
      `🥞 ${pool}`,
      ...formatRangeBar(range),
      ...(h.reserve && h.reserve.bnb > 0 ? [h.reserve.side === 'other' ? `🪜 Reserve range, the price fell through it: ${bnb(h.reserve.bnb)} · waits for the price to come back, then merges` : h.reserve.side === 'both' ? `🪜 Reserve range, the price inside it: ${bnb(h.reserve.bnb)} · earning beside the main range` : `🪜 Reserve below the price: ${bnb(h.reserve.bnb)} · buys on the way down, no trade`] : []),
      h.bobai_units > 0
        ? `🧠 ${Math.round(h.bobai_units).toLocaleString('en-US')} $BOBAI held${h.bobai_usd != null ? ' · ' + usd(h.bobai_usd) : ''} · bought from fees, never sold`
        : '🧠 No $BOBAI held yet. A third of every fee buys some.',
    ],
    [
      `🗓 Last 24 h: ${counts.length ? counts.join(', ') : 'quiet'}${d.last ? ` · last ${String(d.last.at).slice(11, 16)} UTC${d.last.error ? ' ⚠️' : ''}` : ''}`,
      `🧭 Next: ${m.next || '—'}`,
    ],
  ];
  if (!m.last_run_ok) blocks.push(['⚠️ One step failed at the last run. The operator has been told.']);
  blocks.push([`brainonbnb.com/defi · record`]);
  return blocks.map((b) => b.join('\n')).join('\n\n');
}

async function postLpDailyReport(env) {
  const today = new Date().toISOString().slice(0, 10);
  const done = await env.KV.get('lp_report_date');
  // Each way out says why. On 2026-09-08 the report stayed silent through
  // four ticks after the first 04:23 run while every condition held when
  // replayed from outside, and a function that returns false without a word
  // cannot be told apart from one that never ran.
  const skip = (why) => { console.log('[LP REPORT] skipped: ' + why); return false; };
  if (done === today) return skip('already posted today');
  const r = await fetch('https://agent.brainonbnb.com/lp/agent', { cf: { cacheTtl: 60 } });
  if (!r.ok) return skip('/lp/agent answered ' + r.status);
  const rec = await r.json();
  // The report is about today's daily run; if it has not landed yet, wait for
  // the next tick rather than reporting yesterday twice. The series takes its
  // point from that run on the agent worker's next scan, so the sentence
  // must already count today's run, else the next tick.
  if (!rec.last || String(rec.last.at || '').slice(0, 10) !== today) return skip('no run yet today; last ' + (rec.last && rec.last.at));
  const rs = await fetch('https://agent.brainonbnb.com/lp/series', { cf: { cacheTtl: 60 } });
  if (!rs.ok) return skip('/lp/series answered ' + rs.status);
  const series = await rs.json();
  const pts = Array.isArray(series.points) ? series.points : [];
  if (!pts.length || Date.parse(pts[pts.length - 1].at) < Date.parse(rec.last.at)) return skip('series has no point for the run yet; last point ' + (pts.length ? pts[pts.length - 1].at : 'none'));
  // The card is the portfolio model, the same the /defi command and the
  // /defi page show; the checks above only decide that today's run is in it.
  const pm = await fetch('https://agent.brainonbnb.com/lp/portfolio', { cf: { cacheTtl: 30 } }).then((x) => (x.ok ? x.json() : null)).catch(() => null);
  const text = formatDefiCard(pm, { range: pm ? await readDefiRange(pm.pool) : null });
  if (!text) return skip('nothing to say: the portfolio could not be read');
  console.log('[LP REPORT] posting for ' + today);
  // The day is marked done only once Telegram has taken the message; a
  // failed send used to mark it anyway, and the card was lost for the day.
  const sent = await tg('sendMessage', { chat_id: TG_CHAT_ID, text, parse_mode: 'HTML', disable_web_page_preview: true }).catch((e) => ({ ok: false, description: String(e && e.message || e) }));
  if (!sent || !sent.ok) return skip('Telegram refused the card: ' + (sent && sent.description));
  await env.KV.put('lp_report_date', today);
  return true;
}

// ==================== CHAT COMMANDS ====================

async function handleCommand(msg, env) {
  const rawText = (msg.text || '').trim();
  const firstWord = rawText.toLowerCase().split('@')[0].split(' ')[0];
  // A slash command is a command wherever it stands. A bare word ("price",
  // "buy", "help") only counts when it is the whole message — "buy the dip"
  // or "help me out" in the group is conversation, not a request to the bot.
  const singleWord = !/\s/.test(rawText);
  const text = (firstWord.startsWith('/') || singleWord) ? firstWord : '';
  const chatId = msg.chat.id;
  let reply = null;

  // ===== Admin-only whale commands (only inside TG_INTERNAL_CHAT_ID) =====
  const isInternal = TG_INTERNAL_CHAT_ID && String(chatId) === String(TG_INTERNAL_CHAT_ID);

  // Slash-prefixed (work everywhere, but silent-ignore outside internal chat)
  const WHALE_SLASH = ['/whales', '/whales24h', '/whaleadd', '/whalerm', '/whalecleanup', '/whalehelp'];
  if (WHALE_SLASH.includes(text)) {
    // /whales reads everywhere like every public command — the official group and a private chat with the bot
    // (operator, 2026-10-12: "I tap /whales and nothing comes" — it answered only in the group); the admin commands stay internal
    if (text === '/whales' && !isInternal) return handleWhaleAdmin(rawText, text, chatId, { public: true });
    if (!isInternal) return;
    return handleWhaleAdmin(rawText, text, chatId);
  }

  // Bare-word triggers inside the internal chat only — typing `whales`, `whales24h`,
  // `whaleadd 0x...`, `whalerm 0x...`, `whalehelp` works without the leading slash.
  const WHALE_BARE = ['whales', 'whales24h', 'whaleadd', 'whalerm', 'whalecleanup', 'whalehelp'];
  if (isInternal && WHALE_BARE.includes(firstWord)) {
    return handleWhaleAdmin(rawText, '/' + firstWord, chatId);
  }

  // Inside the internal chat: route /help and /start to whale help instead of public help.
  if (isInternal && (text === '/help' || text === '/start' || text === 'help')) {
    return handleWhaleAdmin(rawText, '/whalehelp', chatId);
  }

  switch (text) {
    case '/buy':
    case 'buy': {
      reply = `🛒 How to Buy BOBAI

Step 1: Get BNB in your wallet
MetaMask, Trust Wallet, or any Web3 Wallet (Binance / Bitget / Gate / OKX)

Step 2: Swap BNB → BOBAI
🔶 Binance Web3 Wallet
🟦 Bitget Wallet
🔵 Gate DEX
🟩 OKX Wallet
🤚 Four.Meme
🥞 PancakeSwap

Step 3: Set slippage to 6%, at any size (the 3% tax + a buffer: the quote already carries your price impact; under 3% the swap fails)
(3% on-chain tax on every trade)

📋 CA: ${BOBAI_TOKEN}`;
      break;
    }

    case '/defi':
    case 'defi': {
      // The DeFi agent as a portfolio — the same card the bot posts at
      // 05:00 UTC, from the same model the /defi page renders.
      const pm = await fetch('https://agent.brainonbnb.com/lp/portfolio', { cf: { cacheTtl: 30 } }).then((x) => (x.ok ? x.json() : null)).catch(() => null);
      reply = formatDefiCard(pm, { range: pm ? await readDefiRange(pm.pool) : null }) || '⚠️ Could not read the DeFi agent\'s record right now. Try again in a moment!';
      break;
    }

    case '/price':
    case 'price': {
      // Everything from the chain and from the bot's own ledger. No indexer
      // is asked: a third party's rate limiter must never decide whether the
      // person who typed /price gets a number.
      const [pair, burn, ledger] = await Promise.all([readPairOnchain(), getBurnStats(), readSwapLedger(env)]);
      if (!pair) {
        reply = '⚠️ Could not read the pool from the chain right now. Try again in a moment!';
        break;
      }
      let supply = 0;
      try { supply = await getTotalSupply(); } catch {}
      const price = pair.price, priceInBnb = pair.priceInBnb;
      const fdv = supply > 0 ? price * supply : null;
      // Market cap the way BscScan shows it under "Circulating Supply Market Cap":
      // total minus what sits in the dead address, times the price. FDV counts the
      // burned tokens too, so the two drift apart with every burn.
      const mcap = supply > 0 && burn.percent !== '?' ? price * (supply - burn.burnedTokens) : null;
      const liq = 2 * pair.wbnbReserve * pair.bnbUsd;
      const st = ledgerStats(ledger, priceInBnb);
      const usdOrNa = (v) => Number.isFinite(v) ? formatUsd(v) : 'n/a';
      const change = (v) => v == null ? 'n/a' : priceChangeArrow(v);
      const hoursTxt = st ? (st.hours >= LEDGER_HOURS - 0.5 ? '24h' : `${st.hours < 1 ? Math.max(1, Math.round(st.hours * 60)) + ' min' : st.hours.toFixed(1).replace(/\.0$/, '') + 'h'}`) : '24h';
      const volumeUsd = st ? st.vol_bnb * pair.bnbUsd : null;

      reply = `📊 BOBAI Live Price

💰 $${price.toFixed(8)}
💎 ${priceInBnb.toFixed(10)} BNB

📈 Price Change
1h: ${change(st && st.h1)}  ·  6h: ${change(st && st.h6)}  ·  24h: ${change(st && st.h24)}

📊 Market Stats
🏷 Market Cap: ${usdOrNa(mcap)}
🏷 FDV: ${usdOrNa(fdv)}
💧 Liquidity: ${usdOrNa(liq)}
📦 ${hoursTxt} Volume: ${st ? usdOrNa(volumeUsd) : 'n/a'}
🔄 ${hoursTxt} Trades: ${st ? `${st.buys} buys / ${st.sells} sells` : 'n/a'}

🔥 Burned: ${burn.burnedTokens === null ? '? (the chain read failed, try again)' : `${burn.percent}% (${formatNumber(burn.burnedTokens)} BOBAI${price ? ` ≈${formatUsd(burn.burnedTokens * price)}` : ''})`}

⛓ Read from the chain: pool reserves, Chainlink BNB feed, swap events${st ? (st.hours >= LEDGER_HOURS - 0.5 ? ' of the last 24 h' : ` of the last ${hoursTxt} (record still filling)`) : ' (record starts with the next tick)'}. No price site.

📈 Chart · 🦎 GeckoTerminal`;
      break;
    }

    case '/pop':
    case 'pop': {
      const get = (u) => fetch(u, { signal: AbortSignal.timeout(10000) }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
      const [d, all, pool, px] = await Promise.all([get('https://brainonbnb.com/api/pop/top?scope=day'), get('https://brainonbnb.com/api/pop/top?scope=all'), get('https://brainonbnb.com/api/pop/pool'), get('https://brainonbnb.com/api/price')]);
      reply = d || all ? renderPopNow(new Date().toISOString().slice(0, 10), d, all, pool, px && px.price_usd) : 'The Brain Pop board did not answer just now. Try again in a minute, or play: https://brainonbnb.com/m/pop?from=tg';
      break;
    }
    case '/giggle':
    case 'giggle': {
      let burns = null;
      try {
        const r = await fetch('https://logs.brainonbnb.com/logs/burns.json', { cf: { cacheTtl: 120 } });
        if (r.ok) burns = await r.json();
      } catch { /* said on the card below */ }
      let donation = null;
      try { const d = await fetch('https://brainonbnb.com/giggle-donation.json', { cf: { cacheTtl: 60 } }); if (d.ok) donation = await d.json(); } catch { /* the card says on its way */ }
      reply = formatGiggleCard(burns || [], Date.now(), await getBnbUsd(), donation);
      if (!Array.isArray(burns)) reply += '\n\nThe bot log did not answer just now, so the sends are not counted. Try again in a minute.';
      break;
    }
    case '/burn':
    case 'burn': {
      // Two tokens, two figures each: what the bot burned (its log) and what
      // the dead address holds (chain), both in dollars of today. The split
      // itself moved to /bot (2026-09-19).
      let burns = null;
      try {
        const r = await fetch('https://logs.brainonbnb.com/logs/burns.json', { cf: { cacheTtl: 120 } });
        if (r.ok) burns = await r.json();
      } catch { /* said on the card below */ }
      const logOk = Array.isArray(burns); if (!logOk) burns = [];
      const [burn, bob, pair] = await Promise.all([getBurnStats(), readBobOnchain(), readPairOnchain()]);
      const ours = botBurnsFromLog(burns);
      const bobaiPx = pair ? pair.price : null;
      const share = (a, b) => b > 0 ? ` · ${(a / b * 100).toFixed(1)}% of it` : '';

      reply = `🔥 BOBAI Burn Dashboard

🧠 $BOBAI
🤖 Burned by the bot: ${logOk ? `${fmtAmt(ours.bobai)} BOBAI${approxUsd(ours.bobai, bobaiPx)}` : 'the bot log did not answer, try again'}
💀 At the dead address: ${burn.burnedTokens === null ? 'the chain read failed, try again' : `${fmtAmt(burn.burnedTokens)} BOBAI${approxUsd(burn.burnedTokens, bobaiPx)} · ${burn.percent}% of supply`}

👷 $BOB (Build On BNB)
🤖 Burned by the bot: ${logOk ? `${fmtAmt(ours.bob)} BOB${approxUsd(ours.bob, bob.price)}${share(ours.bob, bob.burned)}` : 'the bot log did not answer'}
💀 At the dead address: ${bob.burned === null ? '?' : fmtAmt(bob.burned)} BOB${bob.burned === null ? '' : approxUsd(bob.burned, bob.price)}

⚙️ ${logOk ? `${ours.runs.toLocaleString('en-US')} bot runs in the log · ` : ''}checks every 10 minutes from ${BOT_WALLET.slice(0, 6)}…${BOT_WALLET.slice(-4)} · /bot shows the split

🔗 BOBAI burns · BOB burns · Live burns`;
      break;
    }
    case '/bot':
    case 'bot': {
      reply = formatBotCard();
      break;
    }

    case '/tax':
    case 'tax':
    case '/buyback':
    case 'buyback': {
      let burns = [];
      try {
        const r = await fetch('https://logs.brainonbnb.com/logs/burns.json', { cf: { cacheTtl: 120 } });
        if (r.ok) burns = await r.json();
      } catch { /* the chain figures still show; the last run says the log did not answer */ }
      reply = formatTaxCard(await readTaxOnchain(), burns);
      break;
    }

    case '/liq':
    case 'liq':
    case 'liquidity':
    case '/depth': {
      const lq = await fetchLiquidityStats();
      if (!lq) {
        reply = '⚠️ Could not read the pool right now. Try again in a moment!';
        break;
      }

      // Explicit 'en-US' everywhere — never let the runtime pick the separators.
      const usd0 = n => '$' + Math.round(n).toLocaleString('en-US');
      const usd2 = n => '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      const pc = n => n.toFixed(2) + '%';
      const signed = n => (n > 0 ? '+' : '') + n.toFixed(2) + '%';
      const row = (d, imp, cost) =>
        `$${d.usd.toLocaleString('en-US')} · ${signed(imp)} · costs ${pc(cost)}`;

      const ratios = [];
      if (lq.mcap) ratios.push(`💧 Liq / Mcap: ${(lq.tvl / lq.mcap * 100).toFixed(1)}%`);
      if (lq.mcap) ratios.push(`🔒 Hard BNB backing: ${(lq.bnbSide / lq.mcap * 100).toFixed(1)}% of mcap`);
      // 99.9996% is not 100.000% (the dashboard says the same, pcEdge in app.js).
      if (lq.lpBurnedPct !== null) ratios.push(`🔥 LP burned: ${lq.lpBurnedPct >= 99.9995 && lq.lpBurnedPct < 100 ? '>99.999' : lq.lpBurnedPct.toFixed(3)}%`);

      reply = `💧 BOBAI Liquidity Depth
Read from the pool contract${lq.block ? ' at block ' + lq.block.toLocaleString('en-US') : ' just now'}.

💎 Pool: ${usd0(lq.tvl)} (both sides)
🟡 BNB side: ${usd0(lq.bnbSide)} · ${lq.rBnb.toFixed(2)} BNB
🧠 BOBAI side: ${formatNumber(lq.rTok)} BOBAI
${ratios.join('\n')}

What moves the price 1%
🟢 A buy of ${usd2(lq.up1)} → +1%
🔴 A sell of ${usd2(lq.dn1)} → −1%

Buying — price up
${lq.depth.map(d => row(d, d.impactBuy, d.costBuy)).join('\n')}

Selling — price down
${lq.depth.map(d => row(d, d.impactSell, d.costSell)).join('\n')}

💡 Impact = how far the trade moves the price. Cost = what you give up vs spot (3% tax + 0.25% LP fee + fill) — 3.24% of it applies at any size.
💡 Every LP add is burned to the dead address. Nobody can pull it.

📊 Full depth panel · 🔍 Pool contract`;
      break;
    }

    case '/social':
    case 'social':
    case 'socials':
    case '/links':
    case 'links': {
      reply = `🧠 BOBAI — All Links

🌍 Website & Dashboard

🐦 Birdeye
🔷 Blockspot.io
🫧 Bubblemaps
🔍 BscScan
🦎 CoinGecko
🌙 CoinMun
🦅 DEX Screener
🌐 DEXTools.io
😉 FunTok
🦎 GeckoTerminal
🟪 Genius
🐊 GMGN.AI
🫆 InsightX

🔶 Binance Web3 Wallet
🟦 Bitget Wallet
🔵 Gate DEX
🟩 OKX Wallet
🤚 Four.Meme
🥞 PancakeSwap

🐦 X Official
🎮 Game
⚽ Worldcup '26
🎁 Buy Drops NFT
🧠 brainScreener
📊 Pool Scanner (Beta)

📋 CA: ${BOBAI_TOKEN}`;
      break;
    }

    case '/contract':
    case 'contract':
    case '/ca':
    case 'ca': {
      reply = `📋 BOBAI Contract

${BOBAI_TOKEN}

Tap to copy — paste in your DEX

🔍 View on BscScan`;
      break;
    }

    case '/security':
    case 'security':
    case '/scam':
    case 'scam': {
      reply = `⚠️ BOBAI Security Notice

🚫 Admins will NEVER DM you first
🚫 NEVER share your seed phrase or private key
🚫 NEVER connect your wallet to unknown sites
🚫 No giveaways, no presales, no airdrops via DM

✅ Official Links Only
🌍 brainonbnb.com
💬 t.me/bobai_official
🐦 x.com/BrainOnBNB

📋 Official CA:
${BOBAI_TOKEN}

Anything else = scam. Stay safe.`;
      break;
    }

    case '/alerts':
    case 'alerts': {
      reply = `🔔 BOBAI Alert Tiers

🧠 Buy Alert Tiers
💰 $100+ → NICE BUY!
💎 $150+ → BIG BUY!
🚀 $250+ → HUGE BUY!
🐋 $500+ → WHALE BUY!
⚡ $1000+ → THUNDER BUY!
🦑 $2500+ → KRAKEN BUY!

🔥 Burn Alert Tiers
♻️ < $5 → BURN
🕯️ $5+ → NICE BURN!
🌋 $15+ → BIG BURN!
💀 $50+ → MEGA BURN!
☄️ $150+ → APOCALYPSE BURN!
💥 $250+ → SUPERNOVA BURN!

💡 Buys under $100 are not alerted.`;
      break;
    }

    case '/help':
    case 'help':
    case '/start': {
      reply = `🤖 Welcome to the BOBAI Bot!

Here's what I can do:

🔔 /alerts — Buy & burn alert tiers
⚙️ /bot — What the bot does: the 3% split now & upcoming
🔥 /burn — Burned by the bot & at the dead address, BOBAI and BOB, in USD
🛒 /buy — How to buy BOBAI
📋 /ca — Contract address
🤖 /defi — The DeFi agent as a portfolio: put in, worth, P&L, last 24 h
☀️ /giggle — Giggle Academy pot: countdown & BNB collected
💧 /liq — Liquidity depth, price impact & trade cost
🎁 /nft — Buy Drops NFT — tier progress & latest mints
🎮 /pop — Brain Pop: today's board, the prize pool, play
📊 /price — Live price, volume & market stats
⚠️ /security — Anti-scam reminder & official links
🧠 /social — All project links
💸 /tax — Tax live: next buyback charge, last buyback, last 24 h
🐋 /whales — The BOBAI whales: holdings, 24 h activity, who moved
🏆 /worldcup — Worldcup '26 tipgame, final results

💡 I also post alerts for buys, burns & whale moves!

🌍 Website · 📈 Chart`;
      break;
    }

    case '/chatid':
    case 'chatid': {
      const info = {
        chat_id: msg.chat.id,
        chat_type: msg.chat.type,
        chat_title: msg.chat.title || null,
        from_user: msg.from?.username || msg.from?.id || null,
      };
      console.log('[CHATID]', JSON.stringify(info));
      reply = `🆔 Chat Info
chat_id: ${msg.chat.id}
type: ${msg.chat.type}
title: ${msg.chat.title || '(private)'}`;
      break;
    }

    case '/worldcup':
    case 'worldcup':
    case '/wc':
    case 'wc': {
      const [pool, top10, playerCount, donations, taxAdds, payouts] = await Promise.all([
        fetchWorldcupPool(),
        fetchWorldcupLeaderboard(10),
        fetchWorldcupPlayerCount(),
        fetchWorldcupDonations(3, false),
        fetchWorldcupDonations(3, true),
        // what each sent payout was worth when it was sent (2026-10-23): the same sum the archive page shows
        sbSelect('wc_payouts', 'select=pot,usd_at_payout&tx_hash=not.is.null'),
      ]);
      const regLine = playerCount != null ? ` (of ${playerCount})` : '';

      const total = pool ? parseFloat(pool.total_bobai) || 0 : 0;
      const price = pool ? parseFloat(pool.bobai_price_usd) || 0 : 0;
      const hasPrice = price > 0;
      // a pot in dollars is the sum of its payouts at the price of the day each was sent (group 28 Jun, the rest
      // 20 Jul); the July price is only the fallback for a pot without recorded values
      const paidUsd = (pot) => (payouts || []).filter((r) => !pot || r.pot === pot).reduce((a, r) => a + (parseFloat(r.usd_at_payout) || 0), 0);
      const usd = (amount, pot) => { const v = paidUsd(pot); return v > 0 ? formatUsd(v) : hasPrice ? formatUsd(amount * price) : 'n/a'; };
      const groupPot  = pool ? parseFloat(pool.group_pot)  || 0 : 0;
      const endPool   = pool ? parseFloat(pool.endpool)    || 0 : 0;
      const cryptoPot = pool ? parseFloat(pool.crypto_pot) || 0 : 0;

      let leaderboardLines;
      if (top10.length === 0) {
        leaderboardLines = 'No players yet — be the first!';
      } else {
        const medals = ['🥇','🥈','🥉'];
        leaderboardLines = top10.map((r, i) => {
          const rank = medals[i] || `#${String(i+1).padStart(2,' ')}`;
          const flag = isoToFlag(r.avatar_country);
          const wallet = r.has_wallet ? ' ⚽' : '';
          const pts = (r.total_points || 0);
          return `${rank} ${flag} ${shownName(r.username)}${wallet} ${pts} pts`;
        }).join('\n');
      }

      const fmtTxLine = (row) => {
        const when = new Date(row.created_at).toISOString().slice(5,16).replace('T',' ');
        const inAmt = parseFloat(row.amount_in) || 0;
        const bobai = parseFloat(row.amount_bobai) || 0;
        const unit  = row.token === 'TAX' ? 'BNB' : row.token;
        const link  = row.swap_tx_hash
          ? `↗`
          : '';
        return `${when} · ${inAmt.toFixed(4)} ${unit} → ${formatNumber(bobai)} BOBAI ${link}`;
      };

      const donLines = donations.length
        ? donations.map(fmtTxLine).join('\n')
        : 'None yet';
      const taxLines = taxAdds.length
        ? taxAdds.map(fmtTxLine).join('\n')
        : 'No tax routing recorded';

      reply = `🏆 BOBAI Worldcup '26 — Prize Pool

💰 ${formatNumber(total)} BOBAI ≈ ${usd(total, null)} at payout

📊 Pots
🅰️ Group · 60 %: ${formatNumber(groupPot)} BOBAI (${usd(groupPot, 'group')})
🏁 End pool · 30/90 %: ${formatNumber(endPool)} BOBAI (${usd(endPool, 'end')})
📈 Crypto · 10 %: ${formatNumber(cryptoPot)} BOBAI (${usd(cryptoPot, 'crypto')})

🏅 Top 10 Overall${regLine}
${leaderboardLines}

💚 Latest donations
${donLines}

⚙️ Latest tax adds
${taxLines}

🎮 Play at brainonbnb.com/worldcup

⚽ = wallet linked (payout-eligible)`;
      break;
    }

    case '/nft':
    case 'nft': {
      const state = await fetchNftState();
      const tiers = state && state.minted && state.cap ? { minted: state.minted, cap: state.cap } : null;
      const allDrops = state?.drops || [];
      const drops = allDrops.slice(0, 3);

      let progressLines, totalMinted = 0, totalCap = 0;
      if (!tiers) {
        progressLines = 'Tier data unavailable — try again in a moment.';
      } else {
        progressLines = NFT_TIERS.map(([emoji, label, thr], i) => {
          const m = tiers.minted[i], c = tiers.cap[i];
          totalMinted += m; totalCap += c;
          const labelPad = `${emoji} ${label}`.padEnd(12, ' ');
          const thrPad   = `$${thr}+`.padEnd(7, ' ');
          return `${labelPad} ${thrPad} ${nftProgressBar(m, c)}  ${m} / ${c}`;
        }).join('\n');
      }
      if (totalCap === 0) totalCap = 1925; // fallback so header still reads sensibly on fetch fail

      // Prefer live on-chain holder count (picks up secondary transfers like donations).
      // Fall back to unique mint recipients if the API didn't return it.
      const uniqueHolders = (typeof state?.holders === 'number')
        ? state.holders
        : new Set(allDrops.map(d => d.to).filter(Boolean)).size;
      const dropLines = drops.length
        ? drops.map(d => {
            const when = new Date(d.ts * 1000).toISOString().slice(5, 16).replace('T', ' ');
            const [tEmoji, tLabel] = NFT_TIERS[d.tier] || ['?', '?'];
            const [rEmoji, rLabel] = NFT_RARITIES[d.rarity] || ['?', '?'];
            const txHash = d.mintTx || d.tx;
            const idLabel = d.tokenId != null ? `#${d.tokenId}` : '↗';
            const idLink  = txHash ? `${idLabel}` : idLabel;
            return `${when} · ${tEmoji} ${tLabel} × ${rEmoji} ${rLabel} · $${d.usd} · ${idLink}`;
          }).join('\n')
        : 'No drops yet — be the first!';

      const holdersLine = uniqueHolders > 0
        ? ` · ${uniqueHolders} unique holder${uniqueHolders === 1 ? '' : 's'}`
        : '';

      reply = `🎁 BOBAI Buy Drops — NFT Collection

🟢 ${totalMinted} / ${totalCap} minted${holdersLine}

📊 Tier Progress
${progressLines}

🎰 Latest Drops
${dropLines}

🎯 How it works
Buy ≥$100 of $BOBAI → auto-mint NFT to your wallet.
Tier = buy size · Rarity = rolled probabilistically.
Sold out tiers stop minting (no refund, no promote).

🖼 brainonbnb.com/nft · 📜 BscScan`;
      break;
    }

    default: {
      // A slash command the bot does not know (a retired /scan, a typo) gets
      // one line in a private chat; in the group it stays silent, as before.
      if (msg.chat && msg.chat.type === 'private' && text.startsWith('/')) reply = 'I don\'t know that command. /help lists what I can do.';
      break;
    }
  }

  if (reply) {
    await tg('sendMessage', {
      chat_id: chatId,
      text: reply,
      parse_mode: 'HTML',
      disable_web_page_preview: true,
    });
  }
}

// ==================== WORKER ENTRY ====================

export default {
  // Webhook handler (Telegram sends updates here)
  async fetch(request, env) {
    TG_BOT_TOKEN = env.BOT_TOKEN;
    TG_INTERNAL_CHAT_ID = env.TG_INTERNAL_CHAT_ID || '';
    WHALE_ENV = env;

    // === /broadcast — authenticated "brain update" announcement endpoint ===
    // POST /broadcast with header `X-Broadcast-Secret: `
    // and JSON body `{ text: "" , prefixBrain?: true, disablePreview?: true }`.
    // Sends a lone 🧠 first (Telegram renders 1-3 emoji-only messages as JUMBO size,
    // which acts as the visual "this is an update" header) followed by the announcement.
    // Used by tg-update.js to broadcast workshop updates without exposing BOT_TOKEN locally.
    const url = new URL(request.url);

    // === /health — liveness, readable by anyone, secrets by nobody ===
    // Reports the last cron tick (written every tenth minute by scheduled()),
    // its age, and whether the bot is configured to post at all. A check that
    // only proved the worker answers HTTP would be worthless: a worker whose
    // cron has stopped still answers HTTP perfectly.
    // /health?sources=1 additionally probes every price source from inside
    // the Worker: the chain read and the two indexers, with the HTTP status
    // each one returns to Cloudflare. That is the view the bot has, not the
    // view a laptop has — the two differ whenever an indexer blocks Workers.
    if (url.pathname === '/health' && request.method === 'GET' && url.searchParams.get('sources')) {
      const probe = async (name, u) => {
        const t0 = Date.now();
        try {
          const r = await fetch(u, { headers: { 'Accept': 'application/json' } });
          const body = (await r.text()).slice(0, 160);
          return { name, status: r.status, ms: Date.now() - t0, body: r.ok ? undefined : body };
        } catch (e) { return { name, status: null, ms: Date.now() - t0, error: e.message || String(e) }; }
      };
      const [pair, gecko, dex] = await Promise.all([
        readPairOnchain(),
        probe('geckoterminal', `${GECKO_POOL_URL}?_=${Date.now()}`),
        probe('dexscreener', `https://api.dexscreener.com/latest/dex/tokens/${BOBAI_TOKEN}`),
      ]);
      return new Response(JSON.stringify({
        ok: true,
        chain: pair ? { price_usd: pair.price, bnb_usd: pair.bnbUsd } : null,
        indexers: [gecko, dex],
        ledger: await (async () => { const l = await readSwapLedger(env); const st = ledgerStats(l, pair ? pair.priceInBnb : 0); return st ? { buckets: l.length, hours: Number(st.hours.toFixed(2)), trades: st.trades, vol_bnb: Number(st.vol_bnb.toFixed(4)), h1: st.h1, h6: st.h6, h24: st.h24 } : { buckets: 0 }; })(),
      }, null, 2), { headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } });
    }

    // === /candles — the 24-hour ledger above, readable by anyone (2026-09-26) ===
    // The Brain Terminal draws BOBAI's chart from it: one ten-minute bucket per candle, the close from the pool's
    // reserves, the wicks from the swaps' own prices. Public on-chain figures only; one KV read, cached a minute.
    if (url.pathname === '/candles' && request.method === 'GET') {
      const rows = (await readSwapLedger(env)).filter((x) => x.price_bnb > 0).map((x) => ({ t: x.t, c: x.price_bnb, h: x.hi_bnb || null, l: x.lo_bnb || null, v: x.vol_bnb, ...(x.own_bnb ? { o: x.own_bnb } : {}), b: x.buys, s: x.sells, u: x.bnb_usd, ...(x.big ? { x: x.big } : {}),
        // what each side moved, in BNB (2026-10-18): the terminal says a red day in dollars — sold against bought — not only in counts
        ...(x.buy_bnb != null ? { bb: x.buy_bnb, sb: x.sell_bnb } : {}) }));
      return new Response(JSON.stringify({ minutes: BUCKET_MINUTES, source: 'PancakeSwap pool Swap events + reserves, read every ten minutes', rows }), {
        headers: { 'content-type': 'application/json', 'cache-control': 'public, max-age=60', 'access-control-allow-origin': '*' },
      });
    }

    if (url.pathname === '/health' && request.method === 'GET') {
      const last = await env.KV.get('last_cron');
      const ageSeconds = last ? Math.round((Date.now() - new Date(last).getTime()) / 1000) : null;
      return new Response(JSON.stringify({
        ok: true,
        worker: 'bobai-tg-bot',
        last_cron: last || null,
        age_seconds: ageSeconds,
        // A heartbeat older than a quarter hour means the every-minute cron has
        // missed its ten-minute write, which is a stopped worker, not a lull.
        cron_alive: ageSeconds !== null && ageSeconds < 900,
        channel_configured: Boolean(env.BOT_TOKEN && TG_CHAT_ID),
        // the last send Telegram refused (noteSendError), null when none ever was; `lasting` = kicked / no rights / chat gone
        last_send_error: await env.KV.get('last_send_error', 'json').catch(() => null),
        alerts: ['buys', 'burns'],
        // The date each daily post last went out. A running cron says nothing
        // about them: the whale recap was silent for six days in September
        // 2026 under a heartbeat that never missed.
        daily: { whale_recap: await env.KV.get('last_daily_summary'), lp_card: await env.KV.get('lp_report_date'), market_card: await env.KV.get('market_card_date') },
        webhook_secured: Boolean(env.TG_WEBHOOK_SECRET) && Boolean(await env.KV.get('webhook_secret_version')),
        ...(await healthEvidence(env)),
      }), { headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } });
    }

    // === /previewbuy — what a buy alert of a given size looks like ===
    // POST {"usd": 1417} with X-Broadcast-Secret. Runs the real postBuyAlert
    // with made-up trade figures and sends it to the OPERATOR's private chat,
    // which is the only chat this route can reach: there is no target field.
    if (url.pathname === '/previewbuy' && request.method === 'POST') {
      const want = env.BROADCAST_SECRET || '';
      if (!want || (request.headers.get('x-broadcast-secret') || '') !== want)
        return new Response(JSON.stringify({ ok: false, error: 'unauthorized' }), { status: 401, headers: { 'content-type': 'application/json' } });
      let body = {};
      try { body = await request.json(); } catch { }
      const usd = Math.min(100000, Math.max(1, Number(body.usd) || 1417));
      if (body.kind === 'burn') {
        const price = 0.00023, prev = 104000000;
        const sent = await postBurnAlert(prev + usd / price, prev, 1000000000, price, OPERATOR_CHAT_ID);
        return new Response(JSON.stringify({ ok: !!sent, kind: 'burn', went_out_as: sent || null, photo_refused: lastPhotoRefusal, caption: lastCaption, usd }), { headers: { 'content-type': 'application/json' } });
      }
      // The longest NFT line an alert really carries, so the preview measures
      // the room a real KRAKEN alert has, not a shorter one.
      const nft = body.nft === false ? '' : '\n🎁 +1 NFT #1925 · 🦑 KRAKEN × 🩷 Legendary · 1925/1925';
      const price = 0.00023, bnbUsd = 780;
      const sent = await postBuyAlert({ bnbAmount: usd / bnbUsd, bobaiAmount: usd / price, usdValue: usd, buyer: '0x000000000000000000000000000000000000dEaD', txHash: '0x' + '0'.repeat(64) },
        '0.00', nft + '\n🧪 Preview — made-up figures, sent to the operator only', OPERATOR_CHAT_ID, body.uncapped === true,
        // the longest context line a real alert carries (2026-10-09), so the preview measures the same room
        (body.context === false ? '' : '\n📊 Holds 12.34M BOBAI (≈$2.8K) · 12th buy from this wallet this week · largest buy in 7 days')
        // "tracked": true — the line a buyer the whale watcher tracks gets (2026-10-15)
        + (body.tracked === true ? trackedBuyLine({ addr: '0x000000000000000000000000000000000000dEaD', buyer: '0x000000000000000000000000000000000000dEaD', bal: 42.1e6, rank: 4 }) : ''));
      return new Response(JSON.stringify({ ok: !!sent, went_out_as: sent || null, photo_refused: lastPhotoRefusal, caption: lastCaption, usd }), { headers: { 'content-type': 'application/json' } });
    }

    // THE GATE, ASKED LIVE (2026-10-23): claims one throwaway key twice and releases it — [true, false] proves the
    // Durable Object answers and refuses a second claim. Operator only (the broadcast secret); sends nothing.
    if (url.pathname === '/gate-check' && request.method === 'POST') {
      if (!env.BROADCAST_SECRET || (request.headers.get('x-broadcast-secret') || '') !== env.BROADCAST_SECRET) return new Response('{"ok":false,"error":"unauthorized"}', { status: 401 });
      const k = 'selftest-' + Date.now();
      const first = await claimAlert(env, 'check', k), second = await claimAlert(env, 'check', k);
      await releaseAlert(env, 'check', k);
      const third = await claimAlert(env, 'check', k);
      await releaseAlert(env, 'check', k);
      return new Response(JSON.stringify({ ok: first === true && second === false && third === true, bound: !!env.GATE, claims: [first, second, third] }), { headers: { 'content-type': 'application/json' } });
    }
    if (url.pathname === '/broadcast' && request.method === 'POST') {
      const got = request.headers.get('x-broadcast-secret') || '';
      const want = env.BROADCAST_SECRET || '';
      if (!want || got !== want) {
        return new Response(JSON.stringify({ ok: false, error: 'unauthorized' }), {
          status: 401, headers: { 'content-type': 'application/json' },
        });
      }
      let body = {};
      try { body = await request.json(); } catch (e) {
        return new Response(JSON.stringify({ ok: false, error: 'invalid json' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const text = (body.text || '').toString().trim();
      if (!text) {
        return new Response(JSON.stringify({ ok: false, error: 'missing text' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      // target: 'internal' routes to TG_INTERNAL_CHAT_ID (BOBAI Intern).
      // Default = public group (TG_CHAT_ID). Brain prefix defaults off for internal.
      const targetChat = body.target === 'operator' ? OPERATOR_CHAT_ID : body.target === 'internal' ? TG_INTERNAL_CHAT_ID : TG_CHAT_ID;
      if (!targetChat) {
        return new Response(JSON.stringify({ ok: false, error: `target chat not configured` }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const wantBrain = (body.target === 'internal' || body.target === 'operator') ? body.prefixBrain === true : body.prefixBrain !== false;
      // ONCE (2026-10-15): the health worker's morning message came twice on 14.10. (09:11 and 09:12 UTC) with no
      // retry anywhere in the code — a cron trigger fired twice. A caller may name the message with `once`; the same
      // name within 2 days is answered as sent and not sent again.
      const onceKey = body.once ? `bc-once:${String(body.once).slice(0, 120)}` : null;
      if (onceKey && env.KV) {
        const seen = await env.KV.get(onceKey).catch(() => null);
        if (seen) {
          return new Response(JSON.stringify({ ok: true, message_id: Number(seen) || null, duplicate: true }), {
            headers: { 'content-type': 'application/json' },
          });
        }
        await env.KV.put(onceKey, 'pending', { expirationTtl: 172800 }).catch(() => {});
      }
      try {
        if (wantBrain) {
          await tg('sendMessage', {
            chat_id: targetChat,
            text: '🧠',
            disable_notification: true,
          });
        }
        const send = () => tg('sendMessage', {
          chat_id: targetChat,
          text,
          parse_mode: 'HTML',
          disable_web_page_preview: body.disablePreview !== false,
        });
        // A REFUSED SEND IS NOT SENT (2026-10-17): tg() answers {ok:false} instead of throwing, so on 16.10. a Telegram
        // timeout (09:11 UTC, "no answer within 10 s") left the once-key at 'pending' and the morning message never came.
        // One more try after 5 s; still nothing -> the key goes and the caller hears ok:false.
        let r = await send();
        if (!r?.result?.message_id) { await new Promise((ok) => setTimeout(ok, 5000)); r = await send(); }
        if (!r?.result?.message_id) {
          if (onceKey && env.KV) await env.KV.delete(onceKey).catch(() => {});
          return new Response(JSON.stringify({ ok: false, error: 'send failed', description: String(r?.description || '').slice(0, 160) }), {
            status: 502, headers: { 'content-type': 'application/json' },
          });
        }
        if (onceKey && env.KV) await env.KV.put(onceKey, String(r.result.message_id), { expirationTtl: 172800 }).catch(() => {});
        return new Response(JSON.stringify({ ok: true, message_id: r?.result?.message_id || null }), {
          headers: { 'content-type': 'application/json' },
        });
      } catch (err) {
        console.error('[BROADCAST ERROR]', err.message || err);
        if (onceKey && env.KV) await env.KV.delete(onceKey).catch(() => {});
        return new Response(JSON.stringify({ ok: false, error: 'send failed' }), {
          status: 500, headers: { 'content-type': 'application/json' },
        });
      }
    }

    // === /broadcastphoto — authenticated announcement with an image ===
    // POST multipart/form-data with header `X-Broadcast-Secret: `
    // and fields: `photo` (image file), `caption` (HTML, optional, max 1024 chars —
    // Telegram's caption limit), `target` ('internal' routes to TG_INTERNAL_CHAT_ID),
    // `prefixBrain` ('0' disables the jumbo 🧠 header).
    // Mirrors /broadcast but sends one sendPhoto message instead of text, so a report
    // card and its numbers arrive together. BOT_TOKEN never leaves Cloudflare.
    if (url.pathname === '/broadcastphoto' && request.method === 'POST') {
      const got = request.headers.get('x-broadcast-secret') || '';
      if (!env.BROADCAST_SECRET || got !== env.BROADCAST_SECRET) {
        return new Response(JSON.stringify({ ok: false, error: 'unauthorized' }), {
          status: 401, headers: { 'content-type': 'application/json' },
        });
      }
      let inForm;
      try { inForm = await request.formData(); } catch (e) {
        return new Response(JSON.stringify({ ok: false, error: 'expected multipart form' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const file = inForm.get('photo');
      if (!file || typeof file === 'string') {
        return new Response(JSON.stringify({ ok: false, error: 'missing photo file' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const caption = (inForm.get('caption') || '').toString().trim();
      if (caption.length > 1024) {
        return new Response(JSON.stringify({ ok: false, error: `caption too long: ${caption.length}/1024` }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const target = (inForm.get('target') || '').toString();
      const targetChat = target === 'internal' ? TG_INTERNAL_CHAT_ID : TG_CHAT_ID;
      if (!targetChat) {
        return new Response(JSON.stringify({ ok: false, error: 'target chat not configured' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const wantBrain = target === 'internal'
        ? (inForm.get('prefixBrain') || '').toString() === '1'
        : (inForm.get('prefixBrain') || '').toString() !== '0';
      try {
        if (wantBrain) {
          await tg('sendMessage', { chat_id: targetChat, text: '🧠', disable_notification: true });
        }
        const tgForm = new FormData();
        tgForm.append('chat_id', targetChat);
        tgForm.append('photo', file, 'report.png');
        if (caption) {
          tgForm.append('caption', caption);
          tgForm.append('parse_mode', 'HTML');
        }
        const r = await fetch(`https://api.telegram.org/bot${TG_BOT_TOKEN}/sendPhoto`, {
          method: 'POST', body: tgForm,
        });
        const j = await r.json();
        if (!j.ok) {
          console.error('[BROADCASTPHOTO] telegram rejected:', JSON.stringify(j));
          return new Response(JSON.stringify({ ok: false, error: j.description || 'send failed' }), {
            status: 502, headers: { 'content-type': 'application/json' },
          });
        }
        return new Response(JSON.stringify({ ok: true, message_id: j.result?.message_id || null }), {
          headers: { 'content-type': 'application/json' },
        });
      } catch (err) {
        console.error('[BROADCASTPHOTO ERROR]', err.message || err);
        return new Response(JSON.stringify({ ok: false, error: 'send failed' }), {
          status: 500, headers: { 'content-type': 'application/json' },
        });
      }
    }

    // === /rpclogs — authenticated eth_getLogs proxy over the keyed endpoints ===
    // POST JSON `{ address, topics, fromBlock, toBlock }` with header
    // `X-Broadcast-Secret`. The free BSC endpoints cap getLogs at ~50 blocks and the
    // Binance dataseeds refuse ranges outright, so historical scans are impossible
    // from a laptop — the keyed NodeReal URLs only exist as Cloudflare secrets.
    // This forwards a single getLogs call and nothing else: the caller does the
    // paging, so no Worker request ever runs long. Read-only by construction —
    // the method is hardcoded, only the range and filter come from the body.
    if (url.pathname === '/rpclogs' && request.method === 'POST') {
      const got = request.headers.get('x-broadcast-secret') || '';
      if (!env.BROADCAST_SECRET || got !== env.BROADCAST_SECRET) {
        return new Response(JSON.stringify({ ok: false, error: 'unauthorized' }), {
          status: 401, headers: { 'content-type': 'application/json' },
        });
      }
      let body = {};
      try { body = await request.json(); } catch (e) {
        return new Response(JSON.stringify({ ok: false, error: 'invalid json' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const filter = {
        address: body.address,
        topics: Array.isArray(body.topics) ? body.topics : [],
        fromBlock: body.fromBlock,
        toBlock: body.toBlock,
      };
      if (!filter.address || !filter.fromBlock || !filter.toBlock) {
        return new Response(JSON.stringify({ ok: false, error: 'need address, fromBlock, toBlock' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const endpoints = [...keyedEndpoints(env), ...LOGS_RPC_ENDPOINTS];
      let lastErr = 'no endpoint answered';
      for (const rpc of endpoints) {
        try {
          const r = await fetch(rpc, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'User-Agent': LOGS_UA },
            body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getLogs', params: [filter] }),
          });
          const j = await r.json();
          if (Array.isArray(j.result)) {
            return new Response(JSON.stringify({ ok: true, logs: j.result }), {
              headers: { 'content-type': 'application/json' },
            });
          }
          lastErr = j.error?.message || 'no result';
        } catch (e) {
          lastErr = e.message || String(e);
        }
      }
      return new Response(JSON.stringify({ ok: false, error: lastErr }), {
        status: 502, headers: { 'content-type': 'application/json' },
      });
    }

    // === /whale-summary — public read-only whale-flow aggregates ===
    // Consumed by the dashboard worker's bobai_smart_money MCP tool. Exposes
    // only aggregates + top movers from the same KV event log that powers
    // /whales24h — no admin data, no secrets. Events are on-chain-derived
    // (BOBAI Transfer logs, scanned every minute by the cron).
    // the Brain Pop champion post as it would go out (nothing is sent): /pop-champion?d=YYYY-MM-DD
    if (url.pathname === '/pop-champion' && request.method === 'GET') {
      const d = url.searchParams.get('d') || '';
      if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) return new Response('d=YYYY-MM-DD', { status: 400 });
      const chainTx = await popChainTx(d), champ = await popChampionRun(d);
      let text = await popChampionText(d);
      if (text && chainTx) text = text.replace('\n\n▶️ Play today:', `\n⛓ On BNB Chain: https://bscscan.com/tx/${chainTx}\n\n▶️ Play today:`); /* the line the night post carries (10.11.) */
      /* the post as it would go out (7.11.): the champion's card as the photo, the text as its caption with the challenge line */
      return new Response(JSON.stringify({ day: d, text: text === undefined ? 'board did not answer' : text, photo: champ ? 'https://brainonbnb.com/og/pop/' + champ + '.png?d=' + d : null, caption: champ && text ? text.replace('▶️ Play today: https://brainonbnb.com/m/pop?from=tg', '⚔️ Beat the champion: https://brainonbnb.com/m/pop/' + champ + '?from=tg') : null }), { headers: { 'content-type': 'application/json' } });
    }
    if (url.pathname === '/whale-summary' && request.method === 'GET') {
      try {
        const [events, trackedW, contracts] = await Promise.all([loadWhaleEvents(env), loadTrackedWallets(env), loadTrackedContracts(env)]);
        const tracked = [...trackedW, ...contracts];
        // Holdings snapshot: self-heals if today's cron snapshot is missing
        // (first request of the day takes it — date-guarded, so at most once).
        let snaps = [];
        try { snaps = await takeWhaleSnapshotIfDue(env, tracked); }
        catch (e) { console.error('[WHALE-SNAP LAZY ERROR]', e.message || e); snaps = await loadWhaleSnapshots(env); }
        const round2 = (x) => Math.round(x * 100) / 100;
        const win = (hours) => {
          const r = recentEvents(events, hours);
          let usdIn = 0, usdOut = 0, buys = 0, sells = 0, burns = 0, transfers = 0;
          for (const e of r) {
            const u = e.usdValue || 0;
            if (e.kind === 'BUY') { buys++; usdIn += u; }
            else if (e.kind === 'TRANSFER_IN') { transfers++; usdIn += u; }
            else if (e.kind === 'SELL') { sells++; usdOut += u; }
            else if (e.kind === 'BURN') { burns++; usdOut += u; }
            else if (e.kind === 'TRANSFER_OUT') { transfers++; usdOut += u; }
          }
          return { events: r.length, buys, sells, burns, transfers, usd_in: round2(usdIn), usd_out: round2(usdOut), net_usd: round2(usdIn - usdOut) };
        };
        const moverWallet = (e) => (e.kind === 'SELL' || e.kind === 'BURN' || e.kind === 'TRANSFER_OUT') ? e.from : e.to;
        const movers = recentEvents(events, 24)
          .filter(e => !e.quiet && !isQuietMove(e.kind, e.usdValue || 0) && ['BUY', 'SELL', 'BURN', 'TRANSFER_OUT', 'TRANSFER_IN', 'INTERNAL_T'].includes(e.kind))
          .slice()
          .sort((a, b) => (b.usdValue || 0) - (a.usdValue || 0))
          .slice(0, 3)
          .map(e => ({
            kind: e.kind,
            bobai: e.amount || 0,
            usd: round2(e.usdValue || 0),
            wallet: moverWallet(e),
            tx: e.txHash ? 'https://bscscan.com/tx/' + e.txHash : null,
            time_utc: e.ts ? new Date(e.ts).toISOString() : null,
          }));
        const last = events[events.length - 1];
        return new Response(JSON.stringify({
          as_of: new Date().toISOString(),
          tracked_wallets: trackedW.length,
          tracked_contracts: contracts.length,
          tracking_threshold: '5,000,000 BOBAI (0.5% of supply) — holders enter the watchlist automatically when they cross it; 10,000,000 (1%) is the whale line',
          holdings: snapshotHoldings(snaps, tracked),
          last_24h: win(24),
          last_7d: win(168),
          top_movers_24h: movers,
          last_event: last ? { kind: last.kind, usd: round2(last.usdValue || 0), time_utc: last.ts ? new Date(last.ts).toISOString() : null } : null,
        }, null, 2), {
          headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*', 'cache-control': 'public, max-age=60' },
        });
      } catch (e) {
        console.error('[WHALE-SUMMARY ERROR]', e.message || e);
        return new Response(JSON.stringify({ error: 'whale summary unavailable' }), {
          status: 502, headers: { 'content-type': 'application/json', 'access-control-allow-origin': '*' },
        });
      }
    }

    // === /sendsticker — authenticated one-off sticker upload (preview tool) ===
    // POST multipart/form-data with header `X-Broadcast-Secret: `
    // and fields: `chat_id` (string) + `sticker` (the .webm file). The worker forwards
    // it to Telegram sendSticker so the BOT_TOKEN never leaves Cloudflare. Used by
    // tg-send-sticker.js to preview animated stickers without exposing the token.
    if (url.pathname === '/sendsticker' && request.method === 'POST') {
      const got = request.headers.get('x-broadcast-secret') || '';
      if (!env.BROADCAST_SECRET || got !== env.BROADCAST_SECRET) {
        return new Response(JSON.stringify({ ok: false, error: 'unauthorized' }), {
          status: 401, headers: { 'content-type': 'application/json' },
        });
      }
      let inForm;
      try { inForm = await request.formData(); } catch (e) {
        return new Response(JSON.stringify({ ok: false, error: 'expected multipart form' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const chatId = (inForm.get('chat_id') || '').toString().trim();
      const file = inForm.get('sticker');
      if (!chatId || !file || typeof file === 'string') {
        return new Response(JSON.stringify({ ok: false, error: 'missing chat_id or sticker file' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      try {
        const tgForm = new FormData();
        tgForm.append('chat_id', chatId);
        tgForm.append('sticker', file, 'sticker.webm');
        const r = await fetch(`https://api.telegram.org/bot${TG_BOT_TOKEN}/sendSticker`, {
          method: 'POST', body: tgForm,
        });
        const j = await r.json();
        return new Response(JSON.stringify(j), {
          status: j.ok ? 200 : 502, headers: { 'content-type': 'application/json' },
        });
      } catch (err) {
        console.error('[SENDSTICKER ERROR]', err.message || err);
        return new Response(JSON.stringify({ ok: false, error: 'send failed' }), {
          status: 500, headers: { 'content-type': 'application/json' },
        });
      }
    }

    // === /deletemessage — authenticated message delete (cleanup for previews) ===
    // POST JSON `{ chat_id, message_id }` with header `X-Broadcast-Secret`.
    // Forwards to Telegram deleteMessage. Used to remove preview stickers on request.
    if (url.pathname === '/deletemessage' && request.method === 'POST') {
      const got = request.headers.get('x-broadcast-secret') || '';
      if (!env.BROADCAST_SECRET || got !== env.BROADCAST_SECRET) {
        return new Response(JSON.stringify({ ok: false, error: 'unauthorized' }), {
          status: 401, headers: { 'content-type': 'application/json' },
        });
      }
      let body = {};
      try { body = await request.json(); } catch (e) {
        return new Response(JSON.stringify({ ok: false, error: 'invalid json' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const chatId = (body.chat_id || '').toString().trim();
      const messageId = body.message_id;
      if (!chatId || !messageId) {
        return new Response(JSON.stringify({ ok: false, error: 'missing chat_id or message_id' }), {
          status: 400, headers: { 'content-type': 'application/json' },
        });
      }
      const j = await tg('deleteMessage', { chat_id: chatId, message_id: messageId });
      return new Response(JSON.stringify(j), {
        status: j.ok ? 200 : 502, headers: { 'content-type': 'application/json' },
      });
    }

    // === /stickerset/* — authenticated sticker set creation endpoints ===
    // POST with header `X-Broadcast-Secret`. Used by tg-create-stickerset.js to
    // build an installable Telegram sticker pack from local .webm files without
    // leaking the BOT_TOKEN. Endpoints:
    //   GET  /stickerset/getbot         → { ok, username }
    //   POST /stickerset/upload         → uploadStickerFile (multipart: user_id, sticker)
    //   POST /stickerset/create  (JSON) → createNewStickerSet
    //   POST /stickerset/add     (JSON) → addStickerToSet
    if (url.pathname.startsWith('/stickerset/')) {
      const got = request.headers.get('x-broadcast-secret') || '';
      if (!env.BROADCAST_SECRET || got !== env.BROADCAST_SECRET) {
        return new Response(JSON.stringify({ ok: false, error: 'unauthorized' }), {
          status: 401, headers: { 'content-type': 'application/json' },
        });
      }
      const jres = (j) => new Response(JSON.stringify(j), {
        status: j.ok ? 200 : 502, headers: { 'content-type': 'application/json' },
      });

      if (url.pathname === '/stickerset/title' && request.method === 'POST') {
        let body = {};
        try { body = await request.json(); } catch (e) {
          return new Response(JSON.stringify({ ok: false, error: 'invalid json' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        if (!body.name || !body.title) {
          return new Response(JSON.stringify({ ok: false, error: 'missing name/title' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        return jres(await tg('setStickerSetTitle', { name: body.name, title: body.title }));
      }

      if (url.pathname === '/stickerset/replace' && request.method === 'POST') {
        let body = {};
        try { body = await request.json(); } catch (e) {
          return new Response(JSON.stringify({ ok: false, error: 'invalid json' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        const { user_id, name, old_sticker, file_id, emoji } = body;
        if (!user_id || !name || !old_sticker || !file_id || !emoji) {
          return new Response(JSON.stringify({ ok: false, error: 'missing user_id/name/old_sticker/file_id/emoji' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        return jres(await tg('replaceStickerInSet', {
          user_id, name, old_sticker,
          sticker: { sticker: file_id, format: 'video', emoji_list: [emoji] },
        }));
      }

      if (url.pathname === '/stickerset/delete' && request.method === 'POST') {
        let body = {};
        try { body = await request.json(); } catch (e) {
          return new Response(JSON.stringify({ ok: false, error: 'invalid json' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        if (!body.name) {
          return new Response(JSON.stringify({ ok: false, error: 'missing name' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        return jres(await tg('deleteStickerSet', { name: body.name }));
      }

      if (url.pathname === '/stickerset/getbot') {
        const me = await tg('getMe', {});
        return new Response(JSON.stringify({
          ok: !!me.ok, username: me.result?.username || null,
        }), { status: me.ok ? 200 : 502, headers: { 'content-type': 'application/json' } });
      }

      if (url.pathname === '/stickerset/upload' && request.method === 'POST') {
        let inForm;
        try { inForm = await request.formData(); } catch (e) {
          return new Response(JSON.stringify({ ok: false, error: 'expected multipart form' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        const userId = (inForm.get('user_id') || '').toString().trim();
        const file = inForm.get('sticker');
        if (!userId || !file || typeof file === 'string') {
          return new Response(JSON.stringify({ ok: false, error: 'missing user_id or sticker file' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        const tgForm = new FormData();
        tgForm.append('user_id', userId);
        tgForm.append('sticker', file, 'sticker.webm');
        tgForm.append('sticker_format', 'video');
        const r = await fetch(`https://api.telegram.org/bot${TG_BOT_TOKEN}/uploadStickerFile`, {
          method: 'POST', body: tgForm,
        });
        return jres(await r.json());
      }

      if (url.pathname === '/stickerset/create' && request.method === 'POST') {
        let body = {};
        try { body = await request.json(); } catch (e) {
          return new Response(JSON.stringify({ ok: false, error: 'invalid json' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        const { user_id, name, title, file_id, emoji } = body;
        if (!user_id || !name || !title || !file_id || !emoji) {
          return new Response(JSON.stringify({ ok: false, error: 'missing user_id/name/title/file_id/emoji' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        return jres(await tg('createNewStickerSet', {
          user_id, name, title,
          stickers: [{ sticker: file_id, format: 'video', emoji_list: [emoji] }],
        }));
      }

      if (url.pathname === '/stickerset/get' && request.method === 'GET') {
        const name = url.searchParams.get('name');
        if (!name) {
          return new Response(JSON.stringify({ ok: false, error: 'missing name' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        return jres(await tg('getStickerSet', { name }));
      }

      if (url.pathname === '/stickerset/add' && request.method === 'POST') {
        let body = {};
        try { body = await request.json(); } catch (e) {
          return new Response(JSON.stringify({ ok: false, error: 'invalid json' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        const { user_id, name, file_id, emoji } = body;
        if (!user_id || !name || !file_id || !emoji) {
          return new Response(JSON.stringify({ ok: false, error: 'missing user_id/name/file_id/emoji' }), {
            status: 400, headers: { 'content-type': 'application/json' },
          });
        }
        return jres(await tg('addStickerToSet', {
          user_id, name,
          sticker: { sticker: file_id, format: 'video', emoji_list: [emoji] },
        }));
      }

      return new Response(JSON.stringify({ ok: false, error: 'unknown stickerset endpoint' }), {
        status: 404, headers: { 'content-type': 'application/json' },
      });
    }

    // === /media/* — retrieve reference media the owner sent the bot in private chat ===
    // The webhook stores the last owner-sent file (animation/video/document/photo/sticker)
    // as KV `incoming_media`. Endpoints (header `X-Broadcast-Secret`):
    //   GET /media/last     → { ok, type, file_id, name, ts }
    //   GET /media/download → raw file bytes (proxied via getFile, token stays on CF)
    if (url.pathname.startsWith('/media/')) {
      const got = request.headers.get('x-broadcast-secret') || '';
      if (!env.BROADCAST_SECRET || got !== env.BROADCAST_SECRET) {
        return new Response(JSON.stringify({ ok: false, error: 'unauthorized' }), {
          status: 401, headers: { 'content-type': 'application/json' },
        });
      }
      const raw = await env.KV.get('incoming_media');
      if (!raw) {
        return new Response(JSON.stringify({ ok: false, error: 'no media received yet' }), {
          status: 404, headers: { 'content-type': 'application/json' },
        });
      }
      const meta = JSON.parse(raw);

      if (url.pathname === '/media/last') {
        return new Response(JSON.stringify({ ok: true, ...meta }), {
          headers: { 'content-type': 'application/json' },
        });
      }

      if (url.pathname === '/media/download') {
        const gf = await tg('getFile', { file_id: meta.file_id });
        if (!gf.ok) {
          return new Response(JSON.stringify({ ok: false, error: 'getFile failed', detail: gf }), {
            status: 502, headers: { 'content-type': 'application/json' },
          });
        }
        const fr = await fetch(`https://api.telegram.org/file/bot${TG_BOT_TOKEN}/${gf.result.file_path}`);
        if (!fr.ok) {
          return new Response(JSON.stringify({ ok: false, error: `file fetch ${fr.status}` }), {
            status: 502, headers: { 'content-type': 'application/json' },
          });
        }
        return new Response(fr.body, {
          headers: {
            'content-type': 'application/octet-stream',
            'x-media-name': encodeURIComponent(meta.name || 'ref.bin'),
            'x-media-type': meta.type || 'document',
          },
        });
      }

      return new Response(JSON.stringify({ ok: false, error: 'unknown media endpoint' }), {
        status: 404, headers: { 'content-type': 'application/json' },
      });
    }

    // === Telegram webhook (default POST route — unchanged behaviour) ===
    if (request.method === 'POST') {
      // Once the secret is registered with Telegram, every genuine update
      // carries it. Before that (first deploy, secret not yet attached) the
      // check must stay open, or the bot would go silent between the two.
      if (env.TG_WEBHOOK_SECRET) {
        const armed = await env.KV.get('webhook_secret_version');
        const got = request.headers.get('x-telegram-bot-api-secret-token') || '';
        if (armed && got !== env.TG_WEBHOOK_SECRET) {
          console.error('[WEBHOOK] rejected update without valid secret');
          return new Response('unauthorized', { status: 401 });
        }
      }
      try {
        const update = await request.json();

        if (update.message?.new_chat_members) {
          await handleNewMember(update.message, env);
        }

        // Capture reference media sent by the owner in private chat → KV incoming_media
        // (picked up locally via GET /media/download; used as style refs for stickers/GIFs)
        const OWNER_USER_ID = '7334850816';
        const pm = update.message;
        if (pm && pm.chat?.type === 'private' && String(pm.from?.id) === OWNER_USER_ID) {
          const media =
            pm.animation ? { type: 'animation', file_id: pm.animation.file_id, name: pm.animation.file_name || 'ref.mp4' } :
            pm.video     ? { type: 'video',     file_id: pm.video.file_id,     name: pm.video.file_name || 'ref.mp4' } :
            pm.document  ? { type: 'document',  file_id: pm.document.file_id,  name: pm.document.file_name || 'ref.bin' } :
            pm.sticker   ? { type: 'sticker',   file_id: pm.sticker.file_id,   name: 'ref.webm' } :
            pm.photo     ? { type: 'photo',     file_id: pm.photo[pm.photo.length - 1].file_id, name: 'ref.jpg' } : null;
          if (media) {
            await env.KV.put('incoming_media', JSON.stringify({ ...media, ts: Date.now() }));
            await tg('sendMessage', {
              chat_id: pm.chat.id,
              text: `✅ Reference saved (${media.type}) — ready for pickup.`,
            });
          }
        }

        if (update.message?.text) {
          await handleCommand(update.message, env);
        }

        if (update.callback_query) {
          await handleCallback(update.callback_query, env);
        }
      } catch (err) {
        console.error('[WEBHOOK ERROR]', err.message || err);
      }
    }

    return new Response('OK');
  },

  // Cron handler (every 1 min)
  async scheduled(event, env) {
    TG_BOT_TOKEN = env.BOT_TOKEN;
    TG_INTERNAL_CHAT_ID = env.TG_INTERNAL_CHAT_ID || '';
    WHALE_ENV = env;

    // === HEARTBEAT ===
    // This bot was in no health check at all: it posts buys and burns into the
    // channel, and a stopped cron looks exactly like a quiet market. Every
    // other bot proves liveness through logs.brainonbnb.com/health; this one
    // had nothing to prove it with, so it writes its own timestamp and serves
    // it on GET /health below.
    //
    // Every tenth minute, not every minute. The cron runs 1,440 times a day and
    // a KV write per tick would spend the daily write budget on a heartbeat
    // nobody reads that often — 144 is plenty to tell a running worker from a
    // stopped one, and the freshness check downstream allows for it.
    //
    // Gated on the tick's nominal minute, not the clock. On 2026-09-11 the
    // 11:00 tick wrote its heartbeat at 11:00:49 — dispatched late by most of
    // a minute — and the 11:10 tick, a little later still, read minute 11
    // from the clock and wrote nothing; health called the cron dead at 16
    // minutes. The tick knows when it was meant to run.
    const nominal = new Date(event && event.scheduledTime ? event.scheduledTime : Date.now());
    if (nominal.getUTCMinutes() % 10 === 0) {
      try { await env.KV.put('last_cron', new Date().toISOString()); }
      catch (e) { console.error('[HEARTBEAT ERROR]', e.message || e); }
      // The bot's own 24-hour ledger, one bucket per tenth minute. Its
      // failure is logged, never fatal: the alerts below do not depend on it.
      try { await recordSwapBucket(env); }
      catch (e) { console.error('[LEDGER ERROR]', e.message || e); }
      // A NEW AGENT ON BRAIN PLAZA, ANNOUNCED ONCE (operator, 2026-10-12: the listing includes an announcement)
      try { await announceListings(env); }
      catch (e) { console.error('[LISTING ANNOUNCE ERROR]', e.message || e); }
      // BRAIN POP: yesterday's champion, once, in the first hour of the UTC day (00:00-00:50 ticks; KV flag)
      if (nominal.getUTCHours() === 0) { try { await postPopChampion(env, nominal); } catch (e) { console.error('[POP CHAMPION ERROR]', e.message || e); } }
    }

    // === ENSURE BOT COMMANDS REGISTERED (idempotent, KV-flagged) ===
    await ensureCommandsRegistered(env);
    try { await ensureWebhookSecret(env); }
    catch (e) { console.error('[WEBHOOK SECRET ERROR]', e.message || e); }

    // === LP AGENT — one sentence a day ===
    // The daily tick (worker-lp, 04:23 UTC) writes one record; the agent
    // worker serves it at /lp/agent and the series at /lp/series. A few
    // minutes past each tenth minute in the hour after the run, once: the
    // series' own sentence. The per-action alert that used to sit here was
    // asked away on 2026-09-07; its call outlived its function until
    // 2026-09-08 and threw on every tick (caught, logged, harmless, wrong).
    // Gated on the tick's nominal time, not the clock: a tick that starts
    // late, or reaches this line after the awaits above, reads minute 16 from
    // the clock and 15 from the schedule. Every tick in the window says so.
    //
    // Declared out here, not inside the block: the whale gates below read it
    // too. From 2026-09-12 to 09-17 it lived in the block, the gates threw
    // "tick is not defined" into their own catch every minute, and no recap
    // and no 06:00 snapshot went out for six days.
    const tick = nominal;
    {
      // 05:00 UTC since 2026-09-09 — the operator's hour for the public LP
      // card (the whale recap goes at 06:00). The window runs to 07:55: a
      // series point that lands after 05:55 (a late 04:23 run, the agent
      // worker briefly down) used to cost the whole day; the date flag
      // inside keeps it to one card.
      if (tick.getUTCMinutes() % 10 === 5 && tick.getUTCHours() >= 5 && tick.getUTCHours() < 8) {
        console.log('[LP REPORT] tick ' + tick.toISOString());
        try { await postLpDailyReport(env); }
        catch (e) { console.error('[LP REPORT ERROR]', e.message || e); }
      }
    }

    // === DAILY MARKET CARD (16:00 UTC = 18:00 CEST, public, 2026-10-09) ===
    // Away from the morning posts (DeFi card 05:00, whale recap 06:00 internal, health 09:10). Asked at minute 7 of
    // each tenth minute until 18:57, so a refused send or a deploy mid-hour still posts that afternoon; the date flag
    // (`market_card_date`, written only once Telegram took it) keeps it to one.
    if (tick.getUTCMinutes() % 10 === 7 && tick.getUTCHours() >= 16 && tick.getUTCHours() < 19) {
      try { await postDailyMarketCard(env, tick.getTime()); }
      catch (e) { console.error('[MARKET CARD ERROR]', e.message || e); }
    }

    // === DAILY WHALE RECAP (06:00 UTC = 08:00 CEST, idempotent via KV flag) ===
    // The window runs to 08:59, like the LP card's: a recap that cannot go out
    // at 06:00 (Telegram down, a deploy mid-hour) still goes out that morning,
    // and the date flag keeps it to one.
    if (TG_INTERNAL_CHAT_ID) {
      try {
        if (tick.getUTCHours() >= 6 && tick.getUTCHours() < 9) {
          const today = tick.toISOString().slice(0, 10);
          const last  = await env.KV.get('last_daily_summary');
          if (last !== today) {
            const sent = await postDailyWhaleRecap(env);
            if (sent) await env.KV.put('last_daily_summary', today);
          }
        }
      } catch (e) {
        console.error('[WHALE DAILY GATE ERROR]', e.message || e);
      }

      // Daily holdings snapshot — own date-guard inside takeWhaleSnapshotIfDue,
      // independent of recap success. /whale-summary self-heals if this misses.
      try {
        if (tick.getUTCHours() >= 6 && tick.getUTCHours() < 9) {
          await takeWhaleSnapshotIfDue(env, [...await loadTrackedWallets(env), ...await loadTrackedContracts(env)]);
        }
      } catch (e) {
        console.error('[WHALE-SNAP GATE ERROR]', e.message || e);
      }
    }

    // === WHALE WATCHER (internal-only alerts + auto-detect new whales) ===
    // Per-TX coalescing: aggregator swaps (1inch / OKX DEX / 0x) emit several
    // Transfer events in a single tx (LP → Router → Router → final EOA). We
    // group by tx, compute net flow per address, and emit ONE alert per moving
    // wallet against its LOGICAL counterparty (LP, DEAD, or another EOA) —
    // router hops are filtered via eth_getCode and never appear in the chat.
    if (TG_INTERNAL_CHAT_ID) {
      try {
        const tracked = await loadTrackedWallets(env);
        const trackedSet = new Set(tracked);
        // Contracts that hold like a whale: watched like a wallet, kept on their own list.
        const contractSet = new Set(await loadTrackedContracts(env));
        let contractsChanged = false;
        const watched = (a) => trackedSet.has(a) || contractSet.has(a);
        const postedWhaleRaw = await env.KV.get('posted_whale_txs');
        const postedWhaleSet = new Set(postedWhaleRaw ? JSON.parse(postedWhaleRaw) : []);
        const prevWhaleSize = postedWhaleSet.size;

        const edges = await loadWalletEdges(env);
        let edgesChanged = false;

        const whaleEvents = await loadWhaleEvents(env);
        const prevEventCount = whaleEvents.length;

        let clusterLabels = labelClusters(computeClusters([...trackedSet, ...contractSet], edges));

        const latestHex = await rpcCall('eth_blockNumber', []);
        if (latestHex) {
          const latest = parseInt(latestHex, 16);
          const fromBlock = '0x' + Math.max(0, latest - SCAN_BLOCKS).toString(16);
          const logs = await getAllRecentTransfers(fromBlock, env);

          // Group transfers by tx, preserve chronological order across txs.
          const txOrder = [];
          const byTx = new Map();
          const sortedLogs = logs.slice().sort((a, b) => {
            const blkA = parseInt(a.blockNumber, 16);
            const blkB = parseInt(b.blockNumber, 16);
            if (blkA !== blkB) return blkA - blkB;
            return parseInt(a.logIndex, 16) - parseInt(b.logIndex, 16);
          });
          for (const log of sortedLogs) {
            const txHash = log.transactionHash;
            if (!byTx.has(txHash)) { byTx.set(txHash, []); txOrder.push(txHash); }
            byTx.get(txHash).push(log);
          }

          // Migrate the prior per-log dedup format ("txHash:logIndex") so we
          // don't re-fire alerts for txs already processed by the old code.
          const postedTxPrefixSet = new Set();
          for (const k of postedWhaleSet) {
            const colon = k.indexOf(':');
            postedTxPrefixSet.add(colon === -1 ? k : k.slice(0, colon));
          }

          let bobaiPriceUsd = null;
          let whaleSnaps = null;
          let alerts = 0;
          const MAX_WHALE_ALERTS = 10;
          let setChanged = false;

          // Per-cron caches — eth_getCode and balanceOf are pure for the run.
          const contractCache = new Map();
          const balanceCache = new Map();
          const poolCache = new Map();
          // Every watched holder's balance, read once per run and only when an alert needs a rank.
          let rankMap = null;
          const rankBals = async () => {
            if (rankMap) return rankMap;
            const all = [...trackedSet, ...contractSet];
            rankMap = new Map();
            for (let i = 0; i < all.length; i += 8) {
              const chunk = all.slice(i, i + 8);
              const bals = await Promise.all(chunk.map((a) => getBalCached(a)));
              chunk.forEach((a, j) => { if (bals[j] != null) rankMap.set(a, Number(bals[j] / 10n ** 18n)); });
            }
            return rankMap;
          };
          const isContractCached = async (addr) => {
            if (contractCache.has(addr)) return contractCache.get(addr);
            const r = await isContract(addr);
            contractCache.set(addr, r);
            return r;
          };
          // A failed read is unknown, never 0 (2026-10-07): getBobaiBalance answers 0n when the node fails, and an alert
          // then said "the whole bag, wallet now empty", a wrong rank, or "100% of the pool's BOBAI" for a buy.
          const getBalCached = async (addr) => {
            if (balanceCache.has(addr)) return balanceCache.get(addr);
            try {
              const b = await getBobaiBalanceStrict(addr);
              balanceCache.set(addr, b);
              return b;
            } catch { return null; }
          };
          const isSpecial = (a) => WHALE_NEVER_TRACK.has(a.toLowerCase());

          const pair = BOBAI_PAIR.toLowerCase();
          const dead = DEAD.toLowerCase();

          for (const txHash of txOrder) {
            if (postedTxPrefixSet.has(txHash)) continue;
            if (alerts >= MAX_WHALE_ALERTS) break;

            const txLogs = byTx.get(txHash);

            // Compute net flow per address within this tx.
            const netFlow = new Map();
            let pairOut = 0n, pairIn = 0n, deadIn = 0n;
            for (const log of txLogs) {
              const from = topicToAddr(log.topics[1]);
              const to   = topicToAddr(log.topics[2]);
              const amtWei = BigInt(log.data || '0x0');
              if (!(amtWei > 0n)) continue;
              netFlow.set(from, (netFlow.get(from) || 0n) - amtWei);
              netFlow.set(to,   (netFlow.get(to)   || 0n) + amtWei);
              if (from === pair) pairOut += amtWei;
              if (to   === pair) pairIn  += amtWei;
              if (to   === dead) deadIn  += amtWei;
            }

            // Movers = addresses with non-zero net flow, excluding hard-skip
            // set (LP, DEAD, BOBAI contract, bots). Sort by |net| desc so the
            // biggest mover is alerted first when MAX is hit.
            const movers = [...netFlow.entries()]
              .filter(([addr, n]) => n !== 0n && !isSpecial(addr))
              .sort((a, b) => {
                const aa = a[1] < 0n ? -a[1] : a[1];
                const bb = b[1] < 0n ? -b[1] : b[1];
                return bb > aa ? 1 : bb < aa ? -1 : 0;
              });

            // Guard against double-emitting an INTERNAL_T (once per side).
            const alertedThisTx = new Set();
            let retryTx = false;

            for (const [addr, netWei] of movers) {
              if (alerts >= MAX_WHALE_ALERTS) { retryTx = true; break; }
              if (alertedThisTx.has(addr)) continue;

              const isTracked = watched(addr);
              const isInflow  = netWei > 0n;
              const absWei = isInflow ? netWei : -netWei;
              const absAmt = Number(absWei) / 1e18;

              let kind = null;
              let counterparty = null;
              let viaContract = false;   // the other side is a contract: told, never tracked

              // Ratio gate: ≥50% of the mover's net flow must hit pair/dead for
              // the alert to classify as a real swap/burn. BOBAI's tax routes
              // 100% to the buyback bot (NEVER_TRACK) and never directly to
              // LP/DEAD, so this gate is rarely hit in practice — kept as
              // defense-in-depth against future config changes or edge txs.
              const TAX_RATIO = 2n;
              const isRealSell = pairIn  * TAX_RATIO >= absWei;
              const isRealBuy  = pairOut * TAX_RATIO >= absWei;
              const isRealBurn = deadIn  * TAX_RATIO >= absWei;

              if (isTracked && isInflow && isRealBuy) {
                kind = 'BUY'; counterparty = pair;
              } else if (isTracked && !isInflow && isRealSell) {
                kind = 'SELL'; counterparty = pair;
              } else if (isTracked && !isInflow && isRealBurn) {
                kind = 'BURN'; counterparty = dead;
              } else if (isTracked && !isInflow) {
                // Tracked outflow not into LP/DEAD — internal move or cascade.
                const inflows = movers.filter(([a, n]) => a !== addr && n > 0n);
                const trackedSink = inflows.find(([a]) => watched(a));
                if (trackedSink) {
                  kind = 'INTERNAL_T'; counterparty = trackedSink[0];
                } else {
                  // The largest person among the recipients; with none, the largest contract.
                  for (const [a] of inflows) await isContractCached(a);
                  const other = pickOtherSide(inflows, (a) => contractCache.get(a));
                  if (!other) continue; // the outflow went to the special addresses only
                  kind = 'TRANSFER_OUT'; counterparty = other.addr; viaContract = other.viaContract;
                }
              } else if (isTracked && isInflow) {
                // Tracked inflow not from LP — find the source EOA.
                const outflows = movers.filter(([a, n]) => a !== addr && n < 0n);
                const trackedSource = outflows.find(([a]) => watched(a));
                if (trackedSource) continue; // INTERNAL_T fires from the sender side
                for (const [a] of outflows) await isContractCached(a);
                const other = pickOtherSide(outflows, (a) => contractCache.get(a));
                if (!other) continue;
                kind = 'TRANSFER_IN'; counterparty = other.addr; viaContract = other.viaContract;
              } else if (!isTracked && isInflow) {
                // NEW_WHALE detection: non-tracked receiver — crossed 10M?
                // A contract that now HOLDS 10M+ is a holder too (not a pool:
                // a market is never a whale) and goes on the contract list.
                const asContract = await isContractCached(addr);
                const bal = await getBalCached(addr);
                if (bal === null || bal < WATCH_THRESHOLD_WEI) continue;
                if (asContract) { if (!poolCache.has(addr)) poolCache.set(addr, await isPool(addr)); if (poolCache.get(addr)) continue; }

                if (asContract) { contractSet.add(addr); contractsChanged = true; }
                else { trackedSet.add(addr); setChanged = true; }
                if (bobaiPriceUsd === null) bobaiPriceUsd = await fetchBobaiPriceUsd();
                const balTokens = Number(bal / 10n ** 18n);
                const usd = bobaiPriceUsd ? balTokens * bobaiPriceUsd : 0;
                console.log('[WHALE] NEW_WHALE detected', addr.slice(0, 10), formatNumber(balTokens));
                const rb = await rankBals();
                rb.set(addr, balTokens);
                const sent = await postWhaleAlert({
                  kind: 'NEW_WHALE', from: pair, to: addr,
                  amount: balTokens, usdValue: usd, txHash, moverIsContract: asContract,
                  rank: holderRank(rb, addr, balTokens),
                });
                if (sent) {
                  alerts++;
                  whaleEvents.push({ kind: 'NEW_WHALE', from: pair, to: addr, amount: balTokens, usdValue: usd, txHash, ts: Date.now(), ...(asContract ? { contract: true } : {}) });
                  alertedThisTx.add(addr);
                } else retryTx = true;
                continue;
              } else {
                continue;
              }

              if (!kind) continue;

              // Cascade-add (TRANSFER_OUT counterparty already EOA-verified).
              let labelsDirty = false;
              if (kind === 'TRANSFER_OUT' && !viaContract && !watched(counterparty)) {
                trackedSet.add(counterparty);
                setChanged = true;
                if (addEdgeInMemory(edges, addr, counterparty)) { edgesChanged = true; labelsDirty = true; }
              }
              if (kind === 'INTERNAL_T') {
                if (addEdgeInMemory(edges, addr, counterparty)) { edgesChanged = true; labelsDirty = true; }
              }
              if (labelsDirty) {
                clusterLabels = labelClusters(computeClusters([...trackedSet, ...contractSet], edges));
              }

              if (bobaiPriceUsd === null) bobaiPriceUsd = await fetchBobaiPriceUsd();
              const usdValue = bobaiPriceUsd ? absAmt * bobaiPriceUsd : 0;

              // Display orientation: sender on left, receiver on right.
              const senderAddr   = isInflow ? counterparty : addr;
              const receiverAddr = isInflow ? addr : counterparty;
              const fromBalWei = isSpecial(senderAddr)   ? null : await getBalCached(senderAddr);
              const toBalWei   = isSpecial(receiverAddr) ? null : await getBalCached(receiverAddr);
              const fromBal = fromBalWei != null ? Number(fromBalWei / 10n ** 18n) : null;
              const toBal   = toBalWei   != null ? Number(toBalWei   / 10n ** 18n) : null;
              const fromTag = clusterLabels.get(senderAddr)   || null;
              const toTag   = clusterLabels.get(receiverAddr) || null;

              // Under the quiet floor the move is logged for the recap and
              // never posted; it does not count against the alert cap.
              // A move into or out of a contract under the quiet floor is dust, not pre-funding.
              const quiet = isQuietMove(kind, usdValue) || (viaContract && usdValue > 0 && usdValue < 5);
              const told = toldAlready(whaleEvents, txHash, kind, senderAddr, receiverAddr);
              console.log('[WHALE]', told ? 'told before' : quiet ? 'quiet' : kind, senderAddr.slice(0,8), '→', receiverAddr.slice(0,8), formatNumber(absAmt), 'BOBAI');
              // Asleep before this move? The snapshots are read once per run, only when an alert goes out.
              let dormant = null, rank = null, rankBefore = null, poolShare = null, pattern = null, folded = false;
              const moverBalNow = isInflow ? toBal : fromBal;
              const moverBalBefore = moverBalNow != null ? (isInflow ? moverBalNow - absAmt : moverBalNow + absAmt) : null;
              if (!told && !quiet) {
                if (whaleSnaps === null) whaleSnaps = await loadWhaleSnapshots(env).catch(() => []);
                if (moverBalNow != null) dormant = dormantDays(whaleSnaps, addr, moverBalBefore, whaleEvents);
                // A run of the same kind: the third move tells the story, later small ones fold into it.
                if (PATTERNS[kind] && moverBalNow != null) {
                  const step = patternStep(whaleEvents, addr, kind);
                  const decision = foldMove(step.n, usdValue, moverBalBefore > 0 ? absAmt / moverBalBefore : 1);
                  if (decision === 'fold') folded = true;
                  if (decision === 'pattern') {
                    const amount = step.prior.reduce((t, e) => t + (e.amount || 0), 0) + absAmt;
                    const usd = step.prior.reduce((t, e) => t + (e.usdValue || 0), 0) + usdValue;
                    const start = isInflow ? moverBalNow - amount : moverBalNow + amount;
                    pattern = {
                      n: step.n, amount, usd,
                      bag: positionNote(kind, amount, moverBalNow) && start >= 1 ? (isInflow ? `bag +${Math.round(amount / start * 100)}% in 24h` : moverBalNow < 1 ? 'the whole bag in 24h' : `${Math.round(amount / start * 100)}% of the bag in 24h`) : null,
                      recipients: kind === 'TRANSFER_OUT' ? [...new Set([...step.prior.map((e) => e.to), receiverAddr])] : null,
                    };
                  }
                }
                if (!folded) {
                  // Place among all holders, exact from 5M up (every holder above that is watched).
                  const rb = await rankBals();
                  if (moverBalNow != null) {
                    rb.set(addr, moverBalNow);
                    if (moverBalNow >= WATCH_THRESHOLD_TOKENS) rank = holderRank(rb, addr, moverBalNow);
                    if (moverBalBefore >= WATCH_THRESHOLD_TOKENS) rankBefore = holderRank(rb, addr, moverBalBefore);
                  }
                  // A trade against the pair: its size against the pool's BOBAI before the trade.
                  if (kind === 'BUY' || kind === 'SELL') {
                    const poolWei = await getBalCached(pair);
                    if (poolWei != null) { const poolNow = Number(poolWei / 10n ** 18n); const poolBefore = kind === 'SELL' ? poolNow - absAmt : poolNow + absAmt; if (poolBefore > 0) poolShare = absAmt / poolBefore * 100; }
                  }
                }
              }
              // A buy the buy alert tells goes to the official group there, once (2026-10-15). A failed read leaves it here.
              let official = true;
              if (kind === 'BUY' && !told && !quiet && !folded) {
                try {
                  const pb = pairBuyOfReceipt(await rpcCall('eth_getTransactionReceipt', [txHash]));
                  if (pb && pb.recipients.has(addr) && buyAlertTells(pb, await getBnbUsd())) official = false;
                } catch { official = true; }
              }
              const sent = told || quiet || folded ? true : await postWhaleAlert({
                kind, from: senderAddr, to: receiverAddr,
                amount: absAmt, usdValue, txHash,
                fromTag, toTag, fromBal, toBal, priceUsd: bobaiPriceUsd, otherIsContract: viaContract, dormant,
                moverIsContract: contractSet.has(addr), rank, rankBefore, poolShare: poolShare != null ? poolShare / 100 : null, pattern,
              }, official);
              if (sent) {
                if (!quiet && !told && !folded) alerts++;
                if (!told) whaleEvents.push({ kind, from: senderAddr, to: receiverAddr, amount: absAmt, usdValue, txHash, ts: Date.now(), ...(quiet ? { quiet: true } : {}), ...(viaContract ? { contract: true } : {}), ...(folded ? { folded: true } : {}), ...(pattern ? { pattern: true } : {}) });
                alertedThisTx.add(addr);
                if (kind === 'INTERNAL_T') alertedThisTx.add(counterparty);
              } else {
                // A FAILED SEND IS TRIED AGAIN (2026-09-18): this line said so and the
                // transaction was marked done a few lines below all the same — the
                // alert was lost and missing from the recap. The transaction stays
                // open now; what it has already told is skipped on the way back.
                retryTx = true;
                console.error('[WHALE] alert NOT sent, retry next cron', txHash);
              }

              // EX_WHALE: tracked wallet crossed from ≥10M to <10M this tx.
              if (isTracked && (kind === 'SELL' || kind === 'BURN' || kind === 'TRANSFER_OUT')) {
                try {
                  const balAfter = await getBobaiBalanceStrict(addr); // fresh, post-tx; a failed read throws and is skipped, never read as 0
                  if (balAfter < WHALE_THRESHOLD_WEI && (balAfter + absWei) >= WHALE_THRESHOLD_WEI) {
                    const balTokens = Number(balAfter / 10n ** 18n);
                    console.log('[WHALE] EX_WHALE crossed', addr.slice(0, 10), formatNumber(balTokens));
                    if (alerts < MAX_WHALE_ALERTS && !toldAlready(whaleEvents, txHash, 'EX_WHALE', addr, counterparty)) {
                      const usd = bobaiPriceUsd ? balTokens * bobaiPriceUsd : 0;
                      const exSent = await postWhaleAlert({
                        kind: 'EX_WHALE', from: addr, to: counterparty,
                        amount: balTokens, usdValue: usd, txHash,
                      });
                      if (!exSent) retryTx = true;
                      if (exSent) {
                        alerts++;
                        whaleEvents.push({ kind: 'EX_WHALE', from: addr, to: counterparty, amount: balTokens, usdValue: usd, txHash, ts: Date.now() });
                      }
                    }
                  }
                } catch { /* skip */ }
              }
            }

            // Mark tx processed even if no alert was emitted (avoid re-scan) —
            // unless a send failed or the cap cut its movers short.
            if (!retryTx) postedWhaleSet.add(txHash);
          }

          if (setChanged) await saveTrackedWallets(env, [...trackedSet]);
          if (contractsChanged) await saveTrackedContracts(env, [...contractSet]);
          if (edgesChanged) await saveWalletEdges(env, edges);
          if (postedWhaleSet.size > prevWhaleSize) {
            await env.KV.put('posted_whale_txs', JSON.stringify([...postedWhaleSet].slice(-600)));
          }
          if (whaleEvents.length > prevEventCount) {
            await saveWhaleEvents(env, whaleEvents);
          }
        }
      } catch (err) {
        console.error('[WHALE WATCHER ERROR]', err.message || err);
      }
    }

    // === BUY ALERTS (on-chain Swap logs — near-instant, like burns/donations) ===
    // Two-phase pipeline for buys ≥ $100 (NFT mint threshold):
    //   1) Detect buy on chain → push into `pending_nft_buys` queue (no alert yet)
    //   2) Each cron, pull /api/nft/state and match queued buys by `buyTx` →
    //      fire alert once the mint-worker has minted the NFT. The alert then
    //      carries the real #tokenId, so /nft, dashboard and TG stay consistent.
    // Sold-out tiers and stuck mints (>5 min) get fired immediately with a
    // graceful fallback line so no alert is ever lost.
    const postedRaw = await env.KV.get('posted_txs');
    const postedSet = new Set(postedRaw ? JSON.parse(postedRaw) : []);
    const prevSize = postedSet.size;

    const pendingRaw = await env.KV.get('pending_nft_buys');
    let pending = pendingRaw ? JSON.parse(pendingRaw) : [];
    let pendingDirty = false;
    const NFT_PENDING_TIMEOUT_MS = 5 * 60 * 1000;

    // Fetch state once — used for both queue draining and sold-out checks
    const nftState = await fetchNftState();
    const dropByBuyTx = new Map(
      (nftState?.drops || []).map(d => [String(d.buyTx || '').toLowerCase(), d])
    );

    // Tier index from USD (highest matching threshold)
    const tierFromUsd = (usd) => {
      for (let i = NFT_TIERS.length - 1; i >= 0; i--) {
        if (usd >= NFT_TIERS[i][2]) return i;
      }
      return -1;
    };

    // Build the NFT line for the buy alert, given a matched drop OR a fallback
    const nftLineFromDrop = (drop) => {
      const tier = drop.tier;
      const [emoji, label] = NFT_TIERS[tier] || ['?', '?'];
      const [rEmoji, rLabel] = NFT_RARITIES[drop.rarity] || ['?', '?'];
      const minted = nftState?.minted?.[tier] ?? '?';
      const cap    = nftState?.cap?.[tier]    ?? '?';
      return `\n🎁 +1 NFT #${drop.tokenId} · ${emoji} ${label} × ${rEmoji} ${rLabel} · ${minted}/${cap}`;
    };
    const nftLineSoldOut = (tier) => {
      const [emoji, label] = NFT_TIERS[tier] || ['?', '?'];
      const cap = nftState?.cap?.[tier] ?? '?';
      return `\n🎁 ${emoji} ${label} NFTs sold out (${cap}/${cap})`;
    };
    const nftLineTimeout = () => `\n🎁 NFT mint pending — check the dashboard`;

    let burnedPctCached = null;
    const burnedPct = async () => {
      if (burnedPctCached === null) burnedPctCached = (await getBurnStats()).percent;
      return burnedPctCached;
    };

    let alertsThisRun = 0;
    const MAX_ALERTS_PER_RUN = 5;

    // The buy alert's context line (2026-10-09): the alert record and the ledger are read once, and only in a tick
    // that alerts; the buyer's holding is read per alert (strict: a failed read leaves that part out). The record is
    // written once at the end of the tick, and only if an alert went out.
    let alertedRec, ledgerCache;
    const alertedNow = [];
    const loadAlerted = async () => { if (alertedRec === undefined) alertedRec = await env.KV.get(ALERTED_BUYS_KEY, 'json').catch(() => null); return alertedRec; };
    const buyCtx = async (trade) => {
      try {
        await loadAlerted();
        if (ledgerCache === undefined) ledgerCache = await readSwapLedger(env);
        let hold = null;
        try { hold = Number(await getBobaiBalanceStrict(trade.buyer)) / 1e18; } catch { hold = null; }
        return buyContextLine({ usd: trade.usdValue, buyer: trade.buyer, tx: trade.txHash, alerted: (alertedRec || alertedNow.length) ? addAlertedBuys(alertedRec, alertedNow) : null,
          ledger: ledgerCache, holdTokens: hold, price: trade.bobaiAmount > 0 ? trade.usdValue / trade.bobaiAmount : 0 }) + await trackedCtx(trade);
      } catch (e) { console.error('[BUY CTX]', e.message || e); return ''; }
    };
    // A buyer the whale watcher tracks (2026-10-15): the watcher's text of this buy stays internal, so the alert says
    // it here. The buyer named, else whoever got BOBAI out of the pair in this transaction. The watch lists and the
    // places are read once per tick, only when a tracked wallet bought.
    let watchSets, placeBals;
    const trackedCtx = async (trade) => {
      try {
        if (watchSets === undefined) {
          const [w, c] = await Promise.all([loadTrackedWallets(env), loadTrackedContracts(env)]);
          watchSets = { w: new Set(w), c: new Set(c) };
        }
        const isWatched = (a) => watchSets.w.has(a) || watchSets.c.has(a);
        const buyer = String(trade.buyer || '').toLowerCase();
        let addr = isWatched(buyer) ? buyer : null;
        if (!addr) {
          const pb = pairBuyOfReceipt(await rpcCall('eth_getTransactionReceipt', [trade.txHash]));
          addr = pb ? [...pb.recipients].find(isWatched) || null : null;
        }
        if (!addr) return '';
        let bal = null, rank = null;
        try { bal = Number(await getBobaiBalanceStrict(addr)) / 1e18; } catch { bal = null; }
        if (bal >= WATCH_THRESHOLD_TOKENS) {
          if (!placeBals) {
            placeBals = new Map();
            const all = [...watchSets.w, ...watchSets.c];
            for (let i = 0; i < all.length; i += 8) {
              const chunk = all.slice(i, i + 8);
              const bals = await Promise.all(chunk.map((a) => getBobaiBalanceStrict(a).catch(() => null)));
              chunk.forEach((a, j) => { if (bals[j] != null) placeBals.set(a, Number(bals[j] / 10n ** 18n)); });
            }
          }
          placeBals.set(addr, bal);
          rank = holderRank(placeBals, addr, bal);
        }
        let cluster;
        if (!(bal >= WATCH_THRESHOLD_TOKENS) && !watchSets.c.has(addr)) {
          try { cluster = labelClusters(computeClusters([...watchSets.w, ...watchSets.c], await loadWalletEdges(env))).get(addr) || ''; }
          catch { cluster = undefined; }
        }
        return trackedBuyLine({ addr, buyer: trade.buyer, bal, rank, contract: watchSets.c.has(addr), cluster });
      } catch (e) { console.error('[BUY TRACKED]', e.message || e); return ''; }
    };
    const noteAlerted = (trade) => alertedNow.push({ tx: trade.txHash, buyer: String(trade.buyer).toLowerCase(), usd: Math.round(trade.usdValue * 100) / 100, ts: Date.now() });

    // --- Phase 1: drain pending queue ----------------------------------------
    const nowMs = Date.now();
    const stillPending = [];
    for (const p of pending) {
      if (alertsThisRun >= MAX_ALERTS_PER_RUN) { stillPending.push(p); continue; }
      const drop = dropByBuyTx.get(String(p.txHash || '').toLowerCase());
      if (drop) {
        if (!(await claimAlert(env, 'buy', p.txHash))) continue;   // another tick sent it: off the queue
        const t = alertTrade(p, drop);
        const sent = await postBuyAlert(t, await burnedPct(), nftLineFromDrop(drop), TG_CHAT_ID, false, await buyCtx(t));
        if (sent) { alertsThisRun++; noteAlerted(t); console.log('[BUY] minted-alert', p.txHash, '→ #' + drop.tokenId); }
        else { await releaseAlert(env, 'buy', p.txHash); stillPending.push(p); console.error('[BUY] minted-alert send failed, will retry', p.txHash); }
        continue;
      }
      if (nowMs - p.queuedAt > NFT_PENDING_TIMEOUT_MS) {
        if (!(await claimAlert(env, 'buy', p.txHash))) continue;
        const sent = await postBuyAlert(p, await burnedPct(), nftLineTimeout(), TG_CHAT_ID, false, await buyCtx(p));
        if (sent) { alertsThisRun++; noteAlerted(p); console.log('[BUY] timeout-alert', p.txHash); }
        else { await releaseAlert(env, 'buy', p.txHash); stillPending.push(p); console.error('[BUY] timeout-alert send failed, will retry', p.txHash); }
        continue;
      }
      stillPending.push(p);
    }
    if (stillPending.length !== pending.length) pendingDirty = true;
    pending = stillPending;

    // --- Phase 2: scan new swap logs -----------------------------------------
    try {
      const latestHex = await rpcCall('eth_blockNumber', []);
      if (latestHex) {
        const latest = parseInt(latestHex, 16);
        // SCAN_BLOCKS ≈ 12 min (BSC ~0.45 s/block) — covers the 1-min cron
        // through ten missed ticks; dedup via posted_txs prevents repeats.
        const fromBlock = '0x' + Math.max(0, latest - SCAN_BLOCKS).toString(16);
        const logs = await getSwapLogs(fromBlock, env);

        if (Array.isArray(logs) && logs.length) {
          let bnbUsd = null;               // lazy-load once

          // Logs are returned oldest-first → chat order stays chronological.
          // One entry per transaction: a buy split into several swaps is one
          // buy of their sum (foldBuysByTx). BUY = WBNB in AND BOBAI out.
          for (const log of foldBuysByTx(logs)) {
            const txHash = log.transactionHash;
            if (postedSet.has(txHash)) continue;
            const { amount1In, amount0Out } = log;

            const bnbAmount   = Number(amount1In)  / 1e18;
            const bobaiAmount = Number(amount0Out) / 1e18;

            if (bnbUsd === null) bnbUsd = await getBnbUsd();
            const usdValue = bnbUsd ? bnbAmount * bnbUsd : 0;
            if (usdValue < 100) continue;  // below threshold — don't even dedup-store

            // Real buyer = tx sender (the `to` topic is often the router contract).
            const tx = await rpcCall('eth_getTransactionByHash', [txHash]);
            // NEVER THE DEAD ADDRESS AS BUYER (2026-10-09): a failed read named 0x…dEaD and skipped the own-wallet
            // check. Left unposted, the next run meets it again.
            if (!tx?.from) continue;
            const buyer = tx.from.toLowerCase();
            if (buyer && IGNORED_WALLETS.has(buyer)) { postedSet.add(txHash); continue; }

            // THE CAP DEFERS, IT DOES NOT DROP (2026-09-18): a buy met with the cap
            // reached was marked posted and never told. It is left open now — the
            // next run's scan (twelve minutes of reach) meets it again. A buy that
            // waits for its NFT sends nothing in this phase and is queued as ever.

            const tradeBase = {
              bnbAmount,
              bobaiAmount,
              usdValue,
              buyer: tx.from,
              txHash,
            };

            const tierIdx = tierFromUsd(usdValue);
            const tierMinted = nftState?.minted?.[tierIdx];
            const tierCap    = nftState?.cap?.[tierIdx];
            const soldOut    = tierIdx >= 0 && Number.isFinite(tierMinted) && Number.isFinite(tierCap) && tierMinted >= tierCap;

            console.log('[BUY] on-chain buy', txHash, '$' + usdValue.toFixed(2), 'tier=' + tierIdx, soldOut ? 'SOLD-OUT' : 'queue');

            if (soldOut && alertsThisRun >= MAX_ALERTS_PER_RUN) {
              console.log('[BUY] alert cap reached, sold-out alert left for the next cron', txHash);
            } else if (soldOut) {
              // No mint will happen — fire immediately with sold-out line
              if (!(await claimAlert(env, 'buy', txHash))) { postedSet.add(txHash); continue; }
              const sent = await postBuyAlert(tradeBase, await burnedPct(), nftLineSoldOut(tierIdx), TG_CHAT_ID, false, await buyCtx(tradeBase));
              if (sent) { postedSet.add(txHash); alertsThisRun++; noteAlerted(tradeBase); }
              else { await releaseAlert(env, 'buy', txHash); console.error('[BUY] sold-out alert NOT sent, will retry next cron', txHash); }
            } else {
              // Queue for matching with mint-worker drop — alert fires once #tokenId known
              postedSet.add(txHash);   // dedup so the next cron's log scan skips this tx
              pending.push({ ...tradeBase, queuedAt: Date.now() });
              pendingDirty = true;
            }
          }
        }
      }
    } catch (err) {
      console.error('[BUY BOT ERROR]', err.message || err);
    }

    // Persist queue (keep small) and seen-set
    if (pendingDirty) {
      await env.KV.put('pending_nft_buys', JSON.stringify(pending.slice(-50)));
    }
    if (postedSet.size > prevSize) {
      const postedArr = [...postedSet].slice(-100);
      await env.KV.put('posted_txs', JSON.stringify(postedArr));
    }
    if (alertedNow.length) {
      try { await env.KV.put(ALERTED_BUYS_KEY, JSON.stringify(addAlertedBuys(await loadAlerted(), alertedNow))); }
      catch (e) { console.error('[ALERTED BUYS]', e.message || e); }
    }

    // === BURN ALERTS ===
    // Check if burned amount increased since last check (1 KV read + RPC calls)
    try {
      const [currentBurned, totalSupply, lastBurnedRaw, tokenPrice] = await Promise.all([
        getBurnedTokens(),
        getTotalSupply(),
        env.KV.get('last_burned'),
        fetchBobaiPriceUsd(),
      ]);

      const lastBurned = lastBurnedRaw ? parseFloat(lastBurnedRaw) : 0;

      // Only alert if burn increased by at least 1000 BOBAI (avoid spam from rounding)
      if (currentBurned > lastBurned + 1000) {
        // one alert per burn total (2026-10-23): two overlapping ticks read the same old last_burned
        const burnKey = String(Math.floor(currentBurned));
        const mine = await claimAlert(env, 'burn', burnKey);
        const sent = mine ? await postBurnAlert(currentBurned, lastBurned, totalSupply, tokenPrice) : true;
        if (mine && !sent) await releaseAlert(env, 'burn', burnKey);
        // A BURN THAT CANNOT BE TOLD IS WRITTEN DOWN ONCE (2026-10-09): `burn_stuck_since` is set the first tick an
        // owed alert does not go out (no price, Telegram refused) and removed once one does — a write only on a
        // failure and on the recovery. /health serves it; the health check is red when it is over an hour old.
        const stuckSince = await env.KV.get('burn_stuck_since');
        if (sent) {
          await env.KV.put('last_burned', currentBurned.toString());
          if (stuckSince) await env.KV.delete('burn_stuck_since');
        } else if (!stuckSince) await env.KV.put('burn_stuck_since', new Date().toISOString());
      }
    } catch (err) {
      console.error('[BURN BOT ERROR]', err.message || err);
    }

    // Donation alerts retired 2026-08-29: the WC26 prize pool closed with the
    // tournament (payout 2026-07-20), so no new donations can arrive. The
    // /worldcup command still serves the frozen final numbers on demand.

    // === CAPTCHA CLEANUP (every tick) ===
    // KV reads only (the index, then one key per open captcha). Every other
    // minute left a joiner who was promised 60 seconds muted for up to three.
    await cleanupExpiredCaptchas(env);
  },
};

==============================================================================
=== FILE: worker-tg-bot/wrangler.toml
==============================================================================

name = "bobai-tg-bot"
main = "index.js"
compatibility_date = "2024-01-01"

[triggers]
crons = ["* * * * *"]

[[kv_namespaces]]
binding = "KV"
id = ""

# One alert per buy (2026-10-23): AlertGate claims each tx once, worldwide (index.js claimAlert)
[[durable_objects.bindings]]
name = "GATE"
class_name = "AlertGate"

[[migrations]]
tag = "v1"
new_sqlite_classes = ["AlertGate"]