@predictasiax/api 2.4.0 → 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,47 +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,
62
+ attachRef: () => attachRef,
63
+ buildCanonical: () => buildCanonical,
61
64
  buildError: () => buildError,
62
- buildMessage: () => buildMessage,
65
+ clearRef: () => clearRef,
63
66
  computeBackoff: () => computeBackoff,
67
+ expectedProofLength: () => expectedProofLength,
68
+ normalizeBaseUrl: () => normalizeBaseUrl,
64
69
  runWithRetry: () => runWithRetry,
65
70
  signRequest: () => signRequest
66
71
  });
67
72
  module.exports = __toCommonJS(index_exports);
68
73
 
69
74
  // src/auth.ts
70
- function buildMessage(method, path, body, timestampMs) {
71
- 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");
72
77
  }
73
- var _nodeCrypto = null;
74
- var _cryptoLoadAttempted = false;
75
- async function loadNodeCrypto() {
76
- if (_cryptoLoadAttempted) return _nodeCrypto;
77
- _cryptoLoadAttempted = true;
78
- try {
79
- const mod = await import("crypto");
80
- _nodeCrypto = { createHmac: mod.createHmac };
81
- return _nodeCrypto;
82
- } catch {
83
- 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("");
84
84
  }
85
- }
86
- function hasSubtleCrypto() {
87
- return typeof globalThis.crypto?.subtle?.sign === "function";
88
- }
89
- async function signWithWebCrypto(secret, message) {
90
- const enc = new TextEncoder();
91
- const key = await globalThis.crypto.subtle.importKey(
92
- "raw",
93
- enc.encode(secret),
94
- { name: "HMAC", hash: "SHA-256" },
95
- false,
96
- ["sign"]
97
- );
98
- const sig = await globalThis.crypto.subtle.sign("HMAC", key, enc.encode(message));
99
- return arrayBufferToBase64(sig);
85
+ throw new Error("No secure random source available for the HMAC nonce");
100
86
  }
101
87
  function arrayBufferToBase64(buf) {
102
88
  const bytes = new Uint8Array(buf);
@@ -105,21 +91,28 @@ function arrayBufferToBase64(buf) {
105
91
  for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
106
92
  return globalThis.btoa(bin);
107
93
  }
108
- async function signWithNodeCrypto(secret, message) {
109
- const nc = await loadNodeCrypto();
110
- if (!nc) throw new Error("No HMAC backend \u2014 neither node:crypto nor WebCrypto available in this runtime");
111
- 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");
112
103
  }
113
104
  async function signRequest(input) {
114
- const ts = String(input.timestampMs ?? Date.now());
115
- const methodUpper = input.method.toUpperCase();
116
- const message = ts + methodUpper + input.path + (input.body || "");
117
- 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);
118
111
  return {
119
- POLY_ACCESS_KEY: input.keyId,
120
- POLY_TIMESTAMP: ts,
121
- POLY_PASSPHRASE: input.passphrase,
122
- POLY_SIGNATURE: signature
112
+ "PAX-ADDRESS": input.keyId,
113
+ "PAX-TIMESTAMP": ts,
114
+ "PAX-NONCE": nonce,
115
+ "PAX-SIGNATURE": await hmacSha256Base64(input.apiKey, canonical)
123
116
  };
124
117
  }
125
118
 
@@ -277,6 +270,16 @@ var PROTECTED_HEADERS = /* @__PURE__ */ new Set(
277
270
  "poly_timestamp",
278
271
  "poly_passphrase",
279
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",
280
283
  "idempotency-key",
281
284
  "cache-control"
282
285
  ]
@@ -365,19 +368,19 @@ async function runWithRetry(fn, opts = {}) {
365
368
  }
366
369
 
367
370
  // src/http.ts
368
- var VERSION = "2.2.0";
369
- var ENV_URLS = {
370
- production: "https://api.predictasiax.com/v1",
371
- prod: "https://api.predictasiax.com/v1",
372
- live: "https://api.predictasiax.com/v1",
373
- sandbox: "https://api.predictasiax.com/v1",
374
- test: "https://api.predictasiax.com/v1"
375
- };
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
+ }
376
379
  var DEFAULT_TIMEOUT_MS = 3e4;
377
380
  var DEFAULT_MAX_RETRIES = 5;
378
381
  var DEFAULT_MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
379
382
  var DEFAULT_USER_AGENT = `pax-api-ts/${VERSION}`;
380
- var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
383
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
381
384
  function isLoopback(hostname) {
382
385
  return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
383
386
  }
