@predictasiax/api 2.5.1 → 3.0.1

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,40 @@
1
1
  # @predictasiax/api Changelog
2
2
 
3
+ ## v3.0.1 — 2026-11-23
4
+
5
+ ### Security
6
+ - `PaxWSClient` accepts only `wss://` URLs; `ws://` is accepted for a loopback host only. The AUTH frame carries the credential. (REST `baseUrl` already required `https://`.)
7
+ - `attachRef()`: first write wins. A `?ref=` in the URL is persisted only when no ref is stored yet, so a later link cannot replace the referral that brought the user in. An explicit `ref` option (or `clearRef()` first) still replaces it. The previous code overwrote the stored ref on every URL hit, contrary to its own documentation.
8
+ - `verifyEvent` adds a `fields_match_canonical` check: `seq`, `event_type`, `payload`, `event_id`, `emitter`, `schema_version` and `idempotency_key` in the response must equal the values inside the hashed `canonical`. Numbers compare by value (the API serves numbers beyond double precision as decimal strings). New export `fieldsMatchCanonical`.
9
+ - When the API withholds `canonical` (public view of an event that names an account), `verifyEvent` returns `ok: false` and says only Merkle inclusion was checked.
10
+
11
+ ## v3.0.0 — 2026-11-23
12
+
13
+ 2.x could not authenticate against the gateway. This release aligns the SDK with what `https://api.predictasiax.com` actually serves.
14
+
15
+ ### Fixed
16
+ - 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.
17
+ - API keys are sent as `Authorization: Bearer sk_live_...`. 2.x sent `X-Api-Key`, which the gateway ignores.
18
+ - 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.
19
+ - `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.
20
+ - Every method targets a route the gateway serves (see Changed / Removed).
21
+
22
+ ### Security
23
+ - `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).
24
+ - New `expectedProofLength`, `AuditResource.verifyEventHash` (recomputes `sha256(prev_event_hash + canonical)`), `AuditResource.verifyEvent`, and `pax.audit.verify(seq)` running every check.
25
+ - PAX-* / POLY-* signing headers added to the caller-protected header list.
26
+
27
+ ### Changed
28
+ - Credentials: `{ apiKey }`, `{ apiKey, keyId }` for HMAC, or `{ bearerToken }`; no credentials allowed for public endpoints. `secret` / `passphrase` throw with a migration hint.
29
+ - `account.retrieve()` → `account.balance()` (`/v1/balance`; `retrieve` kept as an alias); `account.positions()` → `/v1/positions`; new `account.portfolio()`.
30
+ - `orders.list()` → `GET /v1/orders` (returns `{ orders, count }`); new `orders.history()`; `cancelBatch` → `cancelAll({ marketId })`.
31
+ - `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`.
32
+ - `sandboxKeys.mint({ orgName, contactHandle })` (was `contactEmail`, ignored by the gateway).
33
+ - Audit types use the live `*_ms` timestamp fields; `getAnchor` returns `AuditAnchor`.
34
+
35
+ ### Removed (no gateway route)
36
+ - `markets.trades`, `account.trades`, the `keys` resource, `settle.adminBuilder`, `settle.adminCreator`, `buildMessage` (replaced by `buildCanonical`).
37
+
3
38
  ## v2.5.1 — 2026-10-31
4
39
 
