#!/usr/bin/env python3 """Action + snapshot harness for the local lez-programs M1 run. Every action is a spel invocation; after it, a snapshot of the pool, vaults, TWAP state, protocol-fee holdings and user balances is appended to run/log.jsonl together with the action's outcome, so the report can show exactly how each step moved the state. """ import json, os, subprocess, sys, time, urllib.request M = "/home/vpavlin/devel/m1-local" LP = f"{M}/lez-programs" LOG = f"{M}/run/log.jsonl" ENV = dict(os.environ) ENV.update({ "LEE_WALLET_HOME_DIR": f"{M}/run/wallet", "NSSA_WALLET_HOME_DIR": f"{M}/run/wallet", "RISC0_DEV_MODE": "1", "PATH": f"{M}/lez/target/release:{M}/spel/target/release:" + os.environ["PATH"], }) def ids(): out = {} for line in open(f"{M}/run/ids.env"): line = line.strip() if "=" in line: k, v = line.split("=", 1) out[k] = v return out I = ids() def reload_ids(): global I I = ids() def rpc(method, params=None): req = urllib.request.Request( "http://127.0.0.1:3040", data=json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params or []}).encode(), headers={"Content-Type": "application/json"}) return json.load(urllib.request.urlopen(req, timeout=10)).get("result") def inspect(idl, account, typ): r = subprocess.run(["spel", "--idl", f"{LP}/artifacts/{idl}-idl.json", "inspect", account, "--type", typ], capture_output=True, text=True, env=ENV) t = r.stdout if "{" not in t: return None try: return json.loads(t[t.index("{"):]) except Exception: return {"raw": t[-300:]} def holding(account): j = inspect("token", account, "TokenHolding") if not j: return None f = j.get("Fungible") return int(f["balance"]) if f else j def wait_next_block(timeout=60): """spel reports 'confirmed' before the RPC serves the post-state, so wait for one further block before reading accounts.""" start = rpc("getLastBlockId") deadline = time.time() + timeout while time.time() < deadline: if rpc("getLastBlockId") > start: return time.sleep(1) def snapshot(extra_holdings=(), settle=True): if settle: wait_next_block() s = {"block": rpc("getLastBlockId")} p = inspect("amm", I["POOL"], "PoolDefinition") or {} s["pool"] = {k: p.get(k) for k in ("reserve_a", "reserve_b", "liquidity_pool_supply")} s["vault_a"] = holding(I["VAULT_A"]) s["vault_b"] = holding(I["VAULT_B"]) t = inspect("twap_oracle", I["TICK"], "CurrentTickAccount") or {} s["tick"] = t o = inspect("twap_oracle", I["OBS"], "PriceObservations") or {} entries = o.get("entries", []) wi = o.get("write_index", 0) n = int(o.get("total_entries", 0) or 0) # last (up to) 3 written entries, newest last recent = [] for k in range(min(n, 3), 0, -1): recent.append(entries[(wi - k) % len(entries)] if entries else None) s["obs"] = {"total_entries": n, "write_index": wi, "last_recorded_tick": o.get("last_recorded_tick"), "recent": recent} s["price"] = inspect("twap_oracle", I["PRICE"], "OraclePriceAccount") s["pfee_a"] = holding(I["PFEE_A"]) s["pfee_b"] = holding(I["PFEE_B"]) for name in ("HOLD_A", "HOLD_B", "LP_HOLD") + tuple(extra_holdings): if name in I: s[name] = holding(I[name]) return s def spel_tx(idl, prog, instr, **args): cmd = ["spel", "--idl", f"{LP}/artifacts/{idl}-idl.json", "--program", f"{LP}/target/guest/{prog}.bin", "--", instr] for k, v in args.items(): cmd += [f"--{k.replace('_', '-')}", str(v)] r = subprocess.run(cmd, capture_output=True, text=True, env=ENV, input="test\n") out = r.stdout + r.stderr ok = "Transaction confirmed" in out tx = None for line in out.splitlines(): if "tx_hash:" in line: tx = line.split("tx_hash:")[1].strip() err = None if not ok: tail = [l for l in out.splitlines() if l.strip()][-6:] err = " | ".join(tail)[-600:] return {"ok": ok, "tx": tx, "err": err, "rc": r.returncode} def act(label, idl, prog, instr, note="", snap=True, extra_holdings=(), **args): t0 = time.time() res = spel_tx(idl, prog, instr, **args) rec = {"t": round(t0, 1), "label": label, "instr": instr, "args": args, "note": note, **res} if snap: rec["after"] = snapshot(extra_holdings) with open(LOG, "a") as f: f.write(json.dumps(rec) + "\n") short = {k: rec[k] for k in ("label", "ok", "tx", "err")} print(json.dumps(short)) if snap: a = rec["after"] print(" pool", a["pool"], "tick", a["tick"].get("tick") if a["tick"] else None, "obs#", a["obs"]["total_entries"], "lastrec", a["obs"]["last_recorded_tick"], "price", (a["price"] or {}).get("price")) return rec def log_note(label, data): with open(LOG, "a") as f: f.write(json.dumps({"t": round(time.time(), 1), "label": label, "note": data}) + "\n") if __name__ == "__main__": print(json.dumps(snapshot(), indent=1))