@predictasiax/api 2.5.1 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,34 @@ __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
+ fieldsMatchCanonical: () => fieldsMatchCanonical,
69
+ normalizeBaseUrl: () => normalizeBaseUrl,
66
70
  runWithRetry: () => runWithRetry,
67
71
  signRequest: () => signRequest
68
72
  });
69
73
  module.exports = __toCommonJS(index_exports);
70
74
 
71
75
  // src/auth.ts
72
- function buildMessage(method, path, body, timestampMs) {
73
- return `${timestampMs}${method.toUpperCase()}${path}${body || ""}`;
76
+ function buildCanonical(timestamp, nonce, method, pathWithQuery, body) {
77
+ return [String(timestamp), nonce, method.toUpperCase(), pathWithQuery, body || ""].join("\n");
74
78
  }
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;
79
+ function randomNonce() {
80
+ const g = globalThis.crypto;
81
+ if (g && typeof g.getRandomValues === "function") {
82
+ const bytes = new Uint8Array(16);
83
+ g.getRandomValues(bytes);
84
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
86
85
  }
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);
86
+ throw new Error("No secure random source available for the HMAC nonce");
102
87
  }
103
88
  function arrayBufferToBase64(buf) {
104
89
  const bytes = new Uint8Array(buf);
@@ -107,21 +92,28 @@ function arrayBufferToBase64(buf) {
107
92
  for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
108
93
  return globalThis.btoa(bin);
109
94
  }
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");
95
+ async function hmacSha256Base64(key, message) {
96
+ const subtle = globalThis.crypto?.subtle;
97
+ if (subtle && typeof subtle.sign === "function") {
98
+ const enc = new TextEncoder();
99
+ const k = await subtle.importKey("raw", enc.encode(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
100
+ return arrayBufferToBase64(await subtle.sign("HMAC", k, enc.encode(message)));
101
+ }
102
+ const mod = await import("crypto");
103
+ return mod.createHmac("sha256", key).update(message).digest("base64");
114
104
  }
115
105
  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);
106
+ if (!input.keyId || !input.apiKey) {
107
+ throw new Error("HMAC signing needs both keyId (api_...) and apiKey (sk_live_...)");
108
+ }
109
+ const ts = String(Math.floor(input.timestampSec ?? Date.now() / 1e3));
110
+ const nonce = input.nonce ?? randomNonce();
111
+ const canonical = buildCanonical(ts, nonce, input.method, input.pathWithQuery, input.body);
120
112
  return {
121
- POLY_ACCESS_KEY: input.keyId,
122
- POLY_TIMESTAMP: ts,
123
- POLY_PASSPHRASE: input.passphrase,
124
- POLY_SIGNATURE: signature
113
+ "PAX-ADDRESS": input.keyId,
114
+ "PAX-TIMESTAMP": ts,
115
+ "PAX-NONCE": nonce,
116
+ "PAX-SIGNATURE": await hmacSha256Base64(input.apiKey, canonical)
125
117
  };
126
118
  }
127
119
 
@@ -279,6 +271,16 @@ var PROTECTED_HEADERS = /* @__PURE__ */ new Set(
279
271
  "poly_timestamp",
280
272
  "poly_passphrase",
281
273
  "poly_signature",
274
+ "pax-address",
275
+ "pax-timestamp",
276
+ "pax-nonce",
277
+ "pax-signature",
278
+ "pax-method",
279
+ "poly-address",
280
+ "poly-timestamp",
281
+ "poly-nonce",
282
+ "poly-signature",
283
+ "poly-method",
282
284
  "idempotency-key",
283
285
  "cache-control"
284
286
  ]
@@ -367,19 +369,19 @@ async function runWithRetry(fn, opts = {}) {
367
369
  }
368
370
 
369
371
  // 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
- };
372
+ var VERSION = "3.0.1";
373
+ var DEFAULT_BASE_URL = "https://api.predictasiax.com";
374
+ var API_KEY_PREFIXES = ["sk_live_", "sk_test_", "pax_"];
375
+ function normalizeBaseUrl(url) {
376
+ let u = url.trim().replace(/\/+$/, "");
377
+ if (u.endsWith("/v1")) u = u.slice(0, -3);
378
+ return u;
379
+ }
378
380
  var DEFAULT_TIMEOUT_MS = 3e4;
