hypergrok-trading-desk 1.7.1 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.cursor-plugin/plugin.json +1 -1
  5. package/.grok-plugin/marketplace.json +2 -2
  6. package/.grok-plugin/plugin.json +1 -1
  7. package/CHANGELOG.md +10 -0
  8. package/CONTRIBUTING.md +13 -3
  9. package/README.md +7 -6
  10. package/SETUP.md +4 -4
  11. package/docs/ACCOUNT_READ.md +84 -0
  12. package/docs/ARCHITECTURE.md +5 -2
  13. package/docs/FAQ.md +2 -2
  14. package/docs/FORK_REVIEW.md +10 -0
  15. package/docs/GROK_BOT_TEMPLATE.md +9 -1
  16. package/docs/PROVENANCE.md +16 -0
  17. package/docs/RESEARCH_DATASETS.md +1 -1
  18. package/docs/STOP_COST.md +1 -1
  19. package/docs/hyperliquid-claude-code.md +2 -2
  20. package/docs/hyperliquid-codex.md +2 -2
  21. package/docs/hyperliquid-cursor.md +2 -2
  22. package/docs/hyperliquid-gemini-cli.md +2 -2
  23. package/docs/hyperliquid-grok-build.md +4 -4
  24. package/gemini-extension.json +1 -1
  25. package/hooks/exchange_write_gate.py +112 -23
  26. package/package.json +4 -1
  27. package/plugin.json +1 -1
  28. package/scripts/account_read.py +352 -0
  29. package/scripts/check.sh +1 -0
  30. package/scripts/check_grok_template.py +15 -2
  31. package/scripts/check_npm_package.py +3 -3
  32. package/scripts/cli_journeys.py +80 -6
  33. package/scripts/desk_doctor.py +7 -1
  34. package/scripts/stop_cost.py +2 -1
  35. package/scripts/test_account_read.py +205 -0
  36. package/scripts/test_check_grok_template.py +80 -12
  37. package/scripts/test_desk_doctor.py +30 -1
  38. package/scripts/test_exchange_write_gate.py +64 -0
  39. package/scripts/test_order_rounding.py +16 -0
  40. package/scripts/test_stop_cost.py +11 -0
  41. package/skills/hypergrok-bootstrap/SKILL.md +4 -4
  42. package/skills/hyperliquid-api-reference/SKILL.md +6 -6
  43. package/skills/hyperliquid-market-data/SKILL.md +2 -2
  44. package/template/grok-bot.json +9 -9
@@ -7,9 +7,17 @@ command that looks like a signed `/exchange` request gets an "ask" decision, so
7
7
  the user confirms it even in an auto-accepting session. Anything else gets no
8
8
  opinion and follows the normal permission flow. The hook never approves.
9
9
 
