#!/usr/bin/env python3 """Stack POL indexer (2026-11-09). Runs on core every 5 minutes (/etc/cron.d/stackpol-indexer), read-only on every source: - each game's payout file on its Docker volume (rows with status 'paid': pol, tx, wallet, username, paidAt) - InstantAdPay's and LinkSpin's chain index (TierPaid events: the referral payments the contracts send in the purchase tx; MemberActivated maps a member id to its wallet) - usernames for wallets: IAP accounts + positions (MySQL, via the IAP container) and LinkSpin's accounts.json - opt-in: /root/stackpol-indexer/optin.txt (one username per line) plus IAP's stack-optin.json when present - Viral Banner Blitz (2026-11-15): VBBShop Paid (role 0, sponsor) and Claimed logs read from Polygon with eth_getLogs, plus the weekly prize transfers listed in VBB's prizes.json, each checked on chain (sent by the prize wallet, to that winner, succeeded). The scan position and the checked prize transfers are cached in /root/stackpol-indexer/vbb-chain.json (the only file it writes). It builds one snapshot (network totals, per-program totals, last 7 days, latest 300 payouts, a stack per opted-in member) and POSTs it to https://stackpol.com/api/ingest with the key in /root/.stackpol-ingest-key. Nothing is written anywhere else. The ledger shows each payout's username (Marty 2026-11-09); only opted-in members get a public stack page. Usage: indexer.py [--dry] (print a summary, no POST)""" import json import re, os, subprocess, sys, time, urllib.request, glob VOL = '/var/lib/docker/volumes' GAMES = { # key: (volume dir glob, file) 'ph': ('ovmrb8rj1lngf3in4w1ou1pd-polhunter-data', 'payouts.json'), 'dr': ('l11nhvnej9kwsjrjyvs7z3f0-drip-runner-data', 'payouts.json'), 'gk': ('toguzi1lnewgghxhdn4ot3w0-*gem-kingdom-data', 'polpayouts.json'), 'sw': ('u9d4b3e4o5ylrpccl1q613uv-spellwheel-data', 'polpayouts.json'), 'ch': ('z11vzqktt76jedghxsplii0w-clutterhunt-data', 'polpayouts.json'), 'pb': ('cwoa0935eyq2h1sofafzmacw-polybreak-data', 'polpayouts.json'), 'ra': ('ugmtf5of3fgzsa3lg981xg4g-*road-agent-data', 'polpayouts.json'), 'pm': ('0xdfl7ulqjvg65a4azhxjoca-*polminer-data', 'polpayouts.json'), 'pw': ('kq67q1d59m31uqfx1txyr18q-polywarriors-data', 'polpayouts.json'), 'td': ('eo4tqkuwcvny0oqo2dfck9fe-turkeydrop-data', 'polpayouts.json'), } EC_PAYOUTS = 'http://10.100.0.2:18950/payouts' PD_VOL = 'w94d6qjry9wjp0pwqzxheora-passivedrip-engine-data' CHAINS = {'iap': 'h8jd2hmt9y3c1gco9ed5nmva-instantadpay-data', 'ls': 'c10c6soppcsowxsgbrufqb01-*linkspin-prod-data'} # Downline Banners (2026-11-13): its chain index (a file on purpose, a rebuildable cache); member payouts = Paid events with role 0 # (sponsor) or 1 (line level) to anyone but the contract and the two company wallets DLB_VOL = 'gwjsodgtgtc2drdja1ndm0q7*bannerline-data' DLB_HOUSE = {'0x6c77fc0664f58cf17e81966160fc80005a110f9b', '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2'} # Viral Banner Blitz (2026-11-15): VBBShop on Polygon, read-only. Member payouts = Paid role 0 (the 30% sponsor share pushed in the # purchase tx) + Claimed (a sponsor share whose push failed, pulled later) + the weekly prize transfers from the prize wallet. The # prize-wallet (role 1) and company (role 2) shares, and anything to the contract / prize / company / keeper wallets, are not member payouts. VBB_SHOP = '0x36f6ccc8752dce1c84e06b65f07df30e8a4707d7' VBB_START = 97271183 # deploy block (the app's SHOP_START_BLOCK) VBB_PRIZE = '0x167315726fe50cff97b8f4c91c8c606489397907' VBB_HOUSE = {VBB_SHOP, VBB_PRIZE, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x839d97dea43321fcd6dcea1406da4cab6ef29af2'} # + company (Tangem), keeper VBB_RPC = os.environ.get('VBB_RPC', 'https://polygon-bor-rpc.publicnode.com') VBB_TOPICS = {'0x5cd81500d7f34f31cd8d8bd61c8cc1dd873c5ea0a46cd1c00ce014f1781f91d5': 'Paid', # Paid(uint256,address,uint256,uint8) '0xf7a40077ff7a04c7e61f6f26fb13774259ddf1b6bce9ecf26a8276cdd3992683': 'Claimed'} # Claimed(address,address,uint256) VBB_CONFIRM = 30 # blocks behind head VBB_SPAN = 1000 # blocks per eth_getLogs (public RPC limit) VBB_MAX_SPANS = 400 # per run; a long gap catches up over a few runs # The sites keep their data documents in MySQL since 2026-11-13 (docstore.js, table docs). doc() reads one through the app's own # DOCSTORE_URL, inside the database container; falls back to the volume file for an app still on files. APPS = {'iap': 'h8jd2hmt9y3c1gco9ed5nmva', 'ls': 'c10c6soppcsowxsgbrufqb01', 'vbb': 'y8ywvn6hwl3x1hvs4y7eljbp'} IAP_UUID = 'h8jd2hmt9y3c1gco9ed5nmva' HERE = '/root/stackpol-indexer' URL = 'https://stackpol.com/api/ingest' DAY = 86400000 def voldir(pattern): m = sorted(glob.glob(os.path.join(VOL, pattern, '_data'))) return m[0] if m else None def load(path, default): try: with open(path, encoding='utf-8') as f: return json.load(f) except Exception: return default def ms(v): try: v = float(v) except Exception: return 0 return int(v if v > 1e12 else v * 1000) def container(uuid): """the running app container: '-...' (plain apps) or '--...' (compose apps like VBB)""" c = subprocess.run(['docker', 'ps', '--format', '{{.Names}}'], capture_output=True, text=True).stdout.split() return next((x for x in c if x.startswith(uuid) or ('-' + uuid + '-') in x or x.endswith('-' + uuid)), None) def doc(app, name, default): cont = container(APPS[app]) url = subprocess.run(['docker', 'exec', cont, 'printenv', 'DOCSTORE_URL'], capture_output=True, text=True).stdout.strip() if cont else '' if not url: if app not in CHAINS: return default d = voldir(CHAINS[app]) return load(os.path.join(d, name), default) if d else default m = re.match(r'mysql://([^:]+):([^@]+)@([^:/]+)(?::\d+)?/([A-Za-z0-9_]+)', url) if not m: return default user, pw, host, db = m.groups() r = subprocess.run(['docker', 'exec', '-i', '-e', 'MYSQL_PWD=' + pw, host, 'mysql', '--default-character-set=utf8mb4', '-u' + user, db, '-N', '-B', '--raw', '-e', "SELECT body FROM docs WHERE name='%s'" % name.replace("'", "")], capture_output=True, timeout=60, stdin=subprocess.DEVNULL) try: out = r.stdout.decode('utf-8') return json.loads(out) if out.strip() else default except Exception: return default def rpc(method, params): rq = urllib.request.Request(VBB_RPC, data=json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}).encode(), headers={'Content-Type': 'application/json', 'User-Agent': 'stackpol-indexer'}) j = json.load(urllib.request.urlopen(rq, timeout=20)) if j.get('error'): raise RuntimeError(method + ': ' + str(j['error'].get('message') if isinstance(j['error'], dict) else j['error'])) return j.get('result') def vbb_rows(dry=False): """Viral Banner Blitz member payouts, read-only on chain. Returns (rows, note). --dry does not save the cache.""" cpath = os.path.join(HERE, 'vbb-chain.json') cache = load(cpath, {}) or {} last = int(cache.get('lastBlock') or VBB_START - 1) logs = cache.get('logs') or [] # every Paid/Claimed log seen (all roles), so the counting rule can change without a rescan prizes = cache.get('prizes') or {} # tx -> {to, wei, ts, ok} bts = {} def btime(n): if n not in bts: b = rpc('eth_getBlockByNumber', [hex(n), False]) bts[n] = int(b['timestamp'], 16) if b and b.get('timestamp') else 0 return bts[n] note = '' try: head = int(rpc('eth_blockNumber', []), 16) - VBB_CONFIRM seen = {(x['tx'], x['li']) for x in logs} spans = 0 while last < head and spans < VBB_MAX_SPANS: frm, to = last + 1, min(head, last + VBB_SPAN) for l in rpc('eth_getLogs', [{'address': VBB_SHOP, 'topics': [list(VBB_TOPICS)], 'fromBlock': hex(frm), 'toBlock': hex(to)}]) or []: if l.get('removed') or str(l.get('address', '')).lower() != VBB_SHOP: continue kind, t, data = VBB_TOPICS.get(l['topics'][0]), l['topics'], l.get('data') or '0x' key = (l['transactionHash'].lower(), int(l['logIndex'], 16)) if not kind or key in seen: continue n = int(l['blockNumber'], 16) if kind == 'Paid': x = {'ev': 'Paid', 'to': '0x' + t[2][-40:].lower(), 'wei': str(int(data[2:66], 16)), 'role': int(data[66:130], 16)} else: x = {'ev': 'Claimed', 'who': '0x' + t[1][-40:].lower(), 'to': '0x' + t[2][-40:].lower(), 'wei': str(int(data[2:66], 16))} x.update({'tx': key[0], 'li': key[1], 'block': n, 'ts': btime(n)}) logs.append(x) seen.add(key) last = to spans += 1 if last < head: note = 'catching up, %d blocks to go' % (head - last) except Exception as e: note = 'chain read failed (kept the cached logs): %s' % e # weekly prizes: the transfers VBB's prize payer recorded as confirmed, each checked once on chain try: pz = doc('vbb', 'prizes.json', {}) or {} for wk in (pz.get('weeks') or {}).values(): for t in wk.get('transfers') or []: tx = str(t.get('tx') or '').lower() if not tx or tx in prizes or t.get('status') != 'confirmed': continue tr, rc = rpc('eth_getTransactionByHash', [tx]), rpc('eth_getTransactionReceipt', [tx]) if not tr or not rc: continue ok = rc.get('status') == '0x1' and str(tr.get('from', '')).lower() == VBB_PRIZE and str(tr.get('to', '')).lower() == str(t.get('address', '')).lower() prizes[tx] = {'to': str(tr.get('to', '')).lower(), 'wei': str(int(tr.get('value') or '0x0', 16)), 'ts': btime(int(rc['blockNumber'], 16)), 'ok': ok} except Exception as e: note = (note + '; ' if note else '') + 'prizes unavailable: %s' % e if not dry: tmp = cpath + '.tmp' with open(tmp, 'w', encoding='utf-8', newline='\n') as f: json.dump({'lastBlock': last, 'logs': logs, 'prizes': prizes, 'at': int(time.time())}, f) os.replace(tmp, cpath) rows = [] for x in logs: member = (x['ev'] == 'Paid' and x.get('role') == 0) or (x['ev'] == 'Claimed' and x.get('who') not in VBB_HOUSE) if member and x['to'] not in VBB_HOUSE and int(x['wei']) > 0: rows.append({'k': 'vbb', 'pol': int(x['wei']) / 1e18, 'tx': x['tx'], 'ts': ms(x['ts']), 'w': x['to'], 'gu': ''}) for tx, x in prizes.items(): if x.get('ok') and x['to'] not in VBB_HOUSE and int(x['wei']) > 0: rows.append({'k': 'vbb', 'pol': int(x['wei']) / 1e18, 'tx': tx, 'ts': ms(x['ts']), 'w': x['to'], 'gu': ''}) allwei = sum(int(x['wei']) for x in logs if x['ev'] == 'Paid') return rows, 'vbb: scanned to block %d, %d contract logs (%.4f POL in all Paid events), %d prize transfers checked, %d member payouts %.4f POL%s' % ( last, len(logs), allwei / 1e18, len(prizes), len(rows), sum(r['pol'] for r in rows), ('; ' + note) if note else '') def iap_wallet_users(): """{address_lower: username} from IAP accounts + positions, via the IAP container (its DATABASE_URL never leaves it).""" c = subprocess.run(['docker', 'ps', '--format', '{{.Names}}'], capture_output=True, text=True).stdout.split() name = next((x for x in c if x.startswith(IAP_UUID)), None) if not name: return {} js = ("const m=require('mysql2/promise');(async()=>{const c=await m.createConnection(process.env.DATABASE_URL);" "const [a]=await c.query(\"SELECT LOWER(address) a, username u FROM accounts WHERE address IS NOT NULL AND address<>'' AND username IS NOT NULL AND username<>''\");" "const [p]=await c.query(\"SELECT LOWER(p.address) a, x.username u FROM positions p JOIN accounts x ON x.email=p.email WHERE p.address IS NOT NULL AND x.username IS NOT NULL\");" "const o={};for(const r of a.concat(p))if(r.a&&r.u&&!o[r.a])o[r.a]=String(r.u).toLowerCase();console.log(JSON.stringify(o));await c.end()})().catch(e=>{console.log('{}')})") r = subprocess.run(['docker', 'exec', '-i', '-w', '/app', name, 'node', '-e', js], capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL) # never read the caller's stdin try: return json.loads(r.stdout.strip().splitlines()[-1]) except Exception: return {} def main(): dry = '--dry' in sys.argv rows = [] for k, (pat, fn) in GAMES.items(): d = voldir(pat) data = load(os.path.join(d, fn), []) if d else [] if isinstance(data, dict): data = list(data.values()) for x in data: if x.get('status') != 'paid' or not x.get('tx'): continue try: pol = float(x.get('pol') or 0) except Exception: continue if pol <= 0: continue rows.append({'k': k, 'pol': pol, 'tx': x['tx'], 'ts': ms(x.get('paidAt') or x.get('ts') or x.get('at')), 'w': str(x.get('wallet') or '').lower(), 'gu': str(x.get('username') or '').lower()}) # PassiveDrip (Marty 2026-11-10): the payout engine's ledger on core; only live passivedrip.com rows that were paid on chain # (staging test payouts and dry runs stay out). Rows carry the receiving wallet in 'to'; the PassiveDrip username is not an # IAP username, so attribution goes by wallet only. d = voldir(PD_VOL) for x in ((load(os.path.join(d, 'ledger.json'), {}) if d else {}).get('entries') or {}).values(): if x.get('site') != 'passivedrip.com' or x.get('status') != 'paid' or not x.get('tx'): continue try: pol = float(x.get('pol') or 0) except Exception: continue if pol > 0: rows.append({'k': 'pd', 'pol': pol, 'tx': x['tx'], 'ts': ms(x.get('paidAt') or x.get('at')), 'w': str(x.get('to') or '').lower(), 'gu': ''}) # Earners Corner welcome rewards (Marty 2026-11-10): the forum's reward service on core2 lists every reward paid on chain, over # WireGuard, keyed with the Stack POL ingest key. Attribution by wallet like the games. try: rq = urllib.request.Request(EC_PAYOUTS, headers={'x-key': open('/root/.stackpol-ingest-key').read().strip()}) for x in json.load(urllib.request.urlopen(rq, timeout=15)): if x.get('tx') and float(x.get('pol') or 0) > 0: rows.append({'k': 'ec', 'pol': float(x['pol']), 'tx': x['tx'], 'ts': ms(x.get('at')), 'w': str(x.get('wallet') or '').lower(), 'gu': ''}) except Exception as e: print('earners corner payouts unavailable:', e) for k, pat in CHAINS.items(): d = voldir(pat) ci = load(os.path.join(d, 'chain-index.json'), {}) if d else {} ev = ci.get('events', []) acct = {e['id']: str(e.get('account', '')).lower() for e in ev if e.get('type') == 'MemberActivated'} for e in ev: if e.get('type') != 'TierPaid': continue pol = int(e['amountWei']) / 1e18 if pol <= 0: continue rows.append({'k': k, 'pol': pol, 'tx': e['tx'], 'ts': ms(e.get('ts')), 'w': acct.get(e.get('recipientId'), ''), 'gu': ''}) d = voldir(DLB_VOL) for e in (load(os.path.join(d, 'chain-index.json'), {}) if d else {}).get('events', []) or []: if e.get('type') != 'Paid' or e.get('role') not in (0, 1) or str(e.get('to', '')).lower() in DLB_HOUSE: continue try: pol = int(e.get('amount') or 0) / 1e18 except Exception: continue if pol > 0: rows.append({'k': 'dlb', 'pol': pol, 'tx': e['tx'], 'ts': ms(e.get('ts') or 0), 'w': str(e.get('to') or '').lower(), 'gu': ''}) vr, vnote = vbb_rows(dry) rows += vr print(vnote) # wallet -> username wu = iap_wallet_users() lsd = voldir(CHAINS['ls']) ls_accounts = doc('ls', 'accounts.json', {}) for a in (ls_accounts.get('byEmail', {}) or {}).values(): addr, un = str(a.get('address') or '').lower(), str(a.get('username') or '').lower() if addr and un and addr not in wu: wu[addr] = un for r in rows: r['u'] = wu.get(r['w']) or r['gu'] or '' # opt-in opt = set() for line in open(os.path.join(HERE, 'optin.txt'), encoding='utf-8').read().split() if os.path.exists(os.path.join(HERE, 'optin.txt')) else []: opt.add(line.strip().lower().lstrip('@')) iapd = voldir(CHAINS['iap']) so = doc('iap', 'stack-optin.json', {}) # on by default (Marty 2026-11-09): every member who has been paid gets a page; an explicit switch-off in IAP hides it opt |= {r['u'] for r in rows if r['u']} for un, on in (so.get('users', {}) if isinstance(so, dict) else {}).items(): (opt.add if on else opt.discard)(str(un).lower()) # aggregate now = int(time.time() * 1000) progs, wallets = {}, set() for r in rows: p = progs.setdefault(r['k'], {'pol': 0.0, 'payments': 0, 'w': set(), 'first': 0, 'last': 0}) p['pol'] += r['pol']; p['payments'] += 1; p['w'].add(r['w']) p['first'] = min(p['first'] or r['ts'], r['ts']); p['last'] = max(p['last'], r['ts']) wallets.add(r['w']) programs = {k: {'pol': round(v['pol'], 4), 'payments': v['payments'], 'wallets': len(v['w'] - {''}), 'first': v['first'], 'last': v['last']} for k, v in progs.items()} l7 = [r for r in rows if r['ts'] >= now - 7 * DAY] rows.sort(key=lambda r: r['ts'], reverse=True) recent = [{'k': r['k'], 'pol': round(r['pol'], 4), 'tx': r['tx'], 'ts': r['ts'], 'u': r['u'] or None, 'pub': r['u'] in opt} for r in rows[:300]] # Marty 11-09: the ledger always shows the username; pub = has a public page prog_recent = {} # each program's own latest 20 (a quiet program still has rows on its page) for r in rows: lst = prog_recent.setdefault(r['k'], []) if len(lst) < 20: lst.append({'k': r['k'], 'pol': round(r['pol'], 4), 'tx': r['tx'], 'ts': r['ts'], 'u': r['u'] or None, 'pub': r['u'] in opt}) stacks = {} for un in sorted(opt): mine = [r for r in rows if r['u'] == un] if not mine: continue by = {} for r in mine: b = by.setdefault(r['k'], {'pol': 0.0, 'payments': 0}); b['pol'] += r['pol']; b['payments'] += 1 stacks[un] = {'total': round(sum(r['pol'] for r in mine), 4), 'payments': len(mine), 'since': min(r['ts'] for r in mine), 'byProg': {k: {'pol': round(v['pol'], 4), 'payments': v['payments']} for k, v in by.items()}, 'recent': [{'k': r['k'], 'pol': round(r['pol'], 4), 'tx': r['tx'], 'ts': r['ts']} for r in mine[:25]]} # Stack POL Pro (2026-11-09): a paid one-time unlock in IAP. Pro pages (and blog/program pages opened from one) show the member's own # LinkSpin Banner Spins and spin links in place of the network zones. Matched by username (one identity across IAP and LinkSpin). pro = {str(k).lower() for k, v in ((so.get('pro') or {}) if isinstance(so, dict) else {}).items() if v} if pro: em = {} for e, a in (ls_accounts.get('byEmail', {}) or {}).items(): un = str(a.get('username') or '').lower() if un in pro: em[str(e).lower()] = un bs = doc('ls', 'bannerspin.json', {}).get('spins', []) or [] rt = doc('ls', 'rotator.json', {}).get('rotations', []) or [] for un in pro: if un not in stacks: continue mine = [e for e, u in em.items() if u == un] spins = [{'code': x['code'], 'size': x.get('size', ''), 'name': str(x.get('name') or '')[:60]} for x in bs if str(x.get('owner', '')).lower() in mine and not x.get('paused') and any(b.get('active', True) for b in x.get('banners') or [])] links = [{'code': x['code'], 'name': str(x.get('name') or '')[:60]} for x in rt if str(x.get('owner', '')).lower() in mine and not x.get('paused') and any(d.get('active', True) for d in x.get('destinations') or [])] stacks[un]['pro'] = {'spins': spins[:40], 'links': links[:20]} snap = {'v': 1, 'at': now, 'network': {'pol': round(sum(r['pol'] for r in rows), 4), 'payments': len(rows), 'wallets': len(wallets - {''})}, 'last7': {'pol': round(sum(r['pol'] for r in l7), 4), 'payments': len(l7)}, 'programs': programs, 'recent': recent, 'progRecent': prog_recent, 'stacks': stacks} print('network %.2f POL, %d payments, %d wallets | last7 %.2f | stacks %s' % (snap['network']['pol'], snap['network']['payments'], snap['network']['wallets'], snap['last7']['pol'], ','.join(stacks) or '-')) for k, v in sorted(programs.items(), key=lambda x: -x[1]['pol']): print(' %-4s %10.2f POL %6d payments %5d wallets' % (k, v['pol'], v['payments'], v['wallets'])) if dry: return key = open('/root/.stackpol-ingest-key').read().strip() req = urllib.request.Request(URL, data=json.dumps(snap).encode(), headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + key, 'User-Agent': 'stackpol-indexer'}) print('push', urllib.request.urlopen(req, timeout=30).read().decode()[:120]) if __name__ == '__main__': main()