5
40
  **Bugfix: Merkle inclusion-proof verifier now hashes raw bytes, not hex strings —
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, Bearer `sk_live_*` auth (HMAC 5-header available for enterprise-provisioned partners), deterministic market IDs, envelope response, public Merkle audit chain.
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: "20" });
58
44
  ```
59
45
 
60
46
  More runnable examples: [`examples/`](./examples).
@@ -63,186 +49,91 @@ More runnable examples: [`examples/`](./examples).
63
49
 
64
50
  ## Authentication
65
51
 
66
- Three modes, auto-detected from your constructor arguments. **Bearer `sk_live_*` is the standard path for the vast majority of integrations** — read-only aggregators, creator profiles, automated trading, agent frameworks. HMAC 5-header signing is available to enterprise-provisioned partners (contact ops for the signing secret); it is not required for standard use.
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. Bearer `sk_live_*` (standard — start here)
59
+ HMAC signature, exactly as the gateway verifies it:
69
60
 
70
- The canonical path. Capability is scoped by the `tier` flag on the key
71
- (`self_serve` for sandbox testing with $10/$100 caps; `read_live` /
72
- `trade_capped` / `trade_full` / `genesis` / `partner` for production).
73
-
74
- ```ts
75
- 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))
76
64
  ```
77
65
 
78
- Sent as `Authorization: Bearer sk_live_...` header (the legacy `X-Api-Key`
79
- header is still accepted for backward compat). Tier-mismatched operations
80
- reject with `PaxWrongEnvKeyError`.
81
-
82
- ### 2. OAuth 2.1 bearer token (hosted apps on behalf of a PAX user)
83
-
84
- Session-based, obtained via `connect.predictasiax.com` OAuth 2.1 + PKCE S256.
85
- Use for third-party apps acting on behalf of an end user.
86
-
87
- ```ts
88
- const pax = new PaxClient({ bearerToken: "eyJ...", env: "production" });
89
- ```
90
-
91
- Sent as `Authorization: Bearer <token>` header — same wire path as the
92
- `sk_live_*` bearer, differentiated by token format.
93
-
94
- ### 3. HMAC 5-header (enterprise / ops-provisioned)
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.
95
67
 
96
- Reserved for enterprise partners who need per-request replay guards on top of
97
- the transport-layer HTTPS. Requires ops provisioning of the HMAC signing
98
- secret into the server's KV store; any HMAC-shaped credential submitted
99
- without provisioning returns `401 AUTH_INVALID` with a directive to use
100
- Bearer. Not required for standard integrations.
101
-
102
- ```ts
103
- const pax = new PaxClient({
104
- apiKey: "sk_live_ABC",
105
- secret: "your-64-char-secret", // provisioned by ops
106
- passphrase: "your-passphrase", // provisioned by ops
107
- env: "production",
108
- });
109
- ```
110
-
111
- Signed with the 5-header pattern. Canonical header prefix is `PAX_*`
112
- (`PAX_ACCESS_KEY` / `PAX_TIMESTAMP` / `PAX_PASSPHRASE` / `PAX_SIGNATURE`);
113
- the legacy `POLY_*` prefix is still accepted server-side for backward compat
114
- and is the format this SDK currently emits — a `PAX_*`-emitting client is
115
- planned in a future SDK release. Server accepts ±30 s clock skew — sync your
116
- machine via NTP.
68
+ `secret` / `passphrase` from 2.x are not part of the API and now throw with a migration hint.
117
69
 
118
70
  ---
119
71
 
120
- ## Environments
72
+ ## Base URL
121
73
 
122
- All `env` values resolve to the same canonical origin — sandbox is a *tier*
123
- on the production API (`tier=self_serve` on the key), not a separate host.
124
- This lets you promote a sandbox integration to production by upgrading the
125
- key's tier — no code changes, no host switch.
126
-
127
- | `env` | Base URL |
128
- |--------------------------|---------------------------------------|
129
- | `production` (default) | `https://api.predictasiax.com/v1` |
130
- | `sandbox` | `https://api.predictasiax.com/v1` |
131
-
132
- Override completely with `baseUrl`. WebSocket: `wss://predictasiax.com/ws`
133
- for every env.
134
-
135
- Sandbox tier (`tier=self_serve`) enforces:
136
- - `$10` per-order notional cap
137
- - `$100` daily notional cap
138
- - Simulated fills at mid-price against live orderbook state
139
- - Same auth, same endpoints, same envelope shape as production
140
- - 30-day key expiry, refreshable via `pax.sandboxKeys.mint()`
141
- - 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`.
142
75
 
143
76
  ---
144
77
 
145
78
  ## Resources
146
79
 
147
- Every REST endpoint lives on a resource object:
148
-
149
80
  ```ts