10
- It reads the command text and any script file the command names (resolved from
11
- the session's working directory). It does not follow imports, so a write hidden
12
- in a helper module is not seen. Treat it as a backstop, not as the approval.
10
+ It reads the command text and any script file the command names. Relative paths
11
+ are resolved from the session working directory and from each literal ``cd`` in
12
+ the command. Shell scripts are included. A named script that exists but is too
13
+ large or unreadable to scan is treated as a write, so a skipped file cannot
14
+ slip past. The decision text redacts a 32-byte hex key and never includes the
15
+ command or file body.
16
+
17
+ It does not follow imports, expand globs, or resolve a ``cd`` target that is a
18
+ variable, command substitution or glob. A write hidden in a helper module, or
19
+ in a file the shell will name only after expansion, is not seen. Treat it as a
20
+ backstop, not as the approval.
13
21
  """
14
22
  import json
15
23
  import os
@@ -37,37 +45,112 @@ WRITE_METHODS = (
37
45
  "setReferrer", "userOutcome", "claimRewards", "createVault", "vaultDistribute", "vaultModify",
38
46
  "subAccountModify", "hip3LiquidatorTransfer",
39
47
  )
48
+ _METHODS = "|".join(WRITE_METHODS)
49
+ # The receiver has to look like an exchange client. Matching every `.order(`
50
+ # would ask on unrelated code; `ex` and `hl` are the short names that otherwise
51
+ # miss the `exch` requirement. `getattr` is matched separately.
40
52
  SDK_WRITE_RE = re.compile(
41
- r"\b\w*exch\w*\s*\.\s*(" + "|".join(WRITE_METHODS) + r")\s*\(",
53
+ r"\b(?:\w*exch\w*|ex|hl)\s*\.\s*(" + _METHODS + r")\s*\(",
54
+ re.IGNORECASE,
55
+ )
56
+ GETATTR_WRITE_RE = re.compile(
57
+ r"""getattr\s*\(\s*\w+\s*,\s*["'](""" + _METHODS + r""")["']\s*\)\s*\(""",
42
58
  re.IGNORECASE,
43
59
  )
44
60
  # A raw POST: the API host's /exchange path, or a base URL joined to it.
45
- ENDPOINT_RE = re.compile(r"\.xyz/exchange\b|\}/exchange\b|\+\s*[\"']/exchange[\"']")
46
- SCRIPT_RE = re.compile(r"[\w./~-]+\.(?:py|ts|mts|cts|js|mjs|cjs)\b")
61
+ # Hosts are case-insensitive, so `API.HYPERLIQUID.XYZ` is the same exchange.
62
+ # Built from pieces so this file's own source is not itself an /exchange match.
63
+ ENDPOINT_RE = re.compile(
64
+ r"\.xyz" + r"/exchange\b|" + r"\}" + r"/exchange\b|" + r"\+\s*[\"']" + r"/exchange[\"']",
65
+ re.IGNORECASE,
66
+ )
67
+ _SCRIPT_EXT = r"py|ts|mts|cts|js|mjs|cjs|sh|bash|zsh"
68
+ SCRIPT_RE = re.compile(
69
+ rf"""(?:"([^"\n]+\.(?:{_SCRIPT_EXT}))"|'([^'\n]+\.(?:{_SCRIPT_EXT}))'|([\w./~-]+\.(?:{_SCRIPT_EXT}))\b)""",
70
+ re.IGNORECASE,
71
+ )
72
+ CD_RE = re.compile(
73
+ r"""(?:^|&&|\|\||;|\n)\s*cd\s+("[^"\n]+"|'[^'\n]+'|~?[^\s;&|]+)"""
74
+ )
75
+ KEY_RE = re.compile(r"0x[0-9a-fA-F]{64}")
47
76
  MAX_SCRIPT_BYTES = 2_000_000
77
+ MAX_SCRIPTS = 32
78
+
79
+
80
+ class Unscanned(Exception):
81
+ def __init__(self, token):
82
+ self.token = token
83
+
84
+
85
+ def redact(text):
86
+ return KEY_RE.sub("0x[redacted]", text)
48
87
 
49
88
 
50
89
  def find_write(text):
51
- match = SDK_WRITE_RE.search(text)
52
- if match:
53
- return match.group(0).rstrip("( ")
54
- match = ENDPOINT_RE.search(text)
90
+ match = SDK_WRITE_RE.search(text) or GETATTR_WRITE_RE.search(text)
55
91
  if match:
92
+ return match.group(1)
93
+ if ENDPOINT_RE.search(text):
56
94
  return "a POST to /exchange"
57
95
  return None
58
96
 
59
97
 
60
- def named_scripts(command, cwd):
61
- for token in SCRIPT_RE.findall(command):
62
- path = os.path.expanduser(token)
98
+ def script_tokens(command):
99
+ tokens = []
100
+ for match in SCRIPT_RE.finditer(command):
101
+ token = next(part for part in match.groups() if part)
102
+ if token not in tokens:
103
+ tokens.append(token)
104
+ return tokens
105
+
106
+
107
+ def directory_roots(command, cwd):
108
+ """Literal `cd` targets only. A variable or glob stays unresolved."""
109
+ roots = [cwd]
110
+ current = cwd
111
+ for match in CD_RE.finditer(command):
112
+ raw = match.group(1)
113
+ if len(raw) >= 2 and raw[0] in "\"'" and raw[-1] == raw[0]:
114
+ raw = raw[1:-1]
115
+ if not raw or raw == "-" or any(char in raw for char in "$`*?[]"):
116
+ continue
117
+ path = os.path.expanduser(raw)
63
118
  if not os.path.isabs(path):
64
- path = os.path.join(cwd, path)
65
- try:
66
- if os.path.isfile(path) and os.path.getsize(path) <= MAX_SCRIPT_BYTES:
119
+ path = os.path.join(current, path)
120
+ path = os.path.normpath(path)
121
+ current = path
122
+ if path not in roots:
123
+ roots.append(path)
124
+ return roots
125
+
126
+
127
+ def candidate_paths(token, roots):
128
+ path = os.path.expanduser(token)
129
+ if os.path.isabs(path):
130
+ return [os.path.normpath(path)]
131
+ return [os.path.normpath(os.path.join(root, path)) for root in roots]
132
+
133
+
134
+ def named_scripts(command, cwd):
135
+ tokens = script_tokens(command)
136
+ if len(tokens) > MAX_SCRIPTS:
137
+ raise Unscanned(f"{len(tokens)} named scripts")
138
+ roots = directory_roots(command, cwd)
139
+ seen = set()
140
+ for token in tokens:
141
+ for path in candidate_paths(token, roots):
142
+ if path in seen:
143
+ continue
144
+ seen.add(path)
145
+ try:
146
+ if not os.path.isfile(path):
147
+ continue
148
+ if os.path.getsize(path) > MAX_SCRIPT_BYTES:
149
+ raise Unscanned(token)
67
150
  with open(path, encoding="utf-8", errors="replace") as handle:
68
151
  yield token, handle.read()
69
- except OSError:
70
- continue
152
+ except OSError:
153
+ raise Unscanned(token)
71
154
 
72
155
 
73
156
  def decide(event):
@@ -80,13 +163,19 @@ def decide(event):
80
163
  where = "in the command"
81
164
  if not found:
82
165
  cwd = event.get("cwd") or os.getcwd()
83
- for token, text in named_scripts(command, cwd):
84
- found = find_write(text)
85
- if found:
86
- where = f"in {token}"
87
- break
166
+ try:
167
+ for token, text in named_scripts(command, cwd):
168
+ found = find_write(text)
169
+ if found:
170
+ where = f"in {redact(token)}"
171
+ break
172
+ except Unscanned as exc:
173
+ found = "an unscanned script"
174
+ where = f"in {redact(exc.token)}"
88
175
  if not found:
89
176
  return None
177
+ if not found.startswith(("a ", "an ")):
178
+ found = f"{found}()"
90
179
  return {
91
180
  "hookSpecificOutput": {
92
181
  "hookEventName": "PreToolUse",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hypergrok-trading-desk",
3
- "version": "1.7.1",
3
+ "version": "1.7.2",
4
4
  "description": "HyperGrok instructions, seventeen skills, seven role profiles and read-only Python tools for a user-approved Hyperliquid trading desk.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -54,6 +54,7 @@
54
54
  "assets/mascot.jpg",
55
55
  "assets/opening-bell.gif",
56
56
  "assets/ticket-hg-20260816-01.png",
57
+ "docs/ACCOUNT_READ.md",
57
58
  "docs/ARCHITECTURE.md",
58
59
  "docs/FAQ.md",
59
60
  "docs/FORK_REVIEW.md",
@@ -71,6 +72,7 @@
71
72
  "hooks/exchange_write_gate.py",
72
73
  "plugin.json",
73
74
  "rules/hypergrok-team.mdc",
75
+ "scripts/account_read.py",
74
76
  "scripts/check.sh",
75
77
  "scripts/check_grok_template.py",
76
78
  "scripts/check_manifests.py",
@@ -83,6 +85,7 @@
83
85
  "scripts/release_bump.py",
84
86
  "scripts/research_dataset.py",
85
87
  "scripts/stop_cost.py",
88
+ "scripts/test_account_read.py",
86
89
  "scripts/test_check_grok_template.py",
87
90
  "scripts/test_check_manifests.py",
88
91
  "scripts/test_check_npm_package.py",
package/plugin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "hypergrok",
4
4
  "description": "Turn your Grok Bot into a Hyperliquid trading desk: seven specialist roles with full system prompts and seventeen skills for working with Hyperliquid. Includes a zero-key Opening Bell and desk doctor.",
5
- "version": "1.7.1",
5
+ "version": "1.7.2",
6
6
  "author": {"name": "Galleon Labs", "url": "https://galleonlabs.io"},
7
7
  "license": "MIT",
8
8
  "repository": "https://github.com/galleonlabs/hypergrok-trading-desk",
@@ -0,0 +1,352 @@
1
+ #!/usr/bin/env python3
2
+ """Read one Hyperliquid account across every perp DEX and spot, with no keys.
3
+
4
+ Hyperliquid runs the main perp DEX beside builder-deployed (HIP-3) DEXs such
5
+ as `xyz`. Each keeps its own clearinghouse, so `clearinghouseState` without a
6
+ `dex` parameter shows only the main DEX and omits HIP-3 positions and margin.
7
+ This script lists every DEX with `perpDexs`, reads `clearinghouseState` for
8
+ each one, reads spot balances, and reports positions with per-DEX and total
9
+ equity in USD.
10
+
11
+ Equity is summed only where Hyperliquid documents separate balances: the
12
+ standard account mode. There, total equity is each DEX's
13
+ `marginSummary.accountValue`, converted from the DEX's collateral token, plus
14
+ every spot balance valued at its USDC pair. A nonzero balance with no
15
+ positive USDC price is omitted. Those prices are positive, so the partial
16
+ total is a lower bound when every omitted balance is positive and an upper
17
+ bound when every omitted balance is negative. Unified-account and
18
+ portfolio-margin modes share one balance between spot and perps, so the
19
+ script reports the parts without a total rather than double counting.
20
+
21
+ The account address is typed or read from HYPERGROK_ACCOUNT; nothing else is
22
+ read from the environment. The script uses only the public `/info` endpoint.
23
+ It never reads wallet material, signs, or calls the exchange write endpoint.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import os
31
+ import re
32
+ import sys
33
+ from datetime import datetime, timezone
34
+ from decimal import Decimal, DecimalException
35
+
36
+ from cli_contract import ReadOnlyParser, add_network_arguments, describe, emit_error, network_settings
37
+ from opening_bell import decimal, post_info
38
+
39
+ USER_AGENT = "hypergrok-account-read/1.0"
40
+ ADDRESS_ENV = "HYPERGROK_ACCOUNT"
41
+ ADDRESS_RE = re.compile(r"0x[0-9a-fA-F]{40}")
42
+ USDC_TOKEN = 0
43
+ # Hyperliquid's account abstraction modes with separate spot and per-DEX
44
+ # balances. Any other mode shares collateral, so a sum could count it twice.
45
+ SEPARATE_MODES = ("default", "disabled")
46
+ SHARED_NOTE = ("This mode shares collateral between spot and perp DEXs; Hyperliquid documents that "
47
+ "spotClearinghouseState then holds all balances and per-DEX user states are not meaningful, "
48
+ "so no total is summed.")
49
+ SAFETY = "No key requested. No signature. No order, transfer or exchange request."
50
+
51
+
52
+ def mapping(value, field: str) -> dict:
53
+ if not isinstance(value, dict):
54
+ raise ValueError(f"{field} is not an object")
55
+ return value
56
+
57
+
58
+ def dex_names(payload) -> list[str]:
59
+ """`perpDexs` lists `null` for the main DEX, then each builder DEX."""
60
+ if not isinstance(payload, list) or not payload or payload[0] is not None:
61
+ raise ValueError("perpDexs must be a list that starts with the main DEX")
62
+ names = [""]
63
+ for entry in payload[1:]:
64
+ name = mapping(entry, "perpDexs entry").get("name")
65
+ if not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_-]*", name) or name in names:
66
+ raise ValueError("perpDexs names must be unique lowercase DEX names")
67
+ names.append(name)
68
+ return names
69
+
70
+
71
+ def spot_prices(payload) -> tuple[dict[int, str], dict[int, Decimal]]:
72
+ """Token names, and a USD price for every token with a priced USDC pair."""
73
+ if not isinstance(payload, list) or len(payload) != 2 or not isinstance(payload[1], list):
74
+ raise ValueError("spotMetaAndAssetCtxs must be [meta, contexts]")
75
+ meta = mapping(payload[0], "spot meta")
76
+ tokens = {mapping(token, "spot token")["index"]: str(token["name"]) for token in meta.get("tokens", [])}
77
+ contexts = {ctx.get("coin"): ctx for ctx in payload[1] if isinstance(ctx, dict)}
78
+ prices = {USDC_TOKEN: Decimal(1)}
79
+ for pair in meta.get("universe", []):
80
+ base_quote = mapping(pair, "spot pair").get("tokens")
81
+ if not isinstance(base_quote, list) or len(base_quote) != 2 or base_quote[1] != USDC_TOKEN:
82
+ continue
83
+ ctx = contexts.get(pair.get("name")) or {}
84
+ for field in ("midPx", "markPx"):
85
+ if ctx.get(field) is not None:
86
+ px = decimal(ctx[field], f"{pair.get('name')} {field}")
87
+ if px > 0:
88
+ prices.setdefault(base_quote[0], px)
89
+ break
90
+ return tokens, prices
91
+
92
+
93
+ def position(entry) -> dict:
94
+ data = mapping(mapping(entry, "assetPositions entry").get("position"), "position")
95
+ szi = decimal(data.get("szi"), "position szi")
96
+ leverage = data.get("leverage") if isinstance(data.get("leverage"), dict) else {}
97
+ liquidation = data.get("liquidationPx")
98
+ return {
99
+ "coin": str(data.get("coin")),
100
+ "side": "long" if szi > 0 else "short",
101
+ "size": str(abs(szi)),
102
+ "entry_px": str(decimal(data.get("entryPx"), "entryPx")),
103
+ "position_value": str(decimal(data.get("positionValue"), "positionValue")),
104
+ "unrealized_pnl": str(decimal(data.get("unrealizedPnl"), "unrealizedPnl")),
105
+ "margin_used": str(decimal(data.get("marginUsed"), "marginUsed")),
106
+ "leverage_type": str(leverage.get("type", "")),
107
+ "leverage": str(leverage.get("value", "")),
108
+ "liquidation_px": None if liquidation is None else str(decimal(liquidation, "liquidationPx")),
109
+ }
110
+
111
+
112
+ def read_account(read, address: str) -> dict:
113
+ """Every request this read makes, in order; `read` posts one `/info` payload."""
114
+ names = dex_names(read({"type": "perpDexs"}))
115
+ mode = read({"type": "userAbstraction", "user": address})
116
+ if not isinstance(mode, str) or not mode:
117
+ raise ValueError("userAbstraction did not return a mode")
118
+ states = {}
119
+ for name in names:
120
+ payload = {"type": "clearinghouseState", "user": address}
121
+ if name:
122
+ payload["dex"] = name
123
+ states[name] = mapping(read(payload), f"clearinghouseState for {name or 'main'}")
124
+ spot = mapping(read({"type": "spotClearinghouseState", "user": address}), "spotClearinghouseState")
125
+ tokens, prices = spot_prices(read({"type": "spotMetaAndAssetCtxs"}))
126
+ collateral = {}
127
+ for name, state in states.items():
128
+ held = decimal(mapping(state.get("marginSummary"), "marginSummary").get("accountValue"), "accountValue")
129
+ if held != 0 or state.get("assetPositions"):
130
+ token = mapping(read({"type": "meta", "dex": name}), f"meta for {name or 'main'}").get("collateralToken")
131
+ if not isinstance(token, int):
132
+ raise ValueError(f"meta for {name or 'main'} has no collateralToken")
133
+ collateral[name] = token
134
+ return {"names": names, "mode": mode, "states": states, "spot": spot,
135
+ "tokens": tokens, "prices": prices, "collateral": collateral}
136
+
137
+
138
+ def equity_bound(separate: bool, omitted_positive: bool, omitted_negative: bool) -> str | None:
139
+ """How the partial sum sits relative to equity. Prices in the sum are positive."""
140
+ if not separate:
141
+ return None
142
+ if omitted_positive and omitted_negative:
143
+ return "unknown"
144
+ if omitted_negative:
145
+ return "upper"
146
+ if omitted_positive:
147
+ return "lower"
148
+ return "exact"
149
+
150
+
151
+ def build_report(raw: dict, address: str, network: str, base_url: str) -> dict:
152
+ tokens, prices, unpriced = raw["tokens"], raw["prices"], []
153
+ omitted_positive = omitted_negative = False
154
+ dexes, times, perp_usd = [], [], Decimal(0)
155
+ for name in raw["names"]:
156
+ state = raw["states"][name]
157
+ summary = mapping(state.get("marginSummary"), "marginSummary")
158
+ value = decimal(summary.get("accountValue"), "accountValue")
159
+ token = raw["collateral"].get(name)
160
+ price = prices.get(token) if token is not None else None
161
+ value_usd = None
162
+ if token is None:
163
+ value_usd = Decimal(0) # An empty DEX: no balance, no positions.
164
+ elif value == 0:
165
+ value_usd = Decimal(0) # Zero collateral units are zero USD at any price.
166
+ elif price is not None:
167
+ value_usd = value * price
168
+ else:
169
+ unpriced.append(f"{name or 'main'} collateral {tokens.get(token, token)}")
170
+ omitted_positive = omitted_positive or value > 0
171
+ omitted_negative = omitted_negative or value < 0
172
+ if value_usd is not None:
173
+ perp_usd += value_usd
174
+ if isinstance(state.get("time"), int):
175
+ times.append(state["time"])
176
+ dexes.append({
177
+ "dex": name,
178
+ "label": name or "main",
179
+ "collateral": None if token is None else tokens.get(token, str(token)),
180
+ "collateral_usd_price": None if price is None else str(price),
181
+ "account_value": str(value),
182
+ "account_value_usd": None if value_usd is None else str(value_usd),
183
+ "total_ntl_pos": str(decimal(summary.get("totalNtlPos"), "totalNtlPos")),
184
+ "total_margin_used": str(decimal(summary.get("totalMarginUsed"), "totalMarginUsed")),
185
+ "withdrawable": str(decimal(state.get("withdrawable"), "withdrawable")),
186
+ "positions": [position(entry) for entry in state.get("assetPositions") or []],
187
+ })
188
+ balances, spot_usd = [], Decimal(0)
189
+ for entry in raw["spot"].get("balances") or []:
190
+ entry = mapping(entry, "spot balance")
191
+ total = decimal(entry.get("total"), "spot total")
192
+ if total == 0:
193
+ continue
194
+ price = prices.get(entry.get("token"))
195
+ value_usd = None if price is None else total * price
196
+ if value_usd is None:
197
+ unpriced.append(f"spot {entry.get('coin')}")
198
+ omitted_positive = omitted_positive or total > 0
199
+ omitted_negative = omitted_negative or total < 0
200
+ else:
201
+ spot_usd += value_usd
202
+ balances.append({
203
+ "coin": str(entry.get("coin")),
204
+ "token": entry.get("token"),
205
+ "total": str(total),
206
+ "hold": str(decimal(entry.get("hold", "0"), "spot hold")),
207
+ "usd_price": None if price is None else str(price),
208
+ "value_usd": None if value_usd is None else str(value_usd),
209
+ })
210
+ separate = raw["mode"] in SEPARATE_MODES
211
+ if not times:
212
+ raise ValueError("clearinghouseState time is missing")
213
+
214
+ def utc(ms: int) -> str:
215
+ return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z")
216
+
217
+ return {
218
+ "schema_version": 1,
219
+ "mode": "read-only",
220
+ "network": network,
221
+ "account": address,
222
+ "abstraction": raw["mode"],
223
+ "source": {
224
+ "endpoint": "/info",
225
+ "requests": ["perpDexs", "userAbstraction", "clearinghouseState", "spotClearinghouseState",
226
+ "spotMetaAndAssetCtxs", "meta"],
227
+ "clearinghouse_reads": len(raw["names"]),
228
+ "base_url": base_url,
229
+ "observed_from": utc(min(times)),
230
+ "observed_to": utc(max(times)),
231
+ },
232
+ "dexes": dexes,
233
+ "spot": {"balances": balances, "value_usd": str(spot_usd)},
234
+ "equity": {
235
+ "basis": "separate" if separate else "shared",
236
+ "perp_usd": str(perp_usd),
237
+ "spot_usd": str(spot_usd),
238
+ "total_usd": str(perp_usd + spot_usd) if separate else None,
239
+ "complete": separate and not unpriced,
240
+ "bound": equity_bound(separate, omitted_positive, omitted_negative),
241
+ "unpriced": unpriced,
242
+ "note": None if separate else SHARED_NOTE,
243
+ },
244
+ "safety": SAFETY,
245
+ }
246
+
247
+
248
+ def fetch_report(address: str, base_url: str, network: str, timeout: float) -> dict:
249
+ raw = read_account(lambda payload: post_info(base_url, payload, timeout, USER_AGENT), address)
250
+ return build_report(raw, address, network, base_url)
251
+
252
+
253
+ def amount(value: str | None) -> str:
254
+ return "unpriced" if value is None else f"{Decimal(value):,.2f}"
255
+
256
+
257
+ def usd(value: str | None) -> str:
258
+ if value is None:
259
+ return "unpriced"
260
+ number = Decimal(value)
261
+ return f"-${-number:,.2f}" if number < 0 else f"${number:,.2f}"
262
+
263
+
264
+ def render(report: dict) -> str:
265
+ equity, spot = report["equity"], report["spot"]
266
+ address = report["account"]
267
+ lines = [
268
+ f"HYPERGROK ACCOUNT READ · {address[:6]}...{address[-4:]} · {report['abstraction'].upper()} MODE",
269
+ f"READ ONLY · {report['network'].upper()} · {report['source']['observed_to']}",
270
+ f"Sources: Hyperliquid /info perpDexs, userAbstraction, clearinghouseState x{report['source']['clearinghouse_reads']},"
271
+ " spotClearinghouseState, spotMetaAndAssetCtxs, meta",
272
+ "",
273
+ ]
274
+ held = [dex for dex in report["dexes"] if dex["collateral"] is not None]
275
+ rows = [("DEX", "collateral", "account value", "USD", "positions")]
276
+ rows += [(dex["label"], dex["collateral"], amount(dex["account_value"]), usd(dex["account_value_usd"]),
277
+ str(len(dex["positions"]))) for dex in held]
278
+ widths = [max(len(row[i]) for row in rows) for i in range(5)]
279
+ for row in rows:
280
+ lines.append(" ".join([row[0].ljust(widths[0]), row[1].ljust(widths[1]),
281
+ *(cell.rjust(width) for cell, width in zip(row[2:], widths[2:]))]).rstrip())
282
+ empty = len(report["dexes"]) - len(held)
283
+ if not held:
284
+ lines.append("No perp balance or position on any DEX.")
285
+ if empty:
286
+ lines.append(f"{empty} other DEX{'s' if empty != 1 else ''} empty.")
287
+ positions = [p for dex in report["dexes"] for p in dex["positions"]]
288
+ if positions:
289
+ lines.extend(["", "Positions"])
290
+ for p in positions:
291
+ liq = "none" if p["liquidation_px"] is None else amount(p["liquidation_px"])
292
+ pnl = Decimal(p["unrealized_pnl"])
293
+ lines.append(f" {p['coin']} {p['side']} {Decimal(p['size']):f} @ {amount(p['entry_px'])}"
294
+ f" · value {amount(p['position_value'])} · uPnL {'+' if pnl >= 0 else '-'}{abs(pnl):,.2f}"
295
+ f" · {p['leverage_type']} {p['leverage']}x · liq {liq}")
296
+ lines.extend(["", f"Spot {usd(spot['value_usd'])} across {len(spot['balances'])} balance{'s' if len(spot['balances']) != 1 else ''}"])
297
+ if equity["unpriced"]:
298
+ lines.append(f"Unpriced {', '.join(equity['unpriced'])} (no USDC pair price; left out of the sum)")
299
+ if equity["basis"] == "separate":
300
+ prefix = {"exact": "", "lower": "at least ", "upper": "at most ", "unknown": "incomplete "}[equity["bound"]]
301
+ lines.append(f"Equity perps {usd(equity['perp_usd'])} + spot {usd(equity['spot_usd'])} = {prefix}{usd(equity['total_usd'])}")
302
+ else:
303
+ lines.append(f"Equity not summed: {equity['note']}")
304
+ lines.extend(["", "Reads are sequential, not one atomic snapshot. Staking, vaults and sub-accounts are not included.",
305
+ SAFETY, "Facts only. This is not a trading signal."])
306
+ return "\n".join(lines)
307
+
308
+
309
+ def main(argv=None) -> int:
310
+ argv = list(sys.argv[1:] if argv is None else argv)
311
+ parser = ReadOnlyParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
312
+ machine_readable="--json" in argv or "--schema" in argv)
313
+ parser.add_argument("--address", help=f"account (main wallet) address; defaults to ${ADDRESS_ENV}")
314
+ add_network_arguments(parser)
315
+ parser.add_argument("--json", action="store_true", help="print machine-readable JSON")
316
+ args = parser.parse_args(argv)
317
+ if args.schema:
318
+ print(json.dumps(describe("account_read", {
319
+ "schema_version": 1, "mode": "read-only", "network": "mainnet | testnet | custom",
320
+ "account": "the address read", "abstraction": "userAbstraction mode, e.g. default | unifiedAccount | portfolioMargin",
321
+ "source": "endpoint, requests, clearinghouse_reads, base_url, observed_from and observed_to (UTC clearinghouse times)",
322
+ "dexes": "one entry per perpDexs DEX, main first: dex ('' for main), label, collateral (null when empty and unread), "
323
+ "collateral_usd_price, account_value, account_value_usd (null when a nonzero balance has no USD price; "
324
+ "zero collateral units are 0), total_ntl_pos, total_margin_used, "
325
+ "withdrawable, positions[coin, side, size, entry_px, position_value, unrealized_pnl, margin_used, "
326
+ "leverage_type, leverage, liquidation_px]",
327
+ "spot": "balances[coin, token, total, hold, usd_price, value_usd] for nonzero balances; value_usd of priced balances",
328
+ "equity": "basis (separate | shared), perp_usd, spot_usd, total_usd (null when basis is shared), complete, "
329
+ "bound (exact | lower | upper | unknown when separate; null when shared), unpriced, note",
330
+ "safety": SAFETY,
331
+ }), indent=2))
332
+ return 0
333
+ address = (args.address or os.environ.get(ADDRESS_ENV, "")).strip()
334
+ if not address:
335
+ parser.error(f"required: --address or {ADDRESS_ENV}")
336
+ if not ADDRESS_RE.fullmatch(address):
337
+ parser.error("address must be 0x followed by 40 hex characters")
338
+ base_url, network = network_settings(args, parser)
339
+ try:
340
+ report = fetch_report(address.lower(), base_url, network, args.timeout)
341
+ except (OSError, ValueError, KeyError, TypeError, DecimalException, OverflowError) as exc:
342
+ if args.json:
343
+ emit_error("source_unavailable", str(exc))
344
+ else:
345
+ print(f"Account read unavailable: {exc}", file=sys.stderr)
346
+ return 1
347
+ print(json.dumps(report, indent=2, sort_keys=True) if args.json else render(report))
348
+ return 0
349
+
350
+
351
+ if __name__ == "__main__":
352
+ sys.exit(main())
package/scripts/check.sh CHANGED
@@ -123,6 +123,7 @@ python3 scripts/test_check_grok_template.py
123
123
  python3 scripts/test_release_bump.py
124
124
  python3 scripts/test_check_public_template.py
125
125
  python3 scripts/test_stop_cost.py
126
+ python3 scripts/test_account_read.py
126
127
  python3 scripts/test_exchange_write_gate.py
127
128
 
128
129
  # Verify the published arithmetic without loading a wallet or SDK.
@@ -32,16 +32,30 @@ def sha256(path):
32
32
 
33
33
 
34
34
  def run_git(root, args):
35
+ # GIT_DIR and GIT_WORK_TREE override -C and would compare a different repository.
36
+ env = {key: value for key, value in os.environ.items() if not key.startswith("GIT_")}
35
37
  try:
36
38
  return subprocess.run(
37
39
  ["git", "-C", root, *args],
38
40
  capture_output=True,
39
41
  check=False,
42
+ env=env,
40
43
  )
41
44
  except OSError:
42
45
  return None
43
46
 
44
47
 
48
+ def repository_file(root, rel):
49
+ """An existing file inside root. Absolute paths and `..` do not qualify."""
50
+ if not isinstance(rel, str) or not rel or rel.startswith(("http://", "https://")):
51
+ return False
52
+ root = os.path.normpath(root)
53
+ resolved = os.path.normpath(os.path.join(root, rel))
54
+ if os.path.relpath(resolved, root).startswith(".."):
55
+ return False
56
+ return os.path.isfile(resolved)
57
+
58
+
45
59
  def claimed_paths(template):
46
60
  paths = []
47
61
  avatar = template.get("avatar")
@@ -146,8 +160,7 @@ def main(root):
146
160
  if source.get(key) != expected:
147
161
  errors.append(f"{TEMPLATE}: source.{key} must be {expected}")
148
162
 
149
- avatar = template.get("avatar")
150
- if not isinstance(avatar, str) or not os.path.isfile(os.path.join(root, avatar)):
163
+ if not repository_file(root, template.get("avatar")):
151
164
  errors.append(f"{TEMPLATE}: avatar must resolve to a repository file")
152
165
 
153
166
  expected_skill_names = sorted(
@@ -28,7 +28,7 @@ MANIFESTS = (
28
28
  )
29
29
  RESOURCES = (
30
30
  "assets/mascot.jpg", "assets/mascot-320.jpg", "assets/opening-bell.gif", "rules/hypergrok-team.mdc",
31
- "template/grok-bot.json", "docs/ARCHITECTURE.md", "docs/FAQ.md",
31
+ "template/grok-bot.json", "docs/ACCOUNT_READ.md", "docs/ARCHITECTURE.md", "docs/FAQ.md",
32
32
  "docs/FORK_REVIEW.md", "docs/GROK_BOT_TEMPLATE.md", "docs/PROVENANCE.md",
33
33
  "docs/RESEARCH_DATASETS.md", "docs/STOP_COST.md", "docs/hyperliquid-claude-code.md",
34
34
  "docs/hyperliquid-codex.md", "docs/hyperliquid-cursor.md", "docs/hyperliquid-gemini-cli.md",
@@ -37,9 +37,9 @@ RESOURCES = (
37
37
  "hooks/exchange-write-gate.json", "hooks/exchange_write_gate.py",
38
38
  )
39
39
  SCRIPTS = (
40
- "check.sh", "check_grok_template.py", "check_manifests.py",
40
+ "account_read.py", "check.sh", "check_grok_template.py", "check_manifests.py",
41
41
  "check_npm_package.py", "check_public_template.py", "cli_contract.py", "cli_journeys.py", "desk_doctor.py",
42
- "opening_bell.py", "release_bump.py", "research_dataset.py", "stop_cost.py", "test_research_dataset.py", "test_check_grok_template.py", "test_check_manifests.py",
42
+ "opening_bell.py", "release_bump.py", "research_dataset.py", "stop_cost.py", "test_account_read.py", "test_research_dataset.py", "test_check_grok_template.py", "test_check_manifests.py",
43
43
  "test_check_npm_package.py", "test_check_public_template.py",
44
44
  "test_desk_doctor.py", "test_exchange_write_gate.py", "test_opening_bell.py", "test_order_rounding.py",
45
45
  "test_release_bump.py",