WebWorthIt staging: read-only contract + website check (Marty 2026-11-16)

Free check (DeepSeek v4.1 Flash scorecard) and deep report (Opus 5.5) over a generalised
evidence pack from the read-only chain tools; fact gate blocks any address, tx or number not
in the evidence; MySQL store; hub sign-in, sponsor line recorder, vouchers, ad slots in iframes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-16 10:54:08 -06:00
commit 6616680fc6
52 changed files with 5276 additions and 0 deletions
+133
View File
@@ -0,0 +1,133 @@
"""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:]
+53
View File
@@ -0,0 +1,53 @@
"""Pure-Python Keccak-256 (the Ethereum variant, not NIST SHA3), for function selectors and event topics from a verified ABI.
Small inputs only (signatures), so speed does not matter."""
RC = [0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, 0x000000000000808B, 0x0000000080000001,
0x8000000080008081, 0x8000000000008009, 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
0x000000000000800A, 0x800000008000000A, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008]
ROT = [[0, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61], [28, 55, 25, 21, 56], [27, 20, 39, 8, 14]]
M = (1 << 64) - 1
def _rol(x, n): return ((x << n) | (x >> (64 - n))) & M if n else x
def _f(A):
for rnd in range(24):
C = [A[x][0] ^ A[x][1] ^ A[x][2] ^ A[x][3] ^ A[x][4] for x in range(5)]
D = [C[(x - 1) % 5] ^ _rol(C[(x + 1) % 5], 1) for x in range(5)]
A = [[A[x][y] ^ D[x] for y in range(5)] for x in range(5)]
B = [[0] * 5 for _ in range(5)]
for x in range(5):
for y in range(5):
B[y][(2 * x + 3 * y) % 5] = _rol(A[x][y], ROT[x][y])
A = [[B[x][y] ^ ((~B[(x + 1) % 5][y]) & B[(x + 2) % 5][y]) for y in range(5)] for x in range(5)]
A[0][0] ^= RC[rnd]
return A
def keccak256(data: bytes) -> bytes:
rate = 136
p = bytearray(data) + b'\x01' + b'\x00' * ((rate - (len(data) + 1) % rate) % rate)
p[-1] |= 0x80
A = [[0] * 5 for _ in range(5)]
for off in range(0, len(p), rate):
blk = p[off:off + rate]
for i in range(rate // 8):
x, y = i % 5, i // 5
A[x][y] ^= int.from_bytes(blk[8 * i:8 * i + 8], 'little')
A = _f(A)
out = b''
for i in range(4):
x, y = i % 5, i // 5
out += A[x][y].to_bytes(8, 'little')
return out
def selector(sig): return '0x' + keccak256(sig.encode()).hex()[:8]
def topic(sig): return '0x' + keccak256(sig.encode()).hex()
if __name__ == '__main__':
assert selector('transfer(address,uint256)') == '0xa9059cbb', selector('transfer(address,uint256)')
assert topic('Transfer(address,address,uint256)') == '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
print('ok')
+154
View File
@@ -0,0 +1,154 @@
"""Evidence pack + deterministic facts from evidence.json (any contract, any supported chain).
Generalised from D:/tmp/wwi-cost/pack.py (which was hard-wired to the 3xSusu raw files).
build(E) -> markdown the model reads. facts(E) -> [{tag, text, source}] used when a model report fails the fact check,
and shown beside every report. Every number here is computed in code, never by the model."""
import json
def f2(x):
return '%.2f' % x if isinstance(x, (int, float)) else str(x)
def short(a): return a[:6] + '...' + a[-4:] if a and len(a) == 42 else a
def build(E):
o = []; w = o.append
ex = E['explorer']
w('# Evidence pack: %s contract %s' % (E['chain_name'], E['address']))
w('Read at block %s (%s). All reads are public and read-only.\n' % (E['read_at']['block'], E['read_at']['time_ct']))
if not E.get('is_contract'):
w('## Not a contract\nThe address has no contract code. It is: %s. Native balance %s %s, nonce %s.' % (E.get('kind'), f2(E.get('native_balance')), E['native'], E.get('nonce')))
return '\n'.join(o)
px = E['proxy']
w('## Proxy and control (VERIFIED: storage slots and eth_call)')
w('- Type: %s' % px['type'])
w('- Upgradeable: %s' % ('yes' if px['upgradeable'] else 'no proxy slot set'))
if px.get('impl') or px.get('eip1822'): w('- Implementation now: %s' % (px.get('impl') or px.get('eip1822')))
if px.get('admin'): w('- ERC1967 admin slot: %s' % px['admin'])
if px.get('beacon'): w('- Beacon: %s' % px['beacon'])
w('- Code size: %s bytes (implementation %s bytes)' % (E.get('code_bytes'), E.get('impl_code_bytes')))
w('- Role getters read with eth_call: ' + (json.dumps(E.get('roles')) if E.get('roles') else 'none answered'))
if E.get('values'): w('- Other zero-argument values: ' + json.dumps(E['values']))
if 'paused' in E: w('- paused() now: %s' % E['paused'])
w('- Controller wallets:')
for a, k in (E.get('controllers') or {}).items(): w(' - %s: %s' % (a, k.get('desc')))
if E.get('upgrade_test'):
u = E['upgrade_test']
w('- Upgrade test (%s):' % u['method'])
for a, t in u['results'].items(): w(' - from %s%s: %s' % (a, ' (random address)' if a == u['random_address'] else '', t))
w('- Addresses that can upgrade in one transaction: %s' % (', '.join(E.get('can_upgrade') or []) or 'none found'))
w('')
w('## Source verification (Sourcify)')
for k, v in (E.get('verification') or {}).items(): w('- %s: %s%s' % (k, v.get('match') or 'not verified on Sourcify', (' (' + v['name'] + ')') if v.get('name') else ''))
w('- Note: %s\n' % E.get('verification_source'))
s = E.get('selectors') or {}
w('## Functions in the code (%s selectors, %s named; names from %s)' % (s.get('count'), s.get('named'), s.get('names_source')))
w(', '.join('%s %s' % (k, v or '?') for k, v in (s.get('map') or {}).items()))
w('- Control or custody related functions present: ' + (', '.join(E.get('risky_functions') or []) or 'none matched'))
if E.get('abi_functions'): w('- Verified ABI functions: ' + ', '.join(E['abi_functions'][:120]))
w('')
c = E.get('creation') or {}; win = E.get('window') or {}
w('## Deployment and history read')
w('- Creation block: %s (%s) source: %s; time %s; tx %s; deployer %s' % (c.get('block'), c.get('block') is not None and 'known' or 'unknown', c.get('source'), c.get('time_ct'), c.get('tx'), c.get('from')))
if E.get('age_days') is not None: w('- Contract age: %s days' % E['age_days'])
if c.get('addresses_in_input'): w('- Addresses passed in the deployment transaction input: ' + ', '.join(c['addresses_in_input']))
w('- Blocks read: %s to %s (%s blocks, from %s). Complete history: %s' % (win.get('from'), win.get('to'), win.get('blocks'), win.get('from_time_ct'), win.get('complete_history')))
for g in E.get('gaps') or []: w('- NOT READ (provider failure or time limit): %s, block ranges %s' % (g['what'], g['ranges'][:6]))
w('')
ev = E.get('events') or {}
w('## Events emitted by the contract (%s logs in the window)' % ev.get('total'))
for t in ev.get('by_topic', []): w('- %s %s: %d' % (t['topic'][:10], t['name'] or '', t['count']))
for nm, d in (E.get('decoded_events') or {}).items():
w('- Decoded %s: %d events; sums of number fields (raw integer units; for 18-decimal coins divide by 10^18): %s; top addresses per field: %s; first samples: %s' % (
nm, d['count'], json.dumps(d['uint_field_sums_raw']), json.dumps(d['top_addresses']), json.dumps(d['first_samples'])))
cn = E.get('counts') or {}
w('\n## Precomputed counts (use these, do not recount)')
w('- Upgraded events total: %s' % cn.get('upgrade_events_total'))
w('- Upgrades AFTER deployment: %s (%s)' % (cn.get('upgrades_after_deployment'), cn.get('upgrades_note')))
w('- Paused events: %s; ownership transfers: %s' % (cn.get('pause_events'), cn.get('ownership_transfers')))
w('\n## Admin event timeline')
for x in E.get('admin_events') or []:
w('- %s block %s tx %s %s %s%s%s' % (x.get('time_ct'), x['block'], x['tx'], x['event'], x.get('arg') or '', ' [in the deployment tx]' if x.get('in_creation_tx') else '',
(' sent by ' + x['from'] + ' selector ' + x.get('selector', '')) if x.get('from') else ''))
w('\n## Money held and moved (token Transfer logs, VERIFIED)')
w('- Native %s balance of the contract now: %s' % (E['native'], f2(E.get('native_balance'))))
tx = E.get('txs')
if tx:
w('- Transactions behind the events: %d (read %d, %s). Direct calls to the contract among them: %d; native %s sent in with them: %s (%d calls carried a value).' % (
tx['event_txs_total'], tx['read'], tx['read_note'], tx['direct_calls'], E['native'], f2(tx['native_sent_in']), tx['calls_with_native']))
w('- Direct calls by function: ' + ', '.join('%s x%d' % (a, n) for a, n in tx['by_function']))
w('- Top direct callers: ' + ', '.join('%s x%d' % (a, n) for a, n in tx['top_senders']))
w('- Native coin paid OUT by the contract (internal transfers) is not visible in logs and was not traced (UNKNOWN).')
if not E.get('money'): w('- No transfers of the stable tokens checked (%s) in the window, and no balance.' % ', '.join(E.get('tokens_checked', [])))
for sy, m in (E.get('money') or {}).items():
w('### %s (%s, %s decimals)' % (sy, m['token'], m['decimals']))
w('- Balance now (balanceOf): %s' % f2(m['balance_now']))
w('- In: %d transfers, %s total, from %d wallets' % (m['in_count'], f2(m['in_total']), m['payers']))
w('- Out: %d transfers, %s total, to %d wallets' % (m['out_count'], f2(m['out_total']), m['recipients']))
w('- In minus out over the window: %s' % f2(m['net_in_minus_out']))
w('- Top recipients (address, total, transfers): ' + '; '.join('%s %s x%d' % (a, f2(v), n) for a, v, n in m['top_recipients']))
w('- Top payers: ' + '; '.join('%s %s x%d' % (a, f2(v), n) for a, v, n in m['top_payers']))
w('- Most common outgoing sizes (size x count): ' + ', '.join('%s x%d' % (a, n) for a, n in m['out_sizes']))
if m['daily_in_counts']: w('- Incoming transfers per day (CT): ' + ', '.join('%s:%d' % (d, n) for d, n in m['daily_in_counts']))
w('\n## Wallet approvals to this contract (Approval logs + live allowance, VERIFIED)')
if not E.get('approvals'): w('- None found in the window.')
for sy, a in (E.get('approvals') or {}).items():
w('- %s: %d approval events, %d approving wallets (%d read), %d with a live allowance, %d unlimited, total that could be pulled from wallets right now %s' % (
sy, a['approval_events'], a['approving_wallets'], a['read'], a['live_allowances'], a['unlimited'], f2(a['pullable_now'])))
p = E.get('positions')
if p:
w('\n## Positions stored in the contract (%s)' % p['method'])
w('- %s = %s; owners read %s; distinct owners %s' % (p['count_function'], p['count'], p['read'], p['owners']))
w('- Top owners (address, positions): ' + '; '.join('%s %d' % (a, n) for a, n in p['top_owners']))
w('\n## Wallet profiles (role holders, deployer, deployment-input addresses, top recipients)')
for a, k in (E.get('wallets') or {}).items():
w('- %s [%s] %s, nonce %s, native %s, received from contract %s%s' % (a, ', '.join(k.get('labels') or []) or 'top recipient', k.get('desc'), k.get('nonce'), f2(k.get('native_balance')),
json.dumps(k.get('received_from_contract') or {}), (', positions owned %s' % k['positions_owned']) if 'positions_owned' in k else ''))
w('\n## Notes')
for n in E.get('notes') or []: w('- ' + n)
return '\n'.join(o)
def facts(E):
F = []; ex = E['explorer']
add = lambda tag, text, src=None: F.append({'tag': tag, 'text': text, 'source': src})
A = E['address']
if not E.get('is_contract'):
add('VERIFIED', 'This address has no contract code: it is %s.' % E.get('kind'), ex + '/address/' + A)
return F
px = E['proxy']
if px['upgradeable']:
add('VERIFIED', 'The contract is an upgradeable proxy (%s). Its code can be replaced.' % px['type'], ex + '/address/' + A)
else:
add('VERIFIED', 'No upgradeable-proxy slot is set: %s.' % px['type'], ex + '/address/' + A)
for a in E.get('can_upgrade') or []:
k = (E.get('controllers') or {}).get(a) or {}
add('VERIFIED', 'Address %s can upgrade the code in one transaction (simulated with eth_call). It is a %s.' % (a, k.get('desc', 'wallet')), ex + '/address/' + a)
cn = E.get('counts') or {}
if cn.get('upgrades_after_deployment') is not None and px['upgradeable']:
add('VERIFIED', 'Upgrades after deployment: %s.' % cn['upgrades_after_deployment'], None)
for x in [y for y in E.get('admin_events') or [] if y['event'] == 'Upgraded(address)' and not y.get('in_creation_tx')][:6]:
add('VERIFIED', 'Upgrade on %s to implementation %s.' % (x.get('time_ct'), x.get('arg')), ex + '/tx/' + x['tx'])
for k, v in (E.get('verification') or {}).items():
add('VERIFIED' if v.get('match') else 'UNKNOWN', '%s source: %s on Sourcify.' % (k.capitalize(), 'verified (' + v['match'] + ')' if v.get('match') else 'not verified'), None)
for fn, a in (E.get('roles') or {}).items():
k = (E.get('controllers') or {}).get(a) or {}
add('VERIFIED', '%s returns %s (%s).' % (fn, a, k.get('desc', '')), ex + '/address/' + a)
if 'paused' in E: add('VERIFIED', 'paused() is %s now.' % E['paused'], None)
if E.get('risky_functions'): add('INFERRED', 'Functions related to control or custody found in the code: %s.' % ', '.join(E['risky_functions'][:20]), None)
add('VERIFIED', 'Native %s balance now: %s.' % (E['native'], f2(E.get('native_balance'))), ex + '/address/' + A)
for sy, m in (E.get('money') or {}).items():
add('VERIFIED', '%s balance now: %s. Received %s in %d transfers; sent out %s in %d transfers (blocks %s to %s).' % (
sy, f2(m['balance_now']), f2(m['in_total']), m['in_count'], f2(m['out_total']), m['out_count'], E['window']['from'], E['window']['to']), ex + '/address/' + A)
for sy, a in (E.get('approvals') or {}).items():
add('VERIFIED', '%s approvals: %d wallets approved this contract; %d unlimited; %s could be pulled from wallets right now.' % (sy, a['approving_wallets'], a['unlimited'], f2(a['pullable_now'])), None)
p = E.get('positions')
if p and p['top_owners']:
a, n = p['top_owners'][0]
lab = ', '.join(((E.get('wallets') or {}).get(a) or {}).get('labels') or [])
add('INFERRED', 'Top position owner %s%s holds %d of %d positions.' % (a, (' (' + lab + ')') if lab else '', n, p['count']), ex + '/address/' + a)
win = E.get('window') or {}
add('VERIFIED', 'History read: blocks %s to %s%s.' % (win.get('from'), win.get('to'), ' (complete since deployment)' if win.get('complete_history') else ' (partial window)'), None)
for g in E.get('gaps') or []: add('UNKNOWN', 'Not read: %s in %d block ranges (provider limit or time cap).' % (g['what'], len(g['ranges'])), None)
return F
+72
View File
@@ -0,0 +1,72 @@
# Contract risk scoring rubric (draft v1, from the 3xSusu review 2026-11-16)
Score each category 0 to 10 (10 = worst), then weight. A single "critical" red flag caps the overall
grade at High risk whatever the total. Every score must cite evidence tagged VERIFIED (on chain, tx/block),
INFERRED (bytecode/decompile/simulation) or UNKNOWN. Unknown counts against the project: if the team
hid it, assume the worse case and say so.
## 1. Control and upgradeability (weight 25)
Raises risk:
- Upgradeable proxy (UUPS or Transparent) whose upgrade right sits with a single EOA (critical)
- Upgrades already used after launch, especially after money arrived (each one is a reset of everything audited)
- No timelock, no multisig, no on-chain delay or announcement event before upgrade
- Implementation source unverified (critical when combined with upgradeability)
- Owner can pause the functions members use to get money out (refund/claim/withdraw)
- Owner can change fee splits, recipients, limits or token addresses after launch
- Controller wallets are EIP-7702 delegated EOAs (code you also need to review)
Lowers risk:
- Immutable contract, or ownership renounced (verify `owner()` = 0 and no other role can upgrade)
- Upgrade/admin held by a Safe with a meaningful threshold plus a timelock of at least 48 h
- Verified source matching the deployed bytecode
## 2. Custody and exit paths (weight 25)
List every path by which tokens can leave the contract and who can trigger each. Raises risk:
- Any owner/admin sweep, rescue, withdraw, setRecipient or arbitrary-call function (critical)
- Members' unlimited token approvals to an upgradeable spender (the code behind the spender can change)
- Refund/claim promises that the reserve cannot cover (compare liability vs balance)
- Member balances held as a non-transferable internal token that can only be "spent" back into the scheme
Lowers risk:
- Members can withdraw their own principal at any time, unpausable, without a gate
- Exact accounting: outflows = sum of rule-based splits, no unexplained outflows (check with tokenflow)
## 3. Economic design (weight 20)
Raises risk:
- Returns funded only by later entrants (matrix/cycler/"3x"): payouts trigger only on new entries
- Advertised multiple (e.g. "3x") needs N later entries per position; compute N and the growth needed
- Fallback/refund funded by a small slice per entry (e.g. $1 per $35) while the liability grows per position
- "Company buy" / system buyback positions owned by an operator wallet that also collects payouts
Lowers risk:
- An external revenue source exists and is visible on chain
- Reserve fully covers stated refund obligations at today's numbers
## 4. Insider flows (weight 15)
Raises risk:
- Share of outflows going to deployer-configured wallets (platform, admin, buyback, default referrer)
- Insider wallets funding each other or a shared sink, or cycling money back in as "entries"
- Insider wallets sending to exchanges/bridges/mixers soon after receipt (label only when confirmed)
- Operator-owned positions inflating the entry count or "activity"
Lowers risk:
- Fixed, small, disclosed fees to a single published treasury
## 5. Disclosure vs code (weight 10)
Raises risk:
- Claims of "ownerless", "decentralized", "cannot be changed" while an owner can upgrade (critical)
- Guarantee-like language (refund 100% + 50%) that the code meets only partly or in a non-cash token
- No verified source, no audit, anonymous team
Lowers risk:
- Docs match code paths, amounts and conditions
## 6. Trajectory (weight 5)
- Daily/weekly inflow trend: growing, flat, slowing. In a recruitment-funded design, slowing inflow means
later entrants' positions stall and refund liabilities mature.
- Age of the contract versus refund windows (when do the first obligations fall due?)
## Red flags that each force "High risk"
1. Single-EOA upgrade or sweep right over member funds
2. Unverified implementation behind an upgradeable proxy
3. "Ownerless/decentralized" marketing while an owner key controls upgrades
4. Payouts that exist only when new money enters
5. Refund/guarantee liability larger than the reserve that backs it
## Grade bands
0 to 25 Low, 26 to 50 Moderate, 51 to 75 Elevated, 76 to 100 High (or forced High by a red flag).
+593
View File
@@ -0,0 +1,593 @@
"""WebWorthIt chain scan: one read-only pass over a contract, producing evidence.json (structured facts with sources)
and pack.md (the evidence pack the model reads). Generalised from the 3xSusu review tools (D:/tmp/bsc-audit/tools).
Usage: python3 scan.py CHAIN ADDRESS OUTDIR [--budget SECONDS] [--hint-abi FILE]
Prints one JSON progress line per step on stdout ({"step": ...}) and a final {"done": true}.
READ-ONLY: every RPC used is a read (eth_call, eth_getLogs, eth_getCode, eth_getStorageAt, eth_getBalance, ...).
No key, no signing, no transaction is ever sent. eth_call simulations change nothing on chain.
Deterministic counts (the model never counts): upgrades after deployment, events per type, transfers in/out, totals,
balances, positions per owner, approvals. Every number in pack.md comes from here.
"""
import sys, os, json, time, re, collections, datetime, random
from concurrent.futures import ThreadPoolExecutor
import requests
from chainrpc import RPC, CHAINS, TRANSFER, APPROVAL, addr_topic, topic_addr, CallReverted
import keccak
try:
from zoneinfo import ZoneInfo
CT = ZoneInfo('America/Chicago')
except Exception:
CT = None
SLOTS = {'impl': '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc',
'admin': '0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103',
'beacon': '0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50',
'eip1822': '0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7'}
EVENTS = {
'0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b': 'Upgraded(address)',
'0x7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f': 'AdminChanged(address,address)',
'0x1cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e': 'BeaconUpgraded(address)',
'0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0': 'OwnershipTransferred(address,address)',
'0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700': 'OwnershipTransferStarted(address,address)',
'0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258': 'Paused(address)',
'0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa': 'Unpaused(address)',
'0xc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2': 'Initialized(uint64)',
'0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498': 'Initialized(uint8)',
'0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d': 'RoleGranted(bytes32,address,address)',
'0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b': 'RoleRevoked(bytes32,address,address)',
TRANSFER: 'Transfer(address,address,uint256)', APPROVAL: 'Approval(address,address,uint256)',
}
ADMIN_EVENTS = {k for k, v in EVENTS.items() if not v.startswith(('Transfer', 'Approval'))}
UPGRADED = '0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b'
# selectors whose presence matters for custody / control (names from public signature databases)
RISKY = re.compile(r'^(upgradeTo|upgradeToAndCall|withdraw|emergencyWithdraw|sweep|rescue|recover|drain|skim|setFee|setFees|setTax|setRouter|'
r'setToken|setTreasury|setWallet|setRecipient|setReceiver|setPlatform|setAdmin|setOwner|transferOwnership|renounceOwnership|'
r'pause|unpause|mint|burn|blacklist|addBlacklist|setBlacklist|execute|multicall|call|delegatecall|setImplementation|'
r'changeAdmin|grantRole|revokeRole|setOperator|setManager|setSplit|setPrice|setLimit|setMax|withdrawAll|withdrawTokens|'
r'adminWithdraw|ownerWithdraw|emergency|migrate|setContract|setVault|query)', re.I)
POSITION_PAIRS = [('totalEntries()', 'entries(uint256)'), ('totalPositions()', 'positions(uint256)'), ('positionCount()', 'positions(uint256)'),
('nextPositionId()', 'positions(uint256)'), ('totalSlots()', 'slots(uint256)'), ('totalNodes()', 'nodes(uint256)'),
('totalDeposits()', 'deposits(uint256)'), ('depositCount()', 'deposits(uint256)')]
KNOWN_SEL = {'owner()': '0x8da5cb5b', 'admin()': '0xf851a440', 'getOwner()': '0x893d20e8', 'paused()': '0x5c975abb',
'totalEntries()': '0x7fef036e', 'entries(uint256)': '0xb30906d4', 'proxiableUUID()': '0x52d1902d',
'upgradeToAndCall(address,bytes)': '0x4f1ef286', 'decimals()': '0x313ce567', 'balanceOf(address)': '0x70a08231',
'allowance(address,address)': '0xdd62ed3e', 'getThreshold()': '0xe75235b8', 'getOwners()': '0xa0e67e2b',
'pendingOwner()': '0xe30c3978', 'implementation()': '0x5c60da1b', 'symbol()': '0x95d89b41', 'name()': '0x06fdde03'}
T0 = time.time()
def step(name, **kw):
print(json.dumps(dict({'step': name, 't': round(time.time() - T0, 1)}, **kw)), flush=True)
def ct(ts):
d = datetime.datetime.fromtimestamp(ts, CT) if CT else datetime.datetime.utcfromtimestamp(ts)
return d.strftime('%Y-%m-%d %H:%M ') + (d.tzname() if CT else 'UTC')
def addr_of(w):
if not w or w == '0x' or len(w) < 42: return None
try:
v = int(w, 16)
except Exception:
return None
if v == 0 or v >= 2 ** 160: return None
return '0x' + w[-40:].lower()
def words(hexdata):
h = hexdata[2:] if hexdata.startswith('0x') else hexdata
return [h[i:i + 64] for i in range(0, len(h) - len(h) % 64, 64)]
def disasm_push(code):
b = bytes.fromhex(code[2:] if code.startswith('0x') else code); i = 0; out = []
while i < len(b):
op = b[i]
if 0x60 <= op <= 0x7f:
n = op - 0x5f; out.append((n, b[i + 1:i + 1 + n].hex(), b[i + 1 + n] if i + 1 + n < len(b) else None)); i += 1 + n
else:
i += 1
return out
def lookup_selectors(sels):
res = {}
try:
for c in range(0, len(sels), 40):
chunk = sels[c:c + 40]
j = requests.get('https://api.openchain.xyz/signature-database/v1/lookup', params={'function': ','.join(chunk), 'filter': 'true'}, timeout=25).json()
for h, v in (j.get('result', {}).get('function') or {}).items():
if v: res[h] = [x['name'] for x in v]
except Exception:
pass
missing = [s for s in sels if s not in res]
for s in missing[:40]:
try:
j = requests.get('https://www.4byte.directory/api/v1/signatures/', params={'hex_signature': s}, timeout=15).json()
if j.get('results'): res[s] = [x['text_signature'] for x in j['results']][:3]
except Exception:
pass
return res
def sourcify(chain_id, a):
try:
r = requests.get('https://sourcify.dev/server/v2/contract/%d/%s?fields=deployment,abi,compilation' % (chain_id, a), timeout=25)
if r.status_code == 200:
j = r.json(); comp = j.get('compilation') or {}
return {'match': j.get('match'), 'deployment': j.get('deployment'), 'abi': j.get('abi'), 'name': comp.get('name'), 'verifiedAt': j.get('verifiedAt')}
return {'match': None, 'status': r.status_code}
except Exception as e:
return {'match': None, 'error': str(e)[:120]}
def abi_sig(f):
def t(i):
if i.get('type', '').startswith('tuple'):
return '(' + ','.join(t(c) for c in i.get('components', [])) + ')' + i['type'][5:]
return i.get('type')
return '%s(%s)' % (f['name'], ','.join(t(i) for i in f.get('inputs', [])))
def main():
chain, A, OUT = sys.argv[1], sys.argv[2].lower(), sys.argv[3]
budget = 420
if '--budget' in sys.argv: budget = int(sys.argv[sys.argv.index('--budget') + 1])
hint_abi = []
if '--hint-abi' in sys.argv:
try: hint_abi = json.load(open(sys.argv[sys.argv.index('--hint-abi') + 1]))
except Exception: hint_abi = []
os.makedirs(OUT, exist_ok=True)
deadline = T0 + budget
r = RPC(chain); C = CHAINS[chain]
E = {'chain': chain, 'chain_name': C['name'], 'address': A, 'explorer': C['explorer'], 'native': C['native'], 'notes': [], 'gaps': []}
E['notes'].append('All data read with public JSON-RPC nodes and public signature/verification databases. Read-only: no transaction was sent.')
# ---- basics
step('basics')
latest = r.block(); latest_ts = r.block_ts(latest)
E['read_at'] = {'block': latest, 'time_ct': ct(latest_ts), 'ts': latest_ts}
code = r.code(A)
if len(code) <= 2 or code.startswith('0xef0100'):
E['is_contract'] = False
E['kind'] = 'EOA+7702-delegation' if code.startswith('0xef0100') else 'EOA (a personal wallet, no contract code)'
E['native_balance'] = int(r.call('eth_getBalance', [A, 'latest']), 16) / 1e18
E['nonce'] = int(r.call('eth_getTransactionCount', [A, 'latest']), 16)
finish(E, OUT); return
E['is_contract'] = True; E['code_bytes'] = (len(code) - 2) // 2
E['native_balance'] = int(r.call('eth_getBalance', [A, 'latest']), 16) / 1e18
# ---- proxy
step('proxy')
px = {k: addr_of(r.call('eth_getStorageAt', [A, s, 'latest'])) for k, s in SLOTS.items()}
impl = px['impl'] or px['eip1822']
if px['beacon']:
px['type'] = 'beacon proxy'
try: impl = addr_of(r.eth_call(px['beacon'], '0x5c60da1b'))
except Exception: pass
elif impl:
try:
r.eth_call(impl, '0x52d1902d'); uups = True
except Exception:
uups = False
px['type'] = 'UUPS proxy (the upgrade function lives in the implementation)' if uups else ('Transparent proxy (upgrades through the admin slot holder)' if px['admin'] else 'ERC1967 proxy')
else:
px['type'] = 'not a standard upgradeable proxy (no ERC1967 / EIP-1822 / beacon slot set)'
px['upgradeable'] = bool(impl)
E['proxy'] = px
code_target = impl or A
tcode = r.code(code_target) if impl else code
E['impl_code_bytes'] = (len(tcode) - 2) // 2
# ---- verification
step('verification')
ver = {'contract': sourcify(C['id'], A)}
if impl: ver['implementation'] = sourcify(C['id'], impl)
E['verification'] = {k: {kk: v.get(kk) for kk in ('match', 'name', 'verifiedAt')} for k, v in ver.items()}
E['verification_source'] = 'Sourcify (sourcify.dev). A contract verified only on a block explorer may show as not found here.'
abi = (ver.get('implementation') or {}).get('abi') or (ver['contract'] or {}).get('abi') or []
abi_src = 'verified source (Sourcify)' if abi else None
if not abi and hint_abi:
abi = hint_abi; abi_src = 'human-readable ABI found in the project website code (INFERRED)'
# ---- selectors
step('selectors')
P = disasm_push(tcode)
sels = sorted({'0x' + v for (n, v, nx) in P if n == 4 and nx == 0x14})
abi_fns = [f for f in abi if isinstance(f, dict) and f.get('type') == 'function' and f.get('name')]
abi_sigs = {abi_sig(f) for f in abi_fns}
abi_sel = {keccak.selector(abi_sig(f)): abi_sig(f) for f in abi_fns}
outs = {abi_sig(f): [o.get('type') for o in f.get('outputs') or []] for f in abi_fns}
for f in abi:
if isinstance(f, dict) and f.get('type') == 'event' and f.get('name'):
EVENTS.setdefault(keccak.topic(abi_sig(f)), abi_sig(f))
missing = [s for s in sels if s not in abi_sel]
looked = lookup_selectors(missing) if missing else {}
selmap = {s: abi_sel.get(s) or (looked.get(s) or [None])[0] for s in sels}
E['selectors'] = {'count': len(sels), 'named': sum(1 for v in selmap.values() if v), 'map': selmap, 'abi_source': abi_src,
'names_source': ('verified ABI' if abi_src and 'Sourcify' in abi_src else 'openchain.xyz / 4byte.directory signature databases (a name is a public guess from the selector, INFERRED)')}
risky = sorted({v for v in selmap.values() if v and RISKY.match(v)})
E['risky_functions'] = risky
if abi:
E['abi_functions'] = sorted(abi_sigs)[:200]
# ---- role getters: every zero-argument named function, read with eth_call (read-only)
step('roles')
zero = sorted({v for v in selmap.values() if v and v.endswith('()')} | {'owner()', 'admin()', 'getOwner()', 'paused()', 'pendingOwner()'})
sel_of = {v: s for s, v in selmap.items() if v}
sel_of.update({k: v for k, v in KNOWN_SEL.items() if k not in sel_of})
roles, values = {}, {}
skip = re.compile(r'^(renounceOwnership|pause|unpause|refund\(\)$|claim|withdraw|execute|buy|purchase|deposit|stake|unstake|harvest|compound|sync|skim|mint|burn)', re.I)
for fn in zero[:60]:
s = sel_of.get(fn)
if not s or skip.match(fn) and fn not in ('refund()',): continue
try:
v = r.eth_call(A, s)
except Exception:
continue
if not v or v == '0x': continue
if len(v) == 66:
a = addr_of(v)
typed = outs.get(fn)
is_addr = (typed == ['address']) if typed else (a is not None and int(v, 16) > 2 ** 120)
if a and is_addr:
roles[fn] = a
else:
iv = int(v, 16)
if fn == 'paused()': values[fn] = bool(iv)
elif iv < 10 ** 30: values[fn] = iv
E['roles'] = roles; E['values'] = values
if 'paused()' in values: E['paused'] = values['paused()']
# ---- controllers: EOA / contract / Safe
step('controllers')
ctl = {}
for a in sorted(set(list(roles.values()) + [x for x in [px['admin']] if x])):
ctl[a] = kind_of(r, a)
# transparent proxy: the admin slot holder is usually a ProxyAdmin contract; read its owner
if px['admin'] and ctl.get(px['admin'], {}).get('type') == 'contract':
try:
o = addr_of(r.eth_call(px['admin'], '0x8da5cb5b'))
if o: roles['proxy admin owner()'] = o; ctl[o] = kind_of(r, o)
except Exception:
pass
E['controllers'] = ctl
# ---- who can upgrade: read-only eth_call of upgradeToAndCall(current impl, "") from each role holder and a random address
if impl and E['proxy']['type'].startswith('UUPS'):
step('upgrade_test')
data = '0x4f1ef286' + addr_topic(impl)[2:] + '0' * 62 + '40' + '0' * 64
tests = {}
cands = list(dict.fromkeys(list(roles.values())))
rnd = '0x' + ''.join(random.choice('0123456789abcdef') for _ in range(40))
for who in cands[:8] + [rnd]:
try:
r.call('eth_call', [{'from': who, 'to': A, 'data': data}, 'latest'], tries=3)
tests[who] = 'succeeds (this address can upgrade)'
except CallReverted as e:
msg = e.args[0] if e.args else {}
tests[who] = 'reverts ' + str((msg.get('data') if isinstance(msg, dict) else '') or (msg.get('message') if isinstance(msg, dict) else msg))[:80]
except Exception as e:
tests[who] = 'no answer'
E['upgrade_test'] = {'method': 'eth_call (simulation, nothing sent) of upgradeToAndCall(current implementation, empty data)', 'random_address': rnd, 'results': tests}
E['can_upgrade'] = [w for w, t in tests.items() if t.startswith('succeeds') and w != rnd]
if tests.get(rnd, '').startswith('succeeds'): E['notes'].append('A random address could call upgradeToAndCall in simulation: the check is not conclusive for this contract.')
# ---- creation block
step('creation')
dep = (ver['contract'] or {}).get('deployment') or {}
created = None; creation_tx = None; creation_src = None
if dep.get('blockNumber'):
created = int(dep['blockNumber']); creation_tx = (dep.get('transactionHash') or '').lower() or None; creation_src = 'Sourcify deployment record'
else:
created = find_creation(r, A, latest)
if created is not None: creation_src = 'binary search of eth_getCode on an archive node'
E['creation'] = {'block': created, 'source': creation_src}
if created is not None:
try: E['creation']['time_ct'] = ct(r.block_ts(created))
except Exception: pass
E['age_days'] = round((latest_ts - r.block_ts(created)) / 86400, 1) if created else None
# ---- log window
span0 = C['log_providers'][0][1]
cap_chunks = 260 # per filter
frm = created if created is not None else max(0, latest - span0 * 40)
if latest - frm + 1 > span0 * cap_chunks:
E['notes'].append('History is longer than one scan covers: only the latest %d blocks were read.' % (span0 * cap_chunks))
frm = latest - span0 * cap_chunks + 1
E['window'] = {'from': frm, 'to': latest, 'blocks': latest - frm + 1, 'complete_history': created is not None and frm == created}
try: E['window']['from_time_ct'] = ct(r.block_ts(frm))
except Exception: pass
# ---- contract logs
step('logs', blocks=latest - frm + 1)
L, gaps = r.logs(A, frm, latest, threads=2, deadline=T0 + budget * 0.32)
toks = C['tokens']; tlist = list(toks.values()); E['tokens_checked'] = list(toks.keys())
qin = [[TRANSFER, APPROVAL], None, addr_topic(A)]; qout = [TRANSFER, addr_topic(A)]
inn, g1 = r.logs(tlist, frm, latest, qin, threads=2, deadline=max(time.time() + 30, T0 + budget * 0.52))
out, g2 = r.logs(tlist, frm, latest, qout, threads=2, deadline=max(time.time() + 30, T0 + budget * 0.72))
# second pass over every range that failed (rate limits clear in seconds), with what is left of the budget
passes = 0
while (gaps or g1 or g2) and time.time() < T0 + budget * 0.88 and passes < 4:
passes += 1; step('retry_gaps', ranges=len(gaps) + len(g1) + len(g2))
dl = T0 + budget * 0.88
def refill(addr, topics, gs, have):
left = []
for a, b in gs:
more, g = r.logs(addr, a, b, topics, threads=1, deadline=dl); have += more; left += g
return left
gaps = refill(A, None, gaps, L); g1 = refill(tlist, qin, g1, inn); g2 = refill(tlist, qout, g2, out)
for lst in (L, inn, out):
seen = set(); uniq = []
for l in lst:
k = (l['transactionHash'], l['logIndex'])
if k not in seen: seen.add(k); uniq.append(l)
uniq.sort(key=lambda l: (int(l['blockNumber'], 16), int(l['logIndex'], 16))); lst[:] = uniq
if gaps: E['gaps'].append({'what': 'contract events', 'ranges': gaps})
if g1: E['gaps'].append({'what': 'token transfers in + approvals', 'ranges': g1})
if g2: E['gaps'].append({'what': 'token transfers out', 'ranges': g2})
tc = collections.Counter(l['topics'][0] if l['topics'] else 'anonymous' for l in L)
E['events'] = {'total': len(L), 'by_topic': [{'topic': t, 'name': EVENTS.get(t), 'count': n} for t, n in tc.most_common(30)]}
if not creation_tx and created is not None:
first = [l for l in L if int(l['blockNumber'], 16) == created]
if first: creation_tx = first[0]['transactionHash'].lower(); E['creation']['tx_source'] = 'transaction of the first event in the creation block'
else:
try:
recs = r.call('eth_getBlockReceipts', [hex(created)], tries=3)
for rc in recs or []:
if (rc.get('contractAddress') or '').lower() == A: creation_tx = rc['transactionHash'].lower(); E['creation']['tx_source'] = 'block receipts'; break
except Exception:
pass
E['creation']['tx'] = creation_tx
tsc = {}
def bts(n):
if n not in tsc:
try: tsc[n] = r.block_ts(n)
except Exception: tsc[n] = None
return tsc[n]
adm = []
for l in L:
if l['topics'] and l['topics'][0] in ADMIN_EVENTS:
b = int(l['blockNumber'], 16)
ts = int(l['blockTimestamp'], 16) if l.get('blockTimestamp') else bts(b)
arg = topic_addr(l['topics'][1]) if len(l['topics']) > 1 and l['topics'][1][2:26] == '0' * 24 else (topic_addr(l['data']) if l['topics'][0] == UPGRADED and l['data'] != '0x' else None)
if l['topics'][0] == '0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0' and len(l['topics']) > 2:
arg = '%s -> %s' % (topic_addr(l['topics'][1]), topic_addr(l['topics'][2]))
adm.append({'event': EVENTS[l['topics'][0]], 'block': b, 'time_ct': ct(ts) if ts else None, 'tx': l['transactionHash'].lower(), 'arg': arg,
'in_creation_tx': bool(creation_tx and l['transactionHash'].lower() == creation_tx)})
E['admin_events'] = adm[:80]
# decode the contract's own events with the verified ABI (static fields only): counts, sums of number fields, top addresses
dec_ev = {}
abi_events = {keccak.topic(abi_sig(f)): f for f in abi if isinstance(f, dict) and f.get('type') == 'event' and f.get('name') and not f.get('anonymous')}
for t, f in abi_events.items():
if t in ADMIN_EVENTS or t in (TRANSFER, APPROVAL): continue
ls = [l for l in L if l['topics'] and l['topics'][0] == t]
if not ls: continue
sums = collections.Counter(); addrs = collections.defaultdict(collections.Counter); samples = []
for l in ls:
ti = 1; dw = words(l['data']); di = 0; row = {}
for inp in f.get('inputs', []):
typ = inp.get('type'); nm = inp.get('name') or typ
if inp.get('indexed'):
raw = l['topics'][ti] if ti < len(l['topics']) else None; ti += 1
else:
if typ in ('string', 'bytes') or typ.endswith(']') or typ.startswith('tuple'):
di += 1; continue
raw = '0x' + dw[di] if di < len(dw) else None; di += 1
if raw is None: continue
if typ == 'address': v = topic_addr(raw); addrs[nm][v] += 1
elif typ.startswith('uint'): v = int(raw, 16); sums[nm] += v
elif typ == 'bool': v = bool(int(raw, 16))
else: v = raw
row[nm] = v
if len(samples) < 5: samples.append({'block': int(l['blockNumber'], 16), 'tx': l['transactionHash'].lower(), 'fields': row})
dec_ev[abi_sig(f)] = {'count': len(ls), 'uint_field_sums_raw': dict(sums), 'top_addresses': {k: v.most_common(8) for k, v in addrs.items()}, 'first_samples': samples}
E['decoded_events'] = dec_ev
ups = [x for x in adm if x['event'] == 'Upgraded(address)']
E['counts'] = {'upgrade_events_total': len(ups), 'upgrades_after_deployment': sum(1 for x in ups if not x['in_creation_tx']) if creation_tx else None,
'upgrades_note': 'An Upgraded event inside the deployment transaction sets the first implementation and is not counted as an upgrade.',
'pause_events': sum(1 for x in adm if x['event'] == 'Paused(address)'), 'ownership_transfers': sum(1 for x in adm if x['event'].startswith('OwnershipTransferred'))}
if creation_tx is None and ups:
E['notes'].append('The deployment transaction is unknown, so upgrades after deployment could not be separated from the first implementation set at deployment.')
# ---- tokens: transfers in/out and approvals to the contract (stable tokens of this chain)
step('tokens')
dec = {}; sym = {v: k for k, v in toks.items()}
for t in tlist:
try: dec[t] = int(r.eth_call(t, '0x313ce567'), 16)
except Exception: dec[t] = 18 if chain == 'bsc' else 6
tin = [l for l in inn if l['topics'][0] == TRANSFER]; apps = [l for l in inn if l['topics'][0] == APPROVAL]
money = {}
for t in tlist:
d = 10 ** dec[t]
i_ = [l for l in tin if l['address'].lower() == t]; o_ = [l for l in out if l['address'].lower() == t]
try: bal = int(r.eth_call(t, '0x70a08231' + addr_topic(A)[2:]), 16) / d
except Exception: bal = None
if not i_ and not o_ and not bal: continue
fin = collections.Counter(); fout = collections.Counter(); cin = collections.Counter(); cout = collections.Counter()
for l in i_: a = topic_addr(l['topics'][1]); fin[a] += int(l['data'], 16) / d; cin[a] += 1
for l in o_: a = topic_addr(l['topics'][2]); fout[a] += int(l['data'], 16) / d; cout[a] += 1
sizes = collections.Counter(round(int(l['data'], 16) / d, 4) for l in o_)
days = collections.Counter()
for l in i_:
b = int(l['blockNumber'], 16); ts = int(l['blockTimestamp'], 16) if l.get('blockTimestamp') else None
if ts: days[ct(ts)[:10]] += 1
money[sym[t]] = {'token': t, 'decimals': dec[t], 'balance_now': bal, 'in_count': len(i_), 'in_total': round(sum(fin.values()), 6), 'payers': len(fin),
'out_count': len(o_), 'out_total': round(sum(fout.values()), 6), 'recipients': len(fout),
'net_in_minus_out': round(sum(fin.values()) - sum(fout.values()), 6),
'top_recipients': [[a, round(v, 4), cout[a]] for a, v in fout.most_common(15)],
'top_payers': [[a, round(v, 4), cin[a]] for a, v in fin.most_common(10)],
'out_sizes': [[k, v] for k, v in sizes.most_common(10)],
'daily_in_counts': sorted(days.items())}
E['money'] = money
# approvals: live allowance and balance per approving wallet
step('approvals')
appr = {}
for t in tlist:
al = [l for l in apps if l['address'].lower() == t]
if not al: continue
owners = sorted({topic_addr(l['topics'][1]) for l in al})[:1500]
d = 10 ** dec[t]
def one(o):
try:
a_ = int(r.eth_call(t, '0xdd62ed3e' + addr_topic(o)[2:] + addr_topic(A)[2:]), 16)
b_ = int(r.eth_call(t, '0x70a08231' + addr_topic(o)[2:]), 16)
return o, a_, b_
except Exception:
return o, None, None
with ThreadPoolExecutor(6) as ex: res = list(ex.map(one, owners))
ok = [x for x in res if x[1] is not None]
live = [x for x in ok if x[1] > 0]
appr[sym[t]] = {'approval_events': len(al), 'approving_wallets': len(owners), 'read': len(ok),
'live_allowances': len(live), 'unlimited': sum(1 for x in ok if x[1] >= 2 ** 255),
'pullable_now': round(sum(min(x[1], x[2]) for x in ok) / d, 6)}
E['approvals'] = appr
# ---- positions probe (contracts that store numbered positions with an owner in the first field)
step('positions')
pos = None
for cnt_fn, get_fn in POSITION_PAIRS:
if cnt_fn in sel_of and get_fn in sel_of and time.time() < T0 + budget * 0.93:
try:
n = int(r.eth_call(A, sel_of[cnt_fn]), 16)
except Exception:
continue
if not (0 < n <= 20000): continue
s = sel_of[get_fn]
def one(i):
try:
v = r.eth_call(A, s + hex(i)[2:].rjust(64, '0'))
return i, addr_of('0x' + words(v)[0]) if v and len(v) >= 66 else None
except Exception:
return i, None
ids = list(range(0, n + 1))
with ThreadPoolExecutor(8) as ex: res = list(ex.map(one, ids))
own = collections.Counter(a for i, a in res if a)
pos = {'count_function': cnt_fn, 'count': n, 'getter': get_fn, 'read': sum(1 for i, a in res if a),
'method': 'eth_call of %s for ids 0..%d; owner = the first returned field (INFERRED layout)' % (get_fn, n),
'owners': len(own), 'top_owners': [[a, c] for a, c in own.most_common(15)]}
break
E['positions'] = pos
# ---- deployment arguments (addresses passed in the creation transaction)
step('deployer')
labels = {}
for fn, a in roles.items(): labels.setdefault(a, []).append(fn)
if creation_tx:
try:
tx = r.call('eth_getTransactionByHash', [creation_tx])
E['creation']['from'] = tx['from'].lower(); labels.setdefault(tx['from'].lower(), []).append('deployer')
init_addrs = []
for w in words(tx['input'][-64 * 24:]):
a = addr_of('0x' + w)
if a and w[:24] == '0' * 24 and a not in init_addrs and a != A and int(a, 16) > 2 ** 100: init_addrs.append(a)
E['creation']['addresses_in_input'] = init_addrs[:12]
except Exception:
pass
# ---- profiles of labelled wallets (roles + deployer + top recipients)
step('wallets')
recv = collections.Counter();
for sy, m in money.items():
for a, v, c in m['top_recipients']: recv[a] += v
cand = list(dict.fromkeys(list(labels.keys()) + [a for a in E.get('creation', {}).get('addresses_in_input', [])] + [a for a, _ in recv.most_common(6)]))
prof = {}
stable = toks.get('USDT') or tlist[0]
for a in cand[:16]:
try:
k = kind_of(r, a)
k['native_balance'] = int(r.call('eth_getBalance', [a, 'latest']), 16) / 1e18
k['nonce'] = int(r.call('eth_getTransactionCount', [a, 'latest']), 16)
k['labels'] = labels.get(a, []) + (['address in deployment input'] if a in E['creation'].get('addresses_in_input', []) else [])
got = {sy: round(sum(v for x, v, c in m['top_recipients'] if x == a), 4) for sy, m in money.items()}
k['received_from_contract'] = {s: v for s, v in got.items() if v}
if pos: k['positions_owned'] = dict(pos['top_owners']).get(a, 0)
prof[a] = k
except Exception:
continue
E['wallets'] = prof
# ---- native coin sent in with the calls that emitted events (msg.value of those transactions; internal transfers out are not traced)
step('native_in')
hs = list(dict.fromkeys(l['transactionHash'] for l in L))
cap = 400; hs_read = hs[-cap:]
def gtx(h):
try:
t = r.call('eth_getTransactionByHash', [h], tries=3)
return {'from': t['from'].lower(), 'to': (t.get('to') or '').lower(), 'value': int(t['value'], 16), 'sel': t['input'][:10]}
except Exception:
return None
if time.time() < T0 + budget * 0.95:
with ThreadPoolExecutor(8) as ex: txs = [x for x in ex.map(gtx, hs_read) if x]
direct = [t for t in txs if t['to'] == A]
selc = collections.Counter(t['sel'] for t in direct)
sndc = collections.Counter(t['from'] for t in direct)
E['txs'] = {'event_txs_total': len(hs), 'read': len(txs), 'read_note': ('the latest %d of them' % cap) if len(hs) > cap else 'all of them',
'direct_calls': len(direct), 'native_sent_in': round(sum(t['value'] for t in direct) / 1e18, 6),
'calls_with_native': sum(1 for t in direct if t['value']),
'by_function': [[selmap.get(k) or k, n] for k, n in selc.most_common(12)], 'top_senders': [[a, n] for a, n in sndc.most_common(10)]}
# ---- the transactions behind admin events (sender + selector)
step('admin_txs')
for x in E['admin_events'][:30]:
try:
t = r.call('eth_getTransactionByHash', [x['tx']], tries=3)
x['from'] = t['from'].lower(); x['selector'] = t['input'][:10]
except Exception:
pass
E['rpc_calls'] = r.calls
finish(E, OUT)
def kind_of(r, a):
code = r.code(a)
if len(code) <= 2: return {'type': 'EOA', 'desc': 'personal wallet (EOA), one key'}
if code.startswith('0xef0100'): return {'type': 'EOA+7702', 'desc': 'personal wallet with EIP-7702 delegated code', 'delegate': '0x' + code[8:48]}
try:
th = int(r.eth_call(a, '0xe75235b8'), 16)
return {'type': 'safe', 'desc': 'Safe multisig, threshold %d' % th, 'threshold': th}
except Exception:
return {'type': 'contract', 'desc': 'contract (%d bytes)' % ((len(code) - 2) // 2)}
def find_creation(r, A, latest):
urls = r.c.get('archive_rpcs') or []
for u in urls:
try:
def has(b):
c = r.call('eth_getCode', [A, hex(b)], tries=3, urls=[u]); return len(c) > 2
if not has(latest): continue
lo, hi = 0, latest
# quick probe: most contracts we see are young, search the recent part first
for back in (200000, 2000000, 20000000):
if latest - back > 0 and not has(latest - back): lo = latest - back; break
while hi - lo > 1:
mid = (lo + hi) // 2
if has(mid): hi = mid
else: lo = mid
return hi
except Exception:
continue
return None
def finish(E, OUT):
E['elapsed_s'] = round(time.time() - T0, 1)
json.dump(E, open(os.path.join(OUT, 'evidence.json'), 'w', encoding='utf8', newline='\n'), indent=1)
import pack
md = pack.build(E)
open(os.path.join(OUT, 'pack.md'), 'w', encoding='utf8', newline='\n').write(md)
json.dump(pack.facts(E), open(os.path.join(OUT, 'facts.json'), 'w', encoding='utf8', newline='\n'), indent=1)
print(json.dumps({'done': True, 'elapsed': E['elapsed_s'], 'pack_chars': len(md)}), flush=True)
if __name__ == '__main__':
main()