@proof-labs/trading-sdk 7.2.0 → 8.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.
Files changed (65) hide show
  1. package/README.md +70 -24
  2. package/dist/account-recovery.d.ts +117 -0
  3. package/dist/account-recovery.d.ts.map +1 -0
  4. package/dist/account-recovery.js +330 -0
  5. package/dist/account-recovery.js.map +1 -0
  6. package/dist/bridge.d.ts +5 -8
  7. package/dist/bridge.d.ts.map +1 -1
  8. package/dist/bridge.js +5 -8
  9. package/dist/bridge.js.map +1 -1
  10. package/dist/client.d.ts +59 -55
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js +252 -223
  13. package/dist/client.js.map +1 -1
  14. package/dist/codec-adapter.d.ts.map +1 -1
  15. package/dist/codec-adapter.js +13 -0
  16. package/dist/codec-adapter.js.map +1 -1
  17. package/dist/errors.d.ts +24 -0
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/errors.js +77 -0
  20. package/dist/errors.js.map +1 -1
  21. package/dist/feed-types.d.ts +22 -0
  22. package/dist/feed-types.d.ts.map +1 -1
  23. package/dist/feed.d.ts +52 -0
  24. package/dist/feed.d.ts.map +1 -1
  25. package/dist/feed.js +342 -24
  26. package/dist/feed.js.map +1 -1
  27. package/dist/financial-state.d.ts +2 -1
  28. package/dist/financial-state.d.ts.map +1 -1
  29. package/dist/financial-state.js +19 -9
  30. package/dist/financial-state.js.map +1 -1
  31. package/dist/governance-query.d.ts.map +1 -1
  32. package/dist/governance-query.js +69 -0
  33. package/dist/governance-query.js.map +1 -1
  34. package/dist/http-transport.d.ts +56 -0
  35. package/dist/http-transport.d.ts.map +1 -0
  36. package/dist/http-transport.js +78 -0
  37. package/dist/http-transport.js.map +1 -0
  38. package/dist/index.d.ts +7 -3
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +5 -2
  41. package/dist/index.js.map +1 -1
  42. package/dist/insurance-funding.d.ts +6 -0
  43. package/dist/insurance-funding.d.ts.map +1 -0
  44. package/dist/insurance-funding.js +54 -0
  45. package/dist/insurance-funding.js.map +1 -0
  46. package/dist/liquidation-config.d.ts +11 -0
  47. package/dist/liquidation-config.d.ts.map +1 -0
  48. package/dist/liquidation-config.js +54 -0
  49. package/dist/liquidation-config.js.map +1 -0
  50. package/dist/liquidation-events.d.ts +135 -0
  51. package/dist/liquidation-events.d.ts.map +1 -0
  52. package/dist/liquidation-events.js +273 -0
  53. package/dist/liquidation-events.js.map +1 -0
  54. package/dist/market-snapshot.d.ts +2 -1
  55. package/dist/market-snapshot.d.ts.map +1 -1
  56. package/dist/market-snapshot.js +4 -2
  57. package/dist/market-snapshot.js.map +1 -1
  58. package/dist/types.d.ts +88 -13
  59. package/dist/types.d.ts.map +1 -1
  60. package/dist/wasm/proof_trading_sdk_wasm.d.ts +1 -1
  61. package/dist/wasm/proof_trading_sdk_wasm.js +1 -1
  62. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm +0 -0
  63. package/dist/wasm-loader.d.ts +3 -3
  64. package/dist/wasm-loader.d.ts.map +1 -1
  65. package/package.json +1 -1
package/dist/client.js CHANGED
@@ -2,7 +2,8 @@ import { GatewayFeed, } from "./feed.js";
2
2
  import { portfolioHistorySearchParams, decodePortfolioHistoryPage, } from "./portfolio-history.js";
3
3
  import { queryOraclePriceHistoryPage, } from "./oracle-price-history.js";
4
4
  import { GatewayReads } from "./gateway-reads.js";
5
- import { GatewayHttpError } from "./errors.js";
5
+ import { recoveringAccountHandler, } from "./account-recovery.js";
6
+ import { FeedSubscriptionError, GatewayHttpError } from "./errors.js";
6
7
  import { decodeCashFlowEvents, decodeHistoryPositionsPage, historyOwner, historySearchParams, } from "./history.js";
7
8
  import { toWasmFields } from "./codec-adapter.js";
8
9
  import { signAndEncode, encodePayloadBytes, encodeSignedTx, rejectFloats, } from "./codec.js";
