#!/usr/bin/env python3 """Enroll a wallet on the FLOP gateway API (api.flop.network) and run a minimal inference spend to prove the path works. Usage: python3 enroll_devnet.py [--label ] The wallet label selects which wallet in the encrypted store to enroll with; the address is read from that wallet entry (never hardcoded). Default label flop-devnet-test-01. NOTE: api.flop.network currently serves DEVNET (its /health reports network devnet, the challenge says 'devnet gateway key', devnet genesis). This spends DEVNET FLOP only, not the testnet 10 FLOP, and does not count toward the testnet airdrop. The testnet gateway (gateway.testnet.flop.network) is still dead. This is a mechanism test only. Flow: GET challenge -> sign exact message bytes with test-01 Ed25519 key -> POST {address, message, signature} to /v1/enroll/wallet -> use the returned API key for one tiny /v1/chat/completions call (max_tokens 5). Never prints the mnemonic, private key, or the full API key. """ import argparse import json import os import subprocess import sys import time import urllib.request sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) ENC = os.path.expanduser("~/workspace/flop-wallet/test-wallets/wallets.json.enc") PW = os.path.expanduser("~/workspace/flop-wallet/vault/wallet-password.txt") API = "https://api.flop.network" KEYFILE = os.path.expanduser( "~/workspace/goals/flop-labs-testnet-agent-setup/hidden_files/devnet-api-key.txt") def decrypt_wallets(store=ENC, pw=PW): out = subprocess.run( ["openssl", "enc", "-d", "-aes-256-cbc", "-iter", "200000", "-in", store, "-pass", f"file:{pw}"], capture_output=True, check=True) return json.loads(out.stdout.decode()) def http_json(method, url, payload=None, headers=None): data = json.dumps(payload).encode() if payload is not None else None req = urllib.request.Request(url, data=data, method=method) req.add_header("Content-Type", "application/json") req.add_header("User-Agent", "Mozilla/5.0") for k, v in (headers or {}).items(): req.add_header(k, v) try: with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.loads(r.read().decode()) except urllib.error.HTTPError as e: try: body = json.loads(e.read().decode()) except Exception: body = {"raw": "unparsable"} return e.code, body def main(): global ADDRESS ap = argparse.ArgumentParser(description="Enroll a wallet on the devnet gateway API") ap.add_argument("--label", default="flop-devnet-test-01", help="wallet label in the encrypted store") ap.add_argument("--store", default=ENC) ap.add_argument("--pw", default=PW) args = ap.parse_args() from substrateinterface import Keypair, KeypairType from nacl.signing import SigningKey wallets = decrypt_wallets(args.store, args.pw) w = next(x for x in wallets if x["label"] == args.label) ADDRESS = w["address"] kp = Keypair.create_from_mnemonic( w["mnemonic"], ss58_format=42, crypto_type=KeypairType.ED25519) assert kp.ss58_address == ADDRESS, "derived address mismatch" print("keypair ok:", ADDRESS) # 1. Fresh challenge (5-min expiry). status, ch = http_json( "GET", f"{API}/v1/enroll/wallet/challenge?address={ADDRESS}") print("challenge status:", status) if status != 200: print("challenge failed:", ch) return 1 message = ch["message"] print("challenge message first line:", message.splitlines()[0]) print("challenge expires_at:", ch.get("expires_at")) # 2. Sign the exact message bytes with Ed25519. sig = SigningKey(kp.private_key).sign(message.encode("utf-8")).signature sig_hex = "0x" + sig.hex() print("signed (signature kept private)") # 3. Enroll. status, res = http_json("POST", f"{API}/v1/enroll/wallet", { "address": ADDRESS, "message": message, "signature": sig_hex}) print("enroll status:", status) print("enroll response:", json.dumps(res)[:600]) if status not in (200, 201): print("enroll failed") return 1 # Find the API key in the response (field name may vary). api_key = None for k in ("api_key", "key", "token", "gateway_key"): if isinstance(res.get(k), str): api_key = res[k] break if not api_key and isinstance(res.get("data"), dict): for k in ("api_key", "key", "token", "gateway_key"): if isinstance(res["data"].get(k), str): api_key = res["data"][k] break if not api_key: print("no API key in enroll response; full keys:", list(res.keys())) return 1 with open(KEYFILE, "w") as f: f.write(api_key) os.chmod(KEYFILE, 0o600) print("api key saved (prefix):", api_key[:8] + "...") # 4. Minimal inference: tiny prompt, max_tokens 5. status, comp = http_json("POST", f"{API}/v1/chat/completions", { "model": "qwen/qwen2.5-0.5b-instruct", "messages": [{"role": "user", "content": "Say OK"}], "max_tokens": 5, }, headers={"Authorization": f"Bearer {api_key}"}) print("chat status:", status) print("chat response:", json.dumps(comp)[:1200]) return 0 if __name__ == "__main__": raise SystemExit(main())