#!/usr/bin/env python3
# fetch_reads.py — reproduce the on-chain reads behind holder-recount.md
# Usage: python3 fetch_reads.py [block]   (default: latest)
# NOTE: bsc-dataseed prunes state — pinned-block reads return "missing trie node"
# within ~hours. Re-run at latest; the report pins block 124558297 values.
import json, urllib.request, sys
RPCS = ["https://bsc-dataseed.binance.org", "https://bsc-dataseed1.defibit.io",
        "https://bsc-dataseed2.binance.org"]
TOKEN = "0x90c8889f428F9Ebb77BB8f15CAD3a50a9aC680df"
POOL_WBNB = "0xca93ec685b8623688e6b236f9068034b298c2150"
POOL_BTCB = "0x740a3b4a91cb8fa47e85d7f9713ca6ec2f8a037e"

def rpc(method, params):
    for u in RPCS:
        try:
            req = urllib.request.Request(u, data=json.dumps(
                {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode(),
                headers={"Content-Type": "application/json"})
            return json.load(urllib.request.urlopen(req, timeout=20))
        except Exception:
            continue
    raise RuntimeError("all RPCs failed")

def call(to, data, blk):
    return rpc("eth_call", [{"to": to, "data": data}, hex(blk)]).get("result")

pad = lambda a: "0x" + "0" * 24 + a[2:].lower()
HOLDERS = {
    "pair_v3_wbnb (contract)": POOL_WBNB,
    "pair_v3_btcb (contract)": POOL_BTCB,
    "eoa_58fab0": "0x58fab046ce77064bf52c2eff4e163eb84386b8b4",
    "dead": "0x000000000000000000000000000000000000dead",
    "creator_eoa": "0x2ea90ff709b0fb5decd1de944f644eecdc26d33a",
    "eoa_f0e319": "0xf0e319587b54db351f4a20e2da09848fed4d8151",
    "eoa_5dedb3": "0x5dedb37eaa9145dd1a17d385d8c5e256871d6f16",
    "eoa_9a937a": "0x9a937a531a3e4b7930a49548b64c4a3471d049e2",
    "eoa_dbf2bd": "0xdbf2bdecf7dff212880552398b42e0ab997523a7",
    "eoa_4492ca": "0x4492ca070a2caea1502fb807b389b62ab32eb0d3",
    "treasury": "0x7C34E9e21eE28A49Ff0b84B61774119E6633359f",
    "pair_v2_a": "0x10cb4724d87896cd35be7f95322df1eadbb41d64",
    "pair_v2_b": "0x379a1d2cfa054eb3b358d7858831875b1cb46564",
}
blk = int(sys.argv[1]) if len(sys.argv) > 1 else int(rpc("eth_blockNumber", [])["result"], 16)
print("block:", blk)
def num(v):
    return int(v, 16) / 1e18 if v else float("nan")
supply = num(call(TOKEN, "0x18160ddd", blk))
print(f"totalSupply: {supply:,.0f}")
for k, a in HOLDERS.items():
    v = call(TOKEN, "0x70a08231" + pad(a)[2:], blk)
    print(f"{k:26s} {num(v):>18,.2f} FLAPJAX")
v = call(POOL_WBNB, "0x1a686502", blk)
liq = int(v, 16) if v else float("nan")
print(f"pool.liquidity(): {liq/1e18:.11f}  (lock record: 320678.316678999036604866 -> ratio {liq/1e18/320678.316678999036604866:.8f})")
