@proof-labs/trading-sdk 4.2.0 → 5.1.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 (73) hide show
  1. package/README.md +66 -10
  2. package/dist/client.d.ts +111 -41
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +431 -205
  5. package/dist/client.js.map +1 -1
  6. package/dist/codec-adapter.d.ts.map +1 -1
  7. package/dist/codec-adapter.js +20 -4
  8. package/dist/codec-adapter.js.map +1 -1
  9. package/dist/crypto.d.ts +20 -0
  10. package/dist/crypto.d.ts.map +1 -1
  11. package/dist/crypto.js +39 -0
  12. package/dist/crypto.js.map +1 -1
  13. package/dist/errors.d.ts +30 -3
  14. package/dist/errors.d.ts.map +1 -1
  15. package/dist/errors.js +123 -15
  16. package/dist/errors.js.map +1 -1
  17. package/dist/feed-types.d.ts +76 -0
  18. package/dist/feed-types.d.ts.map +1 -0
  19. package/dist/feed-types.js +2 -0
  20. package/dist/feed-types.js.map +1 -0
  21. package/dist/feed.d.ts +158 -0
  22. package/dist/feed.d.ts.map +1 -0
  23. package/dist/feed.js +474 -0
  24. package/dist/feed.js.map +1 -0
  25. package/dist/gateway-reads.d.ts +110 -0
  26. package/dist/gateway-reads.d.ts.map +1 -0
  27. package/dist/gateway-reads.js +91 -0
  28. package/dist/gateway-reads.js.map +1 -0
  29. package/dist/governance-query.d.ts +6 -16
  30. package/dist/governance-query.d.ts.map +1 -1
  31. package/dist/governance-query.js +101 -93
  32. package/dist/governance-query.js.map +1 -1
  33. package/dist/history.d.ts +17 -0
  34. package/dist/history.d.ts.map +1 -0
  35. package/dist/history.js +150 -0
  36. package/dist/history.js.map +1 -0
  37. package/dist/index.d.ts +11 -4
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +7 -4
  40. package/dist/index.js.map +1 -1
  41. package/dist/market-snapshot.d.ts.map +1 -1
  42. package/dist/market-snapshot.js +4 -5
  43. package/dist/market-snapshot.js.map +1 -1
  44. package/dist/oracle-guards.d.ts +5 -0
  45. package/dist/oracle-guards.d.ts.map +1 -0
  46. package/dist/oracle-guards.js +27 -0
  47. package/dist/oracle-guards.js.map +1 -0
  48. package/dist/oracle-permissions.d.ts +13 -0
  49. package/dist/oracle-permissions.d.ts.map +1 -1
  50. package/dist/oracle-permissions.js +44 -1
  51. package/dist/oracle-permissions.js.map +1 -1
  52. package/dist/oracle-price-history.d.ts +30 -0
  53. package/dist/oracle-price-history.d.ts.map +1 -0
  54. package/dist/oracle-price-history.js +108 -0
  55. package/dist/oracle-price-history.js.map +1 -0
  56. package/dist/portfolio-history.d.ts +21 -0
  57. package/dist/portfolio-history.d.ts.map +1 -0
  58. package/dist/portfolio-history.js +49 -0
  59. package/dist/portfolio-history.js.map +1 -0
  60. package/dist/triggers.d.ts +26 -2
  61. package/dist/triggers.d.ts.map +1 -1
  62. package/dist/triggers.js +38 -6
  63. package/dist/triggers.js.map +1 -1
  64. package/dist/tx-result.d.ts +6 -0
  65. package/dist/tx-result.d.ts.map +1 -1
  66. package/dist/tx-result.js +42 -0
  67. package/dist/tx-result.js.map +1 -1
  68. package/dist/types.d.ts +206 -135
  69. package/dist/types.d.ts.map +1 -1
  70. package/dist/types.js +11 -7
  71. package/dist/types.js.map +1 -1
  72. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm +0 -0
  73. package/package.json +5 -1
package/dist/client.js CHANGED
@@ -1,14 +1,21 @@
1
- import { signAndEncode } from "./codec.js";
1
+ import { GatewayFeed, } from "./feed.js";
2
+ import { portfolioHistorySearchParams, decodePortfolioHistoryPage, } from "./portfolio-history.js";
3
+ import { queryOraclePriceHistoryPage, } from "./oracle-price-history.js";
4
+ import { GatewayReads } from "./gateway-reads.js";
5
+ import { GatewayHttpError } from "./errors.js";
6
+ import { decodeCashFlowEvents, decodeHistoryPositionsPage, historyOwner, historySearchParams, } from "./history.js";
7
+ import { toWasmFields } from "./codec-adapter.js";
8
+ import { signAndEncode, encodePayloadBytes, encodeSignedTx } from "./codec.js";
2
9
  import { decodeAccountState } from "./account-state.js";
3
10
  import { fetchFinancialState, } from "./financial-state.js";
4
11
  import { ready as initWasm } from "./wasm-loader.js";
5
- import { txEngineError, txFromEngineCode, txOk, txTimeout, txTransportError, } from "./tx-result.js";
6
- import { getPublicKey, pubkeyToOwner, ownerToHex, bytesToHex, sign, UNBOUND_CHAIN_ID, chainIdFromString, } from "./crypto.js";
7
- import { decodeAdminSignerRegistryInfo, decodeImpactMarketInfo, decodeEventInfo, decodeProposalPage, } from "./governance-query.js";
12
+ import { txEngineError, txFromEngineCode, txFromQueryResponse, txOk, txTimeout, txTransportError, } from "./tx-result.js";
13
+ import { getPublicKey, pubkeyToOwner, ownerToHex, bytesToHex, sign, verify, signingMessage, UNBOUND_CHAIN_ID, chainIdFromString, } from "./crypto.js";
14
+ import { decodeAdminSignerRegistryInfo, decodeEventInfo, decodeProposalPage, } from "./governance-query.js";
8
15
  import { Decoder } from "@msgpack/msgpack";
9
16
  import { readMarketsSnapshot } from "./market-snapshot.js";
10
17
  import { sha256 } from "@noble/hashes/sha2.js";
