Files
stackpol/tools/indexer.py
T
martbost ffa0d74c70 My Stack POL: network sign-in through the hub + signed-in member area at /my (Marty approved 2026-11-19)
- networksso.js (shared file, same copy as IAP/LinkSpin/YPB): hub-only sign-in (HUB_SSO=on), silent check on /my, sign-out
- my.js: signed session cookie (keyed off HUB_SECRET), sign-outs in the my-signouts.json MySQL document; /my shows the page
  link + on/off, Pro, join links per program, share kit, own payout rows with Polygonscan links and totals from the ledger
- iapswitch.js: the page switch stays in IAP's stack-optin.json; Stack POL calls IAP POST /api/partner/stackpol/switch
  (signed, STACKPOL_SWITCH_KEY; spec in the file). Until IAP has it, /my links to IAP Promo tools
- tools/indexer.py: snapshot gains `my` (every paid member's rows, wallets, page flag, IAP switches, Pro list); public data unchanged
- header Sign in / My Stack POL entry; robots keeps /my and /sso/ out
- qa/my.test.mjs: 66 checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 06:57:11 -06:00

488 lines
31 KiB
Python

#!/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.
- ViralAdBlitz (2026-11-15): VABShop Paid (level 1-5 shares) and Claimed logs read from Polygon the same way, cached in
/root/stackpol-indexer/vab-chain.json (ViralAdSource 2026-11-17: + resharer cut and pot rewards, vas-chain.json; YourProgramBuilder ypb-chain.json). These caches are the only files 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)
# ViralAdBlitz (2026-11-15): VABShop on Polygon, read-only. Member payouts = Paid with level 1-5 (the 10% level shares pushed in the
# Boost tx) + Claimed (a share whose push failed, pulled later). Level 0 is the company share; anything to the contract, the company
# (Tangem) or the keeper is not a member payout.
VAB_SHOP = '0xb58447b0ce9a38ad0e7d41a074febee696452905'
VAB_START = 97324419 # deploy block (the app's SHOP_START_BLOCK)
VAB_HOUSE = {VAB_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0xf0b9deee7d9768b1d89d30f30e095def2a9cf1db'} # + company (Tangem), keeper
VAB_TOPICS = {'0x2932f3f87f2814df80b5152511ba1fed7a451f5fb3703cd5dd406de6e684dfcc': 'Paid', # Paid(uint256,address,uint256,uint8,uint8)
'0xf7a40077ff7a04c7e61f6f26fb13774259ddf1b6bce9ecf26a8276cdd3992683': 'Claimed'} # Claimed(address,address,uint256)
# 5xYourTeam (2026-11-15): DraftPosition on Polygon, read-only; same Paid/Claimed events as VABShop. Member payouts = Paid level 1-5
# (sponsor 25% + levels 2-5 5%) + Claimed by a member. Level 0 = company, level 6 = the Best Coach prize pot wallet: not counted.
FX_SHOP = '0x83bb982d8b485de1a24e7d313765dda48d5abc74'
FX_START = 97363529 # deploy block (the app's SHOP_START_BLOCK)
DH_SHOP = '0xed07ad7150ecba62689cf2480729753f2fa44e90' # DownlineHydra HydraPro (2026-11-15): same Paid/Claimed events as VABShop
DH_START = 97364036 # deploy block (the app's SHOP_START_BLOCK)
DH_HOUSE = {DH_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0xf2f54cf271e8942ecb02176f408cc08a2a1d5bca'} # + company (Tangem), keeper
FX_HOUSE = {FX_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x818daeedefbb33a1988b8b4ac76a8c1dd6e82c60', '0x196cfceb0229ee4b2f20a3350a5ec32b93b72ba8'} # + company, keeper, prize pot
# ViralAdSource (2026-11-17): VASShop on Polygon, read-only; same Paid/Claimed events as VABShop plus the reward pot. Member payouts =
# Paid kind 1-5 (10% level shares) and kind 6 (the 20% resharer cut), RewardPaid (a new-member reward from the pot, unless its push
# failed in that tx: then the later Claimed counts it), and Claimed by a member. Kind 0 = company; contract, company, keeper and relay excluded.
# YourProgramBuilder (2026-11-17): YPBShop on Polygon, read-only; same Paid/Claimed events as VABShop. Member payouts = Paid kind 1-5
# (sponsor 20% + four levels 5%) + Claimed by a member (a failed push is owed and counted when claimed). Kind 0 = company; contract, company, keeper excluded.
YPB_SHOP = '0x44a02c5ece4e6eb0edc406a8020f289956803e2a'
YPB_START = 97486277 # deploy block (the app's SHOP_START_BLOCK)
YPB_HOUSE = {YPB_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x5453a3973ed54cd2687c1675b73f1be5dacf26c4'} # + company (Tangem), keeper
VAS_SHOP = '0x7efe7b6ac1e666555f70d005e2cf1637804c4f24'
VAS_START = 97473297 # deploy block (the app's SHOP_START_BLOCK)
VAS_HOUSE = {VAS_SHOP, '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0xc76ca7dd499338299c2b4bde2dc5c61bf2a97aae', '0x2fe1afedc6ba13fea4e820e7f4c67e6ea40dd9d6'} # + company (Tangem), keeper, relay
VAS_TOPICS = {'0xd1c8a663b78b68951e43495fb4824e0454105c7043f5fa8d570d140b5a73d48e': 'RewardPaid', # RewardPaid(uint256,address,uint256,uint256,uint256)
'0x8518389ba90468cb21477807ccd9bf28d0f41f2b3affa2f77a779786efa2cc04': 'PaymentFailed'} # PaymentFailed(uint256,address,uint256,uint8,uint8)
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: '<uuid>-...' (plain apps) or '<service>-<uuid>-...' (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 vab_rows(dry=False, k='vab', shop=VAB_SHOP, start=VAB_START, house=VAB_HOUSE, cachefile='vab-chain.json', maxlevel=5, extra=None):
"""ViralAdBlitz (and, same events, 5xYourTeam, DownlineHydra, ViralAdSource) member payouts, read-only on chain (same scan as VBB,
no prize wallet). maxlevel = highest Paid level/kind counted (ViralAdSource 6 = resharer); extra = more topics (ViralAdSource
RewardPaid + PaymentFailed). Returns (rows, note)."""
topics = dict(VAB_TOPICS, **(extra or {}))
cpath = os.path.join(HERE, cachefile)
cache = load(cpath, {}) or {}
last = int(cache.get('lastBlock') or start - 1)
logs = cache.get('logs') or [] # every Paid/Claimed log seen (all levels), so the counting rule can change without a rescan
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': shop, 'topics': [list(topics)], 'fromBlock': hex(frm), 'toBlock': hex(to)}]) or []:
if l.get('removed') or str(l.get('address', '')).lower() != shop:
continue
kind, t, data = 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 in ('Paid', 'PaymentFailed'): # data: amount, level, depth
x = {'ev': kind, 'to': '0x' + t[2][-40:].lower(), 'wei': str(int(data[2:66], 16)), 'level': int(data[66:130], 16), 'depth': int(data[130:194], 16)}
elif kind == 'RewardPaid': # topics: nonce, to; data: usdCents, weiPaid, day
x = {'ev': 'RewardPaid', 'to': '0x' + t[2][-40:].lower(), 'wei': str(int(data[66:130], 16)), 'cents': int(data[2:66], 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
if not dry:
tmp = cpath + '.tmp'
with open(tmp, 'w', encoding='utf-8', newline='\n') as f:
json.dump({'lastBlock': last, 'logs': logs, 'at': int(time.time())}, f)
os.replace(tmp, cpath)
rows = []
failed = {(x['tx'], x['to']) for x in logs if x['ev'] == 'PaymentFailed'} # a reward whose push failed is counted when Claimed
for x in logs:
member = (x['ev'] == 'Paid' and 1 <= int(x.get('level') or 0) <= maxlevel) or (x['ev'] == 'Claimed' and x.get('who') not in house) or (x['ev'] == 'RewardPaid' and (x['tx'], x['to']) not in failed)
if member and x['to'] not in house and int(x['wei']) > 0:
rows.append({'k': k, 'pol': int(x['wei']) / 1e18, 'tx': x['tx'], 'ts': ms(x['ts']), 'w': x['to'], 'gu': ''})
allwei = sum(int(x['wei']) for x in logs if x['ev'] == 'Paid')
return rows, k + ': scanned to block %d, %d contract logs (%.4f POL in all Paid events), %d member payouts %.4f POL%s' % (
last, len(logs), allwei / 1e18, 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)
ar, anote = vab_rows(dry)
rows += ar
print(anote)
fr, fnote = vab_rows(dry, 'fx', FX_SHOP, FX_START, FX_HOUSE, 'fx-chain.json')
rows += fr
print(fnote)
hr, hnote = vab_rows(dry, 'dh', DH_SHOP, DH_START, DH_HOUSE, 'dh-chain.json')
rows += hr
print(hnote)
sr, snote = vab_rows(dry, 'vas', VAS_SHOP, VAS_START, VAS_HOUSE, 'vas-chain.json', 6, VAS_TOPICS)
rows += sr
print(snote)
yr, ynote = vab_rows(dry, 'ypb', YPB_SHOP, YPB_START, YPB_HOUSE, 'ypb-chain.json')
rows += yr
print(ynote)
# 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]}
# My Stack POL (Marty 2026-11-19): the signed-in member area. Every paid member's own rows (newest first, up to 500), their totals
# (the same sums as their public stack), the wallets mapped to them, whether their page is on, plus IAP's explicit switches and Pro
# owners. Read only by /my for the member who is signed in; never rendered on a public page, so a switched-off member stays hidden.
wl = {}
for a, un in wu.items():
if a and un:
wl.setdefault(str(un).lower(), set()).add(str(a).lower())
members = {}
for r in rows:
un = r['u']
if not un:
continue
m = members.setdefault(un, {'total': 0.0, 'payments': 0, 'since': r['ts'], 'byProg': {}, 'rows': []})
m['total'] += r['pol']; m['payments'] += 1; m['since'] = min(m['since'], r['ts'])
b = m['byProg'].setdefault(r['k'], {'pol': 0.0, 'payments': 0}); b['pol'] += r['pol']; b['payments'] += 1
if len(m['rows']) < 500:
m['rows'].append({'k': r['k'], 'pol': round(r['pol'], 4), 'tx': r['tx'], 'ts': r['ts']})
for un, m in members.items():
m['total'] = round(m['total'], 4)
m['byProg'] = {k: {'pol': round(v['pol'], 4), 'payments': v['payments']} for k, v in m['byProg'].items()}
m['wallets'] = sorted(wl.get(un, set()))
m['page'] = un in stacks
switch = {str(un).lower(): bool(on) for un, on in (so.get('users', {}) if isinstance(so, dict) else {}).items()}
my = {'members': members, 'switch': switch, 'pro': sorted(pro)}
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, 'my': my}
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()