150
- pax.markets // discovery, candles, orderbook, public trades, creation
151
- pax.templates // parameterized market blueprints
152
- pax.orders // place / cancel / list your orders
153
- pax.account // balances, positions, your trade history
154
- pax.keys // programmatic key management
155
- pax.sandbox // faucet, reset, mock oracle
156
- 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
157
112
  ```
158
113
 
159
- <details>
160
- <summary><strong>Markets</strong></summary>
161
-
162
- ```ts
163
- // List — paginated, iterable
164
- for await (const m of pax.markets.list({ category: "crypto", status: "open" })) { ... }
114
+ ### Audit log verification
165
115
 
166
- // Single market
167
- const market = await pax.markets.retrieve("m_abc");
168
-
169
- // Create from template
170
- const created = await pax.markets.create({
171
- templateId: "crypto_price_binary_60s",
172
- params: { asset: "BTC", strike_pct: 0.5 },
173
- });
174
-
175
- // Candles
176
- const candles = await pax.markets.candles("m_abc", {
177
- outcomeId: "yes", interval: "1m", limit: 500,
178
- });
179
-
180
- // Orderbook L2
181
- const book = await pax.markets.orderbook("m_abc", { outcomeId: "yes", depth: 20 });
182
-
183
- // Public trade tape
184
- for await (const t of pax.markets.trades("m_abc", { limit: 100 })) { ... }
185
- ```
186
- </details>
187
-
188
- <details>
189
- <summary><strong>Orders + Account</strong></summary>
116
+ Every platform event is hash-chained and batched into SHA-256 Merkle trees. Verify locally:
190
117
 
191
118
  ```ts
192
- // Market order — fills immediately
193
- const filled = await pax.orders.place({
194
- marketId: "m_abc", outcomeId: "yes",
195
- side: "buy", orderType: "market", size: "10",
196
- }, { idempotencyKey: "ord-2026-08-10-abc" });
197
-
198
- // Limit order — GTC unless overridden
199
- const resting = await pax.orders.place({
200
- marketId: "m_abc", outcomeId: "yes",
201
- side: "buy", orderType: "limit", size: "10", price: "0.42",
202
- timeInForce: "GTC",
203
- });
204
-
205
- await pax.orders.cancel(resting.id);
206
-
207
- // Your orders + trades — paginated
208
- for await (const o of pax.orders.list({ status: "open" })) { ... }
209
- for await (const t of pax.account.trades({ limit: 100 })) { ... }
210
-
211
- // Balances + positions
212
- const account = await pax.account.retrieve();
213
- 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)
214
128
  ```
215
- </details>
216
129
 
217
- <details>
218
- <summary><strong>Keys + Sandbox</strong></summary>
219
-
220
- ```ts
221
- // Create a new key — secret is only returned here, store it now
222
- const { id, secret, scopes } = await pax.keys.create({
223
- name: "trader-bot", scopes: ["read", "trade"],
224
- });
225
-
226
- await pax.keys.list();
227
- await pax.keys.revoke(id);
228
-
229
- // Sandbox mint + Builder applications (anonymous, no auth required)
230
- const key = await pax.sandboxKeys.mint({ orgName: "my-app" });
231
- console.log("sk_live_ tier=self_serve:", key.api_key); // shown ONCE
232
-
233
- const app = await pax.apply.create({ track: "rfb-telegram-bot", org: "my-team" });
234
- if (app.auto_provisioned) console.log("Auto-approved:", app.api_key);
235
- else console.log("Pending review, code:", app.application_code);
236
-
237
- const status = await pax.apply.retrieve(app.application_code);
238
- ```
239
- </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`.
240
131
 
241
132
  ---
242
133
 
243
134
  ## Pagination
244
135
 
245
- Every `list` method returns a `PagePromise<T>` that supports **three** ergonomic styles:
136
+ `pax.markets.list()` returns a `PagePromise<T>` that supports three styles:
246
137
 
247
138
  ```ts
248
139
  // (1) Async iterator — walks pages lazily. Best for large sets.
@@ -271,7 +162,7 @@ Every method accepts a second argument for per-request tuning:
271
162
 
272
163
  ```ts