379
381
  var DEFAULT_MAX_RETRIES = 5;
380
382
  var DEFAULT_MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
381
383
  var DEFAULT_USER_AGENT = `pax-api-ts/${VERSION}`;
382
- var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
384
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
383
385
  function isLoopback(hostname) {
384
386
  return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
385
387
  }
@@ -462,9 +464,15 @@ async function readCappedText(response, maxBytes) {
462
464
  var HttpClient = class {
463
465
  baseUrl;
464
466
  userAgent;
467
+ /** "hmac" | "api_key" | "bearer" | "none" */
468
+ get authMode() {
469
+ if (this.keyId && this.apiKey) return "hmac";
470
+ if (this.apiKey) return "api_key";
471
+ if (this.bearerToken) return "bearer";
472
+ return "none";
473
+ }
465
474
  apiKey;
466
- secret;
467
- passphrase;
475
+ keyId;
468
476
  bearerToken;
469
477
  timeoutMs;
470
478
  maxRetries;
@@ -474,23 +482,30 @@ var HttpClient = class {
474
482
  fetchImpl;
475
483
  fetchOptions;
476
484
  constructor(opts) {
477
- if (!opts.apiKey && !opts.bearerToken) {
478
- throw new Error("Provide apiKey or bearerToken");
485
+ if (opts.secret !== void 0 || opts.passphrase !== void 0) {
486
+ throw new Error(
487
+ "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)."
488
+ );
479
489
  }
480
- if (opts.secret && !opts.passphrase) {
481
- throw new Error("Provide passphrase together with secret for HMAC");
490
+ const apiKey = opts.apiKey === "anonymous" ? void 0 : opts.apiKey;
491
+ if (apiKey !== void 0 && !API_KEY_PREFIXES.some((p) => apiKey.startsWith(p))) {
492
+ throw new Error("apiKey must start with sk_live_, sk_test_ or pax_");
493
+ }
494
+ if (opts.keyId !== void 0 && !apiKey) {
495
+ throw new Error("keyId (HMAC) needs apiKey: 'sk_live_...' as the signing key");
496
+ }
497
+ if (apiKey && opts.bearerToken) {
498
+ throw new Error("Pass either apiKey or bearerToken, not both");
482
499
  }
483
500
  if (typeof window !== "undefined" && !opts.dangerouslyAllowBrowser) {
484
501
  throw new Error(
485
502
  "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
503
  );
487
504
  }
488
- this.apiKey = opts.apiKey;
489
- this.secret = opts.secret;
490
- this.passphrase = opts.passphrase;
505
+ this.apiKey = apiKey;
506
+ this.keyId = opts.keyId;
491
507
  this.bearerToken = opts.bearerToken;
492
- const env = (opts.env ?? "production").toLowerCase();
493
- const rawBaseUrl = (opts.baseUrl ?? ENV_URLS[env] ?? ENV_URLS.production).replace(/\/$/, "");
508
+ const rawBaseUrl = normalizeBaseUrl(opts.baseUrl ?? DEFAULT_BASE_URL);
494
509
  validateBaseUrl(rawBaseUrl, opts.allowInsecureHttp ?? false);
495
510
  this.baseUrl = rawBaseUrl;
496
511
  this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -526,19 +541,18 @@ var HttpClient = class {
526
541
  };
527
542
  if (body) managed["Content-Type"] = "application/json";
528
543
  if (idempotencyKey) managed["Idempotency-Key"] = idempotencyKey;
529
- if (this.secret && this.passphrase && this.apiKey) {
544
+ if (this.keyId && this.apiKey) {
530
545
  const sig = await signRequest({
531
546
  method,
532
- path: pathWithQuery,
547
+ pathWithQuery,
533
548
  body,
534
- keyId: this.apiKey,
535
- secret: this.secret,
536
- passphrase: this.passphrase,
537
- timestampMs: Date.now() + this.clockOffsetMs
549
+ keyId: this.keyId,
550
+ apiKey: this.apiKey,
551
+ timestampSec: (Date.now() + this.clockOffsetMs) / 1e3
538
552
  });
539
553
  Object.assign(managed, sig);
540
554
  } else if (this.apiKey) {
541
- managed["X-Api-Key"] = this.apiKey;
555
+ managed["Authorization"] = `Bearer ${this.apiKey}`;
542
556
  } else if (this.bearerToken) {
543
557
  managed["Authorization"] = `Bearer ${this.bearerToken}`;
544
558
  }
@@ -756,39 +770,50 @@ var Resource = class {
756
770
  });
757
771
  }
758
772
  };
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
773
 
767
774
  // src/resources/account.ts
768
775
  var AccountResource = class extends Resource {
769
- retrieve(opts) {
776
+ balance(opts) {
770
777
  return this._apiPromise(
771
- () => this._http.request("GET", "/v1/account", void 0, void 0, opts)
778
+ () => this._http.request("GET", "/v1/balance", void 0, void 0, opts)
772
779
  );
773
780
  }
774
- positions(opts) {
781
+ /** @deprecated Use balance(). Kept as an alias. */
782
+ retrieve(opts) {
783
+ return this.balance(opts);
784
+ }
785
+ portfolio(opts) {
775
786
  return this._apiPromise(
776
- () => this._http.request("GET", "/v1/account/positions", void 0, void 0, opts)
787
+ () => this._http.request("GET", "/v1/portfolio", void 0, void 0, opts)
777
788
  );
778
789
  }
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
790
+ positions(opts) {
791
+ return this._apiPromise(
792
+ () => this._http.request("GET", "/v1/positions", void 0, void 0, opts)
787
793
  );
788
794
  }
789
795
  };
790
796
 
791
797
  // src/resources/audit.ts
798
+ var HEX32 = /^[0-9a-fA-F]{64}$/;
799
+ function isHex32(x) {
800
+ return typeof x === "string" && HEX32.test(x);
801
+ }
802
+ function expectedProofLength(leafCount) {
803
+ let n = Math.floor(Number(leafCount));
804
+ if (!Number.isFinite(n) || n < 1) throw new Error("leafCount must be >= 1");
805
+ let depth = 0;
806
+ while (n > 1) {
807
+ n = Math.ceil(n / 2);
808
+ depth++;
809
+ }
810
+ return depth;
811
+ }
812
+ function validProofShape(leaf, root, proof, expectedLength) {
813
+ if (!isHex32(leaf) || !isHex32(root)) return false;
814
+ if (!Array.isArray(proof) || proof.length !== expectedLength) return false;
815
+ return proof.every(isHex32);
816
+ }
792
817
  function hexToBytes(hex) {
793
818
  const out = new Uint8Array(hex.length / 2);
794
819
  for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.substr(i * 2, 2), 16);
@@ -949,7 +974,7 @@ function resolveSyncSha256() {
949
974
  }
950
975
  return sha256Pure;
951
976
  }
952
- var AuditResource = class extends Resource {
977
+ var AuditResource = class _AuditResource extends Resource {
953
978
  status(opts) {
954
979
  return this._apiPromise(
955
980
  () => this._http.request("GET", "/v1/audit/status", void 0, void 0, opts)
@@ -981,11 +1006,84 @@ var AuditResource = class extends Resource {
981
1006
  );
982
1007
  }
983
1008
  /**
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.
1009
+ * Fetch event + proof for `seq` and run every offline check (event hash,
1010
+ * same event, seq in batch, proof length, Merkle root). Pass `root` (e.g.
1011
+ * the anchored root) for a check independent of this API's batch record.
987
1012
  */
988
- static verifyProof(leaf, root, proof) {
1013
+ async verify(seq, options = {}) {
1014
+ const { root, ...opts } = options;
1015
+ const [event, proof] = await Promise.all([this.getEvent(seq, opts), this.getProof(seq, opts)]);
1016
+ return _AuditResource.verifyEvent(event, proof, root);
1017
+ }
1018
+ /** Number of siblings in a valid proof for a batch of `leafCount` leaves. */
1019
+ static expectedProofLength(leafCount) {
1020
+ return expectedProofLength(leafCount);
1021
+ }
1022
+ /** Recompute event_hash = sha256(prev_event_hash + canonical) and check canonical.seq. */
1023
+ static verifyEventHash(event) {
1024
+ if (!isHex32(event.prev_event_hash) || !isHex32(event.event_hash) || typeof event.canonical !== "string") {
1025
+ return false;
1026
+ }
1027
+ try {
1028
+ if (Number(JSON.parse(event.canonical).seq) !== Number(event.seq)) return false;
1029
+ } catch {
1030
+ return false;
1031
+ }
1032
+ const sha256 = resolveSyncSha256();
1033
+ const bytes = new TextEncoder().encode(event.prev_event_hash.toLowerCase() + event.canonical);
1034
+ return bytesToHex(sha256(bytes)) === event.event_hash.toLowerCase();
1035
+ }
1036
+ /** Run all checks for one event given getEvent() + getProof() data. */
1037
+ static verifyEvent(event, proof, root) {
1038
+ const checks = {};
1039
+ checks.event_hash = _AuditResource.verifyEventHash(event);
1040
+ checks.fields_match_canonical = fieldsMatchCanonical(event);
1041
+ checks.same_event = proof.seq === event.seq && String(proof.event_hash).toLowerCase() === String(event.event_hash).toLowerCase();
1042
+ const first = Number(proof.batch?.first_seq);
1043
+ const last = Number(proof.batch?.last_seq);
1044
+ if (!Number.isInteger(first) || !Number.isInteger(last) || last < first) {
1045
+ return { ok: false, checks, reason: "proof.batch is missing first_seq/last_seq" };
1046
+ }
1047
+ const leafCount = last - first + 1;
1048
+ const expLen = expectedProofLength(leafCount);
1049
+ checks.seq_in_batch = event.seq >= first && event.seq <= last;
1050
+ checks.server_length_agrees = proof.expected_proof_length === void 0 || Number(proof.expected_proof_length) === expLen;
1051
+ checks.merkle = _AuditResource.verifyProof(
1052
+ event.event_hash,
1053
+ root ?? proof.batch.merkle_root,
1054
+ proof.merkle_proof,
1055
+ expLen
1056
+ );
1057
+ const failed = Object.entries(checks).filter(([, v]) => !v).map(([k]) => k);
1058
+ if (event.canonical_withheld) {
1059
+ return {
1060
+ ok: false,
1061
+ checks,
1062
+ leafCount,
1063
+ expectedProofLength: expLen,
1064
+ reason: "canonical withheld for this event (account identifiers redacted); only Merkle inclusion was checked. Fetch it with the key of the account it names to verify content."
1065
+ };
1066
+ }
1067
+ return {
1068
+ ok: failed.length === 0,
1069
+ checks,
1070
+ leafCount,
1071
+ expectedProofLength: expLen,
1072
+ reason: failed.length ? `failed: ${failed.join(", ")}` : null
1073
+ };
1074
+ }
1075
+ /**
1076
+ * Verify a Merkle inclusion proof locally. Synchronous and isomorphic
1077
+ * (node:crypto when a sync `require` exists, else a built-in SHA-256).
1078
+ *
1079
+ * @param leaf the event's event_hash (64 hex chars)
1080
+ * @param root the batch merkle_root (64 hex chars)
1081
+ * @param proof sibling hashes, leaf level first (64 hex chars each)
1082
+ * @param expectedLength expectedProofLength(leafCount) — required; any other
1083
+ * proof length is rejected (second-preimage guard)
1084
+ */
1085
+ static verifyProof(leaf, root, proof, expectedLength) {
1086
+ if (!validProofShape(leaf, root, proof, expectedLength)) return false;
989
1087
  const sha256 = resolveSyncSha256();
990
1088
  let hash = hexToBytes(leaf);
991
1089
  for (const sibling of proof) {
@@ -996,10 +1094,11 @@ var AuditResource = class extends Resource {
996
1094
  pair.set(b, a.length);
997
1095
  hash = sha256(pair);
998
1096
  }
999
- return bytesToHex(hash) === root;
1097
+ return bytesToHex(hash) === root.toLowerCase();
1000
1098
  }
1001
- /** Async variant using WebCrypto — works in browsers, Deno, Bun, edge runtimes. */
1002
- static async verifyProofAsync(leaf, root, proof) {
1099
+ /** WebCrypto variant of verifyProof (same rules, including expectedLength). */
1100
+ static async verifyProofAsync(leaf, root, proof, expectedLength) {
1101
+ if (!validProofShape(leaf, root, proof, expectedLength)) return false;
1003
1102
  const subtle = globalThis.crypto.subtle;
1004
1103
  let hash = hexToBytes(leaf);
1005
1104
  for (const sibling of proof) {
@@ -1010,9 +1109,39 @@ var AuditResource = class extends Resource {
1010
1109
  pair.set(b, a.length);
1011
1110
  hash = new Uint8Array(await subtle.digest("SHA-256", pair));
1012
1111
  }
1013
- return bytesToHex(hash) === root;
1112
+ return bytesToHex(hash) === root.toLowerCase();
1014
1113
  }
1015
1114
  };
1115
+ var BOUND_FIELDS = ["seq", "event_type", "payload", "event_id", "emitter", "schema_version", "idempotency_key"];
1116
+ var NUMERIC_RE = /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
1117
+ function normForCompare(v) {
1118
+ if (v === null || typeof v === "boolean") return v;
1119
+ if (typeof v === "number") return ["n", v];
1120
+ if (typeof v === "string") return NUMERIC_RE.test(v.trim()) ? ["n", Number(v)] : ["s", v];
1121
+ if (Array.isArray(v)) return v.map(normForCompare);
1122
+ if (typeof v === "object") {
1123
+ const o = {};
1124
+ for (const k of Object.keys(v).sort()) o[k] = normForCompare(v[k]);
1125
+ return o;
1126
+ }
1127
+ return v;
1128
+ }
1129
+ function fieldsMatchCanonical(event) {
1130
+ if (typeof event.canonical !== "string") return false;
1131
+ let c;
1132
+ try {
1133
+ c = JSON.parse(event.canonical);
1134
+ } catch {
1135
+ return false;
1136
+ }
1137
+ if (!c || typeof c !== "object" || Array.isArray(c)) return false;
1138
+ for (const f of BOUND_FIELDS) {
1139
+ if (!(f in event)) continue;
1140
+ if (!(f in c)) return false;
1141
+ if (JSON.stringify(normForCompare(c[f])) !== JSON.stringify(normForCompare(event[f]))) return false;
1142
+ }
1143
+ return true;
1144
+ }
1016
1145
 
1017
1146
  // src/resources/fees.ts
1018
1147
  var FeesResource = class extends Resource {
@@ -1091,193 +1220,124 @@ var GrantsResource = class extends Resource {
1091
1220
  }
1092
1221
  };
1093
1222
 
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
1223
  // src/resources/markets.ts
1124
1224
  var MarketsResource = class extends Resource {
1125
- /** List markets — auto-paginates. Iterate with `for await (const m of ...)`. */
1225
+ /** List markets; iterate every page with `for await (const m of pax.markets.list())`. */
1126
1226
  list(params = {}, opts) {
1127
- const query = this._buildListQuery(params);
1227
+ const query = { limit: params.limit, cursor: params.cursor, category: params.category, q: params.q };
1128
1228
  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
- );
1229
+ return new PagePromise(async () => {
1230
+ const raw = await this._http.request("GET", "/v1/markets", query, void 0, opts);
1231
+ const items = raw.body?.data?.markets ?? [];
1232
+ const nextCursor = raw.body?.data?.page?.next_cursor ?? null;
1233
+ const page = new CursorPage({
1234
+ data: items,
1235
+ nextCursor,
1236
+ hasMore: !!nextCursor,
1237
+ response: raw.response,
1238
+ fetchNext,
1239
+ requestOptions: opts
1240
+ });
1241
+ return { data: page, response: raw.response };
1242
+ });
1134
1243
  }
1135
1244
  retrieve(marketId, opts) {
1136
1245
  return this._apiPromise(
1137
1246
  () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}`, void 0, void 0, opts)
1138
1247
  );
1139
1248
  }
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;
1249
+ categories(opts) {
1146
1250
  return this._apiPromise(
1147
- () => this._http.request("POST", "/v1/markets", void 0, body, opts)
1251
+ () => this._http.request("GET", "/v1/markets/categories", void 0, void 0, opts)
1148
1252
  );
1149
1253
  }
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;
1254
+ orderbook(marketId, opts) {
1158
1255
  return this._apiPromise(
1159
- () => this._http.request("GET", `/v1/candles/${encodeURIComponent(marketId)}`, query, void 0, opts)
1256
+ () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}/orderbook`, void 0, void 0, opts)
1160
1257
  );
1161
1258
  }
1162
- orderbook(marketId, params, opts) {
1163
- const query = {
1164
- outcome_id: params.outcomeId,
1165
- depth: params.depth ?? 20
1166
- };
1259
+ priceHistory(marketId, params = {}, opts) {
1260
+ const query = { range: params.range ?? "1d" };
1167
1261
  return this._apiPromise(
1168
- () => this._http.request("GET", `/v1/orderbook/${encodeURIComponent(marketId)}`, query, void 0, opts)
1262
+ () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}/price-history`, query, void 0, opts)
1169
1263
  );
1170
1264
  }
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
1265
+ resolution(marketId, opts) {
1266
+ return this._apiPromise(
1267
+ () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}/resolution`, void 0, void 0, opts)
1181
1268
  );
1182
1269
  }
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;
1270
+ create(params, opts) {
1271
+ const body = {
1272
+ title: params.title,
1273
+ rules_text: params.rulesText,
1274
+ resolution_rule: params.resolutionRule,
1275
+ primary_source_url: params.primarySourceUrl,
1276
+ cutoff_time_ms: params.cutoffTimeMs,
1277
+ resolution_deadline_ms: params.resolutionDeadlineMs
1278
+ };
1279
+ if (params.backupSourceUrls?.length) body.backup_source_urls = params.backupSourceUrls;
1280
+ if (params.edgeCasesText !== void 0) body.edge_cases_text = params.edgeCasesText;
1281
+ if (params.description !== void 0) body.description = params.description;
1282
+ return this._apiPromise(
1283
+ () => this._http.request("POST", "/v1/composer/markets", void 0, body, opts)
1284
+ );
1189
1285
  }
1190
1286
  };
1191
1287
 
1192
1288
  // src/resources/orders.ts
1289
+ function newClientOrderId() {
1290
+ const bytes = new Uint8Array(12);
1291
+ globalThis.crypto.getRandomValues(bytes);
1292
+ return "pax-sdk-" + Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1293
+ }
1294
+ function toWire(p) {
1295
+ const side = String(p.side).toLowerCase();
1296
+ if (side !== "yes" && side !== "no") throw new Error("side must be 'yes' or 'no' (the outcome to buy)");
1297
+ const body = {
1298
+ market_id: p.marketId,
1299
+ side,
1300
+ price: String(p.price),
1301
+ size: String(p.size),
1302
+ client_order_id: p.clientOrderId ?? newClientOrderId()
1303
+ };
1304
+ if (p.fundingMode !== void 0) body.funding_mode = p.fundingMode;
1305
+ return body;
1306
+ }
1193
1307
  var OrdersResource = class extends Resource {
1194
1308
  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;
1309
+ const body = toWire(params);
1205
1310
  return this._apiPromise(
1206
1311
  () => this._http.request("POST", "/v1/orders", void 0, body, opts)
1207
1312
  );
1208
1313
  }
1209
- cancel(orderId, opts) {
1314
+ placeBatch(orders, opts) {
1315
+ const wire = orders.map(toWire);
1210
1316
  return this._apiPromise(
1211
- () => this._http.request(
1212
- "DELETE",
1213
- `/v1/orders/${encodeURIComponent(orderId)}`,
1214
- void 0,
1215
- void 0,
1216
- opts
1217
- )
1317
+ () => this._http.request("POST", "/v1/orders/batch", void 0, { orders: wire }, opts)
1218
1318
  );
1219
1319
  }
1220
1320
  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
1321
+ const query = { limit: params.limit };
1322
+ return this._apiPromise(
1323
+ () => this._http.request("GET", "/v1/orders", query, void 0, opts)
1228
1324
  );
1229
1325
  }
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
- });
1326
+ history(params = {}, opts) {
1327
+ const query = { limit: params.limit, cursor: params.cursor };
1255
1328
  return this._apiPromise(
1256
- () => this._http.request(
1257
- "POST",
1258
- "/v1/orders/batch",
1259
- void 0,
1260
- { orders: wireOrders },
1261
- opts
1262
- )
1329
+ () => this._http.request("GET", "/v1/orders/history", query, void 0, opts)
1263
1330
  );
1264
1331
  }
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) {
1332
+ cancel(orderId, opts) {
1273
1333
  return this._apiPromise(
1274
- () => this._http.request(
1275
- "DELETE",
1276
- "/v1/orders/batch",
1277
- void 0,
1278
- { orderIds },
1279
- opts
1280
- )
1334
+ () => this._http.request("DELETE", `/v1/orders/${encodeURIComponent(orderId)}`, void 0, void 0, opts)
1335
+ );
1336
+ }
1337
+ cancelAll(params = {}, opts) {
1338
+ const body = params.marketId ? { market_id: params.marketId } : {};
1339
+ return this._apiPromise(
1340
+ () => this._http.request("POST", "/v1/orders/cancel-all", void 0, body, opts)
1281
1341
  );
1282
1342
  }
1283
1343
  };
@@ -1285,10 +1345,8 @@ var OrdersResource = class extends Resource {
1285
1345
  // src/resources/sandbox.ts
1286
1346
  var SandboxKeysResource = class extends Resource {
1287
1347
  mint(params, opts) {
1288
- const body = {
1289
- org_name: params.orgName,
1290
- contact_email: params.contactEmail ?? null
1291
- };
1348
+ const body = { org_name: params.orgName };
1349
+ if (params.contactHandle !== void 0) body.contact_handle = params.contactHandle;
1292
1350
  return this._apiPromise(
1293
1351
  () => this._http.request(
1294
1352
  "POST",
@@ -1341,39 +1399,6 @@ var SettleResource = class extends Resource {
1341
1399
  () => this._http.request("POST", "/v1/builders/me/settle", void 0, body, opts)
1342
1400
  );
1343
1401
  }
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
1402
  };
1378
1403
 
1379
1404
  // src/resources/templates.ts
@@ -1402,7 +1427,6 @@ var PaxClient = class {
1402
1427
  templates;
1403
1428
  orders;
1404
1429
  account;
1405
- keys;
1406
1430
  sandbox;
1407
1431
  // legacy namespace, kept for import compat
1408
1432
  sandboxKeys;
@@ -1416,13 +1440,12 @@ var PaxClient = class {
1416
1440
  // v2.2+: public Merkle chain verifier (no-auth)
1417
1441
  settle;
1418
1442
  // v2.4+: claim accrued fee revenue
1419
- constructor(opts) {
1443
+ constructor(opts = {}) {
1420
1444
  this._http = new HttpClient(opts);
1421
1445
  this.markets = new MarketsResource(this._http);
1422
1446
  this.templates = new TemplatesResource(this._http);
1423
1447
  this.orders = new OrdersResource(this._http);
1424
1448
  this.account = new AccountResource(this._http);
1425
- this.keys = new KeysResource(this._http);
1426
1449
  this.sandbox = new SandboxResource(this._http);
1427
1450
  this.sandboxKeys = new SandboxKeysResource(this._http);
1428
1451
  this.apply = new ApplyResource(this._http);
@@ -1437,6 +1460,9 @@ var PaxClient = class {
1437
1460
  get userAgent() {
1438
1461
  return this._http.userAgent;
1439
1462
  }
1463
+ get authMode() {
1464
+ return this._http.authMode;
1465
+ }
1440
1466
  /** GET /v1/health — top-level, not paginated, always safe. */
1441
1467
  health(opts) {
1442
1468
  return new APIPromise(async () => {
@@ -1526,17 +1552,17 @@ function attachRef(opts = {}) {
1526
1552
  return { ref: s, headers: { [HEADER_NAME]: s }, persisted: true, source: "explicit" };
1527
1553
  }
1528
1554
  }
1529
- const urlRef = _parseRefFromUrl(opts.url, param);
1530
- if (urlRef) {
1531
- _persist(urlRef, key, storage, opts);
1532
- return { ref: urlRef, headers: { [HEADER_NAME]: urlRef }, persisted: true, source: "url" };
1533
- }
1534
1555
  const ck = _sanitize(_readCookie(key));
1535
1556
  if (ck) return { ref: ck, headers: { [HEADER_NAME]: ck }, persisted: false, source: "cookie" };
1536
1557
  const ls = _sanitize(_readLocalStorage(key));
1537
1558
  if (ls) return { ref: ls, headers: { [HEADER_NAME]: ls }, persisted: false, source: "localStorage" };
1538
1559
  const mem = _sanitize(_memoryStore);
1539
1560
  if (mem) return { ref: mem, headers: { [HEADER_NAME]: mem }, persisted: false, source: "memory" };
1561
+ const urlRef = _parseRefFromUrl(opts.url, param);
1562
+ if (urlRef) {
1563
+ _persist(urlRef, key, storage, opts);
1564
+ return { ref: urlRef, headers: { [HEADER_NAME]: urlRef }, persisted: true, source: "url" };
1565
+ }
1540
1566
  return { ref: null, headers: {}, persisted: false, source: "none" };
1541
1567
  }
1542
1568
  function _persist(value, key, storage, opts) {
@@ -1565,7 +1591,7 @@ function clearRef(opts = {}) {
1565
1591
  }
1566
1592
 
1567
1593
  // src/ws-client.ts
1568
- var ENV_URLS2 = {
1594
+ var ENV_URLS = {
1569
1595
  production: "wss://predictasiax.com/ws",
1570
1596
  prod: "wss://predictasiax.com/ws",
1571
1597
  live: "wss://predictasiax.com/ws",
@@ -1581,6 +1607,19 @@ async function resolveWebSocketCtor(override) {
1581
1607
  const wsModule = await import("ws");
1582
1608
  return wsModule.WebSocket;
1583
1609
  }
1610
+ function requireSecureWsUrl(url) {
1611
+ let u;
1612
+ try {
1613
+ u = new URL(url);
1614
+ } catch {
1615
+ throw new Error(`Invalid WebSocket url: ${url}`);
1616
+ }
1617
+ if (u.protocol === "wss:") return url;
1618
+ const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
1619
+ const loopback = host === "localhost" || host === "127.0.0.1" || host === "::1" || host.endsWith(".localhost");
1620
+ if (u.protocol === "ws:" && loopback) return url;
1621
+ throw new Error(`WebSocket url must use wss:// (ws:// is accepted only for localhost); got ${u.protocol}//${u.hostname}`);
1622
+ }
1584
1623
  var PaxWSClient = class {
1585
1624
  url;
1586
1625
  apiKey;
@@ -1606,7 +1645,7 @@ var PaxWSClient = class {
1606
1645
  this.bearerToken = opts.bearerToken;
1607
1646
  this.locale = opts.locale;
1608
1647
  const env = (opts.env ?? "production").toLowerCase();
1609
- this.url = opts.url ?? ENV_URLS2[env] ?? ENV_URLS2.production;
1648
+ this.url = requireSecureWsUrl(opts.url ?? ENV_URLS[env] ?? ENV_URLS.production);
1610
1649
  this.reconnect = opts.reconnect ?? true;
1611
1650
  this.backoffMinSec = opts.backoffMinSec ?? 1;
1612
1651
  this.backoffMaxSec = opts.backoffMaxSec ?? 60;
@@ -1815,9 +1854,9 @@ var PaxWSClient = class {
1815
1854
  ApplyResource,
1816
1855
  AuditResource,
1817
1856
  CursorPage,
1857
+ DEFAULT_BASE_URL,
1818
1858
  FeesResource,
1819
1859
  GrantsResource,
1820
- KeysResource,
1821
1860
  MarketsResource,
1822
1861
  OrdersResource,
1823
1862
  PagePromise,
@@ -1836,13 +1875,17 @@ var PaxWSClient = class {
1836
1875
  PaxWrongEnvKeyError,
1837
1876
  SandboxKeysResource,
1838
1877
  SandboxResource,
1878
+ SettleResource,
1839
1879
  TemplatesResource,
1840
1880
  VERSION,
1841
1881
  attachRef,
1882
+ buildCanonical,
1842
1883
  buildError,
1843
- buildMessage,
1844
1884
  clearRef,
1845
1885
  computeBackoff,
1886
+ expectedProofLength,
1887
+ fieldsMatchCanonical,
1888
+ normalizeBaseUrl,
1846
1889
  runWithRetry,
1847
1890
  signRequest
1848
1891
  });