@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/dist/index.d.ts
ADDED
|
@@ -0,0 +1,1082 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Domain types returned by the PAX Trader Track API.
|
|
3
|
+
*
|
|
4
|
+
* All monetary and price fields are `string` — decimals preserved exactly,
|
|
5
|
+
* never rounded through JS `number`. Convert with a bigdecimal library
|
|
6
|
+
* (decimal.js / big.js) before arithmetic if precision matters.
|
|
7
|
+
*
|
|
8
|
+
* All timestamps ending in `_at_ms` are Unix epoch milliseconds.
|
|
9
|
+
*/
|
|
10
|
+
type Env = "production" | "prod" | "live" | "sandbox" | "test";
|
|
11
|
+
interface ResponseMeta {
|
|
12
|
+
request_id?: string;
|
|
13
|
+
server_time_ms?: number;
|
|
14
|
+
[k: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
interface Envelope<T = unknown> {
|
|
17
|
+
ok: boolean;
|
|
18
|
+
data: T;
|
|
19
|
+
meta?: ResponseMeta;
|
|
20
|
+
}
|
|
21
|
+
interface ListEnvelope<T = unknown> {
|
|
22
|
+
ok: boolean;
|
|
23
|
+
data: T[];
|
|
24
|
+
next_cursor?: string | null;
|
|
25
|
+
has_more?: boolean;
|
|
26
|
+
meta?: ResponseMeta;
|
|
27
|
+
}
|
|
28
|
+
/** Decimal string, e.g. "0.5623". Never lossy `number`. */
|
|
29
|
+
type Decimal = string;
|
|
30
|
+
type MarketStatus = "open" | "closed" | "settled" | "cancelled" | "paused";
|
|
31
|
+
type MarketType = "binary" | "multi" | "scalar" | "fast";
|
|
32
|
+
type Category = "crypto" | "sports" | "politics" | "entertainment" | "esports" | "other" | string;
|
|
33
|
+
interface Outcome {
|
|
34
|
+
id: string;
|
|
35
|
+
name: string;
|
|
36
|
+
price?: Decimal;
|
|
37
|
+
last_traded_price?: Decimal;
|
|
38
|
+
volume?: Decimal;
|
|
39
|
+
probability?: Decimal;
|
|
40
|
+
}
|
|
41
|
+
interface Market {
|
|
42
|
+
id: string;
|
|
43
|
+
slug?: string;
|
|
44
|
+
title: string;
|
|
45
|
+
description?: string;
|
|
46
|
+
category: Category;
|
|
47
|
+
market_type: MarketType;
|
|
48
|
+
status: MarketStatus;
|
|
49
|
+
outcomes: Outcome[];
|
|
50
|
+
volume?: Decimal;
|
|
51
|
+
liquidity?: Decimal;
|
|
52
|
+
open_at_ms?: number;
|
|
53
|
+
close_at_ms?: number;
|
|
54
|
+
settle_at_ms?: number;
|
|
55
|
+
settled_at_ms?: number | null;
|
|
56
|
+
winning_outcome_id?: string | null;
|
|
57
|
+
template_id?: string;
|
|
58
|
+
round_duration_sec?: number;
|
|
59
|
+
image_url?: string;
|
|
60
|
+
tags?: string[];
|
|
61
|
+
metadata?: Record<string, unknown>;
|
|
62
|
+
}
|
|
63
|
+
interface MarketTemplate {
|
|
64
|
+
id: string;
|
|
65
|
+
name: string;
|
|
66
|
+
category: Category;
|
|
67
|
+
market_type: MarketType;
|
|
68
|
+
description?: string;
|
|
69
|
+
params_schema: Record<string, unknown>;
|
|
70
|
+
display_defaults?: Record<string, unknown>;
|
|
71
|
+
round_duration_sec?: number | null;
|
|
72
|
+
active: boolean;
|
|
73
|
+
created_at_ms?: number;
|
|
74
|
+
}
|
|
75
|
+
type CandleInterval = "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "1d";
|
|
76
|
+
interface Candle {
|
|
77
|
+
t_ms: number;
|
|
78
|
+
open: Decimal;
|
|
79
|
+
high: Decimal;
|
|
80
|
+
low: Decimal;
|
|
81
|
+
close: Decimal;
|
|
82
|
+
volume?: Decimal;
|
|
83
|
+
}
|
|
84
|
+
interface OrderbookLevel {
|
|
85
|
+
price: Decimal;
|
|
86
|
+
size: Decimal;
|
|
87
|
+
}
|
|
88
|
+
interface Orderbook {
|
|
89
|
+
market_id: string;
|
|
90
|
+
outcome_id: string;
|
|
91
|
+
bids: OrderbookLevel[];
|
|
92
|
+
asks: OrderbookLevel[];
|
|
93
|
+
ts_ms: number;
|
|
94
|
+
sequence?: number;
|
|
95
|
+
}
|
|
96
|
+
type Side = "buy" | "sell";
|
|
97
|
+
interface Trade {
|
|
98
|
+
id: string;
|
|
99
|
+
market_id: string;
|
|
100
|
+
outcome_id: string;
|
|
101
|
+
side: Side;
|
|
102
|
+
price: Decimal;
|
|
103
|
+
size: Decimal;
|
|
104
|
+
ts_ms: number;
|
|
105
|
+
taker?: boolean;
|
|
106
|
+
fee?: Decimal;
|
|
107
|
+
order_id?: string;
|
|
108
|
+
}
|
|
109
|
+
type OrderType = "market" | "limit";
|
|
110
|
+
type OrderStatus = "open" | "filled" | "partial" | "cancelled" | "rejected" | "expired";
|
|
111
|
+
type TimeInForce = "GTC" | "IOC" | "FOK";
|
|
112
|
+
interface Order {
|
|
113
|
+
id: string;
|
|
114
|
+
client_order_id?: string | null;
|
|
115
|
+
market_id: string;
|
|
116
|
+
outcome_id: string;
|
|
117
|
+
side: Side;
|
|
118
|
+
order_type: OrderType;
|
|
119
|
+
size: Decimal;
|
|
120
|
+
price?: Decimal;
|
|
121
|
+
filled_size: Decimal;
|
|
122
|
+
remaining_size: Decimal;
|
|
123
|
+
status: OrderStatus;
|
|
124
|
+
time_in_force?: TimeInForce;
|
|
125
|
+
avg_fill_price?: Decimal;
|
|
126
|
+
fee?: Decimal;
|
|
127
|
+
created_at_ms: number;
|
|
128
|
+
updated_at_ms: number;
|
|
129
|
+
}
|
|
130
|
+
interface AccountBalance {
|
|
131
|
+
asset: string;
|
|
132
|
+
free: Decimal;
|
|
133
|
+
reserved: Decimal;
|
|
134
|
+
total?: Decimal;
|
|
135
|
+
}
|
|
136
|
+
interface Account {
|
|
137
|
+
id: string;
|
|
138
|
+
balances: AccountBalance[];
|
|
139
|
+
balance_free?: Decimal;
|
|
140
|
+
balance_reserved?: Decimal;
|
|
141
|
+
asset?: string;
|
|
142
|
+
mode?: "cash" | "web3" | string;
|
|
143
|
+
created_at_ms?: number;
|
|
144
|
+
}
|
|
145
|
+
interface Position {
|
|
146
|
+
market_id: string;
|
|
147
|
+
outcome_id: string;
|
|
148
|
+
size: Decimal;
|
|
149
|
+
avg_price: Decimal;
|
|
150
|
+
realised_pnl?: Decimal;
|
|
151
|
+
unrealised_pnl?: Decimal;
|
|
152
|
+
updated_at_ms: number;
|
|
153
|
+
}
|
|
154
|
+
type KeyScope = "read" | "trade" | "manage" | string;
|
|
155
|
+
interface ApiKey {
|
|
156
|
+
id: string;
|
|
157
|
+
name?: string;
|
|
158
|
+
key_prefix?: string;
|
|
159
|
+
scopes: KeyScope[];
|
|
160
|
+
created_at_ms: number;
|
|
161
|
+
last_used_at_ms?: number | null;
|
|
162
|
+
revoked_at_ms?: number | null;
|
|
163
|
+
/** Only present on POST /keys create response (never listed again). */
|
|
164
|
+
secret?: string;
|
|
165
|
+
}
|
|
166
|
+
type Tier = "self_serve" | "verified" | "trade_capped" | "trade_full" | "genesis" | "partner";
|
|
167
|
+
interface TierLimits {
|
|
168
|
+
max_order_usdt: number;
|
|
169
|
+
daily_notional_usdt: number;
|
|
170
|
+
}
|
|
171
|
+
/** Response body of POST /v1/sandbox-keys. `api_key` shown ONCE. */
|
|
172
|
+
interface SandboxKeyResult {
|
|
173
|
+
ok: true;
|
|
174
|
+
key_id: number;
|
|
175
|
+
key_prefix: string;
|
|
176
|
+
api_key: string;
|
|
177
|
+
user_id: string;
|
|
178
|
+
org_name: string;
|
|
179
|
+
tier: Tier;
|
|
180
|
+
expires_at: string;
|
|
181
|
+
expires_at_ms?: number;
|
|
182
|
+
limits: TierLimits;
|
|
183
|
+
docs?: string;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Response body of POST /v1/apply. For auto-approve tracks (self_serve, rfb-*,
|
|
187
|
+
* etc.), `api_key` is populated and shown ONCE. For review tracks (genesis,
|
|
188
|
+
* institutional), `api_key` is null and a human review is scheduled.
|
|
189
|
+
*/
|
|
190
|
+
interface ApplicationResult {
|
|
191
|
+
ok: true;
|
|
192
|
+
application_code: string;
|
|
193
|
+
track: string;
|
|
194
|
+
status: "auto_approved" | "pending_review";
|
|
195
|
+
auto_provisioned: boolean;
|
|
196
|
+
/** Present only when auto_provisioned=true — SAVE IMMEDIATELY. */
|
|
197
|
+
api_key?: string;
|
|
198
|
+
key_prefix?: string;
|
|
199
|
+
user_id?: string;
|
|
200
|
+
next_step?: string;
|
|
201
|
+
}
|
|
202
|
+
/** Response body of GET /v1/apply/{code} — status lookup. */
|
|
203
|
+
interface ApplicationStatus {
|
|
204
|
+
ok: true;
|
|
205
|
+
application_code: string;
|
|
206
|
+
track: string;
|
|
207
|
+
status: "auto_approved" | "pending_review" | "approved" | "rejected";
|
|
208
|
+
auto_provisioned: boolean;
|
|
209
|
+
reviewed_at?: string | null;
|
|
210
|
+
reviewer_note?: string | null;
|
|
211
|
+
}
|
|
212
|
+
interface HealthStatus {
|
|
213
|
+
status: "ok" | "degraded" | "read_only" | string;
|
|
214
|
+
version?: string;
|
|
215
|
+
region?: string;
|
|
216
|
+
time_ms: number;
|
|
217
|
+
}
|
|
218
|
+
type GrantTier = "hackathon" | "builder" | "partner";
|
|
219
|
+
type GrantPhase = "pre_cliff" | "vesting" | "fully_vested" | "cancelled" | "migrated";
|
|
220
|
+
/**
|
|
221
|
+
* Live vesting calculation for a grant — computed server-side at read time,
|
|
222
|
+
* never cached. Numeric fields are decimal strings.
|
|
223
|
+
*/
|
|
224
|
+
interface GrantVesting {
|
|
225
|
+
unlocked: Decimal;
|
|
226
|
+
claimable: Decimal;
|
|
227
|
+
phase: GrantPhase;
|
|
228
|
+
percent_unlocked: number;
|
|
229
|
+
next_unlock_ms: number | null;
|
|
230
|
+
}
|
|
231
|
+
interface TokenGrant {
|
|
232
|
+
id: string;
|
|
233
|
+
user_id: string;
|
|
234
|
+
tier: GrantTier;
|
|
235
|
+
amount_pax: Decimal;
|
|
236
|
+
granted_at_ms: number;
|
|
237
|
+
cliff_ends_at_ms: number;
|
|
238
|
+
vest_ends_at_ms: number;
|
|
239
|
+
claimed_amount: Decimal;
|
|
240
|
+
milestones_completed: number;
|
|
241
|
+
cancelled_at_ms: number | null;
|
|
242
|
+
cancellation_reason: string | null;
|
|
243
|
+
application_url: string | null;
|
|
244
|
+
metadata: Record<string, unknown>;
|
|
245
|
+
on_chain_contract_address: string | null;
|
|
246
|
+
on_chain_migrated_at_ms: number | null;
|
|
247
|
+
vesting?: GrantVesting;
|
|
248
|
+
}
|
|
249
|
+
interface GrantClaimResult {
|
|
250
|
+
claimed_now: Decimal;
|
|
251
|
+
cumulative_claimed: Decimal;
|
|
252
|
+
unlocked_ceiling: Decimal;
|
|
253
|
+
status: "ok" | "no_op";
|
|
254
|
+
}
|
|
255
|
+
type GrantEventType = "created" | "claimed" | "milestone_advanced" | "cancelled" | "migrated_on_chain" | "paused" | "resumed";
|
|
256
|
+
interface GrantEvent {
|
|
257
|
+
id: number;
|
|
258
|
+
grant_id: string;
|
|
259
|
+
event_type: GrantEventType;
|
|
260
|
+
amount_pax: Decimal | null;
|
|
261
|
+
actor: string;
|
|
262
|
+
reason: string | null;
|
|
263
|
+
metadata: Record<string, unknown>;
|
|
264
|
+
ts_ms: number;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Per-request options accepted as the second argument on every SDK method.
|
|
269
|
+
*
|
|
270
|
+
* Example:
|
|
271
|
+
* await pax.orders.place(
|
|
272
|
+
* { marketId, outcomeId, side: "buy", orderType: "market", size: "10" },
|
|
273
|
+
* { idempotencyKey: "ord_abc123", signal: controller.signal, timeout: 5000 },
|
|
274
|
+
* );
|
|
275
|
+
*
|
|
276
|
+
* Design mirrors Stripe / OpenAI / Anthropic SDKs.
|
|
277
|
+
*/
|
|
278
|
+
interface RequestOptions {
|
|
279
|
+
/**
|
|
280
|
+
* User-provided AbortSignal. If fired, the request is aborted and the
|
|
281
|
+
* caller sees an `AbortError`. Chained with the SDK's internal timeout
|
|
282
|
+
* signal — whichever fires first wins.
|
|
283
|
+
*/
|
|
284
|
+
signal?: AbortSignal;
|
|
285
|
+
/**
|
|
286
|
+
* Per-request timeout in ms. Overrides the client default (30 s).
|
|
287
|
+
* Applies to a single HTTP attempt — retries each get their own timeout.
|
|
288
|
+
*/
|
|
289
|
+
timeout?: number;
|
|
290
|
+
/**
|
|
291
|
+
* Per-request retry budget. Overrides the client default (5).
|
|
292
|
+
*/
|
|
293
|
+
maxRetries?: number;
|
|
294
|
+
/**
|
|
295
|
+
* Idempotency-Key sent as an HTTP header (not in the body). Server
|
|
296
|
+
* de-duplicates repeated requests carrying the same key within a 24 h
|
|
297
|
+
* window.
|
|
298
|
+
*
|
|
299
|
+
* - `string`: use exactly this key.
|
|
300
|
+
* - `undefined` (default): if the client has `autoIdempotency` enabled
|
|
301
|
+
* (default: on), a random UUID is generated for POST/PUT/PATCH
|
|
302
|
+
* requests and reused across retries.
|
|
303
|
+
* - `null`: disable auto-generation for this call.
|
|
304
|
+
*/
|
|
305
|
+
idempotencyKey?: string | null;
|
|
306
|
+
/**
|
|
307
|
+
* Per-request response body cap in bytes. Overrides the client default
|
|
308
|
+
* (10 MB). Guards against unbounded reads from a compromised server or
|
|
309
|
+
* MITM proxy.
|
|
310
|
+
*/
|
|
311
|
+
maxResponseBytes?: number;
|
|
312
|
+
/**
|
|
313
|
+
* Extra HTTP headers merged onto the request. Cannot override SDK-managed
|
|
314
|
+
* auth headers (X-Api-Key / POLY_* / Authorization). CR/LF are rejected
|
|
315
|
+
* to block header injection.
|
|
316
|
+
*/
|
|
317
|
+
headers?: Record<string, string>;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Low-level HTTP transport for the PAX SDK.
|
|
322
|
+
*
|
|
323
|
+
* Security posture:
|
|
324
|
+
* - HTTPS-only enforcement (http:// blocked unless target is localhost/loopback)
|
|
325
|
+
* - Response body size cap (default 10 MB, configurable) — prevents unbounded
|
|
326
|
+
* read from a compromised server or MITM
|
|
327
|
+
* - Auto Idempotency-Key on POST/PUT/PATCH — same key reused across retries,
|
|
328
|
+
* prevents double-execution on network flakiness
|
|
329
|
+
* - `Cache-Control: no-store` on every request — prevents intermediary caches
|
|
330
|
+
* retaining authenticated responses
|
|
331
|
+
* - `Referrer-Policy` compatible via `no-referrer` header
|
|
332
|
+
* - HMAC clock skew adjustment via client option
|
|
333
|
+
* - CR/LF injection on user headers rejected in mergeHeaders
|
|
334
|
+
* - `redirect: manual` — refuses server-initiated redirects that could
|
|
335
|
+
* downgrade to plaintext or cross-origin
|
|
336
|
+
*/
|
|
337
|
+
|
|
338
|
+
interface HttpClientOptions {
|
|
339
|
+
apiKey?: string;
|
|
340
|
+
secret?: string;
|
|
341
|
+
passphrase?: string;
|
|
342
|
+
bearerToken?: string;
|
|
343
|
+
env?: Env;
|
|
344
|
+
baseUrl?: string;
|
|
345
|
+
timeoutMs?: number;
|
|
346
|
+
maxRetries?: number;
|
|
347
|
+
userAgent?: string;
|
|
348
|
+
/** Injectable fetch — for testing, edge runtimes, or custom dispatchers. */
|
|
349
|
+
fetch?: typeof globalThis.fetch;
|
|
350
|
+
/** Extra fields passed through to every fetch() call. */
|
|
351
|
+
fetchOptions?: Omit<RequestInit, "method" | "headers" | "body" | "signal">;
|
|
352
|
+
/** Set to `true` if you know what you're doing and want to use this in a browser. */
|
|
353
|
+
dangerouslyAllowBrowser?: boolean;
|
|
354
|
+
/**
|
|
355
|
+
* Response body size cap in bytes. Default 10 MB. Guards against unbounded
|
|
356
|
+
* reads from a compromised server or MITM proxy.
|
|
357
|
+
*/
|
|
358
|
+
maxResponseBytes?: number;
|
|
359
|
+
/**
|
|
360
|
+
* Auto-generate `Idempotency-Key` on POST/PUT/PATCH when caller does not
|
|
361
|
+
* provide one. Same key is reused across all retries of a single call.
|
|
362
|
+
* Default: `true`. Set to `false` to require callers to always provide
|
|
363
|
+
* their own key.
|
|
364
|
+
*/
|
|
365
|
+
autoIdempotency?: boolean;
|
|
366
|
+
/**
|
|
367
|
+
* Milliseconds added to `Date.now()` when constructing HMAC timestamps.
|
|
368
|
+
* Use to compensate for a locally-drifted clock (e.g. from `serverTime - Date.now()`).
|
|
369
|
+
* Server accepts ±30 s skew, so a value beyond that will fail regardless.
|
|
370
|
+
*/
|
|
371
|
+
clockOffsetMs?: number;
|
|
372
|
+
/**
|
|
373
|
+
* Allow `http://` on non-loopback hosts. **DO NOT USE IN PRODUCTION.** Only
|
|
374
|
+
* for local dev tools using cleartext for reasons like packet inspection.
|
|
375
|
+
*/
|
|
376
|
+
allowInsecureHttp?: boolean;
|
|
377
|
+
}
|
|
378
|
+
type QueryParams = Record<string, string | number | boolean | string[] | null | undefined>;
|
|
379
|
+
interface RawResponse<T> {
|
|
380
|
+
/** The parsed JSON envelope returned by the server (typed as T by the caller). */
|
|
381
|
+
body: T;
|
|
382
|
+
/** The underlying Fetch Response. Body has already been consumed. */
|
|
383
|
+
response: Response;
|
|
384
|
+
}
|
|
385
|
+
declare class HttpClient {
|
|
386
|
+
readonly baseUrl: string;
|
|
387
|
+
readonly userAgent: string;
|
|
388
|
+
private readonly apiKey?;
|
|
389
|
+
private readonly secret?;
|
|
390
|
+
private readonly passphrase?;
|
|
391
|
+
private readonly bearerToken?;
|
|
392
|
+
private readonly timeoutMs;
|
|
393
|
+
private readonly maxRetries;
|
|
394
|
+
private readonly maxResponseBytes;
|
|
395
|
+
private readonly autoIdempotency;
|
|
396
|
+
private readonly clockOffsetMs;
|
|
397
|
+
private readonly fetchImpl;
|
|
398
|
+
private readonly fetchOptions;
|
|
399
|
+
constructor(opts: HttpClientOptions);
|
|
400
|
+
private buildQueryString;
|
|
401
|
+
private buildHeaders;
|
|
402
|
+
private resolveIdempotencyKey;
|
|
403
|
+
private attempt;
|
|
404
|
+
/**
|
|
405
|
+
* Execute a request with retry-with-backoff on transient failures.
|
|
406
|
+
* Returns the parsed envelope plus the raw Response.
|
|
407
|
+
*
|
|
408
|
+
* The idempotency key is resolved ONCE per call and reused across every
|
|
409
|
+
* retry — this is what prevents double-execution on network flakiness.
|
|
410
|
+
*/
|
|
411
|
+
request<T>(method: string, path: string, params?: QueryParams, jsonBody?: unknown, opts?: RequestOptions): Promise<RawResponse<T>>;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* APIPromise<T> — a Promise that also exposes the raw HTTP Response.
|
|
416
|
+
*
|
|
417
|
+
* Every SDK method returns an APIPromise. Awaiting it yields the parsed
|
|
418
|
+
* body (data). Calling `.withResponse()` yields both the parsed data and
|
|
419
|
+
* the raw Response (headers, status, request_id). Calling `.asResponse()`
|
|
420
|
+
* yields just the raw Response without parsing.
|
|
421
|
+
*
|
|
422
|
+
* Pattern mirrors the OpenAI / Anthropic TypeScript SDKs.
|
|
423
|
+
*
|
|
424
|
+
* @example
|
|
425
|
+
* const account = await pax.account.retrieve();
|
|
426
|
+
*
|
|
427
|
+
* const { data, response, requestId } = await pax.account.retrieve().withResponse();
|
|
428
|
+
* console.log(response.headers.get("x-ratelimit-remaining"));
|
|
429
|
+
*
|
|
430
|
+
* const raw = await pax.account.retrieve().asResponse();
|
|
431
|
+
* console.log(raw.status);
|
|
432
|
+
*/
|
|
433
|
+
interface APIResponseInfo {
|
|
434
|
+
status: number;
|
|
435
|
+
headers: Headers;
|
|
436
|
+
requestId: string | null;
|
|
437
|
+
raw: Response;
|
|
438
|
+
}
|
|
439
|
+
interface WithResponseResult<T> {
|
|
440
|
+
data: T;
|
|
441
|
+
response: Response;
|
|
442
|
+
requestId: string | null;
|
|
443
|
+
headers: Headers;
|
|
444
|
+
status: number;
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* A thenable that lazily executes the request and lets the caller pick
|
|
448
|
+
* whether they want the parsed data, both data+response, or just the raw
|
|
449
|
+
* response.
|
|
450
|
+
*/
|
|
451
|
+
declare class APIPromise<T> implements PromiseLike<T> {
|
|
452
|
+
private readonly _run;
|
|
453
|
+
private _executed;
|
|
454
|
+
constructor(run: () => Promise<{
|
|
455
|
+
data: T;
|
|
456
|
+
response: Response;
|
|
457
|
+
}>);
|
|
458
|
+
private _exec;
|
|
459
|
+
then<R1 = T, R2 = never>(onFulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null, onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null): Promise<R1 | R2>;
|
|
460
|
+
catch<R = never>(onRejected?: ((reason: unknown) => R | PromiseLike<R>) | null): Promise<T | R>;
|
|
461
|
+
finally(onFinally?: (() => void) | null): Promise<T>;
|
|
462
|
+
/** Return the parsed data plus the raw Response object. */
|
|
463
|
+
withResponse(): Promise<WithResponseResult<T>>;
|
|
464
|
+
/** Return the raw Response object. Body has already been read for parsing. */
|
|
465
|
+
asResponse(): Promise<Response>;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Cursor-based pagination with async iteration.
|
|
470
|
+
*
|
|
471
|
+
* PAX list endpoints return `{ data: T[], next_cursor: string | null, has_more: bool }`.
|
|
472
|
+
* `CursorPage<T>` wraps that and lets callers pick their style:
|
|
473
|
+
*
|
|
474
|
+
* // 1) Auto-iterate across all pages (network I/O per page)
|
|
475
|
+
* for await (const market of pax.markets.list({ limit: 100 })) {
|
|
476
|
+
* console.log(market.id);
|
|
477
|
+
* }
|
|
478
|
+
*
|
|
479
|
+
* // 2) Single page, manual paging
|
|
480
|
+
* let page = await pax.markets.list({ limit: 100 });
|
|
481
|
+
* for (const market of page.data) { ... }
|
|
482
|
+
* while (page.hasNextPage()) page = await page.getNextPage();
|
|
483
|
+
*
|
|
484
|
+
* // 3) Collect all into an array (bounded, guards runaway loops)
|
|
485
|
+
* const all = await pax.markets.list().collect({ limit: 5000 });
|
|
486
|
+
*
|
|
487
|
+
* The pattern mirrors OpenAI / Stripe SDKs.
|
|
488
|
+
*/
|
|
489
|
+
|
|
490
|
+
interface CursorPageParams {
|
|
491
|
+
limit?: number;
|
|
492
|
+
cursor?: string;
|
|
493
|
+
[k: string]: unknown;
|
|
494
|
+
}
|
|
495
|
+
interface CursorPageInit<T> {
|
|
496
|
+
data: T[];
|
|
497
|
+
nextCursor: string | null;
|
|
498
|
+
hasMore: boolean;
|
|
499
|
+
response: Response;
|
|
500
|
+
/** How to fetch the next page — used by `getNextPage` / async iteration. */
|
|
501
|
+
fetchNext: (cursor: string, opts?: RequestOptions) => APIPromise<CursorPage<T>>;
|
|
502
|
+
/** Options carried through to the next-page request (signal + timeout etc.) */
|
|
503
|
+
requestOptions?: RequestOptions;
|
|
504
|
+
}
|
|
505
|
+
declare class CursorPage<T> implements AsyncIterable<T> {
|
|
506
|
+
readonly data: T[];
|
|
507
|
+
readonly nextCursor: string | null;
|
|
508
|
+
readonly hasMore: boolean;
|
|
509
|
+
readonly response: Response;
|
|
510
|
+
private readonly _fetchNext;
|
|
511
|
+
private readonly _requestOptions?;
|
|
512
|
+
constructor(init: CursorPageInit<T>);
|
|
513
|
+
hasNextPage(): boolean;
|
|
514
|
+
getNextPage(): APIPromise<CursorPage<T>>;
|
|
515
|
+
/**
|
|
516
|
+
* Async iterate every item across every page. Fetches subsequent pages
|
|
517
|
+
* lazily as the caller consumes.
|
|
518
|
+
*/
|
|
519
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
520
|
+
/**
|
|
521
|
+
* Collect every item across every page into a single array. Guarded by
|
|
522
|
+
* `limit` to prevent unbounded memory growth.
|
|
523
|
+
*/
|
|
524
|
+
collect(opts?: {
|
|
525
|
+
limit?: number;
|
|
526
|
+
}): Promise<T[]>;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* A Promise resolving to a CursorPage<T> that is also directly async-iterable —
|
|
530
|
+
* callers can either `await` it to get the first page, or `for await` it to
|
|
531
|
+
* walk every item across every page. Mirrors the OpenAI SDK pattern.
|
|
532
|
+
*
|
|
533
|
+
* @example
|
|
534
|
+
* for await (const market of pax.markets.list()) { ... }
|
|
535
|
+
* const page = await pax.markets.list();
|
|
536
|
+
*/
|
|
537
|
+
declare class PagePromise<T> extends APIPromise<CursorPage<T>> implements AsyncIterable<T> {
|
|
538
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Shared helpers for resource classes.
|
|
543
|
+
*
|
|
544
|
+
* Every resource holds a reference to the HttpClient. The APIPromise +
|
|
545
|
+
* CursorPage plumbing lives here so individual resources stay short and
|
|
546
|
+
* declarative.
|
|
547
|
+
*/
|
|
548
|
+
|
|
549
|
+
declare abstract class Resource {
|
|
550
|
+
protected readonly _http: HttpClient;
|
|
551
|
+
constructor(_http: HttpClient);
|
|
552
|
+
/** Wrap an unwrapped-data GET/POST/DELETE in APIPromise<T>. */
|
|
553
|
+
protected _apiPromise<T>(run: () => Promise<RawResponse<Envelope<T>>>): APIPromise<T>;
|
|
554
|
+
/**
|
|
555
|
+
* Wrap a paginated GET in APIPromise<CursorPage<T>>.
|
|
556
|
+
*
|
|
557
|
+
* `fetchNext` is a callback the returned CursorPage uses to walk the
|
|
558
|
+
* next page — it must resend the same request with the new cursor and
|
|
559
|
+
* return an APIPromise<CursorPage<T>> so it composes.
|
|
560
|
+
*/
|
|
561
|
+
protected _pagePromise<T>(run: () => Promise<RawResponse<ListEnvelope<T>>>, fetchNext: CursorPageInit<T>["fetchNext"], requestOptions?: RequestOptions): PagePromise<T>;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Account resource — balances, positions, your trade history.
|
|
566
|
+
*
|
|
567
|
+
* GET /v1/account retrieve()
|
|
568
|
+
* GET /v1/account/positions positions()
|
|
569
|
+
* GET /v1/account/trades trades()
|
|
570
|
+
*/
|
|
571
|
+
|
|
572
|
+
interface ListTradesParams {
|
|
573
|
+
cursor?: string;
|
|
574
|
+
limit?: number;
|
|
575
|
+
marketId?: string;
|
|
576
|
+
}
|
|
577
|
+
declare class AccountResource extends Resource {
|
|
578
|
+
retrieve(opts?: RequestOptions): APIPromise<Account>;
|
|
579
|
+
positions(opts?: RequestOptions): APIPromise<Position[]>;
|
|
580
|
+
trades(params?: ListTradesParams, opts?: RequestOptions): PagePromise<Trade>;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Grants resource — Builder Program token grants (PAX-denominated) with
|
|
585
|
+
* cliff + linear vest. Callers use `pax.grants` to view their grants and
|
|
586
|
+
* claim vested tokens into their custody balance.
|
|
587
|
+
*
|
|
588
|
+
* @example
|
|
589
|
+
* for (const g of await pax.grants.list()) {
|
|
590
|
+
* console.log(g.id, g.vesting?.claimable, "PAX claimable");
|
|
591
|
+
* }
|
|
592
|
+
* const result = await pax.grants.claim("grant_abc");
|
|
593
|
+
* console.log("credited", result.claimed_now);
|
|
594
|
+
*/
|
|
595
|
+
|
|
596
|
+
declare class GrantsResource extends Resource {
|
|
597
|
+
/** List every grant the authenticated user has, oldest last. */
|
|
598
|
+
list(opts?: RequestOptions): APIPromise<TokenGrant[]>;
|
|
599
|
+
/** Get a single grant + live vesting calculation. */
|
|
600
|
+
retrieve(id: string, opts?: RequestOptions): APIPromise<TokenGrant>;
|
|
601
|
+
/** Fetch the audit trail for a grant (append-only). */
|
|
602
|
+
events(id: string, opts?: RequestOptions): APIPromise<GrantEvent[]>;
|
|
603
|
+
/**
|
|
604
|
+
* Claim the vested-but-unclaimed amount into your custody balance.
|
|
605
|
+
* Idempotent — the SDK auto-attaches an Idempotency-Key, so retrying a
|
|
606
|
+
* timed-out claim never double-credits.
|
|
607
|
+
*
|
|
608
|
+
* Returns `{ status: "no_op" }` if nothing new has vested since the last
|
|
609
|
+
* claim.
|
|
610
|
+
*/
|
|
611
|
+
claim(id: string, opts?: RequestOptions): APIPromise<GrantClaimResult>;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Keys resource — programmatic API-key management.
|
|
616
|
+
*
|
|
617
|
+
* POST /v1/keys create()
|
|
618
|
+
* GET /v1/keys list()
|
|
619
|
+
* DELETE /v1/keys/{id} revoke()
|
|
620
|
+
*
|
|
621
|
+
* `secret` is returned only on `create()` and is never shown again — store
|
|
622
|
+
* it securely at that moment.
|
|
623
|
+
*/
|
|
624
|
+
|
|
625
|
+
interface CreateKeyParams {
|
|
626
|
+
name?: string;
|
|
627
|
+
scopes?: KeyScope[];
|
|
628
|
+
}
|
|
629
|
+
declare class KeysResource extends Resource {
|
|
630
|
+
create(params?: CreateKeyParams, opts?: RequestOptions): APIPromise<ApiKey>;
|
|
631
|
+
list(opts?: RequestOptions): APIPromise<ApiKey[]>;
|
|
632
|
+
revoke(keyId: string, opts?: RequestOptions): APIPromise<{
|
|
633
|
+
revoked: boolean;
|
|
634
|
+
}>;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* Markets resource — discovery, candles, orderbook, public trades, creation.
|
|
639
|
+
*
|
|
640
|
+
* Endpoints wrapped:
|
|
641
|
+
* GET /v1/markets list()
|
|
642
|
+
* GET /v1/markets/{id} retrieve()
|
|
643
|
+
* POST /v1/markets create()
|
|
644
|
+
* GET /v1/candles/{market_id} candles()
|
|
645
|
+
* GET /v1/orderbook/{market_id} orderbook()
|
|
646
|
+
* GET /v1/trades/{market_id} trades() (public tape)
|
|
647
|
+
*/
|
|
648
|
+
|
|
649
|
+
interface ListMarketsParams {
|
|
650
|
+
category?: Category;
|
|
651
|
+
marketType?: MarketType;
|
|
652
|
+
status?: MarketStatus;
|
|
653
|
+
cursor?: string;
|
|
654
|
+
limit?: number;
|
|
655
|
+
}
|
|
656
|
+
interface CreateMarketParams {
|
|
657
|
+
templateId: string;
|
|
658
|
+
params: Record<string, unknown>;
|
|
659
|
+
creatorMetadata?: Record<string, unknown>;
|
|
660
|
+
}
|
|
661
|
+
interface CandlesParams {
|
|
662
|
+
outcomeId: string;
|
|
663
|
+
interval?: CandleInterval;
|
|
664
|
+
fromMs?: number;
|
|
665
|
+
toMs?: number;
|
|
666
|
+
limit?: number;
|
|
667
|
+
}
|
|
668
|
+
interface OrderbookParams {
|
|
669
|
+
outcomeId: string;
|
|
670
|
+
depth?: number;
|
|
671
|
+
}
|
|
672
|
+
interface MarketTradesParams {
|
|
673
|
+
outcomeId?: string;
|
|
674
|
+
cursor?: string;
|
|
675
|
+
limit?: number;
|
|
676
|
+
}
|
|
677
|
+
declare class MarketsResource extends Resource {
|
|
678
|
+
/** List markets — auto-paginates. Iterate with `for await (const m of ...)`. */
|
|
679
|
+
list(params?: ListMarketsParams, opts?: RequestOptions): PagePromise<Market>;
|
|
680
|
+
retrieve(marketId: string, opts?: RequestOptions): APIPromise<Market>;
|
|
681
|
+
create(params: CreateMarketParams, opts?: RequestOptions): APIPromise<Market>;
|
|
682
|
+
candles(marketId: string, params: CandlesParams, opts?: RequestOptions): APIPromise<Candle[]>;
|
|
683
|
+
orderbook(marketId: string, params: OrderbookParams, opts?: RequestOptions): APIPromise<Orderbook>;
|
|
684
|
+
/** Public trade tape for a market (all fills, not your fills). */
|
|
685
|
+
trades(marketId: string, params?: MarketTradesParams, opts?: RequestOptions): PagePromise<Trade>;
|
|
686
|
+
private _buildListQuery;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* Orders resource — your orders.
|
|
691
|
+
*
|
|
692
|
+
* POST /v1/orders place()
|
|
693
|
+
* DELETE /v1/orders/{id} cancel()
|
|
694
|
+
* GET /v1/account/orders list()
|
|
695
|
+
*/
|
|
696
|
+
|
|
697
|
+
interface PlaceOrderParams {
|
|
698
|
+
marketId: string;
|
|
699
|
+
outcomeId: string;
|
|
700
|
+
side: Side;
|
|
701
|
+
orderType: OrderType;
|
|
702
|
+
size: Decimal | number;
|
|
703
|
+
price?: Decimal | number;
|
|
704
|
+
clientOrderId?: string;
|
|
705
|
+
timeInForce?: TimeInForce;
|
|
706
|
+
}
|
|
707
|
+
interface ListOrdersParams {
|
|
708
|
+
status?: OrderStatus;
|
|
709
|
+
cursor?: string;
|
|
710
|
+
limit?: number;
|
|
711
|
+
}
|
|
712
|
+
declare class OrdersResource extends Resource {
|
|
713
|
+
place(params: PlaceOrderParams, opts?: RequestOptions): APIPromise<Order>;
|
|
714
|
+
cancel(orderId: string, opts?: RequestOptions): APIPromise<Order>;
|
|
715
|
+
list(params?: ListOrdersParams, opts?: RequestOptions): PagePromise<Order>;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Sandbox resource — self-serve key mint + Builder track applications.
|
|
720
|
+
*
|
|
721
|
+
* Sandbox is a *tier* on the production API (tier=self_serve), not a separate
|
|
722
|
+
* host. Mint an anonymous sk_live_ key with $10/order + $100/day notional caps,
|
|
723
|
+
* or apply for a Builder track (self_serve / rfb-* / genesis / etc.) to get an
|
|
724
|
+
* auto-provisioned key for auto-approve tracks or queued human review for
|
|
725
|
+
* genesis / institutional.
|
|
726
|
+
*
|
|
727
|
+
* POST /v1/sandbox-keys keys.mint()
|
|
728
|
+
* POST /v1/apply apply.create()
|
|
729
|
+
* GET /v1/apply/{code} apply.retrieve()
|
|
730
|
+
*/
|
|
731
|
+
|
|
732
|
+
interface SandboxKeyMintParams {
|
|
733
|
+
orgName: string;
|
|
734
|
+
contactEmail?: string;
|
|
735
|
+
}
|
|
736
|
+
interface ApplyCreateParams {
|
|
737
|
+
/**
|
|
738
|
+
* Track ID — one of: `genesis`, `self_serve`, `rfb-japan-app`, `rfb-ai-agent`,
|
|
739
|
+
* `rfb-telegram-bot`, `rfb-news-media`, `rfb-sports`, `rfb-election`,
|
|
740
|
+
* `rfb-terminal`, `rfb-mm-stack`, `data`, `app`, `agent`, `distribution`,
|
|
741
|
+
* `market`, `liquidity`, `oracle`, `reviewer`, `operator`, `institutional`.
|
|
742
|
+
*
|
|
743
|
+
* Self-serve + RFB tracks auto-provision an sk_live_ key on submit (returned
|
|
744
|
+
* in `api_key` on the response). `genesis` and `institutional` queue for
|
|
745
|
+
* human review (~5 business days).
|
|
746
|
+
*/
|
|
747
|
+
track: string;
|
|
748
|
+
email?: string;
|
|
749
|
+
org?: string;
|
|
750
|
+
url?: string;
|
|
751
|
+
description?: string;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* SandboxKeysResource — POST /v1/sandbox-keys.
|
|
755
|
+
* Anonymous, per-IP-quota, returns a tier=self_serve sk_live_ key shown ONCE.
|
|
756
|
+
*/
|
|
757
|
+
declare class SandboxKeysResource extends Resource {
|
|
758
|
+
mint(params: SandboxKeyMintParams, opts?: RequestOptions): APIPromise<SandboxKeyResult>;
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* ApplyResource — POST /v1/apply and GET /v1/apply/{code}.
|
|
762
|
+
* Apply for a Builder track; auto-approve tracks return an sk_live_ key
|
|
763
|
+
* immediately (shown ONCE), review tracks return an application_code.
|
|
764
|
+
*/
|
|
765
|
+
declare class ApplyResource extends Resource {
|
|
766
|
+
create(params: ApplyCreateParams, opts?: RequestOptions): APIPromise<ApplicationResult>;
|
|
767
|
+
retrieve(applicationCode: string, opts?: RequestOptions): APIPromise<ApplicationStatus>;
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Legacy top-level namespace kept for backward compatibility of imports.
|
|
771
|
+
* The v2 flow uses `pax.sandboxKeys.mint()` and `pax.apply.create()` directly.
|
|
772
|
+
* Old v1 methods (faucet / reset / mockOracle) were removed when sandbox
|
|
773
|
+
* became a tier on production rather than a separate host.
|
|
774
|
+
*/
|
|
775
|
+
declare class SandboxResource extends Resource {
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* Templates resource — parameterized market blueprints.
|
|
780
|
+
*
|
|
781
|
+
* GET /v1/markets/templates list()
|
|
782
|
+
*
|
|
783
|
+
* Templates aren't paginated (small enum-like set), so this returns
|
|
784
|
+
* MarketTemplate[] directly.
|
|
785
|
+
*/
|
|
786
|
+
|
|
787
|
+
interface ListTemplatesParams {
|
|
788
|
+
category?: Category;
|
|
789
|
+
marketType?: MarketType;
|
|
790
|
+
}
|
|
791
|
+
declare class TemplatesResource extends Resource {
|
|
792
|
+
list(params?: ListTemplatesParams, opts?: RequestOptions): APIPromise<MarketTemplate[]>;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* PaxClient — top-level entry point.
|
|
797
|
+
*
|
|
798
|
+
* Auth modes (auto-detected from constructor):
|
|
799
|
+
* 1. HMAC — pass `apiKey` + `secret` + `passphrase`. Every request
|
|
800
|
+
* signed with 5 POLY_* headers. Use for high-security trading.
|
|
801
|
+
* 2. API Key — pass only `apiKey`. Sent via `X-Api-Key` header.
|
|
802
|
+
* 3. Bearer — pass `bearerToken`. Session-based, browser/mobile.
|
|
803
|
+
*
|
|
804
|
+
* Resources hang off the client, e.g. `pax.markets.list()`, following
|
|
805
|
+
* the Stripe/OpenAI/Anthropic convention.
|
|
806
|
+
*
|
|
807
|
+
* @example
|
|
808
|
+
* import { PaxClient } from "@predictasiax/api";
|
|
809
|
+
*
|
|
810
|
+
* // Mint an anonymous sandbox key first (30 sec, no email):
|
|
811
|
+
* // curl -X POST https://api.predictasiax.com/v1/sandbox-keys \
|
|
812
|
+
* // -H 'Content-Type: application/json' -d '{"org_name":"my-app"}'
|
|
813
|
+
* // → { api_key: "sk_live_...", tier: "self_serve", ... }
|
|
814
|
+
* const pax = new PaxClient({ apiKey: "sk_live_..." });
|
|
815
|
+
* const account = await pax.account.retrieve();
|
|
816
|
+
*
|
|
817
|
+
* for await (const market of pax.markets.list({ category: "crypto" })) {
|
|
818
|
+
* console.log(market.id, market.title);
|
|
819
|
+
* }
|
|
820
|
+
*
|
|
821
|
+
* const { data, response, requestId } =
|
|
822
|
+
* await pax.orders.place({
|
|
823
|
+
* marketId: "m_abc", outcomeId: "yes",
|
|
824
|
+
* side: "buy", orderType: "market", size: "10",
|
|
825
|
+
* }, { idempotencyKey: "ord_1" }).withResponse();
|
|
826
|
+
*/
|
|
827
|
+
|
|
828
|
+
declare const VERSION = "2.0.0";
|
|
829
|
+
type PaxClientOptions = HttpClientOptions;
|
|
830
|
+
declare class PaxClient {
|
|
831
|
+
private readonly _http;
|
|
832
|
+
readonly markets: MarketsResource;
|
|
833
|
+
readonly templates: TemplatesResource;
|
|
834
|
+
readonly orders: OrdersResource;
|
|
835
|
+
readonly account: AccountResource;
|
|
836
|
+
readonly keys: KeysResource;
|
|
837
|
+
readonly sandbox: SandboxResource;
|
|
838
|
+
readonly sandboxKeys: SandboxKeysResource;
|
|
839
|
+
readonly apply: ApplyResource;
|
|
840
|
+
readonly grants: GrantsResource;
|
|
841
|
+
constructor(opts: PaxClientOptions);
|
|
842
|
+
get baseUrl(): string;
|
|
843
|
+
get userAgent(): string;
|
|
844
|
+
/** GET /v1/health — top-level, not paginated, always safe. */
|
|
845
|
+
health(opts?: RequestOptions): APIPromise<HealthStatus>;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* PaxWSClient — real-time market data + private events over WebSocket.
|
|
850
|
+
*
|
|
851
|
+
* Features
|
|
852
|
+
* - Isomorphic: uses native `WebSocket` in browsers / Deno / Bun / Edge,
|
|
853
|
+
* and the `ws` package in Node.js. Runtime auto-detected.
|
|
854
|
+
* - Auto-reconnect with exponential backoff (full jitter).
|
|
855
|
+
* - Subscription memory: dynamic subscribe/unsubscribe are tracked
|
|
856
|
+
* locally and resent on every reconnect. Callers never have to
|
|
857
|
+
* re-subscribe manually after a network blip.
|
|
858
|
+
* - Per-event handlers (`.on("fast_tick", cb)`), catch-all (`.onAny`),
|
|
859
|
+
* and typed error events (`.on("error", cb)`).
|
|
860
|
+
* - `.connect()` returns a Promise that resolves on OPEN and rejects
|
|
861
|
+
* on the first connect failure (before entering the reconnect loop).
|
|
862
|
+
*
|
|
863
|
+
* @example
|
|
864
|
+
* const ws = new PaxWSClient({ apiKey: "sk_live_...",
|
|
865
|
+
* subscribeOnConnect: ["fast_tick", "account"] });
|
|
866
|
+
* ws.on("fast_tick", (e) => console.log(e));
|
|
867
|
+
* await ws.connect();
|
|
868
|
+
* ws.subscribe(["trade_executed"]);
|
|
869
|
+
* // ... later
|
|
870
|
+
* ws.close();
|
|
871
|
+
*/
|
|
872
|
+
|
|
873
|
+
interface WsEvent {
|
|
874
|
+
type?: string;
|
|
875
|
+
[k: string]: unknown;
|
|
876
|
+
}
|
|
877
|
+
type WsHandler = (evt: WsEvent) => void;
|
|
878
|
+
type WsErrorHandler = (err: Error) => void;
|
|
879
|
+
interface PaxWSClientOptions {
|
|
880
|
+
apiKey?: string;
|
|
881
|
+
bearerToken?: string;
|
|
882
|
+
env?: Env;
|
|
883
|
+
url?: string;
|
|
884
|
+
locale?: string;
|
|
885
|
+
reconnect?: boolean;
|
|
886
|
+
backoffMinSec?: number;
|
|
887
|
+
backoffMaxSec?: number;
|
|
888
|
+
subscribeOnConnect?: string[];
|
|
889
|
+
pingIntervalMs?: number;
|
|
890
|
+
/** Injectable WebSocket constructor — for testing or custom runtimes. */
|
|
891
|
+
WebSocketImpl?: typeof globalThis.WebSocket;
|
|
892
|
+
}
|
|
893
|
+
declare class PaxWSClient {
|
|
894
|
+
readonly url: string;
|
|
895
|
+
private readonly apiKey?;
|
|
896
|
+
private readonly bearerToken?;
|
|
897
|
+
private locale?;
|
|
898
|
+
private readonly reconnect;
|
|
899
|
+
private readonly backoffMinSec;
|
|
900
|
+
private readonly backoffMaxSec;
|
|
901
|
+
private readonly pingIntervalMs;
|
|
902
|
+
private readonly wsImplOverride?;
|
|
903
|
+
private readonly handlers;
|
|
904
|
+
private readonly catchAll;
|
|
905
|
+
private readonly errorHandlers;
|
|
906
|
+
/** Every subscribe/unsubscribe is remembered — resent on reconnect. */
|
|
907
|
+
private readonly subscriptions;
|
|
908
|
+
private ws;
|
|
909
|
+
private state;
|
|
910
|
+
private backoffCurrent;
|
|
911
|
+
private pingTimer;
|
|
912
|
+
private stopRequested;
|
|
913
|
+
constructor(opts?: PaxWSClientOptions);
|
|
914
|
+
on(eventType: string, handler: WsHandler): this;
|
|
915
|
+
off(eventType: string, handler: WsHandler): this;
|
|
916
|
+
onAny(handler: WsHandler): this;
|
|
917
|
+
onError(handler: WsErrorHandler): this;
|
|
918
|
+
subscribe(channels: string[]): void;
|
|
919
|
+
unsubscribe(channels: string[]): void;
|
|
920
|
+
auth(token?: string): void;
|
|
921
|
+
setLocale(locale: string): void;
|
|
922
|
+
isOpen(): boolean;
|
|
923
|
+
/**
|
|
924
|
+
* Connect once and resolve on OPEN. If `reconnect` is true, subsequent
|
|
925
|
+
* disconnects will silently trigger reconnect attempts in the background.
|
|
926
|
+
* If the initial connect fails and `reconnect` is true, the client keeps
|
|
927
|
+
* trying — the returned promise still resolves as soon as the first OPEN
|
|
928
|
+
* happens.
|
|
929
|
+
*/
|
|
930
|
+
connect(): Promise<void>;
|
|
931
|
+
/**
|
|
932
|
+
* Legacy: connect + block forever, re-connecting on close until close().
|
|
933
|
+
* Equivalent to `await client.connect(); await new Promise(r => client.on("close", r))`.
|
|
934
|
+
* Kept for parity with Python SDK's `run()`.
|
|
935
|
+
*/
|
|
936
|
+
run(): Promise<void>;
|
|
937
|
+
/** Stop reconnect loop + close current socket. */
|
|
938
|
+
close(): void;
|
|
939
|
+
private _send;
|
|
940
|
+
private _connectOnce;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/**
|
|
944
|
+
* HMAC signing helpers — Polymarket-compatible 5-header pattern.
|
|
945
|
+
*
|
|
946
|
+
* Signature construction:
|
|
947
|
+
* message = timestamp_ms + method_upper + path_with_query + body
|
|
948
|
+
* signature = base64(HMAC-SHA256(secret, message))
|
|
949
|
+
*
|
|
950
|
+
* Headers sent:
|
|
951
|
+
* POLY_ACCESS_KEY: <key_id>
|
|
952
|
+
* POLY_TIMESTAMP: <ms epoch>
|
|
953
|
+
* POLY_PASSPHRASE: <passphrase>
|
|
954
|
+
* POLY_SIGNATURE: <base64 sig>
|
|
955
|
+
*
|
|
956
|
+
* Server rejects with 401 INVALID_SIGNATURE if timestamp is more than
|
|
957
|
+
* ±30 seconds from server clock — sync your machine via NTP.
|
|
958
|
+
*
|
|
959
|
+
* Runtime support:
|
|
960
|
+
* - Node.js 18+ / Bun / Deno → node:crypto (via createHmac)
|
|
961
|
+
* - Browser / Cloudflare Workers / Vercel Edge → WebCrypto (subtle.sign)
|
|
962
|
+
*
|
|
963
|
+
* `signRequest` is async because WebCrypto's subtle.sign is async.
|
|
964
|
+
*/
|
|
965
|
+
interface HmacHeaders {
|
|
966
|
+
POLY_ACCESS_KEY: string;
|
|
967
|
+
POLY_TIMESTAMP: string;
|
|
968
|
+
POLY_PASSPHRASE: string;
|
|
969
|
+
POLY_SIGNATURE: string;
|
|
970
|
+
}
|
|
971
|
+
interface SignInput {
|
|
972
|
+
method: string;
|
|
973
|
+
path: string;
|
|
974
|
+
body: string;
|
|
975
|
+
keyId: string;
|
|
976
|
+
secret: string;
|
|
977
|
+
passphrase: string;
|
|
978
|
+
timestampMs?: number;
|
|
979
|
+
}
|
|
980
|
+
/** Return the canonical signing message (exposed for debugging). */
|
|
981
|
+
declare function buildMessage(method: string, path: string, body: string, timestampMs: number): string;
|
|
982
|
+
/**
|
|
983
|
+
* Sign a PAX request. Returns the four POLY_* headers.
|
|
984
|
+
*
|
|
985
|
+
* On Node this uses `node:crypto`; on browser / edge runtimes it falls back
|
|
986
|
+
* to WebCrypto. Both paths are byte-for-byte identical because HMAC-SHA256
|
|
987
|
+
* is deterministic.
|
|
988
|
+
*/
|
|
989
|
+
declare function signRequest(input: SignInput): Promise<HmacHeaders>;
|
|
990
|
+
|
|
991
|
+
/**
|
|
992
|
+
* Exception hierarchy for the PAX SDK.
|
|
993
|
+
*
|
|
994
|
+
* Every PAX error response returns a canonical envelope with an `error.code`.
|
|
995
|
+
* The client maps HTTP status + error.code to the most specific error class.
|
|
996
|
+
* Catch `PaxError` for a blanket catch, or specific subclasses for granular
|
|
997
|
+
* handling.
|
|
998
|
+
*/
|
|
999
|
+
interface PaxErrorDetails {
|
|
1000
|
+
[key: string]: unknown;
|
|
1001
|
+
}
|
|
1002
|
+
interface PaxErrorPayload {
|
|
1003
|
+
ok: false;
|
|
1004
|
+
error: string | {
|
|
1005
|
+
code: string;
|
|
1006
|
+
message: string;
|
|
1007
|
+
details?: PaxErrorDetails;
|
|
1008
|
+
};
|
|
1009
|
+
message?: string;
|
|
1010
|
+
meta?: {
|
|
1011
|
+
request_id?: string;
|
|
1012
|
+
[k: string]: unknown;
|
|
1013
|
+
};
|
|
1014
|
+
}
|
|
1015
|
+
declare class PaxError extends Error {
|
|
1016
|
+
readonly code: string;
|
|
1017
|
+
readonly httpStatus: number;
|
|
1018
|
+
readonly requestId: string | null;
|
|
1019
|
+
readonly details: PaxErrorDetails;
|
|
1020
|
+
readonly responseJson: PaxErrorPayload | null;
|
|
1021
|
+
constructor(opts: {
|
|
1022
|
+
code: string;
|
|
1023
|
+
message: string;
|
|
1024
|
+
httpStatus: number;
|
|
1025
|
+
requestId?: string | null;
|
|
1026
|
+
details?: PaxErrorDetails;
|
|
1027
|
+
responseJson?: PaxErrorPayload | null;
|
|
1028
|
+
});
|
|
1029
|
+
}
|
|
1030
|
+
declare class PaxAuthError extends PaxError {
|
|
1031
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0]);
|
|
1032
|
+
}
|
|
1033
|
+
declare class PaxWrongEnvKeyError extends PaxAuthError {
|
|
1034
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0]);
|
|
1035
|
+
}
|
|
1036
|
+
declare class PaxValidationError extends PaxError {
|
|
1037
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0]);
|
|
1038
|
+
}
|
|
1039
|
+
declare class PaxNotFoundError extends PaxError {
|
|
1040
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0]);
|
|
1041
|
+
}
|
|
1042
|
+
declare class PaxSandboxOnlyError extends PaxNotFoundError {
|
|
1043
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0]);
|
|
1044
|
+
}
|
|
1045
|
+
declare class PaxConflictError extends PaxError {
|
|
1046
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0]);
|
|
1047
|
+
}
|
|
1048
|
+
declare class PaxRateLimitError extends PaxError {
|
|
1049
|
+
readonly retryAfter: number | null;
|
|
1050
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0] & {
|
|
1051
|
+
retryAfter?: number | null;
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
declare class PaxServerError extends PaxError {
|
|
1055
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0]);
|
|
1056
|
+
}
|
|
1057
|
+
declare class PaxReadOnlyModeError extends PaxError {
|
|
1058
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0]);
|
|
1059
|
+
}
|
|
1060
|
+
declare class PaxCircuitBreakerError extends PaxError {
|
|
1061
|
+
constructor(o: ConstructorParameters<typeof PaxError>[0]);
|
|
1062
|
+
}
|
|
1063
|
+
declare function buildError(httpStatus: number, payload: PaxErrorPayload, retryAfter?: number | null): PaxError;
|
|
1064
|
+
|
|
1065
|
+
/**
|
|
1066
|
+
* Retry logic with exponential backoff for transient failures.
|
|
1067
|
+
*
|
|
1068
|
+
* Policy (matches docs.predictasiax.com/errors#retry-policy):
|
|
1069
|
+
* - 4xx except 429: DO NOT retry.
|
|
1070
|
+
* - 429: respect Retry-After header, otherwise exp backoff.
|
|
1071
|
+
* - 500/502/504: retry with exp backoff.
|
|
1072
|
+
* - 503 READ_ONLY_MODE / CIRCUIT_BREAKER_OPEN: do not retry.
|
|
1073
|
+
*/
|
|
1074
|
+
/** Full-jitter exponential backoff. */
|
|
1075
|
+
declare function computeBackoff(attempt: number, base?: number, cap?: number, jitter?: boolean): number;
|
|
1076
|
+
declare function runWithRetry<T>(fn: () => Promise<T>, opts?: {
|
|
1077
|
+
maxAttempts?: number;
|
|
1078
|
+
retryableStatuses?: number[];
|
|
1079
|
+
onRetry?: (attempt: number, error: Error) => void;
|
|
1080
|
+
}): Promise<T>;
|
|
1081
|
+
|
|
1082
|
+
export { APIPromise, type APIResponseInfo, type Account, type AccountBalance, AccountResource, type ApiKey, type ApplicationResult, type ApplicationStatus, type ApplyCreateParams, ApplyResource, type Candle, type CandleInterval, type CandlesParams, type Category, type CreateKeyParams, type CreateMarketParams, CursorPage, type CursorPageInit, type CursorPageParams, type Decimal, type Env, type Envelope, type GrantClaimResult, type GrantEvent, type GrantEventType, type GrantPhase, type GrantTier, type GrantVesting, GrantsResource, type HealthStatus, type HmacHeaders, type HttpClientOptions, type KeyScope, KeysResource, type ListEnvelope, type ListMarketsParams, type ListOrdersParams, type ListTemplatesParams, type ListTradesParams, type Market, type MarketStatus, type MarketTemplate, type MarketTradesParams, type MarketType, MarketsResource, type Order, type OrderStatus, type OrderType, type Orderbook, type OrderbookLevel, type OrderbookParams, OrdersResource, type Outcome, PagePromise, PaxAuthError, PaxCircuitBreakerError, PaxClient, type PaxClientOptions, PaxConflictError, PaxError, type PaxErrorDetails, type PaxErrorPayload, PaxNotFoundError, PaxRateLimitError, PaxReadOnlyModeError, PaxSandboxOnlyError, PaxServerError, PaxValidationError, PaxWSClient, type PaxWSClientOptions, PaxWrongEnvKeyError, type PlaceOrderParams, type Position, type RequestOptions, type ResponseMeta, type SandboxKeyMintParams, type SandboxKeyResult, SandboxKeysResource, SandboxResource, type Side, type SignInput, TemplatesResource, type Tier, type TierLimits, type TimeInForce, type TokenGrant, type Trade, VERSION, type WithResponseResult, type WsEvent, type WsHandler, buildError, buildMessage, computeBackoff, runWithRetry, signRequest };
|