Multi-Asset Investing Token — Crypto, AI Stocks & Precious Metals on Solana

Portfolio

Exposures
LEVERAGE ⓘ
Loading…
LIQUIDITY
Loading…
FEES ⓘ
0.5% P.Y.

Simulation includes trading fees and interest. Does not include slippage.

Market price: loading… / ALEF → Buy: Raydium Biconomy
ALEF Portfolio holds three equal themes: Crypto (≈33%) — BTC, ETH, BNB, TRX; AI & Technology (≈33%) — QQQ, Magnificent Seven stocks; Precious Metals (≈33%) — Gold, Silver, Platinum. Target leverage 1–2×, but leverage is optional: pair ALEF with USDT or USDC to reduce effective exposure to any level. Provide ALEF/USDC liquidity to harvest volatility through automatic rebalancing.

About

How to Make the Most Money — J.ℵ. Bettencourt

NEW BOOK

How to Make the Most Money

J.ℵ. Bettencourt  ·  Philosopher and Scientist

Three chapters: how I invest, how you can build dynastic wealth, and how we as a civilisation can make the most of what we have. Cryptocurrency, leverage, spelling reform, and AI — all under one roof.

0.1 g gold
per hour  ·  paid in crypto
Browser-only · No download
Renew any time

Read/Listen → Free Summary ▶

State of the Art Security Features

Multiple independent layers of protection for investor assets.

Registered 🇵🇦

Alef Financial is incorporated in Panama.

View Registration Documents
Address Control Verification 🇨🇭

Address control independently verified by Alpine Audit (Zürich, Switzerland).

View Report Verify Signature
Audited

Anyone can run a full financial audit in real time using our open-source programs.

View Live Audit
Multi-Signature Wallets

About 95%(We will put our JustLend position in a Multisig when JustLend can integrate them) of funds are in multisignature wallets. No individual administrator has access to the funds. Any movement requires consensus.

24/7 AI-Powered Risk Monitoring

Continuous automated surveillance of on-chain signals and news for early signs of stress — exploits, unusual outflows, or regulatory action.

Multiple Blockchains and Counterparties

Assets are distributed between several blockchains and counterparties. No single failure can compromise the entire portfolio.

Talk is Cheap, Show Me the Code

The Alef portfolio is 100% on-chain and auditable by anyone in real time. Reserve addresses across all active chains are published below. Proof of ownership of any address can be requested using the form at the bottom of this section. You can give our auditing open-source programs to Super-Intelligence systems to verify it is safe and effective yourself.

How to read these addresses: Portfolio assets are deployed into on-chain lending protocols rather than held as raw tokens. On Ethereum, assets are supplied to Aave, which issues position NFTs to the depositor's wallet as proof of entitlement — a standard balance check will show these NFTs and a small gas reserve, not the full underlying value. On BNB Chain, assets are supplied to Venus. On Tron, assets are supplied to JustLend, which issues fungible jTokens (TRC-20 receipt tokens) in return — the underlying value is held in the protocol, not visible as a raw token balance. In all cases, the actual position value must be read from the relevant lending protocol's interface rather than a block explorer balance view.

Full Financial Audit (State)

Reconstructs the full mark-to-market value of all assets and liabilities across every chain — Aave positions on Ethereum, Venus on BNB Chain, JustLend jTokens on Tron, and Solana holdings — using live prices. Requires only a free API key; no trust in the operator needed.

Run this open-source program to audit the current portfolio state:

# ALEF — current state and reverse chronological cash-flow check
# As-of-now is an anchor, not a balancing entry. Historical values are NOT historical NAV.
# A positive forward flow adds funds; backward balance subtracts that flow.
# Optional: define ALEF_CURRENT_STATE in Price_update's previous cell (any current
# portfolio table or dict with verified positions/liabilities/NAV). If absent, the
# code independently shows current direct custody balances, NOT a complete NAV.
# Historical prices are estimates except observed cash/execution amounts.
import os, sys, json, time, math, hashlib, requests, bisect
import pandas as pd
import yfinance as yf
from datetime import datetime, timezone, timedelta
from decimal import Decimal
from IPython.display import display, HTML

pd.set_option("display.max_rows", 500)
pd.set_option("display.float_format", "{:,.2f}".format)
pd.set_option("display.max_colwidth", 60)

print("NOTE: This audit queries multiple blockchains and may take up to an hour to complete in extreme cases. Please be patient.")

# ── Addresses ──────────────────────────────────────────────────────────────────
EVM_ADDR       = "0xfB6b384a64BA407Ee964DF70bf48A6Ef993B1Fd4"
SOL_WALLET     = "9W22wgpcSsbcAjoGvGQfcvVUns5q7LMuWNPCnM4eVXse"
SOL_WALLET_2   = "9JRZdE4rcSUQRDRUTqNrqsFtxm7caT4GfyiNxFJqBHUe"
TRON_ADDR      = "TFMDSKrH2FJx3pdGACb5oHoKPJRzaH8dKv"
BITCOIN_ADDR   = "bc1qmqcggscd9mfddzywukrxksrrfamx5mevr5jr40llmf6ggtdmwyeqcaekt4"
TON_ADDR       = "EQDJ8vy2R0EdEskou7Awf8PX2GXU9j0dLAPrJlNHRrJdlsXy"
TON_ADDR_RAW   = "0:c9f2fcb647411d12c928bbb0307fc3d7d865d4f63d1d2c03eb26534746b25d96"
ALEF_MINT      = "FBHd9upXFkeWSwe9qEdcgRLa4Y6uzsLCSawrpfPkQZGg"
ALEF_MINT_OLD  = "9B3rXYVdL2iUxGnY54TKhR9NroqGB1RBAivVQWb26Zqt"
SOLANA_USDC    = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
RAYDIUM_CLMM   = "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"

# xStock token symbol → yfinance underlying ticker for price lookup
_XSTOCK_TICKERS = {
    "AAPLx": "AAPL",  "AMZNx": "AMZN",  "MSFTx": "MSFT",  "NVDAx": "NVDA",
    "TSLAx": "TSLA",  "GOOGLx": "GOOGL", "METAx": "META",  "COINx": "COIN",
    "SPYx":  "SPY",   "QQQx":  "QQQ",   "SLVx":  "SLV",   "TQQQx": "TQQQ",
}

_XSTOCK_TICKERS.update({"NVDAB":"NVDA","TSLAB":"TSLA","METAB":"META","GOOGLB":"GOOGL","PPLTX":"PPLT","PPLTx":"PPLT"})
BSC_REGISTRY = {"0x55d398326f99059ff775485246999027b3197955":"USDT", "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d":"USDC", "0x02fca66c1d1afb4e2a7884261eb00f63598a7436":"NVDAB", "0x5b1910eaad6450e50f816082aa078c41f10c292f":"TSLAB", "0x7425889fe94f9d693e8daefe88bcced6acfef4c0":"METAB", "0x3f53de71c126bdabae20f9cd64848d317f6c3238":"GOOGLB"}
BSC_REGISTRY["0x8b872732b07be325a8803cdb480d9d20b6f8d11b"] = "SLVon"
_XSTOCK_TICKERS["SLVon"] = "SLV"  # underlying-price proxy; not execution proceeds
PPLT_MINT = "Xst6eFD4YT6sz9RLMysN9SyvaZWtraSdVJQGu5ZkAme"
QUARANTINE = []
ANNUAL_FEE_RATE = 0.005        # 0.5 % / year, accrued on NAV; settled at mint/burn
TRADING_FEE_RATE = 0.005       # 0.5 % of portfolio conversion notional (excluding free pairs)
# Optional upstream actual NAV history: pandas Series, UTC timestamps, USD NAV.
# If absent, live-mint total supply × historical ALEF market quote is a NAV proxy.
RAW_ALEF_SUPPLY_EVENTS = []
NOW             = datetime.now(timezone.utc)
AUDIT_WARNINGS = []
RAYDIUM_LP_REFS = set()
FOUNDER_ADDRESSES = set()  # populate with verified personal addresses
VERIFIED_FOUNDER_REFS = set()  # full hashes, independently classified
VERIFIED_INTERNAL_REFS = set()  # full hashes, independently classified

# ALEF amounts to exclude (test transactions — exact float qty)
EXCLUDE_ALEF_AMOUNTS = {
    100_000_000.0,  # 2026-06-21 joke mint+burn
      942_645.0,    # 2026-06-18 large test mint
      916_000.0,    # 2026-07-01 large test burns ×4
}

# ── Live Raydium ALEF/USDC market price; never manually entered ───────────────
ALEF_POOL_ID = "Gg6WkQW1h8CWTcmdMueEL9Aw3S3XbXqknTpn3RZsaf91"
ALEF_PRICE_USD = None
ALEF_PRICE_SOURCE = "Unavailable"

# Sep 12-14 2026: "conversion mints" re-issued old investors in the new ALEF_MINT
# address — no matching on-chain inflows (capital was in old pre-migration wallets).
# Start after these so net flows ≈ 0. Set to "" to include all history.
AUDIT_START_DATE = "2026-09-17 19:08:04+00:00"
# ──────────────────────────────────────────────────────────────────────────────

ETHERSCAN_KEY = os.getenv("ETHERSCAN_API_KEY") or input("Etherscan API key (free at etherscan.io/apis): ").strip()
HELIUS_KEY    = os.getenv("HELIUS_API_KEY")    or input("Helius API key (free at dev.helius.xyz): ").strip()
HELIUS_RPC    = f"https://mainnet.helius-rpc.com/?api-key={HELIUS_KEY}"

# Known DeFi protocol addresses — transfers to/from these are INTERNAL
PROTOCOL_ADDRS = {a.lower() for a in [
    # Euler BNB vaults
    "0x8f68128438c1101550bf478bbe8f8c80749eb794",
    "0xf4940cde23c164f8ca8d536f3567337349b3208f",
    # Euler EVC / protocol
    "0x0C9a3dd6b8F28529d72d7f9cE918D493519EE383",
    # Aave v3 BNB pool
    "0x6807dc923806fE8Fd134338EABCA509979a7e0cB",
    # Venus unitroller
    "0xfD36E2c2a6789Db23113685031d7F16329158384",
    # Fluid vault resolver
    "0xA5C3E16523eeeDDcC34706b0E6bE88b4c6EA95cC",
    # zero / burn
    "0x0000000000000000000000000000000000000000",
    "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
]}

# Confirmed protocol custody endpoints: Aave V4 docs, Fluid technical docs,
# JustLend V2 deployment docs. Keep exact chain + address; not arbitrary senders.
LENDING_ENDPOINTS = {
    "ethereum": {"0xcca852bc40e560adc3b1cc58ca5b55638ce826c9":"Aave V4 Core Hub",
                 "0x06002e9c4412cb7814a791ea3666d905871e536a":"Aave V4 Plus Hub",
                 "0x943827dca022d0f354a8a8c332da1e5eb9f9f931":"Aave V4 Prime Hub",
                 "0xbbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb":"Morpho Blue",
                 "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2":"Aave V3 Pool"},
    "bsc": {"0x52aa899454998be5b000ad077a46bbe360f4e497":"Fluid Liquidity"},
    "tron": {"TDH4dhmVQQNc1ZNudJwWzBcs2h6ahhWrpp":"JustLend V2 Moolah"},
}
ETH_REGISTRY={
    "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC",
    "0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT",
    "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599":"WBTC",
    "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2":"WETH",
    "0x45804880de22913dafe09f4980848ece6ecbaf78":"PAXG",
    "0x68749665ff8d2d112fa859aa293f07a622782f38":"XAUt",
    "0x6c3ea9036406852006290770bedfcaba0e23a0e8":"PYUSD",
    "0xa45cd7ac9865b9539166ebaf2abc362df4736580":"TQQQon",
    "0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf":"CBBTC",
}
TRON_USDT="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
# Additional confirmed assets/addresses may be added here, never by guessing symbol.
# Pool-wide swap cash delta is the original requested market-flow convention;
# this fraction is an explicit assumption, not an independently verified LP share.
POOL_FLOW_SHARE=1.0
DUST_LIMIT_USD=0.001
# True for the original issuance-offset flow check: mint = negative, burn = positive.
INCLUDE_ISSUANCE_OFFSET=True

# ── Base-58 helpers (no external dep) ─────────────────────────────────────────
_B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
_B58_MAP = {c: i for i, c in enumerate(_B58_ALPHABET)}

def _b58decode(s):
    n = 0
    for ch in str(s):
        n = n * 58 + _B58_MAP[ch]
    body = n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b""
    zeros = len(str(s)) - len(str(s).lstrip("1"))
    return b"\x00" * zeros + body

def _b58encode(b):
    b = bytes(b)
    zeros = len(b) - len(b.lstrip(b"\x00"))
    n = int.from_bytes(b, "big")
    chars = []
    while n:
        n, r = divmod(n, 58)
        chars.append(_B58_ALPHABET[r])
    return "1" * zeros + ("".join(reversed(chars)) if chars else "")

def _ed25519_on_curve(pk32):
    if len(pk32) != 32:
        return False
    p = 2**255 - 19
    d = (-121665 * pow(121666, p - 2, p)) % p
    y = int.from_bytes(pk32, "little") & ((1 << 255) - 1)
    if y >= p:
        return False
    y2 = (y * y) % p
    u = (y2 - 1) % p
    v = (d * y2 + 1) % p
    x2 = (u * pow(v, p - 2, p)) % p
    x = pow(x2, (p + 3) // 8, p)
    if (x * x - x2) % p != 0:
        x = (x * pow(2, (p - 1) // 4, p)) % p
    return (x * x - x2) % p == 0

def _find_pda(seeds, program_id):
    program = _b58decode(program_id)
    for bump in range(255, -1, -1):
        h = hashlib.sha256()
        for seed in seeds:
            h.update(seed)
        h.update(bytes([bump]))
        h.update(program)
        h.update(b"ProgramDerivedAddress")
        digest = h.digest()
        if not _ed25519_on_curve(digest):
            return _b58encode(digest), bump
    raise RuntimeError("PDA not found")

# ── HTTP helpers ───────────────────────────────────────────────────────────────
_sess = requests.Session()
_sess.headers["User-Agent"] = "ALEF-audit/1.0"

def _get(url, **kw):
    r = _sess.get(url, timeout=25, **kw)
    r.raise_for_status()
    return r.json()

def _sol_rpc(method, params, rpc=None):
    url = rpc or HELIUS_RPC
    for attempt in range(3):
        try:
            r = _sess.post(url,
                json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params},
                timeout=30, headers={"Content-Type": "application/json"})
            if r.status_code == 429:
                time.sleep(1 + attempt * 2)
                continue
            r.raise_for_status()
            d = r.json()
            if "error" in d:
                raise RuntimeError(d["error"])
            return d.get("result")
        except Exception as e:
            if attempt == 2:
                raise
            time.sleep(0.5 * (2 ** attempt))

# ── Current prices ─────────────────────────────────────────────────────────────

# Pricing configuration: underlying units per token unit, only if verified.
# PPLTX raw token quantities may differ from displayed share-equivalent quantities.
# Add verified timestamp-effective multipliers here, e.g. {"PPLTX": [("YYYY-MM-DD", factor)]}.
TOKEN_MULTIPLIERS = {}  # optional verified manual overrides, timestamp -> factor
# xStocks: raw SPL/jetton units need scaling; EVM balanceOf already returns
# scaled shares. PPLT's 10:1 split took effect 2026-05-18 (SEC 10-Q).
_XSTOCK_RAW_SYMBOLS = {"PPLTX":"PPLTx", **{k.upper():k for k in _XSTOCK_TICKERS if k.endswith("x") and k.upper()!="PPLTX"}}
_XSTOCK_NETWORKS = {"solana":"Solana", "ton":"Ton"}
_XSTOCK_HISTORY_CACHE = {}
_XSTOCK_CURRENT_CACHE = {}
_MULTIPLIER_WARNED = set()
_XSTOCK_API = "https://api.xstocks.fi/api/v2/public/assets"

def _mult_factor(v):
    try:
        v=float(v)
        return v if math.isfinite(v) and v>0 else None
    except (TypeError,ValueError,OverflowError): return None

def _mult_timestamp(v):
    if v is None or isinstance(v,bool): return None
    try:
        n=float(v)
        if not math.isfinite(n):return None
        return n/1000 if abs(n)>1e12 else n
    except (TypeError,ValueError,OverflowError):
        try:return pd.to_datetime(v,utc=True).timestamp()
        except Exception:return None

def _mult_warn(key,message):
    if key not in _MULTIPLIER_WARNED:
        _MULTIPLIER_WARNED.add(key); AUDIT_WARNINGS.append(message)

def _xstock_api_get(symbol,chain,history=False,page=0):
    path=f"{_XSTOCK_API}/{symbol}/multiplier" + ("/history" if history else "")
    params={"network":_XSTOCK_NETWORKS[chain]}
    if history:params.update(page=page,pageSize=100)
    try:return _get(path,params=params)
    except requests.HTTPError as e:
        # Some deployments accept lowercase network names instead.
        if e.response is None or e.response.status_code not in (400,404,422):raise
        params["network"]=chain
        return _get(path,params=params)

def _xstock_history(symbol,chain):
    key=(symbol,chain)
    if key in _XSTOCK_HISTORY_CACHE:return _XSTOCK_HISTORY_CACHE[key]
    points=[]; complete=False
    try:
        for page in range(100):
            d=_xstock_api_get(symbol,chain,True,page)
            nodes=d.get("nodes")
            if not isinstance(nodes,list):raise ValueError("missing history nodes")
            for row in nodes:
                # Only timestamp-effective entries; never use a future announced multiplier.
                ts=next((x for x in (_mult_timestamp(row.get(k)) for k in ("activationDateTime","activationTimestamp","effectiveAt","effectiveTimestamp","activatedAt","activationTime","effectiveDateTime","timestamp")) if x is not None),None)
                factor=next((x for x in (_mult_factor(row.get(k)) for k in ("newMultiplier","multiplier","value","currentMultiplier")) if x is not None),None)
                if ts is None or factor is None:raise ValueError("unrecognized multiplier history entry")
                points.append((ts,factor))
            if not d.get("page",{}).get("hasNextPage",False):complete=True;break
        if not complete:raise ValueError("multiplier pagination incomplete")
        points=sorted(set(points))
    except Exception as e:
        points=[];complete=False
        _mult_warn((key,"history"),f"{symbol}/{chain} multiplier history unavailable: {type(e).__name__}")
    _XSTOCK_HISTORY_CACHE[key]=(points,complete)
    return points,complete

def _xstock_current(symbol,chain):
    key=(symbol,chain)
    if key in _XSTOCK_CURRENT_CACHE:return _XSTOCK_CURRENT_CACHE[key]
    ts=NOW.timestamp(); result=(None,"unavailable")
    if chain=="solana" and symbol.upper()=="PPLTX":
        # Independent on-chain check of the Token-2022 scaled UI extension.
        try:
            d=_sol_rpc("getAccountInfo",[PPLT_MINT,{"encoding":"jsonParsed","commitment":"finalized"}])
            info=d["value"]["data"]["parsed"]["info"]
            for ext in info.get("extensions",[]):
                if str(ext.get("extension","")).lower().replace("_","") not in ("scaleduiamount","scaleduiamountconfig"):continue
                state=ext["state"]
                f=_mult_factor(state.get("multiplier")); new=_mult_factor(state.get("newMultiplier"))
                activation=_mult_timestamp(state.get("newMultiplierEffectiveTimestamp"))
                if new is not None and activation is not None and activation<=ts:f=new
                if f is not None:result=(f,"Solana Token-2022 mint extension");break
        except Exception as e:_mult_warn((key,"mint"),f"{symbol} mint multiplier unavailable: {type(e).__name__}")
    if result[0] is None:
        try:
            d=_xstock_api_get(symbol,chain)
            f=_mult_factor(d.get("currentMultiplier")); new=_mult_factor(d.get("newMultiplier"))
            activation=_mult_timestamp(d.get("activationDateTime"))
            if new is not None and activation is not None and activation<=ts:f=new
            if f is None:raise ValueError("invalid current multiplier")
            result=(f,"xStocks issuer current multiplier")
        except Exception as e:_mult_warn((key,"current"),f"{symbol}/{chain} current multiplier unavailable: {type(e).__name__}")
    _XSTOCK_CURRENT_CACHE[key]=result
    return result

def xstock_factor(asset,chain,ts,quantity_basis="raw",current=False):
    if quantity_basis=="scaled" or chain not in _XSTOCK_NETWORKS or asset.upper() not in _XSTOCK_RAW_SYMBOLS:
        return 1.0,"share units / no xStocks scaling"
    if quantity_basis!="raw":return None,"quantity basis unknown"
    symbol=_XSTOCK_RAW_SYMBOLS[asset.upper()]
    overrides=[(t,f) for d,v in TOKEN_MULTIPLIERS.get(asset.upper(),[]) if (t:=_mult_timestamp(d)) is not None and t<=ts and (f:=_mult_factor(v)) is not None]
    if overrides:return max(overrides)[1],"verified manual multiplier"
    if current:
        f,source=_xstock_current(symbol,chain)
        if f is not None:return f,source
    points,complete=_xstock_history(symbol,chain)
    i=bisect.bisect_right(points,(ts,float("inf")))-1
    if complete and i>=0:
        # For current balances, prefer current mint/API. History is a labelled fallback.
        return points[i][1],"xStocks issuer executed multiplier history"
    if complete and points and ts<points[0][0]:
        return 1.0,"xStocks initial 1:1 before first recorded adjustment"
    if asset.upper()=="PPLTX" and ts>=pd.Timestamp("2026-05-18",tz="UTC").timestamp():
        _mult_warn((symbol,chain,"split"),"PPLTx: using documented 10:1 PPLT split fallback; issuer multiplier not verified")
        return 10.0,"PPLT 10:1 split fallback (issuer multiplier unverified)"
    if ALLOW_UNVERIFIED_SHARE_PROXY:
        _mult_warn((symbol,chain,"proxy"),f"{symbol}/{chain}: multiplier unverified; 1:1 estimate")
        return 1.0,"ASSUMED 1:1, multiplier unavailable"
    return None,"multiplier unavailable"

# If true, show a clearly labelled one-share proxy when multiplier is unavailable.
# Such amounts are estimates, not verified execution values.
ALLOW_UNVERIFIED_SHARE_PROXY = True
_PRICE_ALIASES = {"WBTC":"BTC-USD", "CBBTC":"BTC-USD", "WETH":"ETH-USD",
                  "XAUT":"GC=F", "PAXG":"GC=F", "XAUt":"GC=F",
                  "PPLTX":"PPLT", "PPLTx":"PPLT", "SLVon":"SLV", "TQQQon":"TQQQ"}
_CG_IDS = {"BTC":"bitcoin","WBTC":"wrapped-bitcoin","CBBTC":"coinbase-wrapped-btc",
           "ETH":"ethereum","WETH":"weth","BNB":"binancecoin","SOL":"solana",
           "TRX":"tron","TON":"the-open-network","XAUT":"tether-gold","PAXG":"pax-gold","TQQQON":"proshares-ultrapro-qqq-ondo-tokenized"}

def fetch_current_prices():
    px = {"USDC": 1.0, "USDT": 1.0, "BUSD": 1.0, "DAI": 1.0, "FDUSD": 1.0}
    for ticker, sym in [("BTC-USD","BTC"),("ETH-USD","ETH"),("BNB-USD","BNB"),
                        ("SOL-USD","SOL"),("TRX-USD","TRX"),("TON11419-USD","TON"),
                        ("PPLT","PPLT"),("SLV","SLV"),("TQQQ","TQQQ"),("NVDA","NVDA"),
                        ("AAPL","AAPL"),("AMZN","AMZN"),("MSFT","MSFT"),
                        ("TSLA","TSLA"),("GOOGL","GOOGL"),("META","META")]:
        try:
            t = yf.Ticker(ticker)
            px[sym] = float(t.fast_info["last_price"])
        except:
            pass
    for sym, ticker in _XSTOCK_TICKERS.items():
        if ticker in px: px[sym] = px[ticker]
    for sym, ticker in _PRICE_ALIASES.items():
        if sym in px: continue
        try:
            val = float(yf.Ticker(ticker).fast_info["last_price"])
            if math.isfinite(val) and val > 0: px[sym] = val
        except Exception: pass
    if ALEF_PRICE_USD is not None: px["ALEF"] = ALEF_PRICE_USD
    return px

# ── ALEF mint / burn history ───────────────────────────────────────────────────
_SUPPLY_OPS = {"mintTo", "mintToChecked", "burn", "burnChecked"}

def _sol_sigs_all(address, max_pages=50):
    """Yield all signatures for address, newest-first across pages."""
    before = None
    for _ in range(max_pages):
        params = {"limit": 100, "commitment": "finalized"}
        if before:
            params["before"] = before
        page = _sol_rpc("getSignaturesForAddress", [address, params]) or []
        yield from page
        if len(page) < 100:
            break
        before = page[-1]["signature"]

def _sol_get_tx(sig):
    return _sol_rpc("getTransaction", [sig, {
        "encoding": "jsonParsed",
        "maxSupportedTransactionVersion": 1,
        "commitment": "finalized",
    }])

def fetch_alef_mint_burn_history(prices):
    events = []
    seen = set()
    for mint_addr in (ALEF_MINT, ALEF_MINT_OLD):
        for s in _sol_sigs_all(mint_addr, max_pages=100):
            sig = s.get("signature")
            if not sig or sig in seen:
                continue
            seen.add(sig)
            try:
                tx = _sol_get_tx(sig)
            except Exception as e:
                AUDIT_WARNINGS.append(f"ALEF mint/burn transaction unavailable: {sig}: {type(e).__name__}")
                print(f"  [WARN] tx fetch {sig[:8]}…: {e}", file=sys.stderr)
                continue
            if not tx or (tx.get("meta") or {}).get("err") is not None:
                continue
            bt = tx.get("blockTime") or s.get("blockTime")
            if not bt:
                continue
            msg = (tx.get("transaction") or {}).get("message") or {}
            all_ixs = list(msg.get("instructions") or [])
            for inner in (tx.get("meta") or {}).get("innerInstructions") or []:
                all_ixs.extend(inner.get("instructions") or [])
            for ix in all_ixs:
                parsed = ix.get("parsed")
                if not isinstance(parsed, dict):
                    continue
                if parsed.get("type") not in _SUPPLY_OPS:
                    continue
                info = parsed.get("info") or {}
                if info.get("mint") not in (ALEF_MINT, ALEF_MINT_OLD):
                    continue
                ta = info.get("tokenAmount") or {}
                raw = int(ta.get("amount") or info.get("amount") or 0)
                dec = int(ta.get("decimals") or 6)
                alef_qty = raw / 10**dec
                RAW_ALEF_SUPPLY_EVENTS.append(dict(ts=bt, mint=info.get("mint"),
                    qty=alef_qty, type="alef_burn" if parsed["type"] in ("burn", "burnChecked") else "alef_mint", ref=sig))
                if alef_qty in EXCLUDE_ALEF_AMOUNTS:
                    continue
                usd_val  = None  # valued at the historical quote in the ledger
                is_burn  = parsed["type"] in ("burn", "burnChecked")
                events.append({
                    "ts":          bt,
                    "dt":          datetime.fromtimestamp(bt, tz=timezone.utc),
                    "type":        "alef_burn" if is_burn else "alef_mint",
                    "chain":       "solana",
                    "asset":       "ALEF",
                    "mint":        info.get("mint"),
                    "qty":         alef_qty,
                    "usd_value":   usd_val,
                    "is_inflow":   is_burn,
                    "description": f"{'Burn' if is_burn else 'Mint'} {alef_qty:,.4f} ALEF",
                    "ref":         sig,
                })
    events.sort(key=lambda x: x["ts"])
    return events

# ── Raydium CLMM pool discovery ────────────────────────────────────────────────
def discover_raydium_pool():
    """Return (pool_id, usdc_vault, alef_vault) or (None, None, None)."""
    # Try Raydium pools-by-mint API first (fastest)
    for mint in (ALEF_MINT, ALEF_MINT_OLD):
        try:
            r = _get("https://api.raydium.io/v2/main/pool/info/token",
                     params={"mint": mint})
            pools = (r or {}).get("data") or []
            for p in pools:
                if p.get("type") == "CLMM" or "clmm" in str(p.get("programId","")).lower():
                    return p.get("id"), None, None
        except:
            pass
    # Fallback: scan wallet SPL accounts for Raydium CLMM position NFTs
    try:
        result = _sol_rpc("getTokenAccountsByOwner", [
            SOL_WALLET,
            {"programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
            {"encoding": "jsonParsed", "commitment": "confirmed"},
        ])
        for acct in (result or {}).get("value") or []:
            info = (acct.get("account",{}).get("data",{})
                       .get("parsed",{}).get("info") or {})
            mint = info.get("mint","")
            amt  = float((info.get("tokenAmount") or {}).get("uiAmount") or 0)
            if amt != 1.0:
                continue
            try:
                mb = _b58decode(mint)
                if len(mb) != 32:
                    continue
                pda, _ = _find_pda([b"position", mb], RAYDIUM_CLMM)
                ai = _sol_rpc("getAccountInfo", [pda, {"encoding":"base64","commitment":"confirmed"}])
                val = (ai or {}).get("value")
                if not val or val.get("owner") != RAYDIUM_CLMM:
                    continue
                data = _get("https://dynamic-ipfs.raydium.io/clmm/position",
                            params={"id": pda})
                pool = (data or {}).get("poolInfo") or {}
                mint_a = (pool.get("mintA") or {}).get("address","")
                mint_b = (pool.get("mintB") or {}).get("address","")
                if ALEF_MINT in (mint_a, mint_b) or ALEF_MINT_OLD in (mint_a, mint_b):
                    return pool.get("id"), None, None
            except:
                continue
    except Exception as e:
        print(f"  [WARN] pool discovery: {e}", file=sys.stderr)
    return None, None, None

# ── Raydium swap history ───────────────────────────────────────────────────────
def fetch_raydium_swaps(pool_id):
    """
    For each transaction on pool_id, infer buy/sell from USDC net flow in pool vaults.
    Returns list of dicts with type=raydium_buy or raydium_sell.
    """
    if not pool_id:
        return []
    swaps = []
    seen  = set()
    for s in _sol_sigs_all(pool_id, max_pages=100):
        sig = s.get("signature")
        if not sig or sig in seen:
            continue
        seen.add(sig)
        try:
            tx = _sol_get_tx(sig)
        except Exception as e:
            AUDIT_WARNINGS.append(f"Raydium transaction unavailable: {sig}: {type(e).__name__}")
            continue
        if not tx or (tx.get("meta") or {}).get("err") is not None:
            continue
        bt   = tx.get("blockTime") or s.get("blockTime")
        meta = tx.get("meta") or {}
        # Require a decoded Anchor swap instruction, including CPI calls.
        ix = list((tx.get("transaction") or {}).get("message", {}).get("instructions", []))
        for inner in meta.get("innerInstructions") or []:
            ix.extend(inner.get("instructions") or [])
        swap_discs = {hashlib.sha256(("global:" + n).encode()).digest()[:8]
                      for n in ("swap", "swap_v2", "swap_router_base_in")}
        lp_discs = {hashlib.sha256(("global:" + n).encode()).digest()[:8]
                    for n in ("increase_liquidity", "increase_liquidity_v2", "decrease_liquidity", "decrease_liquidity_v2", "open_position", "open_position_v2", "open_position_with_token22_nft", "close_position", "collect_fund_fee", "collect_protocol_fee")}
        discs = set()
        for i in ix:
            if i.get("programId") == RAYDIUM_CLMM and i.get("data"):
                try: discs.add(_b58decode(i["data"])[:8])
                except Exception: pass
        if discs & lp_discs:
            if not discs & swap_discs:
                RAYDIUM_LP_REFS.add(sig)
            else:
                AUDIT_WARNINGS.append(f"Mixed Raydium swap/LP: {sig}")
            continue
        if not discs & swap_discs:
            continue
        # Map accountIndex → {mint, owner, pre_ui, post_ui}
        pre_map  = {b["accountIndex"]: b for b in (meta.get("preTokenBalances")  or [])}
        post_map = {b["accountIndex"]: b for b in (meta.get("postTokenBalances") or [])}
        indices  = set(pre_map) | set(post_map)
        usdc_delta = alef_delta = 0.0
        for idx in indices:
            pre  = pre_map.get(idx,  {})
            post = post_map.get(idx, {})
            tok_mint  = pre.get("mint")  or post.get("mint")
            # Only pool-owned accounts
            owner = pre.get("owner") or post.get("owner") or ""
            if owner not in (pool_id, RAYDIUM_CLMM):
                continue
            pre_ui  = float((pre.get("uiTokenAmount")  or {}).get("uiAmount") or 0)
            post_ui = float((post.get("uiTokenAmount") or {}).get("uiAmount") or 0)
            delta = post_ui - pre_ui
            if tok_mint == SOLANA_USDC:
                usdc_delta += delta
            elif tok_mint in (ALEF_MINT, ALEF_MINT_OLD):
                alef_delta += delta
        if abs(usdc_delta) < 0.01 and abs(alef_delta) < 0.01:
            continue
        if abs(alef_delta) < 0.01 or abs(usdc_delta) < 0.01:
            continue  # LP fee collection / pool-only USDC event, not a real swap
        # LP add: both increase; LP remove: both decrease.
        # Real swaps always move USDC and ALEF in opposite directions.
        if (usdc_delta > 0) == (alef_delta > 0):
            continue  # LP add or remove — not a trade
        # buy  = USDC flows IN to pool (someone pays USDC to get ALEF)  → inflow
        # sell = USDC flows OUT of pool (someone gets USDC for their ALEF) → outflow
        is_buy = usdc_delta > 0
        swaps.append({
            "ts":          bt,
            "dt":          datetime.fromtimestamp(bt, tz=timezone.utc),
            "type":        "raydium_buy" if is_buy else "raydium_sell",
            "chain":       "solana",
            "asset":       "USDC",
            "qty":         abs(usdc_delta),
            "usd_value":   abs(usdc_delta),
            "alef_qty":    abs(alef_delta),
            "is_inflow":   is_buy,
            "description": (f"{'Buy' if is_buy else 'Sell'} "
                            f"{abs(alef_delta):,.4f} ALEF "
                            f"({'receive' if is_buy else 'pay'} "
                            f"{abs(usdc_delta):,.2f} USDC)"),
            "ref":         sig,
        })
    swaps.sort(key=lambda x: x["ts"])
    return swaps

# ── BSC token-transfer history via public RPC (no Etherscan key needed) ───────
from concurrent.futures import ThreadPoolExecutor as _TPE
import requests as _req

_BSC_RPC    = "https://bsc-rpc.publicnode.com"
_BSC_CHUNK  = 9000
_ERC20_XFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
_BSC_STABLE = {   # lowercase contract → (symbol, decimals)
    "0x55d398326f99059ff775485246999027b3197955": ("USDT", 18),
    "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d": ("USDC", 18),
}

def _bsc_post(method, params):
    r = _req.post(_BSC_RPC,
                  json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params},
                  timeout=20)
    r.raise_for_status()
    d = r.json()
    if "error" in d:
        raise RuntimeError(d["error"])
    return d.get("result")

NODEREAL_API_KEY = os.getenv("NODEREAL_API_KEY") or input("NodeReal API key (free at nodereal.io): ").strip()

def fetch_bsc_history(prices):
    """Indexed wallet transfers; no block range scans."""
    wallet = EVM_ADDR.lower()
    out = []
    _ref_seen = {}
    for field in ("fromAddress", "toAddress"):
        params = {field: wallet, "category": ["external", "internal", "20"],
                  "order": "desc", "maxCount": "0x3e8"}
        seen_pages = set()
        while True:
            try:
                r = requests.post("https://bsc-mainnet.nodereal.io/v1/" + NODEREAL_API_KEY,
                    json={"jsonrpc":"2.0","id":1,"method":"nr_getAssetTransfers","params":[params]}, timeout=45)
                r.raise_for_status()
                d = r.json()
                if "error" in d or not isinstance(d.get("result"),dict):
                    raise ValueError("NodeReal returned an invalid result or RPC error")
                result = d["result"]
                transfers = result["transfers"]
            except Exception as e:
                AUDIT_WARNINGS.append(f"BSC incomplete ({field}): {type(e).__name__}")
                break
            for t in transfers:
                try:
                    frm,to = t["from"].lower(),t["to"].lower()
                    if frm == to or wallet not in (frm,to): continue
                    if str(t.get("receiptsStatus",1)) in ("0","0x0"): continue
                    ts = int(t.get("blockTimeStamp") or t.get("blockTimestamp"))
                    contract = str(t.get("contractAddress") or "").lower()
                    native = t.get("category") in ("external","internal")
                    sym = "BNB" if native else BSC_REGISTRY.get(contract)
                    if not sym:
                        QUARANTINE.append(dict(chain="bsc", asset=t.get("asset"), contract=contract, ref=t.get("hash"), reason="unverified contract", raw=t))
                        continue
                    dec = t.get("decimal")
                    if dec is None and t.get("category") in ("external","internal"): dec = 18
                    if dec is None: raise ValueError("missing decimals")
                    qty = int(str(t["value"]), 16 if str(t["value"]).startswith("0x") else 10) / 10**int(str(dec), 16 if str(dec).startswith("0x") else 10)
                    if not qty: continue
                    incoming = to == wallet
                    cp = frm if incoming else to
                    px = prices.get(sym)
                    if not px: AUDIT_WARNINGS.append(f"Unpriced BSC asset {sym}: {t['hash']}")
                    _h=t["hash"]; _n=_ref_seen.get(_h,0); _ref_seen[_h]=_n+1
                    out.append(dict(ts=ts,dt=datetime.fromtimestamp(ts,timezone.utc),type="deposit" if incoming else "withdrawal",chain="bsc",asset=sym,qty=qty,usd_value=qty*(px or 0),is_inflow=incoming,description=f"{sym} {qty:g} (BSC)" + (" [UNPRICED]" if not px else ""),ref=_h if _n==0 else f"{_h}_{_n}",counterparty=cp,contract=contract,raw_qty=int(str(t["value"]),16 if str(t["value"]).startswith("0x") else 10)))
                except Exception as e:
                    AUDIT_WARNINGS.append(f"BSC malformed transfer {t.get('hash')}: {type(e).__name__}")
            cursor = result.get("pageKey") or result.get("PageKey")
            if not cursor: break
            if cursor in seen_pages:
                AUDIT_WARNINGS.append("BSC pagination stalled"); break
            seen_pages.add(cursor); params["pageKey"] = cursor
    return sorted(out,key=lambda t:t["ts"])

def fetch_evm_history(chain, prices):
    chain_id = 56 if chain == "bsc" else 1
    base     = "https://api.etherscan.io/v2/api"
    wallet   = EVM_ADDR.lower()
    txns     = []

    def _etherscan(action, extra=None):
        params = {
            "chainid":    chain_id,
            "module":     "account",
            "action":     action,
            "address":    EVM_ADDR,
            "startblock": 0,
            "endblock":   99999999,
            "page":       1,
            "offset":     2000,
            "sort":       "asc",
            "apikey":     ETHERSCAN_KEY,
        }
        if extra:
            params.update(extra)
        rows=[]
        for page in range(1,501):
            params["page"]=page
            try:
                r=_get(base,params=params)
                result=r.get("result")
                if not isinstance(result,list):
                    if "no transactions found" in str(r.get("message", "")).lower() or "no transactions found" in str(result).lower(): break
                    raise RuntimeError(str(r.get("message")))
                rows.extend(result)
                if len(result)<params["offset"]: break
            except Exception as e:
                AUDIT_WARNINGS.append(f"Etherscan {action} ({chain}) incomplete at page {page}: {type(e).__name__}")
                break
        else: AUDIT_WARNINGS.append(f"Etherscan {action} ({chain}) page cap")
        return rows

    _ref_seen = {}
    for tx in _etherscan("tokentx"):
        frm = tx.get("from","").lower()
        to  = tx.get("to","").lower()
        if frm == to:
            continue
        if frm == wallet:
            tx_type, is_inflow = "withdrawal", False
        elif to == wallet:
            tx_type, is_inflow = "deposit", True
        else:
            continue
        contract = tx.get("contractAddress", "").lower()
        sym = ETH_REGISTRY.get(contract)
        if sym is None:
            QUARANTINE.append(dict(chain=chain,contract=contract,asset=tx.get("tokenSymbol"),ref=tx.get("hash"),reason="unverified contract",raw=tx)); continue
        dec   = int(tx.get("tokenDecimal") or 18)
        raw   = int(tx.get("value") or 0)
        qty   = raw / 10**dec
        price = 1.0 if sym in ("USDC","USDT","BUSD","DAI","FDUSD") else prices.get(sym, 0)
        usd   = qty * price
        if qty <= 0: continue
        ts = int(tx.get("timeStamp") or 0)
        _h=tx.get("hash",""); _n=_ref_seen.get(_h,0); _ref_seen[_h]=_n+1
        txns.append({
            "ts":          ts,
            "dt":          datetime.fromtimestamp(ts, tz=timezone.utc),
            "type":        tx_type,
            "chain":       chain,
            "asset":       sym,
            "qty":         qty,
            "usd_value":   usd,
            "is_inflow":   is_inflow,
            "description": f"{tx_type.title()} {qty:,.4f} {sym} ({chain.upper()})",
            "ref":         _h if _n==0 else f"{_h}_{_n}", "counterparty": frm if is_inflow else to, "contract": tx.get("contractAddress", "").lower(), "raw_qty": raw,
        })

    # Native BNB/ETH transfers
    for tx in _etherscan("txlist") + _etherscan("txlistinternal"):
        if str(tx.get("isError","0")) != "0": continue
        frm = tx.get("from","").lower()
        to  = tx.get("to","").lower()
        if frm == to:
            continue
        native = "BNB" if chain == "bsc" else "ETH"
        if frm == wallet:
            tx_type, is_inflow = "withdrawal", False
        elif to == wallet:
            tx_type, is_inflow = "deposit", True
        else:
            continue
        # Skip 0-value txns (pure contract calls)
        raw = int(tx.get("value") or 0)
        if raw == 0:
            continue
        qty   = raw / 1e18
        price = prices.get(native, 0)
        usd   = qty * price
        if qty <= 0: continue
        ts = int(tx.get("timeStamp") or 0)
        _h=tx.get("hash",""); _n=_ref_seen.get(_h,0); _ref_seen[_h]=_n+1
        txns.append({
            "ts":          ts,
            "dt":          datetime.fromtimestamp(ts, tz=timezone.utc),
            "type":        tx_type,
            "chain":       chain,
            "asset":       native,
            "qty":         qty,
            "usd_value":   usd,
            "is_inflow":   is_inflow,
            "description": f"{tx_type.title()} {qty:,.4f} {native} ({chain.upper()})",
            "ref":         _h if _n==0 else f"{_h}_{_n}", "counterparty": frm if is_inflow else to, "contract": tx.get("contractAddress", "").lower(), "raw_qty": raw,
        })

    txns.sort(key=lambda x: x["ts"])
    return txns

# ── Tron external deposits / withdrawals ──────────────────────────────────────
def fetch_tron_history(prices):
    txns = []
    # TRC20 transfers
    try:
        r = _get(f"https://api.trongrid.io/v1/accounts/{TRON_ADDR}/transactions/trc20",
                 params={"limit": 200, "order_by": "block_timestamp,asc"})
        for tx in (r or {}).get("data") or []:
            frm   = tx.get("from","")
            to    = tx.get("to","")
            token=(tx.get("token_info") or {})
            if token.get("address") != TRON_USDT:
                QUARANTINE.append(dict(chain="tron",contract=token.get("address"),asset=token.get("symbol"),ref=tx.get("transaction_id"),reason="unverified contract",raw=tx)); continue
            sym="USDT"
            dec   = int((tx.get("token_info") or {}).get("decimals") or 6)
            raw   = int(tx.get("value") or 0)
            qty   = raw / 10**dec
            if qty > 1_000_000_000:  # skip uint256 overflow / corrupt values
                continue
            price = 1.0 if sym in ("USDT","USDC","TUSD") else prices.get(sym, 0)
            usd   = qty * price
            if qty <= 0: continue
            if frm == TRON_ADDR:
                tx_type, is_inflow = "withdrawal", False
            elif to == TRON_ADDR:
                tx_type, is_inflow = "deposit", True
            else:
                continue
            ts = int(tx.get("block_timestamp",0) or 0) // 1000
            txns.append({
                "ts":          ts,
                "dt":          datetime.fromtimestamp(ts, tz=timezone.utc),
                "type":        tx_type,
                "chain":       "tron",
                "asset":       sym,
                "qty":         qty,
                "usd_value":   usd,
                "is_inflow":   is_inflow,
                "description": f"{tx_type.title()} {qty:,.4f} {sym} (Tron)",
                "ref":         tx.get("transaction_id",""), "counterparty": frm if is_inflow else to,
            })
    except Exception as e:
        AUDIT_WARNINGS.append(f"Tron history incomplete: {type(e).__name__}")
    txns.sort(key=lambda x: x["ts"])
    return txns

# ── Bitcoin history ────────────────────────────────────────────────────────────
def fetch_btc_history(prices):
    btc_price = prices.get("BTC", 100_000)
    txns = []
    try:
        for tx in _get(f"https://mempool.space/api/address/{BITCOIN_ADDR}/txs") or []:
            ts = (tx.get("status") or {}).get("block_time") or 0
            if not ts:
                continue
            net_sats = 0
            for vin in tx.get("vin") or []:
                if (vin.get("prevout") or {}).get("scriptpubkey_address") == BITCOIN_ADDR:
                    net_sats -= vin["prevout"].get("value", 0)
            for vout in tx.get("vout") or []:
                if vout.get("scriptpubkey_address") == BITCOIN_ADDR:
                    net_sats += vout.get("value", 0)
            qty = abs(net_sats) / 1e8
            usd = qty * btc_price
            if qty <= 0: continue
            is_inflow = net_sats > 0
            txns.append({
                "ts":          ts,
                "dt":          datetime.fromtimestamp(ts, tz=timezone.utc),
                "type":        "deposit" if is_inflow else "withdrawal",
                "chain":       "bitcoin",
                "asset":       "BTC",
                "qty":         qty,
                "usd_value":   usd,
                "is_inflow":   is_inflow,
                "description": f"{'Deposit' if is_inflow else 'Withdrawal'} {qty:.6f} BTC",
                "ref":         tx.get("txid",""),
            })
    except Exception as e:
        AUDIT_WARNINGS.append(f"BTC history incomplete: {type(e).__name__}")
    txns.sort(key=lambda x: x["ts"])
    return txns

# ── TON (Gram) jetton + native history via TonAPI v2 ──────────────────────────
_TON_STABLES = {"USDT", "USDC", "TUSD", "USD₮"}

def fetch_ton_history(prices):
    """Fetch TON jetton and native transfers via TonAPI v2 events endpoint."""
    txns  = []
    seen  = set()   # event_ids already processed
    before_lt = None

    for _ in range(20):
        params = {"limit": 100, "subject_only": "true"}
        if before_lt:
            params["before_lt"] = before_lt
        try:
            d = _get(f"https://tonapi.io/v2/accounts/{TON_ADDR}/events",
                     params=params)
        except Exception as e:
            AUDIT_WARNINGS.append(f"TON history incomplete: {type(e).__name__}")
            break

        events = (d or {}).get("events") or []

        for ev in events:
            ts    = int(ev.get("timestamp") or 0)
            ev_id = str(ev.get("event_id") or "")
            if not ts or ev_id in seen:
                continue
            seen.add(ev_id)

            _act_n = 0
            for act in (ev.get("actions") or []):
                if act.get("status") != "ok" or ev.get("in_progress"):
                    continue
                atype = act.get("type")

                if atype == "JettonTransfer":
                    jt     = act.get("JettonTransfer") or {}
                    jetton = jt.get("jetton") or {}
                    sym    = str(jetton.get("symbol") or "?")
                    try:
                        dec = int(jetton.get("decimals") or 9)
                    except Exception:
                        dec = 9
                    raw_amt = int(jt.get("amount") or 0)
                    qty     = raw_amt / (10 ** dec)
                    if qty <= 0 or qty > 1_000_000_000:
                        continue
                    sender = (jt.get("sender")    or {}).get("address", "").lower()
                    recip  = (jt.get("recipient") or {}).get("address", "").lower()
                    if TON_ADDR_RAW not in (sender, recip):
                        continue
                    is_inflow = (recip == TON_ADDR_RAW)
                    if sender == recip:
                        continue  # self-transfer
                    if sym in _TON_STABLES:
                        price = 1.0
                    else:
                        underlying = _XSTOCK_TICKERS.get(sym) or sym.rstrip("x")
                        price = prices.get(underlying) or prices.get(sym, 0)
                    usd = qty * price
                    if qty <= 0: continue
                    tx_type = "deposit" if is_inflow else "withdrawal"
                    txns.append({
                        "ts": ts, "dt": datetime.fromtimestamp(ts, tz=timezone.utc),
                        "type": tx_type, "chain": "ton", "asset": sym,
                        "qty": qty, "usd_value": usd, "is_inflow": is_inflow,
                        "description": f"{tx_type.title()} {qty:,.4f} {sym} (TON)",
                        "ref": f"{ev_id}_{_act_n}", "counterparty": sender if is_inflow else recip,
                    })
                    _act_n += 1

                elif atype == "TonTransfer":
                    tt      = act.get("TonTransfer") or {}
                    amt_nano = int(tt.get("amount") or 0)
                    qty      = amt_nano / 1e9
                    usd      = qty * prices.get("TON", 0)
                    if qty <= 0: continue
                    sender = (tt.get("sender")    or {}).get("address", "").lower()
                    recip  = (tt.get("recipient") or {}).get("address", "").lower()
                    if sender == TON_ADDR_RAW:
                        is_inflow = False
                    elif recip == TON_ADDR_RAW:
                        is_inflow = True
                    else:
                        continue
                    tx_type = "deposit" if is_inflow else "withdrawal"
                    txns.append({
                        "ts": ts, "dt": datetime.fromtimestamp(ts, tz=timezone.utc),
                        "type": tx_type, "chain": "ton", "asset": "TON",
                        "qty": qty, "usd_value": usd, "is_inflow": is_inflow,
                        "description": f"{tx_type.title()} {qty:,.4f} TON",
                        "ref": f"{ev_id}_{_act_n}", "counterparty": sender if is_inflow else recip,
                    })
                    _act_n += 1

        if len(events) < 100:
            break
        before_lt = d.get("next_from") or (events[-1].get("lt") if events else None)

    txns.sort(key=lambda x: x["ts"])
    return txns

# ── Solana wallet external USDC/token deposits+withdrawals (SOL_WALLET_2) ─────
_sol_asset_cache = {}
_XSTOCK_TICKERS.update({"PPLTx":"PPLT", "PPLTX":"PPLT"})

def _enhanced_page(address, before=None, include_tokens=False):
    # Retry rate limits and transient errors, then try smaller pages / legacy host.
    errors=[]
    for host, limit in (("api-mainnet.helius-rpc.com",100),("api-mainnet.helius-rpc.com",25),("api.helius.xyz",25)):
        params={"api-key":HELIUS_KEY,"limit":limit}
        if include_tokens: params["token-accounts"]="balanceChanged"
        if before: params["before-signature"]=before
        for attempt in range(3):
            try:
                r=_sess.get(f"https://{host}/v0/addresses/{address}/transactions",params=params,timeout=45)
                if r.status_code in (429,500,502,503,504):
                    errors.append(str(r.status_code)); time.sleep(2**attempt); continue
                if not r.ok:
                    errors.append(str(r.status_code)); break
                page=r.json()
                if not isinstance(page,list): raise ValueError("invalid page")
                return page,limit
            except Exception as e:
                errors.append(type(e).__name__); time.sleep(2**attempt)
    raise RuntimeError("enhanced history: "+", ".join(errors))

_SOL_RAW_CACHE={}
_SOL_FALLBACK_REFS=set()
def _raw_tx_cached(sig):
    if sig not in _SOL_RAW_CACHE:
        _SOL_RAW_CACHE[sig]=_sol_get_tx(sig)
    return _SOL_RAW_CACHE[sig]

def _raw_address_signatures(address, cutoff):
    before=None
    while True:
        params={"limit":1000,"commitment":"finalized"}
        if before: params["before"]=before
        page=_sol_rpc("getSignaturesForAddress",[address,params])
        if not isinstance(page,list): raise RuntimeError("invalid RPC signature response")
        if not page: return
        for entry in page:
            bt=entry.get("blockTime")
            if (bt is None or bt>=cutoff) and entry.get("err") is None: yield entry["signature"]
        last=page[-1]; cursor=last["signature"]
        if (last.get("blockTime") is not None and last["blockTime"]<cutoff) or len(page)<1000: return
        if cursor==before: raise RuntimeError("RPC pagination stalled")
        before=cursor

def _raw_sol_rows(sig, wallet, owners, label, prices, only_pplt=False):
    tx=_raw_tx_cached(sig)
    if not tx: raise RuntimeError("transaction unavailable")
    meta=tx.get("meta") or {}
    if meta.get("err") is not None: return []
    ts=tx.get("blockTime")
    if not ts: raise RuntimeError("missing block time")
    keys=[k.get("pubkey") if isinstance(k,dict) else k for k in tx["transaction"]["message"]["accountKeys"]]
    totals={}
    for sign,field in ((-1,"preTokenBalances"),(1,"postTokenBalances")):
        for b in meta.get(field) or []:
            idx=b["accountIndex"]; account=keys[idx] if idx<len(keys) else None
            if (b.get("owner") or owners.get(account))!=wallet: continue
            mint=b["mint"]; a=b["uiTokenAmount"]
            qty=Decimal(a["amount"])/(Decimal(10)**int(a["decimals"]))
            totals[mint]=totals.get(mint,Decimal(0))+sign*qty
    if not only_pplt and wallet in keys:
        idx=keys.index(wallet)
        delta=meta["postBalances"][idx]-meta["preBalances"][idx]
        # Add back fee charged to wallet: fee belongs to expense ledger, not capital.
        if idx==0: delta+=meta.get("fee",0)
        totals["SOL"]=Decimal(delta)/Decimal(10**9)
    rows=[]
    for mint,delta in totals.items():
        if not delta or (only_pplt and mint!=PPLT_MINT): continue
        sym={SOLANA_USDC:"USDC","SOL":"SOL",PPLT_MINT:"PPLTX"}.get(mint)
        if not sym:
            if mint not in (ALEF_MINT,ALEF_MINT_OLD): QUARANTINE.append(dict(chain="solana",contract=mint,ref=sig,reason="unverified raw balance delta",qty=str(delta)))
            continue
        qty=float(abs(delta)); px=prices.get(sym) if sym!="PPLTX" else None
        rows.append(dict(ts=ts,dt=datetime.fromtimestamp(ts,timezone.utc),type="deposit" if delta>0 else "withdrawal",chain="solana",asset=sym,qty=qty,usd_value=qty*(px or 0),is_inflow=delta>0,description=f"{sym} {qty:g} ({label}) [raw balance delta]",ref=sig,counterparty="",contract=mint,unpriced=not bool(px),wallet=wallet,raw_fallback=True,quantity_basis="raw"))
    return rows

def fetch_sol_wallet_external_txns(wallet, label, prices):
    out, history = [], {}
    _sig_seen = {}
    accounts = {wallet}; owners={wallet:wallet}; pplt_accounts=set(); fallback=set()
    for program in ("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"):
        try:
            result=_sol_rpc("getTokenAccountsByOwner",[wallet,{"programId":program},{"encoding":"jsonParsed","commitment":"finalized"}])
            for account in result["value"]:
                addr=account["pubkey"]; accounts.add(addr); owners[addr]=wallet
                info=account["account"]["data"]["parsed"]["info"]
                if info["mint"]==PPLT_MINT:
                    pplt_accounts.add(addr)
                    print(f"  {label}: PPLTX account {addr}, raw units={info['tokenAmount']['amount']}")
        except Exception as e: AUDIT_WARNINGS.append(f"{label} token-account discovery incomplete: {type(e).__name__}")
    cutoff=int(pd.to_datetime(AUDIT_START_DATE, utc=True).timestamp()) if AUDIT_START_DATE else 0
    for address in sorted(accounts):
        before=None; seen_cursors=set()
        while True:
            try: page,limit=_enhanced_page(address,before,address==wallet)
            except Exception as e:
                print(f"  {label}: switching {address} to raw RPC ({e})")
                fallback.add(address); break
            if not page: break
            for tx in page:
                if tx.get("signature") and int(tx.get("timestamp") or 0)>=cutoff: history[tx["signature"]]=tx
            cursor=page[-1].get("signature")
            if len(page)<limit or (page[-1].get("timestamp") and int(page[-1]["timestamp"])<cutoff): break
            if not cursor or cursor in seen_cursors:
                fallback.add(address); break
            seen_cursors.add(cursor); before=cursor
    raw_sigs=set(); pplt_sigs=set()
    for address in sorted(fallback|pplt_accounts):
        try:
            sigs=set(_raw_address_signatures(address,cutoff))
            if address in fallback: raw_sigs.update(sigs-set(history))
            if address in pplt_accounts: pplt_sigs.update(sigs)
            print(f"  {label}: raw RPC found {len(sigs)} signatures for {address}")
        except Exception as e: AUDIT_WARNINGS.append(f"{label} raw signature history incomplete for {address}: {type(e).__name__}")
    # Enhanced tokenAmount can be UI-scaled. Fetch raw pre/post amounts for PPLTx.
    for sig,tx in history.items():
        if any(tr.get("mint")==PPLT_MINT for tr in tx.get("tokenTransfers",[])):
            pplt_sigs.add(sig)
    verified_pplt_sigs=set()
    for sig in sorted(raw_sigs|pplt_sigs):
        try:
            for _row in _raw_sol_rows(sig,wallet,owners,label,prices,only_pplt=sig not in raw_sigs):
                _sn=_sig_seen.get(sig,0); _sig_seen[sig]=_sn+1
                out.append(dict(_row, ref=sig if _sn==0 else f"{sig}_{_sn}"))
            if sig in pplt_sigs:verified_pplt_sigs.add(sig)
            if sig in raw_sigs: _SOL_FALLBACK_REFS.add(sig)
        except Exception as e: AUDIT_WARNINGS.append(f"{label} raw transaction incomplete {sig}: {type(e).__name__}")
    for sig,tx in history.items():
        if tx.get("transactionError"): continue
        ts=int(tx.get("timestamp") or 0)
        for tr in list(tx.get("tokenTransfers") or [])+[dict(t,mint="SOL",tokenAmount=int(t.get("amount") or 0)/1e9) for t in tx.get("nativeTransfers") or []]:
            frm=tr.get("fromUserAccount") or owners.get(tr.get("fromTokenAccount"))
            to=tr.get("toUserAccount") or owners.get(tr.get("toTokenAccount"))
            if frm==to or wallet not in (frm,to): continue
            if frm in (SOL_WALLET,SOL_WALLET_2) and to in (SOL_WALLET,SOL_WALLET_2): continue
            mint=tr.get("mint"); qty=float(tr.get("tokenAmount") or 0)
            if qty<=0 or mint in (ALEF_MINT,ALEF_MINT_OLD) or (mint==PPLT_MINT and sig in verified_pplt_sigs): continue
            sym={SOLANA_USDC:"USDC", "SOL":"SOL", PPLT_MINT:"PPLTX"}.get(mint)
            if not sym:
                QUARANTINE.append(dict(chain="solana",contract=mint,ref=sig,raw=tr,reason="unverified mint")); continue
            # PPLTX uses scaled UI units; obtain raw amount and timestamp-specific multiplier separately.
            px=prices.get(sym)
            if sym=="PPLTX": px=None
            incoming=to==wallet
            _sn=_sig_seen.get(sig,0); _sig_seen[sig]=_sn+1
            out.append(dict(ts=ts,dt=datetime.fromtimestamp(ts,timezone.utc),type="deposit" if incoming else "withdrawal",chain="solana",asset=sym,qty=qty,usd_value=qty*(px or 0),is_inflow=incoming,description=f"{sym} {qty:g} ({label})",ref=sig if _sn==0 else f"{sig}_{_sn}",counterparty=frm if incoming else to,contract=mint,unpriced=not bool(px),wallet=wallet,quantity_basis="unknown" if sym=="PPLTX" else "raw"))
    print(f"  {label}: {len(accounts)-1} current token accounts; {len(history)} unique transactions; {len(out)} retained transfers; PPLTX={sum(t['asset']=='PPLTX' for t in out)}")
    return sorted(out,key=lambda t:t['ts'])


# ── Historical price helpers ───────────────────────────────────────────────────
def _build_alef_px_series(swaps):
    """Sorted (ts, price) list from Raydium USDC/ALEF ratios (dust filtered)."""
    out = []
    for s in swaps:
        alef_q = s.get("alef_qty", 0)
        usdc_q = s.get("qty", 0)
        if alef_q > 1.0 and usdc_q > 1.0:
            out.append((s["ts"], usdc_q / alef_q))
    out.sort(key=lambda x: x[0])
    return out

def fetch_alef_spot_price(pool_id=ALEF_POOL_ID):
    """Raydium pool spot price, in USDC per ALEF. Validate both mint addresses."""
    d = _get("https://api-v3.raydium.io/pools/info/ids", params={"ids": pool_id})
    pools = d.get("data") or []
    pool = next((p for p in pools if isinstance(p,dict) and p.get("id")==pool_id), None)
    if not pool: raise ValueError("Raydium pool missing")
    a, b = pool["mintA"]["address"], pool["mintB"]["address"]
    if {a,b} != {ALEF_MINT,SOLANA_USDC}: raise ValueError("Unexpected Raydium pool mints")
    p = float(pool["price"])  # mint B per mint A
    if not math.isfinite(p) or p <= 0: raise ValueError("Invalid Raydium spot price")
    return p if a == ALEF_MINT else 1/p


def fetch_alef_chart_history(start_ts, end_ts, mint=ALEF_MINT):
    """Use Raydium's published TradingView Birdeye base/quote feed.
    15-minute closes become available only at candle end (no look-ahead).
    Request seven-day windows to stay below 1,000 candles per response.
    """
    points = {}
    step = 7*86400
    interval = 15*60
    url = "https://birdeye-proxy.raydium.io/defi/ohlcv/base_quote"
    for lo in range(int(start_ts)//interval*interval, int(end_ts), step):
        hi = min(lo+step, int(end_ts))
        for attempt in range(3):
            try:
                d = _get(url, params={"base_address":mint,"quote_address":SOLANA_USDC,
                    "type":"15m","time_from":lo,"time_to":hi})
                payload = d.get("data",d)
                items = payload.get("items") if isinstance(payload,dict) else None
                if d.get("success") is False or not isinstance(items,list):
                    raise ValueError("Invalid chart response")
                for bar in items:
                    try:
                        ts = int(bar["unixTime"])+interval
                        p = float(bar["c"])
                        if lo < ts <= hi and math.isfinite(p) and p>0: points[ts]=p
                    except (ValueError, TypeError, KeyError):
                        continue
                if not items:
                    AUDIT_WARNINGS.append(f"Raydium ALEF chart returned no candles in window {lo}–{hi}; using trades if available")
                break
            except Exception as e:
                if attempt == 2:
                    AUDIT_WARNINGS.append(f"Raydium chart unavailable {lo}–{hi}: {type(e).__name__}")
                else: time.sleep(1+attempt*2)
        time.sleep(0.15)
    return sorted(points.items())


def alef_historical_detail(ts, chart, trades):
    """Latest available prior chart close or actual pool trade, never a future quote."""
    candidates=[]
    for points, label in [(chart,"Raydium chart (Birdeye 15m prior close)"),
                          (trades,"Raydium on-chain prior swap (execution price)")]:
        i=bisect.bisect_right(points,(ts,float("inf")))-1
        if i>=0 and 0<=ts-points[i][0]<=7*86400:
            candidates.append((points[i][0], points[i][1], label))
    if not candidates: return None,"Missing historical ALEF quote"
    _,p,label=max(candidates,key=lambda x:x[0])
    return p,label

_yf_hist_cache: dict = {}

def _yf_hist_price(ticker, ts):
    """Daily closing price for ticker at unix timestamp ts."""
    dt  = datetime.fromtimestamp(ts, tz=timezone.utc).date()
    key = (ticker, dt.isoformat())
    if key not in _yf_hist_cache:
        try:
            start = (dt - timedelta(days=4)).isoformat()
            end   = (dt + timedelta(days=4)).isoformat()
            df    = yf.download(ticker, start=start, end=end,
                                progress=False, auto_adjust=False)
            if df.empty:
                _yf_hist_cache[key] = None
            else:
                target = pd.Timestamp(dt)
                if df.index.tz is not None: target = target.tz_localize(df.index.tz)
                prior = df.index[df.index <= target]
                if len(prior) == 0: return None
                nearest = prior[-1]
                val = df["Close"].loc[nearest]
                _yf_hist_cache[key] = float(val.iloc[0] if hasattr(val, "iloc") else val)
        except Exception as e:
            print(f"  [WARN] yfinance hist {ticker} {dt}: {e}", file=sys.stderr)
            _yf_hist_cache[key] = None
    return _yf_hist_cache[key]

# [AUDIT_CELL_DEFS_END] — imports + constants + function definitions above;
# network fetch calls and execution follow below.
# ══════════════════════════════════════════════════════════════════════════════
# MAIN
# ══════════════════════════════════════════════════════════════════════════════
VERIFIED_LEG_ACTIONS = {}

print(f"\n{'═'*62}")
print("  ALEF FUND — TRANSACTION AUDIT | LIVE PRICE / RPC v1 / xStocks multipliers / on-chain paid-interest benchmark / portfolio conversion fees / persistent receipt cache")
print(f"  Generated {NOW:%Y-%m-%d %H:%M} UTC")
print(f"{'═'*62}\n")

print("▶ Fetching live ALEF/USDC price from Raydium...")
pool_id = ALEF_POOL_ID
try:
    ALEF_PRICE_USD = fetch_alef_spot_price(pool_id)
    ALEF_PRICE_SOURCE = "Raydium pool spot (USDC par assumption)"
    print(f"  ALEF=${ALEF_PRICE_USD:.8f} — {ALEF_PRICE_SOURCE}")
except Exception as e:
    AUDIT_WARNINGS.append(f"Raydium live spot unavailable: {type(e).__name__}")
    print("  Live spot unavailable; will try latest observed pool swap")

print("\n▶ Fetching Raydium swap history...")
print(f"  → Pool: {pool_id}")
swaps = fetch_raydium_swaps(pool_id)
print(f"  → {len(swaps)} swaps")
alef_trade_history = _build_alef_px_series(swaps)
if ALEF_PRICE_USD is None and alef_trade_history:
    last_ts, last_px = alef_trade_history[-1]
    if 0 <= NOW.timestamp()-last_ts <= 7*86400:
        ALEF_PRICE_USD = last_px
        ALEF_PRICE_SOURCE = f"Last observed pool trade at {datetime.fromtimestamp(last_ts,timezone.utc):%Y-%m-%d %H:%M UTC} (not live spot)"
if ALEF_PRICE_USD is None:
    print("  ALEF current quote unavailable; not substituting an invented price")
else:
    print(f"  ALEF=${ALEF_PRICE_USD:.8f} — {ALEF_PRICE_SOURCE}")

print("\n▶ Fetching current prices...")
prices = fetch_current_prices()
print(f"  BTC={prices.get('BTC',0):,.0f}  ETH={prices.get('ETH',0):,.0f}  "
      f"BNB={prices.get('BNB',0):,.0f}  SOL={prices.get('SOL',0):,.0f}")
print("  ALEF: " + (f"${ALEF_PRICE_USD:.8f} ({ALEF_PRICE_SOURCE})" if ALEF_PRICE_USD is not None else "UNAVAILABLE"))

print("\n▶ Fetching ALEF mint/burn history (Solana)...")
mb_events = fetch_alef_mint_burn_history(prices)
print(f"  → {len(mb_events)} events")
chart_start = int(pd.to_datetime(AUDIT_START_DATE, utc=True).timestamp()) if AUDIT_START_DATE else min((t["ts"] for t in mb_events+swaps),default=int(NOW.timestamp()))
print("\n▶ Fetching Raydium website chart history (15-minute ALEF/USDC candles)...")
previous_settlement = max((t["ts"] for t in mb_events if t.get("mint")==ALEF_MINT and t["ts"]<chart_start), default=chart_start)
alef_chart_history = fetch_alef_chart_history(min(chart_start,previous_settlement)-7*86400,int(NOW.timestamp()))
print(f"  → {len(alef_chart_history)} completed chart candles; {len(alef_trade_history)} on-chain trade price observations")

print("\n▶ Fetching EVM (BSC) history (NodeReal indexed)...")
bsc_txns = fetch_bsc_history(prices)
print(f"  → {len(bsc_txns)} external transfers")

print("\n▶ Fetching EVM (Ethereum) history...")
eth_txns = fetch_evm_history("ethereum", prices)
print(f"  → {len(eth_txns)} external transfers")

print("\n▶ Fetching Tron history...")
tron_txns = fetch_tron_history(prices)
print(f"  → {len(tron_txns)} external transfers")

print("\n▶ Fetching Bitcoin history...")
btc_txns = fetch_btc_history(prices)
print(f"  → {len(btc_txns)} transactions")

print("\n▶ Fetching TON (Gram) history...")
ton_txns = fetch_ton_history(prices)
print(f"  → {len(ton_txns)} transfers")

print("\n▶ Fetching both Solana custody wallets and token accounts...")
sol1_txns = fetch_sol_wallet_external_txns(SOL_WALLET, "Sol-wallet-1", prices)
sol2_txns = fetch_sol_wallet_external_txns(SOL_WALLET_2, "Sol-wallet-2", prices)
print(f"  → {len(sol2_txns)} transfers")


# ── Accounting policy ─────────────────────────────────────────────────────────
# USD 1 is a presentation/materiality threshold, not a deletion rule.
# Unknown assets and small receipts are kept separately for review.
DUST_USD = 1.0
# Confirm economic purpose using full transaction references. Do not infer from a wallet name.
# Values: subscription, redemption, founder_advance, founder_repayment,
# founder_withdrawal, expense, internal, trading, other.
CONFIRMED_PURPOSE = {}
OPENING_FOUNDER_RECEIVABLE = None  # signed USD: positive = founder owes fund
# For verified exchange/bridge groups enter BOTH sides, including actual fees in expense ledger.
CONFIRMED_REBALANCE_GROUPS = []  # list of lists of (chain, full transaction hash)
cutoff_ts = int(pd.to_datetime(AUDIT_START_DATE, utc=True).timestamp()) if AUDIT_START_DATE else 0
all_txns = sorted([t for t in mb_events+swaps+bsc_txns+eth_txns+tron_txns+btc_txns+ton_txns+sol1_txns+sol2_txns if t["ts"]>=cutoff_ts],key=lambda t:t["ts"])
# Load daily history once per ticker rather than per event.
stable_symbols = {"USDC","USDT","BUSD","DAI","FDUSD","TUSD","PYUSD","USD₮"}
crypto_symbols = {"BTC","ETH","BNB","SOL","TON","TRX"}
def ticker_for(asset):
    if asset == "TON": return "TON11419-USD"
    if asset in crypto_symbols: return asset+"-USD"
    return _PRICE_ALIASES.get(asset) or _XSTOCK_TICKERS.get(asset)
series={}
cg_series={}
start=datetime.fromtimestamp(min((t["ts"] for t in all_txns),default=NOW.timestamp()),timezone.utc).date()-timedelta(days=10)
for ticker in sorted({ticker_for(t["asset"]) for t in all_txns}-{None}):
    try:
        data=yf.download(ticker,start=str(start),end=str(NOW.date()+timedelta(days=1)),progress=False,auto_adjust=False)
        close=data["Close"]
        if isinstance(close,pd.DataFrame): close=close.iloc[:,0]
        series[ticker]=close.dropna()
    except Exception as e: AUDIT_WARNINGS.append(f"Price history unavailable {ticker}: {type(e).__name__}")
def _cg_history(asset):
    cid=_CG_IDS.get(asset.upper())
    if not cid: return []
    if cid not in cg_series:
        try:
            start_ts=int(datetime.combine(start,datetime.min.time(),tzinfo=timezone.utc).timestamp())
            d=_get(f"https://api.coingecko.com/api/v3/coins/{cid}/market_chart/range",params={"vs_currency":"usd","from":start_ts,"to":int(NOW.timestamp())})
            cg_series[cid]=sorted((float(ms)/1000,float(p)) for ms,p in d["prices"] if math.isfinite(float(p)) and float(p)>0)
        except Exception as e:
            cg_series[cid]=[]
            AUDIT_WARNINGS.append(f"CoinGecko history unavailable {asset}: {type(e).__name__}")
    return cg_series[cid]
def _cg_at(asset,ts):
    points=_cg_history(asset)
    i=bisect.bisect_right(points,(ts,float("inf")))-1
    if i>=0 and ts-points[i][0]<=7*86400: return points[i][1]
    return None
def historical_detail(asset,ts,chain=None,quantity_basis="raw"):
    if asset == "ALEF":
        p,src=alef_historical_detail(ts,alef_chart_history,alef_trade_history)
        if p is None and ALEF_PRICE_USD and NOW.timestamp()-ts<=7*86400: return ALEF_PRICE_USD,"Raydium last spot price"
        return p,src
    if asset in stable_symbols: return 1.0,"USD par assumption"
    # Prefer actual gold token quotes to a gold futures proxy.
    if asset.upper() in {"XAUT","PAXG","TON","TQQQON"}:
        p=_cg_at(asset,ts)
        if p is not None: return p,"CoinGecko token market quote"
    ticker=ticker_for(asset)
    day=datetime.fromtimestamp(ts,timezone.utc).date()
    p=None
    if ticker in series:
        ser=series[ticker]
        # Use completed prior daily close, avoiding future information on the transfer day.
        v=ser[[x.date()<day for x in ser.index]]
        if len(v) and (day-v.index[-1].date()).days<=7:
            candidate=float(v.iloc[-1])
            if math.isfinite(candidate) and candidate>0: p=candidate
    if p is None:
        p=_cg_at(asset,ts)
        if p is not None: return p,"CoinGecko prior market quote"
        return None,"No historical quote"
    if asset in _XSTOCK_TICKERS or asset in {"PPLTX","PPLTx","SLVon","TQQQon"}:
        if chain in _XSTOCK_NETWORKS and asset.upper() in _XSTOCK_RAW_SYMBOLS:
            factor,source=xstock_factor(asset,chain,ts,quantity_basis)
            if factor is None:return None,f"{ticker} available; {source}"
            return p*factor,f"{ticker} prior close × {factor:.9g} ({source})"
        if ALLOW_UNVERIFIED_SHARE_PROXY:
            return p,f"{ticker} prior close; underlying share proxy"
        return None,f"{ticker} available; multiplier unverified"
    return p,f"{ticker} prior close"+(" (underlying proxy)" if asset in _PRICE_ALIASES else "")
def historical(asset,ts):
    return historical_detail(asset,ts)[0]
pool_refs={t["ref"] for t in swaps}|{t["ref"] for t in sol1_txns+sol2_txns if t.get("counterparty")==pool_id}
fund_sol={SOL_WALLET,SOL_WALLET_2}
internal_refs={(chain,ref) for group in CONFIRMED_REBALANCE_GROUPS for chain,ref in group}
records=[]
for t in all_txns:
    asset=t["asset"]; typ=t["type"]; ref=t["ref"]; chain=t["chain"]
    if typ not in ("raydium_buy","raydium_sell","alef_mint","alef_burn") and asset not in stable_symbols and ticker_for(asset) is None:
        QUARANTINE.append(dict(chain=chain,asset=asset,ref=ref,reason="unsupported asset identity",raw=t))
        continue
    sign=1 if t["is_inflow"] else -1
    p,price_source=historical_detail(asset,t["ts"],chain,t.get("quantity_basis","raw"))
    amount=None if p is None else float(t["qty"])*p
    purpose=CONFIRMED_PURPOSE.get((chain,ref))
    cp=t.get("counterparty") or ""
    if typ in ("raydium_buy","raydium_sell"):
        bucket="pool market activity"; amount=float(t["qty"]); price_source="Observed pool USDC movement"
    elif typ in ("alef_mint","alef_burn"):
        bucket="token supply activity"
        amount=None if p is None else float(t["qty"])*p
        price_source += " (issuance valuation proxy)"
    elif purpose=="internal" or (chain,ref) in internal_refs or ref in VERIFIED_INTERNAL_REFS:
        bucket="confirmed internal"
    elif chain=="solana" and cp in fund_sol:
        bucket="confirmed internal"
    elif chain=="solana" and ref in RAYDIUM_LP_REFS and cp==pool_id:
        bucket="LP custody movement"
    elif chain=="solana" and ref in pool_refs and cp==pool_id:
        bucket="pool custody movement"
    elif purpose in {"subscription","redemption","founder_advance","founder_repayment","founder_withdrawal","expense","trading","other"}:
        bucket=purpose
    elif amount is None:
        bucket="unpriced custody movement"
    elif sign>0 and amount<DUST_USD and asset in stable_symbols|crypto_symbols:
        bucket="dust receipt (review)"
    elif chain=="solana" and ref in pool_refs|RAYDIUM_LP_REFS:
        bucket="pool-related custody review"
    elif t.get("raw_fallback"):
        bucket="raw custody delta review"
    else:
        bucket="unclassified custody movement"
    records.append({"Date":t["dt"],"Chain":chain,"Wallet":t.get("wallet",""),"Asset":asset,"Quantity":sign*float(t["qty"]),"USD":None if amount is None else sign*amount,"Price source":price_source,"Class":bucket,"Type":typ,"Counterparty":cp,"Ref":ref,"Description":t.get("description",""),"Contract":t.get("contract") or "","Raw quantity":str(t.get("raw_qty",""))})
ledger=pd.DataFrame(records,columns=["Date","Chain","Wallet","Asset","Quantity","USD","Price source","Class","Type","Counterparty","Ref","Description","Contract","Raw quantity"])
ledger["Date"]=pd.to_datetime(ledger["Date"],utc=True,errors="coerce")

PROTOCOL_TOPICS = {'0x2b627736bca15cd5381dcf80b0bf11fd197d01a037c52b927a881a10fb73ba61': ('aave', 'collateral_in', -1, 1), '0x3115d1449a7b732c986cba18244e897a450f61e1bb8d589cd2e69e6c8924f9f7': ('aave', 'collateral_out', 1, 0), '0xb3d084820fb1a9decffb176436bd02558d15fac9b0ddfed8c465bc7359d7dce0': ('aave', 'borrow', 1, 1), '0xa534c8dbe71f871f9f3530e97a74601fea17b426cae02e1c5aee42c96c784051': ('aave', 'repay', -1, 0), '0xa3b9472a1399e17e123f3c2e6586c23e504184d504de59cdaa2b375e880c6184': ('morpho', 'collateral_in', -1, 0), '0xe80ebd7cc9223d7382aab2e0d1d6155c65651f83d53c8b9b06901d167e321142': ('morpho', 'collateral_out', 1, 1), '0x570954540bed6b1304a87dfe815a5eda4a648f7097a16240dcd85c9b5fd42a43': ('morpho', 'borrow', 1, 1), '0x52acb05cebbd3cd39715469f22afbf5a17496295ef3bc9bb5944056c63ccaa09': ('morpho', 'repay', -1, 0)}
MORPHO_MARKET_SELECTOR = '0x2c3c9157'
# ── Consolidated economic classification ──
# Evidence sources: Aave IPool.sol, Morpho EventsLib.sol, Ethereum deployed pools.
AAVE_POOLS={"ethereum":{"0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"},"bsc":{"0x6807dc923806fe8fd134338eabca509979a7e0cb"}}
MORPHO_CORE="0xbbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb"
COW_SETTLEMENT="0x9008d19f58aabd9ed0d60971565aa8510560ab41"
RPC_URLS={"ethereum":"https://ethereum-rpc.publicnode.com","bsc":"https://bsc-mainnet.nodereal.io/v1/"+NODEREAL_API_KEY}
wallet_word=EVM_ADDR.lower()[2:].rjust(64,"0")
RPC_FALLBACKS = {
    "ethereum": ["https://eth.llamarpc.com", "https://ethereum.publicnode.com"],
    "bsc": ["https://bsc-rpc.publicnode.com"],
}
def evm_rpc(chain,method,params):
    errors=[]
    for url in dict.fromkeys([RPC_URLS[chain]]+RPC_FALLBACKS.get(chain,[])):
        for attempt in range(2):
            try:
                r=requests.post(url,json={"jsonrpc":"2.0","id":1,"method":method,"params":params},timeout=18)
                r.raise_for_status()
                d=r.json()
                if "error" in d:
                    err=d["error"]
                    raise ValueError(f"RPC error {err.get('code') if isinstance(err,dict) else 'unknown'}")
                if d.get("result") is None:
                    raise ValueError("null RPC result (transaction unavailable)")
                if method=="eth_getTransactionReceipt":
                    receipt=d["result"]
                    if not isinstance(receipt,dict) or receipt.get("transactionHash","").lower()!=params[0].lower():
                        raise ValueError("invalid receipt or transaction hash mismatch")
                return d["result"]
            except requests.HTTPError as e:
                errors.append(f"HTTP {e.response.status_code if e.response is not None else '?'}")
            except ValueError as e:
                errors.append(str(e)[:150])
            except Exception as e:
                errors.append(type(e).__name__)
            if attempt==0: time.sleep(0.5)
    # Etherscan proxy fallback for Ethereum receipts.
    if chain=="ethereum" and method=="eth_getTransactionReceipt":
        try:
            d=_get("https://api.etherscan.io/v2/api",params={"chainid":1,"module":"proxy",
                "action":"eth_getTransactionReceipt","txhash":params[0],"apikey":ETHERSCAN_KEY})
            receipt=d.get("result")
            if isinstance(receipt,dict) and receipt.get("transactionHash","").lower()==params[0].lower():
                return receipt
            errors.append("Etherscan proxy: no matching receipt")
        except Exception as e:
            errors.append("Etherscan proxy: "+type(e).__name__)
    raise RuntimeError(" | ".join(dict.fromkeys(errors)))
def words(data):
    data=data.removeprefix("0x").lower()
    return [data[i:i+64] for i in range(0,len(data),64) if len(data[i:i+64])==64]
def addr(word): return "0x"+word[-40:]
market_cache={}
def protocol_evidence(chain,ref):
    receipt=evm_rpc(chain,"eth_getTransactionReceipt",[ref]); result=[]
    if receipt.get("status")!="0x1": return []
    for log in receipt.get("logs",[]):
        topics=log.get("topics",[]); emitter=log.get("address","").lower()
        if not topics or topics[0].lower() not in PROTOCOL_TOPICS: continue
        proto,action,sign,amount_word=PROTOCOL_TOPICS[topics[0].lower()]
        if proto=="aave" and emitter not in AAVE_POOLS.get(chain,set()):continue
        if proto=="morpho" and (chain!="ethereum" or emitter!=MORPHO_CORE):continue
        indexed=[x[2:].lower() for x in topics[1:]]; data=words(log.get("data",""))
        # Match position owner, not any incidental address in the receipt.
        # Aave supply/borrow: onBehalfOf topic2; withdraw/repay: user topic2.
        # Morpho all four: onBehalf topic3 for supply/repay, topic2 for withdraw/borrow.
        owner_idx=1 if proto=="aave" or action in {"collateral_out","borrow"} else 2
        if len(indexed)<=owner_idx or indexed[owner_idx]!=wallet_word or len(data)<=amount_word:continue
        if proto=="aave": contract=addr(indexed[0])
        else:
            market_id="0x"+indexed[0]
            if market_id not in market_cache:
                try:
                    raw=evm_rpc(chain,"eth_call",[{"to":MORPHO_CORE,"data":MORPHO_MARKET_SELECTOR+market_id[2:]},"latest"])
                    market_cache[market_id]=words(raw)
                except Exception as e: raise RuntimeError("Morpho market parameters unavailable") from e
            params=market_cache[market_id]
            if len(params)<2:
                market_cache.pop(market_id,None)
                raise RuntimeError("Incomplete Morpho market parameters")
            contract=addr(params[1] if action.startswith("collateral") else params[0])
        result.append(dict(protocol=proto,action=action,sign=sign,contract=contract,raw=str(int(data[amount_word],16)),log_index=log.get("logIndex")))
    return result

def classify_economics(ledger, evidence):
    ledger=ledger.copy(); ledger["Evidence"]=""; ledger["Group"]=""
    # Match each protocol event to exactly one wallet leg (asset address, raw units, direction).
    for (chain,ref),g in ledger.groupby(["Chain","Ref"]):
        for e in evidence.get((chain,ref),[]):
            hits=g[(g["Contract"].str.lower()==e["contract"]) & (g["Raw quantity"]==e["raw"]) & (g.Quantity*e["sign"]>0) & (g.Class=="unclassified custody movement")]
            if len(hits)==1:
                i=hits.index[0]
                if ledger.at[i,"Evidence"]:continue
                ledger.loc[i,["Class","Evidence","Group"]]=[e["action"],f'{e["protocol"]} receipt log {e["log_index"]}, owner/asset/raw amount matched',ref]
        # Same-transaction opposite legs through a known CoW settlement are a trade, not capital.
        a=ledger.loc[g.index]; a=a[(a.Class=="unclassified custody movement") & (a.Counterparty.str.lower()==COW_SETTLEMENT)]
        if chain=="ethereum" and len(a)==2 and a.Asset.nunique()==2 and (a.Quantity>0).any() and (a.Quantity<0).any():
            ledger.loc[a.index,["Class","Evidence","Group"]]=["trade","Two opposite asset legs through CoW settlement in one transaction",ref]
        # Other two-sided transactions remain suggestions; never classify whole tx by hash alone.
        a=ledger.loc[g.index]; a=a[a.Class=="unclassified custody movement"]
        if len(a)>1 and a.Asset.nunique()>1 and (a.Quantity>0).any() and (a.Quantity<0).any():
            ledger.loc[a.index,["Class","Evidence","Group"]]=["atomic exchange review","Opposite asset legs in same transaction; purpose not verified",ref]
    for i,r in ledger.iterrows():
        action=VERIFIED_LEG_ACTIONS.get((r.Chain,r.Ref,r.Asset,1 if r.Quantity>0 else -1))
        if action in {"collateral_in","collateral_out","borrow","repay","trade","internal"}:
            ledger.loc[i,["Class","Evidence"]]=[action,"User-confirmed leg purpose"]
        elif r.Class=="unclassified custody movement" and r.Chain in RPC_URLS and r.Counterparty.lower() in PROTOCOL_ADDRS|{MORPHO_CORE,"0x38b0c12ab81976e9417d4ebfe2a34db6df22e6ad"}|AAVE_POOLS.get(r.Chain,set()):
            ledger.loc[i,["Class","Evidence"]]=["protocol review","Known protocol counterparty; action/position not yet verified"]
    return ledger
# Query receipts once per material EVM transaction, parallel with bounded concurrency.
keys=sorted(set(zip(ledger.loc[ledger.Chain.isin(RPC_URLS)&(ledger.USD.abs()>=1),"Chain"],ledger.loc[ledger.Chain.isin(RPC_URLS)&(ledger.USD.abs()>=1),"Ref"])))
print(f"\n▶ Inspecting {len(keys)} material EVM transaction receipts for lending actions...")
from concurrent.futures import ThreadPoolExecutor, as_completed
# Cache only successfully decoded, complete receipt evidence. Never cache RPC failures.
from pathlib import Path
receipt_cache_path=Path.home()/".alef_audit"/"protocol_evidence_v2.json"
cache_namespace="receipt-v2:"+EVM_ADDR.lower()
try:
    cache_document=json.loads(receipt_cache_path.read_text())
    if cache_document.get("namespace")!=cache_namespace: cache_document={}
except (OSError,ValueError): cache_document={}
receipt_cache=cache_document.get("entries",{})
if not isinstance(receipt_cache,dict): receipt_cache={}
def receipt_cache_key(key): return key[0]+":"+key[1].lower()
receipts={key:receipt_cache[receipt_cache_key(key)] for key in keys
          if isinstance(receipt_cache.get(receipt_cache_key(key)),list)}
print(f"  → {len(receipts)} previously decoded receipts recovered from cache")
with ThreadPoolExecutor(max_workers=4) as ex:
    futures={ex.submit(protocol_evidence,*key):key for key in keys if key not in receipts}
    for f in as_completed(futures):
        key=futures[f]
        try:
            receipts[key]=f.result()
            receipt_cache[receipt_cache_key(key)]=receipts[key]
        except Exception as e: AUDIT_WARNINGS.append(f"Receipt review incomplete {key[0]} {key[1]}: {e}")
try:
    receipt_cache_path.parent.mkdir(parents=True,exist_ok=True)
    tmp=receipt_cache_path.with_suffix(".tmp")
    tmp.write_text(json.dumps({"namespace":cache_namespace,"entries":receipt_cache}))
    os.replace(str(tmp),str(receipt_cache_path))
except OSError as e: AUDIT_WARNINGS.append(f"Could not persist receipt cache: {type(e).__name__}")
ledger=classify_economics(ledger,receipts)
# Prior successful audit output (2026-11-26 03:16 UTC) classified these exact
# PYUSD legs as repayments. Preserve that evidence if fresh decoding fails.
# This is a prior-run fallback, not a newly independently verified receipt.
prior_repayments={
    "0xc05088b31906b51544741d3ff018288e5df0970abd60757dd5979fa75f1bfcbc":4992.5257,
    "0x616d459d94fa19574796d94ca6182b2de28e696cc190e5ac4fceb9d7fb1aee85":3045.0,
}
for ref,qty in prior_repayments.items():
    hit=ledger[(ledger.Chain=="ethereum") & (ledger.Ref.str.lower()==ref) &
               (ledger.Asset.str.upper()=="PYUSD") & ((ledger.Quantity+qty).abs()<0.00006)]
    if len(hit)==1:
        i=hit.index[0]
        if ledger.at[i,"Class"] in {"unclassified custody movement","protocol review","raw custody delta review"}:
            ledger.loc[i,["Class","Evidence","Group"]]=["repay","Prior successful run: receipt-derived repayment; exact reference/asset/quantity matched",ref]
            AUDIT_WARNINGS.append("Prior-run repayment fallback used: "+ref)
# Separate small outgoing operational transfers too, but keep them in custody reconciliation.
small=(ledger.Class=="unclassified custody movement") & (ledger.USD<0) & (ledger.USD.abs()<1)
ledger.loc[small,"Class"]="small outgoing review"

# ── One economic flow ledger ────────────────────────────────────────────────
# Identified direct lending/LP operations change the location of fund assets or
# principal liabilities, not the external transfer balance. Keep the raw leg.
for i,r in ledger.iterrows():
    cp=str(r.Counterparty or "")
    key=cp.lower() if r.Chain in ("ethereum","bsc") else cp
    endpoint=LENDING_ENDPOINTS.get(r.Chain,{}).get(key)
    if endpoint and r.Class in {"unclassified custody movement","protocol review","raw custody delta review","atomic exchange review"}:
        ledger.at[i,"Class"]="protocol custody (internal)"
        ledger.at[i,"Evidence"]=endpoint+"; verified protocol endpoint, principal classification approximate"

# Explicitly distinguish original capital-flow diagnostic from the direct wallet movement.
# Exclude identified internal principal/LP legs; keep same-transaction trades as signed
# historical value differences, so pricing/transaction costs remain visible.
INTERNAL_CLASSES={"confirmed internal","internal","collateral_in","collateral_out","borrow","repay","protocol custody (internal)","LP custody movement","pool custody movement"}

def build_reverse(frame, now):
    a=frame.copy()
    a["Raw USD"]=pd.to_numeric(a["USD"],errors="coerce")
    a["Net USD"]=a["Raw USD"]
    a.loc[a.Class.isin(INTERNAL_CLASSES),"Net USD"]=0.0
    a.loc[a.Class=="pool market activity","Net USD"]=a.loc[a.Class=="pool market activity","Raw USD"]*POOL_FLOW_SHARE
    if not INCLUDE_ISSUANCE_OFFSET:
        a.loc[a.Class=="token supply activity","Net USD"]=0.0
    # Hide dust/small operation legs in the visible timeline, but INCLUDE their known
    # values in the full cumulative total. No blanket deletion of small withdrawals.
    small=a["Raw USD"].notna() & (a["Raw USD"].abs()<DUST_LIMIT_USD) & ~a.Class.isin(["token supply activity"])
    # Atomic timestamps: same timestamp has the same after-event running balance.
    # This avoids inventing within-block ordering or false intermediate trade imbalances.
    by_time=a.groupby("Date",sort=True)["Net USD"].agg(net=lambda x:x.sum(min_count=1),missing=lambda x:x.isna().sum())
    by_time["Known net"]=by_time.net.fillna(0)
    # backward balance immediately AFTER this timestamp = minus all LATER flows.
    by_time["Balance vs Now"]=-(by_time["Known net"].iloc[::-1].cumsum().iloc[::-1]-by_time["Known net"])
    by_time["Unpriced later legs"]=by_time.missing.iloc[::-1].cumsum().iloc[::-1]-by_time.missing
    a=a.join(by_time[["Balance vs Now","Unpriced later legs"]],on="Date")
    a=a.sort_values(["Date","Ref"],ascending=[False,True])
    dust=a.loc[small.reindex(a.index)].copy()
    return a,a.loc[~small.reindex(a.index)].copy(),dust,by_time

# ── Match portfolio conversion legs (NOT ALEF/USDC market trading) ────────────
# Preserve all observed ledger flows. A matched withdrawal and deposit are NOT
# deleted: their actual value difference is the residual the cost credit explains.
# Use each leg at most once. Same-asset transfers, USDC/USDT and Raydium cash
# settlements receive no fee. Matching is an estimate absent exchange fills.
CONVERSION_MATCH_HOURS=24
CONVERSION_VALUE_TOL=0.03  # prior-close quotes can differ from execution prices
CONVERSION_MIN_USD=25.0
FREE_STABLE_PAIR={"USDC","USDT"}
ASSET_EQUIVALENTS={"WBTC":"BTC","CBBTC":"BTC","WETH":"ETH","WBNB":"BNB","WSOL":"SOL","USD₮":"USDT"}
def canonical_asset(a):
    a=str(a).upper()
    return ASSET_EQUIVALENTS.get(a,a)
def fee_free_pair(a,b):
    a,b=canonical_asset(a),canonical_asset(b)
    return a==b or {a,b}==FREE_STABLE_PAIR

def match_portfolio_conversions(frame, opening, now):
    a=frame.copy().reset_index(drop=True)
    a["Date"]=pd.to_datetime(a.Date,utc=True)
    a["USD"]=pd.to_numeric(a.USD,errors="coerce")
    eligible={"unclassified custody movement","raw custody delta review","trade","trading","atomic exchange review"}
    a=a.loc[(a.Date>opening)&(a.Date<=now)&(a.USD.abs()>=CONVERSION_MIN_USD)&
            a.Class.isin(eligible|{"pool market activity"})].copy()
    a["Pool"]=a.Class.eq("pool market activity")
    a["Canon"]=a.Asset.map(canonical_asset)
    a=a.loc[~a.Canon.isin({"ALEF","ALEF OLD"}) | a.Pool]
    rows={i:r for i,r in a.iterrows()}
    out=[i for i,r in rows.items() if r.USD<0]
    inc=[i for i,r in rows.items() if r.USD>0]
    used=set(); matches=[]
    def record(i,j,kind,source):
        o,d=rows[i],rows[j]; used.update((i,j))
        value=-float(o.USD)
        matches.append({"Date":max(o.Date,d.Date),"Kind":kind,"Asset out":o.Asset,"Asset in":d.Asset,
          "USD out":value,"USD in":float(d.USD),"Observed shortfall":value-float(d.USD),
          "Fee":value*TRADING_FEE_RATE if kind=="Portfolio conversion" else 0.0,
          "Out ref":str(o.Chain)+":"+str(o.Ref),"In ref":str(d.Chain)+":"+str(d.Ref),
          "Source":source,"Hours apart":abs((d.Date-o.Date).total_seconds())/3600})
    # First recognize genuine two-sided atomic trades (same chain/ref), not
    # independent receipts. No size-ratio gate on a known CoW execution.
    for (chain,ref),g in a.loc[~a.Pool].groupby(["Chain","Ref"]):
        outs=[i for i in g.index if i in out and i not in used]
        ins=[i for i in g.index if i in inc and i not in used]
        if len(outs)!=1 or len(ins)!=1:continue
        i,j=outs[0],ins[0]; o,d=rows[i],rows[j]
        if o.Class not in {"trade","trading","atomic exchange review"} or d.Class not in {"trade","trading","atomic exchange review"}:continue
        if not fee_free_pair(o.Asset,d.Asset) and o.Class!="trade" and abs(d.USD/(-o.USD)-1)>CONVERSION_VALUE_TOL:continue
        record(i,j,"Fee-free movement" if fee_free_pair(o.Asset,d.Asset) else "Portfolio conversion",
               "Same-transaction CoW trade" if o.Class==d.Class=="trade" else "Same-transaction opposing legs (inferred)")
    def match_pass(mode):
        # Score value similarity and time proximity, accept mutual best matches
        # only when there is a meaningful margin over the next candidate.
        candidates=[]
        for i in out:
            if i in used:continue
            o=rows[i]
            for j in inc:
                if j in used:continue
                d=rows[j]
                hrs=abs((d.Date-o.Date).total_seconds())/3600
                if hrs>CONVERSION_MATCH_HOURS or (o.Pool and d.Pool):continue
                ratio=float(d.USD)/(-float(o.USD))
                if mode=="free":
                    if o.Pool or d.Pool or not fee_free_pair(o.Asset,d.Asset):continue
                    if abs(ratio-1)>0.01:continue
                    score=abs(ratio-1)+hrs/2400
                elif mode=="pool":
                    if not (o.Pool ^ d.Pool):continue
                    cash=d if o.Pool else o
                    if cash.Canon not in FREE_STABLE_PAIR or hrs>6 or abs(ratio-1)>0.01:continue
                    score=abs(ratio-1)+hrs/2400
                else:
                    if o.Pool or d.Pool or fee_free_pair(o.Asset,d.Asset):continue
                    if abs(ratio-(1-TRADING_FEE_RATE))>CONVERSION_VALUE_TOL:continue
                    score=abs(ratio-(1-TRADING_FEE_RATE))+hrs/1200
                candidates.append((score,i,j))
        by_o={};by_i={}
        for item in sorted(candidates):
            _,i,j=item
            by_o.setdefault(i,[]).append(item);by_i.setdefault(j,[]).append(item)
        def clear(c): return len(c)==1 or c[1][0]-c[0][0]>=0.001
        for item in sorted(candidates):
            _,i,j=item
            if i in used or j in used:continue
            if by_o[i][0]!=item or by_i[j][0]!=item or not clear(by_o[i]) or not clear(by_i[j]):continue
            if mode=="free": kind="Fee-free movement"
            elif mode=="pool": kind="Raydium cash settlement (excluded)"
            else: kind="Portfolio conversion"
            record(i,j,kind,"Mutual best time/value match (inferred; not exchange fill)")
    match_pass("free")
    match_pass("pool")
    match_pass("conversion")
    # Unmatched legs remain in the raw residual and are not charged a fee.
    unmatched=a.loc[~a.index.isin(used)&~a.Pool].copy()
    cols=["Date","Kind","Asset out","Asset in","USD out","USD in","Observed shortfall","Fee","Out ref","In ref","Source","Hours apart"]
    return pd.DataFrame(matches,columns=cols),unmatched

conversion_matches,unmatched_conversion_legs=match_portfolio_conversions(
    ledger,pd.to_datetime(cutoff_ts,unit="s",utc=True),pd.Timestamp(NOW))
# ── Contractual/estimated fee schedule ───────────────────────────────────────
# Trading credit is 0.5% of a matched portfolio conversion's outgoing notional,
# once per pair, not the difference between two prior-close valuations.
# Management accrues on NAV throughout the audit window; settlements are reported separately.
def build_fee_schedule(mb, supply_events, conversions, supply_now, now_ts, cutoff,
                       nav_history=None, quote_at=None):
    from collections import defaultdict
    end = float(now_ts)
    changes = defaultdict(float)
    for e in supply_events:
        if e.get("mint")==ALEF_MINT and e["ts"]<=end:
            changes[e["ts"]] += float(e["qty"])*(1 if e["type"]=="alef_mint" else -1)
    change_times = sorted(changes)
    # Roll the exact current on-chain supply back across all recorded mints/burns.
    running = supply_now - sum(changes.values()) if supply_now is not None else None
    supply_levels=[]
    for t in change_times:
        if running is not None: running += changes[t]
        supply_levels.append(running)
    def supply_at(t):
        if supply_now is None: return None
        i=bisect.bisect_right(change_times,t)-1
        return supply_levels[i] if i>=0 else supply_now-sum(changes.values())
    navs = None
    if nav_history is not None:
        navs=pd.Series(nav_history,dtype=float).copy()
        navs.index=pd.to_datetime(navs.index,utc=True)
        navs=navs[navs.map(lambda v: math.isfinite(v) and v>0)].sort_index()
        navs=navs[~navs.index.duplicated(keep="last")]
    nav_times=[] if navs is None else [t.timestamp() for t in navs.index]
    nav_values=[] if navs is None else navs.tolist()
    def nav_at(t):
        if nav_times:
            i=bisect.bisect_right(nav_times,t)-1
            if i>=0 and t-nav_times[i]<=7*86400:return nav_values[i]
            return None
        q=supply_at(t); px=quote_at(t) if quote_at else None
        if q is None or q<0 or px is None or not math.isfinite(px) or px<=0:return None
        return q*px
    settlement_refs=defaultdict(set)
    for e in mb:
        if e.get("mint")==ALEF_MINT and e["ts"]<=end:
            settlement_refs[e["ts"]].add(e["ref"])
    settlements=sorted(settlement_refs)
    def accrual_intervals(lo,hi):
        # Integrate only over the selected audit window. NAV is held constant
        # between observations; fee accrues pro rata in elapsed UTC seconds.
        if hi<=lo:return []
        points={lo,hi}
        points.update(t for t in change_times if lo<t<hi)
        points.update(t for t in nav_times if lo<t<hi)
        points.update(t for t in settlements if lo<t<hi)
        if not nav_times:
            points.update(t for t,p in alef_chart_history+alef_trade_history if lo<t<hi)
        points.update(range((int(lo)//86400+1)*86400,int(hi),86400))
        points=sorted(points); intervals=[]
        for a,b in zip(points,points[1:]):
            nav=nav_at(a)
            intervals.append((a,b,0.0 if nav is None else nav*ANNUAL_FEE_RATE*(b-a)/(365.25*86400),
                              b-a if nav is None else 0.0))
        return intervals
    result=[]
    start=float(cutoff) if cutoff else min([end]+change_times+settlements+nav_times)
    intervals=accrual_intervals(start,end)
    for a,b,amount,missing in intervals:
        result.append(dict(Date=pd.to_datetime(b,unit="s",utc=True),Kind="Management accrual",
                           Fee=amount,Incomplete=missing>0,Missing_seconds=missing,
                           Ref="",Source="0.5% annual rate × "+("supplied historical NAV" if nav_times else "market-cap NAV proxy")))
    # Settlements are informational: amounts already accrue above and must NOT
    # be added to the benchmark a second time. Exclude pre-opening entitlement.
    settlement_summary=[]
    prev=start
    for t in settlements:
        if not start<t<=end:continue
        covered=accrual_intervals(prev,t)
        settlement_summary.append(dict(Date=pd.to_datetime(t,unit="s",utc=True),
            Kind="Estimated management settlement (audit-period portion)",
            Fee=sum(x[2] for x in covered),Missing_seconds=sum(x[3] for x in covered),
            Ref="; ".join(sorted(settlement_refs[t]))))
        prev=t
    unsettled_intervals=accrual_intervals(prev,end)
    unsettled=sum(x[2] for x in unsettled_intervals)
    unsettled_missing=sum(x[3] for x in unsettled_intervals)
    for _,e in conversions.iterrows():
        if e["Kind"]!="Portfolio conversion" or not cutoff<e.Date.timestamp()<=end:continue
        result.append(dict(Date=e.Date,Kind="Portfolio trading cost credit",
                           Fee=float(e.Fee),Incomplete=False,Missing_seconds=0.0,
                           Ref=e["Out ref"]+" → "+e["In ref"],
                           Source="0.5% × outgoing conversion notional; "+e.Source))
    return pd.DataFrame(result,columns=["Date","Kind","Fee","Incomplete","Missing_seconds","Ref","Source"]),unsettled,unsettled_missing,pd.DataFrame(settlement_summary,columns=["Date","Kind","Fee","Missing_seconds","Ref"])

try:
    _supply_resp=None
    for _att in range(4):
        _r=_sol_rpc("getTokenSupply",[ALEF_MINT,{"commitment":"finalized"}])
        if _r is not None:
            _supply_resp=_r
            break
        time.sleep(2**_att)
    if _supply_resp is None:
        raise ValueError("getTokenSupply returned None after retries")
    supply_response=_supply_resp["value"]
    fee_supply_now=int(supply_response["amount"])/10**int(supply_response["decimals"])
except Exception as e:
    # Fall back to reconstructing supply from observed mint/burn history
    _derived=sum(ev["qty"]*(1 if ev["type"]=="alef_mint" else -1)
                 for ev in RAW_ALEF_SUPPLY_EVENTS if ev.get("mint")==ALEF_MINT)
    fee_supply_now=_derived if _derived>0 else None
    AUDIT_WARNINGS.append(f"Fee benchmark: live supply unavailable ({type(e).__name__}); using {'derived estimate '+str(round(_derived,2)) if fee_supply_now else 'None — management fee will be zero'}")
fee_nav_history=globals().get("ALEF_NAV_HISTORY")
fee_schedule, unsettled_management_fee, unsettled_missing, estimated_management_settlements=build_fee_schedule(
    mb_events,RAW_ALEF_SUPPLY_EVENTS,conversion_matches,fee_supply_now,NOW.timestamp(),cutoff_ts,
    nav_history=fee_nav_history,quote_at=lambda t:alef_historical_detail(t,alef_chart_history,alef_trade_history)[0])
fee_nav_source="Supplied historical NAV" if fee_nav_history is not None and len(fee_nav_history) else "Estimated NAV = historical ALEF market price × reconstructed live-mint supply"
# ── Per-leg trading fee: 0.5% on every non-stable, non-ALEF eligible leg ──────
# Covers exchange fees, slippage, and round-trip costs; stablecoin flows (USDC,
# USDT, DAI etc.) are exempt — moving USDT to USDC is not a trade.
_STABLE_CANONS={"USDC","USDT","DAI","FDUSD","BUSD","TUSD","FRAX","USDP","USDE","PYUSD","USDM","USDS","CRVUSD","GUSD","LUSD","SUSD","EURS"}
_TRADE_ELIGIBLE={"unclassified custody movement","raw custody delta review","trade","trading","atomic exchange review"}
_per_leg_rows=[]
for _,_lr in ledger.iterrows():
    if _lr.get("Class") not in _TRADE_ELIGIBLE:
        continue
    _lts=_lr["Date"].timestamp() if hasattr(_lr["Date"],"timestamp") else float(_lr["Date"])
    if not (cutoff_ts<_lts<=NOW.timestamp()):
        continue
    if str(_lr.get("Ref","")) in pool_refs:
        continue
    _canon=canonical_asset(str(_lr.get("Asset","")))
    if _canon in _STABLE_CANONS or _canon in {"ALEF","ALEF OLD"}:
        continue
    _usd=pd.to_numeric(_lr.get("USD"),errors="coerce")
    if pd.isna(_usd) or abs(float(_usd))<0.001:
        continue
    _direction="receipt" if _usd>0 else "withdrawal"
    _per_leg_rows.append({"Date":_lr["Date"],"Kind":"Portfolio trading cost credit",
        "Fee":abs(float(_usd))*0.005,"Incomplete":False,"Missing_seconds":0.0,
        "Ref":str(_lr.get("Ref","")),"Source":f"0.5% × {_lr['Asset']} {_direction} ${abs(float(_usd)):,.2f}"})
fee_schedule=fee_schedule.loc[fee_schedule.Kind!="Portfolio trading cost credit"].copy()
if _per_leg_rows:
    fee_schedule=pd.concat([fee_schedule,pd.DataFrame(_per_leg_rows,columns=fee_schedule.columns)],ignore_index=True).sort_values("Date").reset_index(drop=True)
# ── Per-transaction gas cost recovery ────────────────────────────────────────
# Charged once per unique on-chain transaction ref; Raydium ops excluded via
# pool_refs; ALEF mint/burn excluded by asset filter.
_GAS_FEE={
    ('solana',True):0.10,  ('solana',False):0.10,
    ('bsc',True):0.10,     ('bsc',False):0.10,
    ('ton',True):0.50,     ('ton',False):0.10,
    ('ethereum',True):0.50,('ethereum',False):0.50,
    ('tron',True):2.00,    ('tron',False):2.00,
    ('bitcoin',True):2.00, ('bitcoin',False):2.00,
}
_gas_rows=[]; _seen_gas_refs=set()
for _,_lr in ledger.iterrows():
    if _lr.get("Class") not in _TRADE_ELIGIBLE: continue
    _ref=str(_lr.get("Ref",""))
    if _ref in pool_refs or _ref in _seen_gas_refs: continue
    _lts=_lr["Date"].timestamp() if hasattr(_lr["Date"],"timestamp") else float(_lr["Date"])
    if not (cutoff_ts<_lts<=NOW.timestamp()): continue
    _canon=canonical_asset(str(_lr.get("Asset","")))
    if _canon in {"ALEF","ALEF OLD"}: continue
    _usd=pd.to_numeric(_lr.get("USD"),errors="coerce")
    if pd.isna(_usd) or abs(float(_usd))<0.001: continue
    _chain=str(_lr.get("Chain","")).lower()
    _is_dep=float(_usd)>0
    _flat=_GAS_FEE.get((_chain,_is_dep))
    if _flat is None: continue
    _seen_gas_refs.add(_ref)
    _gas_rows.append({"Date":_lr["Date"],"Kind":"Gas cost recovery",
        "Fee":_flat,"Incomplete":False,"Missing_seconds":0.0,
        "Ref":_ref,"Source":f"${_flat:.2f} flat · {_lr['Chain']} {'deposit' if _is_dep else 'withdrawal'}"})
fee_schedule=fee_schedule.loc[fee_schedule.Kind!="Gas cost recovery"].copy()
if _gas_rows:
    fee_schedule=pd.concat([fee_schedule,pd.DataFrame(_gas_rows,columns=fee_schedule.columns)],ignore_index=True).sort_values("Date").reset_index(drop=True)
def make_backward_fee(schedule):
    """Positive add-back of fee withdrawals strictly AFTER the given timestamp."""
    by_time=schedule.groupby("Date")["Fee"].sum().sort_index()
    times=[t.timestamp() for t in by_time.index]
    suffix=[0.0]*(len(times)+1)
    for i in range(len(times)-1,-1,-1):
        suffix[i]=suffix[i+1]+float(by_time.iloc[i])
    def at(date,include_same=False):
        ts=pd.Timestamp(date).timestamp()
        i=(bisect.bisect_left if include_same else bisect.bisect_right)(times,ts)
        return suffix[i]
    return at

calculated_backward_fee=make_backward_fee(fee_schedule)
# Optional verified cash-fee withdrawals from independent records or confirmed
# on-chain transfers. Each record: Date (actual UTC payment timestamp), Kind
# ("Management" or "Trading"), Fee (positive USD actually withdrawn), Ref (unique
# payment reference; append a leg identifier if one tx contains multiple fees).
# Supply before this cell as ALEF_VERIFIED_FEE_WITHDRAWALS (list of dicts/DataFrame).
# Set ALEF_FEE_WITHDRAWALS_COMPLETE=True only if all fee payments are accounted for.
# Do not put theoretical fees or unrelated transfer amounts in this input.
verified_input=globals().get("ALEF_VERIFIED_FEE_WITHDRAWALS")
verified_fees=pd.DataFrame(columns=["Date","Kind","Fee","Ref"])
if verified_input is not None:
    verified_fees=pd.DataFrame(verified_input).copy()
    if not verified_fees.empty:
        required={"Date","Kind","Fee","Ref"}
        if not required.issubset(verified_fees.columns):
            raise ValueError("Verified fee records require Date, Kind, Fee, Ref")
        verified_fees["Date"]=pd.to_datetime(verified_fees["Date"],utc=True,errors="raise")
        verified_fees["Fee"]=pd.to_numeric(verified_fees["Fee"],errors="raise")
        if (verified_fees.Date.isna().any() or not verified_fees.Fee.map(lambda v:math.isfinite(v) and v>=0).all()
            or verified_fees.Ref.isna().any() or verified_fees.Ref.astype(str).str.strip().eq("").any()
            or verified_fees.Ref.duplicated().any() or not verified_fees.Kind.isin(["Management","Trading"]).all()):
            raise ValueError("Invalid or duplicate verified fee record")
        verified_fees=verified_fees.loc[(verified_fees.Date>=pd.to_datetime(cutoff_ts,unit="s",utc=True)) & (verified_fees.Date<=pd.Timestamp(NOW))].copy()
    else:
        verified_fees=pd.DataFrame(columns=["Date","Kind","Fee","Ref"])
verified_complete=verified_input is not None and bool(globals().get("ALEF_FEE_WITHDRAWALS_COMPLETE",False))
verified_backward_fee=make_backward_fee(verified_fees)
# Opening is immediately AFTER the cutoff transaction. Neither series is
# normalized at NOW. Net deposits = signed net fund inflows.
reverse,visible,dust,by_time=build_reverse(ledger,NOW)
opening=pd.to_datetime(cutoff_ts,unit="s",utc=True) if cutoff_ts else (
    reverse.Date.min() if len(reverse) else pd.Timestamp(NOW))
now_point=pd.Timestamp(NOW)

def make_opening_cumulative(values, opening, now, sign=1.0):
    """Independent forward cumulative sum, after opening through t inclusive."""
    opening,now=pd.Timestamp(opening),pd.Timestamp(now)
    if now<opening: raise ValueError("Audit opening is after current time")
    values=values.groupby(level=0).sum().sort_index()
    if values.empty: return lambda date: 0.0
    values=values.loc[(values.index>opening)&(values.index<=now)]
    if not values.empty and not values.map(math.isfinite).all():
        raise ValueError("Nonfinite values in cumulative series")
    times=[t.timestamp() for t in values.index]
    prefix=[0.0]
    for v in values: prefix.append(prefix[-1]+sign*float(v))
    def at(date):
        ts=min(pd.Timestamp(date),now).timestamp()
        return prefix[bisect.bisect_right(times,ts)]
    return at

# ── Borrowing interest reconstructed from historical on-chain debt ────────────
# Interest = closing debt - opening debt - new borrow principal + repayments.
# All amounts first in loan-token base units. No current-balance × APR estimate.
# Aave V4 includes the risk premium; Morpho accrues its borrow-share index at
# each historical block; Euler uses debtOf. Only covered positions are summed.
# Interest is a FUND expense, not manager remuneration. Internal interest is
# included on both sides of the economic chart, because the custody ledger
# excludes borrow/repay transfers. An already observed external interest expense
# can be credited against the residual only with independently verified refs.
import functools

# Ethereum Keccak-256 (NOT hashlib.sha3_256). Use installed eth_utils or Crypto,
# otherwise use the bundled selector table generated from the documented ABIs.
_INTEREST_ABI = {'Borrow(address,uint256)': '0xcbc04eca7e9da35cb1393a6135a199ca52e450d5e9251cbd99f7847d33a36750', 'Borrow(address,uint256,uint256,uint256)': '0x13ed6866d4e1ee6da46f845c46d7e54120883d75c5ea9a2dacc1c4ca8984ab80', 'Borrow(bytes32,address,address,address,uint256,uint256)': '0x570954540bed6b1304a87dfe815a5eda4a648f7097a16240dcd85c9b5fd42a43', 'Borrow(uint256,address,address,uint256,uint256)': '0xef18174796a5d2f91d51dc5e907a4d7867bbd6e800f6225168e0453d581d0dcd', 'Liquidate(address,address,address,uint256,uint256)': '0x8246cc71ab01533b5bebc672a636df812f10637ad720797319d5741d5ebb3962', 'Liquidate(bytes32,address,address,uint256,uint256,uint256,uint256,uint256)': '0xa4946ede45d0c6f06a0f5ce92c9ad3b4751452d2fe0e25010783bcab57a67e41', 'LiquidateBorrow(address,address,uint256,address,uint256)': '0x298637f684da70674f26509b10f07ec2fbc77a335ab1e7d6215a4b2484d8bb52', 'LiquidationCall(uint256,uint256,address,address,bool,uint256,uint256,(int256,int256,uint256),uint256,uint256,uint256)': '0x2a1f12d996f530f89d8038aa293f9fde81cac44b6dfd6225e3358d09b78a4a37', 'PullDebt(address,address,uint256)': '0xe6d0bfd9025bf59969101a13cf02e3ba2811b533816c47d7155546c7c8a1048f', 'Repay(address,uint256)': '0x5c16de4f8b59bd9caf0f49a545f25819a895ed223294290b408242e72a594231', 'Repay(bytes32,address,address,uint256,uint256)': '0x52acb05cebbd3cd39715469f22afbf5a17496295ef3bc9bb5944056c63ccaa09', 'Repay(uint256,address,address,uint256,uint256,(int256,int256,uint256))': '0xd765a0263e8a360da8dd4fdb8c0dc5553adec12a96f29a462cdb45e5bea407dd', 'RepayBorrow(address,address,uint256,uint256,uint256)': '0x1a2a22cb034d26d1854bdc6666a5b91fe25efbbb5dcad3b0355478d6f5c362a1', 'asset()': '0x38d52e0f1dbe7a70d1f1bbce52487d111fd5a226368cd8ae0e1fc641c0299139', 'borrowBalanceCurrent(address)': '0x17bfdfbc470798dfc48d52d1eddabddfa8b8b9511839bfcae88d66cf89851e21', 'borrowRateView((address,address,address,address,uint256),(uint128,uint128,uint128,uint128,uint128,uint128))': '0x8c00bf6ba9f28eac57753f4c26d930190e427f0575a20e721486c4c9e7daf014', 'debtOf(address)': '0xd283e75f6f914f593072d7dfecf53d0fb46a759ef0ea0df0190540f8a5bc982c', 'decimals()': '0x313ce567add4d438edf58b94ff345d7d38c45b17dfc0f947988d7819dca364f9', 'getReserve(uint256)': '0x77778db30ddbbd58d238fdee79ae5d424a0b2234dd9db2b95eb713548d1571aa', 'getUserTotalDebt(uint256,address)': '0x9b7172a6612b51cd8851b60fb2c020dec6080612fec81eb47bf3f8db1141a643', 'idToMarketParams(bytes32)': '0x2c3c915717aa624ad13c9e8e8431a9f6f0b888c080c546f358ea4c4fece73b60', 'market(bytes32)': '0x5c60e39ac0d7b21e2fa891758c5fbc086b4201452fba8ca8abc7419e25aea533', 'position(bytes32,address)': '0x93c52062628e4eb42860e48e7b53e762fe381fd26ace9c0767e2a4c01aa3212b', 'underlying()': '0x6f307dc33eda939db5102f62714675974157fd7019165a7f825f844496510d79'}
_INTEREST_ABI.update({'getAssetsIn(address)': '0xabfceffc7191895ac00a4bbdf817691528aec1222eea5b284c12d7b6cfeab83e', 'Transfer(address,address,uint256)': '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', 'positionsNftIdOfUser(address)': '0xc67b5093f5fe9e79467028a12e3a78c8e7c7dc3c0226a620d45e26361dbf44e9', 'positionByNftId(uint256)': '0x144128e8396543a3e3ed5d43e136adccddd17c1a0e1d32d357c20777997639f6', 'LogOperate(address,uint256,int256,int256,address)': '0xfef64760e30a41b9d5ba7dd65ff7236a61d89ed8b44c67a29e84db1a67513a1c', 'LogLiquidate(address,uint256,uint256,address)': '0x80fd9cc6b1821f4a510e45ffce6852ea3404807b5d3d833ffa85664408afcb66'})
def _it_hash(sig): return _INTEREST_ABI[sig]
def _it_word(v):
    return (f'{v:064x}' if isinstance(v,int) else str(v).removeprefix('0x').lower().rjust(64,'0'))

def _it_rpc(chain,method,params):
    # Archive-capable endpoints are preferred; each failing endpoint is skipped.
    # Never substitute latest state for a historical block.
    explicit=os.getenv({'ethereum':'ALEF_ETH_ARCHIVE_RPC','bsc':'ALEF_BSC_ARCHIVE_RPC'}[chain])
    node='https://'+('eth' if chain=='ethereum' else 'bsc')+'-mainnet.nodereal.io/v1/'+NODEREAL_API_KEY
    extra={'ethereum':['https://ethereum-rpc.publicnode.com','https://eth.drpc.org','https://mainnet.gateway.tenderly.co'],
           'bsc':['https://bsc-rpc.publicnode.com','https://bsc.drpc.org']}[chain]
    urls=list(dict.fromkeys(([explicit] if explicit else [])+[node]+extra))
    preferred=_IT_RPC_PREFERRED.get((chain,method))
    if preferred in urls:urls.remove(preferred);urls.insert(0,preferred)
    errors=[]
    for url in urls:
        try:
            r=requests.post(url,json={'jsonrpc':'2.0','id':1,'method':method,'params':params},timeout=15)
            r.raise_for_status();d=r.json()
            if 'error' in d or d.get('result') is None:raise RuntimeError(str(d.get('error','null RPC result'))[:180])
            _IT_RPC_PREFERRED[(chain,method)]=url
            return d['result']
        except Exception as e:errors.append(type(e).__name__+': '+str(e).replace(url,'[RPC]')[:200])
    if chain=='ethereum' and method in ('eth_blockNumber','eth_getBlockByNumber'):
        try:
            q={'chainid':1,'module':'proxy','action':method,'apikey':ETHERSCAN_KEY}
            if method=='eth_getBlockByNumber':q.update(tag=params[0],boolean='false')
            d=_get('https://api.etherscan.io/v2/api',params=q)
            if d.get('result') is not None and 'error' not in d:return d['result']
        except Exception:pass
    raise RuntimeError(' | '.join(dict.fromkeys(errors)))
_IT_RPC_PREFERRED={}

@functools.lru_cache(maxsize=None)
def _it_block(chain,n):
    d=_it_rpc(chain,'eth_getBlockByNumber',[hex(n),False]);return int(d['timestamp'],16)

def _it_block_at(chain,ts,hi):
    # Highest block timestamp <= cutoff, using chain data, not guessed blocks/day.
    # Explorer timestamp lookup avoids dozens of RPC calls. Verify boundary.
    try:
        d=_get('https://api.etherscan.io/v2/api',params={'chainid':1 if chain=='ethereum' else 56,'module':'block','action':'getblocknobytime','timestamp':int(ts),'closest':'before','apikey':ETHERSCAN_KEY})
        n=int(d['result'])
        if 0<=n<=hi and _it_block(chain,n)<=ts and (n==hi or _it_block(chain,n+1)>ts):return n
    except Exception:pass
    lo=0
    while lo<hi:
        mid=(lo+hi+1)//2
        if _it_block(chain,mid)<=ts:lo=mid
        else:hi=mid-1
    return lo

def _it_call(chain,contract,sig,args,block):
    raw=_it_rpc(chain,'eth_call',[{'to':contract,'data':_it_hash(sig)[:10]+''.join(_it_word(a) for a in args)},hex(block)])
    w=words(raw)
    if not w: raise ValueError('Empty historical contract response')
    return w

_IT_LOG_CACHE={}
_IT_INDEX_AVAILABLE={}
def _it_indexed_logs(chain,contract,topics,start,end):
    # Etherscan v2 indexed API. Page in bounded ranges; confirm topic matches.
    if _IT_INDEX_AVAILABLE.get(chain) is False:raise RuntimeError('Indexed logs unavailable on this chain')
    q={'chainid':1 if chain=='ethereum' else 56,'module':'logs','action':'getLogs','fromBlock':start,'toBlock':end,'offset':1000,'apikey':ETHERSCAN_KEY}
    if contract:q['address']=contract
    slots=[i for i,v in enumerate(topics) if v is not None]
    for i in slots:q['topic'+str(i)]=topics[i]
    for x,y in zip(slots,slots[1:]):q[f'topic{x}_{y}_opr']='and'
    seen=set();out=[]
    for page in range(1,51):
        q['page']=page;d=_get('https://api.etherscan.io/v2/api',params=q);r=d.get('result')
        if d.get('status')=='0' and 'no records' in str(d.get('message','')).lower():
            _IT_INDEX_AVAILABLE[chain]=True;return out
        if d.get('status')!='1' or not isinstance(r,list):
            msg=str(r)[:150]
            if any(x in msg.lower() for x in ('free api','not supported','invalid api key','subscription')):_IT_INDEX_AVAILABLE[chain]=False
            raise RuntimeError('Indexed logs: '+msg)
        _IT_INDEX_AVAILABLE[chain]=True
        for l in r:
            key=(l['transactionHash'],l['logIndex']); t=l['topics']
            if key in seen:raise RuntimeError('Repeated indexed page')
            if not start<=int(l['blockNumber'],16)<=end or (contract and l['address'].lower()!=contract.lower()) or any(i>=len(t) or t[i].lower()!=topics[i].lower() for i in slots):raise RuntimeError('Unexpected indexed log')
            seen.add(key);out.append(l)
        if len(r)<1000:return out
        time.sleep(.25)
    raise RuntimeError('Indexed log pagination incomplete')

def _it_logs(chain,contract,topics,start,end):
    if start>end:return []
    key=(chain,contract,tuple(topics),start,end)
    if key in _IT_LOG_CACHE:return _IT_LOG_CACHE[key]
    try:
        result=_it_indexed_logs(chain,contract,topics,start,end)
    except Exception as index_error:
        # Try wide RPC ranges, split only when needed. Do not silently return a partial scan.
        step=int(globals().get('ALEF_INTEREST_LOG_SPAN',1000000));budget=int(globals().get('ALEF_INTEREST_LOG_QUERY_LIMIT',120))
        result=[];pending=[(a,min(a+step-1,end)) for a in range(start,end+1,step)]
        while pending:
            a,b=pending.pop(0);budget-=1
            if budget<0:raise RuntimeError('Log query budget exhausted; indexed API: '+str(index_error)[:140]+'; configure archive/log RPC')
            q={'fromBlock':hex(a),'toBlock':hex(b),'topics':topics}
            if contract:q['address']=contract
            try:
                logs=_it_rpc(chain,'eth_getLogs',[q])
                if not isinstance(logs,list) or len(logs)>=1000:raise ValueError('Possible truncated log result')
                result.extend(logs)
            except Exception as e:
                if b-a<1000:raise RuntimeError('Log coverage failed: '+str(e)[:140])
                m=(a+b)//2;pending[:0]=[(a,m),(m+1,b)]
    unique={(l['transactionHash'],l['logIndex']):l for l in result if not l.get('removed',False)}
    out=sorted(unique.values(),key=lambda l:(int(l['blockNumber'],16),int(l['logIndex'],16)))
    _IT_LOG_CACHE[key]=out;return out

_IT_AAVE_B='Borrow(uint256,address,address,uint256,uint256)'
_IT_AAVE_R='Repay(uint256,address,address,uint256,uint256,(int256,int256,uint256))'
_IT_AAVE_L='LiquidationCall(uint256,uint256,address,address,bool,uint256,uint256,(int256,int256,uint256),uint256,uint256,uint256)'
_IT_MORPHO_B='Borrow(bytes32,address,address,address,uint256,uint256)'
_IT_MORPHO_R='Repay(bytes32,address,address,uint256,uint256)'
_IT_MORPHO_L='Liquidate(bytes32,address,address,uint256,uint256,uint256,uint256,uint256)'
_IT_EULER_B='Borrow(address,uint256)';_IT_EULER_R='Repay(address,uint256)'
_IT_EULER_P='PullDebt(address,address,uint256)';_IT_EULER_L='Liquidate(address,address,address,uint256,uint256)'
_IT_VENUS_B='Borrow(address,uint256,uint256,uint256)';_IT_VENUS_R='RepayBorrow(address,address,uint256,uint256,uint256)'
_IT_VENUS_L='LiquidateBorrow(address,address,uint256,address,uint256)'
_IT_OWNER='0x'+_it_word(EVM_ADDR)
_IT_HUBS={a for a,n in LENDING_ENDPOINTS['ethereum'].items() if 'Aave V4' in n}

def _it_morpho_debt(chain,contract,market,block):
    pos=_it_call(chain,contract,'position(bytes32,address)',[market,EVM_ADDR],block)
    shares=int(pos[1],16)
    if not shares:return 0
    mp=_it_call(chain,contract,'idToMarketParams(bytes32)',[market],block)
    state=_it_call(chain,contract,'market(bytes32)',[market],block)
    if len(mp)!=5 or len(state)!=6:raise ValueError('Unexpected Morpho ABI')
    assets,marketshares,last=map(lambda x:int(x,16),state[2:5]);elapsed=_it_block(chain,block)-last
    if elapsed<0:raise ValueError('Invalid market timestamp')
    if elapsed and assets and int(mp[3],16):
        rate=int(_it_call(chain,addr(mp[3]),'borrowRateView((address,address,address,address,uint256),(uint128,uint128,uint128,uint128,uint128,uint128))',mp+state,block)[0],16)
        # Morpho MathLib.wTaylorCompounded, integer arithmetic (WAD).
        first=rate*elapsed; second=first*first//(2*10**18); third=second*first//(3*10**18)
        assets+=assets*(first+second+third)//10**18
    # SharesMathLib uses VIRTUAL_SHARES=1e6 and VIRTUAL_ASSETS=1, round up.
    return (shares*(assets+1)+marketshares+10**6-1)//(marketshares+10**6)

def _it_interest_raw(open_debt,close_debt,borrowed,repaid):
    return close_debt-open_debt-borrowed+repaid

def _it_position(chain,proto,contract,key,events,first,last):
    # Never silently equate an unsupported token, liquidation or debt transfer to interest.
    if proto=='Aave V4':
        reserve=_it_call(chain,contract,'getReserve(uint256)',[key],last)
        if addr(reserve[1]) not in _IT_HUBS:raise ValueError('Spoke hub not in verified Aave hub list')
        token=addr(reserve[0]);dec=int(reserve[3],16)
        debt=lambda b:int(_it_call(chain,contract,'getUserTotalDebt(uint256,address)',[key,EVM_ADDR],b)[0],16)
    elif proto=='Morpho Blue':
        token=addr(_it_call(chain,contract,'idToMarketParams(bytes32)',[key],last)[0]);dec=int(_it_call(chain,token,'decimals()',[],last)[0],16)
        debt=lambda b:_it_morpho_debt(chain,contract,key,b)
    elif proto=='Euler':
        token=addr(_it_call(chain,contract,'asset()',[],last)[0]);dec=int(_it_call(chain,token,'decimals()',[],last)[0],16)
        debt=lambda b:int(_it_call(chain,contract,'debtOf(address)',[EVM_ADDR],b)[0],16)
    elif proto=='Venus':
        token=addr(_it_call(chain,contract,'underlying()',[],last)[0]);dec=int(_it_call(chain,token,'decimals()',[],last)[0],16)
        debt=lambda b:int(_it_call(chain,contract,'borrowBalanceCurrent(address)',[EVM_ADDR],b)[0],16)
    else:raise ValueError('Unsupported adapter')
    asset=(ETH_REGISTRY if chain=='ethereum' else BSC_REGISTRY).get(token)
    if not asset or not 0<=dec<=30:raise ValueError('Unverified loan token or decimals')
    if any(e[1]=='unsupported' for e in events):raise ValueError('Liquidation or debt transfer in window; manual reconciliation required')
    groups={}
    for block,kind,amount,ref in events:
        g=groups.setdefault(block,[0,0,[]]);g[0 if kind=='borrow' else 1]+=amount;g[2].append(ref)
    # Read actual debt immediately after each event block and at closing.
    # A deployed-but-inactive account returns zero. Never replace RPC errors with zero.
    def read(b):
        code=_it_rpc(chain,'eth_getCode',[contract,hex(b)])
        if code=='0x':return 0
        return debt(b)
    prev=first;d0=read(first);rows=[]
    for b in sorted(set(groups)|{last}):
        if b<=first:continue
        d1=read(b);borrow,repay,refs=groups.get(b,[0,0,[]]);raw=_it_interest_raw(d0,d1,borrow,repay)
        # Allow only tiny rounding noise (base units), never hide a principal gap.
        if raw < -max(3,len(refs)*3):raise ValueError('Negative inferred interest: incomplete principal/debt evidence')
        raw=max(raw,0)
        date=pd.to_datetime(_it_block(chain,b),unit='s',utc=True)
        px,src=historical_detail(asset,date.timestamp(),chain)
        if px is None or not math.isfinite(px) or px<=0:raise ValueError('Missing historical loan-asset quote')
        rows.append({'Date':date,'Chain':chain,'Protocol':proto,'Position':contract+':'+str(key),'Asset':asset,
                     'Opening block':prev,'Closing block':b,'Debt start':d0/10**dec,'Debt end':d1/10**dec,
                     'Borrowed':borrow/10**dec,'Repaid':repay/10**dec,'Interest units':raw/10**dec,
                     'Interest USD':raw/10**dec*px,'Price source':src,'Refs':'; '.join(refs),
                     'Source':'Historical contract debt + owner-indexed on-chain debt events'})
        prev,d0=b,d1
    return rows

_IT_COLS=['Date','Chain','Protocol','Position','Asset','Opening block','Closing block','Debt start','Debt end','Borrowed','Repaid','Interest units','Interest USD','Price source','Refs','Source']

# ── Additional lending adapters: Venus Core, Fluid / Flux, JustLend V2 ──────
# Sources: official Venus deployed markets; Fluid BNB VaultResolver/VaultFactory
# deployment ABI and T1 events; JustLend SBM V2 / TronGrid event and solidity APIs.
# All calls are read-only. Never broadcast. A failed position is UNKNOWN.
_VENUS_CORE='0xfd36e2c2a6789db23113685031d7f16329158384'
_VENUS_DEFAULT={'0xfd5840cd36d94d7229439859c0112a4185bc0255',
                '0xeca88125a5adbe82614ffc12d0db554e2e2867c8'}
_FLUID_RESOLVER='0xa5c3e16523eeeddcc34706b0e6be88b4c6ea95cc'
_FLUID_FACTORY='0x324c5dc1fc42c7a4d43d92df1eba58a54d13bf2d'
_TRON_MOOLAH='TDH4dhmVQQNc1ZNudJwWzBcs2h6ahhWrpp'
_ZERO='0x'+'0'*40

def _it_uints(w): return [int(x,16) for x in w]
def _it_signed(w):
    v=int(w,16);return v-2**256 if v>=2**255 else v

def _it_array(w):
    a=_it_uints(w)
    if len(a)<2 or a[0]!=32 or a[1]!=len(a)-2:raise ValueError('Unexpected dynamic array ABI')
    return a[2:]

def _it_venus_candidates(first,last,warn):
    candidates=set(_VENUS_DEFAULT)|{a.lower() for a in globals().get('ALEF_VENUS_DEBT_VTOKENS',[])}
    for b in (first,last):
        try:
            w=_it_call('bsc',_VENUS_CORE,'getAssetsIn(address)',[EVM_ADDR],b)
            candidates.update(f'0x{v:040x}' for v in _it_array(w))
        except Exception as e:warn('Venus Core','getAssetsIn',e)
    # vToken list is distinct from the Fluid NFT vaults used by Venus Flux.
    return candidates

def _it_fluid_positions(first,last,warn):
    chain='bsc'; owner=EVM_ADDR.lower(); r=_FLUID_RESOLVER; factory=_FLUID_FACTORY
    def nfts(b):
        if _it_rpc(chain,'eth_getCode',[r,hex(b)])=='0x':return set()
        return set(_it_array(_it_call(chain,r,'positionsNftIdOfUser(address)',[owner],b)))
    before,after=nfts(first),nfts(last)
    changes={}
    transfer=_it_hash('Transfer(address,address,uint256)')
    for topics in ([transfer,_IT_OWNER],[transfer,None,_IT_OWNER]):
        for l in _it_logs(chain,factory,topics,first+1,last):
            if len(l['topics'])!=4:raise ValueError('Unexpected NFT Transfer ABI')
            nft=int(l['topics'][3],16)
            changes.setdefault(nft,{})[(l['transactionHash'],l['logIndex'])]=l
    rows=[]; statuses=[]
    ids=before|after|set(changes)|set(map(int,globals().get('ALEF_FLUID_NFT_IDS',[])))
    for nft in sorted(ids):
        try:
            moves=list(changes.get(nft,{}).values())
            mints=[];burns=[]
            for l in moves:
                frm,to=addr(l['topics'][1]),addr(l['topics'][2]); b=int(l['blockNumber'],16)
                if frm==_ZERO and to==owner:mints.append(b)
                elif frm==owner and to==_ZERO:burns.append(b)
                elif frm!=to:raise ValueError('NFT ownership changed; manual debt attribution required')
            if len(mints)>1 or len(burns)>1:raise ValueError('Unexpected multiple NFT mint/burn')
            if nft not in before and not mints:raise ValueError('NFT opening ownership unverified')
            if nft not in after and not burns:raise ValueError('NFT closing ownership unverified')
            live_first=first if nft in before else mints[0]
            live_last=last if nft in after else burns[0]-1
            if live_last<live_first:raise ValueError('NFT created and closed in same block; manual reconciliation')
            sample=_it_call(chain,r,'positionByNftId(uint256)',[nft],live_last)
            # Deployed BNB v1.0.0 resolver returns two static tuples. UserPosition
            # has 12 words, then VaultEntireData starts at word 12. Borrow is
            # already net of dust, per resolver source. Never subtract it twice.
            if len(sample)<30 or int(sample[0],16)!=nft or addr(sample[1])!=owner:raise ValueError('Resolver NFT ABI/owner mismatch')
            vault=addr(sample[12]);smart=int(sample[14],16);token=addr(sample[25])
            if smart!=0 or addr(sample[26])!=_ZERO:raise ValueError('Smart debt uses DEX shares, not token units')
            asset=BSC_REGISTRY.get(token)
            if not asset:raise ValueError('Unregistered Fluid loan token '+token)
            dec=int(_it_call(chain,token,'decimals()',[],live_last)[0],16)
            if not 0<=dec<=30:raise ValueError('Invalid debt token decimals')
            def debt(b):
                if b<live_first or (burns and b>=burns[0]):return 0
                w=_it_call(chain,r,'positionByNftId(uint256)',[nft],b)
                if len(w)<30 or int(w[0],16)!=nft or addr(w[1])!=owner or addr(w[12])!=vault or int(w[14],16)!=0 or addr(w[25])!=token or addr(w[26])!=_ZERO:raise ValueError('Historical resolver ABI/identity changed')
                if int(w[2],16)!=0:raise ValueError('NFT liquidation observed; manual reconciliation required')
                return int(w[10],16)
            groups={}
            for l in _it_logs(chain,vault,[_it_hash('LogOperate(address,uint256,int256,int256,address)')],first+1,last):
                d=words(l['data'])
                if len(d)!=5 or len(l['topics'])!=1:raise ValueError('Unexpected Fluid operate ABI')
                if int(d[1],16)!=nft:continue
                b=int(l['blockNumber'],16); delta=_it_signed(d[3])
                g=groups.setdefault(b,[0,0,[]]);g[0]+=max(delta,0);g[1]+=max(-delta,0);g[2].append(l['transactionHash'])
            # Any liquidation block is inspected against our NFT, not counted as interest.
            for l in _it_logs(chain,vault,[_it_hash('LogLiquidate(address,uint256,uint256,address)')],first+1,last):
                b=int(l['blockNumber'],16)
                if live_first<=b<=live_last:groups.setdefault(b,[0,0,[]])
            # One point per day makes continuous interest visible rather than
            # placing the entire opening-to-present cost at the last block.
            checkpoints={first,last}|set(groups)|set(mints)|set(burns)
            for t in pd.date_range(pd.to_datetime(_it_block(chain,first),unit='s',utc=True).ceil('D'),pd.to_datetime(_it_block(chain,last),unit='s',utc=True),freq='D'):
                checkpoints.add(_it_block_at(chain,t.timestamp(),last))
            d0=debt(first);prev=first;out=[]
            for b in sorted(checkpoints-{first}):
                d1=debt(b);borrow,repay,refs=groups.get(b,[0,0,[]]);raw=d1-d0-borrow+repay
                # Tick-based positions have rounding. Small negatives are explicitly
                # retained as signed financing adjustments, not clamped to zero.
                if raw < -max(3,int(max(d0,d1,borrow,repay)*0.00001)):
                    raise ValueError('Negative financing change beyond rounding tolerance; missing debt event or liquidation')
                date=pd.to_datetime(_it_block(chain,b),unit='s',utc=True)
                px,src=historical_detail(asset,date.timestamp(),chain)
                if px is None or not math.isfinite(px) or px<=0:raise ValueError('Loan price unavailable')
                out.append(dict(zip(_IT_COLS,[date,chain,'Fluid / Venus Flux',f'{vault}:NFT {nft}',asset,prev,b,d0/10**dec,d1/10**dec,borrow/10**dec,repay/10**dec,raw/10**dec,raw/10**dec*px,src,'; '.join(refs),'Historical Fluid NFT net debt + LogOperate; includes any debt-side financing charge not in operate delta'])));
                d0,prev=d1,b
            rows.extend(out);statuses.append({'Protocol':'Fluid / Venus Flux','Position':str(nft),'Status':'Reconstructed','Detail':f'{len(out)} intervals; ordinary single-token debt'})
        except Exception as e:warn('Fluid / Venus Flux',nft,e)
    if not ids:statuses.append({'Protocol':'Fluid / Venus Flux','Position':'NFT discovery','Status':'No positions found','Detail':'Checked opening and closing resolver and factory transfers'})
    return rows,statuses

# TRON does NOT support historical eth_call. Use confirmed current state and
# reverse the actual market debt events, rather than asking for a historical
# block and accidentally getting today's state. TronGrid indexed event API
# paginates by fingerprint. Only POSTED AccrueInterest events are included;
# the unposted tail and pre-opening component of the first posting are disclosed.
_TRON_GRID=os.getenv('ALEF_TRONGRID_URL','https://api.trongrid.io').rstrip('/')
_TRON_GRID_KEY=os.getenv('TRONGRID_API_KEY','')
_TRON_HEADERS={'TRON-PRO-API-KEY':_TRON_GRID_KEY} if _TRON_GRID_KEY else {}
_B58='123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def _it_tron_hex(a):
    a=str(a)
    if a.startswith('T'):
        n=0
        for c in a:n=n*58+_B58.index(c)
        z=n.to_bytes(25,'big'); payload=z[:-4]
        if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]!=z[-4:] or payload[0]!=65:raise ValueError('Invalid TRON address checksum')
        return '0x'+payload[1:].hex()
    s=a.removeprefix('0x').lower()
    if len(s)==64 and s[:24]=='0'*24:s=s[24:]
    if len(s)==42 and s.startswith('41'):s=s[2:]
    if len(s)!=40:raise ValueError('Invalid TRON address')
    int(s,16);return '0x'+s

def _it_tron_post(path,data):
    resp=requests.post(_TRON_GRID+path,json=data,headers=_TRON_HEADERS,timeout=25);resp.raise_for_status();return resp.json()
def _it_tron_head():
    d=_it_tron_post('/walletsolidity/getnowblock',{})['block_header']['raw_data'];return int(d['number']),int(d['timestamp'])
def _it_tron_call(contract,sig,args):
    d=_it_tron_post('/walletsolidity/triggerconstantcontract',{'owner_address':'41'+_it_tron_hex(TRON_ADDR)[2:],'contract_address':'41'+_it_tron_hex(contract)[2:], 'function_selector':sig,'parameter':''.join(_it_word(a) for a in args),'visible':False})
    if d.get('result',{}).get('result') is not True or not d.get('constant_result'):raise ValueError('TRON constant call failed: '+sig)
    w=words(d['constant_result'][0]);
    if not w:raise ValueError('Empty TRON contract result')
    return w

def _it_tron_events(name,lo,hi):
    if hi<lo:return []
    p={'event_name':name,'only_confirmed':'true','min_block_timestamp':lo,'max_block_timestamp':hi,'limit':200,'order_by':'block_timestamp,asc'}
    seen=set();out={};budget=int(globals().get('ALEF_TRON_EVENT_PAGE_LIMIT',500))
    for _ in range(budget):
        r=requests.get(_TRON_GRID+'/v1/contracts/'+_TRON_MOOLAH+'/events',params=p,headers=_TRON_HEADERS,timeout=30);r.raise_for_status();d=r.json()
        if d.get('success') is not True or not isinstance(d.get('data'),list):raise ValueError('TronGrid event request failed: '+name)
        for e in d['data']:
            if e.get('event_name')!=name or not lo<=int(e['block_timestamp'])<=hi:raise ValueError('Unexpected event or timestamp')
            key=(e['transaction_id'],int(e['event_index']));out[key]=e
        fp=d.get('meta',{}).get('fingerprint')
        if not fp:
            if len(d['data'])>=200:raise ValueError('Full TronGrid page without continuation; coverage uncertain')
            return list(out.values())
        if fp in seen:raise ValueError('TronGrid pagination repeated')
        seen.add(fp);p['fingerprint']=fp
        time.sleep(0.2)
    raise ValueError('TRON event page budget exhausted: '+name)

def _it_tron_marketid(v):
    s=str(v).removeprefix('0x').lower()
    if len(s)!=64:raise ValueError('Invalid Moolah market ID')
    int(s,16);return '0x'+s

def _it_tron_parse(e):
    r=e['result'];k=e['event_name']
    def field(name,i):
        if name in r:return r[name]
        return r[str(i)]
    def num(name,i):
        v=field(name,i);return int(v,16) if str(v).startswith('0x') else int(v)
    market=_it_tron_marketid(field('id',0));owner=None;assets=shares=0;interest=0;bad_assets=bad_shares=0
    if k=='AccrueInterest':interest=num('interest',2)
    elif k=='Borrow':owner=_it_tron_hex(field('onBehalf',2));assets=num('assets',4);shares=num('shares',5)
    elif k=='Repay':owner=_it_tron_hex(field('onBehalf',2));assets=num('assets',3);shares=num('shares',4)
    elif k=='Liquidate':
        owner=_it_tron_hex(field('borrower',2));assets=num('repaidAssets',3);shares=num('repaidShares',4);bad_assets=num('badDebtAssets',6);bad_shares=num('badDebtShares',7)
    else:raise ValueError('Unknown Moolah event')
    if min(assets,shares,interest,bad_assets,bad_shares)<0:raise ValueError('Negative unsigned Moolah event')
    return dict(market=market,kind=k,owner=owner,assets=assets,shares=shares,interest=interest,bad_assets=bad_assets,bad_shares=bad_shares,block=int(e['block_number']),ms=int(e['block_timestamp']),ref=e['transaction_id'],index=int(e['event_index']))

def _it_tron_sorted(events):
    # event_index is receipt-local; resolve transaction ordering for blocks
    # containing multiple distinct relevant transactions.
    by={}
    for e in events:by.setdefault(e['block'],set()).add(e['ref'])
    order={}
    for b,refs in by.items():
        if len(refs)>1:
            raw=_it_tron_post('/walletsolidity/getblockbynum',{'num':b})
            txs={t['txID']:i for i,t in enumerate(raw.get('transactions',[]))}
            if not refs.issubset(txs):raise ValueError('Cannot establish confirmed TRON transaction ordering')
            order[b]=txs
    return sorted(events,key=lambda e:(e['block'],order.get(e['block'],{}).get(e['ref'],0),e['index']))

def _it_tron_replay(events,assets,shares,user_shares,owner):
    # Reverse posted interest and principal events from the same solidified
    # state. Allocate posted market interest by the user's borrow-share fraction.
    # Moolah is Morpho-style; proportional allocation is an estimate (virtual
    # shares and base-unit rounding can differ), not an exact debt claim.
    result=[]
    for e in reversed(events):
        k=e['kind'];a=e['assets'];s=e['shares'];mine=e['owner']==owner
        if k=='AccrueInterest':
            i=e['interest']
            if i>assets or (i and not shares):raise ValueError('Inconsistent market interest replay')
            if user_shares and i:
                result.append((e,assets-i,assets,shares,user_shares,Decimal(i)*Decimal(user_shares)/Decimal(shares)))
            assets-=i
        elif k=='Borrow':
            assets-=a;shares-=s
            if mine:user_shares-=s
        else:
            if k=='Liquidate' and mine:raise ValueError('ALEF liquidation requires separate reconciliation')
            assets+=a+e['bad_assets'];shares+=s+e['bad_shares']
            if mine:user_shares+=s+e['bad_shares']
        if not 0<=user_shares<=shares or assets<0:raise ValueError('Negative/inconsistent TRON share replay; missing or misordered events')
    return result,(assets,shares,user_shares)

def _it_justlend_positions(opening,now,warn):
    start=int(opening.timestamp()*1000)+1; end=int(now.timestamp()*1000)
    owner=_it_tron_hex(TRON_ADDR); kinds=('Borrow','Repay','Liquidate','AccrueInterest')
    # Capture events before snapshotting; then fetch the small tail to the actual
    # confirmed snapshot. This also handles notebooks that took minutes to fetch.
    h0,t0=_it_tron_head()
    if t0<start:raise ValueError('Solidified TRON head precedes opening')
    events=[_it_tron_parse(e) for k in kinds for e in _it_tron_events(k,start,t0)]
    ids={e['market'] for e in events}|{_it_tron_marketid(x) for x in globals().get('ALEF_JUSTLEND_MARKET_IDS',[])}
    snapshots={};statuses=[];rows=[]
    for market in sorted(ids):
        try:
            # Skip inactive non-owner markets after a direct position read.
            probe=_it_tron_call(_TRON_MOOLAH,'position(bytes32,address)',[market,owner])
            if len(probe)!=3:raise ValueError('Unexpected Moolah position ABI')
            if not int(probe[1],16) and not any(e['market']==market and e['owner']==owner for e in events):continue
            # Read owner shares and market totals in the SAME confirmed block.
            for attempt in range(8):
                b0,ms0=_it_tron_head()
                p=_it_tron_call(_TRON_MOOLAH,'position(bytes32,address)',[market,owner]);m=_it_tron_call(_TRON_MOOLAH,'market(bytes32)',[market])
                b1,ms1=_it_tron_head()
                if b0==b1:break
            else:raise ValueError('Could not pin TRON snapshot to one solidified block')
            if len(p)!=3 or len(m)!=6:raise ValueError('Unexpected Moolah position/market ABI')
            a,s,u=int(m[2],16),int(m[3],16),int(p[1],16)
            # Check all active markets, including loans with no user events.
            if not u and not any(e['market']==market and e['owner']==owner for e in events):continue
            mp=_it_tron_call(_TRON_MOOLAH,'idToMarketParams(bytes32)',[market]);
            if len(mp)!=5:raise ValueError('Unexpected Moolah market params ABI')
            token=addr(mp[0]);asset={_it_tron_hex(TRON_USDT):'USDT'}.get(token)
            if not asset:raise ValueError('Unknown JustLend debt token '+token+'; extend verified registry')
            dec=int(_it_tron_call(token,'decimals()',[])[0],16)
            if not 0<=dec<=30:raise ValueError('Invalid loan token decimals')
            snapshots[market]=(b0,ms0,a,s,u,asset,dec,int(m[4],16))
        except Exception as e:warn('JustLend V2',market,e)
    if not snapshots:
        warn('JustLend V2','discovery','No borrower snapshot reconstructed; check market discovery/API coverage');return rows,statuses
    maxt=max(x[1] for x in snapshots.values())
    if maxt>t0:events.extend(_it_tron_parse(e) for k in kinds for e in _it_tron_events(k,t0+1,maxt))
    for market,(b0,ms0,a,s,u,asset,dec,last_update) in snapshots.items():
        try:
            ev=_it_tron_sorted([e for e in events if e['market']==market and e['block']<=b0])
            # A recorded lastUpdate inside the interval must have a matching
            # market accrual event. Zero-rate updates can emit none; flag rather
            # than assume completeness if that evidence is missing.
            if last_update*1000>start and not any(e['kind']=='AccrueInterest' and e['ms']//1000==last_update for e in ev):raise ValueError('Market lastUpdate does not match indexed accrual event; possible index lag or zero-rate update')
            posted,opening_state=_it_tron_replay(ev,a,s,u,owner)
            out=[]
            # Include confirmed repayment events as separate rows, in addition to interest postings.
            for e,aa,ab,ss,us,interest in reversed(posted):
                if not start<=e['ms']<=end:continue
                date=pd.to_datetime(e['ms'],unit='ms',utc=True);px,src=historical_detail(asset,date.timestamp(),'tron')
                if px is None or not math.isfinite(px) or px<=0:raise ValueError('Historical loan quote unavailable')
                out.append(dict(zip(_IT_COLS,[date,'tron','JustLend V2',market,asset,e['block'],e['block'],aa*us/ss/10**dec,ab*us/ss/10**dec,0,0,float(interest/10**dec),float(interest/10**dec)*px,src,e['ref'],'Confirmed AccrueInterest × borrower share fraction; posted not exact accrued interest'])))
            for e in ev:
                if e['kind']!='Repay' or e['owner']!=owner or not start<=e['ms']<=end:continue
                date=pd.to_datetime(e['ms'],unit='ms',utc=True);px,src=historical_detail(asset,date.timestamp(),'tron')
                if px is None or not math.isfinite(px) or px<=0:raise ValueError('Historical repayment quote unavailable')
                out.append(dict(zip(_IT_COLS,[date,'tron','JustLend V2',market,asset,e['block'],e['block'],float('nan'),float('nan'),0,e['assets']/10**dec,0,0,src,e['ref'],'Confirmed borrower Repay; interest allocation estimated'])))
            rows.extend(out);statuses.append({'Protocol':'JustLend V2','Position':market,'Status':'Posted interest reconstructed (estimate)','Detail':f'{len(out)} postings; excludes unposted tail, first posting may include pre-opening accrual; snapshot block {b0}'})
        except Exception as e:warn('JustLend V2',market,e)
    return rows,statuses


def build_onchain_interest(opening,now):
    print('\n▶ Reconstructing lending interest from historical on-chain debt...')
    rows=[]; coverage=[]
    def warn(proto,pos,e):
        coverage.append({'Protocol':proto,'Position':str(pos),'Status':'INCOMPLETE — excluded','Detail':str(e)[:250]})
    def process(chain,proto,contract,key,events,first,last):
        try:
            out=_it_position(chain,proto,contract,key,events,first,last);rows.extend(out)
            coverage.append({'Protocol':proto,'Position':contract+':'+str(key),'Status':'Reconstructed','Detail':f'{len(out)} intervals; accrued, not necessarily paid'})
        except Exception as e:warn(proto,contract+':'+str(key),e)
    for chain in ('ethereum','bsc'):
        try:
            head=int(_it_rpc(chain,'eth_blockNumber',[]),16)
            first=_it_block_at(chain,opening.timestamp(),head);last=_it_block_at(chain,now.timestamp(),head)
            if last<=first:raise ValueError('Invalid block interval')
        except Exception as e:warn(chain,'all',e);continue
        if chain=='ethereum':
            for proto,contract,sigs,owner_slot in [('Aave V4',None,[_IT_AAVE_B,_IT_AAVE_R,_IT_AAVE_L],3),('Morpho Blue',MORPHO_CORE,[_IT_MORPHO_B,_IT_MORPHO_R,_IT_MORPHO_L],None)]:
                try:
                    groups={}
                    for sig in sigs:
                        slot=owner_slot if owner_slot else (2 if sig==_IT_MORPHO_B else 3)
                        topics=[_it_hash(sig)]+[None]*(slot-1)+[_IT_OWNER]
                        logs=_it_logs(chain,contract,topics,first+1,last)
                        for l in logs:
                            c=l['address'].lower(); t=l['topics'];d=words(l['data']);k=t[1] if proto=='Morpho Blue' else int(t[2 if sig==_IT_AAVE_L else 1],16)
                            action='unsupported' if sig in (_IT_AAVE_L,_IT_MORPHO_L) else ('borrow' if sig in (_IT_AAVE_B,_IT_MORPHO_B) else 'repay')
                            amount=0 if action=='unsupported' else int(d[1 if proto=='Aave V4' or sig==_IT_MORPHO_B else 0],16)
                            groups.setdefault((c,k),[]).append((int(l['blockNumber'],16),action,amount,l['transactionHash']))
                    # Optional verified opening-only positions, even if no debt activity in window.
                    for p in globals().get('ALEF_INTEREST_EXTRA_POSITIONS',[]):
                        if p['chain']==chain and p['protocol']==proto:groups.setdefault((p['contract'].lower(),p['key']),[])
                    if not groups:warn(proto,'discovery','No borrower events; opening-only positions require explicit IDs')
                    for (c,k),events in groups.items():process(chain,proto,c,k,events,first,last)
                except Exception as e:warn(proto,'discovery',e)
        else:
            euler_vaults={'0x8f68128438c1101550bf478bbe8f8c80749eb794','0xf4940cde23c164f8ca8d536f3567337349b3208f'}
            venus_vaults=_it_venus_candidates(first,last,warn)
            try:
                fl_rows,fl_status=_it_fluid_positions(first,last,warn);rows.extend(fl_rows);coverage.extend(fl_status)
            except Exception as e:warn('Fluid / Venus Flux','NFT discovery',e)
            for proto,contracts,defs in [('Euler',euler_vaults, [(_IT_EULER_B,1,'borrow',0),(_IT_EULER_R,1,'repay',0),(_IT_EULER_P,1,'unsupported',0),(_IT_EULER_P,2,'unsupported',0),(_IT_EULER_L,2,'unsupported',0)]),('Venus',venus_vaults,[(_IT_VENUS_B,0,'borrow',1),(_IT_VENUS_R,0,'repay',2),(_IT_VENUS_L,0,'unsupported',0)])]:
                if not contracts:warn(proto,'discovery','No verified debt contracts found')
                for c in contracts:
                    try:
                        events=[]
                        if proto=='Venus':
                            endpoint_debt=[]
                            for b in (first,last):
                                if _it_rpc(chain,'eth_getCode',[c,hex(b)])=='0x':endpoint_debt.append(0)
                                else:endpoint_debt.append(int(_it_call(chain,c,'borrowBalanceCurrent(address)',[EVM_ADDR],b)[0],16))
                            if not any(endpoint_debt) and c not in _VENUS_DEFAULT and c not in {a.lower() for a in globals().get('ALEF_VENUS_DEBT_VTOKENS',[])}:
                                # The contract may still have opened and closed a loan during the period.
                                warn('Venus',c,'Zero boundary debt; non-default market not scanned for closed mid-period loans');continue
                        for sig,slot,kind,idx in defs:
                            # Legacy Venus events have unindexed borrower; fetch contract events and filter ABI data.
                            topics=[_it_hash(sig)]+([None]*(slot-1)+[_IT_OWNER] if slot else [])
                            for l in _it_logs(chain,c,topics,first+1,last):
                                d=words(l['data'])
                                if slot==0 and addr(d[0 if kind=='borrow' else 1])!=EVM_ADDR.lower():continue
                                events.append((int(l['blockNumber'],16),kind,0 if kind=='unsupported' else int(d[idx],16),l['transactionHash']))
                        process(chain,proto,c,'',events,first,last)
                    except Exception as e:warn(proto,c,e)
    # Explicitly incomplete protocol coverage: do not invent these interest amounts.
    try:
        tr_rows,tr_status=_it_justlend_positions(opening,now,warn);rows.extend(tr_rows);coverage.extend(tr_status)
    except Exception as e:warn('JustLend V2','TronGrid reconstruction',e)
    for p in ('Aave V3 / other positions',):
        warn(p,'not reconstructed','Requires verified market/position IDs and historical debt/event adapter; no APR fallback')
    warn('Discovery','opening-only positions','Aave/Morpho event discovery can omit inactive positions; provide verified ALEF_INTEREST_EXTRA_POSITIONS. TRON posted interest only; configure ALEF_JUSTLEND_MARKET_IDS for inactive markets. Venus Core covers USDT/USDC and discovered entered markets, not every isolated pool. No claim of complete lending coverage.')
    return pd.DataFrame(rows,columns=_IT_COLS),pd.DataFrame(coverage)

if 'interest_schedule' not in vars():
    import pandas as _pd_empty
    interest_schedule = _pd_empty.DataFrame(columns=_IT_COLS)
    interest_coverage = _pd_empty.DataFrame()
    # Interest removed from benchmark — bypass all interest computation
    external_interest = _pd_empty.DataFrame(columns=['Date','Interest USD','Ref'])
    external_extra = external_interest.copy()
    interest_at = lambda t: 0.0
    external_interest_at = lambda t: 0.0
    external_extra_at = lambda t: 0.0
    paid_at = lambda t: 0.0
# Optional externally verified interest expenses ALREADY present in the flow
# ledger: ALEF_INTEREST_EXTERNAL_REFS = {(chain, txhash): positive USD}.
# Only verified outflow legs may offset the residual; no inference from debt growth.
external_interest_rows=[]
for (chain,ref),amount in globals().get('ALEF_INTEREST_EXTERNAL_REFS',{}).items():
    g=reverse[(reverse.Chain==chain)&(reverse.Ref==ref)&(reverse.Date>opening)&(reverse.Date<=now_point)]
    amount=float(amount)
    if g.empty or not math.isfinite(amount) or amount<=0 or g.Date.nunique()!=1 or amount>max(0,-g['Net USD'].sum())+0.01:
        AUDIT_WARNINGS.append('Invalid external interest reference (not credited): '+str(ref));continue
    external_interest_rows.append({'Date':g.Date.iloc[0],'Interest USD':amount,'Ref':ref})
external_interest=pd.DataFrame(external_interest_rows,columns=['Date','Interest USD','Ref'])
# Repayments do not normally split principal from interest on-chain. Allocate
# *in-window* accrued interest first, in loan units, then remaining payment to
# principal. This is a documented accounting convention, not an observed split.
# Opening debt may contain older interest, which this calculation excludes.
def allocate_period_interest(schedule, quote):
    out=schedule.copy()
    out['Interest paid units']=0.0;out['Interest paid USD']=0.0
    out['Unpaid period interest units']=0.0
    for _,g in out.groupby(['Chain','Protocol','Position','Asset'],sort=False):
        outstanding=0.0
        # Within a timestamp, accrual precedes repayment by convention. EVM
        # records are block-level; TRON postings and repayments are timestamped.
        g=g.assign(_repay_only=(g['Interest units']==0)&(g.Repaid>0)).sort_values(['Date','Closing block','_repay_only'],kind='stable')
        for i,r in g.iterrows():
            outstanding=max(0.0,outstanding+float(r['Interest units']))
            paid=min(outstanding,max(0.0,float(r.Repaid)))
            outstanding-=paid
            out.at[i,'Interest paid units']=paid
            if paid:
                px=quote(r.Asset,r.Date.timestamp(),r.Chain)[0]
                if px is None or not math.isfinite(px) or px<=0:raise ValueError('Missing repayment-time price')
                out.at[i,'Interest paid USD']=paid*px
            out.at[i,'Unpaid period interest units']=outstanding
    return out
# The requested expense benchmark uses period interest allocated to repayments.
# It is a COST-ADJUSTED DIAGNOSTIC, not an assertion that ALEF owes the manager
# every dollar of loan interest. A manager-funded deposit already counted in
# raw deposits must not also be treated as an independently verified credit.
# Exclude overlaps with explicitly verified external payment refs.
paid_refs=set()
for _,r in (interest_schedule.loc[interest_schedule['Interest paid USD']>0].iterrows() if 'Interest paid USD' in interest_schedule.columns else iter([])):
    paid_refs.update((r.Chain,ref.strip().lower()) for ref in str(r.Refs).split(';') if ref.strip())
external_extra=external_interest.copy()
# External refs can be disjoint from the on-chain protocol repayment schedule.
# Where identical refs appear, use the allocated paid amount only once.
if not external_extra.empty:
    overlap={ref for _,ref in paid_refs}
    external_extra=external_extra.loc[~external_extra.Ref.str.lower().isin(overlap)]
raw_deposits_at=make_opening_cumulative(by_time['Known net'],opening,now_point,sign=1.0)
deposits_at=raw_deposits_at
active_schedule=fee_schedule
contractual_fees_at=make_opening_cumulative(fee_schedule.groupby('Date')['Fee'].sum(),opening,now_point)
def fees_at(t):return contractual_fees_at(t)+external_extra_at(t)
verified_paid_at=make_opening_cumulative(verified_fees.groupby('Date')['Fee'].sum(),opening,now_point)
_mgmt_sched=fee_schedule.loc[fee_schedule.Kind=='Management accrual']
_trade_sched=fee_schedule.loc[fee_schedule.Kind=='Portfolio trading cost credit']
mgmt_fees_at=make_opening_cumulative(_mgmt_sched.groupby('Date')['Fee'].sum() if not _mgmt_sched.empty else pd.Series(dtype=float),opening,now_point)
trade_fees_at=make_opening_cumulative(_trade_sched.groupby('Date')['Fee'].sum() if not _trade_sched.empty else pd.Series(dtype=float),opening,now_point)
baseline_label='Negative management fees (partial coverage)'
net_deposits_now=deposits_at(now_point)
fees_since_opening=fees_at(now_point)
fee_credit_now=-fees_since_opening
present_gap=net_deposits_now-fee_credit_now
for frame in (reverse,visible,dust):
    frame['Net deposits since opening']=pd.Series([deposits_at(t) for t in frame.Date],index=frame.index,dtype=float)
    frame['Cumul. mgmt fee']=pd.Series([-mgmt_fees_at(t) for t in frame.Date],index=frame.index,dtype=float)
    frame['Cumul. trading fee']=pd.Series([-trade_fees_at(t) for t in frame.Date],index=frame.index,dtype=float)
    frame['Cumulative fee credits']=pd.Series([-contractual_fees_at(t) for t in frame.Date],index=frame.index,dtype=float)
    frame['Cumulative negative cost benchmark']=pd.Series([-fees_at(t) for t in frame.Date],index=frame.index,dtype=float)
    frame['Fee-adjusted deviation']=frame['Net deposits since opening']-frame['Cumulative negative cost benchmark']
# State now. Prefer the actual output from Price_update rather than inventing a NAV.
# If a preceding cell has not provided ALEF_CURRENT_STATE, query direct holdings now.
# Current wallet balances are only a partial view: debt, collateral, LPs and exchanges
# belong to the full Price_update portfolio. All values here are explicitly scoped.
print("\n=== STATE NOW (UTC) ===",NOW.isoformat())
if globals().get("ALEF_CURRENT_STATE") is not None:
    print("Supplied upstream snapshot displayed unchanged; verify its own xStocks multiplier handling.")
    display(ALEF_CURRENT_STATE)
else:
    current=[]; current_errors=[]
    def state_add(chain,wallet,asset,qty):
        if not qty:return
        p=prices.get(asset)
        if asset in stable_symbols:p=1.0
        factor,source=xstock_factor(asset,chain,NOW.timestamp(),current=True)
        if chain in _XSTOCK_NETWORKS and asset.upper() in _XSTOCK_RAW_SYMBOLS:
            p=prices.get(_XSTOCK_TICKERS.get(asset) or _XSTOCK_TICKERS.get(_XSTOCK_RAW_SYMBOLS[asset.upper()]))
        if p is not None and (not math.isfinite(float(p)) or p<=0):p=None
        scaled=qty*factor if factor is not None else None
        current.append(dict(Chain=chain,Wallet=wallet,Asset=asset,Quantity=qty,
                            Multiplier=factor,**{"Share-equivalent quantity":scaled,"Multiplier source":source},
                            USD=scaled*p if p is not None and scaled is not None else None))
    def attempt(name,fn):
        try:fn()
        except Exception as e:current_errors.append(name+": "+type(e).__name__)
    for chain,registry,native in (("ethereum",ETH_REGISTRY,"ETH"),("bsc",BSC_REGISTRY,"BNB")):
        attempt(chain+" native",lambda c=chain,n=native:state_add(c,EVM_ADDR,n,int(evm_rpc(c,"eth_getBalance",[EVM_ADDR,"latest"]),16)/1e18))
        for contract,asset in registry.items():
            def token_balance(c=chain,ct=contract,a=asset):
                q=int(evm_rpc(c,"eth_call",[{"to":ct,"data":"0x70a08231"+wallet_word},"latest"]),16)
                if q:
                    dec=int(evm_rpc(c,"eth_call",[{"to":ct,"data":"0x313ce567"},"latest"]),16)
                    state_add(c,EVM_ADDR,a,q/10**dec)
            attempt(chain+" "+asset,token_balance)
    def btc_state():
        d=_get("https://mempool.space/api/address/"+BITCOIN_ADDR)["chain_stats"]
        state_add("bitcoin",BITCOIN_ADDR,"BTC",(d["funded_txo_sum"]-d["spent_txo_sum"])/1e8)
    attempt("BTC balance",btc_state)
    for wallet in (SOL_WALLET,SOL_WALLET_2):
        attempt("SOL balance "+wallet,lambda w=wallet:state_add("solana",w,"SOL",_sol_rpc("getBalance",[w,{"commitment":"finalized"}])["value"]/1e9))
        for program in ("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"):
            def sol_state(w=wallet,pr=program):
                d=_sol_rpc("getTokenAccountsByOwner",[w,{"programId":pr},{"encoding":"jsonParsed","commitment":"finalized"}])
                for a in d["value"]:
                    inf=a["account"]["data"]["parsed"]["info"]; tok=inf["tokenAmount"]
                    sym={SOLANA_USDC:"USDC",PPLT_MINT:"PPLTX",ALEF_MINT:"ALEF treasury units",ALEF_MINT_OLD:"ALEF old treasury units"}.get(inf["mint"])
                    if sym:state_add("solana",w,sym,int(tok["amount"])/10**int(tok["decimals"]))
            attempt("SOL tokens "+wallet,sol_state)
    def tron_state():
        d=_get("https://api.trongrid.io/v1/accounts/"+TRON_ADDR)["data"][0]
        state_add("tron",TRON_ADDR,"TRX",int(d.get("balance",0))/1e6)
        for entry in d.get("trc20",[]):
            if TRON_USDT in entry:state_add("tron",TRON_ADDR,"USDT",int(entry[TRON_USDT])/1e6)
    attempt("Tron balances",tron_state)
    def ton_state():
        d=_get("https://tonapi.io/v2/accounts/"+TON_ADDR)
        state_add("ton",TON_ADDR,"TON",int(d["balance"])/1e9)
        j=_get("https://tonapi.io/v2/accounts/"+TON_ADDR+"/jettons")
        for b in j.get("balances",[]):
            token=b["jetton"]; sym=token.get("symbol")
            if sym in _XSTOCK_TICKERS or sym in _TON_STABLES:
                state_add("ton",TON_ADDR,sym,int(b["balance"])/10**int(token["decimals"]))
    attempt("TON balances",ton_state)
    current_wallet_state=pd.DataFrame(current,columns=["Chain","Wallet","Asset","Quantity","Multiplier","Share-equivalent quantity","Multiplier source","USD"])
    display(current_wallet_state)
    print("Direct wallet balances only; not full portfolio NAV. Solana/TON xStocks use raw quantity × multiplier × underlying share price; treasury ALEF excluded from valuation. See Price_update for collateral, debt, LP and exchange positions.")
    for e in current_errors:print("CURRENT STATE WARNING:",e)

# One table, newest first, retaining the original backward-flow diagnostic.
cols=["Date","Chain","Type","Description","Raw USD","Net USD","Balance vs Now","Net deposits since opening","Cumul. mgmt fee","Cumul. trading fee","Cumulative fee credits","Cumulative negative cost benchmark","Fee-adjusted deviation","Unpriced later legs","Price source","Class","Ref"]
anchor={c:"" for c in cols}; anchor.update({"Date":NOW,"Description":"CURRENT STATE — independently calculated gap","Raw USD":0.0,"Net USD":0.0,"Balance vs Now":0.0,"Net deposits since opening":net_deposits_now,"Cumul. mgmt fee":-mgmt_fees_at(now_point),"Cumul. trading fee":-trade_fees_at(now_point),"Cumulative fee credits":-contractual_fees_at(now_point),"Cumulative negative cost benchmark":fee_credit_now,"Fee-adjusted deviation":present_gap,"Unpriced later legs":0})
timeline=pd.concat([pd.DataFrame([anchor]),visible[cols]],ignore_index=True)
print("\n=== HISTORICAL TRANSACTIONS — NEWEST FIRST ===")
with pd.option_context("display.max_rows",None,"display.max_colwidth",None):
    display(timeline.style.format({"Raw USD":"{:,.2f}","Net USD":"{:+,.2f}","Balance vs Now":"{:+,.2f}","Net deposits since opening":"{:+,.2f}","Cumul. mgmt fee":"{:+,.2f}","Cumul. trading fee":"{:+,.2f}","Cumulative fee credits":"{:+,.2f}","Cumulative negative cost benchmark":"{:+,.2f}","Fee-adjusted deviation":"{:+,.2f}"},na_rep="UNKNOWN / UNPRICED"))
# Daily closing observations; independently evaluate both endpoints. No
# normalization, smoothing, or manual replacement of the present values.
import matplotlib.pyplot as plt
closes=[min(t+pd.Timedelta(days=1)-pd.Timedelta(microseconds=1),now_point)
        for t in pd.date_range(opening.floor("D"),now_point.floor("D"),freq="D")]
observed_dates=sorted(set([opening,now_point]+[t for t in closes if opening<t<=now_point]))
observed=pd.Series([deposits_at(t) for t in observed_dates],index=observed_dates,dtype=float)
fee_dates=sorted(set([opening,now_point]+[t for t in list(active_schedule.Date)+list(interest_schedule.Date)+list(external_interest.Date) if opening<t<=now_point]))
# Build supply_at(t) from RAW_ALEF_SUPPLY_EVENTS (ALEF started at 0 supply).
from collections import defaultdict as _dd
_sc = _dd(float)
for _e in RAW_ALEF_SUPPLY_EVENTS:
    if _e.get("mint") == ALEF_MINT:
        _sc[_e["ts"]] += float(_e["qty"]) * (1 if _e["type"] == "alef_mint" else -1)
_sct = sorted(_sc); _sl = []; _running_s = 0.0
for _t in _sct:
    _running_s += _sc[_t]; _sl.append(_running_s)
def _supply_at(t):
    t = float(pd.Timestamp(t).timestamp()) if not isinstance(t, (int, float)) else float(t)
    i = bisect.bisect_right(_sct, t) - 1
    return _sl[i] if i >= 0 else 0.0
def _nav_at(t):
    _ts = float(pd.Timestamp(t).timestamp()) if not isinstance(t, (int, float)) else float(t)
    s = _supply_at(_ts)
    px, _ = alef_historical_detail(_ts, alef_chart_history, alef_trade_history)
    return s * px if (s > 0 and px and px > 0) else None
def _pct_nav(val, t):
    nav = _nav_at(t)
    return val / nav * 100 if nav else None
observed_pct = pd.Series([_pct_nav(deposits_at(t), t) for t in observed_dates], index=observed_dates, dtype=float)
fig,ax=plt.subplots(figsize=(13,5.4))
ax.plot(observed_pct.index,observed_pct.values,label="Net deposits (observed, daily close)",linewidth=1.7)
_fee_pct=[v if v is not None else float('nan') for v in (_pct_nav(-fees_at(t), t) for t in fee_dates)]
ax.step(fee_dates,_fee_pct,where="post",linestyle="--",label=baseline_label,linewidth=1.7,color="tab:orange")
# Only the two requested curves. Verified payment records remain in the report.
_sc0=_pct_nav(deposits_at(opening), opening)
if _sc0 is not None: ax.scatter([opening],[_sc0],color="black",zorder=5,label="Common opening anchor")
_sc1=_pct_nav(net_deposits_now, now_point)
if _sc1 is not None: ax.scatter([now_point],[_sc1],color="tab:blue",zorder=5)
_sc2=_pct_nav(fee_credit_now, now_point)
if _sc2 is not None: ax.scatter([now_point],[_sc2],color="tab:orange",zorder=5)
# Both series use the net-deposit convention; their signed difference is the residual.
_gap_vals=[v for v in [_pct_nav(net_deposits_now,now_point),_pct_nav(fee_credit_now,now_point)] if v is not None]
_ann=_pct_nav(present_gap,now_point); _ann_str=f"{_ann:+.2f}% of NAV" if _ann is not None else f"${present_gap:+,.0f} (NAV unavailable)"
if _gap_vals:
    _gap_lo=min(_gap_vals); _gap_hi=max(_gap_vals)
    ax.vlines(now_point,_gap_lo,_gap_hi,color=".35",linewidth=1.3,zorder=4)
    ax.annotate(f"Cost-adjusted residual: {_ann_str}",xy=(now_point,(_gap_lo+_gap_hi)/2),xytext=(-12,10),textcoords="offset points",ha="right",va="bottom",fontsize=10,bbox=dict(boxstyle="round,pad=.25",fc="white",ec=".7",alpha=.9))
else:
    ax.annotate(f"Cost-adjusted residual: {_ann_str}",xy=(now_point,0),xytext=(-12,10),textcoords="offset points",ha="right",va="bottom",fontsize=10,bbox=dict(boxstyle="round,pad=.25",fc="white",ec=".7",alpha=.9))
ax.axhline(0,color="grey",linewidth=.8,alpha=.4)
# Chronological axis: opening on left, present on right.
ax.set_title("ALEF — net deposits and negative fees (% of NAV)", color="white")
ax.set_ylabel("% of NAV (price × supply)", color="white"); ax.set_xlabel("Date (UTC)", color="white")
ax.tick_params(colors="white"); ax.xaxis.label.set_color("white"); ax.yaxis.label.set_color("white")
for spine in ax.spines.values(): spine.set_edgecolor("#555")
ax.set_facecolor("#0d0d0d"); fig.patch.set_facecolor("#060606")
ax.grid(alpha=.25, color="#555"); ax.legend(facecolor="#1a1a1a", edgecolor="#555", labelcolor="white"); plt.tight_layout()
import matplotlib.dates as _mdates
_ax_bb=ax.get_position()
_xlim_ms=[int(_mdates.num2date(x).timestamp()*1000) for x in ax.get_xlim()]
_tx_pts=[{"t":int(pd.Timestamp(t).timestamp()*1000)} for t in observed_dates]
plt.show()
display(HTML('<script id="alef-chart-data" type="application/json">'+json.dumps({"ax":[_ax_bb.x0,_ax_bb.y0,_ax_bb.width,_ax_bb.height],"xlim":_xlim_ms,"pts":_tx_pts})+'</script>'))
print("\n=== PRESENT FEE-ADJUSTED GAP ===")
print(f"Opening anchor (after transaction): {opening.isoformat()}")
print(f"Net deposits since opening: {net_deposits_now:+,.2f} USD (priced legs only)")
print(f"Raw net deposits before internal interest: {raw_deposits_at(now_point):+,.2f} USD")
_mgmt_total=fee_schedule.loc[fee_schedule.Kind=='Management accrual','Fee'].sum()
_trade_total=fee_schedule.loc[fee_schedule.Kind=='Portfolio trading cost credit','Fee'].sum()
print(f"Contractual fee credits: {-contractual_fees_at(now_point):+,.2f} USD  (management ${_mgmt_total:,.2f} + trading ${_trade_total:,.2f})")
if len(interest_schedule):
    print(f"Reconstructed accrued interest (covered positions): {interest_at(now_point):,.2f} USD")
    print(f"Cumulative interest paid (interest-first allocation, covered positions): {paid_at(now_point):,.2f} USD")
else:
    print("Reconstructed accrued interest: UNKNOWN — no successful intervals")
    print("Cumulative interest paid: UNKNOWN — no successful intervals")
print(f"Residual excluding loan-interest adjustment: {net_deposits_now+contractual_fees_at(now_point):+,.2f} USD")
print(f"Verified external interest already present in raw flows: {external_interest_at(now_point):,.2f} USD")
print(f"Combined negative cost benchmark: {fee_credit_now:+,.2f} USD")
print("Blue line is unchanged. Orange includes allocated paid interest once; unpaid interest is reported separately. Interest paid is an allocation estimate; no claim of personal reimbursement unless payer/ledger attribution is verified.")
print(f"Residual with only explicitly verified external interest credits: {net_deposits_now+contractual_fees_at(now_point)+external_interest_at(now_point):+,.2f} USD (subject to all other ledger assumptions)")
print("=== ON-CHAIN LENDING INTEREST / FINANCING COSTS (partial; TRON posted estimate) ===")
if len(interest_schedule):
    if len(interest_schedule): display(interest_schedule.groupby(["Chain","Protocol","Asset"])[["Interest USD","Interest paid USD","Repaid"]].sum().reset_index())
    display(interest_schedule)
else: print("No successfully reconstructed interest intervals; UNKNOWN, not zero.")
display(interest_coverage)
print(f"Cost-adjusted flow residual (net deposits minus negative fee/paid-interest benchmark): {present_gap:+,.2f} USD")
print("Positive = above cost benchmark; negative = below. This is a conditional cost-adjusted flow diagnostic, NOT a manager payable. Verify who funded interest and whether it is already credited before claiming reimbursement.")
print(f"Daily-close cumulative deposit range: {observed.min():+,.2f} to {observed.max():+,.2f} USD")
print("\n=== CONTRACTUAL FEES (USD; calculated from events, not proof of payment) ===")
print("Management NAV source:",fee_nav_source)
print("Fee structure: management 0.5%/yr of NAV (accrued continuously); trading 0.5% per non-stable-coin transfer.")
_mgmt_rows=fee_schedule.loc[fee_schedule.Kind=='Management accrual']
_trade_rows=fee_schedule.loc[fee_schedule.Kind=='Portfolio trading cost credit']
print(f"  Management fee (0.5%/yr of NAV):        ${_mgmt_rows.Fee.sum():>10,.2f}  ({len(_mgmt_rows)} accrual intervals)")
print(f"  Trading cost credit (0.5%/transfer):    ${_trade_rows.Fee.sum():>10,.2f}  ({len(_trade_rows)} eligible transfers)")
print(f"  Total contractual fee credits:          ${fee_schedule.Fee.sum():>10,.2f}")
print(f"Management unsettled since last mint/burn: ${unsettled_management_fee:,.2f}")
print(f"Estimated management settled at in-window mint/burn (included, NOT additional): ${estimated_management_settlements.Fee.sum():,.2f}")
if not estimated_management_settlements.empty:
    display(estimated_management_settlements)
if fee_schedule.Incomplete.any() or unsettled_missing is None or unsettled_missing>0:
    print("WARNING: missing NAV observations; calculated fees use known estimates only, not a complete fee total.")
if fee_nav_history is None:
    print("WARNING: market capitalization is a NAV proxy, not independently reconstructed historical NAV. Supply depends on complete mint/burn retrieval.")
print("\n=== VERIFIED FEE WITHDRAWALS ===")
if verified_input is None:
    print("No verified fee-payment records supplied. The chart shows calculated fee entitlement, not verified cash payments.")
else:
    print(f"Verified withdrawals: ${verified_fees.Fee.sum():,.2f}; coverage: {'declared complete' if verified_complete else 'partial'}")
    display(verified_fees)
print("Benchmark used:",baseline_label)
print("\n=== PORTFOLIO CONVERSION MATCHES (including fee-free exclusions) ===")
if len(conversion_matches):
    display(conversion_matches.sort_values("Date",ascending=False))
    charged=conversion_matches.loc[conversion_matches.Kind=="Portfolio conversion"]
    print(f"Matched conversion notional: ${charged['USD out'].sum():,.2f}; estimated cost credit: ${charged.Fee.sum():,.2f}")
else: print("No conversion pairs matched; no portfolio trading credit inferred.")
print(f"Unmatched material eligible custody legs: {len(unmatched_conversion_legs)} (no inferred fee; retained in residual)")
if len(unmatched_conversion_legs):
    display(unmatched_conversion_legs[["Date","Chain","Asset","USD","Class","Ref"]].sort_values("Date",ascending=False))
print("Contractual/estimated fee-event breakdown (fee_schedule):")
display(fee_schedule.sort_values("Date",ascending=False))
print(f"Historical forward net AFTER opening: {reverse.loc[reverse.Date>opening,'Net USD'].sum():+,.2f} USD; raw priced sum AFTER opening: {reverse.loc[reverse.Date>opening,'Raw USD'].sum():+,.2f} USD")
print(f"Small legs hidden but included in calculations: {len(dust)}; net {dust['Net USD'].sum(min_count=1):+,.4f} USD")
print(f"Unpriced net legs: {reverse['Net USD'].isna().sum()}; quarantined records: {len(QUARANTINE)}")
print(f"POOL_FLOW_SHARE={POOL_FLOW_SHARE} (assumed), issuance-offset={INCLUDE_ISSUANCE_OFFSET}; this is a flow diagnostic, not verified NAV or personal debt.")
print("\n=== NET CONTRIBUTION BY CHAIN AND TYPE ===")
display(reverse.groupby(["Chain","Class"]).agg(legs=("Net USD","size"),raw_usd=("Raw USD",lambda x:x.sum(min_count=1)),net_usd=("Net USD",lambda x:x.sum(min_count=1))))
if AUDIT_WARNINGS:
    print("\nINCOMPLETE OR APPROXIMATE COVERAGE:")
    for w in AUDIT_WARNINGS:print("WARNING:",w)
if not any(t["asset"]=="PPLTX" for t in sol1_txns+sol2_txns):print("PPLTX: no retrieved movements in window; check opening balance and account history.")
# Full data remain available: reverse, timeline, dust, QUARANTINE, ledger, receipts.

Full Financial Audit (History)

A chronological record of every capital movement since 2026-09-18 — external inflows and outflows, and all ALEF token minting and burning events, across every chain. Reconstructed directly from public blockchain data.

Run this open-source program to audit the full transaction history:

# ALEF — current state and reverse chronological cash-flow check
# As-of-now is an anchor, not a balancing entry. Historical values are NOT historical NAV.
# A positive forward flow adds funds; backward balance subtracts that flow.
# Optional: define ALEF_CURRENT_STATE in Price_update's previous cell (any current
# portfolio table or dict with verified positions/liabilities/NAV). If absent, the
# code independently shows current direct custody balances, NOT a complete NAV.
# Historical prices are estimates except observed cash/execution amounts.
import os, sys, json, time, math, hashlib, requests, bisect
import pandas as pd
import yfinance as yf
from datetime import datetime, timezone, timedelta
from decimal import Decimal
from IPython.display import display, HTML

pd.set_option("display.max_rows", 500)
pd.set_option("display.float_format", "{:,.2f}".format)
pd.set_option("display.max_colwidth", 60)

print("NOTE: This audit queries multiple blockchains and may take up to an hour to complete in extreme cases. Please be patient.")

# ── Addresses ──────────────────────────────────────────────────────────────────
EVM_ADDR       = "0xfB6b384a64BA407Ee964DF70bf48A6Ef993B1Fd4"
SOL_WALLET     = "9W22wgpcSsbcAjoGvGQfcvVUns5q7LMuWNPCnM4eVXse"
SOL_WALLET_2   = "9JRZdE4rcSUQRDRUTqNrqsFtxm7caT4GfyiNxFJqBHUe"
TRON_ADDR      = "TFMDSKrH2FJx3pdGACb5oHoKPJRzaH8dKv"
BITCOIN_ADDR   = "bc1qmqcggscd9mfddzywukrxksrrfamx5mevr5jr40llmf6ggtdmwyeqcaekt4"
TON_ADDR       = "EQDJ8vy2R0EdEskou7Awf8PX2GXU9j0dLAPrJlNHRrJdlsXy"
TON_ADDR_RAW   = "0:c9f2fcb647411d12c928bbb0307fc3d7d865d4f63d1d2c03eb26534746b25d96"
ALEF_MINT      = "FBHd9upXFkeWSwe9qEdcgRLa4Y6uzsLCSawrpfPkQZGg"
ALEF_MINT_OLD  = "9B3rXYVdL2iUxGnY54TKhR9NroqGB1RBAivVQWb26Zqt"
SOLANA_USDC    = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
RAYDIUM_CLMM   = "CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK"

# xStock token symbol → yfinance underlying ticker for price lookup
_XSTOCK_TICKERS = {
    "AAPLx": "AAPL",  "AMZNx": "AMZN",  "MSFTx": "MSFT",  "NVDAx": "NVDA",
    "TSLAx": "TSLA",  "GOOGLx": "GOOGL", "METAx": "META",  "COINx": "COIN",
    "SPYx":  "SPY",   "QQQx":  "QQQ",   "SLVx":  "SLV",   "TQQQx": "TQQQ",
}

_XSTOCK_TICKERS.update({"NVDAB":"NVDA","TSLAB":"TSLA","METAB":"META","GOOGLB":"GOOGL","PPLTX":"PPLT","PPLTx":"PPLT"})
BSC_REGISTRY = {"0x55d398326f99059ff775485246999027b3197955":"USDT", "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d":"USDC", "0x02fca66c1d1afb4e2a7884261eb00f63598a7436":"NVDAB", "0x5b1910eaad6450e50f816082aa078c41f10c292f":"TSLAB", "0x7425889fe94f9d693e8daefe88bcced6acfef4c0":"METAB", "0x3f53de71c126bdabae20f9cd64848d317f6c3238":"GOOGLB"}
BSC_REGISTRY["0x8b872732b07be325a8803cdb480d9d20b6f8d11b"] = "SLVon"
_XSTOCK_TICKERS["SLVon"] = "SLV"  # underlying-price proxy; not execution proceeds
PPLT_MINT = "Xst6eFD4YT6sz9RLMysN9SyvaZWtraSdVJQGu5ZkAme"
QUARANTINE = []
ANNUAL_FEE_RATE = 0.005        # 0.5 % / year, accrued on NAV; settled at mint/burn
TRADING_FEE_RATE = 0.005       # 0.5 % of portfolio conversion notional (excluding free pairs)
# Optional upstream actual NAV history: pandas Series, UTC timestamps, USD NAV.
# If absent, live-mint total supply × historical ALEF market quote is a NAV proxy.
RAW_ALEF_SUPPLY_EVENTS = []
NOW             = datetime.now(timezone.utc)
AUDIT_WARNINGS = []
RAYDIUM_LP_REFS = set()
FOUNDER_ADDRESSES = set()  # populate with verified personal addresses
VERIFIED_FOUNDER_REFS = set()  # full hashes, independently classified
VERIFIED_INTERNAL_REFS = set()  # full hashes, independently classified

# ALEF amounts to exclude (test transactions — exact float qty)
EXCLUDE_ALEF_AMOUNTS = {
    100_000_000.0,  # 2026-06-21 joke mint+burn
      942_645.0,    # 2026-06-18 large test mint
      916_000.0,    # 2026-07-01 large test burns ×4
}

# ── Live Raydium ALEF/USDC market price; never manually entered ───────────────
ALEF_POOL_ID = "Gg6WkQW1h8CWTcmdMueEL9Aw3S3XbXqknTpn3RZsaf91"
ALEF_PRICE_USD = None
ALEF_PRICE_SOURCE = "Unavailable"

# Sep 12-14 2026: "conversion mints" re-issued old investors in the new ALEF_MINT
# address — no matching on-chain inflows (capital was in old pre-migration wallets).
# Start after these so net flows ≈ 0. Set to "" to include all history.
AUDIT_START_DATE = "2026-09-17 19:08:04+00:00"
# ──────────────────────────────────────────────────────────────────────────────

ETHERSCAN_KEY = os.getenv("ETHERSCAN_API_KEY") or input("Etherscan API key (free at etherscan.io/apis): ").strip()
HELIUS_KEY    = os.getenv("HELIUS_API_KEY")    or input("Helius API key (free at dev.helius.xyz): ").strip()
HELIUS_RPC    = f"https://mainnet.helius-rpc.com/?api-key={HELIUS_KEY}"

# Known DeFi protocol addresses — transfers to/from these are INTERNAL
PROTOCOL_ADDRS = {a.lower() for a in [
    # Euler BNB vaults
    "0x8f68128438c1101550bf478bbe8f8c80749eb794",
    "0xf4940cde23c164f8ca8d536f3567337349b3208f",
    # Euler EVC / protocol
    "0x0C9a3dd6b8F28529d72d7f9cE918D493519EE383",
    # Aave v3 BNB pool
    "0x6807dc923806fE8Fd134338EABCA509979a7e0cB",
    # Venus unitroller
    "0xfD36E2c2a6789Db23113685031d7F16329158384",
    # Fluid vault resolver
    "0xA5C3E16523eeeDDcC34706b0E6bE88b4c6EA95cC",
    # zero / burn
    "0x0000000000000000000000000000000000000000",
    "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
]}

# Confirmed protocol custody endpoints: Aave V4 docs, Fluid technical docs,
# JustLend V2 deployment docs. Keep exact chain + address; not arbitrary senders.
LENDING_ENDPOINTS = {
    "ethereum": {"0xcca852bc40e560adc3b1cc58ca5b55638ce826c9":"Aave V4 Core Hub",
                 "0x06002e9c4412cb7814a791ea3666d905871e536a":"Aave V4 Plus Hub",
                 "0x943827dca022d0f354a8a8c332da1e5eb9f9f931":"Aave V4 Prime Hub",
                 "0xbbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb":"Morpho Blue",
                 "0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2":"Aave V3 Pool"},
    "bsc": {"0x52aa899454998be5b000ad077a46bbe360f4e497":"Fluid Liquidity"},
    "tron": {"TDH4dhmVQQNc1ZNudJwWzBcs2h6ahhWrpp":"JustLend V2 Moolah"},
}
ETH_REGISTRY={
    "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48":"USDC",
    "0xdac17f958d2ee523a2206206994597c13d831ec7":"USDT",
    "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599":"WBTC",
    "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2":"WETH",
    "0x45804880de22913dafe09f4980848ece6ecbaf78":"PAXG",
    "0x68749665ff8d2d112fa859aa293f07a622782f38":"XAUt",
    "0x6c3ea9036406852006290770bedfcaba0e23a0e8":"PYUSD",
    "0xa45cd7ac9865b9539166ebaf2abc362df4736580":"TQQQon",
    "0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf":"CBBTC",
}
TRON_USDT="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
# Additional confirmed assets/addresses may be added here, never by guessing symbol.
# Pool-wide swap cash delta is the original requested market-flow convention;
# this fraction is an explicit assumption, not an independently verified LP share.
POOL_FLOW_SHARE=1.0
DUST_LIMIT_USD=1.0
# True for the original issuance-offset flow check: mint = negative, burn = positive.
INCLUDE_ISSUANCE_OFFSET=True

# ── Base-58 helpers (no external dep) ─────────────────────────────────────────
_B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
_B58_MAP = {c: i for i, c in enumerate(_B58_ALPHABET)}

def _b58decode(s):
    n = 0
    for ch in str(s):
        n = n * 58 + _B58_MAP[ch]
    body = n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b""
    zeros = len(str(s)) - len(str(s).lstrip("1"))
    return b"\x00" * zeros + body

def _b58encode(b):
    b = bytes(b)
    zeros = len(b) - len(b.lstrip(b"\x00"))
    n = int.from_bytes(b, "big")
    chars = []
    while n:
        n, r = divmod(n, 58)
        chars.append(_B58_ALPHABET[r])
    return "1" * zeros + ("".join(reversed(chars)) if chars else "")

def _ed25519_on_curve(pk32):
    if len(pk32) != 32:
        return False
    p = 2**255 - 19
    d = (-121665 * pow(121666, p - 2, p)) % p
    y = int.from_bytes(pk32, "little") & ((1 << 255) - 1)
    if y >= p:
        return False
    y2 = (y * y) % p
    u = (y2 - 1) % p
    v = (d * y2 + 1) % p
    x2 = (u * pow(v, p - 2, p)) % p
    x = pow(x2, (p + 3) // 8, p)
    if (x * x - x2) % p != 0:
        x = (x * pow(2, (p - 1) // 4, p)) % p
    return (x * x - x2) % p == 0

def _find_pda(seeds, program_id):
    program = _b58decode(program_id)
    for bump in range(255, -1, -1):
        h = hashlib.sha256()
        for seed in seeds:
            h.update(seed)
        h.update(bytes([bump]))
        h.update(program)
        h.update(b"ProgramDerivedAddress")
        digest = h.digest()
        if not _ed25519_on_curve(digest):
            return _b58encode(digest), bump
    raise RuntimeError("PDA not found")

# ── HTTP helpers ───────────────────────────────────────────────────────────────
_sess = requests.Session()
_sess.headers["User-Agent"] = "ALEF-audit/1.0"

def _get(url, **kw):
    r = _sess.get(url, timeout=25, **kw)
    r.raise_for_status()
    return r.json()

def _sol_rpc(method, params, rpc=None):
    url = rpc or HELIUS_RPC
    for attempt in range(3):
        try:
            r = _sess.post(url,
                json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params},
                timeout=30, headers={"Content-Type": "application/json"})
            if r.status_code == 429:
                time.sleep(1 + attempt * 2)
                continue
            r.raise_for_status()
            d = r.json()
            if "error" in d:
                raise RuntimeError(d["error"])
            return d.get("result")
        except Exception as e:
            if attempt == 2:
                raise
            time.sleep(0.5 * (2 ** attempt))

# ── Current prices ─────────────────────────────────────────────────────────────

# Pricing configuration: underlying units per token unit, only if verified.
# PPLTX raw token quantities may differ from displayed share-equivalent quantities.
# Add verified timestamp-effective multipliers here, e.g. {"PPLTX": [("YYYY-MM-DD", factor)]}.
TOKEN_MULTIPLIERS = {}  # optional verified manual overrides, timestamp -> factor
# xStocks: raw SPL/jetton units need scaling; EVM balanceOf already returns
# scaled shares. PPLT's 10:1 split took effect 2026-05-18 (SEC 10-Q).
_XSTOCK_RAW_SYMBOLS = {"PPLTX":"PPLTx", **{k.upper():k for k in _XSTOCK_TICKERS if k.endswith("x") and k.upper()!="PPLTX"}}
_XSTOCK_NETWORKS = {"solana":"Solana", "ton":"TON"}
_XSTOCK_HISTORY_CACHE = {}
_XSTOCK_CURRENT_CACHE = {}
_MULTIPLIER_WARNED = set()
_XSTOCK_API = "https://api.xstocks.fi/api/v2/public/assets"

def _mult_factor(v):
    try:
        v=float(v)
        return v if math.isfinite(v) and v>0 else None
    except (TypeError,ValueError,OverflowError): return None

def _mult_timestamp(v):
    if v is None or isinstance(v,bool): return None
    try:
        n=float(v)
        if not math.isfinite(n):return None
        return n/1000 if abs(n)>1e12 else n
    except (TypeError,ValueError,OverflowError):
        try:return pd.to_datetime(v,utc=True).timestamp()
        except Exception:return None

def _mult_warn(key,message):
    if key not in _MULTIPLIER_WARNED:
        _MULTIPLIER_WARNED.add(key); AUDIT_WARNINGS.append(message)

def _xstock_api_get(symbol,chain,history=False,page=0):
    path=f"{_XSTOCK_API}/{symbol}/multiplier" + ("/history" if history else "")
    params={"network":_XSTOCK_NETWORKS[chain]}
    if history:params.update(page=page,pageSize=100)
    try:return _get(path,params=params)
    except requests.HTTPError as e:
        # Some deployments accept lowercase network names instead.
        if e.response is None or e.response.status_code not in (400,404,422):raise
        params["network"]=chain
        return _get(path,params=params)

def _xstock_history(symbol,chain):
    key=(symbol,chain)
    if key in _XSTOCK_HISTORY_CACHE:return _XSTOCK_HISTORY_CACHE[key]
    points=[]; complete=False
    try:
        for page in range(100):
            d=_xstock_api_get(symbol,chain,True,page)
            nodes=d.get("nodes")
            if not isinstance(nodes,list):raise ValueError("missing history nodes")
            for row in nodes:
                # Only timestamp-effective entries; never use a future announced multiplier.
                ts=next((x for x in (_mult_timestamp(row.get(k)) for k in ("activationDateTime","activationTimestamp","effectiveAt","effectiveTimestamp","activatedAt","activationTime","effectiveDateTime","timestamp")) if x is not None),None)
                factor=next((x for x in (_mult_factor(row.get(k)) for k in ("newMultiplier","multiplier","value","currentMultiplier")) if x is not None),None)
                if ts is None or factor is None:raise ValueError("unrecognized multiplier history entry")
                points.append((ts,factor))
            if not d.get("page",{}).get("hasNextPage",False):complete=True;break
        if not complete:raise ValueError("multiplier pagination incomplete")
        points=sorted(set(points))
    except Exception as e:
        points=[];complete=False
        _mult_warn((key,"history"),f"{symbol}/{chain} multiplier history unavailable: {type(e).__name__}")
    _XSTOCK_HISTORY_CACHE[key]=(points,complete)
    return points,complete

def _xstock_current(symbol,chain):
    key=(symbol,chain)
    if key in _XSTOCK_CURRENT_CACHE:return _XSTOCK_CURRENT_CACHE[key]
    ts=NOW.timestamp(); result=(None,"unavailable")
    if chain=="solana" and symbol.upper()=="PPLTX":
        # Independent on-chain check of the Token-2022 scaled UI extension.
        try:
            d=_sol_rpc("getAccountInfo",[PPLT_MINT,{"encoding":"jsonParsed","commitment":"finalized"}])
            info=d["value"]["data"]["parsed"]["info"]
            for ext in info.get("extensions",[]):
                if str(ext.get("extension","")).lower().replace("_","") not in ("scaleduiamount","scaleduiamountconfig"):continue
                state=ext["state"]
                f=_mult_factor(state.get("multiplier")); new=_mult_factor(state.get("newMultiplier"))
                activation=_mult_timestamp(state.get("newMultiplierEffectiveTimestamp"))
                if new is not None and activation is not None and activation<=ts:f=new
                if f is not None:result=(f,"Solana Token-2022 mint extension");break
        except Exception as e:_mult_warn((key,"mint"),f"{symbol} mint multiplier unavailable: {type(e).__name__}")
    if result[0] is None:
        try:
            d=_xstock_api_get(symbol,chain)
            f=_mult_factor(d.get("currentMultiplier")); new=_mult_factor(d.get("newMultiplier"))
            activation=_mult_timestamp(d.get("activationDateTime"))
            if new is not None and activation is not None and activation<=ts:f=new
            if f is None:raise ValueError("invalid current multiplier")
            result=(f,"xStocks issuer current multiplier")
        except Exception as e:_mult_warn((key,"current"),f"{symbol}/{chain} current multiplier unavailable: {type(e).__name__}")
    _XSTOCK_CURRENT_CACHE[key]=result
    return result

def xstock_factor(asset,chain,ts,quantity_basis="raw",current=False):
    if quantity_basis=="scaled" or chain not in _XSTOCK_NETWORKS or asset.upper() not in _XSTOCK_RAW_SYMBOLS:
        return 1.0,"share units / no xStocks scaling"
    if quantity_basis!="raw":return None,"quantity basis unknown"
    symbol=_XSTOCK_RAW_SYMBOLS[asset.upper()]
    overrides=[(t,f) for d,v in TOKEN_MULTIPLIERS.get(asset.upper(),[]) if (t:=_mult_timestamp(d)) is not None and t<=ts and (f:=_mult_factor(v)) is not None]
    if overrides:return max(overrides)[1],"verified manual multiplier"
    if current:
        f,source=_xstock_current(symbol,chain)
        if f is not None:return f,source
    points,complete=_xstock_history(symbol,chain)
    i=bisect.bisect_right(points,(ts,float("inf")))-1
    if complete and i>=0:
        # For current balances, prefer current mint/API. History is a labelled fallback.
        return points[i][1],"xStocks issuer executed multiplier history"
    if complete and points and ts<points[0][0]:
        return 1.0,"xStocks initial 1:1 before first recorded adjustment"
    if asset.upper()=="PPLTX" and ts>=pd.Timestamp("2026-05-18",tz="UTC").timestamp():
        _mult_warn((symbol,chain,"split"),"PPLTx: using documented 10:1 PPLT split fallback; issuer multiplier not verified")
        return 10.0,"PPLT 10:1 split fallback (issuer multiplier unverified)"
    if ALLOW_UNVERIFIED_SHARE_PROXY:
        _mult_warn((symbol,chain,"proxy"),f"{symbol}/{chain}: multiplier unverified; 1:1 estimate")
        return 1.0,"ASSUMED 1:1, multiplier unavailable"
    return None,"multiplier unavailable"

# If true, show a clearly labelled one-share proxy when multiplier is unavailable.
# Such amounts are estimates, not verified execution values.
ALLOW_UNVERIFIED_SHARE_PROXY = True
_PRICE_ALIASES = {"WBTC":"BTC-USD", "CBBTC":"BTC-USD", "WETH":"ETH-USD",
                  "XAUT":"GC=F", "PAXG":"GC=F", "XAUt":"GC=F",
                  "PPLTX":"PPLT", "PPLTx":"PPLT", "SLVon":"SLV", "TQQQon":"TQQQ"}
_CG_IDS = {"BTC":"bitcoin","WBTC":"wrapped-bitcoin","CBBTC":"coinbase-wrapped-btc",
           "ETH":"ethereum","WETH":"weth","BNB":"binancecoin","SOL":"solana",
           "TRX":"tron","TON":"the-open-network","XAUT":"tether-gold","PAXG":"pax-gold","TQQQON":"proshares-ultrapro-qqq-ondo-tokenized"}

def fetch_current_prices():
    px = {"USDC": 1.0, "USDT": 1.0, "BUSD": 1.0, "DAI": 1.0, "FDUSD": 1.0}
    for ticker, sym in [("BTC-USD","BTC"),("ETH-USD","ETH"),("BNB-USD","BNB"),
                        ("SOL-USD","SOL"),("TRX-USD","TRX"),("TON11419-USD","TON"),
                        ("PPLT","PPLT"),("SLV","SLV"),("TQQQ","TQQQ"),("NVDA","NVDA"),
                        ("AAPL","AAPL"),("AMZN","AMZN"),("MSFT","MSFT"),
                        ("TSLA","TSLA"),("GOOGL","GOOGL"),("META","META")]:
        try:
            t = yf.Ticker(ticker)
            px[sym] = float(t.fast_info["last_price"])
        except:
            pass
    for sym, ticker in _XSTOCK_TICKERS.items():
        if ticker in px: px[sym] = px[ticker]
    for sym, ticker in _PRICE_ALIASES.items():
        if sym in px: continue
        try:
            val = float(yf.Ticker(ticker).fast_info["last_price"])
            if math.isfinite(val) and val > 0: px[sym] = val
        except Exception: pass
    if ALEF_PRICE_USD is not None: px["ALEF"] = ALEF_PRICE_USD
    return px

# ── ALEF mint / burn history ───────────────────────────────────────────────────
_SUPPLY_OPS = {"mintTo", "mintToChecked", "burn", "burnChecked"}

def _sol_sigs_all(address, max_pages=50):
    """Yield all signatures for address, newest-first across pages."""
    before = None
    for _ in range(max_pages):
        params = {"limit": 100, "commitment": "finalized"}
        if before:
            params["before"] = before
        page = _sol_rpc("getSignaturesForAddress", [address, params]) or []
        yield from page
        if len(page) < 100:
            break
        before = page[-1]["signature"]

def _sol_get_tx(sig):
    return _sol_rpc("getTransaction", [sig, {
        "encoding": "jsonParsed",
        "maxSupportedTransactionVersion": 1,
        "commitment": "finalized",
    }])

def fetch_alef_mint_burn_history(prices):
    events = []
    seen = set()
    for mint_addr in (ALEF_MINT, ALEF_MINT_OLD):
        for s in _sol_sigs_all(mint_addr, max_pages=100):
            sig = s.get("signature")
            if not sig or sig in seen:
                continue
            seen.add(sig)
            try:
                tx = _sol_get_tx(sig)
            except Exception as e:
                AUDIT_WARNINGS.append(f"ALEF mint/burn transaction unavailable: {sig}: {type(e).__name__}")
                print(f"  [WARN] tx fetch {sig[:8]}…: {e}", file=sys.stderr)
                continue
            if not tx or (tx.get("meta") or {}).get("err") is not None:
                continue
            bt = tx.get("blockTime") or s.get("blockTime")
            if not bt:
                continue
            msg = (tx.get("transaction") or {}).get("message") or {}
            all_ixs = list(msg.get("instructions") or [])
            for inner in (tx.get("meta") or {}).get("innerInstructions") or []:
                all_ixs.extend(inner.get("instructions") or [])
            for ix in all_ixs:
                parsed = ix.get("parsed")
                if not isinstance(parsed, dict):
                    continue
                if parsed.get("type") not in _SUPPLY_OPS:
                    continue
                info = parsed.get("info") or {}
                if info.get("mint") not in (ALEF_MINT, ALEF_MINT_OLD):
                    continue
                ta = info.get("tokenAmount") or {}
                raw = int(ta.get("amount") or info.get("amount") or 0)
                dec = int(ta.get("decimals") or 6)
                alef_qty = raw / 10**dec
                RAW_ALEF_SUPPLY_EVENTS.append(dict(ts=bt, mint=info.get("mint"),
                    qty=alef_qty, type="alef_burn" if parsed["type"] in ("burn", "burnChecked") else "alef_mint", ref=sig))
                if alef_qty in EXCLUDE_ALEF_AMOUNTS:
                    continue
                usd_val  = None  # valued at the historical quote in the ledger
                is_burn  = parsed["type"] in ("burn", "burnChecked")
                events.append({
                    "ts":          bt,
                    "dt":          datetime.fromtimestamp(bt, tz=timezone.utc),
                    "type":        "alef_burn" if is_burn else "alef_mint",
                    "chain":       "solana",
                    "asset":       "ALEF",
                    "mint":        info.get("mint"),
                    "qty":         alef_qty,
                    "usd_value":   usd_val,
                    "is_inflow":   is_burn,
                    "description": f"{'Burn' if is_burn else 'Mint'} {alef_qty:,.4f} ALEF",
                    "ref":         sig,
                })
    events.sort(key=lambda x: x["ts"])
    return events

# ── Raydium CLMM pool discovery ────────────────────────────────────────────────
def discover_raydium_pool():
    """Return (pool_id, usdc_vault, alef_vault) or (None, None, None)."""
    # Try Raydium pools-by-mint API first (fastest)
    for mint in (ALEF_MINT, ALEF_MINT_OLD):
        try:
            r = _get("https://api.raydium.io/v2/main/pool/info/token",
                     params={"mint": mint})
            pools = (r or {}).get("data") or []
            for p in pools:
                if p.get("type") == "CLMM" or "clmm" in str(p.get("programId","")).lower():
                    return p.get("id"), None, None
        except:
            pass
    # Fallback: scan wallet SPL accounts for Raydium CLMM position NFTs
    try:
        result = _sol_rpc("getTokenAccountsByOwner", [
            SOL_WALLET,
            {"programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
            {"encoding": "jsonParsed", "commitment": "confirmed"},
        ])
        for acct in (result or {}).get("value") or []:
            info = (acct.get("account",{}).get("data",{})
                       .get("parsed",{}).get("info") or {})
            mint = info.get("mint","")
            amt  = float((info.get("tokenAmount") or {}).get("uiAmount") or 0)
            if amt != 1.0:
                continue
            try:
                mb = _b58decode(mint)
                if len(mb) != 32:
                    continue
                pda, _ = _find_pda([b"position", mb], RAYDIUM_CLMM)
                ai = _sol_rpc("getAccountInfo", [pda, {"encoding":"base64","commitment":"confirmed"}])
                val = (ai or {}).get("value")
                if not val or val.get("owner") != RAYDIUM_CLMM:
                    continue
                data = _get("https://dynamic-ipfs.raydium.io/clmm/position",
                            params={"id": pda})
                pool = (data or {}).get("poolInfo") or {}
                mint_a = (pool.get("mintA") or {}).get("address","")
                mint_b = (pool.get("mintB") or {}).get("address","")
                if ALEF_MINT in (mint_a, mint_b) or ALEF_MINT_OLD in (mint_a, mint_b):
                    return pool.get("id"), None, None
            except:
                continue
    except Exception as e:
        print(f"  [WARN] pool discovery: {e}", file=sys.stderr)
    return None, None, None

# ── Raydium swap history ───────────────────────────────────────────────────────
def fetch_raydium_swaps(pool_id):
    """
    For each transaction on pool_id, infer buy/sell from USDC net flow in pool vaults.
    Returns list of dicts with type=raydium_buy or raydium_sell.
    """
    if not pool_id:
        return []
    swaps = []
    seen  = set()
    for s in _sol_sigs_all(pool_id, max_pages=100):
        sig = s.get("signature")
        if not sig or sig in seen:
            continue
        seen.add(sig)
        try:
            tx = _sol_get_tx(sig)
        except Exception as e:
            AUDIT_WARNINGS.append(f"Raydium transaction unavailable: {sig}: {type(e).__name__}")
            continue
        if not tx or (tx.get("meta") or {}).get("err") is not None:
            continue
        bt   = tx.get("blockTime") or s.get("blockTime")
        meta = tx.get("meta") or {}
        # Require a decoded Anchor swap instruction, including CPI calls.
        ix = list((tx.get("transaction") or {}).get("message", {}).get("instructions", []))
        for inner in meta.get("innerInstructions") or []:
            ix.extend(inner.get("instructions") or [])
        swap_discs = {hashlib.sha256(("global:" + n).encode()).digest()[:8]
                      for n in ("swap", "swap_v2", "swap_router_base_in")}
        lp_discs = {hashlib.sha256(("global:" + n).encode()).digest()[:8]
                    for n in ("increase_liquidity", "increase_liquidity_v2", "decrease_liquidity", "decrease_liquidity_v2", "open_position", "open_position_v2", "open_position_with_token22_nft", "close_position", "collect_fund_fee", "collect_protocol_fee")}
        discs = set()
        for i in ix:
            if i.get("programId") == RAYDIUM_CLMM and i.get("data"):
                try: discs.add(_b58decode(i["data"])[:8])
                except Exception: pass
        if discs & lp_discs:
            if not discs & swap_discs:
                RAYDIUM_LP_REFS.add(sig)
            else:
                AUDIT_WARNINGS.append(f"Mixed Raydium swap/LP: {sig}")
            continue
        if not discs & swap_discs:
            continue
        # Map accountIndex → {mint, owner, pre_ui, post_ui}
        pre_map  = {b["accountIndex"]: b for b in (meta.get("preTokenBalances")  or [])}
        post_map = {b["accountIndex"]: b for b in (meta.get("postTokenBalances") or [])}
        indices  = set(pre_map) | set(post_map)
        usdc_delta = alef_delta = 0.0
        for idx in indices:
            pre  = pre_map.get(idx,  {})
            post = post_map.get(idx, {})
            tok_mint  = pre.get("mint")  or post.get("mint")
            # Only pool-owned accounts
            owner = pre.get("owner") or post.get("owner") or ""
            if owner not in (pool_id, RAYDIUM_CLMM):
                continue
            pre_ui  = float((pre.get("uiTokenAmount")  or {}).get("uiAmount") or 0)
            post_ui = float((post.get("uiTokenAmount") or {}).get("uiAmount") or 0)
            delta = post_ui - pre_ui
            if tok_mint == SOLANA_USDC:
                usdc_delta += delta
            elif tok_mint in (ALEF_MINT, ALEF_MINT_OLD):
                alef_delta += delta
        if abs(usdc_delta) < 0.01 and abs(alef_delta) < 0.01:
            continue
        if abs(alef_delta) < 0.01 or abs(usdc_delta) < 0.01:
            continue  # LP fee collection / pool-only USDC event, not a real swap
        # LP add: both increase; LP remove: both decrease.
        # Real swaps always move USDC and ALEF in opposite directions.
        if (usdc_delta > 0) == (alef_delta > 0):
            continue  # LP add or remove — not a trade
        # buy  = USDC flows IN to pool (someone pays USDC to get ALEF)  → inflow
        # sell = USDC flows OUT of pool (someone gets USDC for their ALEF) → outflow
        is_buy = usdc_delta > 0
        swaps.append({
            "ts":          bt,
            "dt":          datetime.fromtimestamp(bt, tz=timezone.utc),
            "type":        "raydium_buy" if is_buy else "raydium_sell",
            "chain":       "solana",
            "asset":       "USDC",
            "qty":         abs(usdc_delta),
            "usd_value":   abs(usdc_delta),
            "alef_qty":    abs(alef_delta),
            "is_inflow":   is_buy,
            "description": (f"{'Buy' if is_buy else 'Sell'} "
                            f"{abs(alef_delta):,.4f} ALEF "
                            f"({'receive' if is_buy else 'pay'} "
                            f"{abs(usdc_delta):,.2f} USDC)"),
            "ref":         sig,
        })
    swaps.sort(key=lambda x: x["ts"])
    return swaps

# ── BSC token-transfer history via public RPC (no Etherscan key needed) ───────
from concurrent.futures import ThreadPoolExecutor as _TPE
import requests as _req

_BSC_RPC    = "https://bsc-rpc.publicnode.com"
_BSC_CHUNK  = 9000
_ERC20_XFER = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
_BSC_STABLE = {   # lowercase contract → (symbol, decimals)
    "0x55d398326f99059ff775485246999027b3197955": ("USDT", 18),
    "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d": ("USDC", 18),
}

def _bsc_post(method, params):
    r = _req.post(_BSC_RPC,
                  json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params},
                  timeout=20)
    r.raise_for_status()
    d = r.json()
    if "error" in d:
        raise RuntimeError(d["error"])
    return d.get("result")

NODEREAL_API_KEY = os.getenv("NODEREAL_API_KEY") or input("NodeReal API key (free at nodereal.io): ").strip()

def fetch_bsc_history(prices):
    """Indexed wallet transfers; no block range scans."""
    wallet = EVM_ADDR.lower()
    out = []
    for field in ("fromAddress", "toAddress"):
        params = {field: wallet, "category": ["external", "internal", "20"],
                  "order": "desc", "maxCount": "0x3e8"}
        seen_pages = set()
        while True:
            try:
                r = requests.post("https://bsc-mainnet.nodereal.io/v1/" + NODEREAL_API_KEY,
                    json={"jsonrpc":"2.0","id":1,"method":"nr_getAssetTransfers","params":[params]}, timeout=45)
                r.raise_for_status()
                d = r.json()
                if "error" in d or not isinstance(d.get("result"),dict):
                    raise ValueError("NodeReal returned an invalid result or RPC error")
                result = d["result"]
                transfers = result["transfers"]
            except Exception as e:
                AUDIT_WARNINGS.append(f"BSC incomplete ({field}): {type(e).__name__}")
                break
            for t in transfers:
                try:
                    frm,to = t["from"].lower(),t["to"].lower()
                    if frm == to or wallet not in (frm,to): continue
                    if str(t.get("receiptsStatus",1)) in ("0","0x0"): continue
                    ts = int(t.get("blockTimeStamp") or t.get("blockTimestamp"))
                    contract = str(t.get("contractAddress") or "").lower()
                    native = t.get("category") in ("external","internal")
                    sym = "BNB" if native else BSC_REGISTRY.get(contract)
                    if not sym:
                        QUARANTINE.append(dict(chain="bsc", asset=t.get("asset"), contract=contract, ref=t.get("hash"), reason="unverified contract", raw=t))
                        continue
                    dec = t.get("decimal")
                    if dec is None and t.get("category") in ("external","internal"): dec = 18
                    if dec is None: raise ValueError("missing decimals")
                    qty = int(str(t["value"]), 16 if str(t["value"]).startswith("0x") else 10) / 10**int(str(dec), 16 if str(dec).startswith("0x") else 10)
                    if not qty: continue
                    incoming = to == wallet
                    cp = frm if incoming else to
                    px = prices.get(sym)
                    if not px: AUDIT_WARNINGS.append(f"Unpriced BSC asset {sym}: {t['hash']}")
                    out.append(dict(ts=ts,dt=datetime.fromtimestamp(ts,timezone.utc),type="deposit" if incoming else "withdrawal",chain="bsc",asset=sym,qty=qty,usd_value=qty*(px or 0),is_inflow=incoming,description=f"{sym} {qty:g} (BSC)" + (" [UNPRICED]" if not px else ""),ref=t["hash"],counterparty=cp,contract=contract,raw_qty=int(str(t["value"]),16 if str(t["value"]).startswith("0x") else 10)))
                except Exception as e:
                    AUDIT_WARNINGS.append(f"BSC malformed transfer {t.get('hash')}: {type(e).__name__}")
            cursor = result.get("pageKey") or result.get("PageKey")
            if not cursor: break
            if cursor in seen_pages:
                AUDIT_WARNINGS.append("BSC pagination stalled"); break
            seen_pages.add(cursor); params["pageKey"] = cursor
    return sorted(out,key=lambda t:t["ts"])

def fetch_evm_history(chain, prices):
    chain_id = 56 if chain == "bsc" else 1
    base     = "https://api.etherscan.io/v2/api"
    wallet   = EVM_ADDR.lower()
    txns     = []

    def _etherscan(action, extra=None):
        params = {
            "chainid":    chain_id,
            "module":     "account",
            "action":     action,
            "address":    EVM_ADDR,
            "startblock": 0,
            "endblock":   99999999,
            "page":       1,
            "offset":     2000,
            "sort":       "asc",
            "apikey":     ETHERSCAN_KEY,
        }
        if extra:
            params.update(extra)
        rows=[]
        for page in range(1,501):
            params["page"]=page
            try:
                r=_get(base,params=params)
                result=r.get("result")
                if not isinstance(result,list):
                    if "no transactions found" in str(r.get("message", "")).lower() or "no transactions found" in str(result).lower(): break
                    raise RuntimeError(str(r.get("message")))
                rows.extend(result)
                if len(result)<params["offset"]: break
            except Exception as e:
                AUDIT_WARNINGS.append(f"Etherscan {action} ({chain}) incomplete at page {page}: {type(e).__name__}")
                break
        else: AUDIT_WARNINGS.append(f"Etherscan {action} ({chain}) page cap")
        return rows

    for tx in _etherscan("tokentx"):
        frm = tx.get("from","").lower()
        to  = tx.get("to","").lower()
        if frm == to:
            continue
        if frm == wallet:
            tx_type, is_inflow = "withdrawal", False
        elif to == wallet:
            tx_type, is_inflow = "deposit", True
        else:
            continue
        contract = tx.get("contractAddress", "").lower()
        sym = ETH_REGISTRY.get(contract)
        if sym is None:
            QUARANTINE.append(dict(chain=chain,contract=contract,asset=tx.get("tokenSymbol"),ref=tx.get("hash"),reason="unverified contract",raw=tx)); continue
        dec   = int(tx.get("tokenDecimal") or 18)
        raw   = int(tx.get("value") or 0)
        qty   = raw / 10**dec
        price = 1.0 if sym in ("USDC","USDT","BUSD","DAI","FDUSD") else prices.get(sym, 0)
        usd   = qty * price
        if qty <= 0: continue
        ts = int(tx.get("timeStamp") or 0)
        txns.append({
            "ts":          ts,
            "dt":          datetime.fromtimestamp(ts, tz=timezone.utc),
            "type":        tx_type,
            "chain":       chain,
            "asset":       sym,
            "qty":         qty,
            "usd_value":   usd,
            "is_inflow":   is_inflow,
            "description": f"{tx_type.title()} {qty:,.4f} {sym} ({chain.upper()})",
            "ref":         tx.get("hash",""), "counterparty": frm if is_inflow else to, "contract": tx.get("contractAddress", "").lower(), "raw_qty": raw,
        })

    # Native BNB/ETH transfers
    for tx in _etherscan("txlist") + _etherscan("txlistinternal"):
        if str(tx.get("isError","0")) != "0": continue
        frm = tx.get("from","").lower()
        to  = tx.get("to","").lower()
        if frm == to:
            continue
        native = "BNB" if chain == "bsc" else "ETH"
        if frm == wallet:
            tx_type, is_inflow = "withdrawal", False
        elif to == wallet:
            tx_type, is_inflow = "deposit", True
        else:
            continue
        # Skip 0-value txns (pure contract calls)
        raw = int(tx.get("value") or 0)
        if raw == 0:
            continue
        qty   = raw / 1e18
        price = prices.get(native, 0)
        usd   = qty * price
        if qty <= 0: continue
        ts = int(tx.get("timeStamp") or 0)
        txns.append({
            "ts":          ts,
            "dt":          datetime.fromtimestamp(ts, tz=timezone.utc),
            "type":        tx_type,
            "chain":       chain,
            "asset":       native,
            "qty":         qty,
            "usd_value":   usd,
            "is_inflow":   is_inflow,
            "description": f"{tx_type.title()} {qty:,.4f} {native} ({chain.upper()})",
            "ref":         tx.get("hash",""), "counterparty": frm if is_inflow else to, "contract": tx.get("contractAddress", "").lower(), "raw_qty": raw,
        })

    txns.sort(key=lambda x: x["ts"])
    return txns

# ── Tron external deposits / withdrawals ──────────────────────────────────────
def fetch_tron_history(prices):
    txns = []
    # TRC20 transfers
    try:
        r = _get(f"https://api.trongrid.io/v1/accounts/{TRON_ADDR}/transactions/trc20",
                 params={"limit": 200, "order_by": "block_timestamp,asc"})
        for tx in (r or {}).get("data") or []:
            frm   = tx.get("from","")
            to    = tx.get("to","")
            token=(tx.get("token_info") or {})
            if token.get("address") != TRON_USDT:
                QUARANTINE.append(dict(chain="tron",contract=token.get("address"),asset=token.get("symbol"),ref=tx.get("transaction_id"),reason="unverified contract",raw=tx)); continue
            sym="USDT"
            dec   = int((tx.get("token_info") or {}).get("decimals") or 6)
            raw   = int(tx.get("value") or 0)
            qty   = raw / 10**dec
            if qty > 1_000_000_000:  # skip uint256 overflow / corrupt values
                continue
            price = 1.0 if sym in ("USDT","USDC","TUSD") else prices.get(sym, 0)
            usd   = qty * price
            if qty <= 0: continue
            if frm == TRON_ADDR:
                tx_type, is_inflow = "withdrawal", False
            elif to == TRON_ADDR:
                tx_type, is_inflow = "deposit", True
            else:
                continue
            ts = int(tx.get("block_timestamp",0) or 0) // 1000
            txns.append({
                "ts":          ts,
                "dt":          datetime.fromtimestamp(ts, tz=timezone.utc),
                "type":        tx_type,
                "chain":       "tron",
                "asset":       sym,
                "qty":         qty,
                "usd_value":   usd,
                "is_inflow":   is_inflow,
                "description": f"{tx_type.title()} {qty:,.4f} {sym} (Tron)",
                "ref":         tx.get("transaction_id",""), "counterparty": frm if is_inflow else to,
            })
    except Exception as e:
        AUDIT_WARNINGS.append(f"Tron history incomplete: {type(e).__name__}")
    txns.sort(key=lambda x: x["ts"])
    return txns

# ── Bitcoin history ────────────────────────────────────────────────────────────
def fetch_btc_history(prices):
    btc_price = prices.get("BTC", 100_000)
    txns = []
    try:
        for tx in _get(f"https://mempool.space/api/address/{BITCOIN_ADDR}/txs") or []:
            ts = (tx.get("status") or {}).get("block_time") or 0
            if not ts:
                continue
            net_sats = 0
            for vin in tx.get("vin") or []:
                if (vin.get("prevout") or {}).get("scriptpubkey_address") == BITCOIN_ADDR:
                    net_sats -= vin["prevout"].get("value", 0)
            for vout in tx.get("vout") or []:
                if vout.get("scriptpubkey_address") == BITCOIN_ADDR:
                    net_sats += vout.get("value", 0)
            qty = abs(net_sats) / 1e8
            usd = qty * btc_price
            if qty <= 0: continue
            is_inflow = net_sats > 0
            txns.append({
                "ts":          ts,
                "dt":          datetime.fromtimestamp(ts, tz=timezone.utc),
                "type":        "deposit" if is_inflow else "withdrawal",
                "chain":       "bitcoin",
                "asset":       "BTC",
                "qty":         qty,
                "usd_value":   usd,
                "is_inflow":   is_inflow,
                "description": f"{'Deposit' if is_inflow else 'Withdrawal'} {qty:.6f} BTC",
                "ref":         tx.get("txid",""),
            })
    except Exception as e:
        AUDIT_WARNINGS.append(f"BTC history incomplete: {type(e).__name__}")
    txns.sort(key=lambda x: x["ts"])
    return txns

# ── TON (Gram) jetton + native history via TonAPI v2 ──────────────────────────
_TON_STABLES = {"USDT", "USDC", "TUSD", "USD₮"}

def fetch_ton_history(prices):
    """Fetch TON jetton and native transfers via TonAPI v2 events endpoint."""
    txns  = []
    seen  = set()   # event_ids already processed
    before_lt = None

    for _ in range(20):
        params = {"limit": 100, "subject_only": "true"}
        if before_lt:
            params["before_lt"] = before_lt
        try:
            d = _get(f"https://tonapi.io/v2/accounts/{TON_ADDR}/events",
                     params=params)
        except Exception as e:
            AUDIT_WARNINGS.append(f"TON history incomplete: {type(e).__name__}")
            break

        events = (d or {}).get("events") or []

        for ev in events:
            ts    = int(ev.get("timestamp") or 0)
            ev_id = str(ev.get("event_id") or "")
            if not ts or ev_id in seen:
                continue
            seen.add(ev_id)

            for act in (ev.get("actions") or []):
                if act.get("status") != "ok" or ev.get("in_progress"):
                    continue
                atype = act.get("type")

                if atype == "JettonTransfer":
                    jt     = act.get("JettonTransfer") or {}
                    jetton = jt.get("jetton") or {}
                    sym    = str(jetton.get("symbol") or "?")
                    try:
                        dec = int(jetton.get("decimals") or 9)
                    except Exception:
                        dec = 9
                    raw_amt = int(jt.get("amount") or 0)
                    qty     = raw_amt / (10 ** dec)
                    if qty <= 0 or qty > 1_000_000_000:
                        continue
                    sender = (jt.get("sender")    or {}).get("address", "").lower()
                    recip  = (jt.get("recipient") or {}).get("address", "").lower()
                    if TON_ADDR_RAW not in (sender, recip):
                        continue
                    is_inflow = (recip == TON_ADDR_RAW)
                    if sender == recip:
                        continue  # self-transfer
                    if sym in _TON_STABLES:
                        price = 1.0
                    else:
                        underlying = _XSTOCK_TICKERS.get(sym) or sym.rstrip("x")
                        price = prices.get(underlying) or prices.get(sym, 0)
                    usd = qty * price
                    if qty <= 0: continue
                    tx_type = "deposit" if is_inflow else "withdrawal"
                    txns.append({
                        "ts": ts, "dt": datetime.fromtimestamp(ts, tz=timezone.utc),
                        "type": tx_type, "chain": "ton", "asset": sym,
                        "qty": qty, "usd_value": usd, "is_inflow": is_inflow,
                        "description": f"{tx_type.title()} {qty:,.4f} {sym} (TON)",
                        "ref": ev_id, "counterparty": sender if is_inflow else recip,
                    })

                elif atype == "TonTransfer":
                    tt      = act.get("TonTransfer") or {}
                    amt_nano = int(tt.get("amount") or 0)
                    qty      = amt_nano / 1e9
                    usd      = qty * prices.get("TON", 0)
                    if qty <= 0: continue
                    sender = (tt.get("sender")    or {}).get("address", "").lower()
                    recip  = (tt.get("recipient") or {}).get("address", "").lower()
                    if sender == TON_ADDR_RAW:
                        is_inflow = False
                    elif recip == TON_ADDR_RAW:
                        is_inflow = True
                    else:
                        continue
                    tx_type = "deposit" if is_inflow else "withdrawal"
                    txns.append({
                        "ts": ts, "dt": datetime.fromtimestamp(ts, tz=timezone.utc),
                        "type": tx_type, "chain": "ton", "asset": "TON",
                        "qty": qty, "usd_value": usd, "is_inflow": is_inflow,
                        "description": f"{tx_type.title()} {qty:,.4f} TON",
                        "ref": ev_id, "counterparty": sender if is_inflow else recip,
                    })

        if len(events) < 100:
            break
        before_lt = d.get("next_from") or (events[-1].get("lt") if events else None)

    txns.sort(key=lambda x: x["ts"])
    return txns

# ── Solana wallet external USDC/token deposits+withdrawals (SOL_WALLET_2) ─────
_sol_asset_cache = {}
_XSTOCK_TICKERS.update({"PPLTx":"PPLT", "PPLTX":"PPLT"})

def _enhanced_page(address, before=None, include_tokens=False):
    # Retry rate limits and transient errors, then try smaller pages / legacy host.
    errors=[]
    for host, limit in (("api-mainnet.helius-rpc.com",100),("api-mainnet.helius-rpc.com",25),("api.helius.xyz",25)):
        params={"api-key":HELIUS_KEY,"limit":limit}
        if include_tokens: params["token-accounts"]="balanceChanged"
        if before: params["before-signature"]=before
        for attempt in range(3):
            try:
                r=_sess.get(f"https://{host}/v0/addresses/{address}/transactions",params=params,timeout=45)
                if r.status_code in (429,500,502,503,504):
                    errors.append(str(r.status_code)); time.sleep(2**attempt); continue
                if not r.ok:
                    errors.append(str(r.status_code)); break
                page=r.json()
                if not isinstance(page,list): raise ValueError("invalid page")
                return page,limit
            except Exception as e:
                errors.append(type(e).__name__); time.sleep(2**attempt)
    raise RuntimeError("enhanced history: "+", ".join(errors))

_SOL_RAW_CACHE={}
_SOL_FALLBACK_REFS=set()
def _raw_tx_cached(sig):
    if sig not in _SOL_RAW_CACHE:
        _SOL_RAW_CACHE[sig]=_sol_get_tx(sig)
    return _SOL_RAW_CACHE[sig]

def _raw_address_signatures(address, cutoff):
    before=None
    while True:
        params={"limit":1000,"commitment":"finalized"}
        if before: params["before"]=before
        page=_sol_rpc("getSignaturesForAddress",[address,params])
        if not isinstance(page,list): raise RuntimeError("invalid RPC signature response")
        if not page: return
        for entry in page:
            bt=entry.get("blockTime")
            if (bt is None or bt>=cutoff) and entry.get("err") is None: yield entry["signature"]
        last=page[-1]; cursor=last["signature"]
        if (last.get("blockTime") is not None and last["blockTime"]<cutoff) or len(page)<1000: return
        if cursor==before: raise RuntimeError("RPC pagination stalled")
        before=cursor

def _raw_sol_rows(sig, wallet, owners, label, prices, only_pplt=False):
    tx=_raw_tx_cached(sig)
    if not tx: raise RuntimeError("transaction unavailable")
    meta=tx.get("meta") or {}
    if meta.get("err") is not None: return []
    ts=tx.get("blockTime")
    if not ts: raise RuntimeError("missing block time")
    keys=[k.get("pubkey") if isinstance(k,dict) else k for k in tx["transaction"]["message"]["accountKeys"]]
    totals={}
    for sign,field in ((-1,"preTokenBalances"),(1,"postTokenBalances")):
        for b in meta.get(field) or []:
            idx=b["accountIndex"]; account=keys[idx] if idx<len(keys) else None
            if (b.get("owner") or owners.get(account))!=wallet: continue
            mint=b["mint"]; a=b["uiTokenAmount"]
            qty=Decimal(a["amount"])/(Decimal(10)**int(a["decimals"]))
            totals[mint]=totals.get(mint,Decimal(0))+sign*qty
    if not only_pplt and wallet in keys:
        idx=keys.index(wallet)
        delta=meta["postBalances"][idx]-meta["preBalances"][idx]
        # Add back fee charged to wallet: fee belongs to expense ledger, not capital.
        if idx==0: delta+=meta.get("fee",0)
        totals["SOL"]=Decimal(delta)/Decimal(10**9)
    rows=[]
    for mint,delta in totals.items():
        if not delta or (only_pplt and mint!=PPLT_MINT): continue
        sym={SOLANA_USDC:"USDC","SOL":"SOL",PPLT_MINT:"PPLTX"}.get(mint)
        if not sym:
            if mint not in (ALEF_MINT,ALEF_MINT_OLD): QUARANTINE.append(dict(chain="solana",contract=mint,ref=sig,reason="unverified raw balance delta",qty=str(delta)))
            continue
        qty=float(abs(delta)); px=prices.get(sym) if sym!="PPLTX" else None
        rows.append(dict(ts=ts,dt=datetime.fromtimestamp(ts,timezone.utc),type="deposit" if delta>0 else "withdrawal",chain="solana",asset=sym,qty=qty,usd_value=qty*(px or 0),is_inflow=delta>0,description=f"{sym} {qty:g} ({label}) [raw balance delta]",ref=sig,counterparty="",contract=mint,unpriced=not bool(px),wallet=wallet,raw_fallback=True,quantity_basis="raw"))
    return rows

def fetch_sol_wallet_external_txns(wallet, label, prices):
    out, history = [], {}
    accounts = {wallet}; owners={wallet:wallet}; pplt_accounts=set(); fallback=set()
    for program in ("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"):
        try:
            result=_sol_rpc("getTokenAccountsByOwner",[wallet,{"programId":program},{"encoding":"jsonParsed","commitment":"finalized"}])
            for account in result["value"]:
                addr=account["pubkey"]; accounts.add(addr); owners[addr]=wallet
                info=account["account"]["data"]["parsed"]["info"]
                if info["mint"]==PPLT_MINT:
                    pplt_accounts.add(addr)
                    print(f"  {label}: PPLTX account {addr}, raw units={info['tokenAmount']['amount']}")
        except Exception as e: AUDIT_WARNINGS.append(f"{label} token-account discovery incomplete: {type(e).__name__}")
    cutoff=int(pd.to_datetime(AUDIT_START_DATE, utc=True).timestamp()) if AUDIT_START_DATE else 0
    for address in sorted(accounts):
        before=None; seen_cursors=set()
        while True:
            try: page,limit=_enhanced_page(address,before,address==wallet)
            except Exception as e:
                print(f"  {label}: switching {address} to raw RPC ({e})")
                fallback.add(address); break
            if not page: break
            for tx in page:
                if tx.get("signature") and int(tx.get("timestamp") or 0)>=cutoff: history[tx["signature"]]=tx
            cursor=page[-1].get("signature")
            if len(page)<limit or (page[-1].get("timestamp") and int(page[-1]["timestamp"])<cutoff): break
            if not cursor or cursor in seen_cursors:
                fallback.add(address); break
            seen_cursors.add(cursor); before=cursor
    raw_sigs=set(); pplt_sigs=set()
    for address in sorted(fallback|pplt_accounts):
        try:
            sigs=set(_raw_address_signatures(address,cutoff))
            if address in fallback: raw_sigs.update(sigs-set(history))
            if address in pplt_accounts: pplt_sigs.update(sigs)
            print(f"  {label}: raw RPC found {len(sigs)} signatures for {address}")
        except Exception as e: AUDIT_WARNINGS.append(f"{label} raw signature history incomplete for {address}: {type(e).__name__}")
    # Enhanced tokenAmount can be UI-scaled. Fetch raw pre/post amounts for PPLTx.
    for sig,tx in history.items():
        if any(tr.get("mint")==PPLT_MINT for tr in tx.get("tokenTransfers",[])):
            pplt_sigs.add(sig)
    verified_pplt_sigs=set()
    for sig in sorted(raw_sigs|pplt_sigs):
        try:
            out.extend(_raw_sol_rows(sig,wallet,owners,label,prices,only_pplt=sig not in raw_sigs))
            if sig in pplt_sigs:verified_pplt_sigs.add(sig)
            if sig in raw_sigs: _SOL_FALLBACK_REFS.add(sig)
        except Exception as e: AUDIT_WARNINGS.append(f"{label} raw transaction incomplete {sig}: {type(e).__name__}")
    for sig,tx in history.items():
        if tx.get("transactionError"): continue
        ts=int(tx.get("timestamp") or 0)
        for tr in list(tx.get("tokenTransfers") or [])+[dict(t,mint="SOL",tokenAmount=int(t.get("amount") or 0)/1e9) for t in tx.get("nativeTransfers") or []]:
            frm=tr.get("fromUserAccount") or owners.get(tr.get("fromTokenAccount"))
            to=tr.get("toUserAccount") or owners.get(tr.get("toTokenAccount"))
            if frm==to or wallet not in (frm,to): continue
            if frm in (SOL_WALLET,SOL_WALLET_2) and to in (SOL_WALLET,SOL_WALLET_2): continue
            mint=tr.get("mint"); qty=float(tr.get("tokenAmount") or 0)
            if qty<=0 or mint in (ALEF_MINT,ALEF_MINT_OLD) or (mint==PPLT_MINT and sig in verified_pplt_sigs): continue
            sym={SOLANA_USDC:"USDC", "SOL":"SOL", PPLT_MINT:"PPLTX"}.get(mint)
            if not sym:
                QUARANTINE.append(dict(chain="solana",contract=mint,ref=sig,raw=tr,reason="unverified mint")); continue
            # PPLTX uses scaled UI units; obtain raw amount and timestamp-specific multiplier separately.
            px=prices.get(sym)
            if sym=="PPLTX": px=None
            incoming=to==wallet
            out.append(dict(ts=ts,dt=datetime.fromtimestamp(ts,timezone.utc),type="deposit" if incoming else "withdrawal",chain="solana",asset=sym,qty=qty,usd_value=qty*(px or 0),is_inflow=incoming,description=f"{sym} {qty:g} ({label})",ref=sig,counterparty=frm if incoming else to,contract=mint,unpriced=not bool(px),wallet=wallet,quantity_basis="unknown" if sym=="PPLTX" else "raw"))
    print(f"  {label}: {len(accounts)-1} current token accounts; {len(history)} unique transactions; {len(out)} retained transfers; PPLTX={sum(t['asset']=='PPLTX' for t in out)}")
    return sorted(out,key=lambda t:t['ts'])


# ── Historical price helpers ───────────────────────────────────────────────────
def _build_alef_px_series(swaps):
    """Sorted (ts, price) list from Raydium USDC/ALEF ratios (dust filtered)."""
    out = []
    for s in swaps:
        alef_q = s.get("alef_qty", 0)
        usdc_q = s.get("qty", 0)
        if alef_q > 1.0 and usdc_q > 1.0:
            out.append((s["ts"], usdc_q / alef_q))
    out.sort(key=lambda x: x[0])
    return out

def fetch_alef_spot_price(pool_id=ALEF_POOL_ID):
    """Raydium pool spot price, in USDC per ALEF. Validate both mint addresses."""
    d = _get("https://api-v3.raydium.io/pools/info/ids", params={"ids": pool_id})
    pools = d.get("data") or []
    pool = next((p for p in pools if isinstance(p,dict) and p.get("id")==pool_id), None)
    if not pool: raise ValueError("Raydium pool missing")
    a, b = pool["mintA"]["address"], pool["mintB"]["address"]
    if {a,b} != {ALEF_MINT,SOLANA_USDC}: raise ValueError("Unexpected Raydium pool mints")
    p = float(pool["price"])  # mint B per mint A
    if not math.isfinite(p) or p <= 0: raise ValueError("Invalid Raydium spot price")
    return p if a == ALEF_MINT else 1/p


def fetch_alef_chart_history(start_ts, end_ts, mint=ALEF_MINT):
    """Use Raydium's published TradingView Birdeye base/quote feed.
    15-minute closes become available only at candle end (no look-ahead).
    Request seven-day windows to stay below 1,000 candles per response.
    """
    points = {}
    step = 7*86400
    interval = 15*60
    url = "https://birdeye-proxy.raydium.io/defi/ohlcv/base_quote"
    for lo in range(int(start_ts)//interval*interval, int(end_ts), step):
        hi = min(lo+step, int(end_ts))
        for attempt in range(3):
            try:
                d = _get(url, params={"base_address":mint,"quote_address":SOLANA_USDC,
                    "type":"15m","time_from":lo,"time_to":hi})
                payload = d.get("data",d)
                items = payload.get("items") if isinstance(payload,dict) else None
                if d.get("success") is False or not isinstance(items,list):
                    raise ValueError("Invalid chart response")
                for bar in items:
                    try:
                        ts = int(bar["unixTime"])+interval
                        p = float(bar["c"])
                        if lo < ts <= hi and math.isfinite(p) and p>0: points[ts]=p
                    except (ValueError, TypeError, KeyError):
                        continue
                if not items:
                    AUDIT_WARNINGS.append(f"Raydium ALEF chart returned no candles in window {lo}–{hi}; using trades if available")
                break
            except Exception as e:
                if attempt == 2:
                    AUDIT_WARNINGS.append(f"Raydium chart unavailable {lo}–{hi}: {type(e).__name__}")
                else: time.sleep(1+attempt*2)
        time.sleep(0.15)
    return sorted(points.items())


def alef_historical_detail(ts, chart, trades):
    """Latest available prior chart close or actual pool trade, never a future quote."""
    candidates=[]
    for points, label in [(chart,"Raydium chart (Birdeye 15m prior close)"),
                          (trades,"Raydium on-chain prior swap (execution price)")]:
        i=bisect.bisect_right(points,(ts,float("inf")))-1
        if i>=0 and 0<=ts-points[i][0]<=7*86400:
            candidates.append((points[i][0], points[i][1], label))
    if not candidates: return None,"Missing historical ALEF quote"
    _,p,label=max(candidates,key=lambda x:x[0])
    return p,label

_yf_hist_cache: dict = {}

def _yf_hist_price(ticker, ts):
    """Daily closing price for ticker at unix timestamp ts."""
    dt  = datetime.fromtimestamp(ts, tz=timezone.utc).date()
    key = (ticker, dt.isoformat())
    if key not in _yf_hist_cache:
        try:
            start = (dt - timedelta(days=4)).isoformat()
            end   = (dt + timedelta(days=4)).isoformat()
            df    = yf.download(ticker, start=start, end=end,
                                progress=False, auto_adjust=False)
            if df.empty:
                _yf_hist_cache[key] = None
            else:
                target = pd.Timestamp(dt)
                if df.index.tz is not None: target = target.tz_localize(df.index.tz)
                prior = df.index[df.index <= target]
                if len(prior) == 0: return None
                nearest = prior[-1]
                val = df["Close"].loc[nearest]
                _yf_hist_cache[key] = float(val.iloc[0] if hasattr(val, "iloc") else val)
        except Exception as e:
            print(f"  [WARN] yfinance hist {ticker} {dt}: {e}", file=sys.stderr)
            _yf_hist_cache[key] = None
    return _yf_hist_cache[key]

# ══════════════════════════════════════════════════════════════════════════════
# MAIN
# ══════════════════════════════════════════════════════════════════════════════
VERIFIED_LEG_ACTIONS = {}

print(f"\n{'═'*62}")
print("  ALEF FUND — TRANSACTION AUDIT | LIVE PRICE / RPC v1 / xStocks multipliers / on-chain paid-interest benchmark / portfolio conversion fees / persistent receipt cache")
print(f"  Generated {NOW:%Y-%m-%d %H:%M} UTC")
print(f"{'═'*62}\n")

print("▶ Fetching live ALEF/USDC price from Raydium...")
pool_id = ALEF_POOL_ID
try:
    ALEF_PRICE_USD = fetch_alef_spot_price(pool_id)
    ALEF_PRICE_SOURCE = "Raydium pool spot (USDC par assumption)"
    print(f"  ALEF=${ALEF_PRICE_USD:.8f} — {ALEF_PRICE_SOURCE}")
except Exception as e:
    AUDIT_WARNINGS.append(f"Raydium live spot unavailable: {type(e).__name__}")
    print("  Live spot unavailable; will try latest observed pool swap")

print("\n▶ Fetching Raydium swap history...")
print(f"  → Pool: {pool_id}")
swaps = fetch_raydium_swaps(pool_id)
print(f"  → {len(swaps)} swaps")
alef_trade_history = _build_alef_px_series(swaps)
if ALEF_PRICE_USD is None and alef_trade_history:
    last_ts, last_px = alef_trade_history[-1]
    if 0 <= NOW.timestamp()-last_ts <= 7*86400:
        ALEF_PRICE_USD = last_px
        ALEF_PRICE_SOURCE = f"Last observed pool trade at {datetime.fromtimestamp(last_ts,timezone.utc):%Y-%m-%d %H:%M UTC} (not live spot)"
if ALEF_PRICE_USD is None:
    print("  ALEF current quote unavailable; not substituting an invented price")
else:
    print(f"  ALEF=${ALEF_PRICE_USD:.8f} — {ALEF_PRICE_SOURCE}")

print("\n▶ Fetching current prices...")
prices = fetch_current_prices()
print(f"  BTC={prices.get('BTC',0):,.0f}  ETH={prices.get('ETH',0):,.0f}  "
      f"BNB={prices.get('BNB',0):,.0f}  SOL={prices.get('SOL',0):,.0f}")
print("  ALEF: " + (f"${ALEF_PRICE_USD:.8f} ({ALEF_PRICE_SOURCE})" if ALEF_PRICE_USD is not None else "UNAVAILABLE"))

print("\n▶ Fetching ALEF mint/burn history (Solana)...")
mb_events = fetch_alef_mint_burn_history(prices)
print(f"  → {len(mb_events)} events")
chart_start = int(pd.to_datetime(AUDIT_START_DATE, utc=True).timestamp()) if AUDIT_START_DATE else min((t["ts"] for t in mb_events+swaps),default=int(NOW.timestamp()))
print("\n▶ Fetching Raydium website chart history (15-minute ALEF/USDC candles)...")
previous_settlement = max((t["ts"] for t in mb_events if t.get("mint")==ALEF_MINT and t["ts"]<chart_start), default=chart_start)
alef_chart_history = fetch_alef_chart_history(min(chart_start,previous_settlement)-7*86400,int(NOW.timestamp()))
print(f"  → {len(alef_chart_history)} completed chart candles; {len(alef_trade_history)} on-chain trade price observations")

print("\n▶ Fetching EVM (BSC) history (NodeReal indexed)...")
bsc_txns = fetch_bsc_history(prices)
print(f"  → {len(bsc_txns)} external transfers")

print("\n▶ Fetching EVM (Ethereum) history...")
eth_txns = fetch_evm_history("ethereum", prices)
print(f"  → {len(eth_txns)} external transfers")

print("\n▶ Fetching Tron history...")
tron_txns = fetch_tron_history(prices)
print(f"  → {len(tron_txns)} external transfers")

print("\n▶ Fetching Bitcoin history...")
btc_txns = fetch_btc_history(prices)
print(f"  → {len(btc_txns)} transactions")

print("\n▶ Fetching TON (Gram) history...")
ton_txns = fetch_ton_history(prices)
print(f"  → {len(ton_txns)} transfers")

print("\n▶ Fetching both Solana custody wallets and token accounts...")
sol1_txns = fetch_sol_wallet_external_txns(SOL_WALLET, "Sol-wallet-1", prices)
sol2_txns = fetch_sol_wallet_external_txns(SOL_WALLET_2, "Sol-wallet-2", prices)
print(f"  → {len(sol2_txns)} transfers")


# ── Accounting policy ─────────────────────────────────────────────────────────
# USD 1 is a presentation/materiality threshold, not a deletion rule.
# Unknown assets and small receipts are kept separately for review.
DUST_USD = 1.0
# Confirm economic purpose using full transaction references. Do not infer from a wallet name.
# Values: subscription, redemption, founder_advance, founder_repayment,
# founder_withdrawal, expense, internal, trading, other.
CONFIRMED_PURPOSE = {}
OPENING_FOUNDER_RECEIVABLE = None  # signed USD: positive = founder owes fund
# For verified exchange/bridge groups enter BOTH sides, including actual fees in expense ledger.
CONFIRMED_REBALANCE_GROUPS = []  # list of lists of (chain, full transaction hash)
cutoff_ts = int(pd.to_datetime(AUDIT_START_DATE, utc=True).timestamp()) if AUDIT_START_DATE else 0
all_txns = sorted([t for t in mb_events+swaps+bsc_txns+eth_txns+tron_txns+btc_txns+ton_txns+sol1_txns+sol2_txns if t["ts"]>=cutoff_ts],key=lambda t:t["ts"])
# Load daily history once per ticker rather than per event.
stable_symbols = {"USDC","USDT","BUSD","DAI","FDUSD","TUSD","PYUSD","USD₮"}
crypto_symbols = {"BTC","ETH","BNB","SOL","TON","TRX"}
def ticker_for(asset):
    if asset == "TON": return "TON11419-USD"
    if asset in crypto_symbols: return asset+"-USD"
    return _PRICE_ALIASES.get(asset) or _XSTOCK_TICKERS.get(asset)
series={}
cg_series={}
start=datetime.fromtimestamp(min((t["ts"] for t in all_txns),default=NOW.timestamp()),timezone.utc).date()-timedelta(days=10)
for ticker in sorted({ticker_for(t["asset"]) for t in all_txns}-{None}):
    try:
        data=yf.download(ticker,start=str(start),end=str(NOW.date()+timedelta(days=1)),progress=False,auto_adjust=False)
        close=data["Close"]
        if isinstance(close,pd.DataFrame): close=close.iloc[:,0]
        series[ticker]=close.dropna()
    except Exception as e: AUDIT_WARNINGS.append(f"Price history unavailable {ticker}: {type(e).__name__}")
def _cg_history(asset):
    cid=_CG_IDS.get(asset.upper())
    if not cid: return []
    if cid not in cg_series:
        try:
            start_ts=int(datetime.combine(start,datetime.min.time(),tzinfo=timezone.utc).timestamp())
            d=_get(f"https://api.coingecko.com/api/v3/coins/{cid}/market_chart/range",params={"vs_currency":"usd","from":start_ts,"to":int(NOW.timestamp())})
            cg_series[cid]=sorted((float(ms)/1000,float(p)) for ms,p in d["prices"] if math.isfinite(float(p)) and float(p)>0)
        except Exception as e:
            cg_series[cid]=[]
            AUDIT_WARNINGS.append(f"CoinGecko history unavailable {asset}: {type(e).__name__}")
    return cg_series[cid]
def _cg_at(asset,ts):
    points=_cg_history(asset)
    i=bisect.bisect_right(points,(ts,float("inf")))-1
    if i>=0 and ts-points[i][0]<=7*86400: return points[i][1]
    return None
def historical_detail(asset,ts,chain=None,quantity_basis="raw"):
    if asset == "ALEF": return alef_historical_detail(ts, alef_chart_history, alef_trade_history)
    if asset in stable_symbols: return 1.0,"USD par assumption"
    # Prefer actual gold token quotes to a gold futures proxy.
    if asset.upper() in {"XAUT","PAXG","TON","TQQQON"}:
        p=_cg_at(asset,ts)
        if p is not None: return p,"CoinGecko token market quote"
    ticker=ticker_for(asset)
    day=datetime.fromtimestamp(ts,timezone.utc).date()
    p=None
    if ticker in series:
        ser=series[ticker]
        # Use completed prior daily close, avoiding future information on the transfer day.
        v=ser[[x.date()<day for x in ser.index]]
        if len(v) and (day-v.index[-1].date()).days<=7:
            candidate=float(v.iloc[-1])
            if math.isfinite(candidate) and candidate>0: p=candidate
    if p is None:
        p=_cg_at(asset,ts)
        if p is not None: return p,"CoinGecko prior market quote"
        return None,"No historical quote"
    if asset in _XSTOCK_TICKERS or asset in {"PPLTX","PPLTx","SLVon","TQQQon"}:
        if chain in _XSTOCK_NETWORKS and asset.upper() in _XSTOCK_RAW_SYMBOLS:
            factor,source=xstock_factor(asset,chain,ts,quantity_basis)
            if factor is None:return None,f"{ticker} available; {source}"
            return p*factor,f"{ticker} prior close × {factor:.9g} ({source})"
        if ALLOW_UNVERIFIED_SHARE_PROXY:
            return p,f"{ticker} prior close; underlying share proxy"
        return None,f"{ticker} available; multiplier unverified"
    return p,f"{ticker} prior close"+(" (underlying proxy)" if asset in _PRICE_ALIASES else "")
def historical(asset,ts):
    return historical_detail(asset,ts)[0]
pool_refs={t["ref"] for t in swaps}
fund_sol={SOL_WALLET,SOL_WALLET_2}
internal_refs={(chain,ref) for group in CONFIRMED_REBALANCE_GROUPS for chain,ref in group}
records=[]
for t in all_txns:
    asset=t["asset"]; typ=t["type"]; ref=t["ref"]; chain=t["chain"]
    if typ not in ("raydium_buy","raydium_sell","alef_mint","alef_burn") and asset not in stable_symbols and ticker_for(asset) is None:
        QUARANTINE.append(dict(chain=chain,asset=asset,ref=ref,reason="unsupported asset identity",raw=t))
        continue
    sign=1 if t["is_inflow"] else -1
    p,price_source=historical_detail(asset,t["ts"],chain,t.get("quantity_basis","raw"))
    amount=None if p is None else float(t["qty"])*p
    purpose=CONFIRMED_PURPOSE.get((chain,ref))
    cp=t.get("counterparty") or ""
    if typ in ("raydium_buy","raydium_sell"):
        bucket="pool market activity"; amount=float(t["qty"]); price_source="Observed pool USDC movement"
    elif typ in ("alef_mint","alef_burn"):
        bucket="token supply activity"
        # Current-mint history only; never apply it to pre-migration tokens.
        if t.get("mint") == ALEF_MINT_OLD:
            amount=None; price_source="Old ALEF mint; historical price not verified"
        else:
            amount=None if p is None else float(t["qty"])*p
            price_source += " (issuance valuation proxy)"
    elif purpose=="internal" or (chain,ref) in internal_refs or ref in VERIFIED_INTERNAL_REFS:
        bucket="confirmed internal"
    elif chain=="solana" and cp in fund_sol:
        bucket="confirmed internal"
    elif chain=="solana" and ref in RAYDIUM_LP_REFS and cp==pool_id:
        bucket="LP custody movement"
    elif chain=="solana" and ref in pool_refs and cp==pool_id:
        bucket="pool custody movement"
    elif purpose in {"subscription","redemption","founder_advance","founder_repayment","founder_withdrawal","expense","trading","other"}:
        bucket=purpose
    elif amount is None:
        bucket="unpriced custody movement"
    elif sign>0 and amount<DUST_USD and asset in stable_symbols|crypto_symbols:
        bucket="dust receipt (review)"
    elif chain=="solana" and ref in pool_refs|RAYDIUM_LP_REFS:
        bucket="pool-related custody review"
    elif t.get("raw_fallback"):
        bucket="raw custody delta review"
    else:
        bucket="unclassified custody movement"
    records.append({"Date":t["dt"],"Chain":chain,"Wallet":t.get("wallet",""),"Asset":asset,"Quantity":sign*float(t["qty"]),"USD":None if amount is None else sign*amount,"Price source":price_source,"Class":bucket,"Type":typ,"Counterparty":cp,"Ref":ref,"Description":t.get("description",""),"Contract":t.get("contract") or "","Raw quantity":str(t.get("raw_qty",""))})
ledger=pd.DataFrame(records,columns=["Date","Chain","Wallet","Asset","Quantity","USD","Price source","Class","Type","Counterparty","Ref","Description","Contract","Raw quantity"])

PROTOCOL_TOPICS = {'0x2b627736bca15cd5381dcf80b0bf11fd197d01a037c52b927a881a10fb73ba61': ('aave', 'collateral_in', -1, 1), '0x3115d1449a7b732c986cba18244e897a450f61e1bb8d589cd2e69e6c8924f9f7': ('aave', 'collateral_out', 1, 0), '0xb3d084820fb1a9decffb176436bd02558d15fac9b0ddfed8c465bc7359d7dce0': ('aave', 'borrow', 1, 1), '0xa534c8dbe71f871f9f3530e97a74601fea17b426cae02e1c5aee42c96c784051': ('aave', 'repay', -1, 0), '0xa3b9472a1399e17e123f3c2e6586c23e504184d504de59cdaa2b375e880c6184': ('morpho', 'collateral_in', -1, 0), '0xe80ebd7cc9223d7382aab2e0d1d6155c65651f83d53c8b9b06901d167e321142': ('morpho', 'collateral_out', 1, 1), '0x570954540bed6b1304a87dfe815a5eda4a648f7097a16240dcd85c9b5fd42a43': ('morpho', 'borrow', 1, 1), '0x52acb05cebbd3cd39715469f22afbf5a17496295ef3bc9bb5944056c63ccaa09': ('morpho', 'repay', -1, 0)}
MORPHO_MARKET_SELECTOR = '0x2c3c9157'
# ── Consolidated economic classification ──
# Evidence sources: Aave IPool.sol, Morpho EventsLib.sol, Ethereum deployed pools.
AAVE_POOLS={"ethereum":{"0x87870bca3f3fd6335c3f4ce8392d69350b4fa4e2"},"bsc":{"0x6807dc923806fe8fd134338eabca509979a7e0cb"}}
MORPHO_CORE="0xbbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb"
COW_SETTLEMENT="0x9008d19f58aabd9ed0d60971565aa8510560ab41"
RPC_URLS={"ethereum":"https://ethereum-rpc.publicnode.com","bsc":"https://bsc-mainnet.nodereal.io/v1/"+NODEREAL_API_KEY}
wallet_word=EVM_ADDR.lower()[2:].rjust(64,"0")
RPC_FALLBACKS = {
    "ethereum": ["https://eth.llamarpc.com", "https://ethereum.publicnode.com"],
    "bsc": ["https://bsc-rpc.publicnode.com"],
}
def evm_rpc(chain,method,params):
    errors=[]
    for url in dict.fromkeys([RPC_URLS[chain]]+RPC_FALLBACKS.get(chain,[])):
        for attempt in range(2):
            try:
                r=requests.post(url,json={"jsonrpc":"2.0","id":1,"method":method,"params":params},timeout=18)
                r.raise_for_status()
                d=r.json()
                if "error" in d:
                    err=d["error"]
                    raise ValueError(f"RPC error {err.get('code') if isinstance(err,dict) else 'unknown'}")
                if d.get("result") is None:
                    raise ValueError("null RPC result (transaction unavailable)")
                if method=="eth_getTransactionReceipt":
                    receipt=d["result"]
                    if not isinstance(receipt,dict) or receipt.get("transactionHash","").lower()!=params[0].lower():
                        raise ValueError("invalid receipt or transaction hash mismatch")
                return d["result"]
            except requests.HTTPError as e:
                errors.append(f"HTTP {e.response.status_code if e.response is not None else '?'}")
            except ValueError as e:
                errors.append(str(e)[:150])
            except Exception as e:
                errors.append(type(e).__name__)
            if attempt==0: time.sleep(0.5)
    # Etherscan proxy fallback for Ethereum receipts.
    if chain=="ethereum" and method=="eth_getTransactionReceipt":
        try:
            d=_get("https://api.etherscan.io/v2/api",params={"chainid":1,"module":"proxy",
                "action":"eth_getTransactionReceipt","txhash":params[0],"apikey":ETHERSCAN_KEY})
            receipt=d.get("result")
            if isinstance(receipt,dict) and receipt.get("transactionHash","").lower()==params[0].lower():
                return receipt
            errors.append("Etherscan proxy: no matching receipt")
        except Exception as e:
            errors.append("Etherscan proxy: "+type(e).__name__)
    raise RuntimeError(" | ".join(dict.fromkeys(errors)))
def words(data):
    data=data.removeprefix("0x").lower()
    return [data[i:i+64] for i in range(0,len(data),64) if len(data[i:i+64])==64]
def addr(word): return "0x"+word[-40:]
market_cache={}
def protocol_evidence(chain,ref):
    receipt=evm_rpc(chain,"eth_getTransactionReceipt",[ref]); result=[]
    if receipt.get("status")!="0x1": return []
    for log in receipt.get("logs",[]):
        topics=log.get("topics",[]); emitter=log.get("address","").lower()
        if not topics or topics[0].lower() not in PROTOCOL_TOPICS: continue
        proto,action,sign,amount_word=PROTOCOL_TOPICS[topics[0].lower()]
        if proto=="aave" and emitter not in AAVE_POOLS.get(chain,set()):continue
        if proto=="morpho" and (chain!="ethereum" or emitter!=MORPHO_CORE):continue
        indexed=[x[2:].lower() for x in topics[1:]]; data=words(log.get("data",""))
        # Match position owner, not any incidental address in the receipt.
        # Aave supply/borrow: onBehalfOf topic2; withdraw/repay: user topic2.
        # Morpho all four: onBehalf topic3 for supply/repay, topic2 for withdraw/borrow.
        owner_idx=1 if proto=="aave" or action in {"collateral_out","borrow"} else 2
        if len(indexed)<=owner_idx or indexed[owner_idx]!=wallet_word or len(data)<=amount_word:continue
        if proto=="aave": contract=addr(indexed[0])
        else:
            market_id="0x"+indexed[0]
            if market_id not in market_cache:
                try:
                    raw=evm_rpc(chain,"eth_call",[{"to":MORPHO_CORE,"data":MORPHO_MARKET_SELECTOR+market_id[2:]},"latest"])
                    market_cache[market_id]=words(raw)
                except Exception as e: raise RuntimeError("Morpho market parameters unavailable") from e
            params=market_cache[market_id]
            if len(params)<2:
                market_cache.pop(market_id,None)
                raise RuntimeError("Incomplete Morpho market parameters")
            contract=addr(params[1] if action.startswith("collateral") else params[0])
        result.append(dict(protocol=proto,action=action,sign=sign,contract=contract,raw=str(int(data[amount_word],16)),log_index=log.get("logIndex")))
    return result

def classify_economics(ledger, evidence):
    ledger=ledger.copy(); ledger["Evidence"]=""; ledger["Group"]=""
    # Match each protocol event to exactly one wallet leg (asset address, raw units, direction).
    for (chain,ref),g in ledger.groupby(["Chain","Ref"]):
        for e in evidence.get((chain,ref),[]):
            hits=g[(g["Contract"].str.lower()==e["contract"]) & (g["Raw quantity"]==e["raw"]) & (g.Quantity*e["sign"]>0) & (g.Class=="unclassified custody movement")]
            if len(hits)==1:
                i=hits.index[0]
                if ledger.at[i,"Evidence"]:continue
                ledger.loc[i,["Class","Evidence","Group"]]=[e["action"],f'{e["protocol"]} receipt log {e["log_index"]}, owner/asset/raw amount matched',ref]
        # Same-transaction opposite legs through a known CoW settlement are a trade, not capital.
        a=ledger.loc[g.index]; a=a[(a.Class=="unclassified custody movement") & (a.Counterparty.str.lower()==COW_SETTLEMENT)]
        if chain=="ethereum" and len(a)==2 and a.Asset.nunique()==2 and (a.Quantity>0).any() and (a.Quantity<0).any():
            ledger.loc[a.index,["Class","Evidence","Group"]]=["trade","Two opposite asset legs through CoW settlement in one transaction",ref]
        # Other two-sided transactions remain suggestions; never classify whole tx by hash alone.
        a=ledger.loc[g.index]; a=a[a.Class=="unclassified custody movement"]
        if len(a)>1 and a.Asset.nunique()>1 and (a.Quantity>0).any() and (a.Quantity<0).any():
            ledger.loc[a.index,["Class","Evidence","Group"]]=["atomic exchange review","Opposite asset legs in same transaction; purpose not verified",ref]
    for i,r in ledger.iterrows():
        action=VERIFIED_LEG_ACTIONS.get((r.Chain,r.Ref,r.Asset,1 if r.Quantity>0 else -1))
        if action in {"collateral_in","collateral_out","borrow","repay","trade","internal"}:
            ledger.loc[i,["Class","Evidence"]]=[action,"User-confirmed leg purpose"]
        elif r.Class=="unclassified custody movement" and r.Chain in RPC_URLS and r.Counterparty.lower() in PROTOCOL_ADDRS|{MORPHO_CORE,"0x38b0c12ab81976e9417d4ebfe2a34db6df22e6ad"}|AAVE_POOLS.get(r.Chain,set()):
            ledger.loc[i,["Class","Evidence"]]=["protocol review","Known protocol counterparty; action/position not yet verified"]
    return ledger
# Query receipts once per material EVM transaction, parallel with bounded concurrency.
keys=sorted(set(zip(ledger.loc[ledger.Chain.isin(RPC_URLS)&(ledger.USD.abs()>=1),"Chain"],ledger.loc[ledger.Chain.isin(RPC_URLS)&(ledger.USD.abs()>=1),"Ref"])))
print(f"\n▶ Inspecting {len(keys)} material EVM transaction receipts for lending actions...")
from concurrent.futures import ThreadPoolExecutor, as_completed
# Cache only successfully decoded, complete receipt evidence. Never cache RPC failures.
from pathlib import Path
receipt_cache_path=Path.home()/".alef_audit"/"protocol_evidence_v2.json"
cache_namespace="receipt-v2:"+EVM_ADDR.lower()
try:
    cache_document=json.loads(receipt_cache_path.read_text())
    if cache_document.get("namespace")!=cache_namespace: cache_document={}
except (OSError,ValueError): cache_document={}
receipt_cache=cache_document.get("entries",{})
if not isinstance(receipt_cache,dict): receipt_cache={}
def receipt_cache_key(key): return key[0]+":"+key[1].lower()
receipts={key:receipt_cache[receipt_cache_key(key)] for key in keys
          if isinstance(receipt_cache.get(receipt_cache_key(key)),list)}
print(f"  → {len(receipts)} previously decoded receipts recovered from cache")
with ThreadPoolExecutor(max_workers=4) as ex:
    futures={ex.submit(protocol_evidence,*key):key for key in keys if key not in receipts}
    for f in as_completed(futures):
        key=futures[f]
        try:
            receipts[key]=f.result()
            receipt_cache[receipt_cache_key(key)]=receipts[key]
        except Exception as e: AUDIT_WARNINGS.append(f"Receipt review incomplete {key[0]} {key[1]}: {e}")
try:
    receipt_cache_path.parent.mkdir(parents=True,exist_ok=True)
    tmp=receipt_cache_path.with_suffix(".tmp")
    tmp.write_text(json.dumps({"namespace":cache_namespace,"entries":receipt_cache}))
    os.replace(str(tmp),str(receipt_cache_path))
except OSError as e: AUDIT_WARNINGS.append(f"Could not persist receipt cache: {type(e).__name__}")
ledger=classify_economics(ledger,receipts)
# Prior successful audit output (2026-11-26 03:16 UTC) classified these exact
# PYUSD legs as repayments. Preserve that evidence if fresh decoding fails.
# This is a prior-run fallback, not a newly independently verified receipt.
prior_repayments={
    "0xc05088b31906b51544741d3ff018288e5df0970abd60757dd5979fa75f1bfcbc":4992.5257,
    "0x616d459d94fa19574796d94ca6182b2de28e696cc190e5ac4fceb9d7fb1aee85":3045.0,
}
for ref,qty in prior_repayments.items():
    hit=ledger[(ledger.Chain=="ethereum") & (ledger.Ref.str.lower()==ref) &
               (ledger.Asset.str.upper()=="PYUSD") & ((ledger.Quantity+qty).abs()<0.00006)]
    if len(hit)==1:
        i=hit.index[0]
        if ledger.at[i,"Class"] in {"unclassified custody movement","protocol review","raw custody delta review"}:
            ledger.loc[i,["Class","Evidence","Group"]]=["repay","Prior successful run: receipt-derived repayment; exact reference/asset/quantity matched",ref]
            AUDIT_WARNINGS.append("Prior-run repayment fallback used: "+ref)
# Separate small outgoing operational transfers too, but keep them in custody reconciliation.
small=(ledger.Class=="unclassified custody movement") & (ledger.USD<0) & (ledger.USD.abs()<1)
ledger.loc[small,"Class"]="small outgoing review"

# ── One economic flow ledger ────────────────────────────────────────────────
# Identified direct lending/LP operations change the location of fund assets or
# principal liabilities, not the external transfer balance. Keep the raw leg.
for i,r in ledger.iterrows():
    cp=str(r.Counterparty or "")
    key=cp.lower() if r.Chain in ("ethereum","bsc") else cp
    endpoint=LENDING_ENDPOINTS.get(r.Chain,{}).get(key)
    if endpoint and r.Class in {"unclassified custody movement","protocol review","raw custody delta review","atomic exchange review"}:
        ledger.at[i,"Class"]="protocol custody (internal)"
        ledger.at[i,"Evidence"]=endpoint+"; verified protocol endpoint, principal classification approximate"

# Explicitly distinguish original capital-flow diagnostic from the direct wallet movement.
# Exclude identified internal principal/LP legs; keep same-transaction trades as signed
# historical value differences, so pricing/transaction costs remain visible.
INTERNAL_CLASSES={"confirmed internal","internal","collateral_in","collateral_out","borrow","repay","protocol custody (internal)","LP custody movement","pool custody movement"}

def build_reverse(frame, now):
    a=frame.copy()
    a["Raw USD"]=pd.to_numeric(a["USD"],errors="coerce")
    a["Net USD"]=a["Raw USD"]
    a.loc[a.Class.isin(INTERNAL_CLASSES),"Net USD"]=0.0
    a.loc[a.Class=="pool market activity","Net USD"]=a.loc[a.Class=="pool market activity","Raw USD"]*POOL_FLOW_SHARE
    if not INCLUDE_ISSUANCE_OFFSET:
        a.loc[a.Class=="token supply activity","Net USD"]=0.0
    # Hide dust/small operation legs in the visible timeline, but INCLUDE their known
    # values in the full cumulative total. No blanket deletion of small withdrawals.
    small=a["Raw USD"].notna() & (a["Raw USD"].abs()<DUST_LIMIT_USD) & ~a.Class.isin(["token supply activity"])
    # Atomic timestamps: same timestamp has the same after-event running balance.
    # This avoids inventing within-block ordering or false intermediate trade imbalances.
    by_time=a.groupby("Date",sort=True)["Net USD"].agg(net=lambda x:x.sum(min_count=1),missing=lambda x:x.isna().sum())
    by_time["Known net"]=by_time.net.fillna(0)
    # backward balance immediately AFTER this timestamp = minus all LATER flows.
    by_time["Balance vs Now"]=-(by_time["Known net"].iloc[::-1].cumsum().iloc[::-1]-by_time["Known net"])
    by_time["Unpriced later legs"]=by_time.missing.iloc[::-1].cumsum().iloc[::-1]-by_time.missing
    a=a.join(by_time[["Balance vs Now","Unpriced later legs"]],on="Date")
    a=a.sort_values(["Date","Ref"],ascending=[False,True])
    dust=a.loc[small.reindex(a.index)].copy()
    return a,a.loc[~small.reindex(a.index)].copy(),dust,by_time

# ── Match portfolio conversion legs (NOT ALEF/USDC market trading) ────────────
# Preserve all observed ledger flows. A matched withdrawal and deposit are NOT
# deleted: their actual value difference is the residual the cost credit explains.
# Use each leg at most once. Same-asset transfers, USDC/USDT and Raydium cash
# settlements receive no fee. Matching is an estimate absent exchange fills.
CONVERSION_MATCH_HOURS=24
CONVERSION_VALUE_TOL=0.03  # prior-close quotes can differ from execution prices
CONVERSION_MIN_USD=25.0
FREE_STABLE_PAIR={"USDC","USDT"}
ASSET_EQUIVALENTS={"WBTC":"BTC","CBBTC":"BTC","WETH":"ETH","WBNB":"BNB","WSOL":"SOL","USD₮":"USDT"}
def canonical_asset(a):
    a=str(a).upper()
    return ASSET_EQUIVALENTS.get(a,a)
def fee_free_pair(a,b):
    a,b=canonical_asset(a),canonical_asset(b)
    return a==b or {a,b}==FREE_STABLE_PAIR

def match_portfolio_conversions(frame, opening, now):
    a=frame.copy().reset_index(drop=True)
    a["Date"]=pd.to_datetime(a.Date,utc=True)
    a["USD"]=pd.to_numeric(a.USD,errors="coerce")
    eligible={"unclassified custody movement","raw custody delta review","trade","trading","atomic exchange review"}
    a=a.loc[(a.Date>opening)&(a.Date<=now)&(a.USD.abs()>=CONVERSION_MIN_USD)&
            a.Class.isin(eligible|{"pool market activity"})].copy()
    a["Pool"]=a.Class.eq("pool market activity")
    a["Canon"]=a.Asset.map(canonical_asset)
    a=a.loc[~a.Canon.isin({"ALEF","ALEF OLD"}) | a.Pool]
    rows={i:r for i,r in a.iterrows()}
    out=[i for i,r in rows.items() if r.USD<0]
    inc=[i for i,r in rows.items() if r.USD>0]
    used=set(); matches=[]
    def record(i,j,kind,source):
        o,d=rows[i],rows[j]; used.update((i,j))
        value=-float(o.USD)
        matches.append({"Date":max(o.Date,d.Date),"Kind":kind,"Asset out":o.Asset,"Asset in":d.Asset,
          "USD out":value,"USD in":float(d.USD),"Observed shortfall":value-float(d.USD),
          "Fee":value*TRADING_FEE_RATE if kind=="Portfolio conversion" else 0.0,
          "Out ref":str(o.Chain)+":"+str(o.Ref),"In ref":str(d.Chain)+":"+str(d.Ref),
          "Source":source,"Hours apart":abs((d.Date-o.Date).total_seconds())/3600})
    # First recognize genuine two-sided atomic trades (same chain/ref), not
    # independent receipts. No size-ratio gate on a known CoW execution.
    for (chain,ref),g in a.loc[~a.Pool].groupby(["Chain","Ref"]):
        outs=[i for i in g.index if i in out and i not in used]
        ins=[i for i in g.index if i in inc and i not in used]
        if len(outs)!=1 or len(ins)!=1:continue
        i,j=outs[0],ins[0]; o,d=rows[i],rows[j]
        if o.Class not in {"trade","trading","atomic exchange review"} or d.Class not in {"trade","trading","atomic exchange review"}:continue
        if not fee_free_pair(o.Asset,d.Asset) and o.Class!="trade" and abs(d.USD/(-o.USD)-1)>CONVERSION_VALUE_TOL:continue
        record(i,j,"Fee-free movement" if fee_free_pair(o.Asset,d.Asset) else "Portfolio conversion",
               "Same-transaction CoW trade" if o.Class==d.Class=="trade" else "Same-transaction opposing legs (inferred)")
    def match_pass(mode):
        # Score value similarity and time proximity, accept mutual best matches
        # only when there is a meaningful margin over the next candidate.
        candidates=[]
        for i in out:
            if i in used:continue
            o=rows[i]
            for j in inc:
                if j in used:continue
                d=rows[j]
                hrs=abs((d.Date-o.Date).total_seconds())/3600
                if hrs>CONVERSION_MATCH_HOURS or (o.Pool and d.Pool):continue
                ratio=float(d.USD)/(-float(o.USD))
                if mode=="free":
                    if o.Pool or d.Pool or not fee_free_pair(o.Asset,d.Asset):continue
                    if abs(ratio-1)>0.01:continue
                    score=abs(ratio-1)+hrs/2400
                elif mode=="pool":
                    if not (o.Pool ^ d.Pool):continue
                    cash=d if o.Pool else o
                    if cash.Canon not in FREE_STABLE_PAIR or hrs>6 or abs(ratio-1)>0.01:continue
                    score=abs(ratio-1)+hrs/2400
                else:
                    if o.Pool or d.Pool or fee_free_pair(o.Asset,d.Asset):continue
                    if abs(ratio-(1-TRADING_FEE_RATE))>CONVERSION_VALUE_TOL:continue
                    score=abs(ratio-(1-TRADING_FEE_RATE))+hrs/1200
                candidates.append((score,i,j))
        by_o={};by_i={}
        for item in sorted(candidates):
            _,i,j=item
            by_o.setdefault(i,[]).append(item);by_i.setdefault(j,[]).append(item)
        def clear(c): return len(c)==1 or c[1][0]-c[0][0]>=0.001
        for item in sorted(candidates):
            _,i,j=item
            if i in used or j in used:continue
            if by_o[i][0]!=item or by_i[j][0]!=item or not clear(by_o[i]) or not clear(by_i[j]):continue
            if mode=="free": kind="Fee-free movement"
            elif mode=="pool": kind="Raydium cash settlement (excluded)"
            else: kind="Portfolio conversion"
            record(i,j,kind,"Mutual best time/value match (inferred; not exchange fill)")
    match_pass("free")
    match_pass("pool")
    match_pass("conversion")
    # Unmatched legs remain in the raw residual and are not charged a fee.
    unmatched=a.loc[~a.index.isin(used)&~a.Pool].copy()
    cols=["Date","Kind","Asset out","Asset in","USD out","USD in","Observed shortfall","Fee","Out ref","In ref","Source","Hours apart"]
    return pd.DataFrame(matches,columns=cols),unmatched

conversion_matches,unmatched_conversion_legs=match_portfolio_conversions(
    ledger,pd.to_datetime(cutoff_ts,unit="s",utc=True),pd.Timestamp(NOW))
# ── Contractual/estimated fee schedule ───────────────────────────────────────
# Trading credit is 0.5% of a matched portfolio conversion's outgoing notional,
# once per pair, not the difference between two prior-close valuations.
# Management accrues on NAV throughout the audit window; settlements are reported separately.
def build_fee_schedule(mb, supply_events, conversions, supply_now, now_ts, cutoff,
                       nav_history=None, quote_at=None):
    from collections import defaultdict
    end = float(now_ts)
    changes = defaultdict(float)
    for e in supply_events:
        if e.get("mint")==ALEF_MINT and e["ts"]<=end:
            changes[e["ts"]] += float(e["qty"])*(1 if e["type"]=="alef_mint" else -1)
    change_times = sorted(changes)
    # Roll the exact current on-chain supply back across all recorded mints/burns.
    running = supply_now - sum(changes.values()) if supply_now is not None else None
    supply_levels=[]
    for t in change_times:
        if running is not None: running += changes[t]
        supply_levels.append(running)
    def supply_at(t):
        if supply_now is None: return None
        i=bisect.bisect_right(change_times,t)-1
        return supply_levels[i] if i>=0 else supply_now-sum(changes.values())
    navs = None
    if nav_history is not None:
        navs=pd.Series(nav_history,dtype=float).copy()
        navs.index=pd.to_datetime(navs.index,utc=True)
        navs=navs[navs.map(lambda v: math.isfinite(v) and v>0)].sort_index()
        navs=navs[~navs.index.duplicated(keep="last")]
    nav_times=[] if navs is None else [t.timestamp() for t in navs.index]
    nav_values=[] if navs is None else navs.tolist()
    def nav_at(t):
        if nav_times:
            i=bisect.bisect_right(nav_times,t)-1
            if i>=0 and t-nav_times[i]<=7*86400:return nav_values[i]
            return None
        q=supply_at(t); px=quote_at(t) if quote_at else None
        if q is None or q<0 or px is None or not math.isfinite(px) or px<=0:return None
        return q*px
    settlement_refs=defaultdict(set)
    for e in mb:
        if e.get("mint")==ALEF_MINT and e["ts"]<=end:
            settlement_refs[e["ts"]].add(e["ref"])
    settlements=sorted(settlement_refs)
    def accrual_intervals(lo,hi):
        # Integrate only over the selected audit window. NAV is held constant
        # between observations; fee accrues pro rata in elapsed UTC seconds.
        if hi<=lo:return []
        points={lo,hi}
        points.update(t for t in change_times if lo<t<hi)
        points.update(t for t in nav_times if lo<t<hi)
        points.update(t for t in settlements if lo<t<hi)
        if not nav_times:
            points.update(t for t,p in alef_chart_history+alef_trade_history if lo<t<hi)
        points.update(range((int(lo)//86400+1)*86400,int(hi),86400))
        points=sorted(points); intervals=[]
        for a,b in zip(points,points[1:]):
            nav=nav_at(a)
            intervals.append((a,b,0.0 if nav is None else nav*ANNUAL_FEE_RATE*(b-a)/(365.25*86400),
                              b-a if nav is None else 0.0))
        return intervals
    result=[]
    start=float(cutoff) if cutoff else min([end]+change_times+settlements+nav_times)
    intervals=accrual_intervals(start,end)
    for a,b,amount,missing in intervals:
        result.append(dict(Date=pd.to_datetime(b,unit="s",utc=True),Kind="Management accrual",
                           Fee=amount,Incomplete=missing>0,Missing_seconds=missing,
                           Ref="",Source="0.5% annual rate × "+("supplied historical NAV" if nav_times else "market-cap NAV proxy")))
    # Settlements are informational: amounts already accrue above and must NOT
    # be added to the benchmark a second time. Exclude pre-opening entitlement.
    settlement_summary=[]
    prev=start
    for t in settlements:
        if not start<t<=end:continue
        covered=accrual_intervals(prev,t)
        settlement_summary.append(dict(Date=pd.to_datetime(t,unit="s",utc=True),
            Kind="Estimated management settlement (audit-period portion)",
            Fee=sum(x[2] for x in covered),Missing_seconds=sum(x[3] for x in covered),
            Ref="; ".join(sorted(settlement_refs[t]))))
        prev=t
    unsettled_intervals=accrual_intervals(prev,end)
    unsettled=sum(x[2] for x in unsettled_intervals)
    unsettled_missing=sum(x[3] for x in unsettled_intervals)
    for _,e in conversions.iterrows():
        if e["Kind"]!="Portfolio conversion" or not cutoff<e.Date.timestamp()<=end:continue
        result.append(dict(Date=e.Date,Kind="Portfolio trading cost credit",
                           Fee=float(e.Fee),Incomplete=False,Missing_seconds=0.0,
                           Ref=e["Out ref"]+" → "+e["In ref"],
                           Source="0.5% × outgoing conversion notional; "+e.Source))
    return pd.DataFrame(result,columns=["Date","Kind","Fee","Incomplete","Missing_seconds","Ref","Source"]),unsettled,unsettled_missing,pd.DataFrame(settlement_summary,columns=["Date","Kind","Fee","Missing_seconds","Ref"])

try:
    supply_response=_sol_rpc("getTokenSupply",[ALEF_MINT,{"commitment":"finalized"}])["value"]
    fee_supply_now=int(supply_response["amount"])/10**int(supply_response["decimals"])
except Exception as e:
    fee_supply_now=None
    AUDIT_WARNINGS.append(f"Fee benchmark: current mint supply unavailable ({type(e).__name__})")
fee_nav_history=globals().get("ALEF_NAV_HISTORY")
fee_schedule, unsettled_management_fee, unsettled_missing, estimated_management_settlements=build_fee_schedule(
    mb_events,RAW_ALEF_SUPPLY_EVENTS,conversion_matches,fee_supply_now,NOW.timestamp(),cutoff_ts,
    nav_history=fee_nav_history,quote_at=lambda t:alef_historical_detail(t,alef_chart_history,alef_trade_history)[0])
fee_nav_source="Supplied historical NAV" if fee_nav_history is not None and len(fee_nav_history) else "Estimated NAV = historical ALEF market price × reconstructed live-mint supply"
def make_backward_fee(schedule):
    """Positive add-back of fee withdrawals strictly AFTER the given timestamp."""
    by_time=schedule.groupby("Date")["Fee"].sum().sort_index()
    times=[t.timestamp() for t in by_time.index]
    suffix=[0.0]*(len(times)+1)
    for i in range(len(times)-1,-1,-1):
        suffix[i]=suffix[i+1]+float(by_time.iloc[i])
    def at(date,include_same=False):
        ts=pd.Timestamp(date).timestamp()
        i=(bisect.bisect_left if include_same else bisect.bisect_right)(times,ts)
        return suffix[i]
    return at

calculated_backward_fee=make_backward_fee(fee_schedule)
# Optional verified cash-fee withdrawals from independent records or confirmed
# on-chain transfers. Each record: Date (actual UTC payment timestamp), Kind
# ("Management" or "Trading"), Fee (positive USD actually withdrawn), Ref (unique
# payment reference; append a leg identifier if one tx contains multiple fees).
# Supply before this cell as ALEF_VERIFIED_FEE_WITHDRAWALS (list of dicts/DataFrame).
# Set ALEF_FEE_WITHDRAWALS_COMPLETE=True only if all fee payments are accounted for.
# Do not put theoretical fees or unrelated transfer amounts in this input.
verified_input=globals().get("ALEF_VERIFIED_FEE_WITHDRAWALS")
verified_fees=pd.DataFrame(columns=["Date","Kind","Fee","Ref"])
if verified_input is not None:
    verified_fees=pd.DataFrame(verified_input).copy()
    if not verified_fees.empty:
        required={"Date","Kind","Fee","Ref"}
        if not required.issubset(verified_fees.columns):
            raise ValueError("Verified fee records require Date, Kind, Fee, Ref")
        verified_fees["Date"]=pd.to_datetime(verified_fees["Date"],utc=True,errors="raise")
        verified_fees["Fee"]=pd.to_numeric(verified_fees["Fee"],errors="raise")
        if (verified_fees.Date.isna().any() or not verified_fees.Fee.map(lambda v:math.isfinite(v) and v>=0).all()
            or verified_fees.Ref.isna().any() or verified_fees.Ref.astype(str).str.strip().eq("").any()
            or verified_fees.Ref.duplicated().any() or not verified_fees.Kind.isin(["Management","Trading"]).all()):
            raise ValueError("Invalid or duplicate verified fee record")
        verified_fees=verified_fees.loc[(verified_fees.Date>=pd.to_datetime(cutoff_ts,unit="s",utc=True)) & (verified_fees.Date<=pd.Timestamp(NOW))].copy()
    else:
        verified_fees=pd.DataFrame(columns=["Date","Kind","Fee","Ref"])
verified_complete=verified_input is not None and bool(globals().get("ALEF_FEE_WITHDRAWALS_COMPLETE",False))
verified_backward_fee=make_backward_fee(verified_fees)
# Opening is immediately AFTER the cutoff transaction. Neither series is
# normalized at NOW. Net deposits = signed net fund inflows.
reverse,visible,dust,by_time=build_reverse(ledger,NOW)
opening=pd.to_datetime(cutoff_ts,unit="s",utc=True) if cutoff_ts else (
    reverse.Date.min() if len(reverse) else pd.Timestamp(NOW))
now_point=pd.Timestamp(NOW)

def make_opening_cumulative(values, opening, now, sign=1.0):
    """Independent forward cumulative sum, after opening through t inclusive."""
    opening,now=pd.Timestamp(opening),pd.Timestamp(now)
    if now<opening: raise ValueError("Audit opening is after current time")
    values=values.groupby(level=0).sum().sort_index()
    if values.empty: return lambda date: 0.0
    values=values.loc[(values.index>opening)&(values.index<=now)]
    if not values.empty and not values.map(math.isfinite).all():
        raise ValueError("Nonfinite values in cumulative series")
    times=[t.timestamp() for t in values.index]
    prefix=[0.0]
    for v in values: prefix.append(prefix[-1]+sign*float(v))
    def at(date):
        ts=min(pd.Timestamp(date),now).timestamp()
        return prefix[bisect.bisect_right(times,ts)]
    return at

# ── Borrowing interest reconstructed from historical on-chain debt ────────────
# Interest = closing debt - opening debt - new borrow principal + repayments.
# All amounts first in loan-token base units. No current-balance × APR estimate.
# Aave V4 includes the risk premium; Morpho accrues its borrow-share index at
# each historical block; Euler uses debtOf. Only covered positions are summed.
# Interest is a FUND expense, not manager remuneration. Internal interest is
# included on both sides of the economic chart, because the custody ledger
# excludes borrow/repay transfers. An already observed external interest expense
# can be credited against the residual only with independently verified refs.
import functools

# Ethereum Keccak-256 (NOT hashlib.sha3_256). Use installed eth_utils or Crypto,
# otherwise use the bundled selector table generated from the documented ABIs.
_INTEREST_ABI = {'Borrow(address,uint256)': '0xcbc04eca7e9da35cb1393a6135a199ca52e450d5e9251cbd99f7847d33a36750', 'Borrow(address,uint256,uint256,uint256)': '0x13ed6866d4e1ee6da46f845c46d7e54120883d75c5ea9a2dacc1c4ca8984ab80', 'Borrow(bytes32,address,address,address,uint256,uint256)': '0x570954540bed6b1304a87dfe815a5eda4a648f7097a16240dcd85c9b5fd42a43', 'Borrow(uint256,address,address,uint256,uint256)': '0xef18174796a5d2f91d51dc5e907a4d7867bbd6e800f6225168e0453d581d0dcd', 'Liquidate(address,address,address,uint256,uint256)': '0x8246cc71ab01533b5bebc672a636df812f10637ad720797319d5741d5ebb3962', 'Liquidate(bytes32,address,address,uint256,uint256,uint256,uint256,uint256)': '0xa4946ede45d0c6f06a0f5ce92c9ad3b4751452d2fe0e25010783bcab57a67e41', 'LiquidateBorrow(address,address,uint256,address,uint256)': '0x298637f684da70674f26509b10f07ec2fbc77a335ab1e7d6215a4b2484d8bb52', 'LiquidationCall(uint256,uint256,address,address,bool,uint256,uint256,(int256,int256,uint256),uint256,uint256,uint256)': '0x2a1f12d996f530f89d8038aa293f9fde81cac44b6dfd6225e3358d09b78a4a37', 'PullDebt(address,address,uint256)': '0xe6d0bfd9025bf59969101a13cf02e3ba2811b533816c47d7155546c7c8a1048f', 'Repay(address,uint256)': '0x5c16de4f8b59bd9caf0f49a545f25819a895ed223294290b408242e72a594231', 'Repay(bytes32,address,address,uint256,uint256)': '0x52acb05cebbd3cd39715469f22afbf5a17496295ef3bc9bb5944056c63ccaa09', 'Repay(uint256,address,address,uint256,uint256,(int256,int256,uint256))': '0xd765a0263e8a360da8dd4fdb8c0dc5553adec12a96f29a462cdb45e5bea407dd', 'RepayBorrow(address,address,uint256,uint256,uint256)': '0x1a2a22cb034d26d1854bdc6666a5b91fe25efbbb5dcad3b0355478d6f5c362a1', 'asset()': '0x38d52e0f1dbe7a70d1f1bbce52487d111fd5a226368cd8ae0e1fc641c0299139', 'borrowBalanceCurrent(address)': '0x17bfdfbc470798dfc48d52d1eddabddfa8b8b9511839bfcae88d66cf89851e21', 'borrowRateView((address,address,address,address,uint256),(uint128,uint128,uint128,uint128,uint128,uint128))': '0x8c00bf6ba9f28eac57753f4c26d930190e427f0575a20e721486c4c9e7daf014', 'debtOf(address)': '0xd283e75f6f914f593072d7dfecf53d0fb46a759ef0ea0df0190540f8a5bc982c', 'decimals()': '0x313ce567add4d438edf58b94ff345d7d38c45b17dfc0f947988d7819dca364f9', 'getReserve(uint256)': '0x77778db30ddbbd58d238fdee79ae5d424a0b2234dd9db2b95eb713548d1571aa', 'getUserTotalDebt(uint256,address)': '0x9b7172a6612b51cd8851b60fb2c020dec6080612fec81eb47bf3f8db1141a643', 'idToMarketParams(bytes32)': '0x2c3c915717aa624ad13c9e8e8431a9f6f0b888c080c546f358ea4c4fece73b60', 'market(bytes32)': '0x5c60e39ac0d7b21e2fa891758c5fbc086b4201452fba8ca8abc7419e25aea533', 'position(bytes32,address)': '0x93c52062628e4eb42860e48e7b53e762fe381fd26ace9c0767e2a4c01aa3212b', 'underlying()': '0x6f307dc33eda939db5102f62714675974157fd7019165a7f825f844496510d79'}
_INTEREST_ABI.update({'getAssetsIn(address)': '0xabfceffc7191895ac00a4bbdf817691528aec1222eea5b284c12d7b6cfeab83e', 'Transfer(address,address,uint256)': '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', 'positionsNftIdOfUser(address)': '0xc67b5093f5fe9e79467028a12e3a78c8e7c7dc3c0226a620d45e26361dbf44e9', 'positionByNftId(uint256)': '0x144128e8396543a3e3ed5d43e136adccddd17c1a0e1d32d357c20777997639f6', 'LogOperate(address,uint256,int256,int256,address)': '0xfef64760e30a41b9d5ba7dd65ff7236a61d89ed8b44c67a29e84db1a67513a1c', 'LogLiquidate(address,uint256,uint256,address)': '0x80fd9cc6b1821f4a510e45ffce6852ea3404807b5d3d833ffa85664408afcb66'})
def _it_hash(sig): return _INTEREST_ABI[sig]
def _it_word(v):
    return (f'{v:064x}' if isinstance(v,int) else str(v).removeprefix('0x').lower().rjust(64,'0'))

def _it_rpc(chain,method,params):
    # Archive-capable endpoints are preferred; each failing endpoint is skipped.
    # Never substitute latest state for a historical block.
    explicit=os.getenv({'ethereum':'ALEF_ETH_ARCHIVE_RPC','bsc':'ALEF_BSC_ARCHIVE_RPC'}[chain])
    node='https://'+('eth' if chain=='ethereum' else 'bsc')+'-mainnet.nodereal.io/v1/'+NODEREAL_API_KEY
    extra={'ethereum':['https://ethereum-rpc.publicnode.com','https://eth.drpc.org','https://mainnet.gateway.tenderly.co'],
           'bsc':['https://bsc-rpc.publicnode.com','https://bsc.drpc.org']}[chain]
    urls=list(dict.fromkeys(([explicit] if explicit else [])+[node]+extra))
    preferred=_IT_RPC_PREFERRED.get((chain,method))
    if preferred in urls:urls.remove(preferred);urls.insert(0,preferred)
    errors=[]
    for url in urls:
        try:
            r=requests.post(url,json={'jsonrpc':'2.0','id':1,'method':method,'params':params},timeout=15)
            r.raise_for_status();d=r.json()
            if 'error' in d or d.get('result') is None:raise RuntimeError(str(d.get('error','null RPC result'))[:180])
            _IT_RPC_PREFERRED[(chain,method)]=url
            return d['result']
        except Exception as e:errors.append(type(e).__name__+': '+str(e).replace(url,'[RPC]')[:200])
    if chain=='ethereum' and method in ('eth_blockNumber','eth_getBlockByNumber'):
        try:
            q={'chainid':1,'module':'proxy','action':method,'apikey':ETHERSCAN_KEY}
            if method=='eth_getBlockByNumber':q.update(tag=params[0],boolean='false')
            d=_get('https://api.etherscan.io/v2/api',params=q)
            if d.get('result') is not None and 'error' not in d:return d['result']
        except Exception:pass
    raise RuntimeError(' | '.join(dict.fromkeys(errors)))
_IT_RPC_PREFERRED={}

@functools.lru_cache(maxsize=None)
def _it_block(chain,n):
    d=_it_rpc(chain,'eth_getBlockByNumber',[hex(n),False]);return int(d['timestamp'],16)

def _it_block_at(chain,ts,hi):
    # Highest block timestamp <= cutoff, using chain data, not guessed blocks/day.
    # Explorer timestamp lookup avoids dozens of RPC calls. Verify boundary.
    try:
        d=_get('https://api.etherscan.io/v2/api',params={'chainid':1 if chain=='ethereum' else 56,'module':'block','action':'getblocknobytime','timestamp':int(ts),'closest':'before','apikey':ETHERSCAN_KEY})
        n=int(d['result'])
        if 0<=n<=hi and _it_block(chain,n)<=ts and (n==hi or _it_block(chain,n+1)>ts):return n
    except Exception:pass
    lo=0
    while lo<hi:
        mid=(lo+hi+1)//2
        if _it_block(chain,mid)<=ts:lo=mid
        else:hi=mid-1
    return lo

def _it_call(chain,contract,sig,args,block):
    raw=_it_rpc(chain,'eth_call',[{'to':contract,'data':_it_hash(sig)[:10]+''.join(_it_word(a) for a in args)},hex(block)])
    w=words(raw)
    if not w: raise ValueError('Empty historical contract response')
    return w

_IT_LOG_CACHE={}
_IT_INDEX_AVAILABLE={}
def _it_indexed_logs(chain,contract,topics,start,end):
    # Etherscan v2 indexed API. Page in bounded ranges; confirm topic matches.
    if _IT_INDEX_AVAILABLE.get(chain) is False:raise RuntimeError('Indexed logs unavailable on this chain')
    q={'chainid':1 if chain=='ethereum' else 56,'module':'logs','action':'getLogs','fromBlock':start,'toBlock':end,'offset':1000,'apikey':ETHERSCAN_KEY}
    if contract:q['address']=contract
    slots=[i for i,v in enumerate(topics) if v is not None]
    for i in slots:q['topic'+str(i)]=topics[i]
    for x,y in zip(slots,slots[1:]):q[f'topic{x}_{y}_opr']='and'
    seen=set();out=[]
    for page in range(1,51):
        q['page']=page;d=_get('https://api.etherscan.io/v2/api',params=q);r=d.get('result')
        if d.get('status')=='0' and 'no records' in str(d.get('message','')).lower():
            _IT_INDEX_AVAILABLE[chain]=True;return out
        if d.get('status')!='1' or not isinstance(r,list):
            msg=str(r)[:150]
            if any(x in msg.lower() for x in ('free api','not supported','invalid api key','subscription')):_IT_INDEX_AVAILABLE[chain]=False
            raise RuntimeError('Indexed logs: '+msg)
        _IT_INDEX_AVAILABLE[chain]=True
        for l in r:
            key=(l['transactionHash'],l['logIndex']); t=l['topics']
            if key in seen:raise RuntimeError('Repeated indexed page')
            if not start<=int(l['blockNumber'],16)<=end or (contract and l['address'].lower()!=contract.lower()) or any(i>=len(t) or t[i].lower()!=topics[i].lower() for i in slots):raise RuntimeError('Unexpected indexed log')
            seen.add(key);out.append(l)
        if len(r)<1000:return out
        time.sleep(.25)
    raise RuntimeError('Indexed log pagination incomplete')

def _it_logs(chain,contract,topics,start,end):
    if start>end:return []
    key=(chain,contract,tuple(topics),start,end)
    if key in _IT_LOG_CACHE:return _IT_LOG_CACHE[key]
    try:
        result=_it_indexed_logs(chain,contract,topics,start,end)
    except Exception as index_error:
        # Try wide RPC ranges, split only when needed. Do not silently return a partial scan.
        step=int(globals().get('ALEF_INTEREST_LOG_SPAN',1000000));budget=int(globals().get('ALEF_INTEREST_LOG_QUERY_LIMIT',120))
        result=[];pending=[(a,min(a+step-1,end)) for a in range(start,end+1,step)]
        while pending:
            a,b=pending.pop(0);budget-=1
            if budget<0:raise RuntimeError('Log query budget exhausted; indexed API: '+str(index_error)[:140]+'; configure archive/log RPC')
            q={'fromBlock':hex(a),'toBlock':hex(b),'topics':topics}
            if contract:q['address']=contract
            try:
                logs=_it_rpc(chain,'eth_getLogs',[q])
                if not isinstance(logs,list) or len(logs)>=1000:raise ValueError('Possible truncated log result')
                result.extend(logs)
            except Exception as e:
                if b-a<1000:raise RuntimeError('Log coverage failed: '+str(e)[:140])
                m=(a+b)//2;pending[:0]=[(a,m),(m+1,b)]
    unique={(l['transactionHash'],l['logIndex']):l for l in result if not l.get('removed',False)}
    out=sorted(unique.values(),key=lambda l:(int(l['blockNumber'],16),int(l['logIndex'],16)))
    _IT_LOG_CACHE[key]=out;return out

_IT_AAVE_B='Borrow(uint256,address,address,uint256,uint256)'
_IT_AAVE_R='Repay(uint256,address,address,uint256,uint256,(int256,int256,uint256))'
_IT_AAVE_L='LiquidationCall(uint256,uint256,address,address,bool,uint256,uint256,(int256,int256,uint256),uint256,uint256,uint256)'
_IT_MORPHO_B='Borrow(bytes32,address,address,address,uint256,uint256)'
_IT_MORPHO_R='Repay(bytes32,address,address,uint256,uint256)'
_IT_MORPHO_L='Liquidate(bytes32,address,address,uint256,uint256,uint256,uint256,uint256)'
_IT_EULER_B='Borrow(address,uint256)';_IT_EULER_R='Repay(address,uint256)'
_IT_EULER_P='PullDebt(address,address,uint256)';_IT_EULER_L='Liquidate(address,address,address,uint256,uint256)'
_IT_VENUS_B='Borrow(address,uint256,uint256,uint256)';_IT_VENUS_R='RepayBorrow(address,address,uint256,uint256,uint256)'
_IT_VENUS_L='LiquidateBorrow(address,address,uint256,address,uint256)'
_IT_OWNER='0x'+_it_word(EVM_ADDR)
_IT_HUBS={a for a,n in LENDING_ENDPOINTS['ethereum'].items() if 'Aave V4' in n}

def _it_morpho_debt(chain,contract,market,block):
    pos=_it_call(chain,contract,'position(bytes32,address)',[market,EVM_ADDR],block)
    shares=int(pos[1],16)
    if not shares:return 0
    mp=_it_call(chain,contract,'idToMarketParams(bytes32)',[market],block)
    state=_it_call(chain,contract,'market(bytes32)',[market],block)
    if len(mp)!=5 or len(state)!=6:raise ValueError('Unexpected Morpho ABI')
    assets,marketshares,last=map(lambda x:int(x,16),state[2:5]);elapsed=_it_block(chain,block)-last
    if elapsed<0:raise ValueError('Invalid market timestamp')
    if elapsed and assets and int(mp[3],16):
        rate=int(_it_call(chain,addr(mp[3]),'borrowRateView((address,address,address,address,uint256),(uint128,uint128,uint128,uint128,uint128,uint128))',mp+state,block)[0],16)
        # Morpho MathLib.wTaylorCompounded, integer arithmetic (WAD).
        first=rate*elapsed; second=first*first//(2*10**18); third=second*first//(3*10**18)
        assets+=assets*(first+second+third)//10**18
    # SharesMathLib uses VIRTUAL_SHARES=1e6 and VIRTUAL_ASSETS=1, round up.
    return (shares*(assets+1)+marketshares+10**6-1)//(marketshares+10**6)

def _it_interest_raw(open_debt,close_debt,borrowed,repaid):
    return close_debt-open_debt-borrowed+repaid

def _it_position(chain,proto,contract,key,events,first,last):
    # Never silently equate an unsupported token, liquidation or debt transfer to interest.
    if proto=='Aave V4':
        reserve=_it_call(chain,contract,'getReserve(uint256)',[key],last)
        if addr(reserve[1]) not in _IT_HUBS:raise ValueError('Spoke hub not in verified Aave hub list')
        token=addr(reserve[0]);dec=int(reserve[3],16)
        debt=lambda b:int(_it_call(chain,contract,'getUserTotalDebt(uint256,address)',[key,EVM_ADDR],b)[0],16)
    elif proto=='Morpho Blue':
        token=addr(_it_call(chain,contract,'idToMarketParams(bytes32)',[key],last)[0]);dec=int(_it_call(chain,token,'decimals()',[],last)[0],16)
        debt=lambda b:_it_morpho_debt(chain,contract,key,b)
    elif proto=='Euler':
        token=addr(_it_call(chain,contract,'asset()',[],last)[0]);dec=int(_it_call(chain,token,'decimals()',[],last)[0],16)
        debt=lambda b:int(_it_call(chain,contract,'debtOf(address)',[EVM_ADDR],b)[0],16)
    elif proto=='Venus':
        token=addr(_it_call(chain,contract,'underlying()',[],last)[0]);dec=int(_it_call(chain,token,'decimals()',[],last)[0],16)
        debt=lambda b:int(_it_call(chain,contract,'borrowBalanceCurrent(address)',[EVM_ADDR],b)[0],16)
    else:raise ValueError('Unsupported adapter')
    asset=(ETH_REGISTRY if chain=='ethereum' else BSC_REGISTRY).get(token)
    if not asset or not 0<=dec<=30:raise ValueError('Unverified loan token or decimals')
    if any(e[1]=='unsupported' for e in events):raise ValueError('Liquidation or debt transfer in window; manual reconciliation required')
    groups={}
    for block,kind,amount,ref in events:
        g=groups.setdefault(block,[0,0,[]]);g[0 if kind=='borrow' else 1]+=amount;g[2].append(ref)
    # Read actual debt immediately after each event block and at closing.
    # A deployed-but-inactive account returns zero. Never replace RPC errors with zero.
    def read(b):
        code=_it_rpc(chain,'eth_getCode',[contract,hex(b)])
        if code=='0x':return 0
        return debt(b)
    prev=first;d0=read(first);rows=[]
    for b in sorted(set(groups)|{last}):
        if b<=first:continue
        d1=read(b);borrow,repay,refs=groups.get(b,[0,0,[]]);raw=_it_interest_raw(d0,d1,borrow,repay)
        # Allow only tiny rounding noise (base units), never hide a principal gap.
        if raw < -max(3,len(refs)*3):raise ValueError('Negative inferred interest: incomplete principal/debt evidence')
        raw=max(raw,0)
        date=pd.to_datetime(_it_block(chain,b),unit='s',utc=True)
        px,src=historical_detail(asset,date.timestamp(),chain)
        if px is None or not math.isfinite(px) or px<=0:raise ValueError('Missing historical loan-asset quote')
        rows.append({'Date':date,'Chain':chain,'Protocol':proto,'Position':contract+':'+str(key),'Asset':asset,
                     'Opening block':prev,'Closing block':b,'Debt start':d0/10**dec,'Debt end':d1/10**dec,
                     'Borrowed':borrow/10**dec,'Repaid':repay/10**dec,'Interest units':raw/10**dec,
                     'Interest USD':raw/10**dec*px,'Price source':src,'Refs':'; '.join(refs),
                     'Source':'Historical contract debt + owner-indexed on-chain debt events'})
        prev,d0=b,d1
    return rows

_IT_COLS=['Date','Chain','Protocol','Position','Asset','Opening block','Closing block','Debt start','Debt end','Borrowed','Repaid','Interest units','Interest USD','Price source','Refs','Source']

# ── Additional lending adapters: Venus Core, Fluid / Flux, JustLend V2 ──────
# Sources: official Venus deployed markets; Fluid BNB VaultResolver/VaultFactory
# deployment ABI and T1 events; JustLend SBM V2 / TronGrid event and solidity APIs.
# All calls are read-only. Never broadcast. A failed position is UNKNOWN.
_VENUS_CORE='0xfd36e2c2a6789db23113685031d7f16329158384'
_VENUS_DEFAULT={'0xfd5840cd36d94d7229439859c0112a4185bc0255',
                '0xeca88125a5adbe82614ffc12d0db554e2e2867c8'}
_FLUID_RESOLVER='0xa5c3e16523eeeddcc34706b0e6be88b4c6ea95cc'
_FLUID_FACTORY='0x324c5dc1fc42c7a4d43d92df1eba58a54d13bf2d'
_TRON_MOOLAH='TDH4dhmVQQNc1ZNudJwWzBcs2h6ahhWrpp'
_ZERO='0x'+'0'*40

def _it_uints(w): return [int(x,16) for x in w]
def _it_signed(w):
    v=int(w,16);return v-2**256 if v>=2**255 else v

def _it_array(w):
    a=_it_uints(w)
    if len(a)<2 or a[0]!=32 or a[1]!=len(a)-2:raise ValueError('Unexpected dynamic array ABI')
    return a[2:]

def _it_venus_candidates(first,last,warn):
    candidates=set(_VENUS_DEFAULT)|{a.lower() for a in globals().get('ALEF_VENUS_DEBT_VTOKENS',[])}
    for b in (first,last):
        try:
            w=_it_call('bsc',_VENUS_CORE,'getAssetsIn(address)',[EVM_ADDR],b)
            candidates.update(f'0x{v:040x}' for v in _it_array(w))
        except Exception as e:warn('Venus Core','getAssetsIn',e)
    # vToken list is distinct from the Fluid NFT vaults used by Venus Flux.
    return candidates

def _it_fluid_positions(first,last,warn):
    chain='bsc'; owner=EVM_ADDR.lower(); r=_FLUID_RESOLVER; factory=_FLUID_FACTORY
    def nfts(b):
        if _it_rpc(chain,'eth_getCode',[r,hex(b)])=='0x':return set()
        return set(_it_array(_it_call(chain,r,'positionsNftIdOfUser(address)',[owner],b)))
    before,after=nfts(first),nfts(last)
    changes={}
    transfer=_it_hash('Transfer(address,address,uint256)')
    for topics in ([transfer,_IT_OWNER],[transfer,None,_IT_OWNER]):
        for l in _it_logs(chain,factory,topics,first+1,last):
            if len(l['topics'])!=4:raise ValueError('Unexpected NFT Transfer ABI')
            nft=int(l['topics'][3],16)
            changes.setdefault(nft,{})[(l['transactionHash'],l['logIndex'])]=l
    rows=[]; statuses=[]
    ids=before|after|set(changes)|set(map(int,globals().get('ALEF_FLUID_NFT_IDS',[])))
    for nft in sorted(ids):
        try:
            moves=list(changes.get(nft,{}).values())
            mints=[];burns=[]
            for l in moves:
                frm,to=addr(l['topics'][1]),addr(l['topics'][2]); b=int(l['blockNumber'],16)
                if frm==_ZERO and to==owner:mints.append(b)
                elif frm==owner and to==_ZERO:burns.append(b)
                elif frm!=to:raise ValueError('NFT ownership changed; manual debt attribution required')
            if len(mints)>1 or len(burns)>1:raise ValueError('Unexpected multiple NFT mint/burn')
            if nft not in before and not mints:raise ValueError('NFT opening ownership unverified')
            if nft not in after and not burns:raise ValueError('NFT closing ownership unverified')
            live_first=first if nft in before else mints[0]
            live_last=last if nft in after else burns[0]-1
            if live_last<live_first:raise ValueError('NFT created and closed in same block; manual reconciliation')
            sample=_it_call(chain,r,'positionByNftId(uint256)',[nft],live_last)
            # Deployed BNB v1.0.0 resolver returns two static tuples. UserPosition
            # has 12 words, then VaultEntireData starts at word 12. Borrow is
            # already net of dust, per resolver source. Never subtract it twice.
            if len(sample)<30 or int(sample[0],16)!=nft or addr(sample[1])!=owner:raise ValueError('Resolver NFT ABI/owner mismatch')
            vault=addr(sample[12]);smart=int(sample[14],16);token=addr(sample[25])
            if smart!=0 or addr(sample[26])!=_ZERO:raise ValueError('Smart debt uses DEX shares, not token units')
            asset=BSC_REGISTRY.get(token)
            if not asset:raise ValueError('Unregistered Fluid loan token '+token)
            dec=int(_it_call(chain,token,'decimals()',[],live_last)[0],16)
            if not 0<=dec<=30:raise ValueError('Invalid debt token decimals')
            def debt(b):
                if b<live_first or (burns and b>=burns[0]):return 0
                w=_it_call(chain,r,'positionByNftId(uint256)',[nft],b)
                if len(w)<30 or int(w[0],16)!=nft or addr(w[1])!=owner or addr(w[12])!=vault or int(w[14],16)!=0 or addr(w[25])!=token or addr(w[26])!=_ZERO:raise ValueError('Historical resolver ABI/identity changed')
                if int(w[2],16)!=0:raise ValueError('NFT liquidation observed; manual reconciliation required')
                return int(w[10],16)
            groups={}
            for l in _it_logs(chain,vault,[_it_hash('LogOperate(address,uint256,int256,int256,address)')],first+1,last):
                d=words(l['data'])
                if len(d)!=5 or len(l['topics'])!=1:raise ValueError('Unexpected Fluid operate ABI')
                if int(d[1],16)!=nft:continue
                b=int(l['blockNumber'],16); delta=_it_signed(d[3])
                g=groups.setdefault(b,[0,0,[]]);g[0]+=max(delta,0);g[1]+=max(-delta,0);g[2].append(l['transactionHash'])
            # Any liquidation block is inspected against our NFT, not counted as interest.
            for l in _it_logs(chain,vault,[_it_hash('LogLiquidate(address,uint256,uint256,address)')],first+1,last):
                b=int(l['blockNumber'],16)
                if live_first<=b<=live_last:groups.setdefault(b,[0,0,[]])
            # One point per day makes continuous interest visible rather than
            # placing the entire opening-to-present cost at the last block.
            checkpoints={first,last}|set(groups)|set(mints)|set(burns)
            for t in pd.date_range(pd.to_datetime(_it_block(chain,first),unit='s',utc=True).ceil('D'),pd.to_datetime(_it_block(chain,last),unit='s',utc=True),freq='D'):
                checkpoints.add(_it_block_at(chain,t.timestamp(),last))
            d0=debt(first);prev=first;out=[]
            for b in sorted(checkpoints-{first}):
                d1=debt(b);borrow,repay,refs=groups.get(b,[0,0,[]]);raw=d1-d0-borrow+repay
                # Tick-based positions have rounding. Small negatives are explicitly
                # retained as signed financing adjustments, not clamped to zero.
                if raw < -max(3,int(max(d0,d1,borrow,repay)*0.00001)):
                    raise ValueError('Negative financing change beyond rounding tolerance; missing debt event or liquidation')
                date=pd.to_datetime(_it_block(chain,b),unit='s',utc=True)
                px,src=historical_detail(asset,date.timestamp(),chain)
                if px is None or not math.isfinite(px) or px<=0:raise ValueError('Loan price unavailable')
                out.append(dict(zip(_IT_COLS,[date,chain,'Fluid / Venus Flux',f'{vault}:NFT {nft}',asset,prev,b,d0/10**dec,d1/10**dec,borrow/10**dec,repay/10**dec,raw/10**dec,raw/10**dec*px,src,'; '.join(refs),'Historical Fluid NFT net debt + LogOperate; includes any debt-side financing charge not in operate delta'])));
                d0,prev=d1,b
            rows.extend(out);statuses.append({'Protocol':'Fluid / Venus Flux','Position':str(nft),'Status':'Reconstructed','Detail':f'{len(out)} intervals; ordinary single-token debt'})
        except Exception as e:warn('Fluid / Venus Flux',nft,e)
    if not ids:statuses.append({'Protocol':'Fluid / Venus Flux','Position':'NFT discovery','Status':'No positions found','Detail':'Checked opening and closing resolver and factory transfers'})
    return rows,statuses

# TRON does NOT support historical eth_call. Use confirmed current state and
# reverse the actual market debt events, rather than asking for a historical
# block and accidentally getting today's state. TronGrid indexed event API
# paginates by fingerprint. Only POSTED AccrueInterest events are included;
# the unposted tail and pre-opening component of the first posting are disclosed.
_TRON_GRID=os.getenv('ALEF_TRONGRID_URL','https://api.trongrid.io').rstrip('/')
_TRON_GRID_KEY=os.getenv('TRONGRID_API_KEY','')
_TRON_HEADERS={'TRON-PRO-API-KEY':_TRON_GRID_KEY} if _TRON_GRID_KEY else {}
_B58='123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def _it_tron_hex(a):
    a=str(a)
    if a.startswith('T'):
        n=0
        for c in a:n=n*58+_B58.index(c)
        z=n.to_bytes(25,'big'); payload=z[:-4]
        if hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]!=z[-4:] or payload[0]!=65:raise ValueError('Invalid TRON address checksum')
        return '0x'+payload[1:].hex()
    s=a.removeprefix('0x').lower()
    if len(s)==64 and s[:24]=='0'*24:s=s[24:]
    if len(s)==42 and s.startswith('41'):s=s[2:]
    if len(s)!=40:raise ValueError('Invalid TRON address')
    int(s,16);return '0x'+s

def _it_tron_post(path,data):
    resp=requests.post(_TRON_GRID+path,json=data,headers=_TRON_HEADERS,timeout=25);resp.raise_for_status();return resp.json()
def _it_tron_head():
    d=_it_tron_post('/walletsolidity/getnowblock',{})['block_header']['raw_data'];return int(d['number']),int(d['timestamp'])
def _it_tron_call(contract,sig,args):
    d=_it_tron_post('/walletsolidity/triggerconstantcontract',{'owner_address':'41'+_it_tron_hex(TRON_ADDR)[2:],'contract_address':'41'+_it_tron_hex(contract)[2:], 'function_selector':sig,'parameter':''.join(_it_word(a) for a in args),'visible':False})
    if d.get('result',{}).get('result') is not True or not d.get('constant_result'):raise ValueError('TRON constant call failed: '+sig)
    w=words(d['constant_result'][0]);
    if not w:raise ValueError('Empty TRON contract result')
    return w

def _it_tron_events(name,lo,hi):
    if hi<lo:return []
    p={'event_name':name,'only_confirmed':'true','min_block_timestamp':lo,'max_block_timestamp':hi,'limit':200,'order_by':'block_timestamp,asc'}
    seen=set();out={};budget=int(globals().get('ALEF_TRON_EVENT_PAGE_LIMIT',500))
    for _ in range(budget):
        r=requests.get(_TRON_GRID+'/v1/contracts/'+_TRON_MOOLAH+'/events',params=p,headers=_TRON_HEADERS,timeout=30);r.raise_for_status();d=r.json()
        if d.get('success') is not True or not isinstance(d.get('data'),list):raise ValueError('TronGrid event request failed: '+name)
        for e in d['data']:
            if e.get('event_name')!=name or not lo<=int(e['block_timestamp'])<=hi:raise ValueError('Unexpected event or timestamp')
            key=(e['transaction_id'],int(e['event_index']));out[key]=e
        fp=d.get('meta',{}).get('fingerprint')
        if not fp:
            if len(d['data'])>=200:raise ValueError('Full TronGrid page without continuation; coverage uncertain')
            return list(out.values())
        if fp in seen:raise ValueError('TronGrid pagination repeated')
        seen.add(fp);p['fingerprint']=fp
        time.sleep(0.2)
    raise ValueError('TRON event page budget exhausted: '+name)

def _it_tron_marketid(v):
    s=str(v).removeprefix('0x').lower()
    if len(s)!=64:raise ValueError('Invalid Moolah market ID')
    int(s,16);return '0x'+s

def _it_tron_parse(e):
    r=e['result'];k=e['event_name']
    def field(name,i):
        if name in r:return r[name]
        return r[str(i)]
    def num(name,i):
        v=field(name,i);return int(v,16) if str(v).startswith('0x') else int(v)
    market=_it_tron_marketid(field('id',0));owner=None;assets=shares=0;interest=0;bad_assets=bad_shares=0
    if k=='AccrueInterest':interest=num('interest',2)
    elif k=='Borrow':owner=_it_tron_hex(field('onBehalf',2));assets=num('assets',4);shares=num('shares',5)
    elif k=='Repay':owner=_it_tron_hex(field('onBehalf',2));assets=num('assets',3);shares=num('shares',4)
    elif k=='Liquidate':
        owner=_it_tron_hex(field('borrower',2));assets=num('repaidAssets',3);shares=num('repaidShares',4);bad_assets=num('badDebtAssets',6);bad_shares=num('badDebtShares',7)
    else:raise ValueError('Unknown Moolah event')
    if min(assets,shares,interest,bad_assets,bad_shares)<0:raise ValueError('Negative unsigned Moolah event')
    return dict(market=market,kind=k,owner=owner,assets=assets,shares=shares,interest=interest,bad_assets=bad_assets,bad_shares=bad_shares,block=int(e['block_number']),ms=int(e['block_timestamp']),ref=e['transaction_id'],index=int(e['event_index']))

def _it_tron_sorted(events):
    # event_index is receipt-local; resolve transaction ordering for blocks
    # containing multiple distinct relevant transactions.
    by={}
    for e in events:by.setdefault(e['block'],set()).add(e['ref'])
    order={}
    for b,refs in by.items():
        if len(refs)>1:
            raw=_it_tron_post('/walletsolidity/getblockbynum',{'num':b})
            txs={t['txID']:i for i,t in enumerate(raw.get('transactions',[]))}
            if not refs.issubset(txs):raise ValueError('Cannot establish confirmed TRON transaction ordering')
            order[b]=txs
    return sorted(events,key=lambda e:(e['block'],order.get(e['block'],{}).get(e['ref'],0),e['index']))

def _it_tron_replay(events,assets,shares,user_shares,owner):
    # Reverse posted interest and principal events from the same solidified
    # state. Allocate posted market interest by the user's borrow-share fraction.
    # Moolah is Morpho-style; proportional allocation is an estimate (virtual
    # shares and base-unit rounding can differ), not an exact debt claim.
    result=[]
    for e in reversed(events):
        k=e['kind'];a=e['assets'];s=e['shares'];mine=e['owner']==owner
        if k=='AccrueInterest':
            i=e['interest']
            if i>assets or (i and not shares):raise ValueError('Inconsistent market interest replay')
            if user_shares and i:
                result.append((e,assets-i,assets,shares,user_shares,Decimal(i)*Decimal(user_shares)/Decimal(shares)))
            assets-=i
        elif k=='Borrow':
            assets-=a;shares-=s
            if mine:user_shares-=s
        else:
            if k=='Liquidate' and mine:raise ValueError('ALEF liquidation requires separate reconciliation')
            assets+=a+e['bad_assets'];shares+=s+e['bad_shares']
            if mine:user_shares+=s+e['bad_shares']
        if not 0<=user_shares<=shares or assets<0:raise ValueError('Negative/inconsistent TRON share replay; missing or misordered events')
    return result,(assets,shares,user_shares)

def _it_justlend_positions(opening,now,warn):
    start=int(opening.timestamp()*1000)+1; end=int(now.timestamp()*1000)
    owner=_it_tron_hex(TRON_ADDR); kinds=('Borrow','Repay','Liquidate','AccrueInterest')
    # Capture events before snapshotting; then fetch the small tail to the actual
    # confirmed snapshot. This also handles notebooks that took minutes to fetch.
    h0,t0=_it_tron_head()
    if t0<start:raise ValueError('Solidified TRON head precedes opening')
    events=[_it_tron_parse(e) for k in kinds for e in _it_tron_events(k,start,t0)]
    ids={e['market'] for e in events}|{_it_tron_marketid(x) for x in globals().get('ALEF_JUSTLEND_MARKET_IDS',[])}
    snapshots={};statuses=[];rows=[]
    for market in sorted(ids):
        try:
            # Skip inactive non-owner markets after a direct position read.
            probe=_it_tron_call(_TRON_MOOLAH,'position(bytes32,address)',[market,owner])
            if len(probe)!=3:raise ValueError('Unexpected Moolah position ABI')
            if not int(probe[1],16) and not any(e['market']==market and e['owner']==owner for e in events):continue
            # Read owner shares and market totals in the SAME confirmed block.
            for attempt in range(8):
                b0,ms0=_it_tron_head()
                p=_it_tron_call(_TRON_MOOLAH,'position(bytes32,address)',[market,owner]);m=_it_tron_call(_TRON_MOOLAH,'market(bytes32)',[market])
                b1,ms1=_it_tron_head()
                if b0==b1:break
            else:raise ValueError('Could not pin TRON snapshot to one solidified block')
            if len(p)!=3 or len(m)!=6:raise ValueError('Unexpected Moolah position/market ABI')
            a,s,u=int(m[2],16),int(m[3],16),int(p[1],16)
            # Check all active markets, including loans with no user events.
            if not u and not any(e['market']==market and e['owner']==owner for e in events):continue
            mp=_it_tron_call(_TRON_MOOLAH,'idToMarketParams(bytes32)',[market]);
            if len(mp)!=5:raise ValueError('Unexpected Moolah market params ABI')
            token=addr(mp[0]);asset={_it_tron_hex(TRON_USDT):'USDT'}.get(token)
            if not asset:raise ValueError('Unknown JustLend debt token '+token+'; extend verified registry')
            dec=int(_it_tron_call(token,'decimals()',[])[0],16)
            if not 0<=dec<=30:raise ValueError('Invalid loan token decimals')
            snapshots[market]=(b0,ms0,a,s,u,asset,dec,int(m[4],16))
        except Exception as e:warn('JustLend V2',market,e)
    if not snapshots:
        warn('JustLend V2','discovery','No borrower snapshot reconstructed; check market discovery/API coverage');return rows,statuses
    maxt=max(x[1] for x in snapshots.values())
    if maxt>t0:events.extend(_it_tron_parse(e) for k in kinds for e in _it_tron_events(k,t0+1,maxt))
    for market,(b0,ms0,a,s,u,asset,dec,last_update) in snapshots.items():
        try:
            ev=_it_tron_sorted([e for e in events if e['market']==market and e['block']<=b0])
            # A recorded lastUpdate inside the interval must have a matching
            # market accrual event. Zero-rate updates can emit none; flag rather
            # than assume completeness if that evidence is missing.
            if last_update*1000>start and not any(e['kind']=='AccrueInterest' and e['ms']//1000==last_update for e in ev):raise ValueError('Market lastUpdate does not match indexed accrual event; possible index lag or zero-rate update')
            posted,opening_state=_it_tron_replay(ev,a,s,u,owner)
            out=[]
            # Include confirmed repayment events as separate rows, in addition to interest postings.
            for e,aa,ab,ss,us,interest in reversed(posted):
                if not start<=e['ms']<=end:continue
                date=pd.to_datetime(e['ms'],unit='ms',utc=True);px,src=historical_detail(asset,date.timestamp(),'tron')
                if px is None or not math.isfinite(px) or px<=0:raise ValueError('Historical loan quote unavailable')
                out.append(dict(zip(_IT_COLS,[date,'tron','JustLend V2',market,asset,e['block'],e['block'],aa*us/ss/10**dec,ab*us/ss/10**dec,0,0,float(interest/10**dec),float(interest/10**dec)*px,src,e['ref'],'Confirmed AccrueInterest × borrower share fraction; posted not exact accrued interest'])))
            for e in ev:
                if e['kind']!='Repay' or e['owner']!=owner or not start<=e['ms']<=end:continue
                date=pd.to_datetime(e['ms'],unit='ms',utc=True);px,src=historical_detail(asset,date.timestamp(),'tron')
                if px is None or not math.isfinite(px) or px<=0:raise ValueError('Historical repayment quote unavailable')
                out.append(dict(zip(_IT_COLS,[date,'tron','JustLend V2',market,asset,e['block'],e['block'],float('nan'),float('nan'),0,e['assets']/10**dec,0,0,src,e['ref'],'Confirmed borrower Repay; interest allocation estimated'])))
            rows.extend(out);statuses.append({'Protocol':'JustLend V2','Position':market,'Status':'Posted interest reconstructed (estimate)','Detail':f'{len(out)} postings; excludes unposted tail, first posting may include pre-opening accrual; snapshot block {b0}'})
        except Exception as e:warn('JustLend V2',market,e)
    return rows,statuses


def build_onchain_interest(opening,now):
    print('\n▶ Reconstructing lending interest from historical on-chain debt...')
    rows=[]; coverage=[]
    def warn(proto,pos,e):
        coverage.append({'Protocol':proto,'Position':str(pos),'Status':'INCOMPLETE — excluded','Detail':str(e)[:250]})
    def process(chain,proto,contract,key,events,first,last):
        try:
            out=_it_position(chain,proto,contract,key,events,first,last);rows.extend(out)
            coverage.append({'Protocol':proto,'Position':contract+':'+str(key),'Status':'Reconstructed','Detail':f'{len(out)} intervals; accrued, not necessarily paid'})
        except Exception as e:warn(proto,contract+':'+str(key),e)
    for chain in ('ethereum','bsc'):
        try:
            head=int(_it_rpc(chain,'eth_blockNumber',[]),16)
            first=_it_block_at(chain,opening.timestamp(),head);last=_it_block_at(chain,now.timestamp(),head)
            if last<=first:raise ValueError('Invalid block interval')
        except Exception as e:warn(chain,'all',e);continue
        if chain=='ethereum':
            for proto,contract,sigs,owner_slot in [('Aave V4',None,[_IT_AAVE_B,_IT_AAVE_R,_IT_AAVE_L],3),('Morpho Blue',MORPHO_CORE,[_IT_MORPHO_B,_IT_MORPHO_R,_IT_MORPHO_L],None)]:
                try:
                    groups={}
                    for sig in sigs:
                        slot=owner_slot if owner_slot else (2 if sig==_IT_MORPHO_B else 3)
                        topics=[_it_hash(sig)]+[None]*(slot-1)+[_IT_OWNER]
                        logs=_it_logs(chain,contract,topics,first+1,last)
                        for l in logs:
                            c=l['address'].lower(); t=l['topics'];d=words(l['data']);k=t[1] if proto=='Morpho Blue' else int(t[2 if sig==_IT_AAVE_L else 1],16)
                            action='unsupported' if sig in (_IT_AAVE_L,_IT_MORPHO_L) else ('borrow' if sig in (_IT_AAVE_B,_IT_MORPHO_B) else 'repay')
                            amount=0 if action=='unsupported' else int(d[1 if proto=='Aave V4' or sig==_IT_MORPHO_B else 0],16)
                            groups.setdefault((c,k),[]).append((int(l['blockNumber'],16),action,amount,l['transactionHash']))
                    # Optional verified opening-only positions, even if no debt activity in window.
                    for p in globals().get('ALEF_INTEREST_EXTRA_POSITIONS',[]):
                        if p['chain']==chain and p['protocol']==proto:groups.setdefault((p['contract'].lower(),p['key']),[])
                    if not groups:warn(proto,'discovery','No borrower events; opening-only positions require explicit IDs')
                    for (c,k),events in groups.items():process(chain,proto,c,k,events,first,last)
                except Exception as e:warn(proto,'discovery',e)
        else:
            euler_vaults={'0x8f68128438c1101550bf478bbe8f8c80749eb794','0xf4940cde23c164f8ca8d536f3567337349b3208f'}
            venus_vaults=_it_venus_candidates(first,last,warn)
            try:
                fl_rows,fl_status=_it_fluid_positions(first,last,warn);rows.extend(fl_rows);coverage.extend(fl_status)
            except Exception as e:warn('Fluid / Venus Flux','NFT discovery',e)
            for proto,contracts,defs in [('Euler',euler_vaults, [(_IT_EULER_B,1,'borrow',0),(_IT_EULER_R,1,'repay',0),(_IT_EULER_P,1,'unsupported',0),(_IT_EULER_P,2,'unsupported',0),(_IT_EULER_L,2,'unsupported',0)]),('Venus',venus_vaults,[(_IT_VENUS_B,0,'borrow',1),(_IT_VENUS_R,0,'repay',2),(_IT_VENUS_L,0,'unsupported',0)])]:
                if not contracts:warn(proto,'discovery','No verified debt contracts found')
                for c in contracts:
                    try:
                        events=[]
                        if proto=='Venus':
                            endpoint_debt=[]
                            for b in (first,last):
                                if _it_rpc(chain,'eth_getCode',[c,hex(b)])=='0x':endpoint_debt.append(0)
                                else:endpoint_debt.append(int(_it_call(chain,c,'borrowBalanceCurrent(address)',[EVM_ADDR],b)[0],16))
                            if not any(endpoint_debt) and c not in _VENUS_DEFAULT and c not in {a.lower() for a in globals().get('ALEF_VENUS_DEBT_VTOKENS',[])}:
                                # The contract may still have opened and closed a loan during the period.
                                warn('Venus',c,'Zero boundary debt; non-default market not scanned for closed mid-period loans');continue
                        for sig,slot,kind,idx in defs:
                            # Legacy Venus events have unindexed borrower; fetch contract events and filter ABI data.
                            topics=[_it_hash(sig)]+([None]*(slot-1)+[_IT_OWNER] if slot else [])
                            for l in _it_logs(chain,c,topics,first+1,last):
                                d=words(l['data'])
                                if slot==0 and addr(d[0 if kind=='borrow' else 1])!=EVM_ADDR.lower():continue
                                events.append((int(l['blockNumber'],16),kind,0 if kind=='unsupported' else int(d[idx],16),l['transactionHash']))
                        process(chain,proto,c,'',events,first,last)
                    except Exception as e:warn(proto,c,e)
    # Explicitly incomplete protocol coverage: do not invent these interest amounts.
    try:
        tr_rows,tr_status=_it_justlend_positions(opening,now,warn);rows.extend(tr_rows);coverage.extend(tr_status)
    except Exception as e:warn('JustLend V2','TronGrid reconstruction',e)
    for p in ('Aave V3 / other positions',):
        warn(p,'not reconstructed','Requires verified market/position IDs and historical debt/event adapter; no APR fallback')
    warn('Discovery','opening-only positions','Aave/Morpho event discovery can omit inactive positions; provide verified ALEF_INTEREST_EXTRA_POSITIONS. TRON posted interest only; configure ALEF_JUSTLEND_MARKET_IDS for inactive markets. Venus Core covers USDT/USDC and discovered entered markets, not every isolated pool. No claim of complete lending coverage.')
    return pd.DataFrame(rows,columns=_IT_COLS),pd.DataFrame(coverage)

interest_schedule,interest_coverage=build_onchain_interest(opening,now_point)
# Optional externally verified interest expenses ALREADY present in the flow
# ledger: ALEF_INTEREST_EXTERNAL_REFS = {(chain, txhash): positive USD}.
# Only verified outflow legs may offset the residual; no inference from debt growth.
external_interest_rows=[]
for (chain,ref),amount in globals().get('ALEF_INTEREST_EXTERNAL_REFS',{}).items():
    g=reverse[(reverse.Chain==chain)&(reverse.Ref==ref)&(reverse.Date>opening)&(reverse.Date<=now_point)]
    amount=float(amount)
    if g.empty or not math.isfinite(amount) or amount<=0 or g.Date.nunique()!=1 or amount>max(0,-g['Net USD'].sum())+0.01:
        AUDIT_WARNINGS.append('Invalid external interest reference (not credited): '+str(ref));continue
    external_interest_rows.append({'Date':g.Date.iloc[0],'Interest USD':amount,'Ref':ref})
external_interest=pd.DataFrame(external_interest_rows,columns=['Date','Interest USD','Ref'])
interest_at=make_opening_cumulative(interest_schedule.groupby('Date')['Interest USD'].sum(),opening,now_point)
external_interest_at=make_opening_cumulative(external_interest.groupby('Date')['Interest USD'].sum(),opening,now_point)
# Repayments do not normally split principal from interest on-chain. Allocate
# *in-window* accrued interest first, in loan units, then remaining payment to
# principal. This is a documented accounting convention, not an observed split.
# Opening debt may contain older interest, which this calculation excludes.
def allocate_period_interest(schedule, quote):
    out=schedule.copy()
    out['Interest paid units']=0.0;out['Interest paid USD']=0.0
    out['Unpaid period interest units']=0.0
    for _,g in out.groupby(['Chain','Protocol','Position','Asset'],sort=False):
        outstanding=0.0
        # Within a timestamp, accrual precedes repayment by convention. EVM
        # records are block-level; TRON postings and repayments are timestamped.
        g=g.assign(_repay_only=(g['Interest units']==0)&(g.Repaid>0)).sort_values(['Date','Closing block','_repay_only'],kind='stable')
        for i,r in g.iterrows():
            outstanding=max(0.0,outstanding+float(r['Interest units']))
            paid=min(outstanding,max(0.0,float(r.Repaid)))
            outstanding-=paid
            out.at[i,'Interest paid units']=paid
            if paid:
                px=quote(r.Asset,r.Date.timestamp(),r.Chain)[0]
                if px is None or not math.isfinite(px) or px<=0:raise ValueError('Missing repayment-time price')
                out.at[i,'Interest paid USD']=paid*px
            out.at[i,'Unpaid period interest units']=outstanding
    return out
interest_schedule=allocate_period_interest(interest_schedule,historical_detail)
paid_at=make_opening_cumulative(interest_schedule.groupby('Date')['Interest paid USD'].sum(),opening,now_point)
# The requested expense benchmark uses period interest allocated to repayments.
# It is a COST-ADJUSTED DIAGNOSTIC, not an assertion that ALEF owes the manager
# every dollar of loan interest. A manager-funded deposit already counted in
# raw deposits must not also be treated as an independently verified credit.
# Exclude overlaps with explicitly verified external payment refs.
paid_refs=set()
for _,r in interest_schedule.loc[interest_schedule['Interest paid USD']>0].iterrows():
    paid_refs.update((r.Chain,ref.strip().lower()) for ref in str(r.Refs).split(';') if ref.strip())
external_extra=external_interest.copy()
# External refs can be disjoint from the on-chain protocol repayment schedule.
# Where identical refs appear, use the allocated paid amount only once.
if not external_extra.empty:
    overlap={ref for _,ref in paid_refs}
    external_extra=external_extra.loc[~external_extra.Ref.str.lower().isin(overlap)]
external_extra_at=make_opening_cumulative(external_extra.groupby('Date')['Interest USD'].sum(),opening,now_point)
raw_deposits_at=make_opening_cumulative(by_time['Known net'],opening,now_point,sign=1.0)
deposits_at=raw_deposits_at
active_schedule=fee_schedule
contractual_fees_at=make_opening_cumulative(fee_schedule.groupby('Date')['Fee'].sum(),opening,now_point)
def fees_at(t):return contractual_fees_at(t)+paid_at(t)+external_extra_at(t)
verified_paid_at=make_opening_cumulative(verified_fees.groupby('Date')['Fee'].sum(),opening,now_point)
baseline_label='Negative fees + allocated interest paid (partial)'
net_deposits_now=deposits_at(now_point)
fees_since_opening=fees_at(now_point)
fee_credit_now=-fees_since_opening
present_gap=net_deposits_now-fee_credit_now
for frame in (reverse,visible,dust):
    frame['Net deposits since opening']=pd.Series([deposits_at(t) for t in frame.Date],index=frame.index,dtype=float)
    frame['Cumulative fee credits']=pd.Series([-contractual_fees_at(t) for t in frame.Date],index=frame.index,dtype=float)
    frame['Cumulative interest accrued (covered)']=pd.Series([interest_at(t) if len(interest_schedule) else float('nan') for t in frame.Date],index=frame.index,dtype=float)
    frame['Cumulative interest paid (allocated)']=pd.Series([paid_at(t) if len(interest_schedule) else float('nan') for t in frame.Date],index=frame.index,dtype=float)
    frame['Cumulative negative cost benchmark']=pd.Series([-fees_at(t) for t in frame.Date],index=frame.index,dtype=float)
    frame['Fee-adjusted deviation']=frame['Net deposits since opening']-frame['Cumulative negative cost benchmark']
# State now. Prefer the actual output from Price_update rather than inventing a NAV.
# If a preceding cell has not provided ALEF_CURRENT_STATE, query direct holdings now.
# Current wallet balances are only a partial view: debt, collateral, LPs and exchanges
# belong to the full Price_update portfolio. All values here are explicitly scoped.
print("\n=== STATE NOW (UTC) ===",NOW.isoformat())
if globals().get("ALEF_CURRENT_STATE") is not None:
    print("Supplied upstream snapshot displayed unchanged; verify its own xStocks multiplier handling.")
    display(ALEF_CURRENT_STATE)
else:
    current=[]; current_errors=[]
    def state_add(chain,wallet,asset,qty):
        if not qty:return
        p=prices.get(asset)
        if asset in stable_symbols:p=1.0
        factor,source=xstock_factor(asset,chain,NOW.timestamp(),current=True)
        if chain in _XSTOCK_NETWORKS and asset.upper() in _XSTOCK_RAW_SYMBOLS:
            p=prices.get(_XSTOCK_TICKERS.get(asset) or _XSTOCK_TICKERS.get(_XSTOCK_RAW_SYMBOLS[asset.upper()]))
        if p is not None and (not math.isfinite(float(p)) or p<=0):p=None
        scaled=qty*factor if factor is not None else None
        current.append(dict(Chain=chain,Wallet=wallet,Asset=asset,Quantity=qty,
                            Multiplier=factor,**{"Share-equivalent quantity":scaled,"Multiplier source":source},
                            USD=scaled*p if p is not None and scaled is not None else None))
    def attempt(name,fn):
        try:fn()
        except Exception as e:current_errors.append(name+": "+type(e).__name__)
    for chain,registry,native in (("ethereum",ETH_REGISTRY,"ETH"),("bsc",BSC_REGISTRY,"BNB")):
        attempt(chain+" native",lambda c=chain,n=native:state_add(c,EVM_ADDR,n,int(evm_rpc(c,"eth_getBalance",[EVM_ADDR,"latest"]),16)/1e18))
        for contract,asset in registry.items():
            def token_balance(c=chain,ct=contract,a=asset):
                q=int(evm_rpc(c,"eth_call",[{"to":ct,"data":"0x70a08231"+wallet_word},"latest"]),16)
                if q:
                    dec=int(evm_rpc(c,"eth_call",[{"to":ct,"data":"0x313ce567"},"latest"]),16)
                    state_add(c,EVM_ADDR,a,q/10**dec)
            attempt(chain+" "+asset,token_balance)
    def btc_state():
        d=_get("https://mempool.space/api/address/"+BITCOIN_ADDR)["chain_stats"]
        state_add("bitcoin",BITCOIN_ADDR,"BTC",(d["funded_txo_sum"]-d["spent_txo_sum"])/1e8)
    attempt("BTC balance",btc_state)
    for wallet in (SOL_WALLET,SOL_WALLET_2):
        attempt("SOL balance "+wallet,lambda w=wallet:state_add("solana",w,"SOL",_sol_rpc("getBalance",[w,{"commitment":"finalized"}])["value"]/1e9))
        for program in ("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA","TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"):
            def sol_state(w=wallet,pr=program):
                d=_sol_rpc("getTokenAccountsByOwner",[w,{"programId":pr},{"encoding":"jsonParsed","commitment":"finalized"}])
                for a in d["value"]:
                    inf=a["account"]["data"]["parsed"]["info"]; tok=inf["tokenAmount"]
                    sym={SOLANA_USDC:"USDC",PPLT_MINT:"PPLTX",ALEF_MINT:"ALEF treasury units",ALEF_MINT_OLD:"ALEF old treasury units"}.get(inf["mint"])
                    if sym:state_add("solana",w,sym,int(tok["amount"])/10**int(tok["decimals"]))
            attempt("SOL tokens "+wallet,sol_state)
    def tron_state():
        d=_get("https://api.trongrid.io/v1/accounts/"+TRON_ADDR)["data"][0]
        state_add("tron",TRON_ADDR,"TRX",int(d.get("balance",0))/1e6)
        for entry in d.get("trc20",[]):
            if TRON_USDT in entry:state_add("tron",TRON_ADDR,"USDT",int(entry[TRON_USDT])/1e6)
    attempt("Tron balances",tron_state)
    def ton_state():
        d=_get("https://tonapi.io/v2/accounts/"+TON_ADDR)
        state_add("ton",TON_ADDR,"TON",int(d["balance"])/1e9)
        j=_get("https://tonapi.io/v2/accounts/"+TON_ADDR+"/jettons")
        for b in j.get("balances",[]):
            token=b["jetton"]; sym=token.get("symbol")
            if sym in _XSTOCK_TICKERS or sym in _TON_STABLES:
                state_add("ton",TON_ADDR,sym,int(b["balance"])/10**int(token["decimals"]))
    attempt("TON balances",ton_state)
    current_wallet_state=pd.DataFrame(current,columns=["Chain","Wallet","Asset","Quantity","Multiplier","Share-equivalent quantity","Multiplier source","USD"])
    display(current_wallet_state)
    print("Direct wallet balances only; not full portfolio NAV. Solana/TON xStocks use raw quantity × multiplier × underlying share price; treasury ALEF excluded from valuation. See Price_update for collateral, debt, LP and exchange positions.")
    for e in current_errors:print("CURRENT STATE WARNING:",e)

# One table, newest first, retaining the original backward-flow diagnostic.
cols=["Date","Chain","Type","Description","Raw USD","Net USD","Balance vs Now","Net deposits since opening","Cumulative fee credits","Cumulative interest accrued (covered)","Cumulative interest paid (allocated)","Cumulative negative cost benchmark","Fee-adjusted deviation","Unpriced later legs","Price source","Class","Ref"]
anchor={c:"" for c in cols}; anchor.update({"Date":NOW,"Description":"CURRENT STATE — independently calculated gap","Raw USD":0.0,"Net USD":0.0,"Balance vs Now":0.0,"Net deposits since opening":net_deposits_now,"Cumulative fee credits":-contractual_fees_at(now_point),"Cumulative interest accrued (covered)":interest_at(now_point) if len(interest_schedule) else float('nan'),"Cumulative interest paid (allocated)":paid_at(now_point) if len(interest_schedule) else float('nan'),"Cumulative negative cost benchmark":fee_credit_now,"Fee-adjusted deviation":present_gap,"Unpriced later legs":0})
timeline=pd.concat([pd.DataFrame([anchor]),visible[cols]],ignore_index=True)
print("\n=== HISTORICAL TRANSACTIONS — NEWEST FIRST ===")
with pd.option_context("display.max_rows",None,"display.max_colwidth",None):
    display(timeline.style.format({"Raw USD":"{:,.2f}","Net USD":"{:+,.2f}","Balance vs Now":"{:+,.2f}","Net deposits since opening":"{:+,.2f}","Cumulative fee credits":"{:+,.2f}","Cumulative interest accrued (covered)":"{:,.2f}","Cumulative interest paid (allocated)":"{:,.2f}","Cumulative negative cost benchmark":"{:+,.2f}","Fee-adjusted deviation":"{:+,.2f}"},na_rep="UNKNOWN / UNPRICED"))
# Daily closing observations; independently evaluate both endpoints. No
# normalization, smoothing, or manual replacement of the present values.
import matplotlib.pyplot as plt
closes=[min(t+pd.Timedelta(days=1)-pd.Timedelta(microseconds=1),now_point)
        for t in pd.date_range(opening.floor("D"),now_point.floor("D"),freq="D")]
observed_dates=sorted(set([opening,now_point]+[t for t in closes if opening<t<=now_point]))
observed=pd.Series([deposits_at(t) for t in observed_dates],index=observed_dates,dtype=float)
fee_dates=sorted(set([opening,now_point]+[t for t in list(active_schedule.Date)+list(interest_schedule.Date)+list(external_interest.Date) if opening<t<=now_point]))
fig,ax=plt.subplots(figsize=(13,5.4))
ax.plot(observed.index,observed.values,label="Net deposits (observed, daily close)",linewidth=1.7)
ax.step(fee_dates,[-fees_at(t) for t in fee_dates],where="post",linestyle="--",label=baseline_label,linewidth=1.7,color="tab:orange")
# Only the two requested curves. Verified payment records remain in the report.
ax.scatter([opening],[deposits_at(opening)],color="black",zorder=5,label="Common opening anchor")
ax.scatter([now_point],[net_deposits_now],color="tab:blue",zorder=5)
ax.scatter([now_point],[fee_credit_now],color="tab:orange",zorder=5)
# Both series use the net-deposit convention; their signed difference is the residual.
ax.vlines(now_point,min(net_deposits_now,fee_credit_now),max(net_deposits_now,fee_credit_now),color=".35",linewidth=1.3,zorder=4)
ax.annotate(f"Cost-adjusted flow residual: ${present_gap:+,.2f}",xy=(now_point,(net_deposits_now+fee_credit_now)/2),xytext=(-12,10),textcoords="offset points",ha="right",va="bottom",fontsize=10,bbox=dict(boxstyle="round,pad=.25",fc="white",ec=".7",alpha=.9))
ax.axhline(0,color="grey",linewidth=.8,alpha=.4)
# Chronological axis: opening on left, present on right.
ax.set_title("ALEF — net deposits and negative fees + paid interest (partial coverage)")
ax.set_ylabel("Cumulative USD since opening"); ax.set_xlabel("UTC — opening on left, present on right"); ax.grid(alpha=.25); ax.legend(); plt.tight_layout(); plt.show()
print("\n=== PRESENT FEE-ADJUSTED GAP ===")
print(f"Opening anchor (after transaction): {opening.isoformat()}")
print(f"Net deposits since opening: {net_deposits_now:+,.2f} USD (priced legs only)")
print(f"Raw net deposits before internal interest: {raw_deposits_at(now_point):+,.2f} USD")
print(f"Contractual fee credits: {-contractual_fees_at(now_point):+,.2f} USD")
if len(interest_schedule):
    print(f"Reconstructed accrued interest (covered positions): {interest_at(now_point):,.2f} USD")
    print(f"Cumulative interest paid (interest-first allocation, covered positions): {paid_at(now_point):,.2f} USD")
else:
    print("Reconstructed accrued interest: UNKNOWN — no successful intervals")
    print("Cumulative interest paid: UNKNOWN — no successful intervals")
print(f"Residual excluding loan-interest adjustment: {net_deposits_now+contractual_fees_at(now_point):+,.2f} USD")
print(f"Verified external interest already present in raw flows: {external_interest_at(now_point):,.2f} USD")
print(f"Combined negative cost benchmark: {fee_credit_now:+,.2f} USD")
print("Blue line is unchanged. Orange includes allocated paid interest once; unpaid interest is reported separately. Interest paid is an allocation estimate; no claim of personal reimbursement unless payer/ledger attribution is verified.")
print(f"Residual with only explicitly verified external interest credits: {net_deposits_now+contractual_fees_at(now_point)+external_interest_at(now_point):+,.2f} USD (subject to all other ledger assumptions)")
print("=== ON-CHAIN LENDING INTEREST / FINANCING COSTS (partial; TRON posted estimate) ===")
if len(interest_schedule):
    display(interest_schedule.groupby(["Chain","Protocol","Asset"])[["Interest USD","Interest paid USD","Repaid"]].sum().reset_index())
    display(interest_schedule)
else: print("No successfully reconstructed interest intervals; UNKNOWN, not zero.")
display(interest_coverage)
print(f"Cost-adjusted flow residual (net deposits minus negative fee/paid-interest benchmark): {present_gap:+,.2f} USD")
print("Positive = above cost benchmark; negative = below. This is a conditional cost-adjusted flow diagnostic, NOT a manager payable. Verify who funded interest and whether it is already credited before claiming reimbursement.")
print(f"Daily-close cumulative deposit range: {observed.min():+,.2f} to {observed.max():+,.2f} USD")
print("\n=== CONTRACTUAL FEES (USD; calculated from events, not proof of payment) ===")
print("Management NAV source:",fee_nav_source)
print("Trading costs: 0.5% of outgoing matched portfolio conversion notional once per conversion. No ALEF Raydium swap fees, same-asset movements or USDC/USDT fees. Inferred matches are estimates, not verified exchange fills.")
for kind,group in fee_schedule.groupby("Kind"):
    print(f"{kind}: ${group.Fee.sum():,.2f} across {len(group)} events")
print(f"Management accrual since opening (included in line): ${fee_schedule.loc[fee_schedule.Kind=='Management accrual','Fee'].sum():,.2f}")
print(f"Of which unsettled since last in-window mint/burn (included, NOT additional): ${unsettled_management_fee:,.2f}")
print(f"Estimated management settled at in-window mint/burn (included, NOT additional): ${estimated_management_settlements.Fee.sum():,.2f}")
if not estimated_management_settlements.empty:
    display(estimated_management_settlements)
if fee_schedule.Incomplete.any() or unsettled_missing is None or unsettled_missing>0:
    print("WARNING: missing NAV observations; calculated fees use known estimates only, not a complete fee total.")
if fee_nav_history is None:
    print("WARNING: market capitalization is a NAV proxy, not independently reconstructed historical NAV. Supply depends on complete mint/burn retrieval.")
print("\n=== VERIFIED FEE WITHDRAWALS ===")
if verified_input is None:
    print("No verified fee-payment records supplied. The chart shows calculated fee entitlement, not verified cash payments.")
else:
    print(f"Verified withdrawals: ${verified_fees.Fee.sum():,.2f}; coverage: {'declared complete' if verified_complete else 'partial'}")
    display(verified_fees)
print("Benchmark used:",baseline_label)
print("\n=== PORTFOLIO CONVERSION MATCHES (including fee-free exclusions) ===")
if len(conversion_matches):
    display(conversion_matches.sort_values("Date",ascending=False))
    charged=conversion_matches.loc[conversion_matches.Kind=="Portfolio conversion"]
    print(f"Matched conversion notional: ${charged['USD out'].sum():,.2f}; estimated cost credit: ${charged.Fee.sum():,.2f}")
else: print("No conversion pairs matched; no portfolio trading credit inferred.")
print(f"Unmatched material eligible custody legs: {len(unmatched_conversion_legs)} (no inferred fee; retained in residual)")
if len(unmatched_conversion_legs):
    display(unmatched_conversion_legs[["Date","Chain","Asset","USD","Class","Ref"]].sort_values("Date",ascending=False))
print("Contractual/estimated fee-event breakdown (fee_schedule):")
display(fee_schedule.sort_values("Date",ascending=False))
print(f"Historical forward net AFTER opening: {reverse.loc[reverse.Date>opening,'Net USD'].sum():+,.2f} USD; raw priced sum AFTER opening: {reverse.loc[reverse.Date>opening,'Raw USD'].sum():+,.2f} USD")
print(f"Small legs hidden but included in calculations: {len(dust)}; net {dust['Net USD'].sum(min_count=1):+,.4f} USD")
print(f"Unpriced net legs: {reverse['Net USD'].isna().sum()}; quarantined records: {len(QUARANTINE)}")
print(f"POOL_FLOW_SHARE={POOL_FLOW_SHARE} (assumed), issuance-offset={INCLUDE_ISSUANCE_OFFSET}; this is a flow diagnostic, not verified NAV or personal debt.")
print("\n=== NET CONTRIBUTION BY CHAIN AND TYPE ===")
display(reverse.groupby(["Chain","Class"]).agg(legs=("Net USD","size"),raw_usd=("Raw USD",lambda x:x.sum(min_count=1)),net_usd=("Net USD",lambda x:x.sum(min_count=1))))
if AUDIT_WARNINGS:
    print("\nINCOMPLETE OR APPROXIMATE COVERAGE:")
    for w in AUDIT_WARNINGS:print("WARNING:",w)
if not any(t["asset"]=="PPLTX" for t in sol1_txns+sol2_txns):print("PPLTX: no retrieved movements in window; check opening balance and account history.")
# Full data remain available: reverse, timeline, dust, QUARANTINE, ledger, receipts.

Counterparty Monitor

Tracks collapse risk at every exchange and DeFi protocol that Alef Financial uses — combining AI-powered news screening with live on-chain reserve and TVL data, running 24/7 on Alef Financial's own infrastructure.

Run this open-source program to replicate the monitoring locally:

import os
import json
import time
import random
import html
import urllib.parse
import xml.etree.ElementTree as ET
import statistics
from typing import List, Dict, Optional

import requests
from openai import OpenAI
import sys
from datetime import datetime, timedelta
import email.utils as eut
import smtplib
from email.mime.text import MIMEText

# ---------------------------------------------------------
# CONFIGURATION — set these as environment variables
# ---------------------------------------------------------

OPENAI_API_KEY     = os.environ.get("OPENAI_API_KEY", "")
EMAIL_USER         = os.environ.get("EMAIL_USER", "")
EMAIL_PASSWORD     = os.environ.get("EMAIL_PASSWORD", "")   # Gmail app password
EMAIL_TO           = os.environ.get("EMAIL_TO", "")
NTFY_TOPIC         = os.environ.get("NTFY_TOPIC", "")
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
TELEGRAM_CHAT_ID   = os.environ.get("TELEGRAM_CHAT_ID", "")
ETHERSCAN_API_KEY  = os.environ.get("ETHERSCAN_API_KEY", "")

EMAIL_HOST  = "smtp.gmail.com"
EMAIL_PORT  = 587
EMAIL_FROM  = EMAIL_USER
NTFY_SERVER = "https://ntfy.sh"

HISTORY_FILE      = os.path.expanduser("~/alef_data/onchain_history.json")
SEEN_LINKS_FILE   = os.path.expanduser("~/alef_data/seen_links.json")
SEEN_ALERTS_FILE  = os.path.expanduser("~/alef_data/seen_alerts.json")
SEEN_LINKS_TTL    = 7 * 86400   # forget links older than 7 days
ALERT_COOLDOWN    = 48 * 3600   # suppress repeat alerts for same story within this window

# ---------------------------------------------------------
# NEWS MONITORING CONFIG
# ---------------------------------------------------------

BASE_CHECK_INTERVAL = 60
MAX_ITEMS_PER_QUERY = 5
GOOGLE_NEWS_RSS = (
    "https://news.google.com/rss/search"
    "?q={query}&hl=en-US&gl=US&ceid=US:en"
)

NEWS_TARGETS: Dict[str, str] = {
    "Binance":  "binance crypto exchange",
    "Paxos":    "paxos crypto",
    "Bitfinex": "bitfinex crypto exchange",
    "Kraken":   "kraken crypto exchange",
    "Ondo":     "ondo finance crypto",
    "Gate.io":  "gate.io crypto exchange",
    "Bitgo":    "bitgo crypto custodian",
    "Coinbase": "coinbase crypto exchange",
    "OKX":      "okx crypto exchange",
    "MEXC":     "mexc crypto exchange",
    "Circle":   "circle usdc stablecoin",
    "Bybit":    "bybit crypto exchange",
    "AAVE":     "aave defi protocol",
    "Morpho":   "morpho defi lending",
    "JustLend": "justlend tron defi",
    "Venus":    "venus bnb chain defi",
}

# ---------------------------------------------------------
# ON-CHAIN MONITORING CONFIG
# ---------------------------------------------------------

ONCHAIN_CHECK_INTERVAL = 3600    # seconds between on-chain scans
SIGMA_THRESHOLD        = 3.0
MIN_CHANGE_PAIRS       = 7       # need this many historical 24h pairs before alerting

# Known exchange ETH addresses (publicly documented hot/cold wallets)
# Coverage is partial — exchanges have many more addresses, but these are
# the primary consolidation wallets visible on-chain.
ONCHAIN_ETH: Dict[str, List[str]] = {
    "Binance":  ["0x28C6c06298d514Db089934071355E5743bf21d60",
                 "0x21a31Ee1afC51d94C2eFcCAa2092aD1028285549"],
    "Coinbase": ["0x71660c4005BA85c37ccec55d0C4493E66Fe775d3"],
    "Kraken":   ["0x2910543Af39abA0Cd09dBb2D50200b3E800A63D2"],
    "Bitfinex": ["0x742d35Cc6634C0532925a3b844Bc454e4438f44e"],
    "OKX":      ["0x6cC5F688a315f3dC28A7781717a9A798a59fDA7b"],
    "Gate.io":  ["0x0D0707963952f2fBA59dD06f2b425ace40b492Fe"],
    "Bybit":    ["0xf89d7b9c864f589bbF53a82105107622B35EaA40"],
}

# Known exchange BTC cold wallet addresses (limited — exchanges use HD wallets with many addresses)
ONCHAIN_BTC: Dict[str, List[str]] = {
    "Binance":  ["34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo"],
    "Coinbase": ["3Cbq7aT1tY8kMxWLbitaG7yT6bPbKChq64"],
    "Kraken":   ["3AF1LfyevjuZ5GBdRG5HoNr3YJXTA3m41D"],
}

# DeFi protocol slugs on DeFiLlama (https://defillama.com)
DEFI_SLUGS: Dict[str, str] = {
    "AAVE":     "aave",
    "Morpho":   "morpho",
    "JustLend": "justlend",
    "Venus":    "venus-core-pool",
}

# ---------------------------------------------------------
# CLIENTS / STATE
# ---------------------------------------------------------

oa_client  = OpenAI(api_key=OPENAI_API_KEY)
last_onchain_check: float  = 0.0

# seen_links: {name: {url: epoch_timestamp}} — persisted across restarts
def _load_seen_links() -> Dict[str, dict]:
    now = time.time()
    try:
        with open(SEEN_LINKS_FILE) as f:
            raw = json.load(f)
    except Exception:
        raw = {}
    result = {name: {} for name in NEWS_TARGETS}
    for name, links in raw.items():
        if name in result:
            result[name] = {url: ts for url, ts in links.items()
                            if now - ts < SEEN_LINKS_TTL}
    return result

def _save_seen_links(seen: Dict[str, dict]):
    os.makedirs(os.path.dirname(SEEN_LINKS_FILE), exist_ok=True)
    with open(SEEN_LINKS_FILE, "w") as f:
        json.dump(seen, f)

seen_links: Dict[str, dict] = _load_seen_links()

# seen_alerts: {name: {time: epoch, summary: str}} — suppresses repeat alerts for same story
def _load_seen_alerts() -> Dict[str, dict]:
    try:
        with open(SEEN_ALERTS_FILE) as f:
            return json.load(f)
    except Exception:
        return {}

def _save_seen_alerts(alerts: Dict[str, dict]):
    os.makedirs(os.path.dirname(SEEN_ALERTS_FILE), exist_ok=True)
    with open(SEEN_ALERTS_FILE, "w") as f:
        json.dump(alerts, f)

seen_alerts: Dict[str, dict] = _load_seen_alerts()


# ==========================================================
# ALERT CHANNELS
# ==========================================================

def now_str() -> str:
    return time.strftime("%Y-%m-%d %H:%M:%S")


def send_email_alert(subject_tag: str, body: str):
    if not EMAIL_USER or not EMAIL_PASSWORD:
        return
    msg = MIMEText(body, _charset="utf-8")
    msg["Subject"] = f"[ALERT] {subject_tag}"
    msg["From"]    = EMAIL_FROM
    msg["To"]      = EMAIL_TO
    try:
        with smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) as s:
            s.starttls()
            s.login(EMAIL_USER, EMAIL_PASSWORD)
            s.send_message(msg)
        print("    >> Email alert sent.")
    except Exception as e:
        print(f"    >> Email error: {e}")


def send_ntfy_alert(title: str, body: str):
    if not NTFY_TOPIC:
        return
    try:
        requests.post(
            f"{NTFY_SERVER}/{NTFY_TOPIC}",
            data=body.encode("utf-8"),
            headers={"Title": title, "Priority": "urgent",
                     "Tags": "rotating_light", "Click": "https://news.google.com/"},
            timeout=10,
        )
        print("    >> ntfy alert sent.")
    except Exception as e:
        print(f"    >> ntfy error: {e}")


def send_telegram_alert(title: str, body: str):
    if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
        return
    text = f"\U0001f6a8 {title}\n\n{body}"
    try:
        requests.post(
            f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage",
            json={"chat_id": TELEGRAM_CHAT_ID, "text": text},
            timeout=10,
        )
        print("    >> Telegram alert sent.")
    except Exception as e:
        print(f"    >> Telegram error: {e}")


def fire_alert(title: str, body: str):
    print(f"    >> ALERT: {title}: {body}")
    send_email_alert(title, body)
    send_ntfy_alert(title, body)
    send_telegram_alert(title, body)
    time.sleep(60 * 5)  # 5-minute anti-spam pause


# ==========================================================
# NEWS MONITORING
# ==========================================================

def fetch_google_news_rss(query: str) -> List[dict]:
    url = GOOGLE_NEWS_RSS.format(query=urllib.parse.quote(query))
    try:
        resp = requests.get(url, timeout=10)
        resp.raise_for_status()
        root = ET.fromstring(resp.content)
        channel = root.find("channel")
        if channel is None:
            return []
    except Exception:
        return []

    cutoff = datetime.utcnow() - timedelta(hours=24)
    items  = []
    for item in channel.findall("item"):
        title   = item.findtext("title", "") or ""
        link    = item.findtext("link",  "") or ""
        summary = html.unescape(item.findtext("description", "") or "")
        pub     = item.findtext("pubDate", "")
        try:
            pub_dt = eut.parsedate_to_datetime(pub)
            if pub_dt.tzinfo is not None:
                pub_dt = pub_dt.astimezone(tz=None).replace(tzinfo=None)
        except Exception:
            continue
        if pub_dt < cutoff:
            continue
        items.append({"title": title.strip(), "link": link.strip(),
                      "summary": summary.strip(), "pubDate": pub_dt.isoformat()})
        if len(items) >= MAX_ITEMS_PER_QUERY:
            break
    return items


def classify_collapse_risk(counterparty: str, news_items: List[dict]) -> int:
    if not news_items:
        return 0
    snippets = [f"{i}. {it['title']}\n{it['summary']}\nLink: {it['link']}\n"
                for i, it in enumerate(news_items, 1)]
    system_msg = (
        "You are a collapse-risk detector for crypto exchanges, custodians, and DeFi protocols. "
        "You ONLY output '1' or '0'.\n\n"
        "Output '1' if there is any indication of insolvency, liquidity stress, a run on the "
        "platform, withdrawal or redemption pauses or freezes, regulatory freezes that could "
        "affect customer assets, serious fraud or exploit allegations, accounting holes, smart "
        "contract hacks, or anything suggesting users may lose access to their funds.\n"
        "Output '0' if the news is neutral, positive, or unlikely to lead to customer losses.\n\n"
        "Your answer must be exactly one character: '1' or '0'. No other text."
    )
    user_msg = (
        f"Counterparty: {counterparty}\n\nRecent news:\n{''.join(snippets)}\n"
        f"Does this suggest ANY possible collapse, insolvency, exploit risk, withdrawal halt, "
        f"or serious legal/regulatory threat for {counterparty}? Answer: 1 or 0."
    )
    try:
        resp = oa_client.chat.completions.create(
            model="gpt-4.1-mini",
            messages=[{"role": "system", "content": system_msg},
                      {"role": "user",   "content": user_msg}],
            temperature=0,
        )
    except Exception:
        return 0
    raw = resp.choices[0].message.content.strip()
    return int(raw[0]) if raw and raw[0] in ("0", "1") else 0


def summarize_for_alert(counterparty: str, news_items: List[dict]) -> str:
    if not news_items:
        return f"No significant negative news detected for {counterparty}."
    text = "\n".join(f"{it['title']}: {it['summary']}" for it in news_items)
    system_msg = (
        "Summarize in EXACTLY ONE short sentence for a push notification. "
        "Name the counterparty and state the specific risk. No preamble or second sentence."
    )
    try:
        resp = oa_client.chat.completions.create(
            model="gpt-4.1-mini",
            messages=[{"role": "system", "content": system_msg},
                      {"role": "user",   "content": text}],
            temperature=0.3,
        )
    except Exception:
        return "(summary unavailable)"
    s = resp.choices[0].message.content.strip()
    return s[:257] + "..." if len(s) > 260 else s


def _is_same_story(counterparty: str, new_summary: str, prev_summary: str) -> bool:
    """Ask GPT whether two alert summaries describe the same underlying event."""
    system_msg = (
        "You are comparing two risk alert summaries for the same counterparty. "
        "Output '1' if they describe the same underlying event or ongoing situation "
        "(e.g. the same hack, the same regulatory probe, the same insolvency). "
        "Output '0' if the new alert describes a materially distinct new development. "
        "Answer with exactly '1' or '0'. No other text."
    )
    user_msg = (
        f"Counterparty: {counterparty}\n\n"
        f"Previous alert (already sent): {prev_summary}\n\n"
        f"New potential alert: {new_summary}\n\n"
        "Same story? 1 or 0."
    )
    try:
        resp = oa_client.chat.completions.create(
            model="gpt-4.1-mini",
            messages=[{"role": "system", "content": system_msg},
                      {"role": "user",   "content": user_msg}],
            temperature=0,
        )
        raw = resp.choices[0].message.content.strip()
        return bool(raw and raw[0] == "1")
    except Exception:
        return False


def monitor_news(name: str, query: str) -> tuple:
    items = fetch_google_news_rss(query)
    if not items:
        return (0, "No RSS items.")
    seen      = seen_links[name]
    new_items = [it for it in items if it["link"] not in seen]
    for it in new_items:
        seen[it["link"]] = time.time()
    if not new_items:
        return (0, "No new items.")
    signal  = classify_collapse_risk(name, new_items)
    if signal != 1:
        return (signal, summarize_for_alert(name, new_items))
    summary = summarize_for_alert(name, new_items)
    # Suppress if we already alerted on the same story within ALERT_COOLDOWN.
    prev = seen_alerts.get(name, {})
    if prev and time.time() - prev.get("time", 0) < ALERT_COOLDOWN:
        if _is_same_story(name, summary, prev.get("summary", "")):
            age_h = int((time.time() - prev["time"]) / 3600)
            print(f"    >> Suppressed (same story as alert {age_h}h ago): {summary}")
            return (1, f"[suppressed — same story] {summary}")
    fire_alert(f"{name} collapse-risk signal", summary)
    seen_alerts[name] = {"time": time.time(), "summary": summary}
    _save_seen_alerts(seen_alerts)
    return (signal, summary)


# ==========================================================
# ON-CHAIN MONITORING
# ==========================================================

def _get_prices() -> tuple:
    """Returns (eth_usd, btc_usd). Falls back to 0 on error."""
    try:
        r = requests.get(
            "https://api.coingecko.com/api/v3/simple/price"
            "?ids=ethereum,bitcoin&vs_currencies=usd",
            timeout=10,
        )
        d = r.json()
        return d["ethereum"]["usd"], d["bitcoin"]["usd"]
    except Exception:
        return 0.0, 0.0


def _eth_balance_usd(addresses: List[str], eth_price: float) -> float:
    if not ETHERSCAN_API_KEY or not addresses or eth_price == 0:
        return 0.0
    addr_str = ",".join(addresses)
    url = (
        f"https://api.etherscan.io/v2/api?chainid=1"
        f"&module=account&action=balancemulti"
        f"&address={addr_str}&tag=latest&apikey={ETHERSCAN_API_KEY}"
    )
    r = requests.get(url, timeout=10)
    result = r.json().get("result", [])
    total_wei = sum(int(row["balance"]) for row in result)
    return (total_wei / 1e18) * eth_price


def _btc_balance_usd(addresses: List[str], btc_price: float) -> float:
    if not addresses or btc_price == 0:
        return 0.0
    total_sats = 0
    for addr in addresses:
        try:
            r = requests.get(
                f"https://blockstream.info/api/address/{addr}", timeout=10
            )
            d      = r.json()
            funded = d["chain_stats"]["funded_txo_sum"]
            spent  = d["chain_stats"]["spent_txo_sum"]
            total_sats += funded - spent
        except Exception:
            pass
    return (total_sats / 1e8) * btc_price


def _defi_tvl_usd(slug: str) -> float:
    r = requests.get(f"https://api.llama.fi/tvl/{slug}", timeout=10)
    return float(r.text)


def _load_history() -> dict:
    try:
        with open(HISTORY_FILE) as f:
            return json.load(f)
    except Exception:
        return {}


def _save_history(history: dict):
    os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
    with open(HISTORY_FILE, "w") as f:
        json.dump(history, f)


def _append_reading(name: str, value: float, history: dict):
    if name not in history:
        history[name] = []
    history[name].append({"t": int(time.time()), "v": value})
    # Keep 90 days max
    cutoff = time.time() - 90 * 86400
    history[name] = [r for r in history[name] if r["t"] > cutoff]


def _check_sigma_drop(name: str, current_val: float, history: dict) -> Optional[str]:
    """
    Returns an alert string if the 24h change in `current_val` is more than
    SIGMA_THRESHOLD standard deviations below the historical mean 24h change.
    Returns None otherwise (including when there is insufficient history).
    """
    readings = history.get(name, [])
    if len(readings) < 2:
        return None

    sorted_r = sorted(readings, key=lambda r: r["t"])

    # Find reading closest to 24h ago
    now     = time.time()
    target  = now - 86400
    closest = min(sorted_r, key=lambda r: abs(r["t"] - target))
    if abs(closest["t"] - target) > 8 * 3600:
        return None  # no reading within 8h of 24h ago
    change_now = current_val - closest["v"]

    # Build historical 24h changes (non-overlapping, ~daily spacing)
    historical_changes = []
    i = 0
    while i < len(sorted_r):
        r_past   = sorted_r[i]
        tgt      = r_past["t"] + 86400
        near     = [r for r in sorted_r if abs(r["t"] - tgt) < 6 * 3600]
        if near:
            r_fut = min(near, key=lambda r: abs(r["t"] - tgt))
            historical_changes.append(r_fut["v"] - r_past["v"])
        # Advance by 20h to get roughly non-overlapping daily pairs
        i = next((j for j, r in enumerate(sorted_r) if r["t"] >= r_past["t"] + 72000),
                 len(sorted_r))

    if len(historical_changes) < MIN_CHANGE_PAIRS:
        return None

    mean = statistics.mean(historical_changes)
    try:
        std = statistics.stdev(historical_changes)
    except statistics.StatisticsError:
        return None

    if std == 0:
        return None

    z = (change_now - mean) / std
    if z < -SIGMA_THRESHOLD:
        ref_val = closest["v"]
        pct     = ((current_val - ref_val) / ref_val * 100) if ref_val else 0
        label   = f"${current_val / 1e9:.2f}B" if current_val > 1e8 else f"${current_val / 1e6:.1f}M"
        return (
            f"{name} on-chain reserves dropped {abs(pct):.1f}% in 24h "
            f"(z = {z:.1f}σ). Current: {label}."
        )
    return None


def run_onchain_checks():
    print(f"\n  [ON-CHAIN SCAN] {now_str()}")
    history   = _load_history()
    eth_price, btc_price = _get_prices()
    print(f"  Prices: ETH=${eth_price:,.0f}  BTC=${btc_price:,.0f}")

    # If price fetch failed, every USD value would be $0 — skip all checks to
    # avoid a flood of false "100% drop" alerts.
    if eth_price == 0 or btc_price == 0:
        print("  [SKIP] Price fetch returned 0 — aborting on-chain checks to prevent false alerts.")
        return

    # --- Exchange ETH reserves ---
    all_eth_addresses = list({
        addr
        for addrs in ONCHAIN_ETH.values()
        for addr in addrs
    })
    try:
        # Fetch all at once (Etherscan balancemulti supports up to 20 addresses)
        addr_str = ",".join(all_eth_addresses)
        url = (
            f"https://api.etherscan.io/v2/api?chainid=1"
            f"&module=account&action=balancemulti"
            f"&address={addr_str}&tag=latest&apikey={ETHERSCAN_API_KEY}"
        )
        eth_balances: Dict[str, float] = {}
        r = requests.get(url, timeout=15)
        data = r.json()
        result = data.get("result", [])
        # Guard: Etherscan returns a string (error message) instead of a list on failure
        if not isinstance(result, list):
            print(f"  [SKIP ETH] Etherscan returned non-list result: {result!r}")
        else:
            for row in result:
                eth_balances[row["account"].lower()] = int(row["balance"]) / 1e18

            # Guard: if every address came back with 0 balance, API likely failed silently
            if all_eth_addresses and not any(eth_balances.values()):
                print("  [SKIP ETH] All balances returned as 0 — possible API failure, skipping alerts.")
            else:
                for name, addrs in ONCHAIN_ETH.items():
                    eth_total = sum(eth_balances.get(a.lower(), 0.0) for a in addrs)
                    usd_val   = eth_total * eth_price
                    alert     = _check_sigma_drop(name + "_eth", usd_val, history)
                    _append_reading(name + "_eth", usd_val, history)
                    tag = f"  ETH  {name:10}"
                    print(f"{tag} {eth_total:.1f} ETH  ≈  ${usd_val / 1e6:.1f}M")
                    if alert:
                        fire_alert(f"ON-CHAIN RESERVE DROP — {name} (ETH)", alert)
    except Exception as e:
        print(f"  ETH fetch error: {e}")

    # --- Exchange BTC reserves ---
    for name, addrs in ONCHAIN_BTC.items():
        try:
            usd_val = _btc_balance_usd(addrs, btc_price)
            # Guard: 0 with a non-empty address list means the API failed
            if usd_val == 0 and addrs:
                print(f"  [SKIP BTC {name}] Balance returned as 0 — possible API failure, skipping alert.")
                continue
            alert   = _check_sigma_drop(name + "_btc", usd_val, history)
            _append_reading(name + "_btc", usd_val, history)
            print(f"  BTC  {name:10} ${usd_val / 1e6:.1f}M")
            if alert:
                fire_alert(f"ON-CHAIN RESERVE DROP — {name} (BTC)", alert)
        except Exception as e:
            print(f"  BTC {name} error: {e}")

    # --- DeFi protocol TVL ---
    for name, slug in DEFI_SLUGS.items():
        try:
            usd_val = _defi_tvl_usd(slug)
            alert   = _check_sigma_drop(name + "_tvl", usd_val, history)
            _append_reading(name + "_tvl", usd_val, history)
            label = f"${usd_val / 1e9:.2f}B" if usd_val > 1e8 else f"${usd_val / 1e6:.1f}M"
            print(f"  TVL  {name:10} {label}")
            if alert:
                fire_alert(f"ON-CHAIN TVL DROP — {name}", alert)
        except Exception as e:
            print(f"  TVL {name} error: {e}")

    _save_history(history)
    print(f"  [ON-CHAIN SCAN DONE]")


# ==========================================================
# MAIN LOOP
# ==========================================================

def main():
    global last_onchain_check
    print(">>> Counterparty collapse monitor starting…")
    print(f"    News targets:     {len(NEWS_TARGETS)}")
    print(f"    On-chain ETH:     {len(ONCHAIN_ETH)} exchanges")
    print(f"    On-chain BTC:     {len(ONCHAIN_BTC)} exchanges")
    print(f"    DeFi TVL:         {len(DEFI_SLUGS)} protocols")

    while True:
        print(f"\nTime: {now_str()}")
        print("-" * 100)

        # --- News scan ---
        for name, query in NEWS_TARGETS.items():
            try:
                signal, summary = monitor_news(name, query)
            except Exception as e:
                signal, summary = (0, f"ERROR: {e}")
            print(f"{name:10} | SIGNAL = {signal} | {summary}")
        _save_seen_links(seen_links)

        # --- On-chain scan (every ONCHAIN_CHECK_INTERVAL seconds) ---
        if time.time() - last_onchain_check >= ONCHAIN_CHECK_INTERVAL:
            try:
                run_onchain_checks()
            except Exception as e:
                print(f"  [ON-CHAIN ERROR] {e}")
            last_onchain_check = time.time()

        wait = max(20, BASE_CHECK_INTERVAL + random.uniform(-10, 10))
        print("-" * 100)
        print(f"Next news scan in {int(wait)} s  |  Next on-chain scan in "
              f"{max(0, int(ONCHAIN_CHECK_INTERVAL - (time.time() - last_onchain_check)))} s")
        time.sleep(wait)


if __name__ == "__main__":
    main()

Performance Backtest

The exact JavaScript that generates the performance chart — monthly return series from January 2018 to June 2026, plus live daily ALEF price data. Every number visible in the chart comes directly from here.

Chart data and rendering code, verbatim from this page:

        window.BACKTEST_DATA = {"portfolio":[1.048,0.999,0.913,0.917,0.812,0.787,0.88,0.859,0.858,0.817,0.752,0.726,0.654,0.626,0.721,0.817,0.803,0.863,0.809,0.792,0.76,0.768,0.785,0.718,0.69,0.669,0.698,0.677,0.705,0.725,0.696,0.625,0.63,0.628,0.642,0.588,0.587,0.673,0.662,0.651,0.608,0.62,0.611,0.61,0.617,0.575,0.5,0.497,0.45,0.434,0.467,0.5,0.509,0.496,0.496,0.495,0.493,0.508,0.513,0.548,0.529,0.525,0.54,0.544,0.546,0.607,0.601,0.614,0.605,0.626,0.632,0.705,0.717,0.751,0.745,0.764,0.845,0.9,0.852,0.868,0.821,0.818,0.811,0.841,0.791,0.797,0.78,0.795,0.798,0.835,0.739,0.747,0.76,0.758,0.791,0.813,0.785,0.775,0.72,0.739,0.726,0.723,0.712,0.723,0.74,0.784,0.84,0.817,0.853,0.922,1.005,0.964,0.829,0.879,0.625,0.573,0.644,0.654,0.735,0.755,0.781,0.827,0.879,0.858,0.876,0.897,0.916,0.907,0.914,0.909,0.929,0.985,0.971,1.039,1.198,1.292,1.292,1.281,1.315,1.239,1.195,1.214,1.157,1.164,1.235,1.228,1.294,1.244,1.422,1.418,1.518,1.632,1.745,1.705,1.93,1.839,1.991,2.483,2.306,2.32,2.353,2.754,3.099,3.196,2.699,2.731,2.963,3.01,3.009,3.164,3.55,3.989,3.618,3.986,4.18,4.029,3.462,3.47,3.55,3.502,3.317,3.103,3.298,3.299,3.141,3.286,3.647,3.679,4.083,4.207,4.238,4.468,4.059,4.066,3.84,3.987,4.155,4.456,4.502,4.648,4.796,4.944,4.752,4.369,4.317,4.157,4.065,4.395,4.185,3.814,3.899,3.45,3.391,3.613,3.698,3.64,3.623,3.599,3.585,3.821,4.002,4.09,3.854,3.736,3.588,3.353,3.223,2.736,2.679,2.723,2.737,2.615,2.173,2.33,2.122,2.24,2.171,2.355,2.526,2.545,2.681,2.395,2.288,2.212,2.358,2.174,2.196,2.155,2.206,2.087,2.146,2.263,2.278,2.193,2.134,2.158,2.251,2.189,2.09,2.091,2.083,2.136,2.378,2.533,2.588,2.617,2.471,2.587,2.448,2.476,2.333,2.766,2.826,3.006,2.991,3.121,2.9,3.017,3.056,2.902,2.969,3.003,3.116,3.096,3.078,3.184,3.204,3.172,3.493,3.498,3.458,3.298,3.246,2.976,3.049,3.095,3.041,3.053,3.007,2.974,3.002,3.006,3.113,3.265,3.426,3.577,3.595,3.694,3.783,3.937,3.904,4.032,3.989,3.894,3.984,3.961,3.914,3.969,4.135,4.32,4.321,4.839,5.138,5.11,4.985,5.209,5.205,5.139,4.896,4.953,4.91,4.916,5.263,5.374,5.292,5.293,5.304,5.284,5.151,5.154,5.277,5.554,5.477,5.186,5.106,5.292,5.534,5.273,4.843,5.367,5.548,5.706,5.496,5.536,5.827,5.694,5.709,6.126,6.671,7.877,8.333,9.389,9.429,8.961,8.789,9.108,8.853,9.738,9.773,9.665,9.101,9.507,9.317,8.338,8.424,8.242,8.31,8.189,7.544,7.84,7.904,8.558,8.707,9.319,9.612,9.761,9.607,9.809,10.0,9.74,9.943,10.324,10.987,11.65,11.627,11.179,11.96,12.002,12.13,11.763,12.111,12.745,12.805,12.553,13.496,12.728,12.968,13.15,13.075,12.355,12.021,11.148,12.242,12.189,12.273,12.254,12.693,12.499,13.06,13.521,13.694,12.638,11.465,11.393,11.535,11.589,11.399,11.395,10.717,10.162,10.584,11.368,12.296,12.127,12.077,12.768,12.397,12.047,12.145,10.407,10.62],"btc":[1.163,0.933,0.775,0.746,0.589,0.583,0.683,0.688,0.74,0.623,0.557,0.593,0.478,0.443,0.527,0.59,0.6,0.647,0.563,0.551,0.499,0.503,0.509,0.431,0.406,0.415,0.445,0.416,0.491,0.545,0.496,0.413,0.439,0.449,0.47,0.432,0.435,0.45,0.443,0.442,0.419,0.432,0.432,0.426,0.426,0.372,0.29,0.268,0.228,0.216,0.26,0.262,0.257,0.246,0.244,0.24,0.233,0.245,0.242,0.267,0.258,0.26,0.264,0.269,0.274,0.336,0.34,0.354,0.352,0.385,0.426,0.49,0.533,0.572,0.537,0.58,0.677,0.828,0.733,0.789,0.703,0.659,0.702,0.792,0.692,0.695,0.641,0.691,0.692,0.68,0.551,0.548,0.555,0.532,0.578,0.618,0.588,0.567,0.487,0.518,0.504,0.485,0.482,0.487,0.49,0.545,0.596,0.564,0.624,0.654,0.688,0.647,0.579,0.609,0.371,0.414,0.432,0.449,0.487,0.474,0.504,0.592,0.657,0.623,0.613,0.63,0.645,0.633,0.62,0.612,0.609,0.619,0.611,0.637,0.756,0.774,0.786,0.774,0.77,0.702,0.694,0.731,0.714,0.706,0.739,0.756,0.863,0.904,1.039,1.089,1.243,1.142,1.248,1.205,1.544,1.584,1.936,2.723,2.458,2.203,2.29,2.546,3.171,3.73,3.093,3.266,3.827,3.894,3.68,3.944,3.888,4.11,3.41,3.855,3.828,3.329,2.49,2.383,2.463,2.492,2.389,2.112,2.263,2.256,2.097,2.241,2.819,2.858,3.19,3.293,3.274,3.339,2.996,3.155,2.859,3.212,3.602,4.111,4.051,4.153,4.08,4.282,3.879,3.576,3.577,3.153,3.084,3.39,3.091,2.774,2.877,2.433,2.522,2.77,2.831,2.672,2.617,2.612,2.589,2.79,2.96,3.089,2.823,2.666,2.653,2.577,2.406,1.955,1.949,1.911,1.983,1.941,1.366,1.417,1.286,1.45,1.391,1.516,1.589,1.554,1.629,1.393,1.352,1.333,1.427,1.32,1.288,1.297,1.305,1.281,1.28,1.375,1.411,1.137,1.115,1.103,1.141,1.144,1.111,1.121,1.108,1.131,1.329,1.514,1.54,1.565,1.445,1.64,1.548,1.493,1.347,1.83,1.835,1.901,1.872,2.035,1.821,1.958,1.971,1.789,1.795,1.783,1.819,1.767,1.757,2.049,2.034,2.025,2.025,1.996,1.957,1.941,1.962,1.739,1.739,1.722,1.729,1.776,1.774,1.796,1.865,1.793,1.981,2.263,2.318,2.491,2.443,2.518,2.582,2.948,2.799,2.937,2.81,2.948,2.86,2.778,2.791,2.882,3.147,3.482,3.386,4.168,4.559,4.632,4.257,4.722,4.528,4.485,4.261,4.255,4.198,4.058,4.475,4.574,4.505,4.628,4.406,4.278,4.026,3.782,3.865,4.453,4.533,4.099,4.064,3.931,4.278,3.946,3.601,4.043,4.218,4.391,4.143,4.168,4.567,4.448,4.638,5.109,6.078,6.608,6.505,6.669,6.772,6.525,6.285,6.548,6.321,6.972,6.996,6.835,6.443,6.508,6.416,5.632,5.79,5.605,5.61,5.63,5.596,5.567,5.666,6.322,6.468,6.873,6.908,7.161,6.942,6.968,7.081,6.896,7.148,7.319,7.844,7.876,7.852,7.564,7.789,7.836,7.801,7.236,7.386,7.749,7.722,7.323,8.161,7.557,7.106,7.411,7.312,6.9,6.301,5.679,6.069,5.966,6.025,5.881,5.827,6.003,6.041,6.376,5.974,5.615,4.709,4.596,4.539,4.397,4.548,4.737,4.707,4.428,4.465,4.871,5.148,5.17,5.218,5.352,5.277,5.039,4.897,4.066,3.915,3.684,3.936,3.944,4.003,4.045,3.931,4.014,3.89,4.787]};
    window.ALEF_CHART_SEED = {"pts":[{"price":0.9701299125557773,"t":1781654400000},{"price":0.9666778958208094,"t":1781740800000},{"price":0.9589756299778089,"t":1781827200000},{"price":0.9677419865403316,"t":1781913600000},{"price":0.9678387835287172,"t":1782000000000},{"price":0.9644997951469104,"t":1782086400000},{"price":0.9316642512456081,"t":1782172800000},{"price":0.9037854789302074,"t":1782259200000},{"price":0.8831595052909164,"t":1782345600000},{"price":0.888148665516812,"t":1782432000000},{"price":0.8973802102822114,"t":1782691200000},{"price":0.8945587503989605,"t":1782777600000},{"price":0.8967865576948125,"t":1782864000000},{"price":0.8939439989753165,"t":1782950400000},{"price":0.9018424100592309,"t":1783036800000},{"price":0.8998534608985043,"t":1783123200000},{"price":0.9331615299553199,"t":1783296000000},{"price":0.9266739628014922,"t":1783382400000},{"price":0.9094989064810768,"t":1783468800000},{"price":0.9169598280830034,"t":1783555200000},{"price":0.9228971332048579,"t":1783641600000},{"price":0.91560317112136,"t":1783900800000},{"price":0.9198789053269243,"t":1783987200000},{"price":0.9148539675933903,"t":1784246400000},{"price":0.9082250020210703,"t":1784505600000},{"price":0.9039025267780647,"t":1784592000000},{"price":0.9032917434667896,"t":1784851200000},{"price":0.9072134491412259,"t":1785283200000},{"price":0.9098470522115869,"t":1785801600000},{"price":0.9577867967628526,"t":1785888000000},{"price":0.9554228150140983,"t":1785974400000},{"price":0.9556893544490005,"t":1786060800000},{"price":0.9642972500412297,"t":1786147200000},{"price":0.9723086430009021,"t":1786320000000},{"price":0.9674245643331617,"t":1786406400000},{"price":0.9677588847512523,"t":1786492800000},{"price":0.964572534935179,"t":1786924800000},{"price":0.9822319236680227,"t":1787011200000},{"price":1.0217459699276858,"t":1787097600000},{"price":1.0341560418550175,"t":1787184000000},{"price":1.0749472145526642,"t":1787270400000},{"price":1.0814258376812187,"t":1787356800000},{"price":1.0889074085903403,"t":1787443200000},{"price":1.0874361759967583,"t":1787529600000},{"price":1.0822622521494543,"t":1787702400000},{"price":1.0916148996641706,"t":1787788800000},{"price":1.0778945135030724,"t":1787875200000},{"price":1.0719316032168347,"t":1787961600000},{"price":1.0653014927564892,"t":1788219303545},{"price":1.0365773521071424,"t":1788305638603},{"price":1.0438616243831704,"t":1788392514131},{"price":1.08463080915975,"t":1788478851833},{"price":1.0718144377147516,"t":1788558859809},{"price":1.0816622476074227,"t":1788651866830},{"price":1.0834142043820438,"t":1788738661174},{"price":1.0764277257207586,"t":1788825581417},{"price":1.072654369062336,"t":1788911533560},{"price":1.081324629772588,"t":1788957808020},{"price":1.0680246431548126,"t":1788998400000},{"price":1.0323588719999948,"t":1789430400000},{"price":1.0246551627345495,"t":1789516800000},{"price":1.0454564995732214,"t":1789603200000},{"price":1.0598137186964758,"t":1789689600000},{"price":1.0798905388167022,"t":1789776000000},{"price":1.1199029674363394,"t":1789948800000},{"price":1.122606538066355,"t":1790035200000},{"price":1.1034400539015896,"t":1790121600000},{"price":1.0872091750457484,"t":1790208000000},{"price":1.0526114272836928,"t":1790553600000},{"price":1.0593528467094275,"t":1790640000000},{"price":1.0602828693213746,"t":1790726400000},{"price":1.0700726505741742,"t":1790899200000},{"price":1.0895146390355568,"t":1791158400000},{"price":1.065875548123768,"t":1791331200000},{"price":1.0583654201037989,"t":1791417600000}],"btc":{"377":78430.0,"378":83760.0,"379":85179.24,"380":93749.3,"381":94277.62,"382":104118.0,"383":106454.26,"384":109004.19,"385":105642.93,"386":105734.0,"387":105594.01,"388":100963.87,"389":108356.93,"390":109203.84,"391":119086.64,"392":117265.12,"393":119415.55,"394":114208.8,"395":119294.01,"396":117405.01,"397":113493.59,"398":108246.35,"399":111137.34,"400":115268.01,"401":115232.29,"402":112163.95,"403":123482.31,"404":114958.8,"405":108642.78,"406":114559.4,"407":110540.68,"408":104722.96,"409":94261.44,"410":86830.0,"411":90360.0,"412":90395.31,"413":88172.17,"414":88658.86,"415":87952.71,"416":91529.73,"417":91013.65,"418":93673.14,"419":86670.36,"420":76968.21,"421":70330.38,"422":68832.58,"423":67643.4,"424":65776.47,"425":65971.2,"426":72815.24,"427":67859.0,"428":66010.93,"429":69034.18,"430":70740.98,"431":73801.79,"432":78657.55,"433":78568.57,"434":82210.07,"435":77457.67,"436":77064.96,"437":73674.39,"438":63332.01,"439":65746.45,"440":63311.99,"441":59577.01,"442":63650.0,"443":63780.0,"444":64722.54,"445":65399.99,"446":63570.0,"447":64901.59,"448":62900.0,"449":77734.0,"450":77682.0,"451":80341.83,"452":76842.01,"453":81178.0,"454":84472.0,"455":86530.0,"456":81565.66}};
    function initPortfolioPanel() {
        const pd = window.PORTFOLIO_DATA;
        const bd = window.BACKTEST_DATA;

        // ── Interactive single donut ─────────────────────────────────────────
        const dc = document.getElementById('portfolioDonut');
        if (dc) {
            const dpr = window.devicePixelRatio || 1;
            const LOGICAL = 440;
            dc.width  = LOGICAL * dpr;
            dc.height = LOGICAL * dpr;
            const ctx = dc.getContext('2d');
            ctx.scale(dpr, dpr);

            const coinImg = new Image();
            coinImg.src = '/static/images/alef-coin.png';

            const LOGO_URLS = {
                BTC: '/static/images/logos/btc.png',
                BNB: '/static/images/logos/bnb.png',
                TRX: '/static/images/logos/trx.png',
                Ethereum: '/static/images/logos/eth.png',
            };
            const logoImages = {};
            Object.entries(LOGO_URLS).forEach(([lbl, url]) => {
                const img = new Image();
                img.onload  = () => { logoImages[lbl] = img; draw(); };
                img.onerror = () => draw();
                img.src = url;
            });

            const W = LOGICAL, H = LOGICAL;
            const cx = W / 2, cy = H / 2;
            const BG = '#080808';
            const GOLD = '#D4AF37';
            const outerR = 162, innerR = 138;   // thin elegant ring
            const BADGE_DIST = outerR + 38;      // badge centre distance from canvas centre
            const BADGE_R    = 19;               // badge circle radius
            const groupGap = 0.065;
            const segGap   = 0.020;
            const groupArc = (2 * Math.PI) / 3;

            const GROUPS = [
                { name: 'Crypto', color: '#E08020' },
                { name: 'AI',     color: '#2E8BD8' },
                { name: 'Metals', color: '#C9A227' },
            ];

            const segments = [];
            GROUPS.forEach((g, gi) => {
                const items = pd.allocations.filter(a => a.group === g.name);
                const groupTotal = items.reduce((s, a) => s + a.pct, 0);
                const usable = groupArc - groupGap - (items.length - 1) * segGap;
                const groupStart = -Math.PI / 2 + gi * groupArc;
                let angle = groupStart + groupGap / 2;
                items.forEach((item, ii) => {
                    const sweep = (item.pct / groupTotal) * usable;
                    segments.push({
                        label: item.label, pct: item.pct,
                        color: item.color, group: g.name,
                        startAngle: angle, endAngle: angle + sweep,
                        midAngle: angle + sweep / 2,
                    });
                    angle += sweep + (ii < items.length - 1 ? segGap : 0);
                });
            });

            let hoveredIdx = -1;

            const BADGE_EMOJI = { QQQ:'📈', Mag7:'🤖', Gold:'🥇', Silver:'🥈', Platinum:'💎' };

            // Pre-render emojis via SVG so iOS canvas renders them as images (bypasses iOS canvas emoji bug)
            const BADGE_EMOJI_IMGS = {};
            function makeEmojiImg(emoji, size) {
                const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}"><text y="${size * 0.82}" x="${size * 0.5}" font-size="${size * 0.82}" text-anchor="middle">${emoji}</text></svg>`;
                const img = new Image();
                img.onload = () => draw();
                img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
                return img;
            }
            Object.entries(BADGE_EMOJI).forEach(([lbl, emoji]) => {
                BADGE_EMOJI_IMGS[lbl] = makeEmojiImg(emoji, 64);
            });

            function drawBadge(label, midAngle, hov, fadeOut) {
                const dist = hov ? BADGE_DIST + 9 : BADGE_DIST;
                const bx = cx + Math.cos(midAngle) * dist;
                const by = cy + Math.sin(midAngle) * dist;
                const r  = hov ? BADGE_R + 3 : BADGE_R;

                ctx.save();
                ctx.globalAlpha = fadeOut ? 0.22 : 1;

                // Dark circle background
                const grad = ctx.createRadialGradient(bx, by - r * 0.25, r * 0.05, bx, by, r);
                grad.addColorStop(0, '#1c1400');
                grad.addColorStop(1, '#080808');
                ctx.beginPath();
                ctx.arc(bx, by, r, 0, 2 * Math.PI);
                ctx.fillStyle = grad;
                ctx.fill();

                // Thin gold ring
                ctx.beginPath();
                ctx.arc(bx, by, r, 0, 2 * Math.PI);
                ctx.strokeStyle = hov ? 'rgba(212,175,55,0.8)' : 'rgba(212,175,55,0.35)';
                ctx.lineWidth = hov ? 1.8 : 1.1;
                ctx.stroke();

                const img = logoImages[label];
                if (img) {
                    // Clip logo inside circle
                    ctx.save();
                    ctx.beginPath();
                    ctx.arc(bx, by, r - 2, 0, 2 * Math.PI);
                    ctx.clip();
                    ctx.imageSmoothingEnabled = true;
                    ctx.imageSmoothingQuality = 'high';
                    ctx.drawImage(img, bx - (r - 2), by - (r - 2), (r - 2) * 2, (r - 2) * 2);
                    ctx.restore();
                } else {
                    const emojiImg = BADGE_EMOJI_IMGS[label];
                    if (emojiImg && emojiImg.complete && emojiImg.naturalWidth) {
                        const d = (r - 2) * 2;
                        ctx.drawImage(emojiImg, bx - (r - 2), by - (r - 2), d, d);
                    }
                }
                ctx.restore();
            }

            function draw() {
                ctx.clearRect(0, 0, W, H);
                ctx.fillStyle = BG;
                ctx.fillRect(0, 0, W, H);

                // Draw ring segments
                segments.forEach((seg, i) => {
                    const hov = i === hoveredIdx;
                    const oR  = hov ? outerR + 9 : outerR;
                    const fadeOut = hoveredIdx >= 0 && !hov;
                    const alpha = fadeOut ? 0.28 : 0.95;

                    // Segment glow
                    ctx.shadowColor = seg.color;
                    ctx.shadowBlur  = hov ? 22 : (hoveredIdx < 0 ? 6 : 0);

                    ctx.beginPath();
                    ctx.arc(cx, cy, oR, seg.startAngle, seg.endAngle);
                    ctx.arc(cx, cy, innerR, seg.endAngle, seg.startAngle, true);
                    ctx.closePath();
                    ctx.globalAlpha = alpha;
                    ctx.fillStyle = seg.color;
                    ctx.fill();
                    ctx.globalAlpha = 1;
                    ctx.shadowBlur  = 0;
                    ctx.shadowColor = 'transparent';

                    // Thin gold inner edge highlight
                    ctx.beginPath();
                    ctx.arc(cx, cy, innerR + 1, seg.startAngle, seg.endAngle);
                    ctx.strokeStyle = `rgba(212,175,55,${fadeOut ? 0.08 : 0.22})`;
                    ctx.lineWidth = 1;
                    ctx.stroke();
                });

                // Badge icons outside ring
                segments.forEach((seg, i) => {
                    drawBadge(seg.label, seg.midAngle, i === hoveredIdx, hoveredIdx >= 0 && i !== hoveredIdx);
                });

                // Center — coin or hover info
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                if (hoveredIdx >= 0) {
                    const seg = segments[hoveredIdx];
                    ctx.shadowColor = seg.color;
                    ctx.shadowBlur  = 24;
                    ctx.font = '700 22px Inter,sans-serif';
                    ctx.fillStyle = '#fff';
                    ctx.fillText(seg.label, cx, cy - 14);
                    ctx.shadowBlur = 0;
                    ctx.shadowColor = 'transparent';
                    ctx.font = '600 16px Inter,sans-serif';
                    ctx.fillStyle = GOLD;
                    ctx.fillText(seg.pct.toFixed(1) + '%', cx, cy + 12);
                    ctx.font = '400 10px Inter,sans-serif';
                    ctx.fillStyle = 'rgba(212,175,55,0.5)';
                    ctx.fillText(seg.group.toUpperCase(), cx, cy + 30);
                } else {
                    if (coinImg.complete && coinImg.naturalWidth > 0) {
                        const iSize = 110;
                        ctx.imageSmoothingEnabled = true;
                        ctx.imageSmoothingQuality = 'high';
                        ctx.shadowColor = 'rgba(212,175,55,0.55)';
                        ctx.shadowBlur  = 30;
                        ctx.drawImage(coinImg, cx - iSize / 2, cy - iSize / 2, iSize, iSize);
                        ctx.shadowBlur  = 0;
                        ctx.shadowColor = 'transparent';
                    }
                }
            }

            coinImg.onload = draw;
            draw();

            dc.addEventListener('mousemove', e => {
                const rect = dc.getBoundingClientRect();
                const px = (e.clientX - rect.left) * (W / rect.width)  - cx;
                const py = (e.clientY - rect.top)  * (H / rect.height) - cy;
                const dist = Math.sqrt(px * px + py * py);

                if (dist < innerR - 5 || dist > outerR + 14) {
                    if (hoveredIdx !== -1) { hoveredIdx = -1; draw(); }
                    return;
                }

                let ang = Math.atan2(py, px);
                if (ang < -Math.PI / 2) ang += 2 * Math.PI;

                let found = -1;
                segments.forEach((seg, i) => {
                    if (ang >= seg.startAngle && ang <= seg.endAngle) found = i;
                });

                if (found !== hoveredIdx) { hoveredIdx = found; draw(); }
            });

            dc.addEventListener('mouseleave', () => { hoveredIdx = -1; draw(); });
        }

        // ── Metrics box ───────────────────────────────────────────────────
        const lev = document.getElementById('pmLev');
        // pmLev set by fetchAlefMetrics
        const lines = document.getElementById('pmAllocLines');
        if (lines) {
            lines.innerHTML =
                `<div style="display:flex;gap:2rem;">` +
                  `<div style="white-space:nowrap;">` +
                    `<div style="opacity:.55;font-size:.72rem;letter-spacing:.1em;">LIQUIDITY</div>` +
                    `<div><b id="pmLiq" style="color:#D4AF37">Loading…</b></div>` +
                  `</div>` +
                  `<div style="white-space:nowrap;">` +
                    `<div style="opacity:.55;font-size:.72rem;letter-spacing:.1em;">FEES <span style="cursor:help;font-size:.85em;" title="Management fee only — does not include interest on margin, trading fees, or slippage.">ⓘ</span></div>` +
                    `<div><b style="color:#D4AF37">0.5% P.Y.</b></div>` +
                  `</div>` +
                `</div>`;
        }

        // ── Backtest line chart ───────────────────────────────────────────
        const bc = document.getElementById('portfolioBacktest');
        if (!bc || typeof Chart === 'undefined') return;

        // Each series carries dates. Daily observations occupy days, not weekly slots.
        const DAY = 86400000;
        const WEEK = 7 * DAY;
        const BASE_MS = Date.UTC(2018, 0, 5);
        const seed = window.ALEF_CHART_SEED;
        const firstActual = seed.pts[0];
        const LOAN_WEEKLY_DRAG = 0.20 * 0.05 / 52;
        const drag = (i) => Math.pow(1 - LOAN_WEEKLY_DRAG, i);
        // One fixed anchor for the full history, independent of live price or date filters.
        const portScale = firstActual.price / (bd.portfolio.at(-1) * drag(bd.portfolio.length - 1));
        const portfolioPoints = bd.portfolio.map((v, i) => ({x: BASE_MS + i * WEEK, y: v * drag(i) * portScale}));
        // Shared endpoint makes the dashed-to-solid transition exact; no synthetic weekly returns.
        portfolioPoints.push({x: firstActual.t, y: firstActual.price, transition: true});
        const btcStart = portfolioPoints[0].y;
        const btcPoints = bd.btc.map((v, i) => ({x: BASE_MS + i * WEEK, y: v / bd.btc[0] * btcStart}));
        const BTC_REFERENCE_IDX = 400;
        const btcUsdScale = btcPoints[BTC_REFERENCE_IDX].y / seed.btc[BTC_REFERENCE_IDX];
        window.ALEF_ACTUAL_PTS = seed.pts.slice();
        let recentBtc = seed.btc;
        let liveBtc = null;
        let liveAlef = null;
        const fromEl = document.getElementById('btFrom');
        const toEl = document.getElementById('btTo');
        const utcYM = (t) => new Date(t).toISOString().slice(0, 7);
        fromEl.max = toEl.max = utcYM(Date.now());
        toEl.value = utcYM(Date.now());

        function actualPoints() {
            const days = new Map();
            const sorted = window.ALEF_ACTUAL_PTS.filter(p => Number.isFinite(p.t) && Number.isFinite(p.price) && p.price > 0)
                .sort((a,b) => a.t - b.t);
            for (const p of sorted) if (p.t >= firstActual.t && p.t <= Date.now()) days.set(Math.floor(p.t / DAY), {x:p.t,y:p.price});
            const points = [...days.values()];
            // Preserve the launch anchor even when daily NAV samples arrive later that day.
            if (!points.length || points[0].x !== firstActual.t) points.unshift({x:firstActual.t,y:firstActual.price});
            if (liveAlef) points.push({x:Date.now(),y:liveAlef});
            return points;
        }
        function bitcoinPoints() {
            const points = new Map(btcPoints.map(p => [p.x,p]));
            for (const [idx, price] of Object.entries(recentBtc)) {
                const i = Number(idx), p = Number(price);
                if (i >= BTC_REFERENCE_IDX && Number.isFinite(p) && p > 0) {
                    const x = Math.min(BASE_MS + i * WEEK, Date.now());
                    points.set(x, {x,y:p * btcUsdScale});
                }
            }
            const arr = [...points.values()].filter(p => p.x <= Date.now()).sort((a,b) => a.x-b.x);
            const lastPrice = liveBtc || Number(Object.entries(recentBtc).sort((a,b)=>Number(a[0])-Number(b[0])).at(-1)?.[1]);
            if (lastPrice > 0) arr.push({x:Date.now(),y:lastPrice * btcUsdScale});
            return arr;
        }
        function range() {
            const [fy,fm] = fromEl.value.split('-').map(Number);
            const [ty,tm] = toEl.value.split('-').map(Number);
            return {min:Date.UTC(fy,fm-1,1),max:Math.min(Date.now(),Date.UTC(ty,tm,1)-1)};
        }
        function sliceData() {
            const r = range();
            const clip = points => {
                if (!points.length || points[0].x > r.max || points.at(-1).x < r.min) return [];
                // Include adjacent observations for correct intersections with the viewport edges.
                let start = points.findIndex(p=>p.x>=r.min);
                if (start < 0) return [];
                start = Math.max(0,start-1);
                let end = points.findIndex(p=>p.x>r.max);
                if (end < 0) end = points.length-1;
                return points.slice(start,end+1);
            };
            return {portfolio:clip(portfolioPoints),btc:clip(bitcoinPoints()),actual:clip(actualPoints()),...r};
        }
        const initial = sliceData();
        const formatDate = t => new Date(t).toLocaleDateString('en-US',{year:'numeric',month:'short',day:'numeric',timeZone:'UTC'});
        const dataset = (label,data,color,dash,width) => ({label,data,borderColor:color,backgroundColor:'transparent',borderWidth:width,
            pointRadius:0,pointHitRadius:8,tension:0,fill:false,spanGaps:false,borderDash:dash});
        const btChart = new Chart(bc, {
            type:'line',
            plugins:[],
            data:{datasets:[
                dataset('Alef Portfolio (backtest)',initial.portfolio,'#1B6FBF',[6,4],2),
                dataset('BTC',initial.btc,'#E8941A',[6,4],1.5),
                {...dataset('ALEF (actual)',initial.actual,'#1B6FBF',[],1.5), tension:0.35, cubicInterpolationMode:'monotone'}
            ]},
            options:{responsive:true,animation:false,parsing:false,
                interaction:{mode:'nearest',intersect:false},
                plugins:{
                    title:{display:true,text:'Alef Portfolio vs Bitcoin — backtest since 2018 (Alef holds crypto, tech & metals)',font:{size:13}},
                    legend:{position:'top',labels:{font:{size:11},boxWidth:24}},
                    tooltip:{callbacks:{title:items=>items.length?formatDate(items[0].parsed.x):'',
                        label:ctx=>`${ctx.dataset.label}: $${ctx.parsed.y.toFixed(4)}${ctx.raw.transition?' (transition to actual)':''}`}}
                },
                scales:{
                    x:{type:'linear',min:initial.min,max:initial.max,afterBuildTicks:scale=>{
                        const first=new Date(scale.min),last=new Date(scale.max);
                        const months=(last.getUTCFullYear()-first.getUTCFullYear())*12+last.getUTCMonth()-first.getUTCMonth();
                        const step=months>60?24:months>24?6:months>12?3:1;
                        let month=first.getUTCFullYear()*12+first.getUTCMonth();
                        const ticks=[];
                        for (;month<=last.getUTCFullYear()*12+last.getUTCMonth();month+=step) {
                            const value=Date.UTC(Math.floor(month/12),month%12,1);
                            if(value>=scale.min) ticks.push({value});
                        }
                        if(months>12 && (!ticks.length || scale.max-ticks.at(-1).value>90*DAY)) {
                            if(ticks.length && scale.max-ticks.at(-1).value < step*15*DAY) ticks.pop();
                            ticks.push({value:scale.max});
                        }
                        scale.ticks=ticks;
                    },ticks:{maxTicksLimit:7,callback:v=>new Date(v).toLocaleDateString('en-US',{month:'short',year:'2-digit',timeZone:'UTC'})},grid:{display:false}},
                    y:{title:{display:true,text:'ALEF price (USD) / BTC scaled comparison',font:{size:10}},grid:{color:'rgba(0,0,0,0.06)'}}
                }
            }
        });
        function updateBtChart() {
            const s = sliceData();
            if (!Number.isFinite(s.min) || !Number.isFinite(s.max) || s.max <= s.min) return;
            btChart.data.datasets[0].data=s.portfolio;
            btChart.data.datasets[1].data=s.btc;
            btChart.data.datasets[2].data=s.actual;
            btChart.options.scales.x.min=s.min;
            btChart.options.scales.x.max=s.max;
            btChart.update('none');
        }
        fromEl.addEventListener('change',updateBtChart);
        toEl.addEventListener('change',updateBtChart);
        async function getJSON(url) {
            const r = await fetch(url,{signal:AbortSignal.timeout(15000)});
            if (!r.ok) throw new Error(`Price feed ${r.status}`);
            return r.json();
        }
        async function refreshActual() {
            try {
                const d = await getJSON('/api/alef-price-history');
                if (d.pts?.length) {window.ALEF_ACTUAL_PTS = seed.pts.concat(d.pts);updateBtChart();}
            } catch(e) {console.warn('ALEF history refresh unavailable; showing saved observations.');}
        }
        async function refreshPrices() {
            const mint='FBHd9upXFkeWSwe9qEdcgRLa4Y6uzsLCSawrpfPkQZGg';
            const results = await Promise.allSettled([
                getJSON(`https://api-v3.raydium.io/mint/price?mints=${mint}`),
                getJSON('/api/btc-weekly'),
                getJSON('https://data-api.binance.vision/api/v3/ticker/price?symbol=BTCUSDT')
            ]);
            const [alef,btc,currentBtc]=results;
            const price=alef.status==='fulfilled'?Number(alef.value.data?.[mint]):0;
            if (price>0) {liveAlef=price;window.ALEF_LIVE_PRICE=price;}
            if (btc.status==='fulfilled' && btc.value.prices) recentBtc=btc.value.prices;
            if (currentBtc.status==='fulfilled' && Number(currentBtc.value.price)>0) liveBtc=Number(currentBtc.value.price);
            const el=document.getElementById('btAlefPrice');
            if (el) el.textContent='Market price: $'+(liveAlef || actualPoints().at(-1).y).toFixed(4)+' / ALEF';
            updateBtChart();
        }
        const priceEl=document.getElementById('btAlefPrice');
        if (priceEl) priceEl.textContent='Market price: $'+seed.pts.at(-1).price.toFixed(4)+' / ALEF';
        refreshActual();
        refreshPrices();
        setInterval(refreshPrices,60000);
        setInterval(refreshActual,20*60000);

    }

    async function fetchAlefMetrics() {
        try {
            const r = await fetch('https://alef.money/api/alef-nav-metrics');
            if (r.ok) {
                const d = await r.json();
                const lev = document.getElementById('pmLev');
                const liq = document.getElementById('pmLiq');
                if (lev && d.leverage != null) lev.textContent = d.leverage.toFixed(3) + '×';
                if (liq && d.liquidity_pct != null) liq.textContent = Math.round(d.liquidity_pct) + '%';
            }
        } catch(e) {}
        setTimeout(fetchAlefMetrics, 15 * 60 * 1000);
    }

Reserve Addresses

₿
Bitcoin — Multisig
bc1qmqcggscd9mfddzywukrxksrrfamx5mevr5jr40llmf6ggtdmwyeqcaekt4
mempool.space ↗
BNB
Ethereum & BNB Chain
0xfB6b384a64BA407Ee964DF70bf48A6Ef993B1Fd4
Etherscan ↗ BscScan ↗
Solana
9JRZdE4rcSUQRDRUTqNrqsFtxm7caT4GfyiNxFJqBHUe
Solscan ↗
Solana — Squads Multisig Vault
9W22wgpcSsbcAjoGvGQfcvVUns5q7LMuWNPCnM4eVXse
Solscan ↗
Tron
TFMDSKrH2FJx3pdGACb5oHoKPJRzaH8dKv
Tronscan ↗
TON
EQDJ8vy2R0EdEskou7Awf8PX2GXU9j0dLAPrJlNHRrJdlsXy
Tonscan ↗
Raydium
Raydium Liquidity Pool (ALEF)
Pool Liquidity (USD)
Loading...
Pool
USDC/ALEF
24h Volume
Loading...

Request a Proof of Ownership

We will keep any amount sent below the equivalent of 0.1 g of gold without verification. Amounts at or above 0.1 g of gold will receive a verification but will not be returned. To prevent spam, we require the equivalent of 0.1 g of gold to be sent to the reserve address you want verified. We will return the minimum amount the network allows; the remainder is a tip. Prices may increase with demand.

Compare ALEF

See how ALEF compares to other investment products.

⚡ DCIDynamic Composite Index Ondo OndoTokenized RWA 💎 WealtiiOn-chain multi-asset 🔗 Reserve ProtocolRToken & DTF 📊 Crypto Index FundsDPI · BITW · GDLC 📈 Traditional ETFsAOR · Vanguard · RLY 🏛️ Regulated FundsUCITS · SICAV

About the Creator

Betancourt coat of arms

Alef Financial is founded by Juan Correa, who publishes under the pen name J.ℵ. Bettencourt — philosopher (Oxford 2016), scientist (Bocconi 2021), author of How to Make the Most Money, and heir to a 600-year-old legal and financial tradition. Contact details available below.

Contact

Write your message. Sending costs 0.1 g of gold in crypto — returned if genuine, kept if spam.

? FAQ 📖 Learn

ALEF Admin

MULTISIG GOVERNANCE

Connect Wallet

Not connected — choose a wallet above

Proof of Reserves Requests

Loading…

Token Overview

—
—
—
—
Loading…
—

Current Admins

Mint Tokens

Burn Tokens

Freeze / Thaw Account

Add Admin

Remove Admin

Emergency Controls

Pause halts all minting and transfers. Requires admin majority.

Pending Proposals — click to approve

Connect wallet to load proposals