pax-api 2.5.1__tar.gz → 3.0.0__tar.gz

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 (31) hide show
  1. pax_api-3.0.0/PKG-INFO +221 -0
  2. pax_api-3.0.0/README.md +181 -0
  3. {pax_api-2.5.1 → pax_api-3.0.0}/pyproject.toml +5 -2
  4. {pax_api-2.5.1 → pax_api-3.0.0}/src/pax_api/__init__.py +21 -18
  5. pax_api-3.0.0/src/pax_api/audit.py +132 -0
  6. pax_api-3.0.0/src/pax_api/auth.py +72 -0
  7. pax_api-3.0.0/src/pax_api/client.py +397 -0
  8. {pax_api-2.5.1 → pax_api-3.0.0}/src/pax_api/retry.py +2 -2
  9. {pax_api-2.5.1 → pax_api-3.0.0}/src/pax_api/ws_client.py +1 -1
  10. pax_api-3.0.0/src/pax_api.egg-info/PKG-INFO +221 -0
  11. {pax_api-2.5.1 → pax_api-3.0.0}/src/pax_api.egg-info/SOURCES.txt +1 -0
  12. pax_api-3.0.0/tests/test_audit.py +98 -0
  13. pax_api-3.0.0/tests/test_auth.py +44 -0
  14. pax_api-3.0.0/tests/test_client.py +160 -0
  15. {pax_api-2.5.1 → pax_api-3.0.0}/tests/test_errors.py +0 -1
  16. {pax_api-2.5.1 → pax_api-3.0.0}/tests/test_retry.py +0 -1
  17. pax_api-2.5.1/PKG-INFO +0 -277
  18. pax_api-2.5.1/README.md +0 -237
  19. pax_api-2.5.1/src/pax_api/auth.py +0 -66
  20. pax_api-2.5.1/src/pax_api/client.py +0 -497
  21. pax_api-2.5.1/src/pax_api.egg-info/PKG-INFO +0 -277
  22. pax_api-2.5.1/tests/test_audit.py +0 -59
  23. pax_api-2.5.1/tests/test_auth.py +0 -48
  24. pax_api-2.5.1/tests/test_client.py +0 -110
  25. {pax_api-2.5.1 → pax_api-3.0.0}/LICENSE +0 -0
  26. {pax_api-2.5.1 → pax_api-3.0.0}/setup.cfg +0 -0
  27. {pax_api-2.5.1 → pax_api-3.0.0}/src/pax_api/errors.py +0 -0
  28. {pax_api-2.5.1 → pax_api-3.0.0}/src/pax_api/py.typed +0 -0
  29. {pax_api-2.5.1 → pax_api-3.0.0}/src/pax_api.egg-info/dependency_links.txt +0 -0
  30. {pax_api-2.5.1 → pax_api-3.0.0}/src/pax_api.egg-info/requires.txt +0 -0
  31. {pax_api-2.5.1 → pax_api-3.0.0}/src/pax_api.egg-info/top_level.txt +0 -0
