@proof-labs/trading-sdk 4.0.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 +137 -6
- package/dist/account-state.d.ts +17 -0
- package/dist/account-state.d.ts.map +1 -0
- package/dist/account-state.js +63 -0
- package/dist/account-state.js.map +1 -0
- package/dist/client.d.ts +112 -31
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +472 -188
- package/dist/client.js.map +1 -1
- package/dist/codec-adapter.d.ts.map +1 -1
- package/dist/codec-adapter.js +11 -4
- 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/financial-state.d.ts +65 -0
- package/dist/financial-state.d.ts.map +1 -0
- package/dist/financial-state.js +345 -0
- package/dist/financial-state.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 +7 -13
- package/dist/governance-query.d.ts.map +1 -1
- package/dist/governance-query.js +131 -70
- 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 +13 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -3
- package/dist/index.js.map +1 -1
- package/dist/market-snapshot.d.ts +11 -0
- package/dist/market-snapshot.d.ts.map +1 -0
- package/dist/market-snapshot.js +325 -0
- package/dist/market-snapshot.js.map +1 -0
- package/dist/oracle-permissions.d.ts +51 -0
- package/dist/oracle-permissions.d.ts.map +1 -0
- package/dist/oracle-permissions.js +191 -0
- package/dist/oracle-permissions.js.map +1 -0
- 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 +235 -114
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +14 -5
- 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,13 +1,24 @@
|
|
|
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";
|
|
9
|
+
import { decodeAccountState } from "./account-state.js";
|
|
10
|
+
import { fetchFinancialState, } from "./financial-state.js";
|
|
2
11
|
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,
|
|
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";
|
|
6
15
|
import { Decoder } from "@msgpack/msgpack";
|
|
16
|
+
import { readMarketsSnapshot } from "./market-snapshot.js";
|
|
7
17
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
8
18
|
import { decodePositionTriggerInfos, decodeTriggerMarketConfigInfos, decodeTriggerStatusJson, validateCancelPositionTriggers, validateSetPositionTriggers, } from "./triggers.js";
|
|
9
19
|
import { decodePositionTriggerHistoryPage, decodeTriggerMarketHistoryPage, positionTriggerHistorySearchParams, triggerMarketHistorySearchParams, validateTriggerHistoryMarket, } from "./trigger-history.js";
|
|
10
20
|
const msgpackDecoder = new Decoder({ useBigInt64: true });
|
|
21
|
+
import { decodeOraclePermissions, validateOraclePermissionMarket, } from "./oracle-permissions.js";
|
|
11
22
|
/**
|
|
12
23
|
* Fetch the 32-byte chain_id binding from a CometBFT RPC's `/status`
|
|
13
24
|
* endpoint. Hashes `result.node_info.network` via `chainIdFromString`.
|
|
@@ -42,10 +53,15 @@ export class ExchangeClient {
|
|
|
42
53
|
* `/v1/status`, or `${rpcUrl}/status` on the direct path) on first submit.
|
|
43
54
|
*/
|
|
44
55
|
chainId;
|
|
56
|
+
/** Inventory reconciliation requires the caller's pin, not auto-discovery. */
|
|
57
|
+
inventoryChainId;
|
|
45
58
|
allowUnbound;
|
|
46
59
|
/** Single-flight guard so concurrent submits share one /status fetch. */
|
|
47
60
|
chainIdPromise = null;
|
|
48
61
|
privateKey = null;
|
|
62
|
+
externalSigner = null;
|
|
63
|
+
signerRevision = 0;
|
|
64
|
+
gatewayFeed = null;
|
|
49
65
|
publicKey = null;
|
|
50
66
|
address = null;
|
|
51
67
|
addressHex = null;
|
|
@@ -96,6 +112,7 @@ export class ExchangeClient {
|
|
|
96
112
|
// path resolveChainId() fetches /status on first submit; on the gateway
|
|
97
113
|
// path chainId must be pinned (the gateway does not serve /status).
|
|
98
114
|
this.chainId = opts.chainId ? chainIdFromString(opts.chainId) : null;
|
|
115
|
+
this.inventoryChainId = this.chainId?.slice() ?? null;
|
|
99
116
|
this.allowUnbound = opts.allowUnbound ?? false;
|
|
100
117
|
void opts.concurrentNonces;
|
|
101
118
|
}
|
|
@@ -206,11 +223,93 @@ export class ExchangeClient {
|
|
|
206
223
|
// -----------------------------------------------------------------------
|
|
207
224
|
/** Set the private key for signing transactions. */
|
|
208
225
|
setPrivateKey(key) {
|
|
226
|
+
this.externalSigner = null;
|
|
227
|
+
this.signerRevision++;
|
|
209
228
|
this.privateKey = key;
|
|
210
229
|
this.publicKey = getPublicKey(key);
|
|
211
230
|
this.address = pubkeyToOwner(this.publicKey);
|
|
212
231
|
this.addressHex = ownerToHex(this.address);
|
|
213
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
|
+
}
|
|
214
313
|
getAddress() {
|
|
215
314
|
return this.address;
|
|
216
315
|
}
|
|
@@ -247,24 +346,28 @@ export class ExchangeClient {
|
|
|
247
346
|
/**
|
|
248
347
|
* Allocate the next timestamp nonce.
|
|
249
348
|
*
|
|
250
|
-
* Algorithm: `max(now_ms, last_nonce + 1)
|
|
251
|
-
*
|
|
349
|
+
* Algorithm: `max(now_ms, last_nonce + 1)`. Refuse allocation above
|
|
350
|
+
* `now_ms + 60s` without rewinding or repeating the last nonce.
|
|
252
351
|
*
|
|
253
352
|
* Engine window: `[block_time - 2 days, block_time + 1 day]`. All four
|
|
254
353
|
* rejection modes (too old, too far future, replay, below oldest) map to
|
|
255
354
|
* code 21 `InvalidNonce`. Nonces are burned on success — no rewinding.
|
|
256
355
|
*
|
|
257
|
-
*
|
|
356
|
+
* Concurrent calls on this client reserve distinct nonces synchronously.
|
|
258
357
|
*/
|
|
259
358
|
nextTimestampNonce() {
|
|
260
359
|
const now = BigInt(Date.now());
|
|
261
360
|
const max = now + 60000n;
|
|
262
|
-
|
|
361
|
+
const next = this.lastTimestampNonce >= now ? this.lastTimestampNonce + 1n : now;
|
|
263
362
|
if (next > max)
|
|
264
|
-
|
|
363
|
+
throw new Error("Timestamp nonce allocation exceeds clock safety window");
|
|
265
364
|
this.lastTimestampNonce = next;
|
|
266
365
|
return next;
|
|
267
366
|
}
|
|
367
|
+
/** Highest locally allocated nonce; never rewound after rejection. */
|
|
368
|
+
get currentNonce() {
|
|
369
|
+
return this.lastTimestampNonce;
|
|
370
|
+
}
|
|
268
371
|
// -----------------------------------------------------------------------
|
|
269
372
|
// Transaction submission
|
|
270
373
|
// -----------------------------------------------------------------------
|
|
@@ -353,17 +456,7 @@ export class ExchangeClient {
|
|
|
353
456
|
* Both paths submit identical signed wire bytes.
|
|
354
457
|
*/
|
|
355
458
|
async broadcastSigned(action) {
|
|
356
|
-
|
|
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;
|
|
459
|
+
return this.broadcastSignedBytes(await this.signTx(action));
|
|
367
460
|
}
|
|
368
461
|
/**
|
|
369
462
|
* Submit signed wire bytes via the public API gateway
|
|
@@ -393,12 +486,20 @@ export class ExchangeClient {
|
|
|
393
486
|
if (this.apiKey)
|
|
394
487
|
headers["X-Api-Key"] = this.apiKey;
|
|
395
488
|
const body = JSON.stringify({ action: toBase64(txBytes) });
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
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
|
+
}
|
|
402
503
|
// Auth/rate-limit transport failures don't have a JSON body the
|
|
403
504
|
// engine produced — synthesize an HTTP-status code and tag the result
|
|
404
505
|
// `outcome: "transport"` so callers don't read it as an ExecError.
|
|
@@ -413,12 +514,14 @@ export class ExchangeClient {
|
|
|
413
514
|
gatewayBody.raw ??
|
|
414
515
|
"request body exceeds max size (default 8192 bytes)");
|
|
415
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
|
+
}
|
|
416
523
|
if (res.status >= 500) {
|
|
417
|
-
return
|
|
418
|
-
? `gateway error: ${gatewayBody.error}`
|
|
419
|
-
: gatewayBody.raw
|
|
420
|
-
? `gateway error: ${res.status} ${res.statusText}: ${gatewayBody.raw}`
|
|
421
|
-
: `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}` : ""}`);
|
|
422
525
|
}
|
|
423
526
|
if (!res.ok) {
|
|
424
527
|
const errMsg = gatewayBody.error ??
|
|
@@ -451,6 +554,7 @@ export class ExchangeClient {
|
|
|
451
554
|
hash,
|
|
452
555
|
height: json.height,
|
|
453
556
|
log: json.log ?? json.error,
|
|
557
|
+
info: json.info,
|
|
454
558
|
events: json.events,
|
|
455
559
|
});
|
|
456
560
|
}
|
|
@@ -471,10 +575,15 @@ export class ExchangeClient {
|
|
|
471
575
|
// Fallback: the code embedded in the string as "<engine_code>: <message>".
|
|
472
576
|
// The gateway still emits this format for compatibility, so this path also
|
|
473
577
|
// covers a pre-#90 gateway that sends ONLY the string. Parse the leading code;
|
|
474
|
-
//
|
|
578
|
+
// Hashless gateway refusals are terminal; unrecognized bodies remain unknown.
|
|
475
579
|
const errMsg = json?.error ?? gatewayBody.raw ?? "unknown gateway error";
|
|
476
|
-
const code = parseLeadingErrorCode(errMsg)
|
|
477
|
-
|
|
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");
|
|
478
587
|
}
|
|
479
588
|
/**
|
|
480
589
|
* Whether a `TxResult` is already final — i.e. nothing is gained by polling
|
|
@@ -529,37 +638,9 @@ export class ExchangeClient {
|
|
|
529
638
|
let self;
|
|
530
639
|
const verify = async () => {
|
|
531
640
|
try {
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
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.
|
|
641
|
+
const result = await this.waitForDelivery(txTimeout(txHash, "awaiting delivery"), { timeoutMs: 5_000 });
|
|
642
|
+
if (result.outcome !== "timeout")
|
|
643
|
+
this.deliveryResults.push(result);
|
|
563
644
|
}
|
|
564
645
|
finally {
|
|
565
646
|
this.pendingVerifies.delete(self);
|
|
@@ -608,8 +689,6 @@ export class ExchangeClient {
|
|
|
608
689
|
* `broadcast_tx_commit` subscription.
|
|
609
690
|
*/
|
|
610
691
|
async submitTxCommit(action) {
|
|
611
|
-
if (!this.privateKey)
|
|
612
|
-
throw new Error("No private key set");
|
|
613
692
|
// Step 1: broadcast via sync (returns after CheckTx). Use the internal
|
|
614
693
|
// path so we don't double-spawn a background verifier — we're going to
|
|
615
694
|
// do our own synchronous verification below.
|
|
@@ -639,52 +718,48 @@ export class ExchangeClient {
|
|
|
639
718
|
* unknown.
|
|
640
719
|
*/
|
|
641
720
|
async awaitCommit(sync) {
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
}
|
|
650
|
-
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))
|
|
651
728
|
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) {
|
|
729
|
+
if (!sync.hash)
|
|
659
730
|
throw new Error("submitTx returned no tx hash");
|
|
660
|
-
|
|
661
|
-
|
|
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;
|
|
662
735
|
let pollDelay = 200;
|
|
663
|
-
while (Date.now() < deadline) {
|
|
664
|
-
await
|
|
736
|
+
while (Date.now() < deadline && !opts.signal?.aborted) {
|
|
737
|
+
await abortableDelay(Math.min(pollDelay, deadline - Date.now()), opts.signal);
|
|
665
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);
|
|
666
743
|
try {
|
|
667
|
-
const res = await fetch(this.txStatusUrl(
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
if (
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
log: txResult.log,
|
|
676
|
-
events: txResult.events,
|
|
677
|
-
});
|
|
678
|
-
}
|
|
679
|
-
// 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;
|
|
680
752
|
}
|
|
681
753
|
catch {
|
|
682
|
-
|
|
754
|
+
/* Read failures leave the write outcome unknown. */
|
|
755
|
+
}
|
|
756
|
+
finally {
|
|
757
|
+
request.dispose();
|
|
683
758
|
}
|
|
684
759
|
}
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
760
|
+
return txTimeout(sync.hash, opts.signal?.aborted
|
|
761
|
+
? "delivery wait cancelled; reconcile by hash"
|
|
762
|
+
: "delivery wait timed out; reconcile by hash");
|
|
688
763
|
}
|
|
689
764
|
// -----------------------------------------------------------------------
|
|
690
765
|
// Convenience action builders
|
|
@@ -811,6 +886,14 @@ export class ExchangeClient {
|
|
|
811
886
|
asks: raw[1].map(parseLevel),
|
|
812
887
|
};
|
|
813
888
|
}
|
|
889
|
+
/** One atomic committed inventory. Requires explicit chainId; never falls
|
|
890
|
+
* back to a node or synthesizes inventory from independent list reads. */
|
|
891
|
+
async queryMarketsSnapshot() {
|
|
892
|
+
if (!this.inventoryChainId) {
|
|
893
|
+
throw new Error("market snapshot requires an explicit pinned chainId");
|
|
894
|
+
}
|
|
895
|
+
return readMarketsSnapshot(this.gatewayUrl, this.inventoryChainId);
|
|
896
|
+
}
|
|
814
897
|
/** List all registered market configs. */
|
|
815
898
|
async queryMarkets() {
|
|
816
899
|
const json = await fetchApiJson(`${this.readBaseUrl}/v1/markets`);
|
|
@@ -818,21 +901,41 @@ export class ExchangeClient {
|
|
|
818
901
|
const raw = msgpackDecoder.decode(bytes);
|
|
819
902
|
return raw.map((m) => decodeMarketConfig(m));
|
|
820
903
|
}
|
|
821
|
-
/**
|
|
822
|
-
*
|
|
823
|
-
* governance reads: a missing envelope or
|
|
824
|
-
*
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
const json = await fetchApiJson(`${this.readBaseUrl}/v1/impact_markets`);
|
|
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. */
|
|
908
|
+
async queryEvents() {
|
|
909
|
+
const json = await fetchApiJson(`${this.readBaseUrl}/v1/events`);
|
|
828
910
|
if (typeof json.data !== "string") {
|
|
829
|
-
throw new Error("governance decode:
|
|
911
|
+
throw new Error("governance decode: events response has no encoded-data envelope");
|
|
830
912
|
}
|
|
831
913
|
const raw = msgpackDecoder.decode(fromBase64(json.data));
|
|
832
914
|
if (!Array.isArray(raw)) {
|
|
833
|
-
throw new Error("governance decode:
|
|
915
|
+
throw new Error("governance decode: events is not an array");
|
|
916
|
+
}
|
|
917
|
+
return raw.map((r, i) => decodeEventInfo(r, i));
|
|
918
|
+
}
|
|
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. */
|
|
923
|
+
async queryEvent(eventId) {
|
|
924
|
+
const res = await fetch(`${this.readBaseUrl}/v1/event/${eventId}`);
|
|
925
|
+
if (res.status === 404)
|
|
926
|
+
return null;
|
|
927
|
+
const json = (await res.json());
|
|
928
|
+
if (!res.ok || json.error) {
|
|
929
|
+
const msg = json.error ?? `HTTP ${res.status}`;
|
|
930
|
+
throw new Error(`API error: ${msg}`);
|
|
834
931
|
}
|
|
835
|
-
|
|
932
|
+
if (typeof json.data !== "string") {
|
|
933
|
+
throw new Error("governance decode: event response has no encoded-data envelope");
|
|
934
|
+
}
|
|
935
|
+
const raw = msgpackDecoder.decode(fromBase64(json.data));
|
|
936
|
+
if (raw == null)
|
|
937
|
+
return null;
|
|
938
|
+
return decodeEventInfo(raw);
|
|
836
939
|
}
|
|
837
940
|
/** Current whole-position trigger brackets for one owner. Immutable
|
|
838
941
|
* lifecycle history is a separate gateway/indexer query below. */
|
|
@@ -876,6 +979,14 @@ export class ExchangeClient {
|
|
|
876
979
|
}
|
|
877
980
|
return decodeTriggerStatusJson(text);
|
|
878
981
|
}
|
|
982
|
+
/** One committed oracle dependency, not provider health or action authorization. */
|
|
983
|
+
async queryOraclePermissions(market) {
|
|
984
|
+
validateOraclePermissionMarket(market);
|
|
985
|
+
const path = `/v1/oracle/permissions/${market}`;
|
|
986
|
+
const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
|
|
987
|
+
const bytes = fromBase64(requireEncodedData(json, path));
|
|
988
|
+
return decodeOraclePermissions(msgpackDecoder.decode(bytes), market);
|
|
989
|
+
}
|
|
879
990
|
/** Immutable owner-bearing trigger lifecycle history. This always uses the
|
|
880
991
|
* public gateway, including when the client is configured for direct-node
|
|
881
992
|
* current-state reads; the node does not own indexer history. */
|
|
@@ -987,6 +1098,21 @@ export class ExchangeClient {
|
|
|
987
1098
|
requestHeight: BigInt(raw[5]),
|
|
988
1099
|
};
|
|
989
1100
|
}
|
|
1101
|
+
/** Raw finalized ledger facts, independent of oracle valuation. Not authorization. */
|
|
1102
|
+
async queryFinancialState(selection) {
|
|
1103
|
+
return fetchFinancialState(this.gatewayUrl, selection);
|
|
1104
|
+
}
|
|
1105
|
+
/** Raw finalized ledger facts, independent of oracle valuation. Not authorization. */
|
|
1106
|
+
async queryAccountState(addressHex) {
|
|
1107
|
+
const hex = addressHex ?? this.addressHex;
|
|
1108
|
+
if (!hex || !/^[0-9a-fA-F]{40}$/.test(hex)) {
|
|
1109
|
+
throw new Error("account state owner must be a 40-character hex address");
|
|
1110
|
+
}
|
|
1111
|
+
const owner = hex.toLowerCase();
|
|
1112
|
+
const path = `/v1/account/${owner}/state`;
|
|
1113
|
+
const json = await fetchApiJson(`${this.readBaseUrl}${path}`);
|
|
1114
|
+
return decodeAccountState(msgpackDecoder.decode(fromBase64(requireEncodedData(json, path))), owner);
|
|
1115
|
+
}
|
|
990
1116
|
async queryAccount(addressHex) {
|
|
991
1117
|
const hex = addressHex ?? this.addressHex;
|
|
992
1118
|
if (!hex)
|
|
@@ -1035,7 +1161,7 @@ export class ExchangeClient {
|
|
|
1035
1161
|
bindingScenario = (raw[6] ?? []).map((e) => {
|
|
1036
1162
|
const t = e;
|
|
1037
1163
|
return {
|
|
1038
|
-
|
|
1164
|
+
eventId: Number(t[0]),
|
|
1039
1165
|
branch: t[1],
|
|
1040
1166
|
};
|
|
1041
1167
|
});
|
|
@@ -1122,52 +1248,56 @@ export class ExchangeClient {
|
|
|
1122
1248
|
: String(row.open_interest),
|
|
1123
1249
|
};
|
|
1124
1250
|
}
|
|
1125
|
-
/**
|
|
1126
|
-
*
|
|
1127
|
-
* 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. */
|
|
1128
1253
|
async queryHistoryDeposits(addressHex, opts) {
|
|
1129
1254
|
return this.queryHistoryCashFlow("deposits", addressHex, opts);
|
|
1130
1255
|
}
|
|
1131
|
-
/**
|
|
1132
|
-
*
|
|
1133
|
-
*
|
|
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. */
|
|
1134
1261
|
async queryHistoryWithdrawals(addressHex, opts) {
|
|
1135
1262
|
return this.queryHistoryCashFlow("withdrawals", addressHex, opts);
|
|
1136
1263
|
}
|
|
1137
|
-
/**
|
|
1138
|
-
|
|
1139
|
-
* which kinds the server includes. */
|
|
1140
|
-
async queryHistoryCashFlow(path, addressHex, opts) {
|
|
1264
|
+
/** Owner-filtered indexer events; never the removed node history routes. */
|
|
1265
|
+
async queryHistoryCashFlow(path, addressHex, opts = {}) {
|
|
1141
1266
|
const hex = addressHex ?? this.addressHex;
|
|
1142
1267
|
if (!hex)
|
|
1143
1268
|
return [];
|
|
1144
|
-
const
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
solanaDestination: String(row.solana_destination ?? ""),
|
|
1163
|
-
reason: String(row.reason ?? ""),
|
|
1164
|
-
blockHeight: Number(row.block_height ?? 0),
|
|
1165
|
-
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);
|
|
1166
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);
|
|
1167
1297
|
}
|
|
1168
1298
|
/** Per-user position-at-resolution log — each row is one settlement or
|
|
1169
1299
|
* voided-conditional snapshot. Feeds the Portfolio "Resolved" tab
|
|
1170
|
-
* (P2 #7). Optional `
|
|
1300
|
+
* (P2 #7). Optional `eventId` filter scopes to one event.
|
|
1171
1301
|
*
|
|
1172
1302
|
* `fromMs` / `toMs` are unix-ms timestamps; omit for unbounded.
|
|
1173
1303
|
* `limit` caps at 1000 server-side. Results are newest-first. */
|
|
@@ -1176,8 +1306,8 @@ export class ExchangeClient {
|
|
|
1176
1306
|
if (!hex)
|
|
1177
1307
|
return [];
|
|
1178
1308
|
const params = new URLSearchParams();
|
|
1179
|
-
if (opts?.
|
|
1180
|
-
params.set("
|
|
1309
|
+
if (opts?.eventId !== undefined)
|
|
1310
|
+
params.set("event_id", String(opts.eventId));
|
|
1181
1311
|
if (opts?.fromMs !== undefined)
|
|
1182
1312
|
params.set("from", String(opts.fromMs));
|
|
1183
1313
|
if (opts?.toMs !== undefined)
|
|
@@ -1189,7 +1319,7 @@ export class ExchangeClient {
|
|
|
1189
1319
|
const json = await fetchApiArray(url);
|
|
1190
1320
|
return json.map((row) => ({
|
|
1191
1321
|
kind: row.kind,
|
|
1192
|
-
|
|
1322
|
+
eventId: String(row.event_id ?? ""),
|
|
1193
1323
|
market: String(row.market ?? ""),
|
|
1194
1324
|
owner: String(row.owner ?? ""),
|
|
1195
1325
|
side: String(row.side ?? ""),
|
|
@@ -1201,38 +1331,66 @@ export class ExchangeClient {
|
|
|
1201
1331
|
timestamp: Number(row.timestamp ?? 0),
|
|
1202
1332
|
}));
|
|
1203
1333
|
}
|
|
1204
|
-
/**
|
|
1205
|
-
*
|
|
1206
|
-
*
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
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. */
|
|
1211
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 = {}) {
|
|
1212
1379
|
const hex = addressHex ?? this.addressHex;
|
|
1213
1380
|
if (!hex)
|
|
1214
|
-
return [];
|
|
1215
|
-
const
|
|
1216
|
-
|
|
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");
|
|
1217
1389
|
params.set("market", String(opts.market));
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
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
|
-
}));
|
|
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);
|
|
1236
1394
|
}
|
|
1237
1395
|
/**
|
|
1238
1396
|
* Executed fills for an owner, newest first, keyset-paged. The endpoint
|
|
@@ -1326,8 +1484,8 @@ export class ExchangeClient {
|
|
|
1326
1484
|
*
|
|
1327
1485
|
* Auth: account streams require auth only when the gateway runs with
|
|
1328
1486
|
* `--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
|
|
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`
|
|
1331
1489
|
* message and appends `public_key` / `signature` / `timestamp_ms`. Against
|
|
1332
1490
|
* an unauthenticated gateway (e.g. devnet) the owner alone is enough.
|
|
1333
1491
|
*
|
|
@@ -1342,13 +1500,10 @@ export class ExchangeClient {
|
|
|
1342
1500
|
const params = new URLSearchParams({ owner: ownerHex });
|
|
1343
1501
|
if (afterId > 0n)
|
|
1344
1502
|
params.set("after_id", afterId.toString());
|
|
1345
|
-
if (this.privateKey
|
|
1346
|
-
const
|
|
1347
|
-
const
|
|
1348
|
-
|
|
1349
|
-
params.set("public_key", bytesToHex(this.publicKey));
|
|
1350
|
-
params.set("signature", bytesToHex(sign(this.privateKey, msg)));
|
|
1351
|
-
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));
|
|
1352
1507
|
}
|
|
1353
1508
|
return `${this.wsUrl}/account-events?${params.toString()}`;
|
|
1354
1509
|
};
|
|
@@ -1462,8 +1617,41 @@ export class ExchangeClient {
|
|
|
1462
1617
|
void connect();
|
|
1463
1618
|
return unsubscribe;
|
|
1464
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
|
+
}
|
|
1465
1652
|
/** Close every open WebSocket stream and stop their reconnect loops. */
|
|
1466
1653
|
disconnect() {
|
|
1654
|
+
this.gatewayFeed?.close();
|
|
1467
1655
|
for (const unsub of [...this.activeStreams])
|
|
1468
1656
|
unsub();
|
|
1469
1657
|
}
|
|
@@ -1614,6 +1802,57 @@ function deriveNodeUrl(gatewayUrl, fallbackPort) {
|
|
|
1614
1802
|
function computeCometTxHash(txBytes) {
|
|
1615
1803
|
return bytesToHex(sha256(txBytes)).toUpperCase();
|
|
1616
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
|
+
}
|
|
1617
1856
|
async function readGatewayBody(res) {
|
|
1618
1857
|
const raw = await res.text();
|
|
1619
1858
|
if (!raw)
|
|
@@ -1727,4 +1966,49 @@ function decodeMarketConfig(raw) {
|
|
|
1727
1966
|
maxOpenInterest: optBig(raw[24]),
|
|
1728
1967
|
};
|
|
1729
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
|
+
}
|
|
1730
2014
|
//# sourceMappingURL=client.js.map
|