diff --git a/chain/pack.py b/chain/pack.py index 8088349..9f8fee7 100644 --- a/chain/pack.py +++ b/chain/pack.py @@ -107,6 +107,26 @@ def build(E): 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 '')) + pr = E.get('payout_relations') + w('\n## Who gets paid when someone buys (precomputed, rubric red flag 4; use these counts, do not recount)') + if not pr: w('- Not computed for this scan.') + elif pr.get('error'): w('- Could not be computed: %s' % pr['error']) + elif not pr.get('payouts_seen'): w('- %s Purchases seen: %s.' % (pr.get('note'), pr.get('purchases_seen'))) + else: + bc = pr.get('by_class') or {} + w('- Payouts seen: %s; purchases seen: %s; payouts matched to a buyer in the same transaction: %s; sponsor links read from the contract: %s' % ( + pr['payouts_seen'], pr['purchases_seen'], pr['payouts_with_a_buyer_in_tx'], pr['sponsor_links_read'])) + names = {'operator': 'to wallets the contract names (operator, company, prize or fee wallets)', 'referral_line': "to the buyer's sponsor or a sponsor above them (the buyer's referral line)", + 'earlier_buyer': "to an EARLIER buyer or position holder who is NOT in the buyer's referral line (paid from a later buyer's payment)", + 'earlier_buyer_line_unknown': 'to an earlier buyer, but the contract records no sponsor links, so the referral line cannot be read', + 'buyer_self': 'back to the buyer', 'no_purchase_in_tx': 'in a transaction with no purchase (claims, withdrawals, keeper calls)', 'other': 'to a wallet with no earlier purchase seen'} + for k in ['operator', 'referral_line', 'earlier_buyer', 'earlier_buyer_line_unknown', 'buyer_self', 'no_purchase_in_tx', 'other']: + if bc.get(k): w(' - %s payouts %s (%s distinct recipients)' % (bc[k], names[k], (pr.get('distinct_recipients_by_class') or {}).get(k))) + w("- Earlier buyers paid from later buyers' payments: %s" % pr.get('earlier_buyers_paid_by_later_buyers')) + for k, xs in (pr.get('examples') or {}).items(): + if k in ('earlier_buyer', 'earlier_buyer_line_unknown', 'referral_line'): + for x in xs[:3]: w(' - example %s: tx %s block %s paid %s (first bought at block %s), buyer %s' % (k, x['tx'], x['block'], x['to'], x.get('recipient_first_bought_block'), x.get('buyer'))) + w('- Method: %s' % pr.get('method')) w('\n## Notes') for n in E.get('notes') or []: w('- ' + n) return '\n'.join(o) @@ -150,6 +170,15 @@ def facts(E): 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) + pr = E.get('payout_relations') or {} + if pr.get('payouts_seen'): + bc = pr.get('by_class') or {} + if bc.get('earlier_buyer'): + x = (pr.get('examples') or {}).get('earlier_buyer', [{}])[0] + add('VERIFIED', "%d payouts went to earlier buyers or position holders outside the buyer's referral line, paid inside a later buyer's purchase (example tx %s)." % (bc['earlier_buyer'], x.get('tx')), ex + '/tx/' + x['tx'] if x.get('tx') else None) + else: + add('VERIFIED', "Of %d payouts read, %d went to wallets the contract names and %d to the buyer's referral line; none went to an earlier buyer outside that line.%s" % ( + pr['payouts_seen'], bc.get('operator', 0), bc.get('referral_line', 0), (' %d went to earlier buyers whose referral line cannot be read.' % bc['earlier_buyer_line_unknown']) if bc.get('earlier_buyer_line_unknown') else ''), None) 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) diff --git a/chain/payouts.py b/chain/payouts.py new file mode 100644 index 0000000..c43c90a --- /dev/null +++ b/chain/payouts.py @@ -0,0 +1,142 @@ +"""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.', + } diff --git a/chain/rubric.md b/chain/rubric.md index 3c60c41..d5fb9b7 100644 --- a/chain/rubric.md +++ b/chain/rubric.md @@ -1,4 +1,4 @@ -# Contract risk scoring rubric (draft v1, from the 3xSusu review 2026-11-16) +# Contract risk scoring rubric (draft v1.1, 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), @@ -31,7 +31,11 @@ Lowers risk: ## 3. Economic design (weight 20) Raises risk: -- Returns funded only by later entrants (matrix/cycler/"3x"): payouts trigger only on new entries +- Returns funded by later entrants: an earlier buyer or position holder is paid from a later buyer's payment + (matrix, cycler, pot, "3x", "previous N spots" paid from new entries, refunds funded by new entries) (critical, red flag 4) +- Commission to the buyer's sponsor or the sponsors above them (the buyer's referral line) on a sale where the buyer + receives a delivered product (ad credits, views, a report): not red flag 4. Disclose it ("X% of each sale goes to the + buyer's sponsors") and score it on its merits: share of each sale, whether the product is really delivered, who keeps the rest - 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 @@ -65,8 +69,15 @@ Lowers 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 +4. Returns funded by later entrants: an earlier buyer or position holder receives payouts funded by later buyers' payments + (matrix, cycler, pot, "previous N spots" paid from new entries, refunds funded by new entries). A commission paid to the + buyer's referral line on a sale of a delivered product is not this flag; it is disclosed under economic design and + disclosure. A contract that does both (sponsor commissions AND payouts to earlier buyers) gets the flag. Applied the same + way to every contract, including our own. 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). + +## Changelog +- 2026-11-16: red flag 4 now applies only to payouts to earlier buyers funded by later buyers; sponsor commissions on a delivered product are disclosed, not auto-flagged. diff --git a/chain/scan.py b/chain/scan.py index f8393ec..f38e512 100644 --- a/chain/scan.py +++ b/chain/scan.py @@ -368,7 +368,7 @@ def main(): '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 = {} + dec_ev = {}; dec_rows = {} 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 @@ -392,6 +392,7 @@ def main(): else: v = raw row[nm] = v if len(samples) < 5: samples.append({'block': int(l['blockNumber'], 16), 'tx': l['transactionHash'].lower(), 'fields': row}) + dec_rows.setdefault(abi_sig(f), []).append((int(l['blockNumber'], 16), int(l['logIndex'], 16), l['transactionHash'].lower(), 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)'] @@ -497,6 +498,15 @@ def main(): except Exception: pass + # ---- who gets paid when someone buys (rubric red flag 4: earlier buyers paid from later buyers' payments) + step('payouts') + try: + import payouts + tl = lambda l, i: (int(l['blockNumber'], 16), int(l['logIndex'], 16), l['transactionHash'].lower(), topic_addr(l['topics'][i]), int(l['data'], 16) if l['data'] not in ('0x', '') else 0) + E['payout_relations'] = payouts.analyse(E, dec_rows, [tl(l, 1) for l in tin], [tl(l, 2) for l in out]) + except Exception as e: + E['payout_relations'] = {'error': str(e)[:200]} + # ---- profiles of labelled wallets (roles + deployer + top recipients) step('wallets') recv = collections.Counter(); diff --git a/public/404.html b/public/404.html index 822ed77..5b8d1a2 100644 --- a/public/404.html +++ b/public/404.html @@ -12,6 +12,6 @@