#!/usr/bin/env python3
"""Ethereum wallet monitor via public JSON-RPC endpoints (no API keys).
Single shot or loop. Adapt ADDRESSES per incident; full checksummed addresses only.
Usage: python3 eth_wallet_monitor.py [--loop SECONDS]
"""
import json, time, sys, os
from decimal import Decimal
import urllib.request

ADDRESSES = {
    # "label": "0xfull_address",
}

RPC_URLS = [
    "https://ethereum-rpc.publicnode.com",
    "https://eth.llamarpc.com",
    "https://rpc.ankr.com/eth",
]

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "wallet_monitor_log.json")
HEADERS = {"Content-Type": "application/json",
           "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) wallet-monitor/1.0"}

def rpc(method, params):
    last_err = None
    for url in RPC_URLS:
        try:
            req = urllib.request.Request(url, data=json.dumps(
                {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
            ).encode(), headers=HEADERS)
            with urllib.request.urlopen(req, timeout=20) as r:
                out = json.loads(r.read())
                if "result" in out:
                    return out["result"]
        except Exception as e:
            last_err = e
    raise RuntimeError(f"All RPCs failed: {last_err}")

def wei_to_eth(w):
    return str(Decimal(int(w, 16)) / Decimal(10**18))

def snapshot():
    snap = {"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "nonces": {}, "balances_eth": {}}
    for name, addr in ADDRESSES.items():
        snap["nonces"][name] = int(rpc("eth_getTransactionCount", [addr, "latest"]), 16)
        snap["balances_eth"][name] = wei_to_eth(rpc("eth_getBalance", [addr, "latest"]))
    return snap

def main():
    loop = int(sys.argv[sys.argv.index("--loop") + 1]) if "--loop" in sys.argv else None
    log = []
    if os.path.exists(OUT):
        with open(OUT) as f:
            log = json.load(f)
    prev = log[-1] if log and "error" not in log[-1] else None
    while True:
        try:
            snap = snapshot()
        except Exception as e:
            print("RPC error:", e)  # keep prev, never overwrite last-good
            snap = {"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "error": str(e)}
        if prev and "nonces" in snap and "nonces" in (prev or {}):
            for name in ADDRESSES:
                if snap["nonces"].get(name) != prev["nonces"].get(name):
                    msg = f"MOVEMENT: {name} nonce {prev['nonces'].get(name)} -> {snap['nonces'].get(name)}"
                    print("!!", msg)
                    snap.setdefault("alerts", []).append(msg)
        if "error" not in snap:
            prev = snap
        log.append(snap)
        with open(OUT, "w") as f:
            json.dump(log[-500:], f, indent=1)
        print(json.dumps(snap, indent=1))
        if not loop:
            break
        time.sleep(loop)

if __name__ == "__main__":
    main()
