@predictasiax/api 2.5.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -35,9 +35,9 @@ __export(index_exports, {
35
35
  ApplyResource: () => ApplyResource,
36
36
  AuditResource: () => AuditResource,
37
37
  CursorPage: () => CursorPage,
38
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
38
39
  FeesResource: () => FeesResource,
39
40
  GrantsResource: () => GrantsResource,
40
- KeysResource: () => KeysResource,
41
41
  MarketsResource: () => MarketsResource,
42
42
  OrdersResource: () => OrdersResource,
43
43
  PagePromise: () => PagePromise,
@@ -56,49 +56,33 @@ __export(index_exports, {
56
56
  PaxWrongEnvKeyError: () => PaxWrongEnvKeyError,
57
57
  SandboxKeysResource: () => SandboxKeysResource,
58
58
  SandboxResource: () => SandboxResource,
59
+ SettleResource: () => SettleResource,
59
60
  TemplatesResource: () => TemplatesResource,
60
61
  VERSION: () => VERSION2,
61
62
  attachRef: () => attachRef,
63
+ buildCanonical: () => buildCanonical,
62
64
  buildError: () => buildError,
63
- buildMessage: () => buildMessage,
64
65
  clearRef: () => clearRef,
65
66
  computeBackoff: () => computeBackoff,
67
+ expectedProofLength: () => expectedProofLength,
68
+ normalizeBaseUrl: () => normalizeBaseUrl,
66
69
  runWithRetry: () => runWithRetry,
67
70
  signRequest: () => signRequest
68
71
  });
69
72
  module.exports = __toCommonJS(index_exports);
70
73
 
71
74
  // src/auth.ts
72
- function buildMessage(method, path, body, timestampMs) {
73
- return `${timestampMs}${method.toUpperCase()}${path}${body || ""}`;
75
+ function buildCanonical(timestamp, nonce, method, pathWithQuery, body) {
76
+ return [String(timestamp), nonce, method.toUpperCase(), pathWithQuery, body || ""].join("\n");
74
77
  }
75
- var _nodeCrypto = null;
76
- var _cryptoLoadAttempted = false;
77
- async function loadNodeCrypto() {
78
- if (_cryptoLoadAttempted) return _nodeCrypto;
79
- _cryptoLoadAttempted = true;
80
- try {
81
- const mod = await import("crypto");
82
- _nodeCrypto = { createHmac: mod.createHmac };
83
- return _nodeCrypto;
84
- } catch {
85
- return null;
78
+ function randomNonce() {
79
+ const g = globalThis.crypto;
80
+ if (g && typeof g.getRandomValues === "function") {
81
+ const bytes = new Uint8Array(16);
82
+ g.getRandomValues(bytes);
83
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
86
84
  }
87
- }
88
- function hasSubtleCrypto() {
89
- return typeof globalThis.crypto?.subtle?.sign === "function";
90
- }
91
- async function signWithWebCrypto(secret, message) {
92
- const enc = new TextEncoder();
93
- const key = await globalThis.crypto.subtle.importKey(
94
- "raw",
95
- enc.encode(secret),
96
- { name: "HMAC", hash: "SHA-256" },
97
- false,
98
- ["sign"]
99
- );
100
- const sig = await globalThis.crypto.subtle.sign("HMAC", key, enc.encode(message));
101
- return arrayBufferToBase64(sig);
85
+ throw new Error("No secure random source available for the HMAC nonce");
102
86
  }
103
87
  function arrayBufferToBase64(buf) {
104
88
  const bytes = new Uint8Array(buf);
@@ -107,21 +91,28 @@ function arrayBufferToBase64(buf) {
107
91
  for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
108
92
  return globalThis.btoa(bin);
109
93
  }
110
- async function signWithNodeCrypto(secret, message) {
111
- const nc = await loadNodeCrypto();
112
- if (!nc) throw new Error("No HMAC backend \u2014 neither node:crypto nor WebCrypto available in this runtime");
113
- return nc.createHmac("sha256", secret).update(message).digest("base64");
94
+ async function hmacSha256Base64(key, message) {
95
+ const subtle = globalThis.crypto?.subtle;
96
+ if (subtle && typeof subtle.sign === "function") {
97
+ const enc = new TextEncoder();
98
+ const k = await subtle.importKey("raw", enc.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
99
+ return arrayBufferToBase64(await subtle.sign("HMAC", k, enc.encode(message)));
100
+ }
101
+ const mod = await import("crypto");
102
+ return mod.createHmac("sha256", key).update(message).digest("base64");
114
103
  }
115
104
  async function signRequest(input) {
116
- const ts = String(input.timestampMs ?? Date.now());
117
- const methodUpper = input.method.toUpperCase();
118
- const message = ts + methodUpper + input.path + (input.body || "");
119
- const signature = hasSubtleCrypto() ? await signWithWebCrypto(input.secret, message) : await signWithNodeCrypto(input.secret, message);
105
+ if (!input.keyId || !input.apiKey) {
106
+ throw new Error("HMAC signing needs both keyId (api_...) and apiKey (sk_live_...)");
107
+ }
108
+ const ts = String(Math.floor(input.timestampSec ?? Date.now() / 1e3));
109
+ const nonce = input.nonce ?? randomNonce();
110
+ const canonical = buildCanonical(ts, nonce, input.method, input.pathWithQuery, input.body);
120
111
  return {
121
- POLY_ACCESS_KEY: input.keyId,
122
- POLY_TIMESTAMP: ts,
123
- POLY_PASSPHRASE: input.passphrase,
124
- POLY_SIGNATURE: signature
112
+ "PAX-ADDRESS": input.keyId,
113
+ "PAX-TIMESTAMP": ts,
114
+ "PAX-NONCE": nonce,
115
+ "PAX-SIGNATURE": await hmacSha256Base64(input.apiKey, canonical)
125
116
  };
126
117
  }
127
118
 
@@ -279,6 +270,16 @@ var PROTECTED_HEADERS = /* @__PURE__ */ new Set(
279
270
  "poly_timestamp",
280
271
  "poly_passphrase",
281
272
  "poly_signature",
273
+ "pax-address",
274
+ "pax-timestamp",
275
+ "pax-nonce",
276
+ "pax-signature",
277
+ "pax-method",
278
+ "poly-address",
279
+ "poly-timestamp",
280
+ "poly-nonce",
281
+ "poly-signature",
282
+ "poly-method",
282
283
  "idempotency-key",
283
284
  "cache-control"
284
285
  ]
@@ -367,19 +368,19 @@ async function runWithRetry(fn, opts = {}) {
367
368
  }
368
369
 
369
370
  // src/http.ts
370
- var VERSION = "2.2.0";
371
- var ENV_URLS = {
372
- production: "https://api.predictasiax.com/v1",
373
- prod: "https://api.predictasiax.com/v1",
374
- live: "https://api.predictasiax.com/v1",
375
- sandbox: "https://api.predictasiax.com/v1",
376
- test: "https://api.predictasiax.com/v1"
377
- };
371
+ var VERSION = "3.0.0";
372
+ var DEFAULT_BASE_URL = "https://api.predictasiax.com";
373
+ var API_KEY_PREFIXES = ["sk_live_", "sk_test_", "pax_"];
374
+ function normalizeBaseUrl(url) {
375
+ let u = url.trim().replace(/\/+$/, "");
376
+ if (u.endsWith("/v1")) u = u.slice(0, -3);
377
+ return u;
378
+ }
378
379
  var DEFAULT_TIMEOUT_MS = 3e4;
379
380
  var DEFAULT_MAX_RETRIES = 5;
380
381
  var DEFAULT_MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
381
382
  var DEFAULT_USER_AGENT = `pax-api-ts/${VERSION}`;
382
- var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
383
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
383
384
  function isLoopback(hostname) {
384
385
  return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
385
386
  }
@@ -462,9 +463,15 @@ async function readCappedText(response, maxBytes) {
462
463
  var HttpClient = class {
463
464
  baseUrl;
464
465
  userAgent;
466
+ /** "hmac" | "api_key" | "bearer" | "none" */
467
+ get authMode() {
468
+ if (this.keyId && this.apiKey) return "hmac";
469
+ if (this.apiKey) return "api_key";
470
+ if (this.bearerToken) return "bearer";
471
+ return "none";
472
+ }
465
473
  apiKey;
466
- secret;
467
- passphrase;
474
+ keyId;
468
475
  bearerToken;
469
476
  timeoutMs;
470
477
  maxRetries;
@@ -474,23 +481,30 @@ var HttpClient = class {
474
481
  fetchImpl;
475
482
  fetchOptions;
476
483
  constructor(opts) {
477
- if (!opts.apiKey && !opts.bearerToken) {
478
- throw new Error("Provide apiKey or bearerToken");
484
+ if (opts.secret !== void 0 || opts.passphrase !== void 0) {
485
+ throw new Error(
486
+ "secret/passphrase are not part of the PAX API. For HMAC signing pass apiKey: 'sk_live_...' (the HMAC key) and keyId: 'api_...' (sent as PAX-ADDRESS)."
487
+ );
488
+ }
489
+ const apiKey = opts.apiKey === "anonymous" ? void 0 : opts.apiKey;
490
+ if (apiKey !== void 0 && !API_KEY_PREFIXES.some((p) => apiKey.startsWith(p))) {
491
+ throw new Error("apiKey must start with sk_live_, sk_test_ or pax_");
492
+ }
493
+ if (opts.keyId !== void 0 && !apiKey) {
494
+ throw new Error("keyId (HMAC) needs apiKey: 'sk_live_...' as the signing key");
479
495
  }
480
- if (opts.secret && !opts.passphrase) {
481
- throw new Error("Provide passphrase together with secret for HMAC");
496
+ if (apiKey && opts.bearerToken) {
497
+ throw new Error("Pass either apiKey or bearerToken, not both");
482
498
  }
483
499
  if (typeof window !== "undefined" && !opts.dangerouslyAllowBrowser) {
484
500
  throw new Error(
485
501
  "It looks like you're running PAX SDK in a browser. Server-side keys should never ship to end-users. If this is intentional (e.g. read-only sandbox key on a dev tool), pass `dangerouslyAllowBrowser: true`."
486
502
  );
487
503
  }
488
- this.apiKey = opts.apiKey;
489
- this.secret = opts.secret;
490
- this.passphrase = opts.passphrase;
504
+ this.apiKey = apiKey;
505
+ this.keyId = opts.keyId;
491
506
  this.bearerToken = opts.bearerToken;
492
- const env = (opts.env ?? "production").toLowerCase();
493
- const rawBaseUrl = (opts.baseUrl ?? ENV_URLS[env] ?? ENV_URLS.production).replace(/\/$/, "");
507
+ const rawBaseUrl = normalizeBaseUrl(opts.baseUrl ?? DEFAULT_BASE_URL);
494
508
  validateBaseUrl(rawBaseUrl, opts.allowInsecureHttp ?? false);
495
509
  this.baseUrl = rawBaseUrl;
496
510
  this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -526,19 +540,18 @@ var HttpClient = class {
526
540
  };
527
541
  if (body) managed["Content-Type"] = "application/json";
528
542
  if (idempotencyKey) managed["Idempotency-Key"] = idempotencyKey;
529
- if (this.secret && this.passphrase && this.apiKey) {
543
+ if (this.keyId && this.apiKey) {
530
544
  const sig = await signRequest({
531
545
  method,
532
- path: pathWithQuery,
546
+ pathWithQuery,
533
547
  body,
534
- keyId: this.apiKey,
535
- secret: this.secret,
536
- passphrase: this.passphrase,
537
- timestampMs: Date.now() + this.clockOffsetMs
548
+ keyId: this.keyId,
549
+ apiKey: this.apiKey,
550
+ timestampSec: (Date.now() + this.clockOffsetMs) / 1e3
538
551
  });
539
552
  Object.assign(managed, sig);
540
553
  } else if (this.apiKey) {
541
- managed["X-Api-Key"] = this.apiKey;
554
+ managed["Authorization"] = `Bearer ${this.apiKey}`;
542
555
  } else if (this.bearerToken) {
543
556
  managed["Authorization"] = `Bearer ${this.bearerToken}`;
544
557
  }
@@ -756,39 +769,50 @@ var Resource = class {
756
769
  });
757
770
  }
758
771
  };
759
- function paginationParams(p) {
760
- if (!p) return {};
761
- const out = {};
762
- if (p.limit !== void 0) out.limit = p.limit;
763
- if (typeof p.cursor === "string") out.cursor = p.cursor;
764
- return out;
765
- }
766
772
 
767
773
  // src/resources/account.ts
768
774
  var AccountResource = class extends Resource {
769
- retrieve(opts) {
775
+ balance(opts) {
770
776
  return this._apiPromise(
771
- () => this._http.request("GET", "/v1/account", void 0, void 0, opts)
777
+ () => this._http.request("GET", "/v1/balance", void 0, void 0, opts)
772
778
  );
773
779
  }
774
- positions(opts) {
780
+ /** @deprecated Use balance(). Kept as an alias. */
781
+ retrieve(opts) {
782
+ return this.balance(opts);
783
+ }
784
+ portfolio(opts) {
775
785
  return this._apiPromise(
776
- () => this._http.request("GET", "/v1/account/positions", void 0, void 0, opts)
786
+ () => this._http.request("GET", "/v1/portfolio", void 0, void 0, opts)
777
787
  );
778
788
  }
779
- trades(params = {}, opts) {
780
- const query = paginationParams({ limit: params.limit ?? 50, cursor: params.cursor });
781
- if (params.marketId) query.market_id = params.marketId;
782
- const fetchNext = (cursor, ro) => this.trades({ ...params, cursor }, ro);
783
- return this._pagePromise(
784
- () => this._http.request("GET", "/v1/account/trades", query, void 0, opts),
785
- fetchNext,
786
- opts
789
+ positions(opts) {
790
+ return this._apiPromise(
791
+ () => this._http.request("GET", "/v1/positions", void 0, void 0, opts)
787
792
  );
788
793
  }
789
794
  };
790
795
 
791
796
  // src/resources/audit.ts
797
+ var HEX32 = /^[0-9a-fA-F]{64}$/;
798
+ function isHex32(x) {
799
+ return typeof x === "string" && HEX32.test(x);
800
+ }
801
+ function expectedProofLength(leafCount) {
802
+ let n = Math.floor(Number(leafCount));
803
+ if (!Number.isFinite(n) || n < 1) throw new Error("leafCount must be >= 1");
804
+ let depth = 0;
805
+ while (n > 1) {
806
+ n = Math.ceil(n / 2);
807
+ depth++;
808
+ }
809
+ return depth;
810
+ }
811
+ function validProofShape(leaf, root, proof, expectedLength) {
812
+ if (!isHex32(leaf) || !isHex32(root)) return false;
813
+ if (!Array.isArray(proof) || proof.length !== expectedLength) return false;
814
+ return proof.every(isHex32);
815
+ }
792
816
  function hexToBytes(hex) {
793
817
  const out = new Uint8Array(hex.length / 2);
794
818
  for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.substr(i * 2, 2), 16);
@@ -949,7 +973,7 @@ function resolveSyncSha256() {
949
973
  }
950
974
  return sha256Pure;
951
975
  }
952
- var AuditResource = class extends Resource {
976
+ var AuditResource = class _AuditResource extends Resource {
953
977
  status(opts) {
954
978
  return this._apiPromise(
955
979
  () => this._http.request("GET", "/v1/audit/status", void 0, void 0, opts)
@@ -981,11 +1005,74 @@ var AuditResource = class extends Resource {
981
1005
  );
982
1006
  }
983
1007
  /**
984
- * Verify a Merkle inclusion proof locally (client-side). Sorted-pair SHA-256
985
- * over the raw 32-byte digests — identical logic to the server-side batcher,
986
- * so callers can independently confirm inclusion without trusting the API.
1008
+ * Fetch event + proof for `seq` and run every offline check (event hash,
1009
+ * same event, seq in batch, proof length, Merkle root). Pass `root` (e.g.
1010
+ * the anchored root) for a check independent of this API's batch record.
987
1011
  */
988
- static verifyProof(leaf, root, proof) {
1012
+ async verify(seq, options = {}) {
1013
+ const { root, ...opts } = options;
1014
+ const [event, proof] = await Promise.all([this.getEvent(seq, opts), this.getProof(seq, opts)]);
1015
+ return _AuditResource.verifyEvent(event, proof, root);
1016
+ }
1017
+ /** Number of siblings in a valid proof for a batch of `leafCount` leaves. */
1018
+ static expectedProofLength(leafCount) {
1019
+ return expectedProofLength(leafCount);
1020
+ }
1021
+ /** Recompute event_hash = sha256(prev_event_hash + canonical) and check canonical.seq. */
1022
+ static verifyEventHash(event) {
1023
+ if (!isHex32(event.prev_event_hash) || !isHex32(event.event_hash) || typeof event.canonical !== "string") {
1024
+ return false;
1025
+ }
1026
+ try {
1027
+ if (Number(JSON.parse(event.canonical).seq) !== Number(event.seq)) return false;
1028
+ } catch {
1029
+ return false;
1030
+ }
1031
+ const sha256 = resolveSyncSha256();
1032
+ const bytes = new TextEncoder().encode(event.prev_event_hash.toLowerCase() + event.canonical);
1033
+ return bytesToHex(sha256(bytes)) === event.event_hash.toLowerCase();
1034
+ }
1035
+ /** Run all checks for one event given getEvent() + getProof() data. */
1036
+ static verifyEvent(event, proof, root) {
1037
+ const checks = {};
1038
+ checks.event_hash = _AuditResource.verifyEventHash(event);
1039
+ checks.same_event = proof.seq === event.seq && String(proof.event_hash).toLowerCase() === String(event.event_hash).toLowerCase();
1040
+ const first = Number(proof.batch?.first_seq);
1041
+ const last = Number(proof.batch?.last_seq);
1042
+ if (!Number.isInteger(first) || !Number.isInteger(last) || last < first) {
1043
+ return { ok: false, checks, reason: "proof.batch is missing first_seq/last_seq" };
1044
+ }
1045
+ const leafCount = last - first + 1;
1046
+ const expLen = expectedProofLength(leafCount);
1047
+ checks.seq_in_batch = event.seq >= first && event.seq <= last;
1048
+ checks.server_length_agrees = proof.expected_proof_length === void 0 || Number(proof.expected_proof_length) === expLen;
1049
+ checks.merkle = _AuditResource.verifyProof(
1050
+ event.event_hash,
1051
+ root ?? proof.batch.merkle_root,
1052
+ proof.merkle_proof,
1053
+ expLen
1054
+ );
1055
+ const failed = Object.entries(checks).filter(([, v]) => !v).map(([k]) => k);
1056
+ return {
1057
+ ok: failed.length === 0,
1058
+ checks,
1059
+ leafCount,
1060
+ expectedProofLength: expLen,
1061
+ reason: failed.length ? `failed: ${failed.join(", ")}` : null
1062
+ };
1063
+ }
1064
+ /**
1065
+ * Verify a Merkle inclusion proof locally. Synchronous and isomorphic
1066
+ * (node:crypto when a sync `require` exists, else a built-in SHA-256).
1067
+ *
1068
+ * @param leaf the event's event_hash (64 hex chars)
1069
+ * @param root the batch merkle_root (64 hex chars)
1070
+ * @param proof sibling hashes, leaf level first (64 hex chars each)
1071
+ * @param expectedLength expectedProofLength(leafCount) — required; any other
1072
+ * proof length is rejected (second-preimage guard)
1073
+ */
1074
+ static verifyProof(leaf, root, proof, expectedLength) {
1075
+ if (!validProofShape(leaf, root, proof, expectedLength)) return false;
989
1076
  const sha256 = resolveSyncSha256();
990
1077
  let hash = hexToBytes(leaf);
991
1078
  for (const sibling of proof) {
@@ -996,10 +1083,11 @@ var AuditResource = class extends Resource {
996
1083
  pair.set(b, a.length);
997
1084
  hash = sha256(pair);
998
1085
  }
999
- return bytesToHex(hash) === root;
1086
+ return bytesToHex(hash) === root.toLowerCase();
1000
1087
  }
1001
- /** Async variant using WebCrypto — works in browsers, Deno, Bun, edge runtimes. */
1002
- static async verifyProofAsync(leaf, root, proof) {
1088
+ /** WebCrypto variant of verifyProof (same rules, including expectedLength). */
1089
+ static async verifyProofAsync(leaf, root, proof, expectedLength) {
1090
+ if (!validProofShape(leaf, root, proof, expectedLength)) return false;
1003
1091
  const subtle = globalThis.crypto.subtle;
1004
1092
  let hash = hexToBytes(leaf);
1005
1093
  for (const sibling of proof) {
@@ -1010,7 +1098,7 @@ var AuditResource = class extends Resource {
1010
1098
  pair.set(b, a.length);
1011
1099
  hash = new Uint8Array(await subtle.digest("SHA-256", pair));
1012
1100
  }
1013
- return bytesToHex(hash) === root;
1101
+ return bytesToHex(hash) === root.toLowerCase();
1014
1102
  }
1015
1103
  };
1016
1104
 
@@ -1091,193 +1179,124 @@ var GrantsResource = class extends Resource {
1091
1179
  }
1092
1180
  };
1093
1181
 
1094
- // src/resources/keys.ts
1095
- var KeysResource = class extends Resource {
1096
- create(params = {}, opts) {
1097
- const body = {
1098
- name: params.name ?? "default",
1099
- scopes: params.scopes ?? ["read"]
1100
- };
1101
- return this._apiPromise(
1102
- () => this._http.request("POST", "/v1/keys", void 0, body, opts)
1103
- );
1104
- }
1105
- list(opts) {
1106
- return this._apiPromise(
1107
- () => this._http.request("GET", "/v1/keys", void 0, void 0, opts)
1108
- );
1109
- }
1110
- revoke(keyId, opts) {
1111
- return this._apiPromise(
1112
- () => this._http.request(
1113
- "DELETE",
1114
- `/v1/keys/${encodeURIComponent(keyId)}`,
1115
- void 0,
1116
- void 0,
1117
- opts
1118
- )
1119
- );
1120
- }
1121
- };
1122
-
1123
1182
  // src/resources/markets.ts
1124
1183
  var MarketsResource = class extends Resource {
1125
- /** List markets — auto-paginates. Iterate with `for await (const m of ...)`. */
1184
+ /** List markets; iterate every page with `for await (const m of pax.markets.list())`. */
1126
1185
  list(params = {}, opts) {
1127
- const query = this._buildListQuery(params);
1186
+ const query = { limit: params.limit, cursor: params.cursor, category: params.category, q: params.q };
1128
1187
  const fetchNext = (cursor, ro) => this.list({ ...params, cursor }, ro);
1129
- return this._pagePromise(
1130
- () => this._http.request("GET", "/v1/markets", query, void 0, opts),
1131
- fetchNext,
1132
- opts
1133
- );
1188
+ return new PagePromise(async () => {
1189
+ const raw = await this._http.request("GET", "/v1/markets", query, void 0, opts);
1190
+ const items = raw.body?.data?.markets ?? [];
1191
+ const nextCursor = raw.body?.data?.page?.next_cursor ?? null;
1192
+ const page = new CursorPage({
1193
+ data: items,
1194
+ nextCursor,
1195
+ hasMore: !!nextCursor,
1196
+ response: raw.response,
1197
+ fetchNext,
1198
+ requestOptions: opts
1199
+ });
1200
+ return { data: page, response: raw.response };
1201
+ });
1134
1202
  }
1135
1203
  retrieve(marketId, opts) {
1136
1204
  return this._apiPromise(
1137
1205
  () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}`, void 0, void 0, opts)
1138
1206
  );
1139
1207
  }
1140
- create(params, opts) {
1141
- const body = {
1142
- template_id: params.templateId,
1143
- params: params.params
1144
- };
1145
- if (params.creatorMetadata) body.creator_metadata = params.creatorMetadata;
1208
+ categories(opts) {
1146
1209
  return this._apiPromise(
1147
- () => this._http.request("POST", "/v1/markets", void 0, body, opts)
1210
+ () => this._http.request("GET", "/v1/markets/categories", void 0, void 0, opts)
1148
1211
  );
1149
1212
  }
1150
- candles(marketId, params, opts) {
1151
- const query = {
1152
- outcome_id: params.outcomeId,
1153
- interval: params.interval ?? "1m",
1154
- limit: params.limit ?? 500
1155
- };
1156
- if (params.fromMs !== void 0) query.from_ms = params.fromMs;
1157
- if (params.toMs !== void 0) query.to_ms = params.toMs;
1213
+ orderbook(marketId, opts) {
1158
1214
  return this._apiPromise(
1159
- () => this._http.request("GET", `/v1/candles/${encodeURIComponent(marketId)}`, query, void 0, opts)
1215
+ () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}/orderbook`, void 0, void 0, opts)
1160
1216
  );
1161
1217
  }
1162
- orderbook(marketId, params, opts) {
1163
- const query = {
1164
- outcome_id: params.outcomeId,
1165
- depth: params.depth ?? 20
1166
- };
1218
+ priceHistory(marketId, params = {}, opts) {
1219
+ const query = { range: params.range ?? "1d" };
1167
1220
  return this._apiPromise(
1168
- () => this._http.request("GET", `/v1/orderbook/${encodeURIComponent(marketId)}`, query, void 0, opts)
1221
+ () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}/price-history`, query, void 0, opts)
1169
1222
  );
1170
1223
  }
1171
- /** Public trade tape for a market (all fills, not your fills). */
1172
- trades(marketId, params = {}, opts) {
1173
- const query = { limit: params.limit ?? 50 };
1174
- if (params.outcomeId) query.outcome_id = params.outcomeId;
1175
- if (params.cursor) query.cursor = params.cursor;
1176
- const fetchNext = (cursor, ro) => this.trades(marketId, { ...params, cursor }, ro);
1177
- return this._pagePromise(
1178
- () => this._http.request("GET", `/v1/trades/${encodeURIComponent(marketId)}`, query, void 0, opts),
1179
- fetchNext,
1180
- opts
1224
+ resolution(marketId, opts) {
1225
+ return this._apiPromise(
1226
+ () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}/resolution`, void 0, void 0, opts)
1181
1227
  );
1182
1228
  }
1183
- _buildListQuery(params) {
1184
- const query = paginationParams({ limit: params.limit ?? 50, cursor: params.cursor });
1185
- if (params.category) query.category = params.category;
1186
- if (params.marketType) query.market_type = params.marketType;
1187
- if (params.status) query.status = params.status;
1188
- return query;
1229
+ create(params, opts) {
1230
+ const body = {
1231
+ title: params.title,
1232
+ rules_text: params.rulesText,
1233
+ resolution_rule: params.resolutionRule,
1234
+ primary_source_url: params.primarySourceUrl,
1235
+ cutoff_time_ms: params.cutoffTimeMs,
1236
+ resolution_deadline_ms: params.resolutionDeadlineMs
1237
+ };
1238
+ if (params.backupSourceUrls?.length) body.backup_source_urls = params.backupSourceUrls;
1239
+ if (params.edgeCasesText !== void 0) body.edge_cases_text = params.edgeCasesText;
1240
+ if (params.description !== void 0) body.description = params.description;
1241
+ return this._apiPromise(
1242
+ () => this._http.request("POST", "/v1/composer/markets", void 0, body, opts)
1243
+ );
1189
1244
  }
1190
1245
  };
1191
1246
 
1192
1247
  // src/resources/orders.ts
1248
+ function newClientOrderId() {
1249
+ const bytes = new Uint8Array(12);
1250
+ globalThis.crypto.getRandomValues(bytes);
1251
+ return "pax-sdk-" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1252
+ }
1253
+ function toWire(p) {
1254
+ const side = String(p.side).toLowerCase();
1255
+ if (side !== "yes" && side !== "no") throw new Error("side must be 'yes' or 'no' (the outcome to buy)");
1256
+ const body = {
1257
+ market_id: p.marketId,
1258
+ side,
1259
+ price: String(p.price),
1260
+ size: String(p.size),
1261
+ client_order_id: p.clientOrderId ?? newClientOrderId()
1262
+ };
1263
+ if (p.fundingMode !== void 0) body.funding_mode = p.fundingMode;
1264
+ return body;
1265
+ }
1193
1266
  var OrdersResource = class extends Resource {
1194
1267
  place(params, opts) {
1195
- const body = {
1196
- market_id: params.marketId,
1197
- outcome_id: params.outcomeId,
1198
- side: params.side,
1199
- order_type: params.orderType,
1200
- size: String(params.size)
1201
- };
1202
- if (params.price !== void 0) body.price = String(params.price);
1203
- if (params.clientOrderId) body.client_order_id = params.clientOrderId;
1204
- if (params.timeInForce) body.time_in_force = params.timeInForce;
1268
+ const body = toWire(params);
1205
1269
  return this._apiPromise(
1206
1270
  () => this._http.request("POST", "/v1/orders", void 0, body, opts)
1207
1271
  );
1208
1272
  }
1209
- cancel(orderId, opts) {
1273
+ placeBatch(orders, opts) {
1274
+ const wire = orders.map(toWire);
1210
1275
  return this._apiPromise(
1211
- () => this._http.request(
1212
- "DELETE",
1213
- `/v1/orders/${encodeURIComponent(orderId)}`,
1214
- void 0,
1215
- void 0,
1216
- opts
1217
- )
1276
+ () => this._http.request("POST", "/v1/orders/batch", void 0, { orders: wire }, opts)
1218
1277
  );
1219
1278
  }
1220
1279
  list(params = {}, opts) {
1221
- const query = paginationParams({ limit: params.limit ?? 50, cursor: params.cursor });
1222
- if (params.status) query.status = params.status;
1223
- const fetchNext = (cursor, ro) => this.list({ ...params, cursor }, ro);
1224
- return this._pagePromise(
1225
- () => this._http.request("GET", "/v1/account/orders", query, void 0, opts),
1226
- fetchNext,
1227
- opts
1280
+ const query = { limit: params.limit };
1281
+ return this._apiPromise(
1282
+ () => this._http.request("GET", "/v1/orders", query, void 0, opts)
1228
1283
  );
1229
1284
  }
1230
- /**
1231
- * Place multiple orders in a single request (up to 25 per batch).
1232
- *
1233
- * Each order is processed sequentially by the CLOB engine (single-writer per
1234
- * market). Response contains a `results` array with one entry per input order
1235
- * (indexed) plus a `summary` with counts + duration. One bad order does not
1236
- * fail the whole batch — inspect `results[i].ok` per item.
1237
- *
1238
- * Batch cap is env-tunable server-side (BATCH_ORDERS_MAX, default 25). Exceeding
1239
- * returns `413 BATCH_TOO_LARGE`.
1240
- */
1241
- placeBatch(orders, opts) {
1242
- const wireOrders = orders.map((o) => {
1243
- const body = {
1244
- market_id: o.marketId,
1245
- outcome_id: o.outcomeId,
1246
- side: o.side,
1247
- order_type: o.orderType,
1248
- size: String(o.size)
1249
- };
1250
- if (o.price !== void 0) body.price = String(o.price);
1251
- if (o.clientOrderId) body.client_order_id = o.clientOrderId;
1252
- if (o.timeInForce) body.time_in_force = o.timeInForce;
1253
- return body;
1254
- });
1285
+ history(params = {}, opts) {
1286
+ const query = { limit: params.limit, cursor: params.cursor };
1255
1287
  return this._apiPromise(
1256
- () => this._http.request(
1257
- "POST",
1258
- "/v1/orders/batch",
1259
- void 0,
1260
- { orders: wireOrders },
1261
- opts
1262
- )
1288
+ () => this._http.request("GET", "/v1/orders/history", query, void 0, opts)
1263
1289
  );
1264
1290
  }
1265
- /**
1266
- * Cancel multiple orders in a single request (up to 50 per batch).
1267
- *
1268
- * Each cancel is processed sequentially by the CLOB engine. Response mirrors
1269
- * `placeBatch` shape — inspect `results[i].ok` per item. Batch cap env-tunable
1270
- * server-side (BATCH_CANCEL_MAX, default 50).
1271
- */
1272
- cancelBatch(orderIds, opts) {
1291
+ cancel(orderId, opts) {
1273
1292
  return this._apiPromise(
1274
- () => this._http.request(
1275
- "DELETE",
1276
- "/v1/orders/batch",
1277
- void 0,
1278
- { orderIds },
1279
- opts
1280
- )
1293
+ () => this._http.request("DELETE", `/v1/orders/${encodeURIComponent(orderId)}`, void 0, void 0, opts)
1294
+ );
1295
+ }
1296
+ cancelAll(params = {}, opts) {
1297
+ const body = params.marketId ? { market_id: params.marketId } : {};
1298
+ return this._apiPromise(
1299
+ () => this._http.request("POST", "/v1/orders/cancel-all", void 0, body, opts)
1281
1300
  );
1282
1301
  }
1283
1302
  };
@@ -1285,10 +1304,8 @@ var OrdersResource = class extends Resource {
1285
1304
  // src/resources/sandbox.ts
1286
1305
  var SandboxKeysResource = class extends Resource {
1287
1306
  mint(params, opts) {
1288
- const body = {
1289
- org_name: params.orgName,
1290
- contact_email: params.contactEmail ?? null
1291
- };
1307
+ const body = { org_name: params.orgName };
1308
+ if (params.contactHandle !== void 0) body.contact_handle = params.contactHandle;
1292
1309
  return this._apiPromise(
1293
1310
  () => this._http.request(
1294
1311
  "POST",
@@ -1341,39 +1358,6 @@ var SettleResource = class extends Resource {
1341
1358
  () => this._http.request("POST", "/v1/builders/me/settle", void 0, body, opts)
1342
1359
  );
1343
1360
  }
1344
- /** Admin settle a specific builder's fees — POST /v1/admin/builders/{userId}/settle.
1345
- * Requires X-Admin-Key header. */
1346
- adminBuilder(userId, params, adminKey, opts) {
1347
- const body = {
1348
- address: params.address,
1349
- asset: params.asset ?? "USDT",
1350
- network: params.network ?? "polygon",
1351
- min_amount: params.min_amount ?? 0
1352
- };
1353
- const mergedOpts = {
1354
- ...opts || {},
1355
- headers: { ...opts?.headers || {}, "X-Admin-Key": adminKey }
1356
- };
1357
- return this._apiPromise(
1358
- () => this._http.request("POST", `/v1/admin/builders/${encodeURIComponent(userId)}/settle`, void 0, body, mergedOpts)
1359
- );
1360
- }
1361
- /** Admin settle a market creator's fees — POST /v1/admin/creators/{userId}/settle. */
1362
- adminCreator(userId, params, adminKey, opts) {
1363
- const body = {
1364
- address: params.address,
1365
- asset: params.asset ?? "USDT",
1366
- network: params.network ?? "polygon",
1367
- min_amount: params.min_amount ?? 0
1368
- };
1369
- const mergedOpts = {
1370
- ...opts || {},
1371
- headers: { ...opts?.headers || {}, "X-Admin-Key": adminKey }
1372
- };
1373
- return this._apiPromise(
1374
- () => this._http.request("POST", `/v1/admin/creators/${encodeURIComponent(userId)}/settle`, void 0, body, mergedOpts)
1375
- );
1376
- }
1377
1361
  };
1378
1362
 
1379
1363
  // src/resources/templates.ts
@@ -1402,7 +1386,6 @@ var PaxClient = class {
1402
1386
  templates;
1403
1387
  orders;
1404
1388
  account;
1405
- keys;
1406
1389
  sandbox;
1407
1390
  // legacy namespace, kept for import compat
1408
1391
  sandboxKeys;
@@ -1416,13 +1399,12 @@ var PaxClient = class {
1416
1399
  // v2.2+: public Merkle chain verifier (no-auth)
1417
1400
  settle;
1418
1401
  // v2.4+: claim accrued fee revenue
1419
- constructor(opts) {
1402
+ constructor(opts = {}) {
1420
1403
  this._http = new HttpClient(opts);
1421
1404
  this.markets = new MarketsResource(this._http);
1422
1405
  this.templates = new TemplatesResource(this._http);
1423
1406
  this.orders = new OrdersResource(this._http);
1424
1407
  this.account = new AccountResource(this._http);
1425
- this.keys = new KeysResource(this._http);
1426
1408
  this.sandbox = new SandboxResource(this._http);
1427
1409
  this.sandboxKeys = new SandboxKeysResource(this._http);
1428
1410
  this.apply = new ApplyResource(this._http);
@@ -1437,6 +1419,9 @@ var PaxClient = class {
1437
1419
  get userAgent() {
1438
1420
  return this._http.userAgent;
1439
1421
  }
1422
+ get authMode() {
1423
+ return this._http.authMode;
1424
+ }
1440
1425
  /** GET /v1/health — top-level, not paginated, always safe. */
1441
1426
  health(opts) {
1442
1427
  return new APIPromise(async () => {
@@ -1565,7 +1550,7 @@ function clearRef(opts = {}) {
1565
1550
  }
1566
1551
 
1567
1552
  // src/ws-client.ts
1568
- var ENV_URLS2 = {
1553
+ var ENV_URLS = {
1569
1554
  production: "wss://predictasiax.com/ws",
1570
1555
  prod: "wss://predictasiax.com/ws",
1571
1556
  live: "wss://predictasiax.com/ws",
@@ -1606,7 +1591,7 @@ var PaxWSClient = class {
1606
1591
  this.bearerToken = opts.bearerToken;
1607
1592
  this.locale = opts.locale;
1608
1593
  const env = (opts.env ?? "production").toLowerCase();
1609
- this.url = opts.url ?? ENV_URLS2[env] ?? ENV_URLS2.production;
1594
+ this.url = opts.url ?? ENV_URLS[env] ?? ENV_URLS.production;
1610
1595
  this.reconnect = opts.reconnect ?? true;
1611
1596
  this.backoffMinSec = opts.backoffMinSec ?? 1;
1612
1597
  this.backoffMaxSec = opts.backoffMaxSec ?? 60;
@@ -1815,9 +1800,9 @@ var PaxWSClient = class {
1815
1800
  ApplyResource,
1816
1801
  AuditResource,
1817
1802
  CursorPage,
1803
+ DEFAULT_BASE_URL,
1818
1804
  FeesResource,
1819
1805
  GrantsResource,
1820
- KeysResource,
1821
1806
  MarketsResource,
1822
1807
  OrdersResource,
1823
1808
  PagePromise,
@@ -1836,13 +1821,16 @@ var PaxWSClient = class {
1836
1821
  PaxWrongEnvKeyError,
1837
1822
  SandboxKeysResource,
1838
1823
  SandboxResource,
1824
+ SettleResource,
1839
1825
  TemplatesResource,
1840
1826
  VERSION,
1841
1827
  attachRef,
1828
+ buildCanonical,
1842
1829
  buildError,
1843
- buildMessage,
1844
1830
  clearRef,
1845
1831
  computeBackoff,
1832
+ expectedProofLength,
1833
+ normalizeBaseUrl,
1846
1834
  runWithRetry,
1847
1835
  signRequest
1848
1836
  });