"""Shared read-only JSON-RPC helper for the WebWorthIt chain scan. Every method here is a read (eth_call, eth_getLogs, eth_getCode, ...). Nothing signs or sends a transaction. Provider facts (checked 2026-11-16): - bsc: nodereal public demo key = archive + full log history, getLogs 50,000 blocks (use 49,000), rate limited. blxrbdn = full history, 5,000 blocks. publicnode = recent days only (silently returns [] for old blocks: never for history). - polygon: publicnode getLogs 10,000 blocks, about 1M blocks of history (older = "Archive requests require a personal token"). drpc free: archive eth_getCode ok, getLogs small ranges. - eth: publicnode recent ~100k blocks only; drpc free archive getCode, getLogs small ranges. - base: publicnode 1,000-block getLogs with deep history; drpc archive getCode. """ import requests, time, json, threading from concurrent.futures import ThreadPoolExecutor NODEREAL = 'https://bsc-mainnet.nodereal.io/v1/64a9df0874fb4a93b9d0a3849de012d3' CHAINS = { 'bsc': {'id': 56, 'name': 'BNB Chain', 'native': 'BNB', 'explorer': 'https://bscscan.com', 'rpcs': ['https://bsc-dataseed.bnbchain.org', 'https://bsc-rpc.publicnode.com', NODEREAL, 'https://bsc-dataseed1.defibit.io', 'https://bsc-dataseed2.ninicoin.io'], 'log_providers': [(NODEREAL, 49000), ('https://bsc.rpc.blxrbdn.com', 5000)], 'archive_rpcs': [NODEREAL], 'block_secs': 0.45, 'tokens': {'USDT': '0x55d398326f99059ff775485246999027b3197955', 'USDC': '0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d', 'BUSD': '0xe9e7cea3dcd96aee6a24b63ae6d6e53fba8a9b56'}}, 'polygon': {'id': 137, 'name': 'Polygon', 'native': 'POL', 'explorer': 'https://polygonscan.com', 'rpcs': ['https://polygon-bor-rpc.publicnode.com', 'https://polygon.drpc.org', 'https://1rpc.io/matic'], 'log_providers': [('https://polygon-bor-rpc.publicnode.com', 9999), ('https://polygon.drpc.org', 9999)], 'archive_rpcs': ['https://polygon.drpc.org', 'https://1rpc.io/matic'], 'block_secs': 2.0, 'tokens': {'USDT': '0xc2132d05d31c914a87c6611c10748aeb04b58e8f', 'USDC': '0x3c499c542cef5e3811e1192ce70d8cc03d5c3359', 'USDC.e': '0x2791bca1f2de4661ed88a30c99a7a9449aa84174'}}, 'eth': {'id': 1, 'name': 'Ethereum', 'native': 'ETH', 'explorer': 'https://etherscan.io', 'rpcs': ['https://ethereum-rpc.publicnode.com', 'https://eth.drpc.org', 'https://1rpc.io/eth'], 'log_providers': [('https://ethereum-rpc.publicnode.com', 9999), ('https://eth.drpc.org', 9999)], 'archive_rpcs': ['https://eth.drpc.org'], 'block_secs': 12.0, 'tokens': {'USDT': '0xdac17f958d2ee523a2206206994597c13d831ec7', 'USDC': '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'}}, 'base': {'id': 8453, 'name': 'Base', 'native': 'ETH', 'explorer': 'https://basescan.org', 'rpcs': ['https://base-rpc.publicnode.com', 'https://base.drpc.org', 'https://mainnet.base.org'], 'log_providers': [('https://base-rpc.publicnode.com', 999), ('https://base.drpc.org', 999)], 'archive_rpcs': ['https://base.drpc.org', 'https://mainnet.base.org'], 'block_secs': 2.0, 'tokens': {'USDC': '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', 'USDT': '0xfde4c96c8593536e31f229ea8f37b2ada2699bb2'}}, } TRANSFER = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' APPROVAL = '0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925' S = requests.Session() S.headers.update({'user-agent': 'webworthit-readonly-scan/1'}) class RPC: def __init__(self, chain): self.name = chain; self.c = CHAINS[chain]; self.i = 0; self.calls = 0; self.lock = threading.Lock() def _post(self, u, method, params, timeout=60): with self.lock: self.calls += 1 return S.post(u, json={'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}, timeout=timeout).json() def call(self, method, params, tries=6, urls=None): last = None; us = urls or self.c['rpcs'] for t in range(tries): u = us[(self.i + t) % len(us)] try: j = self._post(u, method, params) if 'error' in j: last = j['error'] # a revert is an answer, not a provider failure if method == 'eth_call' and isinstance(last, dict) and ('revert' in str(last.get('message', '')).lower() or last.get('code') == 3): raise CallReverted(last) time.sleep(0.4); continue return j['result'] except CallReverted: raise except Exception as e: last = str(e); time.sleep(0.4) raise Exception('%s failed: %s' % (method, str(last)[:200])) def block(self): return int(self.call('eth_blockNumber', []), 16) def eth_call(self, to, data, block='latest', frm=None): q = {'to': to, 'data': data} if frm: q['from'] = frm return self.call('eth_call', [q, block]) def code(self, a, block='latest', urls=None): return self.call('eth_getCode', [a, block], urls=urls) def block_ts(self, n): return int(self.call('eth_getBlockByNumber', [hex(n), False])['timestamp'], 16) def _chunk(self, q, a, b, deadline): """One block range through the provider list. Returns (logs, ok).""" provs = self.c['log_providers'] # the first provider is the main one: give it most tries (a rate limit clears in seconds); the others are fallbacks order = [0, 0, 0] + list(range(1, len(provs))) + [0, 0] for attempt, pi in enumerate(order): if time.time() > deadline: return [], False u, span = provs[pi] try: out = [] for x in range(a, b + 1, span): if time.time() > deadline: raise TimeoutError() y = min(x + span - 1, b) qq = dict(q); qq['fromBlock'] = hex(x); qq['toBlock'] = hex(y) j = self._post(u, 'eth_getLogs', [qq], timeout=45 if pi == 0 else 20) if 'error' in j: raise Exception(j['error']) out += j['result'] return out, True except TimeoutError: return [], False except Exception: time.sleep(min(1.5 * (attempt + 1), 6)) return [], False def logs(self, addr, frm, to, topics=None, threads=3, deadline=None): """Logs in [frm, to]. Returns (logs, gaps) where gaps = list of [a, b] ranges that could not be read.""" deadline = deadline or time.time() + 600 span = self.c['log_providers'][0][1] rngs = [(a, min(a + span - 1, to)) for a in range(frm, to + 1, span)] q = {} if addr: q['address'] = addr if topics: q['topics'] = topics out, gaps = [], [] with ThreadPoolExecutor(threads) as ex: for (a, b), (r, ok) in zip(rngs, ex.map(lambda r: self._chunk(q, r[0], r[1], deadline), rngs)): out += r if not ok: gaps.append([a, b]) out.sort(key=lambda l: (int(l['blockNumber'], 16), int(l['logIndex'], 16))) # merge adjacent gaps m = [] for g in gaps: if m and g[0] == m[-1][1] + 1: m[-1][1] = g[1] else: m.append(g) return out, m class CallReverted(Exception): pass def addr_topic(a): return '0x' + '0' * 24 + a.lower()[2:] def topic_addr(t): return '0x' + t[-40:]