273
164
  await pax.orders.place(
274
- { marketId, outcomeId, side: "buy", orderType: "market", size: "10" },
165
+ { marketId, side: "yes", price: "0.42", size: "10" },
275
166
  {
276
167
  idempotencyKey: "unique-request-id", // sent as HTTP header, dedupes retries
277
168
  signal: controller.signal, // AbortSignal — cancels in flight
@@ -291,22 +182,21 @@ Idempotency-Key is sent as a real HTTP header (`Idempotency-Key: ...`), the same
291
182
  Await gives you the unwrapped data:
292
183
 
293
184
  ```ts
294
- const account = await pax.account.retrieve();
295
- console.log(account.balances);
185
+ const balance = await pax.account.balance();
296
186
  ```
297
187
 
298
188
  If you need headers, status, or the request-id, use `.withResponse()`:
299
189
 
300
190
  ```ts
301
191
  const { data, response, requestId, status, headers } =
302
- await pax.account.retrieve().withResponse();
192
+ await pax.account.balance().withResponse();
303
193
  console.log(headers.get("x-ratelimit-remaining"));
304
194
  ```
305
195
 
306
196
  Or `.asResponse()` for the raw Response only:
307
197
 
308
198
  ```ts
309
- const raw = await pax.account.retrieve().asResponse();
199
+ const raw = await pax.account.balance().asResponse();
310
200
  ```
311
201
 
312
202
  ---
@@ -399,12 +289,12 @@ Features:
399
289
 
400
290
  | Runtime | REST | WebSocket | Notes |
401
291
  |-----------------------|:----:|:---------:|-------------------------------------|
402
- | Node.js 18+ | ✅ | ✅ | Uses `node:crypto` + `ws` package. |
403
- | Bun 1.0+ | ✅ | ✅ | Native fetch + WebSocket. |
404
- | Deno | ✅ | ✅ | Import via `npm:@predictasiax/api`. |
405
- | Cloudflare Workers | ✅ | ✅ | Uses WebCrypto + native WebSocket. |
406
- | Vercel Edge Runtime | ✅ | ✅ | Same as CF Workers. |
407
- | 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. |
408
298
 
409
299
  Inject a custom `fetch` for proxies or non-standard runtimes:
410
300
 
@@ -420,31 +310,24 @@ const pax = new PaxClient({
420
310
 
421
311
  ## TypeScript
422
312
 
423
- TypeScript **≥ 5.0** recommended. The SDK ships full `.d.ts` files. Every response type is exported:
424
-
425
- ```ts
426
- import type {
427
- Market, Order, Trade, Candle, Orderbook, Account, Position,
428
- MarketTemplate, ApiKey, FaucetResult, HealthStatus,
429
- } from "@predictasiax/api";
430
- ```
313
+ TypeScript 5.0+ recommended; full `.d.ts` files ship with the package. Audit types (`AuditEvent`, `MerkleProof`, `AuditBatch`, `AuditAnchor`, `AuditVerification`) are exported.
431
314
 
432
315
  ---
433
316
 
434
317
  ## Security
435
318
 
436
- 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:
437
320
 
438
321
  - **HTTPS-only** — `http://` is rejected on non-loopback hosts; `redirect: manual` refuses server-initiated downgrades.
439
- - **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.
440
323
  - **Response size cap** (10 MB default) — bounded read, guards against unbounded streams from a compromised server or MITM.
441
324
  - **CRLF header-injection guard** — `\r` / `\n` in caller-supplied header names or values throws before the request leaves the SDK.
442
325
  - **`Cache-Control: no-store`** on every request — intermediary caches can't retain authenticated responses; callers cannot override.
443
- - **`clockOffsetMs`** — compensate for a drifted local clock without weakening the HMAC ±30 s window.
444
- - **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`.
445
328
  - **Browser opt-in guard.** Constructor throws in a browser unless `dangerouslyAllowBrowser: true` — server-side keys never accidentally ship to end-users.
446
329
 
447
- 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.
448
331
 
449
332
  ---
450
333