@@ -460,9 +463,15 @@ async function readCappedText(response, maxBytes) {
460
463
  var HttpClient = class {
461
464
  baseUrl;
462
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
+ }
463
473
  apiKey;
464
- secret;
465
- passphrase;
474
+ keyId;
466
475
  bearerToken;
467
476
  timeoutMs;
468
477
  maxRetries;
@@ -472,23 +481,30 @@ var HttpClient = class {
472
481
  fetchImpl;
473
482
  fetchOptions;
474
483
  constructor(opts) {
475
- if (!opts.apiKey && !opts.bearerToken) {
476
- 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
+ );
477
488
  }
478
- if (opts.secret && !opts.passphrase) {
479
- throw new Error("Provide passphrase together with secret for HMAC");
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");
495
+ }
496
+ if (apiKey && opts.bearerToken) {
497
+ throw new Error("Pass either apiKey or bearerToken, not both");
480
498
  }
481
499
  if (typeof window !== "undefined" && !opts.dangerouslyAllowBrowser) {
482
500
  throw new Error(
483
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`."
484
502
  );
485
503
  }
486
- this.apiKey = opts.apiKey;
487
- this.secret = opts.secret;
488
- this.passphrase = opts.passphrase;
504
+ this.apiKey = apiKey;
505
+ this.keyId = opts.keyId;
489
506
  this.bearerToken = opts.bearerToken;
490
- const env = (opts.env ?? "production").toLowerCase();
491
- const rawBaseUrl = (opts.baseUrl ?? ENV_URLS[env] ?? ENV_URLS.production).replace(/\/$/, "");
507
+ const rawBaseUrl = normalizeBaseUrl(opts.baseUrl ?? DEFAULT_BASE_URL);
492
508
  validateBaseUrl(rawBaseUrl, opts.allowInsecureHttp ?? false);
493
509
  this.baseUrl = rawBaseUrl;
494
510
  this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -524,19 +540,18 @@ var HttpClient = class {
524
540
  };
525
541
  if (body) managed["Content-Type"] = "application/json";
526
542
  if (idempotencyKey) managed["Idempotency-Key"] = idempotencyKey;
527
- if (this.secret && this.passphrase && this.apiKey) {
543
+ if (this.keyId && this.apiKey) {
528
544
  const sig = await signRequest({
529
545
  method,
530
- path: pathWithQuery,
546
+ pathWithQuery,
531
547
  body,
532
- keyId: this.apiKey,
533
- secret: this.secret,
534
- passphrase: this.passphrase,
535
- timestampMs: Date.now() + this.clockOffsetMs
548
+ keyId: this.keyId,
549
+ apiKey: this.apiKey,
550
+ timestampSec: (Date.now() + this.clockOffsetMs) / 1e3
536
551
  });
537
552
  Object.assign(managed, sig);
538
553
  } else if (this.apiKey) {
539
- managed["X-Api-Key"] = this.apiKey;
554
+ managed["Authorization"] = `Bearer ${this.apiKey}`;
540
555
  } else if (this.bearerToken) {
541
556
  managed["Authorization"] = `Bearer ${this.bearerToken}`;
542
557
  }
@@ -754,40 +769,211 @@ var Resource = class {
754
769
  });
755
770
  }
756
771
  };
757
- function paginationParams(p) {
758
- if (!p) return {};
759
- const out = {};
760
- if (p.limit !== void 0) out.limit = p.limit;
761
- if (typeof p.cursor === "string") out.cursor = p.cursor;
762
- return out;
763
- }
764
772
 
765
773
  // src/resources/account.ts
766
774
  var AccountResource = class extends Resource {
767
- retrieve(opts) {
775
+ balance(opts) {
768
776
  return this._apiPromise(
769
- () => this._http.request("GET", "/v1/account", void 0, void 0, opts)
777
+ () => this._http.request("GET", "/v1/balance", void 0, void 0, opts)
770
778
  );
771
779
  }
772
- positions(opts) {
780
+ /** @deprecated Use balance(). Kept as an alias. */
781
+ retrieve(opts) {
782
+ return this.balance(opts);
783
+ }
784
+ portfolio(opts) {
773
785
  return this._apiPromise(
774
- () => this._http.request("GET", "/v1/account/positions", void 0, void 0, opts)
786
+ () => this._http.request("GET", "/v1/portfolio", void 0, void 0, opts)
775
787
  );
776
788
  }
777
- trades(params = {}, opts) {
778
- const query = paginationParams({ limit: params.limit ?? 50, cursor: params.cursor });
779
- if (params.marketId) query.market_id = params.marketId;
780
- const fetchNext = (cursor, ro) => this.trades({ ...params, cursor }, ro);
781
- return this._pagePromise(
782
- () => this._http.request("GET", "/v1/account/trades", query, void 0, opts),
783
- fetchNext,
784
- opts
789
+ positions(opts) {
790
+ return this._apiPromise(
791
+ () => this._http.request("GET", "/v1/positions", void 0, void 0, opts)
785
792
  );
786
793
  }
787
794
  };
788
795
 
789
796
  // src/resources/audit.ts
790
- var AuditResource = class extends Resource {
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
+ }
816
+ function hexToBytes(hex) {
817
+ const out = new Uint8Array(hex.length / 2);
818
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.substr(i * 2, 2), 16);
819
+ return out;
820
+ }
821
+ function bytesToHex(bytes) {
822
+ let s = "";
823
+ for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
824
+ return s;
825
+ }
826
+ function cmpBytes(a, b) {
827
+ const n = Math.min(a.length, b.length);
828
+ for (let i = 0; i < n; i++) if (a[i] !== b[i]) return a[i] - b[i];
829
+ return a.length - b.length;
830
+ }
831
+ function sha256Pure(msg) {
832
+ const K = new Uint32Array([
833
+ 1116352408,
834
+ 1899447441,
835
+ 3049323471,
836
+ 3921009573,
837
+ 961987163,
838
+ 1508970993,
839
+ 2453635748,
840
+ 2870763221,
841
+ 3624381080,
842
+ 310598401,
843
+ 607225278,
844
+ 1426881987,
845
+ 1925078388,
846
+ 2162078206,
847
+ 2614888103,
848
+ 3248222580,
849
+ 3835390401,
850
+ 4022224774,
851
+ 264347078,
852
+ 604807628,
853
+ 770255983,
854
+ 1249150122,
855
+ 1555081692,
856
+ 1996064986,
857
+ 2554220882,
858
+ 2821834349,
859
+ 2952996808,
860
+ 3210313671,
861
+ 3336571891,
862
+ 3584528711,
863
+ 113926993,
864
+ 338241895,
865
+ 666307205,
866
+ 773529912,
867
+ 1294757372,
868
+ 1396182291,
869
+ 1695183700,
870
+ 1986661051,
871
+ 2177026350,
872
+ 2456956037,
873
+ 2730485921,
874
+ 2820302411,
875
+ 3259730800,
876
+ 3345764771,
877
+ 3516065817,
878
+ 3600352804,
879
+ 4094571909,
880
+ 275423344,
881
+ 430227734,
882
+ 506948616,
883
+ 659060556,
884
+ 883997877,
885
+ 958139571,
886
+ 1322822218,
887
+ 1537002063,
888
+ 1747873779,
889
+ 1955562222,
890
+ 2024104815,
891
+ 2227730452,
892
+ 2361852424,
893
+ 2428436474,
894
+ 2756734187,
895
+ 3204031479,
896
+ 3329325298
897
+ ]);
898
+ let h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762;
899
+ let h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225;
900
+ const l = msg.length;
901
+ const bitLen = l * 8;
902
+ const k = (56 - (l + 1) % 64 + 64) % 64;
903
+ const total = l + 1 + k + 8;
904
+ const m = new Uint8Array(total);
905
+ m.set(msg, 0);
906
+ m[l] = 128;
907
+ const hi = Math.floor(bitLen / 4294967296);
908
+ const lo = bitLen >>> 0;
909
+ m[total - 8] = hi >>> 24 & 255;
910
+ m[total - 7] = hi >>> 16 & 255;
911
+ m[total - 6] = hi >>> 8 & 255;
912
+ m[total - 5] = hi & 255;
913
+ m[total - 4] = lo >>> 24 & 255;
914
+ m[total - 3] = lo >>> 16 & 255;
915
+ m[total - 2] = lo >>> 8 & 255;
916
+ m[total - 1] = lo & 255;
917
+ const w = new Uint32Array(64);
918
+ const rotr = (x, n) => x >>> n | x << 32 - n;
919
+ for (let off = 0; off < total; off += 64) {
920
+ for (let i = 0; i < 16; i++) {
921
+ w[i] = (m[off + i * 4] << 24 | m[off + i * 4 + 1] << 16 | m[off + i * 4 + 2] << 8 | m[off + i * 4 + 3]) >>> 0;
922
+ }
923
+ for (let i = 16; i < 64; i++) {
924
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
925
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
926
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
927
+ }
928
+ let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
929
+ for (let i = 0; i < 64; i++) {
930
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
931
+ const ch = e & f ^ ~e & g;
932
+ const t1 = h + S1 + ch + K[i] + w[i] >>> 0;
933
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
934
+ const maj = a & b ^ a & c ^ b & c;
935
+ const t2 = S0 + maj >>> 0;
936
+ h = g;
937
+ g = f;
938
+ f = e;
939
+ e = d + t1 >>> 0;
940
+ d = c;
941
+ c = b;
942
+ b = a;
943
+ a = t1 + t2 >>> 0;
944
+ }
945
+ h0 = h0 + a >>> 0;
946
+ h1 = h1 + b >>> 0;
947
+ h2 = h2 + c >>> 0;
948
+ h3 = h3 + d >>> 0;
949
+ h4 = h4 + e >>> 0;
950
+ h5 = h5 + f >>> 0;
951
+ h6 = h6 + g >>> 0;
952
+ h7 = h7 + h >>> 0;
953
+ }
954
+ const out = new Uint8Array(32);
955
+ const hs = [h0, h1, h2, h3, h4, h5, h6, h7];
956
+ for (let i = 0; i < 8; i++) {
957
+ out[i * 4] = hs[i] >>> 24 & 255;
958
+ out[i * 4 + 1] = hs[i] >>> 16 & 255;
959
+ out[i * 4 + 2] = hs[i] >>> 8 & 255;
960
+ out[i * 4 + 3] = hs[i] & 255;
961
+ }
962
+ return out;
963
+ }
964
+ function resolveSyncSha256() {
965
+ if (typeof require === "function") {
966
+ try {
967
+ const nodeCrypto = require("crypto");
968
+ if (nodeCrypto && typeof nodeCrypto.createHash === "function") {
969
+ return (bytes) => new Uint8Array(nodeCrypto.createHash("sha256").update(bytes).digest());
970
+ }
971
+ } catch {
972
+ }
973
+ }
974
+ return sha256Pure;
975
+ }
976
+ var AuditResource = class _AuditResource extends Resource {
791
977
  status(opts) {
792
978
  return this._apiPromise(
793
979
  () => this._http.request("GET", "/v1/audit/status", void 0, void 0, opts)
@@ -819,36 +1005,100 @@ var AuditResource = class extends Resource {
819
1005
  );
820
1006
  }
821
1007
  /**
822
- * Verify a Merkle inclusion proof locally (client-side). Mirrors
823
- * OpenZeppelin's sorted-pair sha256 algorithm — identical logic to the
824
- * server-side batcher, so callers can independently confirm inclusion
825
- * without trusting the API response.
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.
826
1011
  */
827
- static verifyProof(leaf, root, proof) {
828
- const crypto = globalThis.crypto || require("crypto");
829
- let hash = leaf;
830
- for (const sibling of proof) {
831
- const [a, b] = hash < sibling ? [hash, sibling] : [sibling, hash];
832
- if (crypto.subtle && typeof crypto.subtle.digest === "function") {
833
- throw new Error("Use verifyProofAsync() in browser/edge runtimes (WebCrypto is async)");
834
- }
835
- hash = crypto.createHash("sha256").update(a + b).digest("hex");
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" };
836
1044
  }
837
- return hash === root;
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
+ };
838
1063
  }
839
- /** Async variant using WebCrypto — works in browsers, Deno, Bun, edge runtimes. */
840
- static async verifyProofAsync(leaf, root, proof) {
841
- const enc = new TextEncoder();
842
- async function sha(s) {
843
- const buf = await globalThis.crypto.subtle.digest("SHA-256", enc.encode(s));
844
- return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
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;
1076
+ const sha256 = resolveSyncSha256();
1077
+ let hash = hexToBytes(leaf);
1078
+ for (const sibling of proof) {
1079
+ const sib = hexToBytes(sibling);
1080
+ const [a, b] = cmpBytes(hash, sib) <= 0 ? [hash, sib] : [sib, hash];
1081
+ const pair = new Uint8Array(a.length + b.length);
1082
+ pair.set(a, 0);
1083
+ pair.set(b, a.length);
1084
+ hash = sha256(pair);
845
1085
  }
846
- let hash = leaf;
1086
+ return bytesToHex(hash) === root.toLowerCase();
1087
+ }
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;
1091
+ const subtle = globalThis.crypto.subtle;
1092
+ let hash = hexToBytes(leaf);
847
1093
  for (const sibling of proof) {
848
- const [a, b] = hash < sibling ? [hash, sibling] : [sibling, hash];
849
- hash = await sha(a + b);
1094
+ const sib = hexToBytes(sibling);
1095
+ const [a, b] = cmpBytes(hash, sib) <= 0 ? [hash, sib] : [sib, hash];
1096
+ const pair = new Uint8Array(a.length + b.length);
1097
+ pair.set(a, 0);
1098
+ pair.set(b, a.length);
1099
+ hash = new Uint8Array(await subtle.digest("SHA-256", pair));
850
1100
  }
851
- return hash === root;
1101
+ return bytesToHex(hash) === root.toLowerCase();
852
1102
  }
853
1103
  };
854
1104
 
@@ -929,193 +1179,124 @@ var GrantsResource = class extends Resource {
929
1179
  }
930
1180
  };
931
1181
 
932
- // src/resources/keys.ts
933
- var KeysResource = class extends Resource {
934
- create(params = {}, opts) {
935
- const body = {
936
- name: params.name ?? "default",
937
- scopes: params.scopes ?? ["read"]
938
- };
939
- return this._apiPromise(
940
- () => this._http.request("POST", "/v1/keys", void 0, body, opts)
941
- );
942
- }
943
- list(opts) {
944
- return this._apiPromise(
945
- () => this._http.request("GET", "/v1/keys", void 0, void 0, opts)
946
- );
947
- }
948
- revoke(keyId, opts) {
949
- return this._apiPromise(
950
- () => this._http.request(
951
- "DELETE",
952
- `/v1/keys/${encodeURIComponent(keyId)}`,
953
- void 0,
954
- void 0,
955
- opts
956
- )
957
- );
958
- }
959
- };
960
-
961
1182
  // src/resources/markets.ts
962
1183
  var MarketsResource = class extends Resource {
963
- /** 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())`. */
964
1185
  list(params = {}, opts) {
965
- const query = this._buildListQuery(params);
1186
+ const query = { limit: params.limit, cursor: params.cursor, category: params.category, q: params.q };
966
1187
  const fetchNext = (cursor, ro) => this.list({ ...params, cursor }, ro);
967
- return this._pagePromise(
968
- () => this._http.request("GET", "/v1/markets", query, void 0, opts),
969
- fetchNext,
970
- opts
971
- );
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
+ });
972
1202
  }
973
1203
  retrieve(marketId, opts) {
974
1204
  return this._apiPromise(
975
1205
  () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}`, void 0, void 0, opts)
976
1206
  );
977
1207
  }
978
- create(params, opts) {
979
- const body = {
980
- template_id: params.templateId,
981
- params: params.params
982
- };
983
- if (params.creatorMetadata) body.creator_metadata = params.creatorMetadata;
1208
+ categories(opts) {
984
1209
  return this._apiPromise(
985
- () => this._http.request("POST", "/v1/markets", void 0, body, opts)
1210
+ () => this._http.request("GET", "/v1/markets/categories", void 0, void 0, opts)
986
1211
  );
987
1212
  }
988
- candles(marketId, params, opts) {
989
- const query = {
990
- outcome_id: params.outcomeId,
991
- interval: params.interval ?? "1m",
992
- limit: params.limit ?? 500
993
- };
994
- if (params.fromMs !== void 0) query.from_ms = params.fromMs;
995
- if (params.toMs !== void 0) query.to_ms = params.toMs;
1213
+ orderbook(marketId, opts) {
996
1214
  return this._apiPromise(
997
- () => 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)
998
1216
  );
999
1217
  }
1000
- orderbook(marketId, params, opts) {
1001
- const query = {
1002
- outcome_id: params.outcomeId,
1003
- depth: params.depth ?? 20
1004
- };
1218
+ priceHistory(marketId, params = {}, opts) {
1219
+ const query = { range: params.range ?? "1d" };
1005
1220
  return this._apiPromise(
1006
- () => 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)
1007
1222
  );
1008
1223
  }
1009
- /** Public trade tape for a market (all fills, not your fills). */
1010
- trades(marketId, params = {}, opts) {
1011
- const query = { limit: params.limit ?? 50 };
1012
- if (params.outcomeId) query.outcome_id = params.outcomeId;
1013
- if (params.cursor) query.cursor = params.cursor;
1014
- const fetchNext = (cursor, ro) => this.trades(marketId, { ...params, cursor }, ro);
1015
- return this._pagePromise(
1016
- () => this._http.request("GET", `/v1/trades/${encodeURIComponent(marketId)}`, query, void 0, opts),
1017
- fetchNext,
1018
- opts
1224
+ resolution(marketId, opts) {
1225
+ return this._apiPromise(
1226
+ () => this._http.request("GET", `/v1/markets/${encodeURIComponent(marketId)}/resolution`, void 0, void 0, opts)
1019
1227
  );
1020
1228
  }
1021
- _buildListQuery(params) {
1022
- const query = paginationParams({ limit: params.limit ?? 50, cursor: params.cursor });
1023
- if (params.category) query.category = params.category;
1024
- if (params.marketType) query.market_type = params.marketType;
1025
- if (params.status) query.status = params.status;
1026
- 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
+ );
1027
1244
  }
1028
1245
  };
1029
1246
 
1030
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
+ }
1031
1266
  var OrdersResource = class extends Resource {
1032
1267
  place(params, opts) {
1033
- const body = {
1034
- market_id: params.marketId,
1035
- outcome_id: params.outcomeId,
1036
- side: params.side,
1037
- order_type: params.orderType,
1038
- size: String(params.size)
1039
- };
1040
- if (params.price !== void 0) body.price = String(params.price);
1041
- if (params.clientOrderId) body.client_order_id = params.clientOrderId;
1042
- if (params.timeInForce) body.time_in_force = params.timeInForce;
1268
+ const body = toWire(params);
1043
1269
  return this._apiPromise(
1044
1270
  () => this._http.request("POST", "/v1/orders", void 0, body, opts)
1045
1271
  );
1046
1272
  }
1047
- cancel(orderId, opts) {
1273
+ placeBatch(orders, opts) {
1274
+ const wire = orders.map(toWire);
1048
1275
  return this._apiPromise(
1049
- () => this._http.request(
1050
- "DELETE",
1051
- `/v1/orders/${encodeURIComponent(orderId)}`,
1052
- void 0,
1053
- void 0,
1054
- opts
1055
- )
1276
+ () => this._http.request("POST", "/v1/orders/batch", void 0, { orders: wire }, opts)
1056
1277
  );
1057
1278
  }
1058
1279
  list(params = {}, opts) {
1059
- const query = paginationParams({ limit: params.limit ?? 50, cursor: params.cursor });
1060
- if (params.status) query.status = params.status;
1061
- const fetchNext = (cursor, ro) => this.list({ ...params, cursor }, ro);
1062
- return this._pagePromise(
1063
- () => this._http.request("GET", "/v1/account/orders", query, void 0, opts),
1064
- fetchNext,
1065
- opts
1280
+ const query = { limit: params.limit };
1281
+ return this._apiPromise(
1282
+ () => this._http.request("GET", "/v1/orders", query, void 0, opts)
1066
1283
  );
1067
1284
  }
1068
- /**
1069
- * Place multiple orders in a single request (up to 25 per batch).
1070
- *
1071
- * Each order is processed sequentially by the CLOB engine (single-writer per
1072
- * market). Response contains a `results` array with one entry per input order
1073
- * (indexed) plus a `summary` with counts + duration. One bad order does not
1074
- * fail the whole batch — inspect `results[i].ok` per item.
1075
- *
1076
- * Batch cap is env-tunable server-side (BATCH_ORDERS_MAX, default 25). Exceeding
1077
- * returns `413 BATCH_TOO_LARGE`.
1078
- */
1079
- placeBatch(orders, opts) {
1080
- const wireOrders = orders.map((o) => {
1081
- const body = {
1082
- market_id: o.marketId,
1083
- outcome_id: o.outcomeId,
1084
- side: o.side,
1085
- order_type: o.orderType,
1086
- size: String(o.size)
1087
- };
1088
- if (o.price !== void 0) body.price = String(o.price);
1089
- if (o.clientOrderId) body.client_order_id = o.clientOrderId;
1090
- if (o.timeInForce) body.time_in_force = o.timeInForce;
1091
- return body;
1092
- });
1285
+ history(params = {}, opts) {
1286
+ const query = { limit: params.limit, cursor: params.cursor };
1093
1287
  return this._apiPromise(
1094
- () => this._http.request(
1095
- "POST",
1096
- "/v1/orders/batch",
1097
- void 0,
1098
- { orders: wireOrders },
1099
- opts
1100
- )
1288
+ () => this._http.request("GET", "/v1/orders/history", query, void 0, opts)
1101
1289
  );
1102
1290
  }
1103
- /**
1104
- * Cancel multiple orders in a single request (up to 50 per batch).
1105
- *
1106
- * Each cancel is processed sequentially by the CLOB engine. Response mirrors
1107
- * `placeBatch` shape — inspect `results[i].ok` per item. Batch cap env-tunable
1108
- * server-side (BATCH_CANCEL_MAX, default 50).
1109
- */
1110
- cancelBatch(orderIds, opts) {
1291
+ cancel(orderId, opts) {
1111
1292
  return this._apiPromise(
1112
- () => this._http.request(
1113
- "DELETE",
1114
- "/v1/orders/batch",
1115
- void 0,
1116
- { orderIds },
1117
- opts
1118
- )
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)
1119
1300
  );
1120
1301
  }
1121
1302
  };
@@ -1123,10 +1304,8 @@ var OrdersResource = class extends Resource {
1123
1304
  // src/resources/sandbox.ts
1124
1305
  var SandboxKeysResource = class extends Resource {
1125
1306
  mint(params, opts) {
1126
- const body = {
1127
- org_name: params.orgName,
1128
- contact_email: params.contactEmail ?? null
1129
- };
1307
+ const body = { org_name: params.orgName };
1308
+ if (params.contactHandle !== void 0) body.contact_handle = params.contactHandle;
1130
1309
  return this._apiPromise(
1131
1310
  () => this._http.request(
1132
1311
  "POST",
@@ -1179,39 +1358,6 @@ var SettleResource = class extends Resource {
1179
1358
  () => this._http.request("POST", "/v1/builders/me/settle", void 0, body, opts)
1180
1359
  );
1181
1360
  }
1182
- /** Admin settle a specific builder's fees — POST /v1/admin/builders/{userId}/settle.
1183
- * Requires X-Admin-Key header. */
1184
- adminBuilder(userId, params, adminKey, opts) {
1185
- const body = {
1186
- address: params.address,
1187
- asset: params.asset ?? "USDT",
1188
- network: params.network ?? "polygon",
1189
- min_amount: params.min_amount ?? 0
1190
- };
1191
- const mergedOpts = {
1192
- ...opts || {},
1193
- headers: { ...opts?.headers || {}, "X-Admin-Key": adminKey }
1194
- };
1195
- return this._apiPromise(
1196
- () => this._http.request("POST", `/v1/admin/builders/${encodeURIComponent(userId)}/settle`, void 0, body, mergedOpts)
1197
- );
1198
- }
1199
- /** Admin settle a market creator's fees — POST /v1/admin/creators/{userId}/settle. */
1200
- adminCreator(userId, params, adminKey, opts) {
1201
- const body = {
1202
- address: params.address,
1203
- asset: params.asset ?? "USDT",
1204
- network: params.network ?? "polygon",
1205
- min_amount: params.min_amount ?? 0
1206
- };
1207
- const mergedOpts = {
1208
- ...opts || {},
1209
- headers: { ...opts?.headers || {}, "X-Admin-Key": adminKey }
1210
- };
1211
- return this._apiPromise(
1212
- () => this._http.request("POST", `/v1/admin/creators/${encodeURIComponent(userId)}/settle`, void 0, body, mergedOpts)
1213
- );
1214
- }
1215
1361
  };
1216
1362
 
1217
1363
  // src/resources/templates.ts
@@ -1240,7 +1386,6 @@ var PaxClient = class {
1240
1386
  templates;
1241
1387
  orders;
1242
1388
  account;
1243
- keys;
1244
1389
  sandbox;
1245
1390
  // legacy namespace, kept for import compat
1246
1391
  sandboxKeys;
@@ -1254,13 +1399,12 @@ var PaxClient = class {
1254
1399
  // v2.2+: public Merkle chain verifier (no-auth)
1255
1400
  settle;
1256
1401
  // v2.4+: claim accrued fee revenue
1257
- constructor(opts) {
1402
+ constructor(opts = {}) {
1258
1403
  this._http = new HttpClient(opts);
1259
1404
  this.markets = new MarketsResource(this._http);
1260
1405
  this.templates = new TemplatesResource(this._http);
1261
1406
  this.orders = new OrdersResource(this._http);
1262
1407
  this.account = new AccountResource(this._http);
1263
- this.keys = new KeysResource(this._http);
1264
1408
  this.sandbox = new SandboxResource(this._http);
1265
1409
  this.sandboxKeys = new SandboxKeysResource(this._http);
1266
1410
  this.apply = new ApplyResource(this._http);
@@ -1275,6 +1419,9 @@ var PaxClient = class {
1275
1419
  get userAgent() {
1276
1420
  return this._http.userAgent;
1277
1421
  }
1422
+ get authMode() {
1423
+ return this._http.authMode;
1424
+ }
1278
1425
  /** GET /v1/health — top-level, not paginated, always safe. */
1279
1426
  health(opts) {
1280
1427
  return new APIPromise(async () => {
@@ -1291,8 +1438,119 @@ var PaxClient = class {
1291
1438
  }
1292
1439
  };
1293
1440
 
1441
+ // src/attach-ref.ts
1442
+ var DEFAULT_STORAGE_KEY = "pax_builder_ref";
1443
+ var DEFAULT_COOKIE_MAX_AGE = 90 * 24 * 3600;
1444
+ var HEADER_NAME = "X-Builder-Ref";
1445
+ var _memoryStore = null;
1446
+ function _isBrowser() {
1447
+ return typeof window !== "undefined" && typeof document !== "undefined";
1448
+ }
1449
+ function _sanitize(v) {
1450
+ if (v == null) return null;
1451
+ const s = String(v).trim().slice(0, 64);
1452
+ if (!/^[A-Za-z0-9_-]{3,64}$/.test(s)) return null;
1453
+ return s;
1454
+ }
1455
+ function _readCookie(name) {
1456
+ if (!_isBrowser()) return null;
1457
+ const parts = document.cookie.split(";").map((s) => s.trim());
1458
+ for (const p of parts) {
1459
+ const eq = p.indexOf("=");
1460
+ if (eq === -1) continue;
1461
+ const k = p.slice(0, eq).trim();
1462
+ if (k === name) return decodeURIComponent(p.slice(eq + 1));
1463
+ }
1464
+ return null;
1465
+ }
1466
+ function _writeCookie(name, value, maxAgeSec, domain) {
1467
+ if (!_isBrowser()) return;
1468
+ const parts = [
1469
+ `${name}=${encodeURIComponent(value)}`,
1470
+ `Path=/`,
1471
+ `Max-Age=${maxAgeSec}`,
1472
+ `SameSite=Lax`
1473
+ ];
1474
+ if (window.location && window.location.protocol === "https:") parts.push("Secure");
1475
+ if (domain) parts.push(`Domain=${domain}`);
1476
+ document.cookie = parts.join("; ");
1477
+ }
1478
+ function _readLocalStorage(key) {
1479
+ try {
1480
+ if (!_isBrowser() || !window.localStorage) return null;
1481
+ return window.localStorage.getItem(key);
1482
+ } catch {
1483
+ return null;
1484
+ }
1485
+ }
1486
+ function _writeLocalStorage(key, value) {
1487
+ try {
1488
+ if (!_isBrowser() || !window.localStorage) return;
1489
+ window.localStorage.setItem(key, value);
1490
+ } catch {
1491
+ }
1492
+ }
1493
+ function _parseRefFromUrl(url, param) {
1494
+ const src = url ?? (_isBrowser() ? window.location.href : "");
1495
+ if (!src) return null;
1496
+ try {
1497
+ const u = new URL(src);
1498
+ return _sanitize(u.searchParams.get(param));
1499
+ } catch {
1500
+ return null;
1501
+ }
1502
+ }
1503
+ function attachRef(opts = {}) {
1504
+ const param = opts.queryParam ?? "ref";
1505
+ const key = opts.storageKey ?? DEFAULT_STORAGE_KEY;
1506
+ const storage = opts.storage ?? (_isBrowser() ? "cookie" : "memory");
1507
+ if (opts.ref) {
1508
+ const s = _sanitize(opts.ref);
1509
+ if (s) {
1510
+ _persist(s, key, storage, opts);
1511
+ return { ref: s, headers: { [HEADER_NAME]: s }, persisted: true, source: "explicit" };
1512
+ }
1513
+ }
1514
+ const urlRef = _parseRefFromUrl(opts.url, param);
1515
+ if (urlRef) {
1516
+ _persist(urlRef, key, storage, opts);
1517
+ return { ref: urlRef, headers: { [HEADER_NAME]: urlRef }, persisted: true, source: "url" };
1518
+ }
1519
+ const ck = _sanitize(_readCookie(key));
1520
+ if (ck) return { ref: ck, headers: { [HEADER_NAME]: ck }, persisted: false, source: "cookie" };
1521
+ const ls = _sanitize(_readLocalStorage(key));
1522
+ if (ls) return { ref: ls, headers: { [HEADER_NAME]: ls }, persisted: false, source: "localStorage" };
1523
+ const mem = _sanitize(_memoryStore);
1524
+ if (mem) return { ref: mem, headers: { [HEADER_NAME]: mem }, persisted: false, source: "memory" };
1525
+ return { ref: null, headers: {}, persisted: false, source: "none" };
1526
+ }
1527
+ function _persist(value, key, storage, opts) {
1528
+ switch (storage) {
1529
+ case "cookie":
1530
+ _writeCookie(key, value, opts.cookieMaxAgeSec ?? DEFAULT_COOKIE_MAX_AGE, opts.cookieDomain);
1531
+ break;
1532
+ case "localStorage":
1533
+ _writeLocalStorage(key, value);
1534
+ break;
1535
+ case "memory":
1536
+ _memoryStore = value;
1537
+ break;
1538
+ }
1539
+ }
1540
+ function clearRef(opts = {}) {
1541
+ const key = opts.storageKey ?? DEFAULT_STORAGE_KEY;
1542
+ _memoryStore = null;
1543
+ if (_isBrowser()) {
1544
+ _writeCookie(key, "", 0, opts.cookieDomain);
1545
+ try {
1546
+ window.localStorage && window.localStorage.removeItem(key);
1547
+ } catch {
1548
+ }
1549
+ }
1550
+ }
1551
+
1294
1552
  // src/ws-client.ts
1295
- var ENV_URLS2 = {
1553
+ var ENV_URLS = {
1296
1554
  production: "wss://predictasiax.com/ws",
1297
1555
  prod: "wss://predictasiax.com/ws",
1298
1556
  live: "wss://predictasiax.com/ws",
@@ -1333,7 +1591,7 @@ var PaxWSClient = class {
1333
1591
  this.bearerToken = opts.bearerToken;
1334
1592
  this.locale = opts.locale;
1335
1593
  const env = (opts.env ?? "production").toLowerCase();
1336
- this.url = opts.url ?? ENV_URLS2[env] ?? ENV_URLS2.production;
1594
+ this.url = opts.url ?? ENV_URLS[env] ?? ENV_URLS.production;
1337
1595
  this.reconnect = opts.reconnect ?? true;
1338
1596
  this.backoffMinSec = opts.backoffMinSec ?? 1;
1339
1597
  this.backoffMaxSec = opts.backoffMaxSec ?? 60;
@@ -1542,9 +1800,9 @@ var PaxWSClient = class {
1542
1800
  ApplyResource,
1543
1801
  AuditResource,
1544
1802
  CursorPage,
1803
+ DEFAULT_BASE_URL,
1545
1804
  FeesResource,
1546
1805
  GrantsResource,
1547
- KeysResource,
1548
1806
  MarketsResource,
1549
1807
  OrdersResource,
1550
1808
  PagePromise,
@@ -1563,11 +1821,16 @@ var PaxWSClient = class {
1563
1821
  PaxWrongEnvKeyError,
1564
1822
  SandboxKeysResource,
1565
1823
  SandboxResource,
1824
+ SettleResource,
1566
1825
  TemplatesResource,
1567
1826
  VERSION,
1827
+ attachRef,
1828
+ buildCanonical,
1568
1829
  buildError,
1569
- buildMessage,
1830
+ clearRef,
1570
1831
  computeBackoff,
1832
+ expectedProofLength,
1833
+ normalizeBaseUrl,
1571
1834
  runWithRetry,
1572
1835
  signRequest
1573
1836
  });