"""Who gets paid when someone buys: a deterministic read of the contract's own decoded events and token transfers. Rubric red flag 4 (2026-11-16 wording) forces High only when an EARLIER buyer or position holder is paid from a LATER buyer's payment (matrix, cycler, pot, "previous N spots", refunds funded by new entries). A commission to the buyer's sponsor or the sponsors above them (the buyer's referral line) on a sale is not that flag: it is disclosed and scored. For every payout we can see (a decoded event with a recipient and an amount, or a token Transfer out of the contract) we find the buyer of the same transaction (a purchase-like event, or the wallet that paid tokens in) and classify the recipient: operator a wallet the contract names (role getters, zero-argument address values, deployment input, deployer, the contract itself) referral_line the buyer's sponsor or a sponsor above them, from the contract's own sponsor records earlier_buyer a wallet that bought or held a position BEFORE this purchase and is NOT in the buyer's referral line earlier_buyer_line_unknown an earlier buyer, but the contract records no sponsor links we can read other none of the above (no earlier purchase seen) Field roles come from verified-ABI field names (buyer/owner/account, to/recipient, sponsor/referrer); the money moves and the ordering are on-chain records. Every count printed comes from here, never from the model. """ import re, collections BUYER = re.compile(r'^(buyer|owner|account|member|user|payer|purchaser|holder|depositor|player|participant)(id)?$', re.I) RECIP = re.compile(r'^(to|recipient|receiver|payee|beneficiary|earner)(id)?$', re.I) BUY_AMT = re.compile(r'(wei|paid|value|price|cents|usd|cost)', re.I) BUY_EVENT = re.compile(r'(buy|bought|purchase|deposit|join|entry|enter|order)', re.I) SPONSOR = re.compile(r'^(sponsor|referrer|referer|upline|inviter|parent)(id)?$', re.I) AMOUNT = re.compile(r'(amount|value|wei|paid|price|cents|cost|usd)', re.I) ZERO = '0x' + '0' * 40 def _is_addr(v): return isinstance(v, str) and v.startswith('0x') and len(v) == 42 def analyse(E, rows, token_in, token_out): """rows: {event_sig: [(block, logIndex, tx, fields)]}; token_in/out: [(block, logIndex, tx, wallet, amount)]. Returns a JSON-able summary (counts, examples, method) or None when the contract shows no payouts at all.""" A = E['address'] insiders = {A, ZERO} for a in (E.get('roles') or {}).values(): if _is_addr(a): insiders.add(a.lower()) for v in (E.get('values') or {}).values(): if _is_addr(v): insiders.add(v.lower()) for a in (E.get('controllers') or {}): insiders.add(a.lower()) c = E.get('creation') or {} for a in c.get('addresses_in_input') or []: insiders.add(a.lower()) if c.get('from'): insiders.add(c['from'].lower()) # pass 1: id -> address, member -> sponsor (address or id keys), from any event that carries the pair id2addr = {}; sponsor = {} for sig, rs in rows.items(): for b, li, tx, f in rs: idf = [k for k in f if k.lower() == 'id' and isinstance(f[k], int)] adf = [k for k in f if BUYER.match(k) and _is_addr(f[k])] # registration-style events only (no money field), so spot or order ids never mix with member ids if idf and adf and not any(AMOUNT.search(k) for k in f): id2addr[f[idf[0]]] = f[adf[0]] def key(k, v): if _is_addr(v): return v.lower() if isinstance(v, int): return id2addr.get(v, 'id:%d' % v) return None for sig, rs in rows.items(): for b, li, tx, f in rs: sp = [k for k in f if SPONSOR.match(k)] if not sp: continue me = [k for k in f if BUYER.match(k) and _is_addr(f[k])] or [k for k in f if k.lower() == 'id' and isinstance(f[k], int)] if not me: continue m, s = key(me[0], f[me[0]]), key(sp[0], f[sp[0]]) if m and s and s not in (ZERO, 'id:0') and s != m: sponsor.setdefault(m, s) # pass 2: purchases (buyer + an amount field, not a payout) and payouts (recipient + amount) buys = []; pays = [] for sig, rs in rows.items(): for b, li, tx, f in rs: rk = [k for k in f if RECIP.match(k)] am = [k for k in f if AMOUNT.search(k) and isinstance(f[k], int)] bk = [k for k in f if BUYER.match(k) and not RECIP.match(k)] if rk and am: r = key(rk[0], f[rk[0]]) amt = next((f[k] for k in am if re.search('amount|wei|paid|value', k, re.I)), f[am[0]]) if r: pays.append({'b': b, 'li': li, 'tx': tx, 'to': r, 'amount': amt, 'event': sig.split('(')[0], 'buyer_field': key(bk[0], f[bk[0]]) if bk else None}) elif bk and am and (any(BUY_AMT.search(k) for k in am) or BUY_EVENT.search(sig.split('(')[0])): pref = sorted(bk, key=lambda k: ['owner', 'buyer', 'account', 'member', 'user', 'holder', 'player', 'participant', 'depositor', 'purchaser', 'payer'].index(re.sub('id$', '', k.lower())) if re.sub('id$', '', k.lower()) in ['owner', 'buyer', 'account', 'member', 'user', 'holder', 'player', 'participant', 'depositor', 'purchaser', 'payer'] else 99) who = [key(k, f[k]) for k in pref] buys.append({'b': b, 'li': li, 'tx': tx, 'buyer': who[0], 'also': [w for w in who[1:] if w], 'event': sig.split('(')[0]}) sp = [k for k in f if SPONSOR.match(k)] if sp and who[0]: s = key(sp[0], f[sp[0]]) if s and s not in (ZERO, 'id:0') and s != who[0]: sponsor.setdefault(who[0], s) for b, li, tx, w, amt in token_in: if w not in insiders: buys.append({'b': b, 'li': li, 'tx': tx, 'buyer': w, 'also': [], 'event': 'token transfer in'}) for b, li, tx, w, amt in token_out: pays.append({'b': b, 'li': li, 'tx': tx, 'to': w, 'amount': amt, 'event': 'token transfer out', 'buyer_field': None}) if not pays: return {'payouts_seen': 0, 'purchases_seen': len({x['tx'] for x in buys}), 'note': 'No payouts by the contract were seen in the events and token transfers read.'} buyer_of_tx = {} for x in sorted(buys, key=lambda x: (x['b'], x['li'])): buyer_of_tx.setdefault(x['tx'], x) first_buy = {} for x in sorted(buys, key=lambda x: (x['b'], x['li'])): for w in [x['buyer']] + x['also']: if w and w not in insiders: first_buy.setdefault(w, (x['b'], x['li'], x['tx'])) def upline(w, n=40): out = []; seen = {w} while w in sponsor and len(out) < n: w = sponsor[w] if w in seen: break seen.add(w); out.append(w) return out cls = collections.Counter(); amt = collections.Counter(); ex = collections.defaultdict(list); tx_with_buyer = 0 recips = collections.defaultdict(collections.Counter) for p in pays: bx = buyer_of_tx.get(p['tx']) buyer = bx['buyer'] if bx else p['buyer_field'] if p['to'] in insiders: k = 'operator' elif not buyer: k = 'no_purchase_in_tx' elif p['to'] == buyer or (bx and p['to'] in bx['also']): k = 'buyer_self' elif p['to'] in upline(buyer): k = 'referral_line' elif p['to'] in first_buy and first_buy[p['to']][:2] < ((bx['b'], bx['li']) if bx else (p['b'], p['li'])) and first_buy[p['to']][2] != p['tx']: k = 'earlier_buyer' if sponsor else 'earlier_buyer_line_unknown' else: k = 'other' if buyer: tx_with_buyer += 1 cls[k] += 1; amt[k] += p['amount'] or 0; recips[k][p['to']] += 1 if len(ex[k]) < 4 and p['tx'] not in [e['tx'] for e in ex[k]]: ex[k].append({'tx': p['tx'], 'block': p['b'], 'to': p['to'], 'buyer': buyer, 'event': p['event'], 'recipient_first_bought_block': first_buy.get(p['to'], (None,))[0]}) return { 'payouts_seen': len(pays), 'purchases_seen': len({x['tx'] for x in buys}), 'payouts_with_a_buyer_in_tx': tx_with_buyer, 'sponsor_links_read': len(sponsor), 'operator_wallets': sorted(insiders - {ZERO, A})[:20], 'by_class': dict(cls), 'amount_raw_by_class': {k: str(v) for k, v in amt.items()}, 'distinct_recipients_by_class': {k: len(v) for k, v in recips.items()}, 'examples': dict(ex), 'earlier_buyers_paid_by_later_buyers': cls['earlier_buyer'], 'readable': bool(sponsor) or cls['earlier_buyer_line_unknown'] == 0, 'method': 'Each payout (decoded event with a recipient and an amount, or a token transfer out) is matched to the buyer of the same ' 'transaction. Recipient classes: operator = wallets the contract names (roles, address values, deployment input, deployer); ' 'referral_line = the buyer\'s sponsor or a sponsor above them in the contract\'s own sponsor records; earlier_buyer = a wallet ' 'that bought or held a position before this purchase and is not in the buyer\'s referral line; earlier_buyer_line_unknown = ' 'an earlier buyer when the contract records no sponsor links; other = no earlier purchase seen. Field roles come from verified ' 'ABI field names; amounts and ordering are on-chain records.', }