@@ -14,6 +15,7 @@ import { getPublicKey, pubkeyToOwner, ownerToHex, bytesToHex, sign, verify, sign
14
15
  import { decodeAdminSignerRegistryInfo, decodeAuthoritiesSnapshot, decodeNodeVersion, decodeUpgradesInfo, decodeEventInfo, decodeProposalPage, } from "./governance-query.js";
15
16
  import { Decoder } from "@msgpack/msgpack";
16
17
  import { readMarketsSnapshot } from "./market-snapshot.js";
18
+ import { defaultExchangeHttpTransport, exchangeHttpPriorityForAction, gatewayReadContext, readContext, surfaceFor, } from "./http-transport.js";
17
19
  import { yesOrder } from "./binary.js";
18
20
  import { Side } from "./types.js";
19
21
  import { sha256 } from "@noble/hashes/sha2.js";
@@ -30,8 +32,12 @@ import { decodeOraclePermissions, validateOraclePermissionMarket, } from "./orac
30
32
  * (raw `signAndEncode` callers, gateway-side helpers) that build wire
31
33
  * bytes without going through a client instance.
32
34
  */
33
- export async function fetchChainId(rpcUrl) {
34
- const res = await fetch(`${rpcUrl}/status`);
35
+ export async function fetchChainId(rpcUrl, httpTransport = defaultExchangeHttpTransport) {
36
+ const res = await httpTransport(`${rpcUrl}/status`, undefined, {
37
+ purpose: "chain_id",
38
+ priority: "critical",
39
+ surface: "status_chain_id",
40
+ });
35
41
  if (!res.ok)
36
42
  throw new Error(`/status returned HTTP ${res.status}`);
37
43
  const json = (await res.json());
@@ -47,6 +53,7 @@ export class ExchangeClient {
47
53
  gatewayUrl;
48
54
  useGateway;
49
55
  apiKey;
56
+ httpTransport;
50
57
  wsUrl;
51
58
  /**
52
59
  * 32-byte chain_id binding for v3 signatures (audit B4). `null` until
@@ -64,13 +71,17 @@ export class ExchangeClient {
64
71
  externalSigner = null;
65
72
  signerRevision = 0;
66
73
  gatewayFeed = null;
74
+ /** Dedicated feeds behind pending `orderbookSnapshot` calls, so
75
+ * `disconnect()` closes them too. */
76
+ snapshotFeeds = new Set();
77
+ /** Reconnect recoveries of live `subscribeAccount` calls, closed with the feed. */
78
+ accountRecoveries = new Set();
67
79
  publicKey = null;
68
80
  address = null;
69
81
  addressHex = null;
70
82
  lastTimestampNonce = 0n;
71
83
  /** Unsubscribe handles for every open WebSocket stream, so `disconnect()`
72
84
  * can tear them all down at once. */
73
- activeStreams = new Set();
74
85
  /**
75
86
  * In-flight DeliverTx verification promises spawned by submitTx. Awaiting
76
87
  * this set lets callers serialize against block inclusion when they need to;
@@ -104,10 +115,11 @@ export class ExchangeClient {
104
115
  this.rpcUrl = stripTrailingSlash(opts.rpcUrl ?? deriveNodeUrl(this.gatewayUrl, "26657"));
105
116
  this.apiUrl = stripTrailingSlash(opts.apiUrl ?? deriveNodeUrl(this.gatewayUrl, "8080"));
106
117
  this.apiKey = opts.apiKey ?? null;
107
- // WebSocket base URL (no path). Per-stream methods append the channel
108
- // path (`/account-events`, `/orderbook-deltas`). Mirrors the Python SDK,
109
- // which derives the WS base by swapping the gateway URL's scheme. Local
110
- // stacks whose WS listener is on a different port must pass `wsUrl`.
118
+ this.httpTransport = opts.httpTransport ?? defaultExchangeHttpTransport;
119
+ // WebSocket base URL (no path); the feed appends `/ws`. Mirrors the
120
+ // Python SDK, which derives the WS base by swapping the gateway URL's
121
+ // scheme. Local stacks whose WS listener is on a different port must pass
122
+ // `wsUrl`.
111
123
  this.wsUrl = stripTrailingSlash(opts.wsUrl ??
112
124
  (this.useGateway ? this.gatewayUrl : this.rpcUrl).replace(/^http/, "ws"));
113
125
  // Bind chainId eagerly when supplied, else leave null. On the direct
@@ -174,7 +186,7 @@ export class ExchangeClient {
174
186
  try {
175
187
  // `fetchChainId` appends `/status`, so the gateway path resolves from
176
188
  // `${gatewayUrl}/v1/status` and the direct path from `${rpcUrl}/status`.
177
- const bound = await fetchChainId(this.chainBase);
189
+ const bound = await fetchChainId(this.chainBase, this.httpTransport);
178
190
  this.chainId = bound;
179
191
  return bound;
180
192
  }
@@ -276,7 +288,8 @@ export class ExchangeClient {
276
288
  }
277
289
  return encodeSignedTx(snapshot, seq, signer.publicKey, signature);
278
290
  }
279
- /** Sign existing gateway account-events auth bytes; call again per reconnect.
291
+ /** Sign the gateway's account-stream auth bytes for an `accountEvents`
292
+ * subscription on `/ws`; call again per reconnect.
280
293
  * Direct owner keys only; no delegated-owner authorization is inferred.
281
294
  */
282
295
  async accountAuth(owner = this.addressHex ?? "", afterId = 0n) {
@@ -338,7 +351,8 @@ export class ExchangeClient {
338
351
  const hex = addressHex ?? this.addressHex;
339
352
  if (!hex)
340
353
  throw new Error("No address available");
341
- const res = await fetch(`${this.readBaseUrl}/v1/account/${hex}/recent-nonces`);
354
+ const url = `${this.readBaseUrl}/v1/account/${hex}/recent-nonces`;
355
+ const res = await this.httpTransport(url, undefined, readContext(url, "account"));
342
356
  const json = await res.json();
343
357
  if (json.error)
344
358
  throw new Error(json.error);
@@ -402,7 +416,7 @@ export class ExchangeClient {
402
416
  // the tx but could not report the outcome in time, so the SDK reconciles by
403
417
  // hash on the caller's behalf, exactly as before.
404
418
  if (this.autoVerifyDelivery && r.hash && !this.isFinalResult(r)) {
405
- this.spawnDeliveryVerifier(r.hash);
419
+ this.spawnDeliveryVerifier(r.hash, action);
406
420
  }
407
421
  return r;
408
422
  }
@@ -440,10 +454,10 @@ export class ExchangeClient {
440
454
  * the internal `useGateway: false` opt-out. Both submit identical bytes.
441
455
  * Shared by `submitSignedTx` and `submitSignedTxCommit`.
442
456
  */
443
- async broadcastSignedBytes(txBytes) {
457
+ async broadcastSignedBytes(txBytes, action) {
444
458
  return this.useGateway
445
- ? this.submitViaGateway(txBytes)
446
- : this.submitViaCometBFT(txBytes);
459
+ ? this.submitViaGateway(txBytes, action)
460
+ : this.submitViaCometBFT(txBytes, action);
447
461
  }
448
462
  /**
449
463
  * Internal: sign + submit with a fresh timestamp nonce. Does NOT spawn a
@@ -458,7 +472,7 @@ export class ExchangeClient {
458
472
  * Both paths submit identical signed wire bytes.
459
473
  */
460
474
  async broadcastSigned(action) {
461
- return this.broadcastSignedBytes(await this.signTx(action));
475
+ return this.broadcastSignedBytes(await this.signTx(action), action);
462
476
  }
463
477
  /**
464
478
  * Submit signed wire bytes via the public API gateway
@@ -480,7 +494,7 @@ export class ExchangeClient {
480
494
  * For transport-level failures (rate limit, auth, etc.) we synthesize a code
481
495
  * from the HTTP status.
482
496
  */
483
- async submitViaGateway(txBytes) {
497
+ async submitViaGateway(txBytes, action) {
484
498
  const txHash = computeCometTxHash(txBytes);
485
499
  const headers = {
486
500
  "Content-Type": "application/json",
@@ -491,10 +505,11 @@ export class ExchangeClient {
491
505
  let res;
492
506
  let gatewayBody;
493
507
  try {
494
- res = await fetch(`${this.gatewayUrl}/exchange`, {
495
- method: "POST",
496
- headers,
497
- body,
508
+ res = await this.httpTransport(`${this.gatewayUrl}/exchange`, { method: "POST", headers, body }, {
509
+ purpose: "submit",
510
+ priority: action ? exchangeHttpPriorityForAction(action) : "critical",
511
+ surface: "gateway_exchange",
512
+ action,
498
513
  });
499
514
  gatewayBody = await readGatewayBody(res);
500
515
  }
@@ -633,9 +648,9 @@ export class ExchangeClient {
633
648
  * when `useGateway` is false (internal-tools opt-out). Bypasses
634
649
  * gateway auth/rate-limit and goes directly to CometBFT.
635
650
  */
636
- async submitViaCometBFT(txBytes) {
651
+ async submitViaCometBFT(txBytes, action) {
637
652
  const b64 = toBase64(txBytes);
638
- const res = await fetch(this.rpcUrl, {
653
+ const res = await this.httpTransport(this.rpcUrl, {
639
654
  method: "POST",
640
655
  headers: { "Content-Type": "application/json" },
641
656
  body: JSON.stringify({
@@ -644,6 +659,11 @@ export class ExchangeClient {
644
659
  method: "broadcast_tx_sync",
645
660
  params: { tx: b64 },
646
661
  }),
662
+ }, {
663
+ purpose: "submit",
664
+ priority: action ? exchangeHttpPriorityForAction(action) : "critical",
665
+ surface: "rpc_broadcast_tx_sync",
666
+ action,
647
667
  });
648
668
  const json = await res.json();
649
669
  if (json.error) {
@@ -663,11 +683,11 @@ export class ExchangeClient {
663
683
  * block rather than via a chained .finally() so there's no microtask race
664
684
  * between p settling and the awaitPendingVerifies() loop seeing size==0.
665
685
  */
666
- spawnDeliveryVerifier(txHash) {
686
+ spawnDeliveryVerifier(txHash, action) {
667
687
  let self;
668
688
  const verify = async () => {
669
689
  try {
670
- const result = await this.waitForDelivery(txTimeout(txHash, "awaiting delivery"), { timeoutMs: 5_000 });
690
+ const result = await this.pollDelivery(txTimeout(txHash, "awaiting delivery"), { timeoutMs: 5_000 }, action);
671
691
  if (result.outcome !== "timeout")
672
692
  this.deliveryResults.push(result);
673
693
  }
@@ -722,7 +742,7 @@ export class ExchangeClient {
722
742
  // path so we don't double-spawn a background verifier — we're going to
723
743
  // do our own synchronous verification below.
724
744
  const sync = await this.broadcastSigned(action);
725
- return this.awaitCommit(sync);
745
+ return this.awaitCommit(sync, action);
726
746
  }
727
747
  /**
728
748
  * Submit **externally signed** wire bytes and wait for block inclusion —
@@ -746,13 +766,19 @@ export class ExchangeClient {
746
766
  * final chain verdict, polling `/tx?hash=` only when the outcome is still
747
767
  * unknown.
748
768
  */
749
- async awaitCommit(sync) {
750
- return this.waitForDelivery(sync);
769
+ async awaitCommit(sync, action) {
770
+ return this.pollDelivery(sync, {}, action);
751
771
  }
752
772
  /** Per-submission finality. Timeout/cancellation retains the hash as unknown.
753
773
  * Never resubmits writes. Use setUnsafeFastSubmit(true) to avoid a second poller.
754
774
  */
755
775
  async waitForDelivery(sync, opts = {}) {
776
+ return this.pollDelivery(sync, opts);
777
+ }
778
+ /** `waitForDelivery`, with the originating action (when the client signed
779
+ * it) passed to the transport so its confirmation keeps the action's
780
+ * priority. */
781
+ async pollDelivery(sync, opts, action) {
756
782
  if (this.isFinalResult(sync))
757
783
  return sync;
758
784
  if (!sync.hash)
@@ -770,8 +796,14 @@ export class ExchangeClient {
770
796
  break;
771
797
  const request = readDeadline(Math.ceil(remaining), opts.signal);
772
798
  try {
773
- const res = await fetch(this.txStatusUrl(sync.hash), {
774
- signal: request.signal,
799
+ const url = this.txStatusUrl(sync.hash);
800
+ const res = await this.httpTransport(url, { signal: request.signal }, {
801
+ purpose: "confirmation",
802
+ priority: action
803
+ ? exchangeHttpPriorityForAction(action)
804
+ : "critical",
805
+ surface: surfaceFor(url),
806
+ action,
775
807
  });
776
808
  if (!res.ok)
777
809
  continue;
@@ -954,8 +986,16 @@ export class ExchangeClient {
954
986
  */
955
987
  async queryOwnerScoped(info, nodePath) {
956
988
  return this.useGateway
957
- ? postInfoJson(this.gatewayUrl, info)
958
- : fetchApiJson(`${this.apiUrl}${nodePath}`);
989
+ ? postInfoJson(this.httpTransport, this.gatewayUrl, info, {
990
+ purpose: "account",
991
+ priority: "urgent",
992
+ surface: `api_info_${String(info.type)}`,
993
+ })
994
+ : this.apiJson(`${this.apiUrl}${nodePath}`, "account");
995
+ }
996
+ /** `fetchApiJson` through this client's transport. */
997
+ apiJson(url, purpose = "query") {
998
+ return fetchApiJson(this.httpTransport, url, readContext(url, purpose));
959
999
  }
960
1000
  /** Decode gateway MessagePack bytes after the authoritative strict preflight
961
1001
  * (`rejectFloats`). Reads now route through the WASM core, so this
@@ -971,7 +1011,7 @@ export class ExchangeClient {
971
1011
  return value;
972
1012
  }
973
1013
  async queryOrderbook(market) {
974
- const json = await fetchApiJson(`${this.readBaseUrl}/v1/orderbook/${market}`);
1014
+ const json = await this.apiJson(`${this.readBaseUrl}/v1/orderbook/${market}`);
975
1015
  const bytes = fromBase64(json.data);
976
1016
  const raw = (await this.strictDecode(bytes));
977
1017
  const parseLevel = (arr) => ({
@@ -990,11 +1030,11 @@ export class ExchangeClient {
990
1030
  if (!this.inventoryChainId) {
991
1031
  throw new Error("market snapshot requires an explicit pinned chainId");
992
1032
  }
993
- return readMarketsSnapshot(this.gatewayUrl, this.inventoryChainId);
1033
+ return readMarketsSnapshot(this.gatewayUrl, this.inventoryChainId, this.httpTransport);
994
1034
  }
995
1035
  /** List all registered market configs. */
996
1036
  async queryMarkets() {
997
- const json = await fetchApiJson(`${this.readBaseUrl}/v1/markets`);
1037
+ const json = await this.apiJson(`${this.readBaseUrl}/v1/markets`);
998
1038
  const bytes = fromBase64(json.data);
999
1039
  const raw = (await this.strictDecode(bytes));
1000
1040
  return raw.map((m) => decodeMarketConfig(m));
@@ -1005,7 +1045,7 @@ export class ExchangeClient {
1005
1045
  * governance reads: a missing envelope or malformed row is a refusal.
1006
1046
  * Decoder pinned to the engine golden vector in governance-query.test.ts. */
1007
1047
  async queryEvents() {
1008
- const json = await fetchApiJson(`${this.readBaseUrl}/v1/events`);
1048
+ const json = await this.apiJson(`${this.readBaseUrl}/v1/events`);
1009
1049
  if (typeof json.data !== "string") {
1010
1050
  throw new Error("governance decode: events response has no encoded-data envelope");
1011
1051
  }
@@ -1020,7 +1060,8 @@ export class ExchangeClient {
1020
1060
  * here to map 404 -> null while still throwing on real transport / decode
1021
1061
  * failures. */
1022
1062
  async queryEvent(eventId) {
1023
- const res = await fetch(`${this.readBaseUrl}/v1/event/${eventId}`);
1063
+ const url = `${this.readBaseUrl}/v1/event/${eventId}`;
1064
+ const res = await this.httpTransport(url, undefined, readContext(url, "query"));
1024
1065
  if (res.status === 404)
1025
1066
  return null;
1026
1067
  const json = (await res.json());
@@ -1046,7 +1087,7 @@ export class ExchangeClient {
1046
1087
  throw new Error("trigger owner must be a 40-character hex address");
1047
1088
  }
1048
1089
  const path = `/v1/triggers/${hex.toLowerCase()}`;
1049
- const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
1090
+ const json = await this.apiJson(`${this.readBaseUrl}${path}`, "account");
1050
1091
  const bytes = fromBase64(requireEncodedData(json, path));
1051
1092
  return decodePositionTriggerInfos(await this.strictDecode(bytes));
1052
1093
  }
@@ -1054,7 +1095,7 @@ export class ExchangeClient {
1054
1095
  * markets are disabled; callers must never synthesize a default policy. */
1055
1096
  async queryTriggerMarketConfigs() {
1056
1097
  const path = "/v1/triggers/markets";
1057
- const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
1098
+ const json = await this.apiJson(`${this.readBaseUrl}${path}`);
1058
1099
  const bytes = fromBase64(requireEncodedData(json, path));
1059
1100
  return decodeTriggerMarketConfigInfos(await this.strictDecode(bytes));
1060
1101
  }
@@ -1069,7 +1110,8 @@ export class ExchangeClient {
1069
1110
  * for the 404 response. It will be removed in the next major version. */
1070
1111
  async queryTriggerStatus() {
1071
1112
  const path = "/v1/triggers/status";
1072
- const res = await fetch(`${this.readBaseUrl}${path}`);
1113
+ const url = `${this.readBaseUrl}${path}`;
1114
+ const res = await this.httpTransport(url, undefined, readContext(url, "query"));
1073
1115
  const text = await res.text();
1074
1116
  if (!res.ok) {
1075
1117
  let message = `HTTP ${res.status}`;
@@ -1089,7 +1131,7 @@ export class ExchangeClient {
1089
1131
  async queryOraclePermissions(market) {
1090
1132
  validateOraclePermissionMarket(market);
1091
1133
  const path = `/v1/oracle/permissions/${market}`;
1092
- const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
1134
+ const json = await this.apiJson(`${this.readBaseUrl}${path}`);
1093
1135
  const bytes = fromBase64(requireEncodedData(json, path));
1094
1136
  return decodeOraclePermissions(await this.strictDecode(bytes), market);
1095
1137
  }
@@ -1106,7 +1148,7 @@ export class ExchangeClient {
1106
1148
  const canonicalOwner = hex.toLowerCase();
1107
1149
  const params = positionTriggerHistorySearchParams(filters);
1108
1150
  const qs = params.toString();
1109
- const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/triggers/${canonicalOwner}${qs ? `?${qs}` : ""}`);
1151
+ const json = await this.apiJson(`${this.gatewayUrl}/v1/history/triggers/${canonicalOwner}${qs ? `?${qs}` : ""}`, "account");
1110
1152
  return decodePositionTriggerHistoryPage(json, canonicalOwner, filters.market);
1111
1153
  }
1112
1154
  /** Shared market-level deferred/resumed trigger transitions. These are not
@@ -1115,7 +1157,7 @@ export class ExchangeClient {
1115
1157
  validateTriggerHistoryMarket(market);
1116
1158
  const params = triggerMarketHistorySearchParams(filters);
1117
1159
  const qs = params.toString();
1118
- const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/trigger-markets/${market}${qs ? `?${qs}` : ""}`);
1160
+ const json = await this.apiJson(`${this.gatewayUrl}/v1/history/trigger-markets/${market}${qs ? `?${qs}` : ""}`);
1119
1161
  return decodeTriggerMarketHistoryPage(json, market);
1120
1162
  }
1121
1163
  /**
@@ -1128,7 +1170,7 @@ export class ExchangeClient {
1128
1170
  * differently.
1129
1171
  */
1130
1172
  async queryAdminSignerRegistry() {
1131
- const json = await fetchApiJson(`${this.readBaseUrl}/v1/admin/signer-registry`);
1173
+ const json = await this.apiJson(`${this.readBaseUrl}/v1/admin/signer-registry`);
1132
1174
  const bytes = fromBase64(requireEncodedData(json, "/v1/admin/signer-registry"));
1133
1175
  return decodeAdminSignerRegistryInfo(await this.strictDecode(bytes));
1134
1176
  }
@@ -1140,7 +1182,7 @@ export class ExchangeClient {
1140
1182
  * empty set.
1141
1183
  */
1142
1184
  async queryAuthorities() {
1143
- const json = await fetchApiJson(`${this.readBaseUrl}/v1/admin/authorities`);
1185
+ const json = await this.apiJson(`${this.readBaseUrl}/v1/admin/authorities`);
1144
1186
  const bytes = fromBase64(requireEncodedData(json, "/v1/admin/authorities"));
1145
1187
  return decodeAuthoritiesSnapshot(await this.strictDecode(bytes));
1146
1188
  }
@@ -1149,7 +1191,7 @@ export class ExchangeClient {
1149
1191
  * ledger via the gateway proxy (`GET /v1/upgrades`).
1150
1192
  */
1151
1193
  async queryUpgrades() {
1152
- const json = await fetchApiJson(`${this.readBaseUrl}/v1/upgrades`);
1194
+ const json = await this.apiJson(`${this.readBaseUrl}/v1/upgrades`);
1153
1195
  const bytes = fromBase64(requireEncodedData(json, "/v1/upgrades"));
1154
1196
  return decodeUpgradesInfo(await this.strictDecode(bytes));
1155
1197
  }
@@ -1159,7 +1201,7 @@ export class ExchangeClient {
1159
1201
  * whichever node served the request.
1160
1202
  */
1161
1203
  async queryNodeVersion() {
1162
- const json = await fetchApiJson(`${this.readBaseUrl}/v1/version`);
1204
+ const json = await this.apiJson(`${this.readBaseUrl}/v1/version`);
1163
1205
  return decodeNodeVersion(json);
1164
1206
  }
1165
1207
  /**
@@ -1183,7 +1225,7 @@ export class ExchangeClient {
1183
1225
  if (opts?.limit != null)
1184
1226
  params.set("limit", String(opts.limit));
1185
1227
  const qs = params.toString();
1186
- const json = await fetchApiJson(`${this.readBaseUrl}/v1/proposals${qs ? `?${qs}` : ""}`);
1228
+ const json = await this.apiJson(`${this.readBaseUrl}/v1/proposals${qs ? `?${qs}` : ""}`);
1187
1229
  const bytes = fromBase64(requireEncodedData(json, "/v1/proposals"));
1188
1230
  return decodeProposalPage(await this.strictDecode(bytes));
1189
1231
  }
@@ -1238,7 +1280,7 @@ export class ExchangeClient {
1238
1280
  }
1239
1281
  /** Raw finalized ledger facts, independent of oracle valuation. Not authorization. */
1240
1282
  async queryFinancialState(selection) {
1241
- return fetchFinancialState(this.gatewayUrl, selection);
1283
+ return fetchFinancialState(this.gatewayUrl, selection, this.httpTransport);
1242
1284
  }
1243
1285
  /** Raw finalized ledger facts, independent of oracle valuation. Not authorization. */
1244
1286
  async queryAccountState(addressHex) {
@@ -1248,7 +1290,7 @@ export class ExchangeClient {
1248
1290
  }
1249
1291
  const owner = hex.toLowerCase();
1250
1292
  const path = `/v1/account/${owner}/state`;
1251
- const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
1293
+ const json = await this.apiJson(`${this.readBaseUrl}${path}`, "account");
1252
1294
  return decodeAccountState(await this.strictDecode(fromBase64(requireEncodedData(json, path))), owner);
1253
1295
  }
1254
1296
  async queryAccount(addressHex) {
@@ -1342,14 +1384,16 @@ export class ExchangeClient {
1342
1384
  return acct ? acct.equity : null;
1343
1385
  }
1344
1386
  async queryHealth() {
1345
- const res = await fetch(`${this.readBaseUrl}/v1/health`);
1387
+ const url = `${this.readBaseUrl}/v1/health`;
1388
+ const res = await this.httpTransport(url, undefined, readContext(url, "query"));
1346
1389
  return res.json();
1347
1390
  }
1348
1391
  /** Fetch the auto-deleveraging queue for a market — profitable positions
1349
1392
  * ranked by `adlScore` desc (highest first). Empty array if the market has
1350
1393
  * no profitable positions. Routes through the gateway's `/v1/adl/queue`. */
1351
1394
  async queryAdlQueue(market) {
1352
- const res = await fetch(`${this.readBaseUrl}/v1/adl/queue/${market}`);
1395
+ const url = `${this.readBaseUrl}/v1/adl/queue/${market}`;
1396
+ const res = await this.httpTransport(url, undefined, readContext(url, "query"));
1353
1397
  const json = await res.json();
1354
1398
  if (json.error)
1355
1399
  return [];
@@ -1370,7 +1414,8 @@ export class ExchangeClient {
1370
1414
  * and top-of-book blobs). Returns `null` if the market is unknown. Routes
1371
1415
  * through the gateway's `/v1/ticker`. */
1372
1416
  async queryTicker(market) {
1373
- const res = await fetch(`${this.readBaseUrl}/v1/ticker/${market}`);
1417
+ const url = `${this.readBaseUrl}/v1/ticker/${market}`;
1418
+ const res = await this.httpTransport(url, undefined, readContext(url, "query"));
1374
1419
  if (!res.ok)
1375
1420
  return null;
1376
1421
  const row = (await res.json());
@@ -1420,7 +1465,7 @@ export class ExchangeClient {
1420
1465
  const pages = await Promise.all(kinds.map(async (kind) => {
1421
1466
  const query = new URLSearchParams(params);
1422
1467
  query.set("event_type", kind);
1423
- const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/account-events?${query}`);
1468
+ const json = await this.apiJson(`${this.gatewayUrl}/v1/history/account-events?${query}`, "account");
1424
1469
  return decodeCashFlowEvents(json, owner, kind);
1425
1470
  }));
1426
1471
  return pages
@@ -1454,7 +1499,7 @@ export class ExchangeClient {
1454
1499
  params.set("limit", String(opts.limit));
1455
1500
  const qs = params.toString();
1456
1501
  const url = `${this.readBaseUrl}/v1/history/resolutions/${hex}${qs ? `?${qs}` : ""}`;
1457
- const json = await fetchApiArray(url);
1502
+ const json = await fetchApiArray(this.httpTransport, url, readContext(url, "account"));
1458
1503
  return json.map((row) => ({
1459
1504
  kind: row.kind,
1460
1505
  eventId: String(row.event_id ?? ""),
@@ -1476,7 +1521,8 @@ export class ExchangeClient {
1476
1521
  * Uses this client's gateway; never targets a node, even in internal node mode.
1477
1522
  */
1478
1523
  reads(opts = {}) {
1479
- return new GatewayReads(this.gatewayUrl, opts.fetch ?? ((url, init) => fetch(url, init)));
1524
+ return new GatewayReads(this.gatewayUrl, opts.fetch ??
1525
+ ((url, init) => this.httpTransport(url, init, gatewayReadContext(url, init))));
1480
1526
  }
1481
1527
  /** Gateway/indexer portfolio page, including in internal node mode.
1482
1528
  * Keep bounds fixed across opaque cursors. */
@@ -1486,7 +1532,8 @@ export class ExchangeClient {
1486
1532
  throw new Error("Invalid portfolio owner");
1487
1533
  const params = portfolioHistorySearchParams(opts);
1488
1534
  opts.signal?.throwIfAborted();
1489
- const res = await fetch(`${this.gatewayUrl}/v1/history/portfolio/${canonicalOwner}?${params}`, { signal: opts.signal });
1535
+ const url = `${this.gatewayUrl}/v1/history/portfolio/${canonicalOwner}?${params}`;
1536
+ const res = await this.httpTransport(url, { signal: opts.signal }, readContext(url, "account"));
1490
1537
  if (!res.ok)
1491
1538
  throw new GatewayHttpError(res.status, res);
1492
1539
  const page = await res.json();
@@ -1496,7 +1543,14 @@ export class ExchangeClient {
1496
1543
  /** One newest-first gateway page of a market's indexed `price_updated`
1497
1544
  * history. Keep market and bounds fixed across opaque cursors. */
1498
1545
  async queryOraclePriceHistory(market, options) {
1499
- return queryOraclePriceHistoryPage(this.gatewayUrl, market, options);
1546
+ return queryOraclePriceHistoryPage(this.gatewayUrl, market, {
1547
+ ...options,
1548
+ fetch: options.fetch ??
1549
+ ((input, init) => {
1550
+ const url = String(input instanceof Request ? input.url : input);
1551
+ return this.httpTransport(url, init, readContext(url, "query"));
1552
+ }),
1553
+ });
1500
1554
  }
1501
1555
  /** Compatibility array of position snapshots. Absent close fields are empty
1502
1556
  * strings and timestamps are milliseconds. Use queryHistoryPositionsPage for
@@ -1529,7 +1583,7 @@ export class ExchangeClient {
1529
1583
  params.set("market", String(opts.market));
1530
1584
  }
1531
1585
  const query = params.toString();
1532
- const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/positions/${owner}${query ? `?${query}` : ""}`);
1586
+ const json = await this.apiJson(`${this.gatewayUrl}/v1/history/positions/${owner}${query ? `?${query}` : ""}`, "account");
1533
1587
  return decodeHistoryPositionsPage(json, owner, opts.market);
1534
1588
  }
1535
1589
  /**
@@ -1558,7 +1612,7 @@ export class ExchangeClient {
1558
1612
  }
1559
1613
  const qs = params.toString();
1560
1614
  const url = `${this.readBaseUrl}/v1/history/fills/${hex}${qs ? `?${qs}` : ""}`;
1561
- const res = await fetch(url);
1615
+ const res = await this.httpTransport(url, undefined, readContext(url, "account"));
1562
1616
  const json = (await res.json());
1563
1617
  const body = (json ?? {});
1564
1618
  if (!res.ok || "error" in body) {
@@ -1589,7 +1643,8 @@ export class ExchangeClient {
1589
1643
  // Chain status & block queries (via the gateway's /v1/* by default)
1590
1644
  // -----------------------------------------------------------------------
1591
1645
  async status() {
1592
- const res = await fetch(`${this.chainBase}/status`);
1646
+ const url = `${this.chainBase}/status`;
1647
+ const res = await this.httpTransport(url, undefined, readContext(url, "query"));
1593
1648
  const json = await res.json();
1594
1649
  const info = json.result.sync_info;
1595
1650
  return {
@@ -1599,189 +1654,158 @@ export class ExchangeClient {
1599
1654
  }
1600
1655
  async getBlock(height) {
1601
1656
  const params = height != null ? `?height=${height}` : "";
1602
- const res = await fetch(`${this.chainBase}/block${params}`);
1657
+ const url = `${this.chainBase}/block${params}`;
1658
+ const res = await this.httpTransport(url, undefined, readContext(url, "query"));
1603
1659
  const json = await res.json();
1604
1660
  if (json.error)
1605
1661
  throw new Error(json.error.message ?? JSON.stringify(json.error));
1606
1662
  return json.result;
1607
1663
  }
1608
1664
  async getBlockResults(height) {
1609
- const res = await fetch(`${this.chainBase}/block_results?height=${height}`);
1665
+ const url = `${this.chainBase}/block_results?height=${height}`;
1666
+ const res = await this.httpTransport(url, undefined, readContext(url, "query"));
1610
1667
  const json = await res.json();
1611
1668
  if (json.error)
1612
1669
  throw new Error(json.error.message ?? JSON.stringify(json.error));
1613
1670
  return json.result;
1614
1671
  }
1615
1672
  // -----------------------------------------------------------------------
1616
- // WebSocket streams (gateway-native; mirror the Python SDK)
1673
+ // WebSocket streams (the gateway's multiplexed /ws feed)
1617
1674
  // -----------------------------------------------------------------------
1618
1675
  /**
1619
- * Subscribe to the account-events stream (`/account-events`). Mirrors the
1620
- * Python SDK's `AccountEventStream`: the gateway sends an initial snapshot
1621
- * frame followed by incremental event frames. The SDK tracks the highest
1622
- * `event_id` seen and replays from it via `after_id` on reconnect, so no
1623
- * events are dropped across a disconnect.
1624
- *
1625
- * Auth: account streams require auth only when the gateway runs with
1626
- * `--api-key`. A browser `WebSocket` cannot send the `X-Api-Key` header, so
1627
- * the SDK uses the gateway's signed-query auth instead — when a private key or external signer
1628
- * is connected it signs the `ProofExchange-account-events-v1`
1629
- * message and appends `public_key` / `signature` / `timestamp_ms`. Against
1630
- * an unauthenticated gateway (e.g. devnet) the owner alone is enough.
1631
- *
1632
- * Returns an unsubscribe function; `disconnect()` closes all streams.
1633
- */
1634
- subscribeAccountEvents(owner, onEvent, opts = {}) {
1635
- const ownerHex = (owner instanceof Uint8Array ? bytesToHex(owner) : owner.replace(/^0x/, "")).toLowerCase();
1636
- // Tracked across reconnects for gap recovery. Signed into the auth
1637
- // message too, so the value we send and the value we sign always match.
1638
- let afterId = 0n;
1639
- const buildUrl = async () => {
1640
- const params = new URLSearchParams({ owner: ownerHex });
1641
- if (afterId > 0n)
1642
- params.set("after_id", afterId.toString());
1643
- if (opts.auth !== false && (this.privateKey || this.externalSigner)) {
1644
- const auth = await this.accountAuth(ownerHex, afterId);
1645
- for (const [key, value] of Object.entries(auth))
1646
- params.set(key, String(value));
1647
- }
1648
- return `${this.wsUrl}/account-events?${params.toString()}`;
1649
- };
1650
- return this.openStream(buildUrl, (frame) => {
1651
- const id = frame.event_id;
1652
- if (typeof id === "number" || typeof id === "bigint") {
1653
- const big = BigInt(id);
1654
- if (big > afterId)
1655
- afterId = big;
1656
- }
1657
- onEvent(frame);
1658
- }, opts);
1659
- }
1660
- /**
1661
- * Subscribe to the L2 orderbook delta stream for a market
1662
- * (`/orderbook-deltas`). Mirrors the Python SDK's `OrderbookDeltaStream`:
1663
- * the first frame is a full `l2Book` snapshot, then incremental deltas.
1664
- * Returns an unsubscribe function.
1676
+ * One-shot orderbook snapshot from the gateway's `/ws` feed, read over a
1677
+ * connection of its own: it never answers from a book an existing
1678
+ * `subscribeOrderbook` built, so a stalled shared socket cannot serve stale
1679
+ * prices. Resolves the first `snapshot` frame and closes the connection.
1680
+ * Rejects with {@link FeedSubscriptionError} when the gateway refuses the
1681
+ * subscription, or when no snapshot arrives within `timeoutMs`.
1665
1682
  */
1666
- subscribeOrderbookDeltas(market, onMessage, opts = {}) {
1667
- return this.openStream(async () => `${this.wsUrl}/orderbook-deltas?market=${market}`, onMessage, opts);
1668
- }
1669
- /**
1670
- * One-shot L2 orderbook snapshot via a temporary delta-stream connection:
1671
- * opens the stream, resolves the first `l2Book` snapshot frame, and closes.
1672
- * Mirrors the Python SDK's `orderbook_snapshot`.
1673
- */
1674
- orderbookSnapshot(market) {
1683
+ orderbookSnapshot(market, timeoutMs = 10_000) {
1684
+ const feed = this.createFeed({ pingIntervalMs: 0 });
1685
+ this.snapshotFeeds.add(feed);
1675
1686
  return new Promise((resolve, reject) => {
1676
- const unsub = this.subscribeOrderbookDeltas(market, (msg) => {
1677
- if (msg.type === "l2Book") {
1678
- unsub();
1679
- resolve(msg);
1687
+ let settled = false;
1688
+ const finish = () => {
1689
+ settled = true;
1690
+ clearTimeout(timer);
1691
+ this.snapshotFeeds.delete(feed);
1692
+ feed.close();
1693
+ };
1694
+ const timer = setTimeout(() => {
1695
+ finish();
1696
+ reject(new FeedSubscriptionError("orderbook", `orderbook snapshot for market ${market} timed out after ${timeoutMs}ms`));
1697
+ }, timeoutMs);
1698
+ feed.subscribeOrderbook(market, (frame) => {
1699
+ if (settled)
1700
+ return;
1701
+ const raw = frame;
1702
+ if (raw.type === "error") {
1703
+ finish();
1704
+ reject(new FeedSubscriptionError("orderbook", raw.error, raw.code));
1705
+ }
1706
+ else if (raw.type === "snapshot") {
1707
+ finish();
1708
+ resolve(raw);
1680
1709
  }
1681
- }, {
1682
- onError: (err) => {
1683
- unsub();
1684
- reject(err instanceof Error ? err : new Error(String(err)));
1685
- },
1686
1710
  });
1687
1711
  });
1688
1712
  }
1689
- /**
1690
- * Internal: open one self-reconnecting WebSocket. `buildUrl` is re-invoked
1691
- * on every (re)connect so per-connect state (fresh auth timestamp, current
1692
- * `after_id`) is rebuilt each time. Reconnects with exponential backoff and
1693
- * jitter. Returns an unsubscribe that stops reconnecting and closes the
1694
- * socket.
1695
- */
1696
- openStream(buildUrl, onMessage, opts) {
1697
- const backoffCapMs = opts.reconnectBackoffMaxMs ?? 30_000;
1698
- let closed = false;
1699
- let ws = null;
1700
- let timer = null;
1701
- let backoff = 500;
1702
- const scheduleReconnect = () => {
1703
- if (closed)
1704
- return;
1705
- const jitter = backoff * (0.75 + Math.random() * 0.5);
1706
- timer = setTimeout(() => void connect(), jitter);
1707
- backoff = Math.min(backoff * 2, backoffCapMs);
1708
- };
1709
- const connect = async () => {
1710
- if (closed)
1711
- return;
1712
- let url;
1713
- try {
1714
- url = await buildUrl();
1715
- }
1716
- catch (err) {
1717
- opts.onError?.(err);
1718
- scheduleReconnect();
1719
- return;
1720
- }
1721
- if (closed)
1722
- return;
1723
- ws = new WebSocket(url);
1724
- ws.onopen = () => {
1725
- backoff = 500;
1726
- };
1727
- ws.onmessage = (ev) => {
1728
- try {
1729
- onMessage(JSON.parse(ev.data));
1730
- }
1731
- catch (err) {
1732
- opts.onError?.(err);
1733
- }
1734
- };
1735
- ws.onerror = (err) => {
1736
- opts.onError?.(err);
1737
- };
1738
- ws.onclose = () => {
1739
- ws = null;
1740
- if (!closed)
1741
- scheduleReconnect();
1742
- };
1743
- };
1744
- const unsubscribe = () => {
1745
- closed = true;
1746
- if (timer) {
1747
- clearTimeout(timer);
1748
- timer = null;
1749
- }
1750
- if (ws) {
1751
- ws.close();
1752
- ws = null;
1753
- }
1754
- this.activeStreams.delete(unsubscribe);
1755
- };
1756
- this.activeStreams.add(unsubscribe);
1757
- void connect();
1758
- return unsubscribe;
1713
+ /** A new `/ws` connection with this client's URL, auth and headers. */
1714
+ createFeed(opts = {}) {
1715
+ let base = this.wsUrl;
1716
+ if (!base && typeof globalThis.location !== "undefined")
1717
+ base = globalThis.location.origin.replace(/^http/, "ws");
1718
+ return new GatewayFeed({
1719
+ url: `${base}/ws`,
1720
+ accountAuth: async (owner) => this.privateKey || this.externalSigner ? this.accountAuth(owner) : {},
1721
+ headers: this.apiKey ? { "X-Api-Key": this.apiKey } : undefined,
1722
+ ...opts,
1723
+ });
1759
1724
  }
1760
1725
  /** Shared multiplexed /ws feed. Options apply on first creation only.
1761
1726
  * Reconnect restores snapshots, not missed events. Default auth reads the current signer.
1762
1727
  */
1763
1728
  feed(opts = {}) {
1764
- if (!this.gatewayFeed) {
1765
- let base = this.wsUrl;
1766
- if (!base && typeof globalThis.location !== "undefined")
1767
- base = globalThis.location.origin.replace(/^http/, "ws");
1768
- this.gatewayFeed = new GatewayFeed({
1769
- url: `${base}/ws`,
1770
- accountAuth: async (owner) => this.privateKey || this.externalSigner ? this.accountAuth(owner) : {},
1771
- headers: this.apiKey ? { "X-Api-Key": this.apiKey } : undefined,
1772
- ...opts,
1773
- });
1774
- }
1729
+ if (!this.gatewayFeed)
1730
+ this.gatewayFeed = this.createFeed(opts);
1775
1731
  return this.gatewayFeed;
1776
1732
  }
1777
- /** Account snapshot plus live stream, with auth renewed per reconnect. */
1733
+ /**
1734
+ * Account snapshot plus live stream, with auth renewed per reconnect.
1735
+ *
1736
+ * By default a reconnect recovers the events missed while disconnected:
1737
+ * the SDK reads `/v1/history/account-events` back to the last delivered
1738
+ * event (or the previous snapshot's `height`), retrying while
1739
+ * `/v1/history/status` shows history behind the new snapshot's `height`,
1740
+ * delivers the newer rows in order (marked `backfilled`), buffers live
1741
+ * frames meanwhile and drops those a backfilled row already delivered,
1742
+ * then resumes live delivery. `onRecovery` reports each reconnect's
1743
+ * outcome once: `unverified` when the snapshot has no `height`,
1744
+ * `unsupported` when the gateway predates 7.9.0 and sends no history key.
1745
+ * `recover: false` turns recovery off.
1746
+ */
1778
1747
  subscribeAccount(onFrame, opts = {}) {
1779
- const owner = opts.owner ?? this.addressHex;
1748
+ const owner = (opts.owner ?? this.addressHex)
1749
+ ?.replace(/^0x/i, "")
1750
+ .toLowerCase();
1780
1751
  if (!owner)
1781
1752
  throw new Error("No account owner available");
1782
- return this.feed().subscribeAccount(owner, onFrame, async (address) => opts.auth !== false && (this.privateKey || this.externalSigner)
1753
+ const auth = async (address) => opts.auth !== false && (this.privateKey || this.externalSigner)
1783
1754
  ? this.accountAuth(address)
1784
- : {});
1755
+ : {};
1756
+ if (opts.recover === false)
1757
+ return this.feed().subscribeAccount(owner, onFrame, auth);
1758
+ const recovery = recoveringAccountHandler({
1759
+ owner,
1760
+ onFrame,
1761
+ onRecovery: opts.onRecovery,
1762
+ fetchPage: (cursor, signal) => this.accountHistoryPage(owner, cursor, signal),
1763
+ fetchIndexedHeight: (signal) => this.historyIndexedHeight(signal),
1764
+ });
1765
+ const unsubscribe = this.feed().subscribeAccount(owner, recovery.handle, auth);
1766
+ this.accountRecoveries.add(recovery.close);
1767
+ return () => {
1768
+ this.accountRecoveries.delete(recovery.close);
1769
+ recovery.close();
1770
+ unsubscribe();
1771
+ };
1772
+ }
1773
+ /** One newest-first `/v1/history/account-events` page for recovery. */
1774
+ async accountHistoryPage(owner, cursor, signal) {
1775
+ const res = await this.reads().accountEvents({
1776
+ owner,
1777
+ order: "desc",
1778
+ limit: 500,
1779
+ ...(cursor ? { cursor } : {}),
1780
+ }, { signal });
1781
+ // Status before parse: a gateway error body need not be JSON, and a
1782
+ // SyntaxError from `res.json()` would bury the intended message.
1783
+ if (!res.ok) {
1784
+ let error;
1785
+ try {
1786
+ error = (await res.json()).error;
1787
+ }
1788
+ catch {
1789
+ error = undefined;
1790
+ }
1791
+ throw new Error(`account history read failed: ${error ?? `HTTP ${res.status}`}`);
1792
+ }
1793
+ const body = (await res.json());
1794
+ if (!Array.isArray(body.account_events))
1795
+ throw new Error(`account history read failed: ${body.error ?? `HTTP ${res.status}`}`);
1796
+ return { rows: body.account_events, nextCursor: body.next_cursor ?? null };
1797
+ }
1798
+ /** The newest height history has indexed in full
1799
+ * (`/v1/history/status` → `ingest.newest_height`). */
1800
+ async historyIndexedHeight(signal) {
1801
+ const res = await this.reads().historyStatus({ signal });
1802
+ if (!res.ok)
1803
+ throw new Error(`history status read failed: HTTP ${res.status}`);
1804
+ const body = (await res.json());
1805
+ const height = body.ingest?.newest_height;
1806
+ if (typeof height !== "number")
1807
+ throw new Error(`history status read failed: HTTP ${res.status}`);
1808
+ return height;
1785
1809
  }
1786
1810
  subscribeOrderbook(market, onFrame) {
1787
1811
  return this.feed().subscribeOrderbook(market, onFrame);
@@ -1789,11 +1813,16 @@ export class ExchangeClient {
1789
1813
  subscribeTrades(market, onFrame) {
1790
1814
  return this.feed().subscribeTrades(market, onFrame);
1791
1815
  }
1792
- /** Close every open WebSocket stream and stop their reconnect loops. */
1816
+ /** Close the shared `/ws` feed, any pending `orderbookSnapshot` feed, any
1817
+ * account backfill in progress, and stop their reconnect loops. */
1793
1818
  disconnect() {
1819
+ for (const close of this.accountRecoveries)
1820
+ close();
1821
+ this.accountRecoveries.clear();
1822
+ for (const feed of this.snapshotFeeds)
1823
+ feed.close();
1824
+ this.snapshotFeeds.clear();
1794
1825
  this.gatewayFeed?.close();
1795
- for (const unsub of [...this.activeStreams])
1796
- unsub();
1797
1826
  }
1798
1827
  }
1799
1828
  // ---------------------------------------------------------------------------
@@ -1830,8 +1859,8 @@ function accountWsAuthMessage(chainId, ownerHex, afterId, timestampMs) {
1830
1859
  * Fetch JSON from the API server and throw on non-2xx or `json.error`.
1831
1860
  * Returns the parsed JSON body on success.
1832
1861
  */
1833
- async function fetchApiJson(url) {
1834
- const res = await fetch(url);
1862
+ async function fetchApiJson(transport, url, context) {
1863
+ const res = await transport(url, undefined, context);
1835
1864
  const json = (await res.json());
1836
1865
  if (!res.ok || json.error) {
1837
1866
  const msg = json.error ?? `HTTP ${res.status}`;
@@ -1857,12 +1886,12 @@ function requireEncodedData(json, endpoint) {
1857
1886
  * `{ data: <base64-msgpack> }`). Used for owner-scoped reads the gateway
1858
1887
  * does not expose as GETs (account, open orders, withdrawal).
1859
1888
  */
1860
- async function postInfoJson(gatewayUrl, info) {
1861
- const res = await fetch(`${gatewayUrl}/info`, {
1889
+ async function postInfoJson(transport, gatewayUrl, info, context) {
1890
+ const res = await transport(`${gatewayUrl}/info`, {
1862
1891
  method: "POST",
1863
1892
  headers: { "Content-Type": "application/json" },
1864
1893
  body: JSON.stringify(info),
1865
- });
1894
+ }, context);
1866
1895
  // The error keeps an unread copy, so callers can still read the body.
1867
1896
  const unread = res.clone();
1868
1897
  let parsed;
@@ -1889,8 +1918,8 @@ async function postInfoJson(gatewayUrl, info) {
1889
1918
  * Fetch a JSON array from the API server and throw on non-2xx or
1890
1919
  * `json.error`. Returns the parsed array on success.
1891
1920
  */
1892
- async function fetchApiArray(url) {
1893
- const res = await fetch(url);
1921
+ async function fetchApiArray(transport, url, context) {
1922
+ const res = await transport(url, undefined, context);
1894
1923
  const json = (await res.json());
1895
1924
  if (!res.ok ||
1896
1925
  (json !== null &&