11
- import { decodePositionTriggerInfos, decodeTriggerMarketConfigInfos, decodeTriggerStatusJson, validateCancelPositionTriggers, validateSetPositionTriggers, } from "./triggers.js";
18
+ import { decodePositionTriggerInfos, decodeTriggerMarketConfigInfos, decodeTriggerStatusJson, validateCancelPositionTriggers, validateOrderTriggers, validateSetPositionTriggers, } from "./triggers.js";
12
19
  import { decodePositionTriggerHistoryPage, decodeTriggerMarketHistoryPage, positionTriggerHistorySearchParams, triggerMarketHistorySearchParams, validateTriggerHistoryMarket, } from "./trigger-history.js";
13
20
  const msgpackDecoder = new Decoder({ useBigInt64: true });
14
21
  import { decodeOraclePermissions, validateOraclePermissionMarket, } from "./oracle-permissions.js";
@@ -52,6 +59,9 @@ export class ExchangeClient {
52
59
  /** Single-flight guard so concurrent submits share one /status fetch. */
53
60
  chainIdPromise = null;
54
61
  privateKey = null;
62
+ externalSigner = null;
63
+ signerRevision = 0;
64
+ gatewayFeed = null;
55
65
  publicKey = null;
56
66
  address = null;
57
67
  addressHex = null;
@@ -213,11 +223,93 @@ export class ExchangeClient {
213
223
  // -----------------------------------------------------------------------
214
224
  /** Set the private key for signing transactions. */
215
225
  setPrivateKey(key) {
226
+ this.externalSigner = null;
227
+ this.signerRevision++;
216
228
  this.privateKey = key;
217
229
  this.publicKey = getPublicKey(key);
218
230
  this.address = pubkeyToOwner(this.publicKey);
219
231
  this.addressHex = ownerToHex(this.address);
220
232
  }
233
+ /** Replace the signing connection; no private key is retained. */
234
+ setExternalSigner(signer) {
235
+ if (signer.publicKey.length !== 32)
236
+ throw new Error("External signer public key must be 32 bytes");
237
+ this.signerRevision++;
238
+ this.privateKey = null;
239
+ this.externalSigner = {
240
+ publicKey: signer.publicKey.slice(),
241
+ signRaw: signer.signRaw.bind(signer),
242
+ };
243
+ this.publicKey = this.externalSigner.publicKey.slice();
244
+ this.address = pubkeyToOwner(this.publicKey);
245
+ this.addressHex = ownerToHex(this.address);
246
+ }
247
+ /** Sign only. Cancellation or a replaced connection prevents submission. */
248
+ async signTx(action, opts = {}) {
249
+ opts.signal?.throwIfAborted();
250
+ const signer = this.externalSigner;
251
+ const key = this.privateKey?.slice();
252
+ const revision = this.signerRevision;
253
+ if (!signer && !key)
254
+ throw new Error("No signer set");
255
+ // Freeze caller-owned inputs before any await (wallet prompts may be long).
256
+ const snapshot = cloneSigningInput(action);
257
+ const [chainId] = await Promise.all([this.resolveChainId(), initWasm()]);
258
+ opts.signal?.throwIfAborted();
259
+ if (revision !== this.signerRevision)
260
+ throw new Error("Signing connection changed");
261
+ const seq = this.nextTimestampNonce();
262
+ if (!signer)
263
+ return signAndEncode(chainId, snapshot, seq, key);
264
+ const payload = encodePayloadBytes(snapshot);
265
+ const message = signingMessage(chainId, toWasmFields(snapshot).actionType, seq, payload);
266
+ const signature = cloneSigningInput(await signer.signRaw(message.slice()));
267
+ opts.signal?.throwIfAborted();
268
+ if (revision !== this.signerRevision)
269
+ throw new Error("Signing connection changed");
270
+ if (!(signature instanceof Uint8Array) ||
271
+ signature.length !== 64 ||
272
+ !verify(signer.publicKey, signature, message)) {
273
+ throw new Error("External signer returned an invalid signature");
274
+ }
275
+ return encodeSignedTx(snapshot, seq, signer.publicKey, signature);
276
+ }
277
+ /** Sign existing gateway account-events auth bytes; call again per reconnect.
278
+ * Direct owner keys only; no delegated-owner authorization is inferred.
279
+ */
280
+ async accountAuth(owner = this.addressHex ?? "", afterId = 0n) {
281
+ const ownerHex = owner.replace(/^0x/i, "").toLowerCase();
282
+ if (!/^[0-9a-f]{40}$/.test(ownerHex) || ownerHex !== this.addressHex)
283
+ throw new Error("Account auth owner does not match signer");
284
+ if (afterId < 0n || afterId > BigInt(Number.MAX_SAFE_INTEGER))
285
+ throw new Error("Invalid account auth cursor");
286
+ const signer = this.externalSigner;
287
+ const key = this.privateKey?.slice();
288
+ const publicKey = this.publicKey?.slice();
289
+ const revision = this.signerRevision;
290
+ if (!publicKey || (!signer && !key))
291
+ throw new Error("No signer set");
292
+ const chainId = await this.resolveChainId();
293
+ if (revision !== this.signerRevision)
294
+ throw new Error("Signing connection changed");
295
+ const timestampMs = BigInt(Date.now());
296
+ const message = accountWsAuthMessage(chainId, ownerHex, afterId, timestampMs);
297
+ const signature = signer
298
+ ? cloneSigningInput(await signer.signRaw(message.slice()))
299
+ : sign(key, message);
300
+ if (revision !== this.signerRevision)
301
+ throw new Error("Signing connection changed");
302
+ if (!ArrayBuffer.isView(signature) ||
303
+ signature.byteLength !== 64 ||
304
+ !verify(publicKey, signature, message))
305
+ throw new Error("External signer returned an invalid signature");
306
+ return {
307
+ public_key: bytesToHex(publicKey),
308
+ signature: bytesToHex(signature),
309
+ timestamp_ms: Number(timestampMs),
310
+ ...(afterId > 0n ? { after_id: Number(afterId) } : {}),
311
+ };
312
+ }
221
313
  getAddress() {
222
314
  return this.address;
223
315
  }
@@ -254,24 +346,28 @@ export class ExchangeClient {
254
346
  /**
255
347
  * Allocate the next timestamp nonce.
256
348
  *
257
- * Algorithm: `max(now_ms, last_nonce + 1)` capped at `now_ms + 60s` to
258
- * bound the growth if the clock stops ticking.
349
+ * Algorithm: `max(now_ms, last_nonce + 1)`. Refuse allocation above
350
+ * `now_ms + 60s` without rewinding or repeating the last nonce.
259
351
  *
260
352
  * Engine window: `[block_time - 2 days, block_time + 1 day]`. All four
261
353
  * rejection modes (too old, too far future, replay, below oldest) map to
262
354
  * code 21 `InvalidNonce`. Nonces are burned on success — no rewinding.
263
355
  *
264
- * Thread-safe only through external serialization (caller's responsibility).
356
+ * Concurrent calls on this client reserve distinct nonces synchronously.
265
357
  */
266
358
  nextTimestampNonce() {
267
359
  const now = BigInt(Date.now());
268
360
  const max = now + 60000n;
269
- let next = this.lastTimestampNonce >= now ? this.lastTimestampNonce + 1n : now;
361
+ const next = this.lastTimestampNonce >= now ? this.lastTimestampNonce + 1n : now;
270
362
  if (next > max)
271
- next = max;
363
+ throw new Error("Timestamp nonce allocation exceeds clock safety window");
272
364
  this.lastTimestampNonce = next;
273
365
  return next;
274
366
  }
367
+ /** Highest locally allocated nonce; never rewound after rejection. */
368
+ get currentNonce() {
369
+ return this.lastTimestampNonce;
370
+ }
275
371
  // -----------------------------------------------------------------------
276
372
  // Transaction submission
277
373
  // -----------------------------------------------------------------------
@@ -360,17 +456,7 @@ export class ExchangeClient {
360
456
  * Both paths submit identical signed wire bytes.
361
457
  */
362
458
  async broadcastSigned(action) {
363
- if (!this.privateKey)
364
- throw new Error("No private key set");
365
- // Initialize the WASM codec/signing core and resolve the chain_id
366
- // concurrently; both are cached, so only the first submit pays for either.
367
- const [chainId] = await Promise.all([this.resolveChainId(), initWasm()]);
368
- const seq = this.nextTimestampNonce();
369
- const txBytes = signAndEncode(chainId, action, seq, this.privateKey);
370
- const r = this.useGateway
371
- ? await this.submitViaGateway(txBytes)
372
- : await this.submitViaCometBFT(txBytes);
373
- return r;
459
+ return this.broadcastSignedBytes(await this.signTx(action));
374
460
  }
375
461
  /**
376
462
  * Submit signed wire bytes via the public API gateway
@@ -400,12 +486,20 @@ export class ExchangeClient {
400
486
  if (this.apiKey)
401
487
  headers["X-Api-Key"] = this.apiKey;
402
488
  const body = JSON.stringify({ action: toBase64(txBytes) });
403
- const res = await fetch(`${this.gatewayUrl}/exchange`, {
404
- method: "POST",
405
- headers,
406
- body,
407
- });
408
- const gatewayBody = await readGatewayBody(res);
489
+ let res;
490
+ let gatewayBody;
491
+ try {
492
+ res = await fetch(`${this.gatewayUrl}/exchange`, {
493
+ method: "POST",
494
+ headers,
495
+ body,
496
+ });
497
+ gatewayBody = await readGatewayBody(res);
498
+ }
499
+ catch {
500
+ // A dropped response does not prove the signed transaction was rejected.
501
+ return txTimeout(txHash, "gateway transport interrupted; reconcile by hash");
502
+ }
409
503
  // Auth/rate-limit transport failures don't have a JSON body the
410
504
  // engine produced — synthesize an HTTP-status code and tag the result
411
505
  // `outcome: "transport"` so callers don't read it as an ExecError.
@@ -420,12 +514,14 @@ export class ExchangeClient {
420
514
  gatewayBody.raw ??
421
515
  "request body exceeds max size (default 8192 bytes)");
422
516
  }
517
+ const refusal = preAdmissionRefusal(res.status, gatewayBody.json);
518
+ // Gateway ExchangeResponse::err is hashless: a structured 503 proves
519
+ // the transaction never entered the broadcaster queue.
520
+ if (res.status === 503 && refusal !== undefined) {
521
+ return txTransportError(503, refusal);
522
+ }
423
523
  if (res.status >= 500) {
424
- return txTransportError(500, gatewayBody.error
425
- ? `gateway error: ${gatewayBody.error}`
426
- : gatewayBody.raw
427
- ? `gateway error: ${res.status} ${res.statusText}: ${gatewayBody.raw}`
428
- : `gateway error: ${res.status} ${res.statusText}`);
524
+ return txTimeout(txHash, `gateway HTTP ${res.status}; reconcile by hash${gatewayBody.error || gatewayBody.raw ? `: ${gatewayBody.error ?? gatewayBody.raw}` : ""}`);
429
525
  }
430
526
  if (!res.ok) {
431
527
  const errMsg = gatewayBody.error ??
@@ -458,6 +554,7 @@ export class ExchangeClient {
458
554
  hash,
459
555
  height: json.height,
460
556
  log: json.log ?? json.error,
557
+ info: json.info,
461
558
  events: json.events,
462
559
  });
463
560
  }
@@ -478,10 +575,15 @@ export class ExchangeClient {
478
575
  // Fallback: the code embedded in the string as "<engine_code>: <message>".
479
576
  // The gateway still emits this format for compatibility, so this path also
480
577
  // covers a pre-#90 gateway that sends ONLY the string. Parse the leading code;
481
- // if missing, surface 1 (DecodeError) as the conservative default.
578
+ // Hashless gateway refusals are terminal; unrecognized bodies remain unknown.
482
579
  const errMsg = json?.error ?? gatewayBody.raw ?? "unknown gateway error";
483
- const code = parseLeadingErrorCode(errMsg) ?? 1;
484
- return txEngineError(code, { log: errMsg });
580
+ const code = parseLeadingErrorCode(errMsg);
581
+ if (code !== null)
582
+ return txEngineError(code, { log: errMsg });
583
+ if (res.status === 200 && refusal !== undefined) {
584
+ return txTransportError(1, refusal);
585
+ }
586
+ return txTimeout(txHash, "gateway returned no verdict; reconcile by hash");
485
587
  }
486
588
  /**
487
589
  * Whether a `TxResult` is already final — i.e. nothing is gained by polling
@@ -536,37 +638,9 @@ export class ExchangeClient {
536
638
  let self;
537
639
  const verify = async () => {
538
640
  try {
539
- // Poll up to 5 s — enough for normal block time (~1 s).
540
- const deadline = Date.now() + 5_000;
541
- let pollDelay = 250;
542
- while (Date.now() < deadline) {
543
- await new Promise((r) => setTimeout(r, pollDelay));
544
- pollDelay = Math.min(pollDelay + 100, 600);
545
- try {
546
- const res = await fetch(this.txStatusUrl(txHash));
547
- const json = await res.json();
548
- const txResult = json.result?.tx_result;
549
- if (txResult) {
550
- const code = txResult.code ?? 0;
551
- const height = json.result.height
552
- ? Number(json.result.height)
553
- : undefined;
554
- this.deliveryResults.push(txFromEngineCode(code, {
555
- hash: txHash,
556
- height,
557
- log: txResult.log ?? "",
558
- events: txResult.events,
559
- }));
560
- return;
561
- }
562
- // Tx not yet indexed — keep polling.
563
- }
564
- catch {
565
- // Network blip — retry.
566
- }
567
- }
568
- // Timed out without seeing the result. The timestamp nonce may have
569
- // landed or may be reusable only if never included; do not rewind.
641
+ const result = await this.waitForDelivery(txTimeout(txHash, "awaiting delivery"), { timeoutMs: 5_000 });
642
+ if (result.outcome !== "timeout")
643
+ this.deliveryResults.push(result);
570
644
  }
571
645
  finally {
572
646
  this.pendingVerifies.delete(self);
@@ -615,8 +689,6 @@ export class ExchangeClient {
615
689
  * `broadcast_tx_commit` subscription.
616
690
  */
617
691
  async submitTxCommit(action) {
618
- if (!this.privateKey)
619
- throw new Error("No private key set");
620
692
  // Step 1: broadcast via sync (returns after CheckTx). Use the internal
621
693
  // path so we don't double-spawn a background verifier — we're going to
622
694
  // do our own synchronous verification below.
@@ -646,52 +718,48 @@ export class ExchangeClient {
646
718
  * unknown.
647
719
  */
648
720
  async awaitCommit(sync) {
649
- if (this.isFinalResult(sync)) {
650
- // Either the gateway already returned the on-chain result (the
651
- // synchronous submit path — nothing to wait for), or the tx was rejected
652
- // at CheckTx / never reached the chain, in which case no DeliverTx will
653
- // ever run. This is the case H14 was filed about: a confirmed order used
654
- // to cost a 9-second poll loop, and now costs one round-trip.
655
- return sync;
656
- }
657
- if (!sync.ok && sync.outcome !== "timeout") {
721
+ return this.waitForDelivery(sync);
722
+ }
723
+ /** Per-submission finality. Timeout/cancellation retains the hash as unknown.
724
+ * Never resubmits writes. Use setUnsafeFastSubmit(true) to avoid a second poller.
725
+ */
726
+ async waitForDelivery(sync, opts = {}) {
727
+ if (this.isFinalResult(sync))
658
728
  return sync;
659
- }
660
- // Step 2: the outcome is still unknown (a pre-#90 gateway that only acks
661
- // CheckTx, the direct-to-CometBFT path, or a gateway that broadcast the tx
662
- // but could not report the result in time). Poll /tx?hash=... until found
663
- // or timeout (~9 seconds).
664
- const txHash = sync.hash;
665
- if (!txHash) {
729
+ if (!sync.hash)
666
730
  throw new Error("submitTx returned no tx hash");
667
- }
668
- const deadline = Date.now() + 9_000;
731
+ const timeoutMs = opts.timeoutMs ?? 9_000;
732
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
733
+ throw new Error("Invalid delivery timeout");
734
+ const deadline = Date.now() + timeoutMs;
669
735
  let pollDelay = 200;
670
- while (Date.now() < deadline) {
671
- await new Promise((r) => setTimeout(r, pollDelay));
736
+ while (Date.now() < deadline && !opts.signal?.aborted) {
737
+ await abortableDelay(Math.min(pollDelay, deadline - Date.now()), opts.signal);
672
738
  pollDelay = Math.min(pollDelay + 100, 600);
739
+ const remaining = deadline - Date.now();
740
+ if (remaining <= 0 || opts.signal?.aborted)
741
+ break;
742
+ const request = readDeadline(Math.ceil(remaining), opts.signal);
673
743
  try {
674
- const res = await fetch(this.txStatusUrl(txHash));
675
- const json = await res.json();
676
- const txResult = json.result?.tx_result;
677
- if (txResult) {
678
- const code = txResult.code ?? 0;
679
- return txFromEngineCode(code, {
680
- hash: txHash,
681
- height: json.result.height ? Number(json.result.height) : undefined,
682
- log: txResult.log,
683
- events: txResult.events,
684
- });
685
- }
686
- // tx not yet indexed → keep polling
744
+ const res = await fetch(this.txStatusUrl(sync.hash), {
745
+ signal: request.signal,
746
+ });
747
+ if (!res.ok)
748
+ continue;
749
+ const result = txFromQueryResponse(await res.json(), sync.hash);
750
+ if (!opts.signal?.aborted && result)
751
+ return result;
687
752
  }
688
753
  catch {
689
- // network blip — retry
754
+ /* Read failures leave the write outcome unknown. */
755
+ }
756
+ finally {
757
+ request.dispose();
690
758
  }
691
759
  }
692
- // Timed out waiting for inclusion. We don't know whether it landed, so
693
- // do not reuse or rewind the timestamp nonce.
694
- return txTimeout(txHash, "submitTxCommit: timed out polling /tx after 9s");
760
+ return txTimeout(sync.hash, opts.signal?.aborted
761
+ ? "delivery wait cancelled; reconcile by hash"
762
+ : "delivery wait timed out; reconcile by hash");
695
763
  }
696
764
  // -----------------------------------------------------------------------
697
765
  // Convenience action builders
@@ -716,15 +784,24 @@ export class ExchangeClient {
716
784
  * Place a limit order for the loaded signer. `owner` is supplied
717
785
  * automatically. Equivalent to
718
786
  * `submitTx({ type: "PlaceOrder", data: { ...params, owner } })`.
787
+ * Optional `stopLoss`/`takeProfit` limbs attach a pre-fill bracket that
788
+ * installs on the order's first fill (validated client-side here and in
789
+ * the codec path; encoded as the proof-wire 2.1.0 trailing fields).
719
790
  */
720
791
  async placeOrder(params) {
792
+ validateOrderTriggers(params);
721
793
  return this.submitTx({
722
794
  type: "PlaceOrder",
723
795
  data: { ...params, owner: this.requireOwner() },
724
796
  });
725
797
  }
726
- /** Place a market order (crosses immediately) for the loaded signer. */
798
+ /**
799
+ * Place a market order (crosses immediately) for the loaded signer.
800
+ * Optional `stopLoss`/`takeProfit` limbs are validated like
801
+ * {@link ExchangeClient.placeOrder}.
802
+ */
727
803
  async marketOrder(params) {
804
+ validateOrderTriggers(params);
728
805
  return this.submitTx({
729
806
  type: "MarketOrder",
730
807
  data: { ...params, owner: this.requireOwner() },
@@ -833,26 +910,10 @@ export class ExchangeClient {
833
910
  const raw = msgpackDecoder.decode(bytes);
834
911
  return raw.map((m) => decodeMarketConfig(m));
835
912
  }
836
- /** List all impact-market families (the 5-book event structures: an
837
- * underlying perp plus CPY/CPN/EBY/EBN children). Fail-closed like the
838
- * governance reads: a missing envelope or a malformed row is a refusal,
839
- * never a partially-rendered list (decoder pinned to engine golden bytes
840
- * in governance-query.test.ts). */
841
- async queryImpactMarkets() {
842
- const json = await fetchApiJson(`${this.readBaseUrl}/v1/impact_markets`);
843
- if (typeof json.data !== "string") {
844
- throw new Error("governance decode: impact-markets response has no encoded-data envelope");
845
- }
846
- const raw = msgpackDecoder.decode(fromBase64(json.data));
847
- if (!Array.isArray(raw)) {
848
- throw new Error("governance decode: impactMarkets is not an array");
849
- }
850
- return raw.map((r, i) => decodeImpactMarketInfo(r, i));
851
- }
852
- /** All standalone events (G17). Each is two prediction-binary books (EBY/EBN)
853
- * under one `EventInfo`, no underlying perp. Fail-closed like the impact
854
- * read: a missing envelope or malformed row is a refusal. Decoder pinned to
855
- * the engine golden vector in governance-query.test.ts. */
913
+ /** All events: each is two prediction-binary books (EBY/EBN) under one
914
+ * `EventInfo`, plus every conditional attached to it. Fail-closed like the
915
+ * governance reads: a missing envelope or malformed row is a refusal.
916
+ * Decoder pinned to the engine golden vector in governance-query.test.ts. */
856
917
  async queryEvents() {
857
918
  const json = await fetchApiJson(`${this.readBaseUrl}/v1/events`);
858
919
  if (typeof json.data !== "string") {
@@ -864,10 +925,10 @@ export class ExchangeClient {
864
925
  }
865
926
  return raw.map((r, i) => decodeEventInfo(r, i));
866
927
  }
867
- /** A single standalone event by id, or `null` if it does not exist. The node
868
- * returns 404 for a missing event (the engine's msgpack-nil, translated like
869
- * the impact-market route), so a raw fetch is used here to map 404 -> null
870
- * while still throwing on real transport / decode failures. */
928
+ /** A single event by id, or `null` if it does not exist. The node returns
929
+ * 404 for a missing event (the engine's msgpack-nil), so a raw fetch is used
930
+ * here to map 404 -> null while still throwing on real transport / decode
931
+ * failures. */
871
932
  async queryEvent(eventId) {
872
933
  const res = await fetch(`${this.readBaseUrl}/v1/event/${eventId}`);
873
934
  if (res.status === 404)
@@ -908,7 +969,14 @@ export class ExchangeClient {
908
969
  return decodeTriggerMarketConfigInfos(msgpackDecoder.decode(bytes));
909
970
  }
910
971
  /** Read the fail-closed next-height trigger admission predicate. Heights
911
- * are parsed from raw JSON into bigint without a lossy Number round-trip. */
972
+ * are parsed from raw JSON into bigint without a lossy Number round-trip.
973
+ *
974
+ * @deprecated `GET /v1/triggers/status` is deleted upstream: the node
975
+ * dropped it with its activation gates (exchange#619, genesis-first) and
976
+ * the gateway drops it in gateway 4.0.0 (api-gateway#175). Trigger actions
977
+ * are permanently active, so there is nothing to read. Against a gateway or
978
+ * node that no longer serves the route this rejects with an `API error`
979
+ * for the 404 response. It will be removed in the next major version. */
912
980
  async queryTriggerStatus() {
913
981
  const path = "/v1/triggers/status";
914
982
  const res = await fetch(`${this.readBaseUrl}${path}`);
@@ -1109,7 +1177,7 @@ export class ExchangeClient {
1109
1177
  bindingScenario = (raw[6] ?? []).map((e) => {
1110
1178
  const t = e;
1111
1179
  return {
1112
- impactMarketId: Number(t[0]),
1180
+ eventId: Number(t[0]),
1113
1181
  branch: t[1],
1114
1182
  };
1115
1183
  });
@@ -1196,52 +1264,56 @@ export class ExchangeClient {
1196
1264
  : String(row.open_interest),
1197
1265
  };
1198
1266
  }
1199
- /** Per-user deposit log — every `deposit_confirmed` event for this
1200
- * owner, newest first. Feeds Portfolio EquityChart equity-over-time
1201
- * reconstruction (P2 #6). */
1267
+ /** Direct relayer deposits and custody-confirmed deposits, newest first.
1268
+ * Returns a bounded merged head, not a cursor over the complete history. */
1202
1269
  async queryHistoryDeposits(addressHex, opts) {
1203
1270
  return this.queryHistoryCashFlow("deposits", addressHex, opts);
1204
1271
  }
1205
- /** Per-user withdrawal lifecycle log — withdraw_requested /
1206
- * withdrawal_confirmed / withdrawal_failed, newest first. Filter by
1207
- * `kind` client-side if you want only pending requests. P2 #6. */
1272
+ /** Direct relayer withdrawals and indexed custody events, newest first,
1273
+ * capped after merging each kind's first page. This is not withdrawal status:
1274
+ * ownerless confirmation events
1275
+ * are not indexed for the account. Use queryWithdrawal(id) for status.
1276
+ * Request/refund amounts exclude fees; unknown signedDelta stays empty. */
1208
1277
  async queryHistoryWithdrawals(addressHex, opts) {
1209
1278
  return this.queryHistoryCashFlow("withdrawals", addressHex, opts);
1210
1279
  }
1211
- /** Internal: shared decoder for the two cash-flow endpoints. They
1212
- * return identical row shapes (HistoryCashFlow); the difference is
1213
- * which kinds the server includes. */
1214
- async queryHistoryCashFlow(path, addressHex, opts) {
1280
+ /** Owner-filtered indexer events; never the removed node history routes. */
1281
+ async queryHistoryCashFlow(path, addressHex, opts = {}) {
1215
1282
  const hex = addressHex ?? this.addressHex;
1216
1283
  if (!hex)
1217
1284
  return [];
1218
- const params = new URLSearchParams();
1219
- if (opts?.fromMs !== undefined)
1220
- params.set("from", String(opts.fromMs));
1221
- if (opts?.toMs !== undefined)
1222
- params.set("to", String(opts.toMs));
1223
- if (opts?.limit !== undefined)
1224
- params.set("limit", String(opts.limit));
1225
- const qs = params.toString();
1226
- const url = `${this.readBaseUrl}/v1/history/${path}/${hex}${qs ? `?${qs}` : ""}`;
1227
- const json = await fetchApiArray(url);
1228
- return json.map((row) => ({
1229
- kind: row.kind,
1230
- owner: String(row.owner ?? ""),
1231
- amount: String(row.amount ?? ""),
1232
- signedDelta: String(row.signed_delta ?? "0"),
1233
- newBalance: String(row.new_balance ?? ""),
1234
- withdrawalId: String(row.withdrawal_id ?? ""),
1235
- solanaTxSig: String(row.solana_tx_sig ?? ""),
1236
- solanaDestination: String(row.solana_destination ?? ""),
1237
- reason: String(row.reason ?? ""),
1238
- blockHeight: Number(row.block_height ?? 0),
1239
- timestamp: Number(row.timestamp ?? 0),
1285
+ const owner = historyOwner(hex);
1286
+ const limit = opts.limit ?? 200;
1287
+ const params = historySearchParams({ ...opts, limit });
1288
+ params.set("owner", owner);
1289
+ params.set("order", "desc");
1290
+ const kinds = path === "deposits"
1291
+ ? ["deposited", "deposit_confirmed"]
1292
+ : [
1293
+ "withdrawn",
1294
+ "withdraw_requested",
1295
+ "withdrawal_confirmed",
1296
+ "withdrawal_failed",
1297
+ ];
1298
+ const pages = await Promise.all(kinds.map(async (kind) => {
1299
+ const query = new URLSearchParams(params);
1300
+ query.set("event_type", kind);
1301
+ const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/account-events?${query}`);
1302
+ return decodeCashFlowEvents(json, owner, kind);
1240
1303
  }));
1304
+ return pages
1305
+ .flat()
1306
+ .sort((a, b) => {
1307
+ if (a.nanos !== b.nanos)
1308
+ return a.nanos > b.nanos ? -1 : 1;
1309
+ return a.eventId > b.eventId ? -1 : a.eventId < b.eventId ? 1 : 0;
1310
+ })
1311
+ .slice(0, limit)
1312
+ .map((event) => event.cashFlow);
1241
1313
  }
1242
1314
  /** Per-user position-at-resolution log — each row is one settlement or
1243
1315
  * voided-conditional snapshot. Feeds the Portfolio "Resolved" tab
1244
- * (P2 #7). Optional `impactMarketId` filter scopes to one event family.
1316
+ * (P2 #7). Optional `eventId` filter scopes to one event.
1245
1317
  *
1246
1318
  * `fromMs` / `toMs` are unix-ms timestamps; omit for unbounded.
1247
1319
  * `limit` caps at 1000 server-side. Results are newest-first. */
@@ -1250,8 +1322,8 @@ export class ExchangeClient {
1250
1322
  if (!hex)
1251
1323
  return [];
1252
1324
  const params = new URLSearchParams();
1253
- if (opts?.impactMarketId !== undefined)
1254
- params.set("impact_market_id", String(opts.impactMarketId));
1325
+ if (opts?.eventId !== undefined)
1326
+ params.set("event_id", String(opts.eventId));
1255
1327
  if (opts?.fromMs !== undefined)
1256
1328
  params.set("from", String(opts.fromMs));
1257
1329
  if (opts?.toMs !== undefined)
@@ -1263,7 +1335,7 @@ export class ExchangeClient {
1263
1335
  const json = await fetchApiArray(url);
1264
1336
  return json.map((row) => ({
1265
1337
  kind: row.kind,
1266
- impactMarketId: String(row.impact_market_id ?? ""),
1338
+ eventId: String(row.event_id ?? ""),
1267
1339
  market: String(row.market ?? ""),
1268
1340
  owner: String(row.owner ?? ""),
1269
1341
  side: String(row.side ?? ""),
@@ -1275,38 +1347,66 @@ export class ExchangeClient {
1275
1347
  timestamp: Number(row.timestamp ?? 0),
1276
1348
  }));
1277
1349
  }
1278
- /** Per-user position-history snapshot log. Each row is one
1279
- * point-in-time snapshot persisted after a fill that changes the
1280
- * position. A `size === "0"` row is a CLOSE event; the immediately
1281
- * preceding non-zero snapshot for the same `(owner, market, side)`
1282
- * carries the entry price. Feeds the trading-UI Position History tab
1283
- * (FE-23). Optional `market` filter scopes to one book; `fromMs` /
1284
- * `toMs` window the timestamps; `limit` caps server-side at 5000. */
1350
+ /** Named gateway responses for HTTP consumers that own body parsing, deadlines
1351
+ * and scheduling. Prefer typed query methods when raw response metadata is unnecessary.
1352
+ * Uses this client's gateway; never targets a node, even in internal node mode.
1353
+ */
1354
+ reads(opts = {}) {
1355
+ return new GatewayReads(this.gatewayUrl, opts.fetch ?? ((url, init) => fetch(url, init)));
1356
+ }
1357
+ /** Gateway/indexer portfolio page, including in internal node mode.
1358
+ * Keep bounds fixed across opaque cursors. */
1359
+ async queryPortfolioHistory(owner, opts) {
1360
+ const canonicalOwner = owner.replace(/^0x/i, "").toLowerCase();
1361
+ if (!/^[0-9a-f]{40}$/.test(canonicalOwner))
1362
+ throw new Error("Invalid portfolio owner");
1363
+ const params = portfolioHistorySearchParams(opts);
1364
+ opts.signal?.throwIfAborted();
1365
+ const res = await fetch(`${this.gatewayUrl}/v1/history/portfolio/${canonicalOwner}?${params}`, { signal: opts.signal });
1366
+ if (!res.ok)
1367
+ throw new GatewayHttpError(res.status, res);
1368
+ const page = await res.json();
1369
+ opts.signal?.throwIfAborted();
1370
+ return decodePortfolioHistoryPage(page, canonicalOwner, opts);
1371
+ }
1372
+ /** One newest-first gateway page of a market's indexed `price_updated`
1373
+ * history. Keep market and bounds fixed across opaque cursors. */
1374
+ async queryOraclePriceHistory(market, options) {
1375
+ return queryOraclePriceHistoryPage(this.gatewayUrl, market, options);
1376
+ }
1377
+ /** Compatibility array of position snapshots. Absent close fields are empty
1378
+ * strings and timestamps are milliseconds. Use queryHistoryPositionsPage for
1379
+ * nullable fields, exact block times and opaque cursor continuation. */
1285
1380
  async queryHistoryPositions(addressHex, opts) {
1381
+ const page = await this.queryHistoryPositionsPage(addressHex, opts);
1382
+ return page.positions.map((row) => ({
1383
+ owner: row.owner,
1384
+ market: String(row.market),
1385
+ side: row.side ?? "",
1386
+ entryPrice: row.entryPrice ?? "",
1387
+ size: row.size,
1388
+ blockHeight: row.blockHeight,
1389
+ timestamp: Date.parse(row.blockTime),
1390
+ }));
1391
+ }
1392
+ /** Gateway/indexer snapshots, newest first. Preserve filters when passing an
1393
+ * opaque nextCursor back in opts.cursor. Null close fields stay null. */
1394
+ async queryHistoryPositionsPage(addressHex, opts = {}) {
1286
1395
  const hex = addressHex ?? this.addressHex;
1287
1396
  if (!hex)
1288
- return [];
1289
- const params = new URLSearchParams();
1290
- if (opts?.market !== undefined)
1397
+ return { positions: [], nextCursor: "" };
1398
+ const owner = historyOwner(hex);
1399
+ const params = historySearchParams(opts);
1400
+ if (opts.market !== undefined) {
1401
+ if (!Number.isInteger(opts.market) ||
1402
+ opts.market < 0 ||
1403
+ opts.market > 0x7fffffff)
1404
+ throw new Error("Invalid history market");
1291
1405
  params.set("market", String(opts.market));
1292
- if (opts?.fromMs !== undefined)
1293
- params.set("from", String(opts.fromMs));
1294
- if (opts?.toMs !== undefined)
1295
- params.set("to", String(opts.toMs));
1296
- if (opts?.limit !== undefined)
1297
- params.set("limit", String(opts.limit));
1298
- const qs = params.toString();
1299
- const url = `${this.readBaseUrl}/v1/history/positions/${hex}${qs ? `?${qs}` : ""}`;
1300
- const json = await fetchApiArray(url);
1301
- return json.map((row) => ({
1302
- owner: String(row.owner ?? ""),
1303
- market: String(row.market ?? ""),
1304
- side: String(row.side ?? ""),
1305
- entryPrice: String(row.entry_price ?? "0"),
1306
- size: String(row.size ?? "0"),
1307
- blockHeight: Number(row.block_height ?? 0),
1308
- timestamp: Number(row.timestamp ?? 0),
1309
- }));
1406
+ }
1407
+ const query = params.toString();
1408
+ const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/positions/${owner}${query ? `?${query}` : ""}`);
1409
+ return decodeHistoryPositionsPage(json, owner, opts.market);
1310
1410
  }
1311
1411
  /**
1312
1412
  * Executed fills for an owner, newest first, keyset-paged. The endpoint
@@ -1400,8 +1500,8 @@ export class ExchangeClient {
1400
1500
  *
1401
1501
  * Auth: account streams require auth only when the gateway runs with
1402
1502
  * `--api-key`. A browser `WebSocket` cannot send the `X-Api-Key` header, so
1403
- * the SDK uses the gateway's signed-query auth instead — when a private key
1404
- * is loaded (`setPrivateKey`) it signs the `ProofExchange-account-events-v1`
1503
+ * the SDK uses the gateway's signed-query auth instead — when a private key or external signer
1504
+ * is connected it signs the `ProofExchange-account-events-v1`
1405
1505
  * message and appends `public_key` / `signature` / `timestamp_ms`. Against
1406
1506
  * an unauthenticated gateway (e.g. devnet) the owner alone is enough.
1407
1507
  *
@@ -1416,13 +1516,10 @@ export class ExchangeClient {
1416
1516
  const params = new URLSearchParams({ owner: ownerHex });
1417
1517
  if (afterId > 0n)
1418
1518
  params.set("after_id", afterId.toString());
1419
- if (this.privateKey && this.publicKey) {
1420
- const chainId = await this.resolveChainId();
1421
- const timestampMs = BigInt(Date.now());
1422
- const msg = accountWsAuthMessage(chainId, ownerHex, afterId, timestampMs);
1423
- params.set("public_key", bytesToHex(this.publicKey));
1424
- params.set("signature", bytesToHex(sign(this.privateKey, msg)));
1425
- params.set("timestamp_ms", timestampMs.toString());
1519
+ if (opts.auth !== false && (this.privateKey || this.externalSigner)) {
1520
+ const auth = await this.accountAuth(ownerHex, afterId);
1521
+ for (const [key, value] of Object.entries(auth))
1522
+ params.set(key, String(value));
1426
1523
  }
1427
1524
  return `${this.wsUrl}/account-events?${params.toString()}`;
1428
1525
  };
@@ -1536,8 +1633,41 @@ export class ExchangeClient {
1536
1633
  void connect();
1537
1634
  return unsubscribe;
1538
1635
  }
1636
+ /** Shared multiplexed /ws feed. Options apply on first creation only.
1637
+ * Reconnect restores snapshots, not missed events. Default auth reads the current signer.
1638
+ */
1639
+ feed(opts = {}) {
1640
+ if (!this.gatewayFeed) {
1641
+ let base = this.wsUrl;
1642
+ if (!base && typeof globalThis.location !== "undefined")
1643
+ base = globalThis.location.origin.replace(/^http/, "ws");
1644
+ this.gatewayFeed = new GatewayFeed({
1645
+ url: `${base}/ws`,
1646
+ accountAuth: async (owner) => this.privateKey || this.externalSigner ? this.accountAuth(owner) : {},
1647
+ headers: this.apiKey ? { "X-Api-Key": this.apiKey } : undefined,
1648
+ ...opts,
1649
+ });
1650
+ }
1651
+ return this.gatewayFeed;
1652
+ }
1653
+ /** Account snapshot plus live stream, with auth renewed per reconnect. */
1654
+ subscribeAccount(onFrame, opts = {}) {
1655
+ const owner = opts.owner ?? this.addressHex;
1656
+ if (!owner)
1657
+ throw new Error("No account owner available");
1658
+ return this.feed().subscribeAccount(owner, onFrame, async (address) => opts.auth !== false && (this.privateKey || this.externalSigner)
1659
+ ? this.accountAuth(address)
1660
+ : {});
1661
+ }
1662
+ subscribeOrderbook(market, onFrame) {
1663
+ return this.feed().subscribeOrderbook(market, onFrame);
1664
+ }
1665
+ subscribeTrades(market, onFrame) {
1666
+ return this.feed().subscribeTrades(market, onFrame);
1667
+ }
1539
1668
  /** Close every open WebSocket stream and stop their reconnect loops. */
1540
1669
  disconnect() {
1670
+ this.gatewayFeed?.close();
1541
1671
  for (const unsub of [...this.activeStreams])
1542
1672
  unsub();
1543
1673
  }
@@ -1688,6 +1818,57 @@ function deriveNodeUrl(gatewayUrl, fallbackPort) {
1688
1818
  function computeCometTxHash(txBytes) {
1689
1819
  return bytesToHex(sha256(txBytes)).toUpperCase();
1690
1820
  }
1821
+ /** Only a fixed, known set of (HTTP status, message) pairs is hashless proof
1822
+ * of a pre-admission refusal — mirrors
1823
+ * `crates/proof-trading-sdk/src/gateway/mod.rs::pre_admission_refusal`
1824
+ * exactly for the statuses reached here (200, 503). ExchangeResponse::err
1825
+ * omits admission/verdict and rate-limit fields, but the shape alone is not
1826
+ * enough: an unrecognized message in that same shape can come from a generic
1827
+ * failure (an intermediary, a proxy) rather than the gateway's own refusal
1828
+ * path, and contradictory or unknown evidence must not become a terminal
1829
+ * refusal for a transaction that may have executed. */
1830
+ const PRE_ADMISSION_REFUSAL_FIELDS = new Set([
1831
+ "status",
1832
+ "error",
1833
+ "mode",
1834
+ "retryAfterMs",
1835
+ ]);
1836
+ function preAdmissionRefusal(status, value) {
1837
+ if (!value || typeof value !== "object" || Array.isArray(value))
1838
+ return;
1839
+ const body = value;
1840
+ // Mirrors `RefusalRead`'s `#[serde(deny_unknown_fields)]`: any field
1841
+ // outside this exact set — including ones this SDK doesn't know about
1842
+ // yet — makes the body unrecognized, not refusal evidence.
1843
+ if (body.status !== "error" ||
1844
+ typeof body.error !== "string" ||
1845
+ Object.keys(body).some((key) => !PRE_ADMISSION_REFUSAL_FIELDS.has(key)))
1846
+ return undefined;
1847
+ if (status === 503 &&
1848
+ body.error === "maintenance: signed writes are not open") {
1849
+ if (body.retryAfterMs !== undefined)
1850
+ return undefined;
1851
+ return body.mode === "paused" || body.mode === "cancel-only"
1852
+ ? body.error
1853
+ : undefined;
1854
+ }
1855
+ if (body.mode !== undefined || body.retryAfterMs !== undefined)
1856
+ return undefined;
1857
+ if (status === 503 &&
1858
+ (body.error === "service overloaded" ||
1859
+ body.error === "service unavailable"))
1860
+ return body.error;
1861
+ if (status === 200 &&
1862
+ (body.error === "invalid request body" ||
1863
+ body.error === "invalid action parameters" ||
1864
+ body.error === "invalid base64 in action field" ||
1865
+ body.error === "invalid signature" ||
1866
+ body.error === "internal encoding error" ||
1867
+ body.error ===
1868
+ "action type 0x1d is proposer-only and cannot enter through the gateway"))
1869
+ return body.error;
1870
+ return undefined;
1871
+ }
1691
1872
  async function readGatewayBody(res) {
1692
1873
  const raw = await res.text();
1693
1874
  if (!raw)
@@ -1801,4 +1982,49 @@ function decodeMarketConfig(raw) {
1801
1982
  maxOpenInterest: optBig(raw[24]),
1802
1983
  };
1803
1984
  }
1985
+ /** Copy protocol inputs without structuredClone or cross-realm instanceof checks. */
1986
+ function cloneSigningInput(value) {
1987
+ if (ArrayBuffer.isView(value) &&
1988
+ Object.prototype.toString.call(value) === "[object Uint8Array]") {
1989
+ const bytes = value;
1990
+ return new Uint8Array(bytes);
1991
+ }
1992
+ if (Array.isArray(value))
1993
+ return value.map(cloneSigningInput);
1994
+ if (value && typeof value === "object") {
1995
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, cloneSigningInput(v)]));
1996
+ }
1997
+ return value;
1998
+ }
1999
+ /** Abort interrupts the sleep; callers inspect the signal for their own result policy. */
2000
+ function abortableDelay(ms, signal) {
2001
+ if (signal?.aborted)
2002
+ return Promise.resolve();
2003
+ return new Promise((resolve) => {
2004
+ const done = () => {
2005
+ clearTimeout(timer);
2006
+ signal?.removeEventListener("abort", done);
2007
+ resolve();
2008
+ };
2009
+ const timer = setTimeout(done, ms);
2010
+ signal?.addEventListener("abort", done, { once: true });
2011
+ });
2012
+ }
2013
+ /** Per-read deadline with explicit cleanup, without AbortSignal.any/timeout. */
2014
+ function readDeadline(ms, parent) {
2015
+ const controller = new AbortController();
2016
+ const abort = () => controller.abort(parent?.reason);
2017
+ if (parent?.aborted)
2018
+ abort();
2019
+ else
2020
+ parent?.addEventListener("abort", abort, { once: true });
2021
+ const timer = setTimeout(() => controller.abort(), ms);
2022
+ return {
2023
+ signal: controller.signal,
2024
+ dispose() {
2025
+ clearTimeout(timer);
2026
+ parent?.removeEventListener("abort", abort);
2027
+ },
2028
+ };
2029
+ }
1804
2030
  //# sourceMappingURL=client.js.map