pax_api-3.0.0/PKG-INFO ADDED
@@ -0,0 +1,221 @@
1
+ Metadata-Version: 2.4
2
+ Name: pax-api
3
+ Version: 3.0.0
4
+ Summary: Official Python SDK for the PredictAsiaX Trader Track API — Web3-native prediction markets
5
+ Author-email: PredictAsiaX <support@predictasiax.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://predictasiax.com/developer
8
+ Project-URL: Documentation, https://docs.predictasiax.com
9
+ Project-URL: Repository, https://github.com/predictasiax/pax-python-sdk
10
+ Project-URL: Issues, https://github.com/predictasiax/pax-python-sdk/issues
11
+ Project-URL: Changelog, https://docs.predictasiax.com/changelog
12
+ Keywords: predictasiax,pax,prediction-market,trading-api,web3,hmac
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Financial and Insurance Industry
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Office/Business :: Financial :: Investment
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Requires-Python: >=3.8
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: requests>=2.28
30
+ Requires-Dist: websocket-client>=1.5
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=7; extra == "dev"
33
+ Requires-Dist: pytest-cov>=4; extra == "dev"
34
+ Requires-Dist: responses>=0.23; extra == "dev"
35
+ Requires-Dist: ruff>=0.1; extra == "dev"
36
+ Requires-Dist: mypy>=1; extra == "dev"
37
+ Requires-Dist: build>=1; extra == "dev"
38
+ Requires-Dist: twine>=4; extra == "dev"
39
+ Dynamic: license-file
40
+
41
+ # pax-api — Official Python SDK for PredictAsiaX
42
+
43
+ REST + WebSocket client for the PredictAsiaX API gateway (`https://api.predictasiax.com`).
44
+
45
+ **Version 3.0.0** · MIT license · Python 3.8+ · [Changelog](CHANGELOG.md)
46
+
47
+ - **Docs**: https://docs.predictasiax.com
48
+ - **Verify**: https://docs.predictasiax.com/verify — public audit-log verifier
49
+ - **Sandbox key (anonymous)**: `POST /v1/sandbox-keys`
50
+ - **Support**: support@predictasiax.com
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ pip install --upgrade pax-api
56
+ ```
57
+
58
+ ## Quickstart
59
+
60
+ ```python
61
+ from pax_api import PaxClient
62
+
63
+ # Public endpoints need no key
64
+ pax = PaxClient()
65
+ print(pax.audit_status()["data"]["events"]["total"])
66
+ print(pax.get_orderbook("hadjar-f1-2026"))
67
+
68
+ # Mint a sandbox key (the api_key is shown once — store it)
69
+ key = pax.mint_sandbox_key(org_name="my-app")["data"]["api_key"]
70
+
71
+ pax = PaxClient(api_key=key) # sent as Authorization: Bearer sk_live_...
72
+ print(pax.get_balance())
73
+ print(pax.get_positions())
74
+ ```
75
+
76
+ ## Credentials
77
+
78
+ | Mode | Constructor | Sent on the wire |
79
+ |------|-------------|------------------|
80
+ | API key | `PaxClient(api_key="sk_live_...")` | `Authorization: Bearer sk_live_...` |
81
+ | HMAC signing | `PaxClient(api_key="sk_live_...", key_id="api_...")` | `PAX-ADDRESS`, `PAX-TIMESTAMP`, `PAX-NONCE`, `PAX-SIGNATURE` (no key) |
82
+ | Session / OAuth | `PaxClient(bearer_token="...")` | `Authorization: Bearer ...` |
83
+
84
+ HMAC signature (what the gateway verifies):
85
+
86
+ ```text
87
+ canonical = timestamp + "\n" + nonce + "\n" + METHOD + "\n" + path_with_query + "\n" + body
88
+ signature = base64(HMAC-SHA256(key = the full sk_live_ key, msg = canonical))
89
+ ```
90
+
91
+ `timestamp` is Unix seconds (accepted window ±300 s), `nonce` is single-use, `path_with_query` includes `/v1` and the query string. The SDK signs every attempt afresh, retries included. `pax_api.auth.sign_request` is exported if you need the headers yourself.
92
+
93
+ ## Trading
94
+
95
+ ```python
96
+ pax = PaxClient(api_key="sk_live_...", key_id="api_...")
97
+
98
+ order = pax.place_order(market_id="hadjar-f1-2026", side="yes", price="0.05", size="10")
99
+ pax.get_orders(status="open")
100
+ pax.cancel_order(order_id)
101
+ pax.cancel_all_orders(market_id="hadjar-f1-2026")
102
+
103
+ pax.place_orders_batch([
104
+ {"market_id": "hadjar-f1-2026", "side": "yes", "price": "0.04", "size": "5"},
105
+ {"market_id": "hadjar-f1-2026", "side": "no", "price": "0.90", "size": "5"},
106
+ ])
107
+ ```
108
+
109
+ `place_order` is a limit BUY of the chosen outcome (`side="yes"` or `"no"`), price 0.01–0.99.
110
+
111
+ ## Fee estimate
112
+
113
+ ```python
114
+ pax.estimate_fees(size="10", price="0.55", market_id="hadjar-f1-2026", side="yes")
115
+ ```
116
+
117
+ ## Audit log verification
118
+
119
+ Every platform event is hash-chained and batched into SHA-256 Merkle trees. The SDK checks everything locally:
120
+
121
+ ```python
122
+ from pax_api import PaxClient, verify_event, verify_merkle_proof, expected_proof_length
123
+
124
+ pax = PaxClient()
125
+ result = pax.verify_audit_event(1866215)
126
+ print(result["ok"], result["checks"])
127
+ # checks: event_hash (sha256(prev_event_hash + canonical)), same_event,
128
+ # seq_in_batch, server_length_agrees, merkle (incl. proof length)
129
+
130
+ # Low level
131
+ proof = pax.audit_proof(1866215)["data"]
132
+ n = proof["batch"]["last_seq"] - proof["batch"]["first_seq"] + 1
133
+ verify_merkle_proof(proof["event_hash"], proof["batch"]["merkle_root"],
134
+ proof["merkle_proof"], expected_proof_length(n))
135
+ ```
136
+
137
+ `verify_merkle_proof` requires `expected_length`: a proof with any other number of siblings is rejected, so an interior node cannot pass as a leaf. A root read from the same API proves internal consistency; for an independent check pass the anchored root (`pax.audit_anchor(batch_num)`) as `root=`.
138
+
139
+ ## WebSocket streams
140
+
141
+ See `examples/03_websocket.py` and `PaxWSClient`.
142
+
143
+ ## Error handling
144
+
145
+ Every response error becomes a typed exception:
146
+
147
+ ```python
148
+ from pax_api import (
149
+ PaxClient,
150
+ PaxRateLimitError,
151
+ PaxReadOnlyModeError,
152
+ PaxValidationError,
153
+ PaxWrongEnvKeyError,
154
+ PaxError, # base class — catch-all
155
+ )
156
+
157
+ try:
158
+ pax.place_order(...)
159
+ except PaxRateLimitError as e:
160
+ time.sleep(e.retry_after or 5)
161
+ except PaxValidationError as e:
162
+ print(f"Bad request: {e.details}")
163
+ except PaxReadOnlyModeError:
164
+ print("Trading paused by ops")
165
+ except PaxWrongEnvKeyError:
166
+ print("Wrong environment key")
167
+ except PaxError as e:
168
+ print(f"[{e.code}] {e.message} (request_id={e.request_id})")
169
+ ```
170
+
171
+ ## Automatic retry
172
+
173
+ Built-in exponential backoff on `429`, `500`, `502`, `504`. `Retry-After` header respected on rate limits. Each mutating call gets one `Idempotency-Key`, reused by every retry of that call; `place_order` also fixes its `client_order_id` before the first attempt, so a retry can never place a second order.
174
+
175
+ ```python
176
+ pax = PaxClient(api_key=key, max_retries=5)
177
+ # max_retries=1 disables retries
178
+ ```
179
+
180
+ ## Base URL
181
+
182
+ The gateway is `https://api.predictasiax.com`; methods add the `/v1/...` path themselves. A `base_url` ending in `/v1` is accepted and normalised. Sandbox and production share the host: sandbox is a tier on the key (`tier=self_serve`), with per-order and per-day caps.
183
+
184
+ ## Applications (progressive trust)
185
+
186
+ Move from sandbox → trade-capped → trade-full by submitting an application:
187
+
188
+ ```python
189
+ res = pax.apply(track="self_serve", org="my-org", email="team@my-org.io")
190
+ print(res["data"]["application_code"]) # save this
191
+
192
+ status = pax.get_application(res["data"]["application_code"])
193
+ print(status["data"]["status"]) # submitted → in_review → approved / declined
194
+ ```
195
+
196
+ ## Development
197
+
198
+ ```bash
199
+ git clone https://github.com/predictasiax/pax-python-sdk
200
+ cd pax-python-sdk
201
+ pip install -e ".[dev]"
202
+ pytest # run all tests
203
+ ruff check src tests # lint
204
+ mypy src # type-check
205
+ ```
206
+
207
+ ## Links
208
+
209
+ - [OpenAPI spec](https://docs.predictasiax.com/openapi)
210
+ - [AsyncAPI (WebSocket) spec](https://docs.predictasiax.com/asyncapi)
211
+ - [Auth guide](https://docs.predictasiax.com/auth)
212
+ - [Verify (public Merkle verifier)](https://docs.predictasiax.com/verify)
213
+ - [Error codes](https://docs.predictasiax.com/errors)
214
+ - [Rate limits](https://docs.predictasiax.com/rate-limits)
215
+ - [FAQ](https://docs.predictasiax.com/faq)
216
+ - [Changelog](https://docs.predictasiax.com/changelog)
217
+ - [API Terms](https://docs.predictasiax.com/api-terms)
218
+
219
+ ## License
220
+
221
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,181 @@
1
+ # pax-api — Official Python SDK for PredictAsiaX
2
+
3
+ REST + WebSocket client for the PredictAsiaX API gateway (`https://api.predictasiax.com`).
4
+
5
+ **Version 3.0.0** · MIT license · Python 3.8+ · [Changelog](CHANGELOG.md)
6
+
7
+ - **Docs**: https://docs.predictasiax.com
8
+ - **Verify**: https://docs.predictasiax.com/verify — public audit-log verifier
9
+ - **Sandbox key (anonymous)**: `POST /v1/sandbox-keys`
10
+ - **Support**: support@predictasiax.com
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ pip install --upgrade pax-api
16
+ ```
17
+
18
+ ## Quickstart
19
+
20
+ ```python
21
+ from pax_api import PaxClient
22
+
23
+ # Public endpoints need no key
24
+ pax = PaxClient()
25
+ print(pax.audit_status()["data"]["events"]["total"])
26
+ print(pax.get_orderbook("hadjar-f1-2026"))
27
+
28
+ # Mint a sandbox key (the api_key is shown once — store it)
29
+ key = pax.mint_sandbox_key(org_name="my-app")["data"]["api_key"]
30
+
31
+ pax = PaxClient(api_key=key) # sent as Authorization: Bearer sk_live_...
32
+ print(pax.get_balance())
33
+ print(pax.get_positions())
34
+ ```
35
+
36
+ ## Credentials
37
+
38
+ | Mode | Constructor | Sent on the wire |
39
+ |------|-------------|------------------|
40
+ | API key | `PaxClient(api_key="sk_live_...")` | `Authorization: Bearer sk_live_...` |
41
+ | HMAC signing | `PaxClient(api_key="sk_live_...", key_id="api_...")` | `PAX-ADDRESS`, `PAX-TIMESTAMP`, `PAX-NONCE`, `PAX-SIGNATURE` (no key) |
42
+ | Session / OAuth | `PaxClient(bearer_token="...")` | `Authorization: Bearer ...` |
43
+
44
+ HMAC signature (what the gateway verifies):
45
+
46
+ ```text
47
+ canonical = timestamp + "\n" + nonce + "\n" + METHOD + "\n" + path_with_query + "\n" + body
48
+ signature = base64(HMAC-SHA256(key = the full sk_live_ key, msg = canonical))
49
+ ```
50
+
51
+ `timestamp` is Unix seconds (accepted window ±300 s), `nonce` is single-use, `path_with_query` includes `/v1` and the query string. The SDK signs every attempt afresh, retries included. `pax_api.auth.sign_request` is exported if you need the headers yourself.
52
+
53
+ ## Trading
54
+
55
+ ```python
56
+ pax = PaxClient(api_key="sk_live_...", key_id="api_...")
57
+
58
+ order = pax.place_order(market_id="hadjar-f1-2026", side="yes", price="0.05", size="10")
59
+ pax.get_orders(status="open")
60
+ pax.cancel_order(order_id)
61
+ pax.cancel_all_orders(market_id="hadjar-f1-2026")
62
+
63
+ pax.place_orders_batch([
64
+ {"market_id": "hadjar-f1-2026", "side": "yes", "price": "0.04", "size": "5"},
65
+ {"market_id": "hadjar-f1-2026", "side": "no", "price": "0.90", "size": "5"},
66
+ ])
67
+ ```
68
+
69
+ `place_order` is a limit BUY of the chosen outcome (`side="yes"` or `"no"`), price 0.01–0.99.
70
+
71
+ ## Fee estimate
72
+
73
+ ```python
74
+ pax.estimate_fees(size="10", price="0.55", market_id="hadjar-f1-2026", side="yes")
75
+ ```
76
+
77
+ ## Audit log verification
78
+
79
+ Every platform event is hash-chained and batched into SHA-256 Merkle trees. The SDK checks everything locally:
80
+
81
+ ```python
82
+ from pax_api import PaxClient, verify_event, verify_merkle_proof, expected_proof_length
83
+
84
+ pax = PaxClient()
85
+ result = pax.verify_audit_event(1866215)
86
+ print(result["ok"], result["checks"])
87
+ # checks: event_hash (sha256(prev_event_hash + canonical)), same_event,
88
+ # seq_in_batch, server_length_agrees, merkle (incl. proof length)
89
+
90
+ # Low level
91
+ proof = pax.audit_proof(1866215)["data"]
92
+ n = proof["batch"]["last_seq"] - proof["batch"]["first_seq"] + 1
93
+ verify_merkle_proof(proof["event_hash"], proof["batch"]["merkle_root"],
94
+ proof["merkle_proof"], expected_proof_length(n))
95
+ ```
96
+
97
+ `verify_merkle_proof` requires `expected_length`: a proof with any other number of siblings is rejected, so an interior node cannot pass as a leaf. A root read from the same API proves internal consistency; for an independent check pass the anchored root (`pax.audit_anchor(batch_num)`) as `root=`.
98
+
99
+ ## WebSocket streams
100
+
101
+ See `examples/03_websocket.py` and `PaxWSClient`.
102
+
103
+ ## Error handling
104
+
105
+ Every response error becomes a typed exception:
106
+
107
+ ```python
108
+ from pax_api import (
109
+ PaxClient,
110
+ PaxRateLimitError,
111
+ PaxReadOnlyModeError,
112
+ PaxValidationError,
113
+ PaxWrongEnvKeyError,
114
+ PaxError, # base class — catch-all
115
+ )
116
+
117
+ try:
118
+ pax.place_order(...)
119
+ except PaxRateLimitError as e:
120
+ time.sleep(e.retry_after or 5)
121
+ except PaxValidationError as e:
122
+ print(f"Bad request: {e.details}")
123
+ except PaxReadOnlyModeError:
124
+ print("Trading paused by ops")
125
+ except PaxWrongEnvKeyError:
126
+ print("Wrong environment key")
127
+ except PaxError as e:
128
+ print(f"[{e.code}] {e.message} (request_id={e.request_id})")
129
+ ```
130
+
131
+ ## Automatic retry
132
+
133
+ Built-in exponential backoff on `429`, `500`, `502`, `504`. `Retry-After` header respected on rate limits. Each mutating call gets one `Idempotency-Key`, reused by every retry of that call; `place_order` also fixes its `client_order_id` before the first attempt, so a retry can never place a second order.
134
+
135
+ ```python
136
+ pax = PaxClient(api_key=key, max_retries=5)
137
+ # max_retries=1 disables retries
138
+ ```
139
+
140
+ ## Base URL
141
+
142
+ The gateway is `https://api.predictasiax.com`; methods add the `/v1/...` path themselves. A `base_url` ending in `/v1` is accepted and normalised. Sandbox and production share the host: sandbox is a tier on the key (`tier=self_serve`), with per-order and per-day caps.
143
+
144
+ ## Applications (progressive trust)
145
+
146
+ Move from sandbox → trade-capped → trade-full by submitting an application:
147
+
148
+ ```python
149
+ res = pax.apply(track="self_serve", org="my-org", email="team@my-org.io")
150
+ print(res["data"]["application_code"]) # save this
151
+
152
+ status = pax.get_application(res["data"]["application_code"])
153
+ print(status["data"]["status"]) # submitted → in_review → approved / declined
154
+ ```
155
+
156
+ ## Development
157
+
158
+ ```bash
159
+ git clone https://github.com/predictasiax/pax-python-sdk
160
+ cd pax-python-sdk
161
+ pip install -e ".[dev]"
162
+ pytest # run all tests
163
+ ruff check src tests # lint
164
+ mypy src # type-check
165
+ ```
166
+
167
+ ## Links
168
+
169
+ - [OpenAPI spec](https://docs.predictasiax.com/openapi)
170
+ - [AsyncAPI (WebSocket) spec](https://docs.predictasiax.com/asyncapi)
171
+ - [Auth guide](https://docs.predictasiax.com/auth)
172
+ - [Verify (public Merkle verifier)](https://docs.predictasiax.com/verify)
173
+ - [Error codes](https://docs.predictasiax.com/errors)
174
+ - [Rate limits](https://docs.predictasiax.com/rate-limits)
175
+ - [FAQ](https://docs.predictasiax.com/faq)
176
+ - [Changelog](https://docs.predictasiax.com/changelog)
177
+ - [API Terms](https://docs.predictasiax.com/api-terms)
178
+
179
+ ## License
180
+
181
+ MIT — see [LICENSE](LICENSE).
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pax-api"
7
- version = "2.5.1"
7
+ version = "3.0.0"
8
8
  description = "Official Python SDK for the PredictAsiaX Trader Track API — Web3-native prediction markets"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -12,7 +12,7 @@ license = { text = "MIT" }
12
12
  authors = [
13
13
  { name = "PredictAsiaX", email = "support@predictasiax.com" },
14
14
  ]
15
- keywords = ["predictasiax", "pax", "prediction-market", "trading-api", "web3", "hmac", "polymarket-compatible"]
15
+ keywords = ["predictasiax", "pax", "prediction-market", "trading-api", "web3", "hmac"]
16
16
  classifiers = [
17
17
  "Development Status :: 4 - Beta",
18
18
  "Intended Audience :: Developers",
@@ -61,6 +61,9 @@ pax_api = ["py.typed"]
61
61
  line-length = 120
62
62
  target-version = "py38"
63
63
 
64
+ [tool.ruff.lint]
65
+ select = ["E", "F"]
66
+
64
67
  [tool.mypy]
65
68
  python_version = "3.8"
66
69
  strict = true
@@ -4,31 +4,30 @@ Web3-native prediction market REST + WebSocket API client.
4
4
  Homepage: https://predictasiax.com/developer
5
5
  Docs: https://docs.predictasiax.com
6
6
 
7
- Quick start (anonymous sandbox mint in 30 sec):
7
+ Quick start:
8
8
  >>> from pax_api import PaxClient
9
- >>> boot = PaxClient(api_key="anonymous")
10
- >>> key = boot.mint_sandbox_key(org_name="my-app")
11
- >>> print(key["api_key"]) # sk_live_..., shown ONCE — save it
12
- >>> client = PaxClient(api_key=key["api_key"])
13
- >>> client.list_markets(category="crypto", limit=10)
9
+ >>> PaxClient().audit_status() # public, no key
10
+ >>> key = PaxClient().mint_sandbox_key(org_name="my-app")
11
+ >>> pax = PaxClient(api_key=key["data"]["api_key"]) # Authorization: Bearer
12
+ >>> pax.get_balance()
14
13
 
15
- For HMAC signing (production trading bots):
16
- >>> client = PaxClient(
17
- ... api_key="sk_live_...",
18
- ... secret="<hex-secret>",
19
- ... passphrase="<passphrase>",
20
- ... )
21
- >>> client.place_order(market_id="m_...", outcome_id="yes",
22
- ... side="buy", order_type="market", size="100")
14
+ HMAC request signing (the key never leaves your machine):
15
+ >>> pax = PaxClient(api_key="sk_live_...", key_id="api_...")
16
+ >>> pax.place_order(market_id="...", side="yes", price="0.42", size="10")
23
17
 
24
- Environment model: sandbox is a *tier* on the key (tier=self_serve, $10/$100
25
- caps), not a separate host. Same prefix, same URL — promote to production by
26
- upgrading the key's tier.
18
+ Offline audit verification:
19
+ >>> PaxClient().verify_audit_event(1866215)["ok"]
27
20
  """
28
21
 
29
- __version__ = "2.5.1"
22
+ __version__ = "3.0.0"
30
23
 
31
24
  from pax_api.client import PaxClient # noqa: E402
25
+ from pax_api.audit import ( # noqa: E402
26
+ expected_proof_length,
27
+ verify_event,
28
+ verify_event_hash,
29
+ verify_merkle_proof,
30
+ )
32
31
  from pax_api.ws_client import PaxWSClient # noqa: E402
33
32
  from pax_api.errors import ( # noqa: E402
34
33
  PaxError,
@@ -56,5 +55,9 @@ __all__ = [
56
55
  "PaxReadOnlyModeError",
57
56
  "PaxSandboxOnlyError",
58
57
  "PaxWrongEnvKeyError",
58
+ "expected_proof_length",
59
+ "verify_event",
60
+ "verify_event_hash",
61
+ "verify_merkle_proof",
59
62
  "__version__",
60
63
  ]
@@ -0,0 +1,132 @@
1
+ """Offline verification of the PAX public audit log.
2
+
3
+ Three checks, all local (no trust in the SDK transport needed):
4
+
5
+ 1. Event hash — ``event_hash == sha256_hex(utf8(prev_event_hash + canonical))``
6
+ where ``canonical`` is returned verbatim by ``GET /v1/audit/events/{seq}``.
7
+ 2. Merkle inclusion — the leaf is the event's ``event_hash``; each level hashes
8
+ the sorted pair of RAW 32-byte digests with SHA-256 (not keccak256, not the
9
+ hex strings); an odd level duplicates its last node.
10
+ 3. Proof length — a valid proof for a batch of ``n`` leaves has exactly
11
+ ``expected_proof_length(n)`` siblings. Rejecting any other length stops an
12
+ interior node from being presented as a leaf (second-preimage).
13
+
14
+ A root fetched from the same API proves only internal consistency. Compare
15
+ ``merkle_root`` with the batch's external anchor (``GET /v1/audit/anchor/{n}``)
16
+ for an independent check.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import re
24
+ from typing import Any, Dict, List, Mapping, Optional, Sequence
25
+
26
+ _HEX32 = re.compile(r"^[0-9a-fA-F]{64}$")
27
+
28
+
29
+ def _is_hex32(value: Any) -> bool:
30
+ return isinstance(value, str) and bool(_HEX32.match(value))
31
+
32
+
33
+ def expected_proof_length(leaf_count: int) -> int:
34
+ """Number of siblings in a valid proof for a batch of ``leaf_count`` leaves."""
35
+ n = int(leaf_count)
36
+ if n < 1:
37
+ raise ValueError("leaf_count must be >= 1")
38
+ depth = 0
39
+ while n > 1:
40
+ n = (n + 1) // 2
41
+ depth += 1
42
+ return depth
43
+
44
+
45
+ def verify_merkle_proof(leaf: str, root: str, proof: Sequence[str], expected_length: int) -> bool:
46
+ """Verify a Merkle inclusion proof.
47
+
48
+ Args:
49
+ leaf: The event's ``event_hash`` (64 hex chars).
50
+ root: The batch ``merkle_root`` (64 hex chars).
51
+ proof: Sibling hashes, leaf level first (each 64 hex chars).
52
+ expected_length: ``expected_proof_length(leaf_count)`` for the batch.
53
+ Required: a proof of any other length is rejected.
54
+
55
+ Returns:
56
+ True only if every element is a 32-byte hex digest, the proof has
57
+ exactly ``expected_length`` siblings, and it folds to ``root``.
58
+ """
59
+ if not (_is_hex32(leaf) and _is_hex32(root)):
60
+ return False
61
+ if isinstance(proof, (str, bytes)) or len(proof) != int(expected_length):
62
+ return False
63
+ if not all(_is_hex32(s) for s in proof):
64
+ return False
65
+ h = bytes.fromhex(leaf)
66
+ for sibling in proof:
67
+ s = bytes.fromhex(sibling)
68
+ a, b = (h, s) if h <= s else (s, h)
69
+ h = hashlib.sha256(a + b).digest()
70
+ return h.hex() == root.lower()
71
+
72
+
73
+ def verify_event_hash(event: Mapping[str, Any]) -> bool:
74
+ """Recompute ``event_hash`` from ``prev_event_hash`` + ``canonical``.
75
+
76
+ ``event`` is the ``data`` object of ``GET /v1/audit/events/{seq}``. Also
77
+ checks that the canonical string commits to the same ``seq``.
78
+ """
79
+ prev = event.get("prev_event_hash")
80
+ canonical = event.get("canonical")
81
+ expected = event.get("event_hash")
82
+ if not (_is_hex32(prev) and _is_hex32(expected) and isinstance(canonical, str)):
83
+ return False
84
+ try:
85
+ if int(json.loads(canonical).get("seq")) != int(event.get("seq")): # type: ignore[arg-type]
86
+ return False
87
+ except (ValueError, TypeError, AttributeError):
88
+ return False
89
+ digest = hashlib.sha256((str(prev).lower() + canonical).encode("utf-8")).hexdigest()
90
+ return digest == str(expected).lower()
91
+
92
+
93
+ def verify_event(event: Mapping[str, Any], proof: Mapping[str, Any], root: Optional[str] = None) -> Dict[str, Any]:
94
+ """Run all three checks for one event.
95
+
96
+ Args:
97
+ event: ``data`` of ``GET /v1/audit/events/{seq}``.
98
+ proof: ``data`` of ``GET /v1/audit/proof/{seq}``.
99
+ root: Root to verify against. Defaults to ``proof["batch"]["merkle_root"]``;
100
+ pass the externally anchored root for an independent check.
101
+
102
+ Returns:
103
+ ``{"ok": bool, "checks": {...}, "reason": str | None}``.
104
+ """
105
+ checks: Dict[str, bool] = {}
106
+ batch = proof.get("batch") or {}
107
+ seq: Any = event.get("seq")
108
+ checks["event_hash"] = verify_event_hash(event)
109
+ checks["same_event"] = (
110
+ proof.get("seq") == seq and str(proof.get("event_hash", "")).lower() == str(event.get("event_hash", "")).lower()
111
+ )
112
+ try:
113
+ first, last = int(batch["first_seq"]), int(batch["last_seq"])
114
+ leaf_count = last - first + 1
115
+ exp_len = expected_proof_length(leaf_count)
116
+ checks["seq_in_batch"] = first <= int(seq) <= last
117
+ except (KeyError, TypeError, ValueError):
118
+ return {"ok": False, "checks": checks, "reason": "proof.batch is missing first_seq/last_seq"}
119
+ server_len = proof.get("expected_proof_length")
120
+ checks["server_length_agrees"] = server_len is None or int(server_len) == exp_len
121
+ merkle_proof: List[str] = list(proof.get("merkle_proof") or [])
122
+ checks["merkle"] = verify_merkle_proof(
123
+ str(event.get("event_hash", "")), root or str(batch.get("merkle_root", "")), merkle_proof, exp_len
124
+ )
125
+ failed = [k for k, v in checks.items() if not v]
126
+ return {
127
+ "ok": not failed,
128
+ "checks": checks,
129
+ "leaf_count": leaf_count,
130
+ "expected_proof_length": exp_len,
131
+ "reason": ("failed: " + ", ".join(failed)) if failed else None,
132
+ }