@predictasiax/api 2.4.0 → 3.0.0

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,88 @@
1
1
  # @predictasiax/api Changelog
2
2
 
3
+ ## v3.0.0 — 2026-11-23
4
+
5
+ 2.x could not authenticate against the gateway. This release aligns the SDK with what `https://api.predictasiax.com` actually serves.
6
+
7
+ ### Fixed
8
+ - Default base URL is the origin `https://api.predictasiax.com`. 2.x used `.../v1` and then added `/v1` again, so every call hit `/v1/v1/...` (404). A `baseUrl` ending in `/v1` is now normalised.
9
+ - API keys are sent as `Authorization: Bearer sk_live_...`. 2.x sent `X-Api-Key`, which the gateway ignores.
10
+ - HMAC signing matches the gateway: `PAX-ADDRESS` (key id), `PAX-TIMESTAMP` (seconds), `PAX-NONCE`, `PAX-SIGNATURE` = base64 HMAC-SHA256 keyed with the full `sk_live_` key over `timestamp\nnonce\nMETHOD\npathWithQuery\nbody`, re-signed on every attempt.
11
+ - `orders.place` sends the fields the gateway requires (`side` yes/no, `price`, `size`, `client_order_id`); `client_order_id` is generated once per call when omitted, so a retry cannot place a second order. Idempotency-Key also covers DELETE.
12
+ - Every method targets a route the gateway serves (see Changed / Removed).
13
+
14
+ ### Security
15
+ - `AuditResource.verifyProof(leaf, root, proof, expectedLength)` / `verifyProofAsync` now require the expected proof length and 32-byte hex elements. Without it, an interior node plus a shortened proof verified as a leaf (second-preimage).
16
+ - New `expectedProofLength`, `AuditResource.verifyEventHash` (recomputes `sha256(prev_event_hash + canonical)`), `AuditResource.verifyEvent`, and `pax.audit.verify(seq)` running every check.
17
+ - PAX-* / POLY-* signing headers added to the caller-protected header list.
18
+
19
+ ### Changed
20
+ - Credentials: `{ apiKey }`, `{ apiKey, keyId }` for HMAC, or `{ bearerToken }`; no credentials allowed for public endpoints. `secret` / `passphrase` throw with a migration hint.
21
+ - `account.retrieve()` → `account.balance()` (`/v1/balance`; `retrieve` kept as an alias); `account.positions()` → `/v1/positions`; new `account.portfolio()`.
22
+ - `orders.list()` → `GET /v1/orders` (returns `{ orders, count }`); new `orders.history()`; `cancelBatch` → `cancelAll({ marketId })`.
23
+ - `markets.orderbook(id)` → `/v1/markets/{id}/orderbook`; `candles` → `priceHistory(id, { range })`; new `categories()`, `resolution()`; `markets.create` → `POST /v1/composer/markets` with the composer fields; `markets.list` reads the gateway's `data.markets` / `data.page.next_cursor`.
24
+ - `sandboxKeys.mint({ orgName, contactHandle })` (was `contactEmail`, ignored by the gateway).
25
+ - Audit types use the live `*_ms` timestamp fields; `getAnchor` returns `AuditAnchor`.
26
+
27
+ ### Removed (no gateway route)
28
+ - `markets.trades`, `account.trades`, the `keys` resource, `settle.adminBuilder`, `settle.adminCreator`, `buildMessage` (replaced by `buildCanonical`).
29
+
30
+ ## v2.5.1 — 2026-10-31
31
+
32
+ **Bugfix: Merkle inclusion-proof verifier now hashes raw bytes, not hex strings —
33
+ and `verifyProof()` no longer crashes under native ESM.**
34
+
35
+ ### Fixed
36
+ - `Audit.verifyProof()` / `verifyProofAsync()` previously hashed the 64-character
37
+ hex **strings** of each digest (UTF-8 bytes), instead of decoding each hex
38
+ digest to its raw 32 bytes first. The publisher builds `merkle_root` as a
39
+ sorted-pair SHA-256 over the **raw 32-byte digests**, so the SDK computed a
40
+ different root and rejected every authentic proof returned by
41
+ `/v1/audit/proof/{seq}`. Fail-closed — the bug could only reject valid proofs,
42
+ never accept a forged one, so no verification was ever falsely passed.
43
+ - Both code paths now decode hex to raw bytes, sort the pair by byte value,
44
+ concat the raw bytes, then SHA-256 — bit-identical to the publisher and to
45
+ OpenZeppelin's `bytes32` `MerkleProof.verify`. Proofs from the live API now
46
+ verify locally.
47
+ - `verifyProof()` (the synchronous variant) previously called `require("crypto")`,
48
+ which throws `Dynamic require of "crypto" is not supported` in the ESM build
49
+ (`dist/index.js`) — so every ESM consumer calling it crashed rather than
50
+ verifying. It is now **isomorphic**: it uses Node's native SHA-256 when a
51
+ synchronous `require` is available (CommonJS) and otherwise a self-contained,
52
+ dependency-free SHA-256, so it runs unchanged in Node (CJS + ESM), browsers,
53
+ Deno, Bun and edge runtimes. The fallback is pinned by tests to be byte-identical
54
+ to `node:crypto` (fixed vectors + 500 random inputs) and to reconstruct the
55
+ live anchored root. No static `node:` imports were added — the package stays
56
+ safe to import in the browser.
57
+
58
+ ### Compatibility
59
+ - Verifier-side only. No change to request signing, wire format, response
60
+ envelopes, or any other resource. Zero new runtime dependencies. Matches
61
+ Python SDK `pax-api` 2.5.1.
62
+
63
+ ## v2.5.0 — 2026-09-26
64
+
65
+ **Auth positioning correction + API 2.6.1 compatibility notice.** Content-only release — no wire-format changes vs v2.4.0. All 61 tests unchanged.
66
+
67
+ ### Compatibility
68
+ - **Compatible with** PredictAsiaX Trader Track API **v2.5.0 → v2.6.1** (69 paths / 76 operations, current REST surface at docs.predictasiax.com/openapi).
69
+ - No breaking changes since v2.2.0. All resources added in v2.3.0 / v2.4.0 remain shipped and stable in v2.5.0.
70
+
71
+ ### Changed — README auth positioning
72
+ - Repositioned **Bearer `sk_live_*` as the standard path** (formerly listed as "Option 1: API Key" with `X-Api-Key`-first framing). Bearer is what 100% of standard integrations should use.
73
+ - **HMAC section demoted to enterprise-only** — clarified that HMAC signing requires ops provisioning of the signing secret and that submitting HMAC credentials without provisioning returns `401 AUTH_INVALID`. Standard integrations should not attempt HMAC.
74
+ - **OAuth 2.1 + PKCE** promoted to a proper `#2` section (was buried at `#3` "Bearer token — browser / mobile").
75
+ - Corrected package description away from "HMAC 5-header signing" as headline feature → Bearer-first framing.
76
+
77
+ ### Notes on wire format (unchanged in this release)
78
+ - HMAC header prefix on-wire is still `POLY_*` — backend accepts this as a legacy alias for the canonical `PAX_*` prefix (which the docs and Portal both document as the canonical form). A future SDK release will emit `PAX_*` by default; both prefixes will be accepted server-side indefinitely for backward compat.
79
+ - `X-Api-Key` header is still emitted alongside `Authorization: Bearer` for the api-key auth path — legacy compat, no plan to remove.
80
+
81
+ ### CHANGELOG gap acknowledgment
82
+ v2.3.0 and v2.4.0 shipped on npm without changelog entries. The additive resource surface accumulated in those versions (Merkle audit resource, batch orders, fee estimate — see v2.1.0 / v2.2.0 above for the surface added just before that gap) remains stable in v2.5.0.
83
+
84
+ ---
85
+
3
86
  ## v2.2.0 — 2026-09-05
