#!/usr/bin/env python3
# Watch the distributor $LEDGER reserve after the Bob re-up request.
# Exits (re-invoking Aura): TOP-UP landed (0), CRITICAL floor breached (2), TIMEOUT (3).
import time, pathlib, sys
from web3 import Web3
CA   = "0xD1F2586790a5bD6DA1e443441df53aF6EC213D83"
DIST = "0x58f8703C7051283811807BdB4d169C349Fa39FCe"
SPOT = 0.000231
CRIT = 870000   # ~$200 — buyers about to stall
LOGP = "/tmp/claude-1000/-home-paul-Aura/a2239ea0-e18d-4178-9864-2c3f48478801/scratchpad/reserve_watch.log"
w3 = Web3(Web3.HTTPProvider(pathlib.Path.home().joinpath('.eth_rpc').read_text().strip()))
erc = w3.eth.contract(address=Web3.to_checksum_address(CA), abi=[
    {"name":"balanceOf","type":"function","stateMutability":"view",
     "inputs":[{"name":"a","type":"address"}],"outputs":[{"name":"","type":"uint256"}]}])

def bal():
    # resilient: retry transient RPC/DNS errors rather than crash the watch
    last = None
    for _ in range(5):
        try:
            return erc.functions.balanceOf(Web3.to_checksum_address(DIST)).call()/1e18
        except Exception as e:
            last = e; time.sleep(5)
    raise last
def log(m):
    with open(LOGP,"a") as f: f.write(f"{time.strftime('%H:%M:%S')} {m}\n")

base = bal()
log(f"RESERVE WATCH START — {base:,.0f} $LEDGER (~${base*SPOT:,.0f})")
deadline = time.time() + 4*3600
while time.time() < deadline:
    time.sleep(90)
    try:
        cur = bal()
    except Exception:
        continue
    if cur >= base + 1_000_000:
        log(f"TOP-UP landed — reserve now {cur:,.0f} $LEDGER (~${cur*SPOT:,.0f}); +{cur-base:,.0f} from Bob")
        sys.exit(0)
    if cur < CRIT:
        log(f"CRITICAL — reserve {cur:,.0f} $LEDGER (~${cur*SPOT:,.0f}) below floor; paid buyers about to stall")
        sys.exit(2)
log(f"TIMEOUT — reserve {bal():,.0f} $LEDGER, no top-up in 4h")
sys.exit(3)
