@proof-labs/trading-sdk 4.2.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -7
- package/dist/client.d.ts +95 -39
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +412 -202
- package/dist/client.js.map +1 -1
- package/dist/codec-adapter.d.ts.map +1 -1
- package/dist/codec-adapter.js +8 -3
- package/dist/codec-adapter.js.map +1 -1
- package/dist/crypto.d.ts +20 -0
- package/dist/crypto.d.ts.map +1 -1
- package/dist/crypto.js +39 -0
- package/dist/crypto.js.map +1 -1
- package/dist/errors.d.ts +26 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +111 -15
- package/dist/errors.js.map +1 -1
- package/dist/feed-types.d.ts +76 -0
- package/dist/feed-types.d.ts.map +1 -0
- package/dist/feed-types.js +2 -0
- package/dist/feed-types.js.map +1 -0
- package/dist/feed.d.ts +158 -0
- package/dist/feed.d.ts.map +1 -0
- package/dist/feed.js +474 -0
- package/dist/feed.js.map +1 -0
- package/dist/gateway-reads.d.ts +74 -0
- package/dist/gateway-reads.d.ts.map +1 -0
- package/dist/gateway-reads.js +91 -0
- package/dist/gateway-reads.js.map +1 -0
- package/dist/governance-query.d.ts +6 -16
- package/dist/governance-query.d.ts.map +1 -1
- package/dist/governance-query.js +80 -93
- package/dist/governance-query.js.map +1 -1
- package/dist/history.d.ts +17 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +150 -0
- package/dist/history.js.map +1 -0
- package/dist/index.d.ts +9 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/market-snapshot.d.ts.map +1 -1
- package/dist/market-snapshot.js +4 -5
- package/dist/market-snapshot.js.map +1 -1
- package/dist/oracle-price-history.d.ts +30 -0
- package/dist/oracle-price-history.d.ts.map +1 -0
- package/dist/oracle-price-history.js +108 -0
- package/dist/oracle-price-history.js.map +1 -0
- package/dist/portfolio-history.d.ts +21 -0
- package/dist/portfolio-history.d.ts.map +1 -0
- package/dist/portfolio-history.js +49 -0
- package/dist/portfolio-history.js.map +1 -0
- package/dist/tx-result.d.ts +6 -0
- package/dist/tx-result.d.ts.map +1 -1
- package/dist/tx-result.js +42 -0
- package/dist/tx-result.js.map +1 -1
- package/dist/types.d.ts +160 -134
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +11 -7
- package/dist/types.js.map +1 -1
- package/dist/wasm/proof_trading_sdk_wasm_bg.wasm +0 -0
- package/package.json +5 -1
package/dist/client.js
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
|
-
import {
|
|
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,
|
|
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";
|
|
@@ -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)
|
|
258
|
-
*
|
|
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
|
-
*
|
|
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
|
-
|
|
361
|
+
const next = this.lastTimestampNonce >= now ? this.lastTimestampNonce + 1n : now;
|
|
270
362
|
if (next > max)
|
|
271
|
-
|
|
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
|
-
|
|
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
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
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
|
|
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
|
-
//
|
|
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)
|
|
484
|
-
|
|
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
|
-
|
|
540
|
-
|
|
541
|
-
|
|
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
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
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
|
-
|
|
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
|
|
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(
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
if (
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
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
|
-
|
|
754
|
+
/* Read failures leave the write outcome unknown. */
|
|
755
|
+
}
|
|
756
|
+
finally {
|
|
757
|
+
request.dispose();
|
|
690
758
|
}
|
|
691
759
|
}
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
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
|
|
@@ -833,26 +901,10 @@ export class ExchangeClient {
|
|
|
833
901
|
const raw = msgpackDecoder.decode(bytes);
|
|
834
902
|
return raw.map((m) => decodeMarketConfig(m));
|
|
835
903
|
}
|
|
836
|
-
/**
|
|
837
|
-
*
|
|
838
|
-
* governance reads: a missing envelope or
|
|
839
|
-
*
|
|
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. */
|
|
904
|
+
/** All events: each is two prediction-binary books (EBY/EBN) under one
|
|
905
|
+
* `EventInfo`, plus every conditional attached to it. Fail-closed like the
|
|
906
|
+
* governance reads: a missing envelope or malformed row is a refusal.
|
|
907
|
+
* Decoder pinned to the engine golden vector in governance-query.test.ts. */
|
|
856
908
|
async queryEvents() {
|
|
857
909
|
const json = await fetchApiJson(`${this.readBaseUrl}/v1/events`);
|
|
858
910
|
if (typeof json.data !== "string") {
|
|
@@ -864,10 +916,10 @@ export class ExchangeClient {
|
|
|
864
916
|
}
|
|
865
917
|
return raw.map((r, i) => decodeEventInfo(r, i));
|
|
866
918
|
}
|
|
867
|
-
/** A single
|
|
868
|
-
*
|
|
869
|
-
*
|
|
870
|
-
*
|
|
919
|
+
/** A single event by id, or `null` if it does not exist. The node returns
|
|
920
|
+
* 404 for a missing event (the engine's msgpack-nil), so a raw fetch is used
|
|
921
|
+
* here to map 404 -> null while still throwing on real transport / decode
|
|
922
|
+
* failures. */
|
|
871
923
|
async queryEvent(eventId) {
|
|
872
924
|
const res = await fetch(`${this.readBaseUrl}/v1/event/${eventId}`);
|
|
873
925
|
if (res.status === 404)
|
|
@@ -1109,7 +1161,7 @@ export class ExchangeClient {
|
|
|
1109
1161
|
bindingScenario = (raw[6] ?? []).map((e) => {
|
|
1110
1162
|
const t = e;
|
|
1111
1163
|
return {
|
|
1112
|
-
|
|
1164
|
+
eventId: Number(t[0]),
|
|
1113
1165
|
branch: t[1],
|
|
1114
1166
|
};
|
|
1115
1167
|
});
|
|
@@ -1196,52 +1248,56 @@ export class ExchangeClient {
|
|
|
1196
1248
|
: String(row.open_interest),
|
|
1197
1249
|
};
|
|
1198
1250
|
}
|
|
1199
|
-
/**
|
|
1200
|
-
*
|
|
1201
|
-
* reconstruction (P2 #6). */
|
|
1251
|
+
/** Direct relayer deposits and custody-confirmed deposits, newest first.
|
|
1252
|
+
* Returns a bounded merged head, not a cursor over the complete history. */
|
|
1202
1253
|
async queryHistoryDeposits(addressHex, opts) {
|
|
1203
1254
|
return this.queryHistoryCashFlow("deposits", addressHex, opts);
|
|
1204
1255
|
}
|
|
1205
|
-
/**
|
|
1206
|
-
*
|
|
1207
|
-
*
|
|
1256
|
+
/** Direct relayer withdrawals and indexed custody events, newest first,
|
|
1257
|
+
* capped after merging each kind's first page. This is not withdrawal status:
|
|
1258
|
+
* ownerless confirmation events
|
|
1259
|
+
* are not indexed for the account. Use queryWithdrawal(id) for status.
|
|
1260
|
+
* Request/refund amounts exclude fees; unknown signedDelta stays empty. */
|
|
1208
1261
|
async queryHistoryWithdrawals(addressHex, opts) {
|
|
1209
1262
|
return this.queryHistoryCashFlow("withdrawals", addressHex, opts);
|
|
1210
1263
|
}
|
|
1211
|
-
/**
|
|
1212
|
-
|
|
1213
|
-
* which kinds the server includes. */
|
|
1214
|
-
async queryHistoryCashFlow(path, addressHex, opts) {
|
|
1264
|
+
/** Owner-filtered indexer events; never the removed node history routes. */
|
|
1265
|
+
async queryHistoryCashFlow(path, addressHex, opts = {}) {
|
|
1215
1266
|
const hex = addressHex ?? this.addressHex;
|
|
1216
1267
|
if (!hex)
|
|
1217
1268
|
return [];
|
|
1218
|
-
const
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
solanaDestination: String(row.solana_destination ?? ""),
|
|
1237
|
-
reason: String(row.reason ?? ""),
|
|
1238
|
-
blockHeight: Number(row.block_height ?? 0),
|
|
1239
|
-
timestamp: Number(row.timestamp ?? 0),
|
|
1269
|
+
const owner = historyOwner(hex);
|
|
1270
|
+
const limit = opts.limit ?? 200;
|
|
1271
|
+
const params = historySearchParams({ ...opts, limit });
|
|
1272
|
+
params.set("owner", owner);
|
|
1273
|
+
params.set("order", "desc");
|
|
1274
|
+
const kinds = path === "deposits"
|
|
1275
|
+
? ["deposited", "deposit_confirmed"]
|
|
1276
|
+
: [
|
|
1277
|
+
"withdrawn",
|
|
1278
|
+
"withdraw_requested",
|
|
1279
|
+
"withdrawal_confirmed",
|
|
1280
|
+
"withdrawal_failed",
|
|
1281
|
+
];
|
|
1282
|
+
const pages = await Promise.all(kinds.map(async (kind) => {
|
|
1283
|
+
const query = new URLSearchParams(params);
|
|
1284
|
+
query.set("event_type", kind);
|
|
1285
|
+
const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/account-events?${query}`);
|
|
1286
|
+
return decodeCashFlowEvents(json, owner, kind);
|
|
1240
1287
|
}));
|
|
1288
|
+
return pages
|
|
1289
|
+
.flat()
|
|
1290
|
+
.sort((a, b) => {
|
|
1291
|
+
if (a.nanos !== b.nanos)
|
|
1292
|
+
return a.nanos > b.nanos ? -1 : 1;
|
|
1293
|
+
return a.eventId > b.eventId ? -1 : a.eventId < b.eventId ? 1 : 0;
|
|
1294
|
+
})
|
|
1295
|
+
.slice(0, limit)
|
|
1296
|
+
.map((event) => event.cashFlow);
|
|
1241
1297
|
}
|
|
1242
1298
|
/** Per-user position-at-resolution log — each row is one settlement or
|
|
1243
1299
|
* voided-conditional snapshot. Feeds the Portfolio "Resolved" tab
|
|
1244
|
-
* (P2 #7). Optional `
|
|
1300
|
+
* (P2 #7). Optional `eventId` filter scopes to one event.
|
|
1245
1301
|
*
|
|
1246
1302
|
* `fromMs` / `toMs` are unix-ms timestamps; omit for unbounded.
|
|
1247
1303
|
* `limit` caps at 1000 server-side. Results are newest-first. */
|
|
@@ -1250,8 +1306,8 @@ export class ExchangeClient {
|
|
|
1250
1306
|
if (!hex)
|
|
1251
1307
|
return [];
|
|
1252
1308
|
const params = new URLSearchParams();
|
|
1253
|
-
if (opts?.
|
|
1254
|
-
params.set("
|
|
1309
|
+
if (opts?.eventId !== undefined)
|
|
1310
|
+
params.set("event_id", String(opts.eventId));
|
|
1255
1311
|
if (opts?.fromMs !== undefined)
|
|
1256
1312
|
params.set("from", String(opts.fromMs));
|
|
1257
1313
|
if (opts?.toMs !== undefined)
|
|
@@ -1263,7 +1319,7 @@ export class ExchangeClient {
|
|
|
1263
1319
|
const json = await fetchApiArray(url);
|
|
1264
1320
|
return json.map((row) => ({
|
|
1265
1321
|
kind: row.kind,
|
|
1266
|
-
|
|
1322
|
+
eventId: String(row.event_id ?? ""),
|
|
1267
1323
|
market: String(row.market ?? ""),
|
|
1268
1324
|
owner: String(row.owner ?? ""),
|
|
1269
1325
|
side: String(row.side ?? ""),
|
|
@@ -1275,38 +1331,66 @@ export class ExchangeClient {
|
|
|
1275
1331
|
timestamp: Number(row.timestamp ?? 0),
|
|
1276
1332
|
}));
|
|
1277
1333
|
}
|
|
1278
|
-
/**
|
|
1279
|
-
*
|
|
1280
|
-
*
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1334
|
+
/** Named gateway responses for HTTP consumers that own body parsing, deadlines
|
|
1335
|
+
* and scheduling. Prefer typed query methods when raw response metadata is unnecessary.
|
|
1336
|
+
* Uses this client's gateway; never targets a node, even in internal node mode.
|
|
1337
|
+
*/
|
|
1338
|
+
reads(opts = {}) {
|
|
1339
|
+
return new GatewayReads(this.gatewayUrl, opts.fetch ?? ((url, init) => fetch(url, init)));
|
|
1340
|
+
}
|
|
1341
|
+
/** Gateway/indexer portfolio page, including in internal node mode.
|
|
1342
|
+
* Keep bounds fixed across opaque cursors. */
|
|
1343
|
+
async queryPortfolioHistory(owner, opts) {
|
|
1344
|
+
const canonicalOwner = owner.replace(/^0x/i, "").toLowerCase();
|
|
1345
|
+
if (!/^[0-9a-f]{40}$/.test(canonicalOwner))
|
|
1346
|
+
throw new Error("Invalid portfolio owner");
|
|
1347
|
+
const params = portfolioHistorySearchParams(opts);
|
|
1348
|
+
opts.signal?.throwIfAborted();
|
|
1349
|
+
const res = await fetch(`${this.gatewayUrl}/v1/history/portfolio/${canonicalOwner}?${params}`, { signal: opts.signal });
|
|
1350
|
+
if (!res.ok)
|
|
1351
|
+
throw new GatewayHttpError(res.status, res);
|
|
1352
|
+
const page = await res.json();
|
|
1353
|
+
opts.signal?.throwIfAborted();
|
|
1354
|
+
return decodePortfolioHistoryPage(page, canonicalOwner, opts);
|
|
1355
|
+
}
|
|
1356
|
+
/** One newest-first gateway page of a market's indexed `price_updated`
|
|
1357
|
+
* history. Keep market and bounds fixed across opaque cursors. */
|
|
1358
|
+
async queryOraclePriceHistory(market, options) {
|
|
1359
|
+
return queryOraclePriceHistoryPage(this.gatewayUrl, market, options);
|
|
1360
|
+
}
|
|
1361
|
+
/** Compatibility array of position snapshots. Absent close fields are empty
|
|
1362
|
+
* strings and timestamps are milliseconds. Use queryHistoryPositionsPage for
|
|
1363
|
+
* nullable fields, exact block times and opaque cursor continuation. */
|
|
1285
1364
|
async queryHistoryPositions(addressHex, opts) {
|
|
1365
|
+
const page = await this.queryHistoryPositionsPage(addressHex, opts);
|
|
1366
|
+
return page.positions.map((row) => ({
|
|
1367
|
+
owner: row.owner,
|
|
1368
|
+
market: String(row.market),
|
|
1369
|
+
side: row.side ?? "",
|
|
1370
|
+
entryPrice: row.entryPrice ?? "",
|
|
1371
|
+
size: row.size,
|
|
1372
|
+
blockHeight: row.blockHeight,
|
|
1373
|
+
timestamp: Date.parse(row.blockTime),
|
|
1374
|
+
}));
|
|
1375
|
+
}
|
|
1376
|
+
/** Gateway/indexer snapshots, newest first. Preserve filters when passing an
|
|
1377
|
+
* opaque nextCursor back in opts.cursor. Null close fields stay null. */
|
|
1378
|
+
async queryHistoryPositionsPage(addressHex, opts = {}) {
|
|
1286
1379
|
const hex = addressHex ?? this.addressHex;
|
|
1287
1380
|
if (!hex)
|
|
1288
|
-
return [];
|
|
1289
|
-
const
|
|
1290
|
-
|
|
1381
|
+
return { positions: [], nextCursor: "" };
|
|
1382
|
+
const owner = historyOwner(hex);
|
|
1383
|
+
const params = historySearchParams(opts);
|
|
1384
|
+
if (opts.market !== undefined) {
|
|
1385
|
+
if (!Number.isInteger(opts.market) ||
|
|
1386
|
+
opts.market < 0 ||
|
|
1387
|
+
opts.market > 0x7fffffff)
|
|
1388
|
+
throw new Error("Invalid history market");
|
|
1291
1389
|
params.set("market", String(opts.market));
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
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
|
-
}));
|
|
1390
|
+
}
|
|
1391
|
+
const query = params.toString();
|
|
1392
|
+
const json = await fetchApiJson(`${this.gatewayUrl}/v1/history/positions/${owner}${query ? `?${query}` : ""}`);
|
|
1393
|
+
return decodeHistoryPositionsPage(json, owner, opts.market);
|
|
1310
1394
|
}
|
|
1311
1395
|
/**
|
|
1312
1396
|
* Executed fills for an owner, newest first, keyset-paged. The endpoint
|
|
@@ -1400,8 +1484,8 @@ export class ExchangeClient {
|
|
|
1400
1484
|
*
|
|
1401
1485
|
* Auth: account streams require auth only when the gateway runs with
|
|
1402
1486
|
* `--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
|
|
1487
|
+
* the SDK uses the gateway's signed-query auth instead — when a private key or external signer
|
|
1488
|
+
* is connected it signs the `ProofExchange-account-events-v1`
|
|
1405
1489
|
* message and appends `public_key` / `signature` / `timestamp_ms`. Against
|
|
1406
1490
|
* an unauthenticated gateway (e.g. devnet) the owner alone is enough.
|
|
1407
1491
|
*
|
|
@@ -1416,13 +1500,10 @@ export class ExchangeClient {
|
|
|
1416
1500
|
const params = new URLSearchParams({ owner: ownerHex });
|
|
1417
1501
|
if (afterId > 0n)
|
|
1418
1502
|
params.set("after_id", afterId.toString());
|
|
1419
|
-
if (this.privateKey
|
|
1420
|
-
const
|
|
1421
|
-
const
|
|
1422
|
-
|
|
1423
|
-
params.set("public_key", bytesToHex(this.publicKey));
|
|
1424
|
-
params.set("signature", bytesToHex(sign(this.privateKey, msg)));
|
|
1425
|
-
params.set("timestamp_ms", timestampMs.toString());
|
|
1503
|
+
if (opts.auth !== false && (this.privateKey || this.externalSigner)) {
|
|
1504
|
+
const auth = await this.accountAuth(ownerHex, afterId);
|
|
1505
|
+
for (const [key, value] of Object.entries(auth))
|
|
1506
|
+
params.set(key, String(value));
|
|
1426
1507
|
}
|
|
1427
1508
|
return `${this.wsUrl}/account-events?${params.toString()}`;
|
|
1428
1509
|
};
|
|
@@ -1536,8 +1617,41 @@ export class ExchangeClient {
|
|
|
1536
1617
|
void connect();
|
|
1537
1618
|
return unsubscribe;
|
|
1538
1619
|
}
|
|
1620
|
+
/** Shared multiplexed /ws feed. Options apply on first creation only.
|
|
1621
|
+
* Reconnect restores snapshots, not missed events. Default auth reads the current signer.
|
|
1622
|
+
*/
|
|
1623
|
+
feed(opts = {}) {
|
|
1624
|
+
if (!this.gatewayFeed) {
|
|
1625
|
+
let base = this.wsUrl;
|
|
1626
|
+
if (!base && typeof globalThis.location !== "undefined")
|
|
1627
|
+
base = globalThis.location.origin.replace(/^http/, "ws");
|
|
1628
|
+
this.gatewayFeed = new GatewayFeed({
|
|
1629
|
+
url: `${base}/ws`,
|
|
1630
|
+
accountAuth: async (owner) => this.privateKey || this.externalSigner ? this.accountAuth(owner) : {},
|
|
1631
|
+
headers: this.apiKey ? { "X-Api-Key": this.apiKey } : undefined,
|
|
1632
|
+
...opts,
|
|
1633
|
+
});
|
|
1634
|
+
}
|
|
1635
|
+
return this.gatewayFeed;
|
|
1636
|
+
}
|
|
1637
|
+
/** Account snapshot plus live stream, with auth renewed per reconnect. */
|
|
1638
|
+
subscribeAccount(onFrame, opts = {}) {
|
|
1639
|
+
const owner = opts.owner ?? this.addressHex;
|
|
1640
|
+
if (!owner)
|
|
1641
|
+
throw new Error("No account owner available");
|
|
1642
|
+
return this.feed().subscribeAccount(owner, onFrame, async (address) => opts.auth !== false && (this.privateKey || this.externalSigner)
|
|
1643
|
+
? this.accountAuth(address)
|
|
1644
|
+
: {});
|
|
1645
|
+
}
|
|
1646
|
+
subscribeOrderbook(market, onFrame) {
|
|
1647
|
+
return this.feed().subscribeOrderbook(market, onFrame);
|
|
1648
|
+
}
|
|
1649
|
+
subscribeTrades(market, onFrame) {
|
|
1650
|
+
return this.feed().subscribeTrades(market, onFrame);
|
|
1651
|
+
}
|
|
1539
1652
|
/** Close every open WebSocket stream and stop their reconnect loops. */
|
|
1540
1653
|
disconnect() {
|
|
1654
|
+
this.gatewayFeed?.close();
|
|
1541
1655
|
for (const unsub of [...this.activeStreams])
|
|
1542
1656
|
unsub();
|
|
1543
1657
|
}
|
|
@@ -1688,6 +1802,57 @@ function deriveNodeUrl(gatewayUrl, fallbackPort) {
|
|
|
1688
1802
|
function computeCometTxHash(txBytes) {
|
|
1689
1803
|
return bytesToHex(sha256(txBytes)).toUpperCase();
|
|
1690
1804
|
}
|
|
1805
|
+
/** Only a fixed, known set of (HTTP status, message) pairs is hashless proof
|
|
1806
|
+
* of a pre-admission refusal — mirrors
|
|
1807
|
+
* `crates/proof-trading-sdk/src/gateway/mod.rs::pre_admission_refusal`
|
|
1808
|
+
* exactly for the statuses reached here (200, 503). ExchangeResponse::err
|
|
1809
|
+
* omits admission/verdict and rate-limit fields, but the shape alone is not
|
|
1810
|
+
* enough: an unrecognized message in that same shape can come from a generic
|
|
1811
|
+
* failure (an intermediary, a proxy) rather than the gateway's own refusal
|
|
1812
|
+
* path, and contradictory or unknown evidence must not become a terminal
|
|
1813
|
+
* refusal for a transaction that may have executed. */
|
|
1814
|
+
const PRE_ADMISSION_REFUSAL_FIELDS = new Set([
|
|
1815
|
+
"status",
|
|
1816
|
+
"error",
|
|
1817
|
+
"mode",
|
|
1818
|
+
"retryAfterMs",
|
|
1819
|
+
]);
|
|
1820
|
+
function preAdmissionRefusal(status, value) {
|
|
1821
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1822
|
+
return;
|
|
1823
|
+
const body = value;
|
|
1824
|
+
// Mirrors `RefusalRead`'s `#[serde(deny_unknown_fields)]`: any field
|
|
1825
|
+
// outside this exact set — including ones this SDK doesn't know about
|
|
1826
|
+
// yet — makes the body unrecognized, not refusal evidence.
|
|
1827
|
+
if (body.status !== "error" ||
|
|
1828
|
+
typeof body.error !== "string" ||
|
|
1829
|
+
Object.keys(body).some((key) => !PRE_ADMISSION_REFUSAL_FIELDS.has(key)))
|
|
1830
|
+
return undefined;
|
|
1831
|
+
if (status === 503 &&
|
|
1832
|
+
body.error === "maintenance: signed writes are not open") {
|
|
1833
|
+
if (body.retryAfterMs !== undefined)
|
|
1834
|
+
return undefined;
|
|
1835
|
+
return body.mode === "paused" || body.mode === "cancel-only"
|
|
1836
|
+
? body.error
|
|
1837
|
+
: undefined;
|
|
1838
|
+
}
|
|
1839
|
+
if (body.mode !== undefined || body.retryAfterMs !== undefined)
|
|
1840
|
+
return undefined;
|
|
1841
|
+
if (status === 503 &&
|
|
1842
|
+
(body.error === "service overloaded" ||
|
|
1843
|
+
body.error === "service unavailable"))
|
|
1844
|
+
return body.error;
|
|
1845
|
+
if (status === 200 &&
|
|
1846
|
+
(body.error === "invalid request body" ||
|
|
1847
|
+
body.error === "invalid action parameters" ||
|
|
1848
|
+
body.error === "invalid base64 in action field" ||
|
|
1849
|
+
body.error === "invalid signature" ||
|
|
1850
|
+
body.error === "internal encoding error" ||
|
|
1851
|
+
body.error ===
|
|
1852
|
+
"action type 0x1d is proposer-only and cannot enter through the gateway"))
|
|
1853
|
+
return body.error;
|
|
1854
|
+
return undefined;
|
|
1855
|
+
}
|
|
1691
1856
|
async function readGatewayBody(res) {
|
|
1692
1857
|
const raw = await res.text();
|
|
1693
1858
|
if (!raw)
|
|
@@ -1801,4 +1966,49 @@ function decodeMarketConfig(raw) {
|
|
|
1801
1966
|
maxOpenInterest: optBig(raw[24]),
|
|
1802
1967
|
};
|
|
1803
1968
|
}
|
|
1969
|
+
/** Copy protocol inputs without structuredClone or cross-realm instanceof checks. */
|
|
1970
|
+
function cloneSigningInput(value) {
|
|
1971
|
+
if (ArrayBuffer.isView(value) &&
|
|
1972
|
+
Object.prototype.toString.call(value) === "[object Uint8Array]") {
|
|
1973
|
+
const bytes = value;
|
|
1974
|
+
return new Uint8Array(bytes);
|
|
1975
|
+
}
|
|
1976
|
+
if (Array.isArray(value))
|
|
1977
|
+
return value.map(cloneSigningInput);
|
|
1978
|
+
if (value && typeof value === "object") {
|
|
1979
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, cloneSigningInput(v)]));
|
|
1980
|
+
}
|
|
1981
|
+
return value;
|
|
1982
|
+
}
|
|
1983
|
+
/** Abort interrupts the sleep; callers inspect the signal for their own result policy. */
|
|
1984
|
+
function abortableDelay(ms, signal) {
|
|
1985
|
+
if (signal?.aborted)
|
|
1986
|
+
return Promise.resolve();
|
|
1987
|
+
return new Promise((resolve) => {
|
|
1988
|
+
const done = () => {
|
|
1989
|
+
clearTimeout(timer);
|
|
1990
|
+
signal?.removeEventListener("abort", done);
|
|
1991
|
+
resolve();
|
|
1992
|
+
};
|
|
1993
|
+
const timer = setTimeout(done, ms);
|
|
1994
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
1995
|
+
});
|
|
1996
|
+
}
|
|
1997
|
+
/** Per-read deadline with explicit cleanup, without AbortSignal.any/timeout. */
|
|
1998
|
+
function readDeadline(ms, parent) {
|
|
1999
|
+
const controller = new AbortController();
|
|
2000
|
+
const abort = () => controller.abort(parent?.reason);
|
|
2001
|
+
if (parent?.aborted)
|
|
2002
|
+
abort();
|
|
2003
|
+
else
|
|
2004
|
+
parent?.addEventListener("abort", abort, { once: true });
|
|
2005
|
+
const timer = setTimeout(() => controller.abort(), ms);
|
|
2006
|
+
return {
|
|
2007
|
+
signal: controller.signal,
|
|
2008
|
+
dispose() {
|
|
2009
|
+
clearTimeout(timer);
|
|
2010
|
+
parent?.removeEventListener("abort", abort);
|
|
2011
|
+
},
|
|
2012
|
+
};
|
|
2013
|
+
}
|
|
1804
2014
|
//# sourceMappingURL=client.js.map
|