Index of theproofnetwork/open-problems@860a535/scripts/create_markets.py
qedmarket’s copy of theproofnetwork/open-problems@860a535, 3 Dec 2026original source ↗
#!/usr/bin/env python3"""Open markets on entries of index.json, through a qedmarket site's public API. QEDMARKET_TOKEN=px_live_… python3 -I scripts/create_markets.py \ --base https://staging.qedmarket.com --commit <full sha of this repository> --due 2026-12-27 --due 2027-06-30 \ [--verifier SLUG] [--write] [--wait 900] (THEOREM | MODULE | tag:TAG | all) … - Selects the entries whose theorem or module is named, or that have the tag (`tag:erdos problems`).- Without `--write` it only prints what it would send. With it, for each entry it posts `POST /api/v1/markets` with a new challenge: this repository at `--commit`, the entry's module and theorem, its title and a description with the statement's source and licence. The creator pays the market's collateral when it opens.- A new challenge is checked by the verifier first (`202`, a pending market): with `--wait` the script waits up to that many seconds for it to open, then sets the problem's tags (`PUT /problems/{id}/tags`). A challenge that exists already (same locator) gets another market; the platform keeps one problem per challenge.- `--commit` must be a commit of https://github.com/theproofnetwork/open-problems that has the entry. Use the commit whose index.json you read: the script refuses when the local checkout is at another commit or has changes. The token is an API key with the `trade` scope of the account that should create the markets (on the platform'sown account only after deciding so). It is read from the environment, never from the command line."""import argparseimport jsonimport osimport subprocessimport sysimport timeimport urllib.errorimport urllib.requestfrom pathlib import Path ROOT = Path(__file__).resolve().parent.parentREPO_URL = "https://github.com/theproofnetwork/open-problems" def call(base, token, method, path, body=None): """One API request; a network failure (DNS, timeout, reset) is retried with a pause, never fatal at once.""" last = None for attempt in range(8): req = urllib.request.Request(f"{base}/api/v1{path}", method=method, data=None if body is None else json.dumps(body).encode(), headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json", "Accept": "application/json", "User-Agent": "open-problems-importer"}) try: with urllib.request.urlopen(req, timeout=60) as res: return res.status, json.loads(res.read() or b"null") except urllib.error.HTTPError as e: try: return e.code, json.loads(e.read() or b"null") except ValueError: return e.code, None except (urllib.error.URLError, OSError) as e: # includes timeouts and name-resolution failures last = e time.sleep(min(60, 5 * 2 ** attempt)) raise SystemExit(f"{method} {path}: the network failed 8 times in a row ({last}); run again, it picks up where it was") def description(e): src = e["source"] parts = [] if e.get("docstring"): parts.append(e["docstring"].strip()) if e.get("question") == "yes_no": parts.append("The source asks this as a yes-or-no question; so the statement may as well be false.") if src["name"] == "formal-conjectures": parts.append(f"Statement from [google-deepmind/formal-conjectures]({src['url']}) at commit " f"`{src['commit'][:12]}`, licensed {e['license']}; ported to Lean v4.34.0-rc2 / Mathlib 85e3a25 " f"in [open-problems]({REPO_URL}).") else: lemmas = src.get("openLemmas") or [] if lemmas: shown = ", ".join(f"`{n}`" for n in lemmas[:5]) more = src.get("openLemmasTotal", len(lemmas)) - min(len(lemmas), 5) parts.append(f"On Prove2Me this is already proved from lemmas that are still open: {shown}" + (f" and {more} more" if more > 0 else "") + f" (as of {src['openLemmasAt']}; see [the mission]({src['mission']})). A proof of those " "would prove it.") parts.append(f"Statement from [Prove2Me]({src['url']}) (theorem `{src['id']}`), licensed {e['license']}; " f"copied into [open-problems]({REPO_URL}).") return "\n\n".join(parts)[:20_000] def select(entries, wanted): if wanted == ["all"]: return list(entries) out = [] for e in entries: for w in wanted: if w.startswith("tag:") and w[4:] in e["tags"] or w in (e["theorem"], e["module"]): out.append(e) break return out def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--base", required=True, help="the site, e.g. https://staging.qedmarket.com") ap.add_argument("--commit", required=True, help="full commit of this repository to pin the challenges to") ap.add_argument("--due", required=True, action="append", help="due date, ISO 8601 (a date means its end in UTC); repeat it for one market per date") ap.add_argument("--verifier", help="the verifier's id or slug (default: the site's official verifier that is ready)") ap.add_argument("--write", action="store_true", help="really create the markets") ap.add_argument("--wait", type=int, default=0, help="seconds to wait for each checked challenge to open") ap.add_argument("--limit", type=int, default=20, help="at most this many markets per run (default 20)") ap.add_argument("--shard", help="I/N: only every Nth selected problem, from the Ith (0-based): run N copies side by side") ap.add_argument("select", nargs="+") a = ap.parse_args() base = a.base.rstrip("/") dues = [d if "T" in d else d + "T23:59:59Z" for d in a.due] if len(a.commit) != 40: sys.exit("--commit must be a full 40-character commit") head = subprocess.run(["git", "-C", str(ROOT), "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() dirty = subprocess.run(["git", "-C", str(ROOT), "status", "--porcelain", "index.json"], capture_output=True, text=True).stdout.strip() if head != a.commit or dirty: sys.exit(f"the checkout is at {head or '?'}{' with changes to index.json' if dirty else ''}, not {a.commit}: " "check out that commit so the index matches it") entries = select(json.loads((ROOT / "index.json").read_text())["entries"], a.select) for w in a.select: modules = {e["module"] for e in entries if e["theorem"] == w} if len(modules) > 1: sys.exit(f"{w} is in more than one module ({', '.join(sorted(modules))}): name the module instead") if not entries: sys.exit("no entry matches") if a.shard: i, n = (int(x) for x in a.shard.split("/")) entries = entries[i::n] if len(entries) > a.limit: sys.exit(f"{len(entries)} entries match, more than --limit {a.limit}") token = os.environ.get("QEDMARKET_TOKEN", "") if a.write and not token: sys.exit("set QEDMARKET_TOKEN") verifier = a.verifier if not verifier: _, res = call(base, token, "GET", "/verifiers") official = [v for v in (res or {}).get("items", []) if v.get("official") and v.get("state") == "ready"] if len(official) != 1: sys.exit("can't tell the official verifier; pass --verifier") verifier = official[0]["slug"] print(f"verifier: {verifier} ({official[0]['name']})", file=sys.stderr) # The platform lets one account have 10 checks waiting or running at once (429 too_many_runs). So: submit while # that allows, wait for checks to finish, go on. Safe to run again: markets already pending (or opened from # this run's earlier attempt) are found by challenge title and due date, or by locator, and not made twice. # A market is told apart by its challenge's module and theorem (the site returns the locator), not by its title: # two problems may have the same title. A pending market comes back without its locator, so only a title that # one entry has is recognised there. def key(e): return (e["module"], e["theorem"]) entry_of = {} for e in entries: entry_of.setdefault(e["title"], []).append(e) selected = {key(e) for e in entries} tagged, existing, waiting = set(), set(), [] # waiting: (entry, pending market id) def set_tags(e, problem): if problem in tagged or not e["tags"]: return tagged.add(problem) status, res = call(base, token, "PUT", f"/problems/{problem}/tags", {"tags": e["tags"]}) if status != 200: print(f" tags of {e['theorem']} not set: {status} {json.dumps(res)[:300]}") def adopt(row): """A pending market that exists already (from an earlier run).""" found = entry_of.get(row["challenge"]["title"], []) if len(found) != 1 or row["status"] not in ("checking", "opened"): return e = found[0] existing.add((key(e), row["dueAt"][:10])) if row["status"] == "checking": waiting.append((e, row["id"])) elif row.get("market"): _, market = call(base, token, "GET", f"/markets/{row['market']['id']}") set_tags(e, market["problem"]["id"]) if a.write: # Markets on the site already (by module, theorem and due date): not made twice, however long ago. cursor, seen = None, 0 while True: _, page = call(base, token, "GET", "/markets?status=all&limit=200" + (f"&cursor={cursor}" if cursor else "")) for m in (page or {}).get("items", []): seen += 1 params = ((m.get("challenge") or {}).get("locator") or {}).get("params") or {} if (params.get("module"), params.get("theorem")) in selected: existing.add(((params["module"], params["theorem"]), m["dueAt"][:10])) cursor = (page or {}).get("nextCursor") if not cursor or not (page or {}).get("items"): break print(f"{seen} markets on the site; {len(existing)} of them are for the selected problems") _, mine = call(base, token, "GET", "/me/pending-markets") for row in (mine or {}).get("items", []): adopt(row) if existing: print(f"{len(existing)} markets are pending or opened already; not made again") todo = list(entries) deadline = time.time() + a.wait while True: blocked = False for e in list(todo): challenge = {"title": e["title"], "description": description(e), "locator": {"git": {"repoUrl": REPO_URL, "commit": a.commit}, "params": {"module": e["module"], "theorem": e["theorem"]}}} for due in dues: if (key(e), due[:10]) in existing: continue body = {"newChallenge": challenge, "verifier": verifier, "dueAt": due} if not a.write: print(json.dumps(body, indent=1, ensure_ascii=False)) existing.add((key(e), due[:10])) continue status, res = call(base, token, "POST", "/markets", body) if status == 201: print(f"opened {e['theorem']} (due {due[:10]}): {res['url']}") existing.add((key(e), due[:10])) set_tags(e, res["problem"]["id"]) elif status == 202: print(f"checking {e['theorem']} (due {due[:10]}): {res['url']}") existing.add((key(e), due[:10])) waiting.append((e, res["id"])) elif status == 429 and (res or {}).get("error", {}).get("code") == "too_many_runs": blocked = True break else: print(f"refused {e['theorem']} (due {due[:10]}): {status} {json.dumps(res)[:500]}") existing.add((key(e), due[:10])) # not tried again in this run if blocked: break todo.remove(e) if not a.write or (not todo and not waiting): break if time.time() > deadline: break time.sleep(30) for e, pid in list(waiting): _, res = call(base, token, "GET", f"/pending-markets/{pid}") if res and res["status"] == "opened": _, market = call(base, token, "GET", f"/markets/{res['market']['id']}") print(f" opened {e['theorem']}: {res['market']['url']}") set_tags(e, market["problem"]["id"]) waiting.remove((e, pid)) elif res and res["status"] in ("failed", "cancelled"): print(f" {res['status']} {e['theorem']}: {res.get('reason')}: {res.get('message')}") waiting.remove((e, pid)) if todo or waiting: print(f"not finished: {len(todo)} problems not yet submitted, {len(waiting)} markets still checking; " "run the same command again to go on") if __name__ == "__main__": main()