@predictasiax/api 2.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 +94 -0
- package/LICENSE +21 -0
- package/README.md +465 -0
- package/dist/index.cjs +1369 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1082 -0
- package/dist/index.d.ts +1082 -0
- package/dist/index.js +0 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# @predictasiax/api Changelog
|
|
2
|
+
|
|
3
|
+
## v2.0.0 — 2026-09-05
|
|
4
|
+
|
|
5
|
+
**Aligned with PAX API v2.0.0 (`https://api.predictasiax.com/v1`).**
|
|
6
|
+
|
|
7
|
+
### Breaking changes
|
|
8
|
+
|
|
9
|
+
- **Base URL**: `production` env now targets `https://api.predictasiax.com/v1`
|
|
10
|
+
(was `https://predictasiax.com/api`). Update any hardcoded `baseUrl`
|
|
11
|
+
overrides.
|
|
12
|
+
- **Sandbox is a tier, not a separate host**: `env: "sandbox"` now resolves
|
|
13
|
+
to the same canonical origin as `env: "production"`. Capability is scoped
|
|
14
|
+
by the `tier` flag on the key.
|
|
15
|
+
- **Removed sandbox subroutes**: `pax.sandbox.faucet()`, `.reset()`, and
|
|
16
|
+
`.mockOracle()` are gone (endpoints were retired). Use `pax.sandboxKeys.mint()`
|
|
17
|
+
to get a `tier=self_serve` key with $10/order + $100/day notional caps —
|
|
18
|
+
fills are simulated at mid-price against live orderbook state.
|
|
19
|
+
- **Removed types**: `FaucetResult`, `ResetResult`, `MockOracleResult`,
|
|
20
|
+
`MockOracleParams`.
|
|
21
|
+
|
|
22
|
+
### Added
|
|
23
|
+
|
|
24
|
+
- **`pax.sandboxKeys`** — `POST /v1/sandbox-keys` self-serve mint. Anonymous,
|
|
25
|
+
per-IP quota. Returns an `sk_live_*` key tagged `tier=self_serve` with
|
|
26
|
+
`{ max_order_usdt: 10, daily_notional_usdt: 100 }` limits and 30-day expiry.
|
|
27
|
+
- **`pax.apply`** — Builder track applications:
|
|
28
|
+
- `pax.apply.create({ track, org?, email?, url?, description? })` — 20 tracks
|
|
29
|
+
supported (genesis / self_serve / rfb-* / data / app / agent / distribution
|
|
30
|
+
/ market / liquidity / oracle / reviewer / operator / institutional).
|
|
31
|
+
Self-serve + RFB tracks auto-provision a key on submit; genesis +
|
|
32
|
+
institutional queue for human review.
|
|
33
|
+
- `pax.apply.retrieve(applicationCode)` — status lookup.
|
|
34
|
+
- **New types**: `Tier`, `TierLimits`, `SandboxKeyResult`, `ApplicationResult`,
|
|
35
|
+
`ApplicationStatus`, `SandboxKeyMintParams`, `ApplyCreateParams`.
|
|
36
|
+
- **`SandboxKeysResource`** + **`ApplyResource`** exported at top-level for
|
|
37
|
+
advanced instantiation.
|
|
38
|
+
|
|
39
|
+
### Retained
|
|
40
|
+
|
|
41
|
+
- All other resources (`pax.markets`, `pax.orders`, `pax.account`, `pax.keys`,
|
|
42
|
+
`pax.templates`, `pax.grants`) — API contracts unchanged.
|
|
43
|
+
- HMAC signing (Polymarket-compatible 5-header pattern), auto Idempotency-Key
|
|
44
|
+
on writes, isomorphic WebSocket, retry with backoff, error hierarchy.
|
|
45
|
+
|
|
46
|
+
## v1.1.0 — 2026-08-11
|
|
47
|
+
All notable changes to `@predictasiax/api` are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
48
|
+
|
|
49
|
+
## [1.1.0] — 2026-08-11
|
|
50
|
+
|
|
51
|
+
### Added
|
|
52
|
+
|
|
53
|
+
- **Grants resource** — `pax.grants.list() / .retrieve(id) / .events(id) / .claim(id)` for the PredictAsiaX **Builder Program** (PAX-token grants w/ cliff + linear vest, PULL claim model). Idempotency-Key auto-attached on `claim()` so a timed-out claim never double-credits.
|
|
54
|
+
- **Grant domain types** — `TokenGrant`, `GrantVesting`, `GrantClaimResult`, `GrantEvent`, `GrantTier`, `GrantPhase`, `GrantEventType`.
|
|
55
|
+
|
|
56
|
+
### Changed / Fixed
|
|
57
|
+
|
|
58
|
+
- **Retry policy tightened**: only genuine transport failures (`TypeError` from fetch — DNS/refused/TLS) are now retried. Client-side config errors (CRLF header injection, invalid URL, JSON serialization) throw immediately instead of being retried 5× × backoff. Faster failure + smaller attack window.
|
|
59
|
+
|
|
60
|
+
## [1.0.0] — 2026-08-10
|
|
61
|
+
|
|
62
|
+
Initial public release.
|
|
63
|
+
|
|
64
|
+
### Features
|
|
65
|
+
|
|
66
|
+
- **Resource-oriented API**: `pax.markets`, `pax.orders`, `pax.account`, `pax.templates`, `pax.keys`, `pax.sandbox`. Every REST endpoint is grouped under its resource.
|
|
67
|
+
- **Full TypeScript types** for every domain object: `Market`, `Order`, `Trade`, `Candle`, `Orderbook`, `Account`, `Position`, `MarketTemplate`, `ApiKey`, `FaucetResult`, `HealthStatus`.
|
|
68
|
+
- **Auto-pagination** via `PagePromise<T>` — `for await (const m of pax.markets.list())` walks pages lazily. Also supports manual `page.getNextPage()` and bounded `page.collect({ limit })`.
|
|
69
|
+
- **APIPromise wrapper** with `.withResponse()` (data + raw Response + requestId) and `.asResponse()` (raw Response only).
|
|
70
|
+
- **Request options** as second argument on every method: `signal`, `timeout`, `maxRetries`, `idempotencyKey`, `headers`. Idempotency-Key sent as an HTTP header (Stripe convention).
|
|
71
|
+
- **Isomorphic HMAC signing** — `node:crypto` in Node, WebCrypto in browser / Cloudflare Workers / Vercel Edge / Deno.
|
|
72
|
+
- **AbortSignal** on every request; chained with the SDK's internal timeout controller.
|
|
73
|
+
- **Retry with backoff** (full-jitter exponential) on 429 / 500 / 502 / 504. Respects `Retry-After`. Does not retry validation, sandbox-only, read-only-mode, circuit-breaker, or abort/timeout errors.
|
|
74
|
+
- **Error hierarchy**: `PaxError` → `PaxAuthError` → `PaxWrongEnvKeyError`, `PaxValidationError`, `PaxNotFoundError` → `PaxSandboxOnlyError`, `PaxConflictError`, `PaxRateLimitError`, `PaxServerError`, `PaxReadOnlyModeError`, `PaxCircuitBreakerError`. Every error carries `code`, `message`, `httpStatus`, `requestId`, `details`.
|
|
75
|
+
- **WebSocket client** with subscription memory — dynamic `subscribe()` / `unsubscribe()` calls are tracked and automatically resent on every reconnect. AUTH + LOCALE re-issued before subscriptions. JSON heartbeat every 25 s. Full-jitter exponential backoff.
|
|
76
|
+
- **Isomorphic WebSocket** — native `WebSocket` in browsers / Bun / Deno / Edge, `ws` package on Node.
|
|
77
|
+
- **Browser safety** — constructor throws in a browser environment unless `dangerouslyAllowBrowser: true` is set explicitly (prevents accidental key leaks in bundled apps).
|
|
78
|
+
- **ESM + CJS dual build** via tsup. `.d.ts` files ship in both flavors. Bundle size: ~32 KB ESM.
|
|
79
|
+
- **61 tests passing** across auth, errors, retry, client (URL/headers/errors/options/response wrapper), pagination, and security.
|
|
80
|
+
|
|
81
|
+
### Security hardening (see SECURITY.md)
|
|
82
|
+
|
|
83
|
+
- **HTTPS-only enforcement.** Constructor rejects `http://` unless the host is `localhost` / `127.0.0.1` / `::1`. Explicit `allowInsecureHttp: true` escape hatch for lab environments.
|
|
84
|
+
- **`redirect: manual`** on every fetch — server-initiated redirects (including downgrades and cross-origin re-targets) are refused.
|
|
85
|
+
- **`Cache-Control: no-store`** on every request — proxies / CDNs / browser caches cannot retain authenticated responses. Callers cannot override.
|
|
86
|
+
- **Auto Idempotency-Key** on POST / PUT / PATCH. Fresh UUID per logical call (via `crypto.randomUUID`), reused across every retry — prevents double-executed orders on network flakiness. Opt-out via `idempotencyKey: null` or `autoIdempotency: false`.
|
|
87
|
+
- **CR / LF / NUL injection guard** on caller-supplied header names + values — throws before the request leaves the SDK.
|
|
88
|
+
- **Response body size cap** (10 MB default, `maxResponseBytes` configurable). Streamed reader checks both `Content-Length` and chunk-by-chunk to reject unbounded payloads from a compromised server or MITM.
|
|
89
|
+
- **`clockOffsetMs`** option — compensates for a drifted local clock when signing HMAC timestamps, without weakening the server's ±30 s window.
|
|
90
|
+
- **Auth headers are protected.** `X-Api-Key`, `Authorization`, `POLY_*`, `Idempotency-Key`, `Cache-Control` cannot be overridden via `opts.headers`.
|
|
91
|
+
- **No env-var URL override, no env-var credential loading.** All configuration must be passed explicitly to the constructor — blocks supply-chain hijack where a malicious dependency sets `process.env.PAX_BASE_URL` or reads keys off `process.env`.
|
|
92
|
+
- **Zero runtime dependencies.** `ws` moved to `peerDependencies.optional` — Node uses it, browser bundlers tree-shake it out.
|
|
93
|
+
- **Browser opt-in guard.** Constructor throws in a browser environment unless `dangerouslyAllowBrowser: true` — server-side keys can't accidentally ship to end-users.
|
|
94
|
+
- **Timing / abort correctness.** Cancellation listeners are removed on request completion so cancelled or timed-out requests don't leak `AbortSignal` listeners on the user's controller.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PredictAsiaX
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
# @predictasiax/api
|
|
2
|
+
|
|
3
|
+
Official TypeScript / JavaScript SDK for the **PredictAsiaX Trader Track API** — Web3-native prediction markets, REST + WebSocket, Polymarket-compatible HMAC signing.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@predictasiax/api)
|
|
6
|
+
[](https://docs.predictasiax.com)
|
|
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).
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install @predictasiax/api
|
|
22
|
+
# or
|
|
23
|
+
pnpm add @predictasiax/api
|
|
24
|
+
# or
|
|
25
|
+
bun add @predictasiax/api
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Node.js **≥ 18** required (native `fetch`). Also works in Bun 1.0+, Deno, Cloudflare Workers, Vercel Edge, and modern browsers.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Quickstart
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { PaxClient } from "@predictasiax/api";
|
|
36
|
+
|
|
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);
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
More runnable examples: [`examples/`](./examples).
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Authentication
|
|
65
|
+
|
|
66
|
+
Three modes, auto-detected from your constructor arguments.
|
|
67
|
+
|
|
68
|
+
### 1. API Key (`sk_live_*`, tier-flagged)
|
|
69
|
+
|
|
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_..." });
|
|
77
|
+
```
|
|
78
|
+
|
|
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
|
+
```
|
|
94
|
+
|
|
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.
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## Environments
|
|
110
|
+
|
|
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
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## Resources
|
|
135
|
+
|
|
136
|
+
Every REST endpoint lives on a resource object:
|
|
137
|
+
|
|
138
|
+
```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
|
|
146
|
+
```
|
|
147
|
+
|
|
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" })) { ... }
|
|
154
|
+
|
|
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>
|
|
179
|
+
|
|
180
|
+
```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();
|
|
203
|
+
```
|
|
204
|
+
</details>
|
|
205
|
+
|
|
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>
|
|
229
|
+
|
|
230
|
+
---
|
|
231
|
+
|
|
232
|
+
## Pagination
|
|
233
|
+
|
|
234
|
+
Every `list` method returns a `PagePromise<T>` that supports **three** ergonomic styles:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
// (1) Async iterator — walks pages lazily. Best for large sets.
|
|
238
|
+
for await (const market of pax.markets.list({ limit: 100 })) {
|
|
239
|
+
console.log(market.id);
|
|
240
|
+
if (someCondition) break; // early exit, no wasted requests
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// (2) Manual paging — full control.
|
|
244
|
+
let page = await pax.markets.list({ limit: 100 });
|
|
245
|
+
while (true) {
|
|
246
|
+
for (const m of page.data) console.log(m.id);
|
|
247
|
+
if (!page.hasNextPage()) break;
|
|
248
|
+
page = await page.getNextPage();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// (3) Collect bounded — for small lists / CLIs.
|
|
252
|
+
const all = await pax.markets.list({ limit: 100 }).then((p) => p.collect({ limit: 5000 }));
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
## Request options
|
|
258
|
+
|
|
259
|
+
Every method accepts a second argument for per-request tuning:
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
await pax.orders.place(
|
|
263
|
+
{ marketId, outcomeId, side: "buy", orderType: "market", size: "10" },
|
|
264
|
+
{
|
|
265
|
+
idempotencyKey: "unique-request-id", // sent as HTTP header, dedupes retries
|
|
266
|
+
signal: controller.signal, // AbortSignal — cancels in flight
|
|
267
|
+
timeout: 5_000, // per-attempt timeout in ms
|
|
268
|
+
maxRetries: 2, // override client default (5)
|
|
269
|
+
headers: { "X-Correlation-ID": "abc" },
|
|
270
|
+
},
|
|
271
|
+
);
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
Idempotency-Key is sent as a real HTTP header (`Idempotency-Key: ...`), the same convention Stripe / OpenAI use.
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
## Response access
|
|
279
|
+
|
|
280
|
+
Await gives you the unwrapped data:
|
|
281
|
+
|
|
282
|
+
```ts
|
|
283
|
+
const account = await pax.account.retrieve();
|
|
284
|
+
console.log(account.balances);
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
If you need headers, status, or the request-id, use `.withResponse()`:
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
const { data, response, requestId, status, headers } =
|
|
291
|
+
await pax.account.retrieve().withResponse();
|
|
292
|
+
console.log(headers.get("x-ratelimit-remaining"));
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
Or `.asResponse()` for the raw Response only:
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
const raw = await pax.account.retrieve().asResponse();
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
---
|
|
302
|
+
|
|
303
|
+
## Errors
|
|
304
|
+
|
|
305
|
+
Every non-2xx response throws a typed error. Catch specifically or blanket-catch on `PaxError`.
|
|
306
|
+
|
|
307
|
+
```ts
|
|
308
|
+
import {
|
|
309
|
+
PaxError, PaxAuthError, PaxWrongEnvKeyError, PaxValidationError,
|
|
310
|
+
PaxNotFoundError, PaxSandboxOnlyError, PaxRateLimitError,
|
|
311
|
+
PaxReadOnlyModeError, PaxCircuitBreakerError, PaxServerError,
|
|
312
|
+
} from "@predictasiax/api";
|
|
313
|
+
|
|
314
|
+
try {
|
|
315
|
+
await pax.orders.place({...});
|
|
316
|
+
} catch (e) {
|
|
317
|
+
if (e instanceof PaxValidationError) {
|
|
318
|
+
console.error("Bad input:", e.code, e.details);
|
|
319
|
+
} else if (e instanceof PaxRateLimitError) {
|
|
320
|
+
console.error(`Rate limited — retry after ${e.retryAfter}s`);
|
|
321
|
+
} else if (e instanceof PaxError) {
|
|
322
|
+
// Any PAX-side error — always has code, message, requestId, httpStatus
|
|
323
|
+
console.error(`[${e.code}] ${e.message} req=${e.requestId}`);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
Full class hierarchy:
|
|
329
|
+
|
|
330
|
+
```
|
|
331
|
+
PaxError
|
|
332
|
+
├── PaxAuthError (401 / 403)
|
|
333
|
+
│ └── PaxWrongEnvKeyError
|
|
334
|
+
├── PaxValidationError (400)
|
|
335
|
+
├── PaxNotFoundError (404)
|
|
336
|
+
│ └── PaxSandboxOnlyError
|
|
337
|
+
├── PaxConflictError (409)
|
|
338
|
+
├── PaxRateLimitError (429 — carries .retryAfter)
|
|
339
|
+
├── PaxServerError (5xx)
|
|
340
|
+
├── PaxReadOnlyModeError (503, not retried)
|
|
341
|
+
└── PaxCircuitBreakerError (503, not retried)
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
### Retry policy
|
|
345
|
+
|
|
346
|
+
- `429`: respects `Retry-After` header, otherwise full-jitter exponential backoff.
|
|
347
|
+
- `500 / 502 / 504`: exponential backoff, up to `maxRetries` attempts.
|
|
348
|
+
- `503 READ_ONLY_MODE` and `503 CIRCUIT_BREAKER_OPEN`: **not retried** — the server is asking you to back off.
|
|
349
|
+
- All 4xx except 429: not retried.
|
|
350
|
+
- `AbortError` / `TimeoutError`: not retried.
|
|
351
|
+
|
|
352
|
+
Tune with `maxRetries` on either the client or per-request.
|
|
353
|
+
|
|
354
|
+
---
|
|
355
|
+
|
|
356
|
+
## WebSocket
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
import { PaxWSClient } from "@predictasiax/api";
|
|
360
|
+
|
|
361
|
+
const ws = new PaxWSClient({
|
|
362
|
+
apiKey: process.env.PAX_API_KEY!,
|
|
363
|
+
subscribeOnConnect: ["fast_tick", "trade_executed", "account"],
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
ws.on("fast_tick", (e) => { /* ... */ });
|
|
367
|
+
ws.on("trade_executed", (e) => { /* ... */ });
|
|
368
|
+
ws.onError((err) => console.error(err));
|
|
369
|
+
|
|
370
|
+
await ws.connect(); // resolves on OPEN
|
|
371
|
+
|
|
372
|
+
ws.subscribe(["market_updated"]); // dynamic subscription
|
|
373
|
+
// The SDK remembers this — resent automatically after any reconnect.
|
|
374
|
+
|
|
375
|
+
process.on("SIGINT", () => ws.close());
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
Features:
|
|
379
|
+
- Auto-reconnect with full-jitter exponential backoff (1–60 s configurable)
|
|
380
|
+
- Subscriptions are remembered locally and resent on every reconnect
|
|
381
|
+
- AUTH + LOCALE re-issued on reconnect before subscriptions
|
|
382
|
+
- JSON heartbeat every 25 s
|
|
383
|
+
- Isomorphic — native `WebSocket` in browsers / Deno / Bun / Edge, `ws` package in Node
|
|
384
|
+
|
|
385
|
+
---
|
|
386
|
+
|
|
387
|
+
## Runtime support
|
|
388
|
+
|
|
389
|
+
| Runtime | REST | WebSocket | Notes |
|
|
390
|
+
|-----------------------|:----:|:---------:|-------------------------------------|
|
|
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. |
|
|
397
|
+
|
|
398
|
+
Inject a custom `fetch` for proxies or non-standard runtimes:
|
|
399
|
+
|
|
400
|
+
```ts
|
|
401
|
+
const pax = new PaxClient({
|
|
402
|
+
apiKey: "sk_live_...",
|
|
403
|
+
fetch: myCustomFetch,
|
|
404
|
+
fetchOptions: { dispatcher: proxyAgent },
|
|
405
|
+
});
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
---
|
|
409
|
+
|
|
410
|
+
## TypeScript
|
|
411
|
+
|
|
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
|
+
```
|
|
420
|
+
|
|
421
|
+
---
|
|
422
|
+
|
|
423
|
+
## Security
|
|
424
|
+
|
|
425
|
+
The SDK carries HMAC secrets and signs real-money trades — full threat model and guarantees live in [SECURITY.md](./SECURITY.md). Highlights:
|
|
426
|
+
|
|
427
|
+
- **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.
|
|
429
|
+
- **Response size cap** (10 MB default) — bounded read, guards against unbounded streams from a compromised server or MITM.
|
|
430
|
+
- **CRLF header-injection guard** — `\r` / `\n` in caller-supplied header names or values throws before the request leaves the SDK.
|
|
431
|
+
- **`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`.
|
|
434
|
+
- **Browser opt-in guard.** Constructor throws in a browser unless `dangerouslyAllowBrowser: true` — server-side keys never accidentally ship to end-users.
|
|
435
|
+
|
|
436
|
+
Report vulnerabilities to **security@predictasiax.com** — never open a public issue.
|
|
437
|
+
|
|
438
|
+
---
|
|
439
|
+
|
|
440
|
+
## Documentation
|
|
441
|
+
|
|
442
|
+
- Full API reference: <https://docs.predictasiax.com>
|
|
443
|
+
- OpenAPI spec: <https://docs.predictasiax.com/downloads/openapi.json>
|
|
444
|
+
- AsyncAPI spec: <https://docs.predictasiax.com/downloads/asyncapi.json>
|
|
445
|
+
- Developer portal: <https://predictasiax.com/developer>
|
|
446
|
+
|
|
447
|
+
---
|
|
448
|
+
|
|
449
|
+
## Contributing
|
|
450
|
+
|
|
451
|
+
Issues + PRs welcome at <https://github.com/predictasiax/pax-typescript-sdk>.
|
|
452
|
+
|
|
453
|
+
```bash
|
|
454
|
+
git clone https://github.com/predictasiax/pax-typescript-sdk
|
|
455
|
+
cd pax-typescript-sdk
|
|
456
|
+
npm install
|
|
457
|
+
npm test
|
|
458
|
+
npm run build
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
---
|
|
462
|
+
|
|
463
|
+
## License
|
|
464
|
+
|
|
465
|
+
MIT © PredictAsiaX
|