4
87
 
5
88
  **Trust Layer — public Merkle verifier.**
package/README.md CHANGED
@@ -1,17 +1,15 @@
1
1
  # @predictasiax/api
2
2
 
3
- Official TypeScript / JavaScript SDK for the **PredictAsiaX Trader Track API** — Web3-native prediction markets, REST + WebSocket, Polymarket-compatible HMAC signing.
3
+ Official TypeScript / JavaScript SDK for the PredictAsiaX API gateway (`https://api.predictasiax.com`): REST + WebSocket, Bearer or HMAC auth, and an offline verifier for the public audit log.
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/@predictasiax/api.svg)](https://www.npmjs.com/package/@predictasiax/api)
6
6
  [![docs](https://img.shields.io/badge/docs-docs.predictasiax.com-blue)](https://docs.predictasiax.com)
7
7
 
8
- - **Fully typed.** Every response is a real TypeScript type — no `data as any`.
9
- - **Resource-oriented.** `pax.markets.list()`, `pax.orders.place()`, `pax.account.retrieve()`.
10
- - **Auto-pagination.** `for await (const m of pax.markets.list())` — the SDK walks pages for you.
11
- - **Isomorphic.** Node 18+, Bun, Deno, Cloudflare Workers, Vercel Edge, browsers.
12
- - **Retries + backoff** built-in for 429 / 5xx, respects `Retry-After`.
13
- - **AbortSignal, timeout, idempotency-key** on every method.
14
- - **Security-first.** HTTPS-only, auto-idempotency for real trading, response size cap, CRLF header guard, no hardcoded credentials — full posture in [SECURITY.md](./SECURITY.md).
8
+ - **Resource-oriented.** `pax.markets.list()`, `pax.orders.place()`, `pax.account.balance()`, `pax.audit.verify()`.
9
+ - **Isomorphic.** Node 18+, Bun, Deno, Cloudflare Workers, Vercel Edge, browsers (opt-in).
10
+ - **Retries + backoff** for 429 / 5xx, respects `Retry-After`; one Idempotency-Key per call across retries.
11
+ - **Security-first.** HTTPS-only, response size cap, CRLF header guard, protected auth headers — see [SECURITY.md](./SECURITY.md).
12
+ - [Changelog](./CHANGELOG.md) — 3.0.0 is required to talk to the current gateway.
15
13
 
16
14
  ---
17
15
 
@@ -19,13 +17,9 @@ Official TypeScript / JavaScript SDK for the **PredictAsiaX Trader Track API**
19
17
 
20
18
  ```bash
21
19
  npm install @predictasiax/api
22
- # or
23
- pnpm add @predictasiax/api
24
- # or
25
- bun add @predictasiax/api
26
20
  ```
27
21
 
28
- Node.js **≥ 18** required (native `fetch`). Also works in Bun 1.0+, Deno, Cloudflare Workers, Vercel Edge, and modern browsers.
22
+ Node.js 18+ (native `fetch`). Also Bun, Deno, Cloudflare Workers, Vercel Edge, modern browsers.
29
23
 
30
24
  ---
31
25
 
@@ -34,27 +28,19 @@ Node.js **≥ 18** required (native `fetch`). Also works in Bun 1.0+, Deno, Clou
34
28
  ```ts
35
29
  import { PaxClient } from "@predictasiax/api";
36
30
 
37
- // 1. Mint an anonymous sandbox key (30 sec, no email, tier=self_serve)
38
- const bootstrap = new PaxClient({ apiKey: "anonymous" });
39
- const key = await bootstrap.sandboxKeys.mint({ orgName: "my-app" });
40
- console.log("Save this once:", key.api_key); // sk_live_...
41
-
42
- // 2. Use the key
43
- const pax = new PaxClient({ apiKey: key.api_key });
44
-
45
- // Discovery
46
- const templates = await pax.templates.list({ category: "crypto", marketType: "fast" });
47
- const markets = await pax.markets.list({ category: "crypto", limit: 5 });
48
-
49
- // Trade (capped at $10/order + $100/day on self_serve tier)
50
- const order = await pax.orders.place({
51
- marketId: markets.data[0].id,
52
- outcomeId: markets.data[0].outcomes[0].id,
53
- side: "buy",
54
- orderType: "market",
55
- size: "10",
56
- });
57
- console.log("Filled:", order.id, order.avg_fill_price);
31
+ // Public endpoints need no key
32
+ const pub = new PaxClient();
33
+ console.log(await pub.audit.status());
34
+ console.log(await pub.markets.orderbook("hadjar-f1-2026"));
35
+
36
+ // Mint a sandbox key — the api_key is shown once, store it
37
+ const minted = await pub.sandboxKeys.mint({ orgName: "my-app" });
38
+
39
+ const pax = new PaxClient({ apiKey: minted.api_key }); // Authorization: Bearer sk_live_...
40
+ console.log(await pax.account.balance());
41
+ console.log(await pax.account.positions());
42
+
43
+ const order = await pax.orders.place({ marketId: "hadjar-f1-2026", side: "yes", price: "0.05", size: "10" });
58
44
  ```
59
45
 
60
46
  More runnable examples: [`examples/`](./examples).
@@ -63,175 +49,91 @@ More runnable examples: [`examples/`](./examples).
63
49
 
64
50
  ## Authentication
65
51
 
66
- Three modes, auto-detected from your constructor arguments.
52
+ | Mode | Constructor | Sent on the wire |
53
+ |------|-------------|------------------|
54
+ | API key | `new PaxClient({ apiKey: "sk_live_..." })` | `Authorization: Bearer sk_live_...` |
55
+ | HMAC signing | `new PaxClient({ apiKey: "sk_live_...", keyId: "api_..." })` | `PAX-ADDRESS`, `PAX-TIMESTAMP`, `PAX-NONCE`, `PAX-SIGNATURE` (the key is not sent) |
56
+ | Session / OAuth | `new PaxClient({ bearerToken: "..." })` | `Authorization: Bearer ...` |
57
+ | None | `new PaxClient()` | public endpoints only |
67
58
 
68
- ### 1. API Key (`sk_live_*`, tier-flagged)
59
+ HMAC signature, exactly as the gateway verifies it:
69
60
 
70
- Simplest — good for read-only + basic trading. Capability is scoped by the
71
- `tier` flag on the key (`self_serve` for sandbox testing with $10/$100 caps;
72
- `verified` / `trade_capped` / `trade_full` / `genesis` / `partner` for
73
- production).
74
-
75
- ```ts
76
- const pax = new PaxClient({ apiKey: "sk_live_..." });
61
+ ```text
62
+ canonical = timestamp + "\n" + nonce + "\n" + METHOD + "\n" + pathWithQuery + "\n" + body
63
+ signature = base64(HMAC-SHA256(key = the full sk_live_ key, msg = canonical))
77
64
  ```
78
65
 
79
- Sent as `X-Api-Key` header (or `Authorization: Bearer` — both accepted).
80
- Tier-mismatched operations reject with `PaxWrongEnvKeyError`.
81
-
82
- ### 2. HMAC signing (Polymarket-compatible)
83
-
84
- Recommended for production trading — signature guards against replay and MITM.
85
-
86
- ```ts
87
- const pax = new PaxClient({
88
- apiKey: "sk_live_ABC",
89
- secret: "your-64-char-secret",
90
- passphrase: "your-passphrase",
91
- env: "production",
92
- });
93
- ```
66
+ `timestamp` is Unix seconds (window ±300 s), `nonce` is single-use, `pathWithQuery` includes `/v1` and the query string. The SDK re-signs every attempt, retries included. `signRequest()` and `buildCanonical()` are exported for custom transports.
94
67
 
95
- Sent as five `POLY_ACCESS_KEY` / `POLY_TIMESTAMP` / `POLY_PASSPHRASE` / `POLY_SIGNATURE` headers. Server accepts a ±30 s clock skew — sync your machine via NTP.
96
-
97
- ### 3. Bearer token (browser / mobile)
98
-
99
- Session-based, obtained via your own login flow.
100
-
101
- ```ts
102
- const pax = new PaxClient({ bearerToken: "eyJ...", env: "production" });
103
- ```
104
-
105
- Sent as `Authorization: Bearer <token>` header.
68
+ `secret` / `passphrase` from 2.x are not part of the API and now throw with a migration hint.
106
69
 
107
70
  ---
108
71
 
109
- ## Environments
72
+ ## Base URL
110
73
 
111
- All `env` values resolve to the same canonical origin — sandbox is a *tier*
112
- on the production API (`tier=self_serve` on the key), not a separate host.
113
- This lets you promote a sandbox integration to production by upgrading the
114
- key's tier — no code changes, no host switch.
115
-
116
- | `env` | Base URL |
117
- |--------------------------|---------------------------------------|
118
- | `production` (default) | `https://api.predictasiax.com/v1` |
119
- | `sandbox` | `https://api.predictasiax.com/v1` |
120
-
121
- Override completely with `baseUrl`. WebSocket: `wss://predictasiax.com/ws`
122
- for every env.
123
-
124
- Sandbox tier (`tier=self_serve`) enforces:
125
- - `$10` per-order notional cap
126
- - `$100` daily notional cap
127
- - Simulated fills at mid-price against live orderbook state
128
- - Same auth, same endpoints, same envelope shape as production
129
- - 30-day key expiry, refreshable via `pax.sandboxKeys.mint()`
130
- - 10× higher rate limits, 90-day key expiry
74
+ The default is `https://api.predictasiax.com`; resource methods add `/v1/...`. A `baseUrl` ending in `/v1` is normalised, so paths never double to `/v1/v1`. Sandbox and production share the host: sandbox is a tier on the key (`tier=self_serve`) with per-order and per-day caps. WebSocket: `wss://predictasiax.com/ws`.
131
75
 
132
76
  ---
133
77
 
134
78
  ## Resources
135
79
 
136
- Every REST endpoint lives on a resource object:
137
-
138
80
  ```ts
139
- pax.markets // discovery, candles, orderbook, public trades, creation
140
- pax.templates // parameterized market blueprints
141
- pax.orders // place / cancel / list your orders
142
- pax.account // balances, positions, your trade history
143
- pax.keys // programmatic key management
144
- pax.sandbox // faucet, reset, mock oracle
145
- pax.health() // top-level health check
81
+ // Markets
82
+ pax.markets.list({ category, q, limit, cursor }) // GET /v1/markets (paginated)
83
+ pax.markets.retrieve(id) // GET /v1/markets/{id}
84
+ pax.markets.categories() // GET /v1/markets/categories
85
+ pax.markets.orderbook(id) // GET /v1/markets/{id}/orderbook (public)
86
+ pax.markets.priceHistory(id, { range: "7d" }) // GET /v1/markets/{id}/price-history (public)
87
+ pax.markets.resolution(id) // GET /v1/markets/{id}/resolution (public)
88
+ pax.markets.create({ title, rulesText, resolutionRule, primarySourceUrl,
89
+ cutoffTimeMs, resolutionDeadlineMs }) // POST /v1/composer/markets
90
+ pax.templates.list() // GET /v1/markets/templates
91
+
92
+ // Orders — limit BUY of one outcome, price 0.01..0.99
93
+ pax.orders.place({ marketId, side: "yes", price, size }) // POST /v1/orders
94
+ pax.orders.placeBatch([...]) // POST /v1/orders/batch
95
+ pax.orders.list({ limit }) // GET /v1/orders
96
+ pax.orders.history({ limit, cursor }) // GET /v1/orders/history
97
+ pax.orders.cancel(orderId) // DELETE /v1/orders/{id}
98
+ pax.orders.cancelAll({ marketId }) // POST /v1/orders/cancel-all
99
+
100
+ // Account
101
+ pax.account.balance() // GET /v1/balance
102
+ pax.account.portfolio() // GET /v1/portfolio
103
+ pax.account.positions() // GET /v1/positions
104
+
105
+ // Fees, onboarding, revenue
106
+ pax.fees.estimate({ size, price, ... }) // GET /v1/fees/estimate
107
+ pax.sandboxKeys.mint({ orgName, contactHandle }) // POST /v1/sandbox-keys
108
+ pax.apply.create({ track, org, email }) // POST /v1/apply
109
+ pax.apply.retrieve("ba_...") // GET /v1/apply/{code}
110
+ pax.settle.me({ address }) // POST /v1/builders/me/settle
111
+ pax.grants.list() // GET /v1/grants
146
112
  ```
147
113
 
148
- <details>
149
- <summary><strong>Markets</strong></summary>
150
-
151
- ```ts
152
- // List — paginated, iterable
153
- for await (const m of pax.markets.list({ category: "crypto", status: "open" })) { ... }
114
+ ### Audit log verification
154
115
 
155
- // Single market
156
- const market = await pax.markets.retrieve("m_abc");
157
-
158
- // Create from template
159
- const created = await pax.markets.create({
160
- templateId: "crypto_price_binary_60s",
161
- params: { asset: "BTC", strike_pct: 0.5 },
162
- });
163
-
164
- // Candles
165
- const candles = await pax.markets.candles("m_abc", {
166
- outcomeId: "yes", interval: "1m", limit: 500,
167
- });
168
-
169
- // Orderbook L2
170
- const book = await pax.markets.orderbook("m_abc", { outcomeId: "yes", depth: 20 });
171
-
172
- // Public trade tape
173
- for await (const t of pax.markets.trades("m_abc", { limit: 100 })) { ... }
174
- ```
175
- </details>
176
-
177
- <details>
178
- <summary><strong>Orders + Account</strong></summary>
116
+ Every platform event is hash-chained and batched into SHA-256 Merkle trees. Verify locally:
179
117
 
180
118
  ```ts
181
- // Market order — fills immediately
182
- const filled = await pax.orders.place({
183
- marketId: "m_abc", outcomeId: "yes",
184
- side: "buy", orderType: "market", size: "10",
185
- }, { idempotencyKey: "ord-2026-08-10-abc" });
186
-
187
- // Limit order — GTC unless overridden
188
- const resting = await pax.orders.place({
189
- marketId: "m_abc", outcomeId: "yes",
190
- side: "buy", orderType: "limit", size: "10", price: "0.42",
191
- timeInForce: "GTC",
192
- });
193
-
194
- await pax.orders.cancel(resting.id);
195
-
196
- // Your orders + trades — paginated
197
- for await (const o of pax.orders.list({ status: "open" })) { ... }
198
- for await (const t of pax.account.trades({ limit: 100 })) { ... }
199
-
200
- // Balances + positions
201
- const account = await pax.account.retrieve();
202
- const positions = await pax.account.positions();
119
+ const r = await pub.audit.verify(1866215);
120
+ // r.ok, r.checks = { event_hash, same_event, seq_in_batch, server_length_agrees, merkle }
121
+
122
+ // Low level
123
+ import { AuditResource, expectedProofLength } from "@predictasiax/api";
124
+ const proof = await pub.audit.getProof(1866215);
125
+ const n = proof.batch.last_seq - proof.batch.first_seq + 1;
126
+ AuditResource.verifyProof(proof.event_hash, proof.batch.merkle_root, proof.merkle_proof, expectedProofLength(n));
127
+ AuditResource.verifyEventHash(await pub.audit.getEvent(1866215)); // sha256(prev_event_hash + canonical)
203
128
  ```
204
- </details>
205
129
 
206
- <details>
207
- <summary><strong>Keys + Sandbox</strong></summary>
208
-
209
- ```ts
210
- // Create a new key — secret is only returned here, store it now
211
- const { id, secret, scopes } = await pax.keys.create({
212
- name: "trader-bot", scopes: ["read", "trade"],
213
- });
214
-
215
- await pax.keys.list();
216
- await pax.keys.revoke(id);
217
-
218
- // Sandbox mint + Builder applications (anonymous, no auth required)
219
- const key = await pax.sandboxKeys.mint({ orgName: "my-app" });
220
- console.log("sk_live_ tier=self_serve:", key.api_key); // shown ONCE
221
-
222
- const app = await pax.apply.create({ track: "rfb-telegram-bot", org: "my-team" });
223
- if (app.auto_provisioned) console.log("Auto-approved:", app.api_key);
224
- else console.log("Pending review, code:", app.application_code);
225
-
226
- const status = await pax.apply.retrieve(app.application_code);
227
- ```
228
- </details>
130
+ `verifyProof` requires the expected proof length: 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 (`pub.audit.getAnchor(batchNum)`) as `root`.
229
131
 
230
132
  ---
231
133
 
232
134
  ## Pagination
233
135
 
234
- Every `list` method returns a `PagePromise<T>` that supports **three** ergonomic styles:
136
+ `pax.markets.list()` returns a `PagePromise<T>` that supports three styles:
235
137
 
236
138
  ```ts
237
139
  // (1) Async iterator — walks pages lazily. Best for large sets.
@@ -260,7 +162,7 @@ Every method accepts a second argument for per-request tuning:
260
162
 
261
163
  ```ts
262
164
  await pax.orders.place(
263
- { marketId, outcomeId, side: "buy", orderType: "market", size: "10" },
165
+ { marketId, side: "yes", price: "0.42", size: "10" },
264
166
  {
265
167
  idempotencyKey: "unique-request-id", // sent as HTTP header, dedupes retries
266
168
  signal: controller.signal, // AbortSignal — cancels in flight
@@ -280,22 +182,21 @@ Idempotency-Key is sent as a real HTTP header (`Idempotency-Key: ...`), the same
280
182
  Await gives you the unwrapped data:
281
183
 
282
184
  ```ts
283
- const account = await pax.account.retrieve();
284
- console.log(account.balances);
185
+ const balance = await pax.account.balance();
285
186
  ```
286
187
 
287
188
  If you need headers, status, or the request-id, use `.withResponse()`:
288
189
 
289
190
  ```ts
290
191
  const { data, response, requestId, status, headers } =
291
- await pax.account.retrieve().withResponse();
192
+ await pax.account.balance().withResponse();
292
193
  console.log(headers.get("x-ratelimit-remaining"));
293
194
  ```
294
195
 
295
196
  Or `.asResponse()` for the raw Response only:
296
197
 
297
198
  ```ts
298
- const raw = await pax.account.retrieve().asResponse();
199
+ const raw = await pax.account.balance().asResponse();
299
200
  ```
300
201
 
301
202
  ---
@@ -388,12 +289,12 @@ Features:
388
289
 
389
290
  | Runtime | REST | WebSocket | Notes |
390
291
  |-----------------------|:----:|:---------:|-------------------------------------|
391
- | Node.js 18+ | ✅ | ✅ | Uses `node:crypto` + `ws` package. |
392
- | Bun 1.0+ | ✅ | ✅ | Native fetch + WebSocket. |
393
- | Deno | ✅ | ✅ | Import via `npm:@predictasiax/api`. |
394
- | Cloudflare Workers | ✅ | ✅ | Uses WebCrypto + native WebSocket. |
395
- | Vercel Edge Runtime | ✅ | ✅ | Same as CF Workers. |
396
- | Modern browsers | ⚠️ | ✅ | Requires `dangerouslyAllowBrowser: true` — server keys should not ship to end-users. |
292
+ | Node.js 18+ | Yes | Yes | Uses `node:crypto` + `ws` package. |
293
+ | Bun 1.0+ | Yes | Yes | Native fetch + WebSocket. |
294
+ | Deno | Yes | Yes | Import via `npm:@predictasiax/api`. |
295
+ | Cloudflare Workers | Yes | Yes | Uses WebCrypto + native WebSocket. |
296
+ | Vercel Edge Runtime | Yes | Yes | Same as CF Workers. |
297
+ | Modern browsers | Opt-in | Yes | Requires `dangerouslyAllowBrowser: true` — server keys should not ship to end-users. |
397
298
 
398
299
  Inject a custom `fetch` for proxies or non-standard runtimes:
399
300
 
@@ -409,31 +310,24 @@ const pax = new PaxClient({
409
310
 
410
311
  ## TypeScript
411
312
 
412
- TypeScript **≥ 5.0** recommended. The SDK ships full `.d.ts` files. Every response type is exported:
413
-
414
- ```ts
415
- import type {
416
- Market, Order, Trade, Candle, Orderbook, Account, Position,
417
- MarketTemplate, ApiKey, FaucetResult, HealthStatus,
418
- } from "@predictasiax/api";
419
- ```
313
+ TypeScript 5.0+ recommended; full `.d.ts` files ship with the package. Audit types (`AuditEvent`, `MerkleProof`, `AuditBatch`, `AuditAnchor`, `AuditVerification`) are exported.
420
314
 
421
315
  ---
422
316
 
423
317
  ## Security
424
318
 
425
- The SDK carries HMAC secrets and signs real-money trades — full threat model and guarantees live in [SECURITY.md](./SECURITY.md). Highlights:
319
+ The SDK carries API keys and signs real-money trades — full threat model and guarantees live in [SECURITY.md](./SECURITY.md). Highlights:
426
320
 
427
321
  - **HTTPS-only** — `http://` is rejected on non-loopback hosts; `redirect: manual` refuses server-initiated downgrades.
428
- - **Auto Idempotency-Key** on every POST / PUT / PATCH — same key reused across retries, so a timed-out order is never placed twice.
322
+ - **Auto Idempotency-Key** on every POST / PUT / PATCH / DELETE — same key reused across retries; `orders.place` also fixes `client_order_id` before the first attempt.
429
323
  - **Response size cap** (10 MB default) — bounded read, guards against unbounded streams from a compromised server or MITM.
430
324
  - **CRLF header-injection guard** — `\r` / `\n` in caller-supplied header names or values throws before the request leaves the SDK.
431
325
  - **`Cache-Control: no-store`** on every request — intermediary caches can't retain authenticated responses; callers cannot override.
432
- - **`clockOffsetMs`** — compensate for a drifted local clock without weakening the HMAC ±30 s window.
433
- - **Zero hardcoded credentials.** No env-var URL override, no auto-loading of `PAX_API_KEY` / `PAX_SECRET` — callers pass credentials explicitly, closing off supply-chain hijack via a malicious dependency setting `process.env`.
326
+ - **`clockOffsetMs`** — compensate for a drifted local clock without weakening the HMAC ±300 s window.
327
+ - **Zero hardcoded credentials.** No env-var URL override, no auto-loading of `PAX_API_KEY` — callers pass credentials explicitly, closing off supply-chain hijack via a malicious dependency setting `process.env`.
434
328
  - **Browser opt-in guard.** Constructor throws in a browser unless `dangerouslyAllowBrowser: true` — server-side keys never accidentally ship to end-users.
435
329
 
436
- Report vulnerabilities to **security@predictasiax.com** — never open a public issue.
330
+ Report vulnerabilities as described in <https://predictasiax.com/.well-known/security.txt> — never open a public issue.
437
331
 
438
332
  ---
439
333