@proof-labs/trading-sdk 4.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 (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +391 -0
  3. package/dist/client.d.ts +640 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/client.js +1730 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/codec-adapter.d.ts +33 -0
  8. package/dist/codec-adapter.d.ts.map +1 -0
  9. package/dist/codec-adapter.js +419 -0
  10. package/dist/codec-adapter.js.map +1 -0
  11. package/dist/codec.d.ts +137 -0
  12. package/dist/codec.d.ts.map +1 -0
  13. package/dist/codec.js +229 -0
  14. package/dist/codec.js.map +1 -0
  15. package/dist/crypto.d.ts +78 -0
  16. package/dist/crypto.d.ts.map +1 -0
  17. package/dist/crypto.js +145 -0
  18. package/dist/crypto.js.map +1 -0
  19. package/dist/errors.d.ts +122 -0
  20. package/dist/errors.d.ts.map +1 -0
  21. package/dist/errors.js +397 -0
  22. package/dist/errors.js.map +1 -0
  23. package/dist/governance-query.d.ts +47 -0
  24. package/dist/governance-query.d.ts.map +1 -0
  25. package/dist/governance-query.js +525 -0
  26. package/dist/governance-query.js.map +1 -0
  27. package/dist/index.d.ts +11 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +22 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/testing.d.ts +25 -0
  32. package/dist/testing.d.ts.map +1 -0
  33. package/dist/testing.js +22 -0
  34. package/dist/testing.js.map +1 -0
  35. package/dist/trigger-history.d.ts +9 -0
  36. package/dist/trigger-history.d.ts.map +1 -0
  37. package/dist/trigger-history.js +442 -0
  38. package/dist/trigger-history.js.map +1 -0
  39. package/dist/triggers.d.ts +15 -0
  40. package/dist/triggers.d.ts.map +1 -0
  41. package/dist/triggers.js +399 -0
  42. package/dist/triggers.js.map +1 -0
  43. package/dist/tx-result.d.ts +53 -0
  44. package/dist/tx-result.d.ts.map +1 -0
  45. package/dist/tx-result.js +58 -0
  46. package/dist/tx-result.js.map +1 -0
  47. package/dist/types.d.ts +2085 -0
  48. package/dist/types.d.ts.map +1 -0
  49. package/dist/types.js +121 -0
  50. package/dist/types.js.map +1 -0
  51. package/dist/wasm/proof_trading_sdk_wasm.d.ts +98 -0
  52. package/dist/wasm/proof_trading_sdk_wasm.js +698 -0
  53. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm +0 -0
  54. package/dist/wasm/proof_trading_sdk_wasm_bg.wasm.d.ts +19 -0
  55. package/dist/wasm-loader.d.ts +42 -0
  56. package/dist/wasm-loader.d.ts.map +1 -0
  57. package/dist/wasm-loader.js +95 -0
  58. package/dist/wasm-loader.js.map +1 -0
  59. package/package.json +72 -0
package/dist/client.js ADDED
@@ -0,0 +1,1730 @@
1
+ import { signAndEncode } from "./codec.js";
2
+ import { ready as initWasm } from "./wasm-loader.js";
3
+ import { txEngineError, txFromEngineCode, txOk, txTimeout, txTransportError, } from "./tx-result.js";
4
+ import { getPublicKey, pubkeyToOwner, ownerToHex, bytesToHex, sign, UNBOUND_CHAIN_ID, chainIdFromString, } from "./crypto.js";
5
+ import { decodeAdminSignerRegistryInfo, decodeImpactMarketInfo, decodeProposalPage, } from "./governance-query.js";
6
+ import { Decoder } from "@msgpack/msgpack";
7
+ import { sha256 } from "@noble/hashes/sha2.js";
8
+ import { decodePositionTriggerInfos, decodeTriggerMarketConfigInfos, decodeTriggerStatusJson, validateCancelPositionTriggers, validateSetPositionTriggers, } from "./triggers.js";
9
+ import { decodePositionTriggerHistoryPage, decodeTriggerMarketHistoryPage, positionTriggerHistorySearchParams, triggerMarketHistorySearchParams, validateTriggerHistoryMarket, } from "./trigger-history.js";
10
+ const msgpackDecoder = new Decoder({ useBigInt64: true });
11
+ /**
12
+ * Fetch the 32-byte chain_id binding from a CometBFT RPC's `/status`
13
+ * endpoint. Hashes `result.node_info.network` via `chainIdFromString`.
14
+ *
15
+ * `ExchangeClient` resolves this lazily on first submit and caches it
16
+ * — most callers don't need this directly. Use it from offline tooling
17
+ * (raw `signAndEncode` callers, gateway-side helpers) that build wire
18
+ * bytes without going through a client instance.
19
+ */
20
+ export async function fetchChainId(rpcUrl) {
21
+ const res = await fetch(`${rpcUrl}/status`);
22
+ if (!res.ok)
23
+ throw new Error(`/status returned HTTP ${res.status}`);
24
+ const json = (await res.json());
25
+ const network = json.result?.node_info?.network;
26
+ if (!network) {
27
+ throw new Error("/status response missing result.node_info.network");
28
+ }
29
+ return chainIdFromString(network);
30
+ }
31
+ export class ExchangeClient {
32
+ rpcUrl;
33
+ apiUrl;
34
+ gatewayUrl;
35
+ useGateway;
36
+ apiKey;
37
+ wsUrl;
38
+ /**
39
+ * 32-byte chain_id binding for v3 signatures (audit B4). `null` until
40
+ * either an explicit `opts.chainId` is hashed in the constructor or
41
+ * `resolveChainId()` fetches `${chainBase}/status` (the gateway's
42
+ * `/v1/status`, or `${rpcUrl}/status` on the direct path) on first submit.
43
+ */
44
+ chainId;
45
+ allowUnbound;
46
+ /** Single-flight guard so concurrent submits share one /status fetch. */
47
+ chainIdPromise = null;
48
+ privateKey = null;
49
+ publicKey = null;
50
+ address = null;
51
+ addressHex = null;
52
+ lastTimestampNonce = 0n;
53
+ /** Unsubscribe handles for every open WebSocket stream, so `disconnect()`
54
+ * can tear them all down at once. */
55
+ activeStreams = new Set();
56
+ /**
57
+ * In-flight DeliverTx verification promises spawned by submitTx. Awaiting
58
+ * this set lets callers serialize against block inclusion when they need to;
59
+ * timestamp nonces do not require drift reconciliation.
60
+ */
61
+ pendingVerifies = new Set();
62
+ /**
63
+ * Completed DeliverTx results collected by background verifiers. Cleared on
64
+ * each `awaitPendingVerifies()` call. Non-zero code entries indicate a tx
65
+ * passed CheckTx but failed at inclusion time — the caller should handle
66
+ * these (e.g. retry or log).
67
+ */
68
+ deliveryResults = [];
69
+ /**
70
+ * When true, submitTx is the safe-by-default fire-and-spawn-verifier mode.
71
+ * Callers that need maximum throughput and don't need inclusion polling can
72
+ * flip this off via setUnsafeFastSubmit(true).
73
+ */
74
+ autoVerifyDelivery = true;
75
+ constructor(opts = {}) {
76
+ // `gatewayUrl` is the single source of truth for where the SDK points.
77
+ // Everything else is derived from it. The direct-node URLs (`rpcUrl`,
78
+ // `apiUrl`) are only consulted on the internal `useGateway: false`
79
+ // path; when omitted they are derived from the gateway by remapping
80
+ // the conventional local gateway port (9080) to the node ports
81
+ // (26657 for CometBFT RPC, 8080 for the Go API). Those port remaps are
82
+ // best-effort fallbacks — deployments that differ should pass `rpcUrl`
83
+ // / `apiUrl` explicitly.
84
+ this.gatewayUrl = stripTrailingSlash(opts.gatewayUrl ?? "https://api.dev.proof.trade");
85
+ this.useGateway = opts.useGateway ?? true;
86
+ this.rpcUrl = stripTrailingSlash(opts.rpcUrl ?? deriveNodeUrl(this.gatewayUrl, "26657"));
87
+ this.apiUrl = stripTrailingSlash(opts.apiUrl ?? deriveNodeUrl(this.gatewayUrl, "8080"));
88
+ this.apiKey = opts.apiKey ?? null;
89
+ // WebSocket base URL (no path). Per-stream methods append the channel
90
+ // path (`/account-events`, `/orderbook-deltas`). Mirrors the Python SDK,
91
+ // which derives the WS base by swapping the gateway URL's scheme. Local
92
+ // stacks whose WS listener is on a different port must pass `wsUrl`.
93
+ this.wsUrl = stripTrailingSlash(opts.wsUrl ??
94
+ (this.useGateway ? this.gatewayUrl : this.rpcUrl).replace(/^http/, "ws"));
95
+ // Bind chainId eagerly when supplied, else leave null. On the direct
96
+ // path resolveChainId() fetches /status on first submit; on the gateway
97
+ // path chainId must be pinned (the gateway does not serve /status).
98
+ this.chainId = opts.chainId ? chainIdFromString(opts.chainId) : null;
99
+ this.allowUnbound = opts.allowUnbound ?? false;
100
+ void opts.concurrentNonces;
101
+ }
102
+ /**
103
+ * Base URL for read/query endpoints (`/v1/*`). Routes through the
104
+ * gateway under the default `useGateway: true`; only the internal
105
+ * direct-node path (`useGateway: false`) targets the bare `apiUrl`.
106
+ */
107
+ get readBaseUrl() {
108
+ return this.useGateway ? this.gatewayUrl : this.apiUrl;
109
+ }
110
+ /**
111
+ * URL for the transaction-status lookup by hash. On the gateway path
112
+ * (default) this is the gateway's native `/v1/tx/{hash}` route, which
113
+ * proxies CometBFT's `/tx?hash=` and returns the body verbatim. On the
114
+ * internal direct-node path (`useGateway: false`) it is CometBFT's native
115
+ * `/tx?hash=0x{hash}`. Both yield the same `{ result: { tx_result, height } }`
116
+ * shape, so callers parse the response identically.
117
+ */
118
+ txStatusUrl(txHash) {
119
+ return this.useGateway
120
+ ? `${this.gatewayUrl}/v1/tx/${txHash}`
121
+ : `${this.rpcUrl}/tx?hash=0x${txHash}`;
122
+ }
123
+ /**
124
+ * Base URL for CometBFT-style chain reads (`/status`, `/block`,
125
+ * `/block_results`) and the chain-id bootstrap. On the gateway path
126
+ * (default) this is the gateway's `/v1` proxy prefix — the gateway fronts
127
+ * these as `/v1/status`, `/v1/block`, `/v1/block_results` (api-gateway #69)
128
+ * and returns the CometBFT body verbatim. On the internal direct-node path
129
+ * (`useGateway: false`) it is the bare `rpcUrl`. Append the endpoint
130
+ * (`/status`, …); both paths yield the same response shape.
131
+ */
132
+ get chainBase() {
133
+ return this.useGateway ? `${this.gatewayUrl}/v1` : this.rpcUrl;
134
+ }
135
+ /**
136
+ * Resolve and cache the 32-byte chain_id binding. Idempotent and
137
+ * single-flight: concurrent callers share one in-flight promise.
138
+ *
139
+ * Resolution order:
140
+ * 1. Explicit `opts.chainId` from the constructor (already hashed) — return it.
141
+ * 2. Fetch `${chainBase}/status` (the gateway's `/v1/status`, or
142
+ * `${rpcUrl}/status` on the direct path), hash `result.node_info.network`.
143
+ * 3. On fetch failure: if `allowUnbound`, warn and use `UNBOUND_CHAIN_ID`;
144
+ * otherwise throw.
145
+ *
146
+ * Public via `ready()`. `broadcastSigned` calls this internally before every
147
+ * submit; the cache means only the first submit pays the round-trip.
148
+ */
149
+ resolveChainId() {
150
+ if (this.chainId)
151
+ return Promise.resolve(this.chainId);
152
+ if (this.chainIdPromise)
153
+ return this.chainIdPromise;
154
+ this.chainIdPromise = (async () => {
155
+ try {
156
+ // `fetchChainId` appends `/status`, so the gateway path resolves from
157
+ // `${gatewayUrl}/v1/status` and the direct path from `${rpcUrl}/status`.
158
+ const bound = await fetchChainId(this.chainBase);
159
+ this.chainId = bound;
160
+ return bound;
161
+ }
162
+ catch (err) {
163
+ // Reset so a future caller can retry (e.g. node was momentarily down).
164
+ this.chainIdPromise = null;
165
+ if (this.allowUnbound) {
166
+ console.warn(`ExchangeClient: failed to resolve chain_id from ${this.chainBase}/status ` +
167
+ `(${err.message}); falling back to UNBOUND_CHAIN_ID. ` +
168
+ "Production callers should pin chainId or fix the gateway/rpc URL.");
169
+ // Copy the shared singleton — it cannot be frozen, so caching it
170
+ // directly would let an external mutation corrupt our signing key.
171
+ const unbound = UNBOUND_CHAIN_ID.slice();
172
+ this.chainId = unbound;
173
+ return unbound;
174
+ }
175
+ throw new Error(`ExchangeClient could not resolve chain_id from ${this.chainBase}/status: ` +
176
+ `${err.message}. Pass opts.chainId explicitly, or set ` +
177
+ "opts.allowUnbound = true if you intend to sign for an unbound chain.");
178
+ }
179
+ })();
180
+ return this.chainIdPromise;
181
+ }
182
+ /**
183
+ * Pre-resolve the chain_id binding before any `submitTx` call. Surfaces
184
+ * `/status`-fetch errors at init time rather than mid-flow. Optional —
185
+ * `submitTx` resolves lazily on its own.
186
+ */
187
+ async ready() {
188
+ // Initialize the WASM codec/signing core and pre-resolve the chain_id.
189
+ await Promise.all([initWasm(), this.resolveChainId()]);
190
+ }
191
+ /**
192
+ * Return the cached chain_id binding. `null` if `ready()` hasn't run
193
+ * and no explicit `opts.chainId` was passed. Callers that bypass
194
+ * `submitTx` (e.g. signing wire bytes for an out-of-band submit
195
+ * path) should `await client.ready()` first, then use this to feed
196
+ * `signAndEncode`.
197
+ */
198
+ getChainId() {
199
+ return this.chainId;
200
+ }
201
+ // -----------------------------------------------------------------------
202
+ // Chain-id discovery
203
+ // -----------------------------------------------------------------------
204
+ // -----------------------------------------------------------------------
205
+ // Wallet management
206
+ // -----------------------------------------------------------------------
207
+ /** Set the private key for signing transactions. */
208
+ setPrivateKey(key) {
209
+ this.privateKey = key;
210
+ this.publicKey = getPublicKey(key);
211
+ this.address = pubkeyToOwner(this.publicKey);
212
+ this.addressHex = ownerToHex(this.address);
213
+ }
214
+ getAddress() {
215
+ return this.address;
216
+ }
217
+ getAddressHex() {
218
+ return this.addressHex;
219
+ }
220
+ getPublicKey() {
221
+ return this.publicKey;
222
+ }
223
+ /**
224
+ * Return the private key the client is signing with. Exposed so
225
+ * adjacent ops tools can build a signed envelope without re-loading
226
+ * the key from disk. Callers that don't need to bypass the normal
227
+ * `submitTx` path should not use this.
228
+ */
229
+ getPrivateKey() {
230
+ return this.privateKey;
231
+ }
232
+ // -----------------------------------------------------------------------
233
+ // Nonce diagnostics
234
+ // -----------------------------------------------------------------------
235
+ /** Fetch the retained timestamp nonce set from the node, for diagnostics. */
236
+ async getRecentNonces(addressHex) {
237
+ const hex = addressHex ?? this.addressHex;
238
+ if (!hex)
239
+ throw new Error("No address available");
240
+ const res = await fetch(`${this.readBaseUrl}/v1/account/${hex}/recent-nonces`);
241
+ const json = await res.json();
242
+ if (json.error)
243
+ throw new Error(json.error);
244
+ const recent = (json.recent ?? []);
245
+ return recent.map((n) => BigInt(n));
246
+ }
247
+ /**
248
+ * Allocate the next timestamp nonce.
249
+ *
250
+ * Algorithm: `max(now_ms, last_nonce + 1)` capped at `now_ms + 60s` to
251
+ * bound the growth if the clock stops ticking.
252
+ *
253
+ * Engine window: `[block_time - 2 days, block_time + 1 day]`. All four
254
+ * rejection modes (too old, too far future, replay, below oldest) map to
255
+ * code 21 `InvalidNonce`. Nonces are burned on success — no rewinding.
256
+ *
257
+ * Thread-safe only through external serialization (caller's responsibility).
258
+ */
259
+ nextTimestampNonce() {
260
+ const now = BigInt(Date.now());
261
+ const max = now + 60000n;
262
+ let next = this.lastTimestampNonce >= now ? this.lastTimestampNonce + 1n : now;
263
+ if (next > max)
264
+ next = max;
265
+ this.lastTimestampNonce = next;
266
+ return next;
267
+ }
268
+ // -----------------------------------------------------------------------
269
+ // Transaction submission
270
+ // -----------------------------------------------------------------------
271
+ /**
272
+ * Sign and submit a transaction via broadcast_tx_sync.
273
+ *
274
+ * The SDK signs each transaction with a fresh millisecond timestamp nonce
275
+ * before submitting. Whenever the response has a tx hash but no final chain
276
+ * verdict, a fire-and-forget verifier polls `/tx?hash=...` for the actual
277
+ * `DeliverTx` result. It never rewinds or resyncs nonce state: included failed
278
+ * transactions still burn their timestamp nonce by design.
279
+ *
280
+ * Callers that need to know definitively whether a tx landed should use
281
+ * `submitTxCommit`, which awaits the same verification synchronously.
282
+ *
283
+ * Callers needing to serialize against in-flight verifications (e.g. before
284
+ * issuing a tx that depends on the previous tx's effect) can call
285
+ * `awaitPendingVerifies()` first.
286
+ *
287
+ * No nonce sync call is required before the first transaction.
288
+ */
289
+ async submitTx(action) {
290
+ const r = await this.broadcastSigned(action);
291
+ // Spawn the background DeliverTx verifier only if the outcome is still
292
+ // unknown. A synchronous gateway (api-gateway#90) already returns the
293
+ // executed result, so polling for it would be pure waste — and a CheckTx
294
+ // reject is terminal, so there is nothing to verify either.
295
+ //
296
+ // The `timeout` case is the one that still needs it: the gateway broadcast
297
+ // the tx but could not report the outcome in time, so the SDK reconciles by
298
+ // hash on the caller's behalf, exactly as before.
299
+ if (this.autoVerifyDelivery && r.hash && !this.isFinalResult(r)) {
300
+ this.spawnDeliveryVerifier(r.hash);
301
+ }
302
+ return r;
303
+ }
304
+ /**
305
+ * Submit **externally signed** wire bytes — the public counterpart of
306
+ * `submitTx` for callers that never load a private key into the client
307
+ * (hardware or CLI signers, multisig proposers/approvers). Build the bytes
308
+ * with `signingMessage()` → sign anywhere → `encodeSignedTx()`; this method
309
+ * is pure transport for the result.
310
+ *
311
+ * The caller owns everything the loaded-key path normally does: the
312
+ * chain id, a fresh millisecond-timestamp `seq` (one per signature), and
313
+ * the signature itself. The bytes are deliberately treated as opaque —
314
+ * never decoded or validated here — so wire-valid action types this SDK
315
+ * build does not know yet still submit; the gateway and engine are the
316
+ * authorities that reject malformed bytes.
317
+ *
318
+ * Routes exactly like `submitTx` (gateway by default, CometBFT
319
+ * `broadcast_tx_sync` on the internal `useGateway: false` opt-out) with the
320
+ * same delivery-verification semantics: a synchronous gateway verdict is
321
+ * final and returns as-is; a hash-only ambiguous response spawns the same
322
+ * fire-and-forget `/tx?hash=` reconciliation, awaitable via
323
+ * `awaitPendingVerifies()`.
324
+ */
325
+ async submitSignedTx(txBytes) {
326
+ const r = await this.broadcastSignedBytes(txBytes);
327
+ if (this.autoVerifyDelivery && r.hash && !this.isFinalResult(r)) {
328
+ this.spawnDeliveryVerifier(r.hash);
329
+ }
330
+ return r;
331
+ }
332
+ /**
333
+ * Internal: route pre-signed wire bytes to the configured transport —
334
+ * gateway (`POST /exchange`, default) or CometBFT `broadcast_tx_sync` on
335
+ * the internal `useGateway: false` opt-out. Both submit identical bytes.
336
+ * Shared by `submitSignedTx` and `submitSignedTxCommit`.
337
+ */
338
+ async broadcastSignedBytes(txBytes) {
339
+ return this.useGateway
340
+ ? this.submitViaGateway(txBytes)
341
+ : this.submitViaCometBFT(txBytes);
342
+ }
343
+ /**
344
+ * Internal: sign + submit with a fresh timestamp nonce. Does NOT spawn a
345
+ * background verifier — the public `submitTx` adds that.
346
+ * `submitTxCommit` uses this directly so it can run its own
347
+ * synchronous verification without two pollers racing for the same
348
+ * tx hash.
349
+ *
350
+ * Routes via the gateway (`POST gatewayUrl/exchange`) when
351
+ * `useGateway` is true (default), or via CometBFT
352
+ * `broadcast_tx_sync` when false (internal-tools opt-out path).
353
+ * Both paths submit identical signed wire bytes.
354
+ */
355
+ async broadcastSigned(action) {
356
+ if (!this.privateKey)
357
+ throw new Error("No private key set");
358
+ // Initialize the WASM codec/signing core and resolve the chain_id
359
+ // concurrently; both are cached, so only the first submit pays for either.
360
+ const [chainId] = await Promise.all([this.resolveChainId(), initWasm()]);
361
+ const seq = this.nextTimestampNonce();
362
+ const txBytes = signAndEncode(chainId, action, seq, this.privateKey);
363
+ const r = this.useGateway
364
+ ? await this.submitViaGateway(txBytes)
365
+ : await this.submitViaCometBFT(txBytes);
366
+ return r;
367
+ }
368
+ /**
369
+ * Submit signed wire bytes via the public API gateway
370
+ * (`POST gatewayUrl/exchange`). Sends the **pre-signed** JSON shape
371
+ * the gateway accepts (`{"action": "<base64-wire-bytes>"}`) since
372
+ * the SDK already has the wire bytes — saves the gateway from
373
+ * re-encoding from structured JSON.
374
+ *
375
+ * The gateway re-verifies the signature, applies rate limiting and,
376
+ * when configured with `--api-key`, checks the `X-Api-Key` header.
377
+ * On success it forwards the wire bytes to CometBFT's
378
+ * `broadcast_tx_sync`.
379
+ *
380
+ * The gateway response is an `ExchangeResponse`: a structured chain verdict
381
+ * carries `code` and optionally `height`/`events`; an admitted-but-ambiguous
382
+ * submission carries `txHash` without `code` and must be reconciled. We map
383
+ * every shape to `TxResult`. Engine rejections retain the compatibility error
384
+ * string `"<code>: <message>"`, while the structured `code` is authoritative.
385
+ * For transport-level failures (rate limit, auth, etc.) we synthesize a code
386
+ * from the HTTP status.
387
+ */
388
+ async submitViaGateway(txBytes) {
389
+ const txHash = computeCometTxHash(txBytes);
390
+ const headers = {
391
+ "Content-Type": "application/json",
392
+ };
393
+ if (this.apiKey)
394
+ headers["X-Api-Key"] = this.apiKey;
395
+ const body = JSON.stringify({ action: toBase64(txBytes) });
396
+ const res = await fetch(`${this.gatewayUrl}/exchange`, {
397
+ method: "POST",
398
+ headers,
399
+ body,
400
+ });
401
+ const gatewayBody = await readGatewayBody(res);
402
+ // Auth/rate-limit transport failures don't have a JSON body the
403
+ // engine produced — synthesize an HTTP-status code and tag the result
404
+ // `outcome: "transport"` so callers don't read it as an ExecError.
405
+ if (res.status === 401) {
406
+ return txTransportError(401, gatewayBody.error ?? "unauthorized: invalid or missing X-Api-Key");
407
+ }
408
+ if (res.status === 429) {
409
+ return txTransportError(429, gatewayBody.error ?? gatewayBody.raw ?? "rate limited by gateway");
410
+ }
411
+ if (res.status === 413) {
412
+ return txTransportError(413, gatewayBody.error ??
413
+ gatewayBody.raw ??
414
+ "request body exceeds max size (default 8192 bytes)");
415
+ }
416
+ if (res.status >= 500) {
417
+ return txTransportError(500, gatewayBody.error
418
+ ? `gateway error: ${gatewayBody.error}`
419
+ : gatewayBody.raw
420
+ ? `gateway error: ${res.status} ${res.statusText}: ${gatewayBody.raw}`
421
+ : `gateway error: ${res.status} ${res.statusText}`);
422
+ }
423
+ if (!res.ok) {
424
+ const errMsg = gatewayBody.error ??
425
+ gatewayBody.raw ??
426
+ `gateway returned HTTP ${res.status} ${res.statusText}`;
427
+ // Non-JSON / unexpected HTTP error with no engine body — transport, not
428
+ // an ExecError. `code` stays 1 for back-compat; `outcome` disambiguates.
429
+ return txTransportError(1, errMsg);
430
+ }
431
+ const json = gatewayBody.json;
432
+ // The gateway is synchronous on the on-chain result (api-gateway#90): it
433
+ // parks the response on the tx hash and answers with the chain's own
434
+ // `code` / `log` / `height` / `events`. A body carrying a `height` is a
435
+ // FINISHED verdict — the tx is in a block and there is nothing left to
436
+ // poll for, so `submitTx` skips its background verifier and
437
+ // `submitTxCommit` returns immediately instead of polling `/tx?hash=` for
438
+ // up to 9 seconds.
439
+ //
440
+ // Older gateways answer `{status: "ok"}` with no `code`/`height`, so the
441
+ // absence of those fields still means "CheckTx accepted, execution
442
+ // unknown" and the polling paths below stay exactly as they were. That
443
+ // fallback is what makes this safe against a gateway that has not been
444
+ // upgraded yet.
445
+ if (typeof json?.code === "number") {
446
+ const hash = json.txHash ?? txHash;
447
+ // `height` present → committed: the code IS the ExecTxResult code.
448
+ // `height` absent → CheckTx reject: never entered a block, and equally
449
+ // terminal — no DeliverTx will ever run for it.
450
+ return txFromEngineCode(json.code, {
451
+ hash,
452
+ height: json.height,
453
+ log: json.log ?? json.error,
454
+ events: json.events,
455
+ });
456
+ }
457
+ if (json?.status === "ok") {
458
+ // Legacy gateway: CheckTx ack only, execution still unknown.
459
+ return txOk({ hash: txHash });
460
+ }
461
+ // `status: error` with a `txHash` but NO `code` is not a rejection — it is
462
+ // the gateway saying "I broadcast this and could not tell you the outcome
463
+ // in time" (park deadline exceeded, a byte-identical tx already in flight,
464
+ // or a result it could not parse). The tx may well still commit, so this is
465
+ // a `timeout` outcome to be reconciled by hash, NOT an engine error. Calling
466
+ // it an engine error here would report a phantom rejection for an order
467
+ // that is about to fill.
468
+ if (json?.txHash) {
469
+ return txTimeout(json.txHash, json.error ?? "gateway returned no on-chain result; reconcile by hash");
470
+ }
471
+ // Fallback: the code embedded in the string as "<engine_code>: <message>".
472
+ // The gateway still emits this format for compatibility, so this path also
473
+ // covers a pre-#90 gateway that sends ONLY the string. Parse the leading code;
474
+ // if missing, surface 1 (DecodeError) as the conservative default.
475
+ const errMsg = json?.error ?? gatewayBody.raw ?? "unknown gateway error";
476
+ const code = parseLeadingErrorCode(errMsg) ?? 1;
477
+ return txEngineError(code, { log: errMsg });
478
+ }
479
+ /**
480
+ * Whether a `TxResult` is already final — i.e. nothing is gained by polling
481
+ * for it.
482
+ *
483
+ * A `height` means the tx executed in a block (the synchronous gateway
484
+ * response carries it). An `engine` outcome without a height is a CheckTx
485
+ * reject: it never entered a block and never will, so DeliverTx will not run.
486
+ * A `transport` failure never reached the chain at all.
487
+ */
488
+ isFinalResult(r) {
489
+ return (r.height !== undefined ||
490
+ r.outcome === "engine" ||
491
+ r.outcome === "transport");
492
+ }
493
+ /**
494
+ * Submit signed wire bytes via CometBFT `broadcast_tx_sync`. Used
495
+ * when `useGateway` is false (internal-tools opt-out). Bypasses
496
+ * gateway auth/rate-limit and goes directly to CometBFT.
497
+ */
498
+ async submitViaCometBFT(txBytes) {
499
+ const b64 = toBase64(txBytes);
500
+ const res = await fetch(this.rpcUrl, {
501
+ method: "POST",
502
+ headers: { "Content-Type": "application/json" },
503
+ body: JSON.stringify({
504
+ jsonrpc: "2.0",
505
+ id: 1,
506
+ method: "broadcast_tx_sync",
507
+ params: { tx: b64 },
508
+ }),
509
+ });
510
+ const json = await res.json();
511
+ if (json.error) {
512
+ throw new Error(json.error.message ?? JSON.stringify(json.error));
513
+ }
514
+ const r = json.result;
515
+ return txFromEngineCode(r.code, { hash: r.hash, log: r.log });
516
+ }
517
+ /**
518
+ * Internal: spawn a fire-and-forget verifier that polls /tx?hash for the
519
+ * DeliverTx result. Timestamp nonces are intentionally not reconciled on
520
+ * DeliverTx failure or timeout.
521
+ * The promise is added to `pendingVerifies` so callers can await it via
522
+ * `awaitPendingVerifies()` when they need synchronization.
523
+ *
524
+ * The cleanup (Set deletion) is performed INSIDE the verifier's finally
525
+ * block rather than via a chained .finally() so there's no microtask race
526
+ * between p settling and the awaitPendingVerifies() loop seeing size==0.
527
+ */
528
+ spawnDeliveryVerifier(txHash) {
529
+ let self;
530
+ const verify = async () => {
531
+ try {
532
+ // Poll up to 5 s — enough for normal block time (~1 s).
533
+ const deadline = Date.now() + 5_000;
534
+ let pollDelay = 250;
535
+ while (Date.now() < deadline) {
536
+ await new Promise((r) => setTimeout(r, pollDelay));
537
+ pollDelay = Math.min(pollDelay + 100, 600);
538
+ try {
539
+ const res = await fetch(this.txStatusUrl(txHash));
540
+ const json = await res.json();
541
+ const txResult = json.result?.tx_result;
542
+ if (txResult) {
543
+ const code = txResult.code ?? 0;
544
+ const height = json.result.height
545
+ ? Number(json.result.height)
546
+ : undefined;
547
+ this.deliveryResults.push(txFromEngineCode(code, {
548
+ hash: txHash,
549
+ height,
550
+ log: txResult.log ?? "",
551
+ events: txResult.events,
552
+ }));
553
+ return;
554
+ }
555
+ // Tx not yet indexed — keep polling.
556
+ }
557
+ catch {
558
+ // Network blip — retry.
559
+ }
560
+ }
561
+ // Timed out without seeing the result. The timestamp nonce may have
562
+ // landed or may be reusable only if never included; do not rewind.
563
+ }
564
+ finally {
565
+ this.pendingVerifies.delete(self);
566
+ }
567
+ };
568
+ self = verify();
569
+ this.pendingVerifies.add(self);
570
+ }
571
+ /**
572
+ * Wait for every in-flight DeliverTx verifier spawned by submitTx to settle,
573
+ * then return the collected delivery results. Each entry is the DeliverTx
574
+ * result observed by the background poller — `code === 0` means the tx was
575
+ * included successfully, non-zero means it passed CheckTx but failed at
576
+ * inclusion. Call this before a tx that depends on a previous tx's state
577
+ * having actually landed.
578
+ *
579
+ * Results are drained from the internal buffer: subsequent calls return
580
+ * only verifications that completed *after* the previous drain.
581
+ */
582
+ async awaitPendingVerifies() {
583
+ // Snapshot then await — verifiers self-remove from the set in their
584
+ // finally blocks, but new ones could be spawned mid-wait. Loop until
585
+ // the set is genuinely empty.
586
+ while (this.pendingVerifies.size > 0) {
587
+ const snapshot = Array.from(this.pendingVerifies);
588
+ await Promise.allSettled(snapshot);
589
+ }
590
+ const results = [...this.deliveryResults];
591
+ this.deliveryResults = [];
592
+ return results;
593
+ }
594
+ /**
595
+ * Opt out of background DeliverTx verification. Only use this for
596
+ * high-throughput stress workloads that do not need inclusion polling.
597
+ */
598
+ setUnsafeFastSubmit(unsafe) {
599
+ this.autoVerifyDelivery = !unsafe;
600
+ }
601
+ /**
602
+ * Submit and wait for block inclusion (slower, but confirms execution).
603
+ *
604
+ * A synchronous gateway verdict returns immediately. If the gateway only
605
+ * acknowledges CheckTx (legacy) or returns a hash-only ambiguous response,
606
+ * this falls back to polling `/tx?hash=...`. The direct-node path likewise
607
+ * uses `broadcast_tx_sync` plus polling instead of CometBFT's less reliable
608
+ * `broadcast_tx_commit` subscription.
609
+ */
610
+ async submitTxCommit(action) {
611
+ if (!this.privateKey)
612
+ throw new Error("No private key set");
613
+ // Step 1: broadcast via sync (returns after CheckTx). Use the internal
614
+ // path so we don't double-spawn a background verifier — we're going to
615
+ // do our own synchronous verification below.
616
+ const sync = await this.broadcastSigned(action);
617
+ return this.awaitCommit(sync);
618
+ }
619
+ /**
620
+ * Submit **externally signed** wire bytes and wait for block inclusion —
621
+ * the commit counterpart of `submitSignedTx`, for the same callers
622
+ * (hardware/CLI signers, multisig propose/approve) that never load a
623
+ * private key into the client. Shares `submitTxCommit`'s exact finality
624
+ * logic: a synchronous gateway verdict returns immediately; a hash-only
625
+ * ambiguous response or a legacy CheckTx-only ack falls back to polling
626
+ * `/tx?hash=...` (~9 s), scoped to THIS call — no background verifier, no
627
+ * draining the client-global `awaitPendingVerifies()` buffer. Use this
628
+ * when the caller must know definitively whether the tx landed (an
629
+ * operator action, a multisig proposal) rather than fire-and-forget.
630
+ */
631
+ async submitSignedTxCommit(txBytes) {
632
+ const sync = await this.broadcastSignedBytes(txBytes);
633
+ return this.awaitCommit(sync);
634
+ }
635
+ /**
636
+ * Internal: shared commit-semantics tail of `submitTxCommit` and
637
+ * `submitSignedTxCommit` — take a broadcast's sync result and return the
638
+ * final chain verdict, polling `/tx?hash=` only when the outcome is still
639
+ * unknown.
640
+ */
641
+ async awaitCommit(sync) {
642
+ if (this.isFinalResult(sync)) {
643
+ // Either the gateway already returned the on-chain result (the
644
+ // synchronous submit path — nothing to wait for), or the tx was rejected
645
+ // at CheckTx / never reached the chain, in which case no DeliverTx will
646
+ // ever run. This is the case H14 was filed about: a confirmed order used
647
+ // to cost a 9-second poll loop, and now costs one round-trip.
648
+ return sync;
649
+ }
650
+ if (!sync.ok && sync.outcome !== "timeout") {
651
+ return sync;
652
+ }
653
+ // Step 2: the outcome is still unknown (a pre-#90 gateway that only acks
654
+ // CheckTx, the direct-to-CometBFT path, or a gateway that broadcast the tx
655
+ // but could not report the result in time). Poll /tx?hash=... until found
656
+ // or timeout (~9 seconds).
657
+ const txHash = sync.hash;
658
+ if (!txHash) {
659
+ throw new Error("submitTx returned no tx hash");
660
+ }
661
+ const deadline = Date.now() + 9_000;
662
+ let pollDelay = 200;
663
+ while (Date.now() < deadline) {
664
+ await new Promise((r) => setTimeout(r, pollDelay));
665
+ pollDelay = Math.min(pollDelay + 100, 600);
666
+ try {
667
+ const res = await fetch(this.txStatusUrl(txHash));
668
+ const json = await res.json();
669
+ const txResult = json.result?.tx_result;
670
+ if (txResult) {
671
+ const code = txResult.code ?? 0;
672
+ return txFromEngineCode(code, {
673
+ hash: txHash,
674
+ height: json.result.height ? Number(json.result.height) : undefined,
675
+ log: txResult.log,
676
+ events: txResult.events,
677
+ });
678
+ }
679
+ // tx not yet indexed → keep polling
680
+ }
681
+ catch {
682
+ // network blip — retry
683
+ }
684
+ }
685
+ // Timed out waiting for inclusion. We don't know whether it landed, so
686
+ // do not reuse or rewind the timestamp nonce.
687
+ return txTimeout(txHash, "submitTxCommit: timed out polling /tx after 9s");
688
+ }
689
+ // -----------------------------------------------------------------------
690
+ // Convenience action builders
691
+ //
692
+ // Thin wrappers over `submitTx` for the common trader actions. Each fills
693
+ // `owner` from the loaded signer key so callers don't repeat their own
694
+ // address on every action, and returns the same `TxResult` as `submitTx`
695
+ // (CheckTx result + background DeliverTx verification). For inclusion-
696
+ // waiting semantics, build the action yourself and call `submitTxCommit`.
697
+ // -----------------------------------------------------------------------
698
+ /**
699
+ * The loaded signer's 20-byte owner address, or throw if no key is set.
700
+ * Every convenience builder needs it, so the guard lives here.
701
+ */
702
+ requireOwner() {
703
+ if (!this.address) {
704
+ throw new Error("No signer key loaded — call setPrivateKey() before submitting actions");
705
+ }
706
+ return this.address;
707
+ }
708
+ /**
709
+ * Place a limit order for the loaded signer. `owner` is supplied
710
+ * automatically. Equivalent to
711
+ * `submitTx({ type: "PlaceOrder", data: { ...params, owner } })`.
712
+ */
713
+ async placeOrder(params) {
714
+ return this.submitTx({
715
+ type: "PlaceOrder",
716
+ data: { ...params, owner: this.requireOwner() },
717
+ });
718
+ }
719
+ /** Place a market order (crosses immediately) for the loaded signer. */
720
+ async marketOrder(params) {
721
+ return this.submitTx({
722
+ type: "MarketOrder",
723
+ data: { ...params, owner: this.requireOwner() },
724
+ });
725
+ }
726
+ /** Cancel a resting order by its engine-assigned order ID. */
727
+ async cancelOrder(orderId) {
728
+ return this.submitTx({
729
+ type: "CancelOrder",
730
+ data: { orderId, owner: this.requireOwner() },
731
+ });
732
+ }
733
+ /** Cancel a resting order by the owner-scoped client order ID. */
734
+ async cancelClientOrder(clientOrderId) {
735
+ return this.submitTx({
736
+ type: "CancelClientOrder",
737
+ data: { clientOrderId, owner: this.requireOwner() },
738
+ });
739
+ }
740
+ /**
741
+ * Cancel all resting orders for the loaded signer. Pass a `market` to
742
+ * scope the cancel to one market; omit it to cancel across all markets.
743
+ */
744
+ async cancelAllOrders(market) {
745
+ return this.submitTx({
746
+ type: "CancelAllOrders",
747
+ data: { owner: this.requireOwner(), market: market ?? null },
748
+ });
749
+ }
750
+ /**
751
+ * Close the loaded signer's entire position on `market` via an
752
+ * opposite-side IOC order at oracle±spread. Idempotent on an already-flat
753
+ * position.
754
+ */
755
+ async closePosition(market) {
756
+ return this.submitTx({
757
+ type: "ClosePosition",
758
+ data: { market, owner: this.requireOwner() },
759
+ });
760
+ }
761
+ /** Atomically replace a complete SL/TP bracket. When `owner` is omitted,
762
+ * use the loaded signer; a version-active trading agent may pass the
763
+ * delegated owner explicitly. The engine remains the authorization source. */
764
+ async setPositionTriggers(params) {
765
+ const data = {
766
+ ...params,
767
+ owner: params.owner ?? this.requireOwner(),
768
+ };
769
+ validateSetPositionTriggers(data);
770
+ return this.submitTx({ type: "SetPositionTriggers", data });
771
+ }
772
+ /** Cancel the loaded signer's bracket for one exact position generation. */
773
+ async cancelPositionTriggers(market, expectedPositionEpoch, owner) {
774
+ const data = {
775
+ market,
776
+ owner: owner ?? this.requireOwner(),
777
+ expectedPositionEpoch,
778
+ };
779
+ validateCancelPositionTriggers(data);
780
+ return this.submitTx({ type: "CancelPositionTriggers", data });
781
+ }
782
+ // -----------------------------------------------------------------------
783
+ // Query endpoints
784
+ // -----------------------------------------------------------------------
785
+ /**
786
+ * Owner-scoped reads (account, open orders, withdrawal) are deliberately
787
+ * NOT exposed as GETs on the gateway — it 404s them and requires
788
+ * `POST /info` instead (see `api-gateway/src/server.rs`
789
+ * `is_public_node_path`). On the gateway path we POST the matching
790
+ * `/info` request; on the internal `useGateway: false` path we hit the
791
+ * Go API GET directly. The gateway proxies the node body verbatim, so
792
+ * both return the same `{ data: <base64-msgpack> }` shape and callers
793
+ * decode identically.
794
+ */
795
+ async queryOwnerScoped(info, nodePath) {
796
+ return this.useGateway
797
+ ? postInfoJson(this.gatewayUrl, info)
798
+ : fetchApiJson(`${this.apiUrl}${nodePath}`);
799
+ }
800
+ async queryOrderbook(market) {
801
+ const json = await fetchApiJson(`${this.readBaseUrl}/v1/orderbook/${market}`);
802
+ const bytes = fromBase64(json.data);
803
+ const raw = msgpackDecoder.decode(bytes);
804
+ const parseLevel = (arr) => ({
805
+ price: BigInt(arr[0]),
806
+ totalQty: BigInt(arr[1]),
807
+ orderCount: Number(arr[2]),
808
+ });
809
+ return {
810
+ bids: raw[0].map(parseLevel),
811
+ asks: raw[1].map(parseLevel),
812
+ };
813
+ }
814
+ /** List all registered market configs. */
815
+ async queryMarkets() {
816
+ const json = await fetchApiJson(`${this.readBaseUrl}/v1/markets`);
817
+ const bytes = fromBase64(json.data);
818
+ const raw = msgpackDecoder.decode(bytes);
819
+ return raw.map((m) => decodeMarketConfig(m));
820
+ }
821
+ /** List all impact-market families (the 5-book event structures: an
822
+ * underlying perp plus CPY/CPN/EBY/EBN children). Fail-closed like the
823
+ * governance reads: a missing envelope or a malformed row is a refusal,
824
+ * never a partially-rendered list (decoder pinned to engine golden bytes
825
+ * in governance-query.test.ts). */
826
+ async queryImpactMarkets() {
827
+ const json = await fetchApiJson(`${this.readBaseUrl}/v1/impact_markets`);
828
+ if (typeof json.data !== "string") {
829
+ throw new Error("governance decode: impact-markets response has no encoded-data envelope");
830
+ }
831
+ const raw = msgpackDecoder.decode(fromBase64(json.data));
832
+ if (!Array.isArray(raw)) {
833
+ throw new Error("governance decode: impactMarkets is not an array");
834
+ }
835
+ return raw.map((r, i) => decodeImpactMarketInfo(r, i));
836
+ }
837
+ /** Current whole-position trigger brackets for one owner. Immutable
838
+ * lifecycle history is a separate gateway/indexer query below. */
839
+ async queryPositionTriggers(addressHex) {
840
+ const hex = addressHex ?? this.addressHex;
841
+ if (!hex)
842
+ throw new Error("No address available");
843
+ if (!/^[0-9a-fA-F]{40}$/.test(hex)) {
844
+ throw new Error("trigger owner must be a 40-character hex address");
845
+ }
846
+ const path = `/v1/triggers/${hex.toLowerCase()}`;
847
+ const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
848
+ const bytes = fromBase64(requireEncodedData(json, path));
849
+ return decodePositionTriggerInfos(msgpackDecoder.decode(bytes));
850
+ }
851
+ /** Read the complete governed trigger-market policy registry. Missing
852
+ * markets are disabled; callers must never synthesize a default policy. */
853
+ async queryTriggerMarketConfigs() {
854
+ const path = "/v1/triggers/markets";
855
+ const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
856
+ const bytes = fromBase64(requireEncodedData(json, path));
857
+ return decodeTriggerMarketConfigInfos(msgpackDecoder.decode(bytes));
858
+ }
859
+ /** Read the fail-closed next-height trigger admission predicate. Heights
860
+ * are parsed from raw JSON into bigint without a lossy Number round-trip. */
861
+ async queryTriggerStatus() {
862
+ const path = "/v1/triggers/status";
863
+ const res = await fetch(`${this.readBaseUrl}${path}`);
864
+ const text = await res.text();
865
+ if (!res.ok) {
866
+ let message = `HTTP ${res.status}`;
867
+ try {
868
+ const body = JSON.parse(text);
869
+ if (typeof body.error === "string")
870
+ message = body.error;
871
+ }
872
+ catch {
873
+ // Keep the HTTP fallback for a non-JSON upstream response.
874
+ }
875
+ throw new Error(`API error: ${message}`);
876
+ }
877
+ return decodeTriggerStatusJson(text);
878
+ }
879
+ /** Immutable owner-bearing trigger lifecycle history. This always uses the
880
+ * public gateway, including when the client is configured for direct-node
881
+ * current-state reads; the node does not own indexer history. */
882
+ async queryPositionTriggerHistory(addressHex, filters = {}) {
883
+ const hex = addressHex ?? this.addressHex;
884
+ if (!hex)
885
+ throw new Error("No address available");
886
+ if (!/^[0-9a-fA-F]{40}$/.test(hex)) {
887
+ throw new Error("trigger history owner must be a 40-character hex address");
888
+ }
889
+ const canonicalOwner = hex.toLowerCase();
890
+ const params = positionTriggerHistorySearchParams(filters);
891
+ const qs = params.toString();
892
+ const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/triggers/${canonicalOwner}${qs ? `?${qs}` : ""}`);
893
+ return decodePositionTriggerHistoryPage(json, canonicalOwner, filters.market);
894
+ }
895
+ /** Shared market-level deferred/resumed trigger transitions. These are not
896
+ * duplicated into every owner's history and always route through gateway. */
897
+ async queryTriggerMarketHistory(market, filters = {}) {
898
+ validateTriggerHistoryMarket(market);
899
+ const params = triggerMarketHistorySearchParams(filters);
900
+ const qs = params.toString();
901
+ const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/trigger-markets/${market}${qs ? `?${qs}` : ""}`);
902
+ return decodeTriggerMarketHistoryPage(json, market);
903
+ }
904
+ /**
905
+ * Read the current on-chain admin signer registry via the gateway proxy
906
+ * (`GET /v1/admin/signer-registry`). The engine wraps the
907
+ * registry in an `Option`, so the proxy returns MessagePack `[registry|nil]`.
908
+ *
909
+ * Returns `null` when no registry is seeded — which means admin multisig is
910
+ * **inactive** (fail-closed), NOT an empty roster; callers must treat the two
911
+ * differently.
912
+ */
913
+ async queryAdminSignerRegistry() {
914
+ const json = await fetchApiJson(`${this.readBaseUrl}/v1/admin/signer-registry`);
915
+ const bytes = fromBase64(requireEncodedData(json, "/v1/admin/signer-registry"));
916
+ return decodeAdminSignerRegistryInfo(msgpackDecoder.decode(bytes));
917
+ }
918
+ /**
919
+ * List admin governance proposals via the gateway proxy
920
+ * (`GET /v1/proposals`). Optional `status` / `cursor` /
921
+ * `limit` are forwarded as query params (the node clamps oversized limits).
922
+ * The proxy returns MessagePack `[proposals, nextCursor|nil]`.
923
+ *
924
+ * Each proposal is decoded into a `ProposalDisplayInfo` — including the
925
+ * canonical action bytes and content hash an approving signer needs to
926
+ * rebuild their approval locally. Decoding fails closed: a proposal
927
+ * carrying an operation or status this SDK build does not know throws
928
+ * rather than being returned partially rendered.
929
+ */
930
+ async queryProposals(opts) {
931
+ const params = new URLSearchParams();
932
+ if (opts?.status)
933
+ params.set("status", opts.status);
934
+ if (opts?.cursor != null)
935
+ params.set("cursor", String(opts.cursor));
936
+ if (opts?.limit != null)
937
+ params.set("limit", String(opts.limit));
938
+ const qs = params.toString();
939
+ const json = await fetchApiJson(`${this.readBaseUrl}/v1/proposals${qs ? `?${qs}` : ""}`);
940
+ const bytes = fromBase64(requireEncodedData(json, "/v1/proposals"));
941
+ return decodeProposalPage(msgpackDecoder.decode(bytes));
942
+ }
943
+ /** Fetch open orders for an address. Returns an empty array if the
944
+ * account has no open orders.
945
+ * Each order is a 6-tuple `[id, market, owner, side, price, quantity]`
946
+ * decoded from MessagePack. */
947
+ async queryOpenOrders(addressHex) {
948
+ const hex = addressHex ?? this.addressHex;
949
+ if (!hex)
950
+ return [];
951
+ const json = await this.queryOwnerScoped({ type: "openOrders", user: hex }, `/v1/orders/${hex}`);
952
+ if (!json.data)
953
+ return [];
954
+ const bytes = fromBase64(json.data);
955
+ let decoded;
956
+ try {
957
+ decoded = msgpackDecoder.decode(bytes);
958
+ }
959
+ catch {
960
+ return [];
961
+ }
962
+ if (!Array.isArray(decoded))
963
+ return [];
964
+ return decoded.map((order) => ({
965
+ id: BigInt(order[0]),
966
+ market: Number(order[1]),
967
+ owner: toBytes(order[2]),
968
+ side: order[3],
969
+ price: BigInt(order[4]),
970
+ quantity: BigInt(order[5]),
971
+ }));
972
+ }
973
+ /** Fetch a withdrawal record by id. Returns `null` for unknown ids
974
+ * (the engine encodes "not found" as msgpack `nil`, not HTTP 404). */
975
+ async queryWithdrawal(id) {
976
+ const json = await this.queryOwnerScoped({ type: "withdrawalStatus", withdrawalId: Number(id) }, `/v1/withdrawal/${id}`);
977
+ const bytes = fromBase64(json.data);
978
+ const raw = msgpackDecoder.decode(bytes);
979
+ if (raw === null)
980
+ return null;
981
+ return {
982
+ id: BigInt(raw[0]),
983
+ owner: toBytes(raw[1]),
984
+ amount: BigInt(raw[2]),
985
+ solanaDestination: toBytes(raw[3]),
986
+ status: raw[4],
987
+ requestHeight: BigInt(raw[5]),
988
+ };
989
+ }
990
+ async queryAccount(addressHex) {
991
+ const hex = addressHex ?? this.addressHex;
992
+ if (!hex)
993
+ return null;
994
+ const json = await this.queryOwnerScoped({ type: "clearinghouseState", user: hex }, `/v1/account/${hex}`);
995
+ const bytes = fromBase64(json.data);
996
+ const raw = msgpackDecoder.decode(bytes);
997
+ const balance = BigInt(raw[0]);
998
+ const positions = (raw[1] ?? []).map((p) => {
999
+ // Optional enrichments (indices 6-13) shipped incrementally:
1000
+ // 6-11: scenario-aware brief fields, 2026-04-24 (P1 #2).
1001
+ // 12 : adlScore, 2026-04-25 (item 7 — ADL rank surface).
1002
+ // 13 : persistent position epoch (first-attach trigger input).
1003
+ // Older gateways return shorter tuples; missing fields are
1004
+ // surfaced as `undefined` so the UI can show a "—" placeholder.
1005
+ const optBig = (v) => v === undefined || v === null
1006
+ ? undefined
1007
+ : BigInt(v);
1008
+ return {
1009
+ owner: toBytes(p[0]),
1010
+ market: Number(p[1]),
1011
+ side: p[2],
1012
+ entryPrice: BigInt(p[3]),
1013
+ size: BigInt(p[4]),
1014
+ lastFundingIndex: BigInt(p[5] ?? 0),
1015
+ upnlNow: optBig(p[6]),
1016
+ mmNow: optBig(p[7]),
1017
+ imNow: optBig(p[8]),
1018
+ pnlIfFires: optBig(p[9]),
1019
+ pnlIfDies: optBig(p[10]),
1020
+ fundingSince: optBig(p[11]),
1021
+ adlScore: optBig(p[12]),
1022
+ positionEpoch: optBig(p[13]),
1023
+ };
1024
+ });
1025
+ const equity = BigInt(raw[2] ?? 0);
1026
+ const totalMm = BigInt(raw[3] ?? 0);
1027
+ const totalIm = BigInt(raw[4] ?? 0);
1028
+ const marginRatioBps = BigInt(raw[5] ?? 0);
1029
+ // Index [6] — shipped 2026-04-24 (Sprint 1 Day 2 / P1 #3). Older
1030
+ // gateways omit this field; leave bindingScenario undefined rather
1031
+ // than defaulting to [] so callers can tell "no data available"
1032
+ // from "empty (perp-only account)".
1033
+ let bindingScenario;
1034
+ if (raw[6] !== undefined) {
1035
+ bindingScenario = (raw[6] ?? []).map((e) => {
1036
+ const t = e;
1037
+ return {
1038
+ impactMarketId: Number(t[0]),
1039
+ branch: t[1],
1040
+ };
1041
+ });
1042
+ }
1043
+ // Index [7] — added 2026-05-03 (BE-45). Cumulative trading fees
1044
+ // paid (positive) or rebates received (negative). Older gateways
1045
+ // omit this field; leave feesAccrued undefined so callers can
1046
+ // distinguish "no data" from "0 fees".
1047
+ let feesAccrued;
1048
+ if (raw[7] !== undefined) {
1049
+ feesAccrued = BigInt(raw[7] ?? 0);
1050
+ }
1051
+ // Index [8] — added 2026-05-17. Rolling 30-day taker volume in
1052
+ // micro-USDC at the account's last volume update. Used by the
1053
+ // fee-tier program; older gateways omit it.
1054
+ let volume30dMicroUsdc;
1055
+ if (raw[8] !== undefined) {
1056
+ volume30dMicroUsdc = BigInt(raw[8] ?? 0);
1057
+ }
1058
+ return {
1059
+ balance,
1060
+ positions,
1061
+ equity,
1062
+ totalMm,
1063
+ totalIm,
1064
+ marginRatioBps,
1065
+ bindingScenario,
1066
+ feesAccrued,
1067
+ volume30dMicroUsdc,
1068
+ };
1069
+ }
1070
+ /** Convenience: fetch just the USDC balance (microUSDC) for an address. */
1071
+ async queryBalance(addressHex) {
1072
+ const acct = await this.queryAccount(addressHex);
1073
+ return acct ? acct.balance : null;
1074
+ }
1075
+ /** Convenience: fetch just the equity (microUSDC) for an address. */
1076
+ async queryEquity(addressHex) {
1077
+ const acct = await this.queryAccount(addressHex);
1078
+ return acct ? acct.equity : null;
1079
+ }
1080
+ async queryHealth() {
1081
+ const res = await fetch(`${this.readBaseUrl}/v1/health`);
1082
+ return res.json();
1083
+ }
1084
+ /** Fetch the auto-deleveraging queue for a market — profitable positions
1085
+ * ranked by `adlScore` desc (highest first). Empty array if the market has
1086
+ * no profitable positions. Routes through the gateway's `/v1/adl/queue`. */
1087
+ async queryAdlQueue(market) {
1088
+ const res = await fetch(`${this.readBaseUrl}/v1/adl/queue/${market}`);
1089
+ const json = await res.json();
1090
+ if (json.error)
1091
+ return [];
1092
+ const bytes = fromBase64(json.data);
1093
+ const raw = msgpackDecoder.decode(bytes);
1094
+ if (!Array.isArray(raw))
1095
+ return [];
1096
+ return raw.map((row) => ({
1097
+ owner: toBytes(row[0]),
1098
+ market: Number(row[1]),
1099
+ side: row[2],
1100
+ size: BigInt(row[3]),
1101
+ upnlNow: BigInt(row[4]),
1102
+ adlScore: BigInt(row[5]),
1103
+ }));
1104
+ }
1105
+ /** One-round-trip market summary (last / 24h volume / 24h change + funding
1106
+ * and top-of-book blobs). Returns `null` if the market is unknown. Routes
1107
+ * through the gateway's `/v1/ticker`. */
1108
+ async queryTicker(market) {
1109
+ const res = await fetch(`${this.readBaseUrl}/v1/ticker/${market}`);
1110
+ if (!res.ok)
1111
+ return null;
1112
+ const row = (await res.json());
1113
+ return {
1114
+ market: String(row.market ?? market),
1115
+ lastPrice: String(row.last_price ?? "0"),
1116
+ volume24hContracts: String(row.volume_24h_contracts ?? "0"),
1117
+ change24hBps: String(row.change_24h_bps ?? "0"),
1118
+ fundingMsgpackB64: String(row.funding_msgpack_b64 ?? ""),
1119
+ orderbookMsgpackB64: String(row.orderbook_msgpack_b64 ?? ""),
1120
+ openInterest: row.open_interest === null || row.open_interest === undefined
1121
+ ? null
1122
+ : String(row.open_interest),
1123
+ };
1124
+ }
1125
+ /** Per-user deposit log — every `deposit_confirmed` event for this
1126
+ * owner, newest first. Feeds Portfolio EquityChart equity-over-time
1127
+ * reconstruction (P2 #6). */
1128
+ async queryHistoryDeposits(addressHex, opts) {
1129
+ return this.queryHistoryCashFlow("deposits", addressHex, opts);
1130
+ }
1131
+ /** Per-user withdrawal lifecycle log — withdraw_requested /
1132
+ * withdrawal_confirmed / withdrawal_failed, newest first. Filter by
1133
+ * `kind` client-side if you want only pending requests. P2 #6. */
1134
+ async queryHistoryWithdrawals(addressHex, opts) {
1135
+ return this.queryHistoryCashFlow("withdrawals", addressHex, opts);
1136
+ }
1137
+ /** Internal: shared decoder for the two cash-flow endpoints. They
1138
+ * return identical row shapes (HistoryCashFlow); the difference is
1139
+ * which kinds the server includes. */
1140
+ async queryHistoryCashFlow(path, addressHex, opts) {
1141
+ const hex = addressHex ?? this.addressHex;
1142
+ if (!hex)
1143
+ return [];
1144
+ const params = new URLSearchParams();
1145
+ if (opts?.fromMs !== undefined)
1146
+ params.set("from", String(opts.fromMs));
1147
+ if (opts?.toMs !== undefined)
1148
+ params.set("to", String(opts.toMs));
1149
+ if (opts?.limit !== undefined)
1150
+ params.set("limit", String(opts.limit));
1151
+ const qs = params.toString();
1152
+ const url = `${this.readBaseUrl}/v1/history/${path}/${hex}${qs ? `?${qs}` : ""}`;
1153
+ const json = await fetchApiArray(url);
1154
+ return json.map((row) => ({
1155
+ kind: row.kind,
1156
+ owner: String(row.owner ?? ""),
1157
+ amount: String(row.amount ?? ""),
1158
+ signedDelta: String(row.signed_delta ?? "0"),
1159
+ newBalance: String(row.new_balance ?? ""),
1160
+ withdrawalId: String(row.withdrawal_id ?? ""),
1161
+ solanaTxSig: String(row.solana_tx_sig ?? ""),
1162
+ solanaDestination: String(row.solana_destination ?? ""),
1163
+ reason: String(row.reason ?? ""),
1164
+ blockHeight: Number(row.block_height ?? 0),
1165
+ timestamp: Number(row.timestamp ?? 0),
1166
+ }));
1167
+ }
1168
+ /** Per-user position-at-resolution log — each row is one settlement or
1169
+ * voided-conditional snapshot. Feeds the Portfolio "Resolved" tab
1170
+ * (P2 #7). Optional `impactMarketId` filter scopes to one event family.
1171
+ *
1172
+ * `fromMs` / `toMs` are unix-ms timestamps; omit for unbounded.
1173
+ * `limit` caps at 1000 server-side. Results are newest-first. */
1174
+ async queryHistoryResolutions(addressHex, opts) {
1175
+ const hex = addressHex ?? this.addressHex;
1176
+ if (!hex)
1177
+ return [];
1178
+ const params = new URLSearchParams();
1179
+ if (opts?.impactMarketId !== undefined)
1180
+ params.set("impact_market_id", String(opts.impactMarketId));
1181
+ if (opts?.fromMs !== undefined)
1182
+ params.set("from", String(opts.fromMs));
1183
+ if (opts?.toMs !== undefined)
1184
+ params.set("to", String(opts.toMs));
1185
+ if (opts?.limit !== undefined)
1186
+ params.set("limit", String(opts.limit));
1187
+ const qs = params.toString();
1188
+ const url = `${this.readBaseUrl}/v1/history/resolutions/${hex}${qs ? `?${qs}` : ""}`;
1189
+ const json = await fetchApiArray(url);
1190
+ return json.map((row) => ({
1191
+ kind: row.kind,
1192
+ impactMarketId: String(row.impact_market_id ?? ""),
1193
+ market: String(row.market ?? ""),
1194
+ owner: String(row.owner ?? ""),
1195
+ side: String(row.side ?? ""),
1196
+ size: String(row.size ?? ""),
1197
+ entryPrice: String(row.entry_price ?? ""),
1198
+ settlementPrice: String(row.settlement_price ?? ""),
1199
+ realizedPnl: String(row.realized_pnl ?? "0"),
1200
+ blockHeight: Number(row.block_height ?? 0),
1201
+ timestamp: Number(row.timestamp ?? 0),
1202
+ }));
1203
+ }
1204
+ /** Per-user position-history snapshot log. Each row is one
1205
+ * point-in-time snapshot persisted after a fill that changes the
1206
+ * position. A `size === "0"` row is a CLOSE event; the immediately
1207
+ * preceding non-zero snapshot for the same `(owner, market, side)`
1208
+ * carries the entry price. Feeds the trading-UI Position History tab
1209
+ * (FE-23). Optional `market` filter scopes to one book; `fromMs` /
1210
+ * `toMs` window the timestamps; `limit` caps server-side at 5000. */
1211
+ async queryHistoryPositions(addressHex, opts) {
1212
+ const hex = addressHex ?? this.addressHex;
1213
+ if (!hex)
1214
+ return [];
1215
+ const params = new URLSearchParams();
1216
+ if (opts?.market !== undefined)
1217
+ params.set("market", String(opts.market));
1218
+ if (opts?.fromMs !== undefined)
1219
+ params.set("from", String(opts.fromMs));
1220
+ if (opts?.toMs !== undefined)
1221
+ params.set("to", String(opts.toMs));
1222
+ if (opts?.limit !== undefined)
1223
+ params.set("limit", String(opts.limit));
1224
+ const qs = params.toString();
1225
+ const url = `${this.readBaseUrl}/v1/history/positions/${hex}${qs ? `?${qs}` : ""}`;
1226
+ const json = await fetchApiArray(url);
1227
+ return json.map((row) => ({
1228
+ owner: String(row.owner ?? ""),
1229
+ market: String(row.market ?? ""),
1230
+ side: String(row.side ?? ""),
1231
+ entryPrice: String(row.entry_price ?? "0"),
1232
+ size: String(row.size ?? "0"),
1233
+ blockHeight: Number(row.block_height ?? 0),
1234
+ timestamp: Number(row.timestamp ?? 0),
1235
+ }));
1236
+ }
1237
+ /**
1238
+ * Executed fills for an owner, newest first, keyset-paged. The endpoint
1239
+ * returns an envelope rather than a bare array: pass `opts.cursor` from a
1240
+ * previous page's `nextCursor` to continue; an empty `nextCursor` is the
1241
+ * last page. `fromMs` is inclusive, `toMs` exclusive (the API's uniform
1242
+ * half-open window), both epoch milliseconds. Omitting `addressHex` with
1243
+ * no bound key yields an empty page, matching the other history queries.
1244
+ */
1245
+ async queryHistoryFills(addressHex, opts) {
1246
+ const hex = addressHex ?? this.addressHex;
1247
+ if (!hex)
1248
+ return { fills: [], nextCursor: "" };
1249
+ const params = new URLSearchParams();
1250
+ if (opts?.market !== undefined)
1251
+ params.set("market", String(opts.market));
1252
+ if (opts?.fromMs !== undefined)
1253
+ params.set("from", String(opts.fromMs));
1254
+ if (opts?.toMs !== undefined)
1255
+ params.set("to", String(opts.toMs));
1256
+ if (opts?.limit !== undefined)
1257
+ params.set("limit", String(opts.limit));
1258
+ if (opts?.cursor !== undefined && opts.cursor !== "") {
1259
+ params.set("cursor", opts.cursor);
1260
+ }
1261
+ const qs = params.toString();
1262
+ const url = `${this.readBaseUrl}/v1/history/fills/${hex}${qs ? `?${qs}` : ""}`;
1263
+ const res = await fetch(url);
1264
+ const json = (await res.json());
1265
+ const body = (json ?? {});
1266
+ if (!res.ok || "error" in body) {
1267
+ const msg = body.error ?? `HTTP ${res.status}`;
1268
+ throw new Error(`API error: ${msg}`);
1269
+ }
1270
+ const rows = Array.isArray(body.fills)
1271
+ ? body.fills
1272
+ : [];
1273
+ return {
1274
+ fills: rows.map((row) => ({
1275
+ fillId: String(row.fill_id ?? "0"),
1276
+ market: Number(row.market ?? 0),
1277
+ blockHeight: Number(row.block_height ?? 0),
1278
+ blockTime: String(row.block_time ?? ""),
1279
+ price: String(row.price ?? "0"),
1280
+ quantity: String(row.quantity ?? "0"),
1281
+ makerOwner: String(row.maker_owner ?? ""),
1282
+ takerOwner: String(row.taker_owner ?? ""),
1283
+ makerSide: String(row.maker_side ?? ""),
1284
+ takerFee: Number(row.taker_fee ?? 0),
1285
+ makerFee: Number(row.maker_fee ?? 0),
1286
+ })),
1287
+ nextCursor: String(body.next_cursor ?? ""),
1288
+ };
1289
+ }
1290
+ // -----------------------------------------------------------------------
1291
+ // Chain status & block queries (via the gateway's /v1/* by default)
1292
+ // -----------------------------------------------------------------------
1293
+ async status() {
1294
+ const res = await fetch(`${this.chainBase}/status`);
1295
+ const json = await res.json();
1296
+ const info = json.result.sync_info;
1297
+ return {
1298
+ latestHeight: Number(info.latest_block_height),
1299
+ latestAppHash: info.latest_app_hash,
1300
+ };
1301
+ }
1302
+ async getBlock(height) {
1303
+ const params = height != null ? `?height=${height}` : "";
1304
+ const res = await fetch(`${this.chainBase}/block${params}`);
1305
+ const json = await res.json();
1306
+ if (json.error)
1307
+ throw new Error(json.error.message ?? JSON.stringify(json.error));
1308
+ return json.result;
1309
+ }
1310
+ async getBlockResults(height) {
1311
+ const res = await fetch(`${this.chainBase}/block_results?height=${height}`);
1312
+ const json = await res.json();
1313
+ if (json.error)
1314
+ throw new Error(json.error.message ?? JSON.stringify(json.error));
1315
+ return json.result;
1316
+ }
1317
+ // -----------------------------------------------------------------------
1318
+ // WebSocket streams (gateway-native; mirror the Python SDK)
1319
+ // -----------------------------------------------------------------------
1320
+ /**
1321
+ * Subscribe to the account-events stream (`/account-events`). Mirrors the
1322
+ * Python SDK's `AccountEventStream`: the gateway sends an initial snapshot
1323
+ * frame followed by incremental event frames. The SDK tracks the highest
1324
+ * `event_id` seen and replays from it via `after_id` on reconnect, so no
1325
+ * events are dropped across a disconnect.
1326
+ *
1327
+ * Auth: account streams require auth only when the gateway runs with
1328
+ * `--api-key`. A browser `WebSocket` cannot send the `X-Api-Key` header, so
1329
+ * the SDK uses the gateway's signed-query auth instead — when a private key
1330
+ * is loaded (`setPrivateKey`) it signs the `ProofExchange-account-events-v1`
1331
+ * message and appends `public_key` / `signature` / `timestamp_ms`. Against
1332
+ * an unauthenticated gateway (e.g. devnet) the owner alone is enough.
1333
+ *
1334
+ * Returns an unsubscribe function; `disconnect()` closes all streams.
1335
+ */
1336
+ subscribeAccountEvents(owner, onEvent, opts = {}) {
1337
+ const ownerHex = (owner instanceof Uint8Array ? bytesToHex(owner) : owner.replace(/^0x/, "")).toLowerCase();
1338
+ // Tracked across reconnects for gap recovery. Signed into the auth
1339
+ // message too, so the value we send and the value we sign always match.
1340
+ let afterId = 0n;
1341
+ const buildUrl = async () => {
1342
+ const params = new URLSearchParams({ owner: ownerHex });
1343
+ if (afterId > 0n)
1344
+ params.set("after_id", afterId.toString());
1345
+ if (this.privateKey && this.publicKey) {
1346
+ const chainId = await this.resolveChainId();
1347
+ const timestampMs = BigInt(Date.now());
1348
+ const msg = accountWsAuthMessage(chainId, ownerHex, afterId, timestampMs);
1349
+ params.set("public_key", bytesToHex(this.publicKey));
1350
+ params.set("signature", bytesToHex(sign(this.privateKey, msg)));
1351
+ params.set("timestamp_ms", timestampMs.toString());
1352
+ }
1353
+ return `${this.wsUrl}/account-events?${params.toString()}`;
1354
+ };
1355
+ return this.openStream(buildUrl, (frame) => {
1356
+ const id = frame.event_id;
1357
+ if (typeof id === "number" || typeof id === "bigint") {
1358
+ const big = BigInt(id);
1359
+ if (big > afterId)
1360
+ afterId = big;
1361
+ }
1362
+ onEvent(frame);
1363
+ }, opts);
1364
+ }
1365
+ /**
1366
+ * Subscribe to the L2 orderbook delta stream for a market
1367
+ * (`/orderbook-deltas`). Mirrors the Python SDK's `OrderbookDeltaStream`:
1368
+ * the first frame is a full `l2Book` snapshot, then incremental deltas.
1369
+ * Returns an unsubscribe function.
1370
+ */
1371
+ subscribeOrderbookDeltas(market, onMessage, opts = {}) {
1372
+ return this.openStream(async () => `${this.wsUrl}/orderbook-deltas?market=${market}`, onMessage, opts);
1373
+ }
1374
+ /**
1375
+ * One-shot L2 orderbook snapshot via a temporary delta-stream connection:
1376
+ * opens the stream, resolves the first `l2Book` snapshot frame, and closes.
1377
+ * Mirrors the Python SDK's `orderbook_snapshot`.
1378
+ */
1379
+ orderbookSnapshot(market) {
1380
+ return new Promise((resolve, reject) => {
1381
+ const unsub = this.subscribeOrderbookDeltas(market, (msg) => {
1382
+ if (msg.type === "l2Book") {
1383
+ unsub();
1384
+ resolve(msg);
1385
+ }
1386
+ }, {
1387
+ onError: (err) => {
1388
+ unsub();
1389
+ reject(err instanceof Error ? err : new Error(String(err)));
1390
+ },
1391
+ });
1392
+ });
1393
+ }
1394
+ /**
1395
+ * Internal: open one self-reconnecting WebSocket. `buildUrl` is re-invoked
1396
+ * on every (re)connect so per-connect state (fresh auth timestamp, current
1397
+ * `after_id`) is rebuilt each time. Reconnects with exponential backoff and
1398
+ * jitter. Returns an unsubscribe that stops reconnecting and closes the
1399
+ * socket.
1400
+ */
1401
+ openStream(buildUrl, onMessage, opts) {
1402
+ const backoffCapMs = opts.reconnectBackoffMaxMs ?? 30_000;
1403
+ let closed = false;
1404
+ let ws = null;
1405
+ let timer = null;
1406
+ let backoff = 500;
1407
+ const scheduleReconnect = () => {
1408
+ if (closed)
1409
+ return;
1410
+ const jitter = backoff * (0.75 + Math.random() * 0.5);
1411
+ timer = setTimeout(() => void connect(), jitter);
1412
+ backoff = Math.min(backoff * 2, backoffCapMs);
1413
+ };
1414
+ const connect = async () => {
1415
+ if (closed)
1416
+ return;
1417
+ let url;
1418
+ try {
1419
+ url = await buildUrl();
1420
+ }
1421
+ catch (err) {
1422
+ opts.onError?.(err);
1423
+ scheduleReconnect();
1424
+ return;
1425
+ }
1426
+ if (closed)
1427
+ return;
1428
+ ws = new WebSocket(url);
1429
+ ws.onopen = () => {
1430
+ backoff = 500;
1431
+ };
1432
+ ws.onmessage = (ev) => {
1433
+ try {
1434
+ onMessage(JSON.parse(ev.data));
1435
+ }
1436
+ catch (err) {
1437
+ opts.onError?.(err);
1438
+ }
1439
+ };
1440
+ ws.onerror = (err) => {
1441
+ opts.onError?.(err);
1442
+ };
1443
+ ws.onclose = () => {
1444
+ ws = null;
1445
+ if (!closed)
1446
+ scheduleReconnect();
1447
+ };
1448
+ };
1449
+ const unsubscribe = () => {
1450
+ closed = true;
1451
+ if (timer) {
1452
+ clearTimeout(timer);
1453
+ timer = null;
1454
+ }
1455
+ if (ws) {
1456
+ ws.close();
1457
+ ws = null;
1458
+ }
1459
+ this.activeStreams.delete(unsubscribe);
1460
+ };
1461
+ this.activeStreams.add(unsubscribe);
1462
+ void connect();
1463
+ return unsubscribe;
1464
+ }
1465
+ /** Close every open WebSocket stream and stop their reconnect loops. */
1466
+ disconnect() {
1467
+ for (const unsub of [...this.activeStreams])
1468
+ unsub();
1469
+ }
1470
+ }
1471
+ // ---------------------------------------------------------------------------
1472
+ // Helpers
1473
+ // ---------------------------------------------------------------------------
1474
+ /**
1475
+ * Build the byte string the gateway expects for signed account-events stream
1476
+ * auth (`api-gateway` `account_ws_auth_message`):
1477
+ *
1478
+ * "ProofExchange-account-events-v1" || chain_id(32B) ||
1479
+ * owner(ascii hex) || after_id(i64 BE) || timestamp_ms(u64 BE)
1480
+ *
1481
+ * Signed with the account's Ed25519 key; the gateway re-derives the owner
1482
+ * from the public key and verifies the signature.
1483
+ */
1484
+ function accountWsAuthMessage(chainId, ownerHex, afterId, timestampMs) {
1485
+ const prefix = new TextEncoder().encode("ProofExchange-account-events-v1");
1486
+ const ownerBytes = new TextEncoder().encode(ownerHex);
1487
+ const msg = new Uint8Array(prefix.length + 32 + ownerBytes.length + 16);
1488
+ let o = 0;
1489
+ msg.set(prefix, o);
1490
+ o += prefix.length;
1491
+ msg.set(chainId, o);
1492
+ o += 32;
1493
+ msg.set(ownerBytes, o);
1494
+ o += ownerBytes.length;
1495
+ const dv = new DataView(msg.buffer);
1496
+ dv.setBigInt64(o, afterId, false);
1497
+ o += 8;
1498
+ dv.setBigUint64(o, timestampMs, false);
1499
+ return msg;
1500
+ }
1501
+ /**
1502
+ * Fetch JSON from the API server and throw on non-2xx or `json.error`.
1503
+ * Returns the parsed JSON body on success.
1504
+ */
1505
+ async function fetchApiJson(url) {
1506
+ const res = await fetch(url);
1507
+ const json = (await res.json());
1508
+ if (!res.ok || json.error) {
1509
+ const msg = json.error ?? `HTTP ${res.status}`;
1510
+ throw new Error(`API error: ${msg}`);
1511
+ }
1512
+ return json;
1513
+ }
1514
+ /**
1515
+ * Governance reads carry a MessagePack envelope in `data`. A successful HTTP
1516
+ * response without that envelope is malformed, not an inactive registry or
1517
+ * an empty proposal page.
1518
+ */
1519
+ function requireEncodedData(json, endpoint) {
1520
+ if (typeof json.data !== "string" || json.data.length === 0) {
1521
+ throw new Error(`API error: ${endpoint} response is missing encoded data`);
1522
+ }
1523
+ return json.data;
1524
+ }
1525
+ /**
1526
+ * POST a structured `/info` request to the gateway and throw on non-2xx or
1527
+ * `json.error`. The gateway proxies the node's response body verbatim, so
1528
+ * the returned shape matches the equivalent direct-node GET (e.g.
1529
+ * `{ data: <base64-msgpack> }`). Used for owner-scoped reads the gateway
1530
+ * does not expose as GETs (account, open orders, withdrawal).
1531
+ */
1532
+ async function postInfoJson(gatewayUrl, info) {
1533
+ const res = await fetch(`${gatewayUrl}/info`, {
1534
+ method: "POST",
1535
+ headers: { "Content-Type": "application/json" },
1536
+ body: JSON.stringify(info),
1537
+ });
1538
+ const json = (await res.json());
1539
+ if (!res.ok || json.error) {
1540
+ const msg = json.error ?? `HTTP ${res.status}`;
1541
+ throw new Error(`API error: ${msg}`);
1542
+ }
1543
+ return json;
1544
+ }
1545
+ /**
1546
+ * Fetch a JSON array from the API server and throw on non-2xx or
1547
+ * `json.error`. Returns the parsed array on success.
1548
+ */
1549
+ async function fetchApiArray(url) {
1550
+ const res = await fetch(url);
1551
+ const json = (await res.json());
1552
+ if (!res.ok ||
1553
+ (json !== null &&
1554
+ typeof json === "object" &&
1555
+ "error" in json)) {
1556
+ const msg = json?.error ??
1557
+ `HTTP ${res.status}`;
1558
+ throw new Error(`API error: ${msg}`);
1559
+ }
1560
+ if (!Array.isArray(json)) {
1561
+ throw new Error(`API error: expected array, got ${typeof json}`);
1562
+ }
1563
+ return json;
1564
+ }
1565
+ function toBase64(bytes) {
1566
+ return btoa(String.fromCharCode(...bytes));
1567
+ }
1568
+ /** Coerce a decoded owner/destination field to bytes. serde encodes `[u8; N]`
1569
+ * as a msgpack ARRAY (not BIN), so the decoder may hand back `number[]`; some
1570
+ * encoders use BIN (`Uint8Array`). Accept both; null/undefined → empty. */
1571
+ function toBytes(v) {
1572
+ if (v instanceof Uint8Array)
1573
+ return v;
1574
+ if (Array.isArray(v))
1575
+ return Uint8Array.from(v);
1576
+ return new Uint8Array();
1577
+ }
1578
+ function fromBase64(b64) {
1579
+ const raw = atob(b64);
1580
+ const arr = new Uint8Array(raw.length);
1581
+ for (let i = 0; i < raw.length; i++)
1582
+ arr[i] = raw.charCodeAt(i);
1583
+ return arr;
1584
+ }
1585
+ function stripTrailingSlash(url) {
1586
+ return url.replace(/\/+$/, "");
1587
+ }
1588
+ /**
1589
+ * Derive a direct-node URL from the gateway URL by remapping the
1590
+ * conventional local gateway port (9080) to a node port. Used only as a
1591
+ * fallback for the internal `useGateway: false` path when an explicit
1592
+ * `rpcUrl` / `apiUrl` is not supplied.
1593
+ *
1594
+ * When the gateway has no port (a hosted gateway on 80/443) the node is
1595
+ * assumed to sit behind the same host, so the URL is returned unchanged
1596
+ * minus any path/query/hash. Callers whose node ports differ from the
1597
+ * 26657/8080 convention must pass the URL explicitly.
1598
+ */
1599
+ function deriveNodeUrl(gatewayUrl, fallbackPort) {
1600
+ try {
1601
+ const url = new URL(gatewayUrl);
1602
+ if (url.port === "9080") {
1603
+ url.port = fallbackPort;
1604
+ }
1605
+ url.pathname = "";
1606
+ url.search = "";
1607
+ url.hash = "";
1608
+ return stripTrailingSlash(url.toString());
1609
+ }
1610
+ catch {
1611
+ return `http://localhost:${fallbackPort}`;
1612
+ }
1613
+ }
1614
+ function computeCometTxHash(txBytes) {
1615
+ return bytesToHex(sha256(txBytes)).toUpperCase();
1616
+ }
1617
+ async function readGatewayBody(res) {
1618
+ const raw = await res.text();
1619
+ if (!raw)
1620
+ return {};
1621
+ try {
1622
+ const json = JSON.parse(raw);
1623
+ const error = typeof json === "object" &&
1624
+ json !== null &&
1625
+ "error" in json &&
1626
+ typeof json.error === "string"
1627
+ ? json.error
1628
+ : undefined;
1629
+ return { json, error, raw };
1630
+ }
1631
+ catch {
1632
+ return { raw };
1633
+ }
1634
+ }
1635
+ /**
1636
+ * Parse the leading numeric code from a gateway error string.
1637
+ *
1638
+ * The gateway formats engine errors as `"<code>: <message>"` per the
1639
+ * `ExecErrorCode` table in `api-gateway/openapi.yaml`. This helper lets
1640
+ * the SDK branch on `code === 21` (fresh timestamp required) and similar
1641
+ * patterns the same way it does for CometBFT-path responses.
1642
+ *
1643
+ * Returns `null` when the string doesn't match the expected shape so
1644
+ * callers can fall back to a conservative default.
1645
+ *
1646
+ * Examples:
1647
+ * "21: invalid nonce: expected 5, got 4" → 21
1648
+ * "12: insufficient margin" → 12
1649
+ * "signature verification failed" → null
1650
+ */
1651
+ function parseLeadingErrorCode(s) {
1652
+ const m = s.match(/^(\d+):\s/);
1653
+ if (!m)
1654
+ return null;
1655
+ const n = Number(m[1]);
1656
+ return Number.isFinite(n) ? n : null;
1657
+ }
1658
+ // ---------------------------------------------------------------------------
1659
+ // MarketConfig decoder
1660
+ // ---------------------------------------------------------------------------
1661
+ /** Decode a single MarketConfig from its MessagePack positional array.
1662
+ * Field order mirrors the Rust struct in exchange-core/src/types.rs.
1663
+ * Null-safe reads on every optional field. */
1664
+ function decodeMarketConfig(raw) {
1665
+ const optBig = (v) => v == null ? undefined : BigInt(v);
1666
+ const addr = (v) => v == null
1667
+ ? undefined
1668
+ : v instanceof Uint8Array
1669
+ ? v
1670
+ : Uint8Array.from(v);
1671
+ let kind;
1672
+ if (raw[7] != null) {
1673
+ if (typeof raw[7] === "string") {
1674
+ kind = raw[7];
1675
+ }
1676
+ else if (typeof raw[7] === "object" && raw[7] !== null) {
1677
+ const obj = raw[7];
1678
+ if (Array.isArray(obj.ConditionalPerp))
1679
+ kind = {
1680
+ ConditionalPerp: [
1681
+ Number(obj.ConditionalPerp[0]),
1682
+ obj.ConditionalPerp[1],
1683
+ ],
1684
+ };
1685
+ else if (Array.isArray(obj.PredictionBinary))
1686
+ kind = {
1687
+ PredictionBinary: [
1688
+ Number(obj.PredictionBinary[0]),
1689
+ obj.PredictionBinary[1],
1690
+ ],
1691
+ };
1692
+ }
1693
+ }
1694
+ let feeTiers;
1695
+ if (Array.isArray(raw[13])) {
1696
+ feeTiers = raw[13].map((t) => ({
1697
+ min30dVolumeMicroUsdc: BigInt(t[0]),
1698
+ makerFeeTenthBps: Number(t[1]),
1699
+ takerFeeTenthBps: Number(t[2]),
1700
+ }));
1701
+ }
1702
+ return {
1703
+ market: Number(raw[0]),
1704
+ imBps: Number(raw[1]),
1705
+ mmBps: Number(raw[2]),
1706
+ takerFeeBps: Number(raw[3]),
1707
+ makerFeeBps: Number(raw[4]),
1708
+ fundingIntervalMs: BigInt(raw[5]),
1709
+ maxFundingRateBps: Number(raw[6]),
1710
+ kind,
1711
+ maxPositionSize: optBig(raw[8]),
1712
+ defaultTtlMs: optBig(raw[9]),
1713
+ netDeltaMargin: raw[10] == null ? undefined : Boolean(raw[10]),
1714
+ poolId: raw[11] == null ? undefined : Number(raw[11]),
1715
+ markPriceMaxOracleAgeMs: optBig(raw[12]),
1716
+ feeTiers,
1717
+ tickSize: optBig(raw[14]),
1718
+ lotSize: optBig(raw[15]),
1719
+ primaryOracleSigner: addr(raw[16]),
1720
+ oracleStalenessMs: optBig(raw[17]),
1721
+ markSourceMode: raw[18] == null ? undefined : raw[18],
1722
+ maxMarkSpreadBps: raw[19] == null ? undefined : Number(raw[19]),
1723
+ cexCompositeStalenessMs: optBig(raw[20]),
1724
+ partialLiquidationEnabled: raw[21] == null ? undefined : Boolean(raw[21]),
1725
+ szDecimals: raw[22] == null ? undefined : Number(raw[22]),
1726
+ ticker: raw[23] == null ? undefined : String(raw[23]),
1727
+ maxOpenInterest: optBig(raw[24]),
1728
+ };
1729
+ }
1730
+ //# sourceMappingURL=client.js.map