@proof-labs/trading-sdk 9.0.0 → 9.2.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 +8 -1
- package/dist/block-header.d.ts +13 -0
- package/dist/block-header.d.ts.map +1 -0
- package/dist/block-header.js +29 -0
- package/dist/block-header.js.map +1 -0
- package/dist/block-results-window.d.ts +58 -0
- package/dist/block-results-window.d.ts.map +1 -0
- package/dist/block-results-window.js +140 -0
- package/dist/block-results-window.js.map +1 -0
- package/dist/bounded-read.d.ts +47 -0
- package/dist/bounded-read.d.ts.map +1 -0
- package/dist/bounded-read.js +288 -0
- package/dist/bounded-read.js.map +1 -0
- package/dist/chain-evidence.d.ts +37 -0
- package/dist/chain-evidence.d.ts.map +1 -0
- package/dist/chain-evidence.js +123 -0
- package/dist/chain-evidence.js.map +1 -0
- package/dist/client.d.ts +3 -2
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +3 -4
- package/dist/client.js.map +1 -1
- package/dist/codec-adapter.d.ts.map +1 -1
- package/dist/codec-adapter.js +25 -0
- package/dist/codec-adapter.js.map +1 -1
- package/dist/committed-transaction.d.ts +34 -0
- package/dist/committed-transaction.d.ts.map +1 -0
- package/dist/committed-transaction.js +58 -0
- package/dist/committed-transaction.js.map +1 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +12 -0
- package/dist/errors.js.map +1 -1
- package/dist/finalized-account-reads.d.ts +75 -0
- package/dist/finalized-account-reads.d.ts.map +1 -0
- package/dist/finalized-account-reads.js +199 -0
- package/dist/finalized-account-reads.js.map +1 -0
- package/dist/finalized-oracle-read.d.ts +10 -0
- package/dist/finalized-oracle-read.d.ts.map +1 -0
- package/dist/finalized-oracle-read.js +25 -0
- package/dist/finalized-oracle-read.js.map +1 -0
- package/dist/finalized-orderbook.d.ts +23 -0
- package/dist/finalized-orderbook.d.ts.map +1 -0
- package/dist/finalized-orderbook.js +92 -0
- package/dist/finalized-orderbook.js.map +1 -0
- package/dist/finalized-state-reads.d.ts +21 -0
- package/dist/finalized-state-reads.d.ts.map +1 -0
- package/dist/finalized-state-reads.js +66 -0
- package/dist/finalized-state-reads.js.map +1 -0
- package/dist/financial-state.d.ts.map +1 -1
- package/dist/financial-state.js +12 -56
- package/dist/financial-state.js.map +1 -1
- package/dist/gateway-reads.d.ts +7 -2
- package/dist/gateway-reads.d.ts.map +1 -1
- package/dist/gateway-reads.js +3 -1
- package/dist/gateway-reads.js.map +1 -1
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/market-snapshot.d.ts +3 -0
- package/dist/market-snapshot.d.ts.map +1 -1
- package/dist/market-snapshot.js +16 -38
- package/dist/market-snapshot.js.map +1 -1
- package/dist/read-values.d.ts +49 -0
- package/dist/read-values.d.ts.map +1 -0
- package/dist/read-values.js +88 -0
- package/dist/read-values.js.map +1 -0
- package/dist/ticker.d.ts +49 -0
- package/dist/ticker.d.ts.map +1 -0
- package/dist/ticker.js +101 -0
- package/dist/ticker.js.map +1 -0
- package/dist/trade-history.d.ts +50 -0
- package/dist/trade-history.d.ts.map +1 -0
- package/dist/trade-history.js +135 -0
- package/dist/trade-history.js.map +1 -0
- package/dist/typed-gateway-reads.d.ts +54 -0
- package/dist/typed-gateway-reads.d.ts.map +1 -0
- package/dist/typed-gateway-reads.js +92 -0
- package/dist/typed-gateway-reads.js.map +1 -0
- package/dist/types.d.ts +3 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/wasm/proof_trading_sdk_wasm_bg.wasm +0 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -271,10 +271,17 @@ the Rust core by `conformance/binary.ndjson`.
|
|
|
271
271
|
### Oracle freshness for trading UIs
|
|
272
272
|
|
|
273
273
|
```typescript
|
|
274
|
-
const response = await client.reads().oracleHealth({ signal });
|
|
274
|
+
const response = await client.reads().oracleHealth({ market: 3, signal });
|
|
275
275
|
const health = await response.json();
|
|
276
276
|
```
|
|
277
277
|
|
|
278
|
+
With `market`, a 10.3.0+ gateway returns the same object cut to that market's
|
|
279
|
+
row (~1 KB instead of the full feeder state); omit it for every market. Older
|
|
280
|
+
gateways do not accept the query. The cut drops `failover` and `inventory`, and
|
|
281
|
+
its `status` is the feeder's 60-second rule, not the engine's per-market age
|
|
282
|
+
gate: use it for a UI freshness poll, and the bare path for monitoring and
|
|
283
|
+
maker guards.
|
|
284
|
+
|
|
278
285
|
This forwards `GET /v1/oracle/health` through the configured gateway, preserving
|
|
279
286
|
the response body, HTTP errors and cancellation. The Web-UI uses feeder freshness
|
|
280
287
|
for its existing delay warnings and order guards. Thresholds and display policy
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Hash32Hex } from "./read-values.js";
|
|
2
|
+
export interface BlockEvidenceHeader {
|
|
3
|
+
hash: Hash32Hex;
|
|
4
|
+
chainId: string;
|
|
5
|
+
height: bigint;
|
|
6
|
+
parentHash: Hash32Hex | null;
|
|
7
|
+
time: string;
|
|
8
|
+
/** Header H contains the app hash after H-1, not after H. */
|
|
9
|
+
appHash: Hash32Hex | null;
|
|
10
|
+
}
|
|
11
|
+
/** Internal common header decoder; does not verify validator signatures. */
|
|
12
|
+
export declare function decodeBlockEvidenceHeader(response: Record<string, unknown>, height: bigint, chain: Uint8Array): BlockEvidenceHeader;
|
|
13
|
+
//# sourceMappingURL=block-header.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block-header.d.ts","sourceRoot":"","sources":["../src/block-header.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,SAAS,GAAG,IAAI,CAAC;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,6DAA6D;IAC7D,OAAO,EAAE,SAAS,GAAG,IAAI,CAAC;CAC3B;AAED,4EAA4E;AAC5E,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,UAAU,GAChB,mBAAmB,CA4BrB"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { I64_MAX, blockTime, hash, invalid, object, same, uint, } from "./chain-evidence.js";
|
|
2
|
+
import { chainIdFromString } from "./crypto.js";
|
|
3
|
+
/** Internal common header decoder; does not verify validator signatures. */
|
|
4
|
+
export function decodeBlockEvidenceHeader(response, height, chain) {
|
|
5
|
+
const block = object(response.block, "block");
|
|
6
|
+
const header = object(block.header, "block header");
|
|
7
|
+
if (uint(header.height, I64_MAX, "block height") !== height)
|
|
8
|
+
invalid("block height mismatch", "binding");
|
|
9
|
+
if (typeof header.chain_id !== "string" ||
|
|
10
|
+
header.chain_id.length === 0 ||
|
|
11
|
+
header.chain_id.length > 128 ||
|
|
12
|
+
!same(chainIdFromString(header.chain_id), chain))
|
|
13
|
+
invalid("block chain mismatch", "binding");
|
|
14
|
+
const previous = object(header.last_block_id, "previous block ID").hash;
|
|
15
|
+
const parentHash = height === 1n && previous === ""
|
|
16
|
+
? null
|
|
17
|
+
: hash(previous, "parent block hash");
|
|
18
|
+
return {
|
|
19
|
+
hash: hash(object(response.block_id, "block ID").hash, "block hash"),
|
|
20
|
+
chainId: header.chain_id,
|
|
21
|
+
height,
|
|
22
|
+
parentHash,
|
|
23
|
+
time: blockTime(header.time),
|
|
24
|
+
appHash: height === 1n && header.app_hash === ""
|
|
25
|
+
? null
|
|
26
|
+
: hash(header.app_hash, "block app hash"),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=block-header.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
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AAC,IAAI,EAAE,YAAY,CAAC;QACpE,OAAO,EAAE,MAAM,CAAC,QAAkB;QAClC,MAAM;QACN,UAAU;QACV,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC;QAC5B,OAAO,EACL,MAAM,KAAK,EAAE,IAAI,MAAM,CAAC,QAAQ,KAAK,EAAE;YACrC,CAAC,CAAC,IAAI;YACN,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,gBAAgB,CAAC;KAC9C,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type BlockEvidenceHeader } from "./block-header.js";
|
|
2
|
+
import { type Hash32Hex } from "./read-values.js";
|
|
3
|
+
import { type BoundedReadOptions } from "./bounded-read.js";
|
|
4
|
+
import { type TransactionEvidenceEvent } from "./chain-evidence.js";
|
|
5
|
+
import type { ExchangeHttpTransport } from "./http-transport.js";
|
|
6
|
+
export interface BlockResultsWindowSelection {
|
|
7
|
+
/** Fixed half-open wall-clock window, in exact epoch milliseconds. */
|
|
8
|
+
fromMs: number;
|
|
9
|
+
toMs: number;
|
|
10
|
+
/** Explicit last height to inspect; its block time must reach toMs. */
|
|
11
|
+
throughHeight: bigint;
|
|
12
|
+
/** Maximum backward-scanned heights, 1..128. Default 32. No partial success. */
|
|
13
|
+
maxHeights?: number;
|
|
14
|
+
/** Caller may reduce these per-window ceilings, never exceed them. */
|
|
15
|
+
maxDecodedBytes?: number;
|
|
16
|
+
maxTransactions?: number;
|
|
17
|
+
maxEvents?: number;
|
|
18
|
+
maxAttributes?: number;
|
|
19
|
+
}
|
|
20
|
+
/** One block transaction and its same-index execution result. */
|
|
21
|
+
export interface BlockTransactionEvidence {
|
|
22
|
+
index: number;
|
|
23
|
+
hash: Hash32Hex;
|
|
24
|
+
signedBytes: Uint8Array;
|
|
25
|
+
code: number;
|
|
26
|
+
events: TransactionEvidenceEvent[];
|
|
27
|
+
}
|
|
28
|
+
export interface BlockResultsEvidence {
|
|
29
|
+
header: BlockEvidenceHeader;
|
|
30
|
+
postAppHash: Hash32Hex;
|
|
31
|
+
/** Every block transaction and its same-index result, including rejections. */
|
|
32
|
+
transactions: BlockTransactionEvidence[];
|
|
33
|
+
/** All system events, including any trades outside user transactions. */
|
|
34
|
+
finalizeBlockEvents: TransactionEvidenceEvent[];
|
|
35
|
+
}
|
|
36
|
+
/** Complete bounded responses from one configured trusted gateway, NOT a
|
|
37
|
+
* validator-signature or cryptographic event proof. Comet's results hash does
|
|
38
|
+
* not include event strings. Node trust remains essential. Height continuity,
|
|
39
|
+
* chain, result counts, times, each block's transaction list against its
|
|
40
|
+
* header `data_hash`, and post-state/header bindings are checked. Block hashes
|
|
41
|
+
* are not recomputed from headers, so a coherently lying gateway is not caught.
|
|
42
|
+
* Blocks include the lower-boundary block (before fromMs, or genesis) and may
|
|
43
|
+
* include end-boundary blocks. Consumers must apply [fromMs,toMs) themselves. */
|
|
44
|
+
export interface BlockResultsWindow {
|
|
45
|
+
source: "trusted-gateway";
|
|
46
|
+
fromMs: number;
|
|
47
|
+
toMs: number;
|
|
48
|
+
fromHeight: bigint;
|
|
49
|
+
throughHeight: bigint;
|
|
50
|
+
/** H+1 header binding the final scanned block's post-state hash. */
|
|
51
|
+
anchor: BlockEvidenceHeader;
|
|
52
|
+
/** Ascending heights; no missing or skipped blocks within this range. */
|
|
53
|
+
blocks: BlockResultsEvidence[];
|
|
54
|
+
}
|
|
55
|
+
/** Internal bounded scan. At most 2*maxHeights+1 GETs; each response <=1 MiB,
|
|
56
|
+
* retained decoded JSON <=8 MiB, and all reads share one deadline. */
|
|
57
|
+
export declare function readBlockResultsWindow(gatewayUrl: string, expectedChainId: Uint8Array, selection: BlockResultsWindowSelection, options: BoundedReadOptions, transport: ExchangeHttpTransport): Promise<BlockResultsWindow>;
|
|
58
|
+
//# sourceMappingURL=block-results-window.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block-results-window.d.ts","sourceRo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AM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,oEAAoE;IACpE,MAAM,EAAE,mBAAmB,CAAC;IAC5B,yEAAyE;IACzE,MAAM,EAAE,oBAAoB,EAAE,CAAC;CAChC;AASD;sEACsE;AACtE,wBAAsB,sBAAsB,CAC1C,UAAU,EAAE,MAAM,EAClB,eAAe,EAAE,UAAU,EAC3B,SAAS,EAAE,2BAA2B,EACtC,OAAO,EAAE,kBAAkB,EAC3B,SAAS,EAAE,qBAAqB,GAC/B,OAAO,CAAC,kBAAkB,CAAC,CAqL7B"}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { decodeBlockEvidenceHeader, } from "./block-header.js";
|
|
2
|
+
import { hash32, readDeadline, rfc3339, MAX_DATE_MS, } from "./read-values.js";
|
|
3
|
+
import { GatewayReadError } from "./errors.js";
|
|
4
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
5
|
+
import { boundedGatewayJson } from "./bounded-read.js";
|
|
6
|
+
import { I64_MAX, bindBlockTransactions, bytes, events, invalid, object, rpcResult, uint, } from "./chain-evidence.js";
|
|
7
|
+
import { bytesToHex } from "./crypto.js";
|
|
8
|
+
const WINDOW_DEFAULT_HEIGHTS = 32;
|
|
9
|
+
const WINDOW_MAX_HEIGHTS = 128;
|
|
10
|
+
const WINDOW_MAX_DECODED_BYTES = 8 * 1024 * 1024;
|
|
11
|
+
const WINDOW_MAX_TRANSACTIONS = 10_000;
|
|
12
|
+
const WINDOW_MAX_EVENTS = 16_384;
|
|
13
|
+
const WINDOW_MAX_ATTRIBUTES = 65_536;
|
|
14
|
+
/** Internal bounded scan. At most 2*maxHeights+1 GETs; each response <=1 MiB,
|
|
15
|
+
* retained decoded JSON <=8 MiB, and all reads share one deadline. */
|
|
16
|
+
export async function readBlockResultsWindow(gatewayUrl, expectedChainId, selection, options, transport) {
|
|
17
|
+
const { fromMs, toMs, throughHeight } = selection;
|
|
18
|
+
const deadline = readDeadline(options);
|
|
19
|
+
const budget = (value, ceiling, field) => {
|
|
20
|
+
const n = value ?? ceiling;
|
|
21
|
+
if (!Number.isSafeInteger(n) || n < 1 || n > ceiling)
|
|
22
|
+
throw new GatewayReadError("configuration", field);
|
|
23
|
+
return n;
|
|
24
|
+
};
|
|
25
|
+
const maxHeights = budget(selection.maxHeights ?? WINDOW_DEFAULT_HEIGHTS, WINDOW_MAX_HEIGHTS, "window heights");
|
|
26
|
+
const maxBytes = budget(selection.maxDecodedBytes, WINDOW_MAX_DECODED_BYTES, "window bytes");
|
|
27
|
+
const maxTransactions = budget(selection.maxTransactions, WINDOW_MAX_TRANSACTIONS, "window transactions");
|
|
28
|
+
const maxEvents = budget(selection.maxEvents, WINDOW_MAX_EVENTS, "window events");
|
|
29
|
+
const maxAttributes = budget(selection.maxAttributes, WINDOW_MAX_ATTRIBUTES, "window attributes");
|
|
30
|
+
if (!Number.isSafeInteger(fromMs) ||
|
|
31
|
+
fromMs < 0 ||
|
|
32
|
+
!Number.isSafeInteger(toMs) ||
|
|
33
|
+
toMs <= fromMs ||
|
|
34
|
+
toMs > MAX_DATE_MS)
|
|
35
|
+
invalid("fixed window");
|
|
36
|
+
if (typeof throughHeight !== "bigint" ||
|
|
37
|
+
throughHeight < 1n ||
|
|
38
|
+
throughHeight >= I64_MAX)
|
|
39
|
+
invalid("through height");
|
|
40
|
+
if (!(expectedChainId instanceof Uint8Array) || expectedChainId.length !== 32)
|
|
41
|
+
invalid("pinned chain");
|
|
42
|
+
const chain = Uint8Array.from(expectedChainId);
|
|
43
|
+
const base = gatewayUrl.replace(/\/+$/, "");
|
|
44
|
+
let decodedBytes = 0;
|
|
45
|
+
let transactionCount = 0;
|
|
46
|
+
let eventCount = 0;
|
|
47
|
+
let attributeCount = 0;
|
|
48
|
+
const read = async (path) => {
|
|
49
|
+
const raw = await boundedGatewayJson(`${base}${path}`, transport, deadline.remaining());
|
|
50
|
+
decodedBytes += new TextEncoder().encode(JSON.stringify(raw)).length;
|
|
51
|
+
if (decodedBytes > maxBytes)
|
|
52
|
+
invalid("window byte budget", "limit");
|
|
53
|
+
deadline.remaining();
|
|
54
|
+
return rpcResult(raw);
|
|
55
|
+
};
|
|
56
|
+
const decodeEvents = (value) => {
|
|
57
|
+
// Enforce the remaining window budget before allocating decoded lists.
|
|
58
|
+
// A busy block must not inherit the single-transaction evidence limits.
|
|
59
|
+
const decoded = events(value, {
|
|
60
|
+
maxEvents: maxEvents - eventCount,
|
|
61
|
+
maxAttributes: maxAttributes - attributeCount,
|
|
62
|
+
});
|
|
63
|
+
eventCount += decoded.length;
|
|
64
|
+
attributeCount += decoded.reduce((total, event) => total + (event.attributes?.length ?? 0), 0);
|
|
65
|
+
return decoded;
|
|
66
|
+
};
|
|
67
|
+
const anchor = decodeBlockEvidenceHeader(await read(`/v1/block?height=${throughHeight + 1n}`), throughHeight + 1n, chain);
|
|
68
|
+
const fromNs = BigInt(fromMs) * 1000000n;
|
|
69
|
+
const toNs = BigInt(toMs) * 1000000n;
|
|
70
|
+
const blocks = [];
|
|
71
|
+
let next = anchor;
|
|
72
|
+
for (let height = throughHeight; blocks.length < maxHeights && height >= 1n; height--) {
|
|
73
|
+
const response = await read(`/v1/block?height=${height}`);
|
|
74
|
+
const header = decodeBlockEvidenceHeader(response, height, chain);
|
|
75
|
+
if (next.parentHash !== header.hash)
|
|
76
|
+
invalid("parent hash continuity");
|
|
77
|
+
if (rfc3339(header.time).nanos > rfc3339(next.time).nanos)
|
|
78
|
+
invalid("block time continuity");
|
|
79
|
+
if (height === throughHeight && rfc3339(header.time).nanos < toNs)
|
|
80
|
+
invalid("source has not reached window end");
|
|
81
|
+
const rawTransactions = object(object(response.block, "block").data, "block data").txs;
|
|
82
|
+
// Go's non-omitempty slices encode a genuine empty list as null or [].
|
|
83
|
+
if (rawTransactions !== null && !Array.isArray(rawTransactions))
|
|
84
|
+
invalid("block transactions");
|
|
85
|
+
const txs = (rawTransactions ?? []);
|
|
86
|
+
transactionCount += txs.length;
|
|
87
|
+
if (transactionCount > maxTransactions)
|
|
88
|
+
invalid("window transaction budget", "limit");
|
|
89
|
+
const blockTransactions = txs.map((value) => bytes(value, "block transaction bytes"));
|
|
90
|
+
bindBlockTransactions(response, blockTransactions);
|
|
91
|
+
const result = await read(`/v1/block_results?height=${height}`);
|
|
92
|
+
if (uint(result.height, I64_MAX, "results height") !== height)
|
|
93
|
+
invalid("results height mismatch", "binding");
|
|
94
|
+
if (result.txs_results !== null && !Array.isArray(result.txs_results))
|
|
95
|
+
invalid("transaction results");
|
|
96
|
+
const txResults = (result.txs_results ?? []);
|
|
97
|
+
if (txResults.length !== txs.length)
|
|
98
|
+
invalid("transaction result count");
|
|
99
|
+
if (result.finalize_block_events !== null &&
|
|
100
|
+
!Array.isArray(result.finalize_block_events))
|
|
101
|
+
invalid("finalize block events");
|
|
102
|
+
const postState = bytes(result.app_hash, "results app hash");
|
|
103
|
+
if (postState.length !== 32)
|
|
104
|
+
invalid("results app hash length");
|
|
105
|
+
const postAppHash = hash32(bytesToHex(postState), "results app hash");
|
|
106
|
+
if (next.appHash === null || postAppHash !== next.appHash)
|
|
107
|
+
invalid("post-state/header binding");
|
|
108
|
+
const transactions = blockTransactions.map((signedBytes, index) => {
|
|
109
|
+
const execution = object(txResults[index], "transaction result");
|
|
110
|
+
return {
|
|
111
|
+
index,
|
|
112
|
+
hash: hash32(bytesToHex(sha256(signedBytes))),
|
|
113
|
+
signedBytes,
|
|
114
|
+
code: Number(uint(execution.code === undefined ? 0 : execution.code, 0xffffffffn, "execution code")),
|
|
115
|
+
events: decodeEvents(execution.events),
|
|
116
|
+
};
|
|
117
|
+
});
|
|
118
|
+
blocks.push({
|
|
119
|
+
header,
|
|
120
|
+
postAppHash,
|
|
121
|
+
transactions,
|
|
122
|
+
finalizeBlockEvents: decodeEvents(result.finalize_block_events ?? []),
|
|
123
|
+
});
|
|
124
|
+
deadline.remaining();
|
|
125
|
+
if (rfc3339(header.time).nanos < fromNs || height === 1n) {
|
|
126
|
+
return {
|
|
127
|
+
source: "trusted-gateway",
|
|
128
|
+
fromMs,
|
|
129
|
+
toMs,
|
|
130
|
+
fromHeight: height,
|
|
131
|
+
throughHeight,
|
|
132
|
+
anchor,
|
|
133
|
+
blocks: blocks.reverse(),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
next = header;
|
|
137
|
+
}
|
|
138
|
+
throw new GatewayReadError("limit", "height budget", "Block-results window exceeds height budget; no complete window available");
|
|
139
|
+
}
|
|
140
|
+
//# sourceMappingURL=block-results-window.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block-results-window.js","sourceRoot":"","sources":["../src/block-results-window.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,GAE1B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,MAAM,EACN,YAAY,EACZ,OAAO,EACP,WAAW,GAEZ,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAA2B,MAAM,mBAAmB,CAAC;AAChF,OAAO,EACL,OAAO,EACP,qBAAqB,EACrB,KAAK,EACL,MAAM,EACN,OAAO,EACP,MAAM,EACN,SAAS,EACT,IAAI,GAEL,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAwDzC,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAClC,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAC/B,MAAM,wBAAwB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD,MAAM,uBAAuB,GAAG,MAAM,CAAC;AACvC,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAErC;sEACsE;AACtE,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC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AAI,CAAC,CAAC,KAAK,GAAG,MAAM,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;YACzD,OAAO;gBACL,MAAM,EAAE,iBAAiB;gBACzB,MAAM;gBACN,IAAI;gBACJ,UAAU,EAAE,MAAM;gBAClB,aAAa;gBACb,MAAM;gBACN,MAAM,EAAE,MAAM,CAAC,OAAO,EAAE;aACzB,CAAC;QACJ,CAAC;QACD,IAAI,GAAG,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,IAAI,gBAAgB,CACxB,OAAO,EACP,eAAe,EACf,0EAA0E,CAC3E,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type Hash32Hex } from "./read-values.js";
|
|
2
|
+
import { type ExchangeHttpTransport } from "./http-transport.js";
|
|
3
|
+
/** Deadline covers queueing, headers and the entire bounded response body. */
|
|
4
|
+
export interface BoundedReadOptions {
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
/** Default 5 seconds, matching existing reads; explicit maximum 60 seconds. */
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
}
|
|
9
|
+
/** The gateway's assertion of the finalized state a read was served from, NOT
|
|
10
|
+
* validator signatures or a cryptographic event proof. How far a payload is
|
|
11
|
+
* checked against it varies per read: some payloads carry no height or owner
|
|
12
|
+
* to compare, and then the gateway's word is the only binding. verifyWitness
|
|
13
|
+
* binds the height and app hash to a chain-qualified H+1 header, which proves
|
|
14
|
+
* nothing beyond the gateway's word when that header came from the same
|
|
15
|
+
* gateway. This is not freshness, solvency, or authorization to trade. */
|
|
16
|
+
export interface FinalizedReadWitness {
|
|
17
|
+
version: 1;
|
|
18
|
+
nodeId: string;
|
|
19
|
+
height: bigint;
|
|
20
|
+
finalizedBlockTimeMs: bigint;
|
|
21
|
+
appHash: Hash32Hex;
|
|
22
|
+
}
|
|
23
|
+
export declare function decodeFinalizedReadWitness(value: unknown, expectedHeight?: bigint, expectedTimeMs?: bigint): FinalizedReadWitness;
|
|
24
|
+
/** Run a decoder that throws plain `Error`s, re-throwing them as a malformed
|
|
25
|
+
* `GatewayReadError` with the same message so callers can branch on `kind`. */
|
|
26
|
+
export declare function asReadError<T>(field: string, decode: () => T): T;
|
|
27
|
+
/** Compare a witness with an H+1 header. The check is only as strong as the
|
|
28
|
+
* header's source: `reads().evidence.blockHeader` asks the same gateway that
|
|
29
|
+
* served the witness and does not check validator signatures, so pairing the
|
|
30
|
+
* two shows the gateway is self-consistent, not that the state is authentic.
|
|
31
|
+
* H+1's timestamp is NOT H's timestamp, so it is deliberately not compared. */
|
|
32
|
+
export declare function verifyWitness(witness: FinalizedReadWitness, nextHeader: {
|
|
33
|
+
height: bigint;
|
|
34
|
+
chainId: string;
|
|
35
|
+
appHash: string | null;
|
|
36
|
+
}, chainId: string | Uint8Array): void;
|
|
37
|
+
export declare function parseBoundedJson(text: string): unknown;
|
|
38
|
+
/** Transport lane, plus setup that must finish inside the same deadline. */
|
|
39
|
+
export interface BoundedReadRequest {
|
|
40
|
+
/** Owner-scoped reads take the account lane, like the unwitnessed reads. */
|
|
41
|
+
purpose?: "account" | "query";
|
|
42
|
+
/** Awaited after the deadline and cancellation are armed, e.g. `ready()`. */
|
|
43
|
+
prepare?: () => Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
/** Internal one-shot SDK read. No retry, alternate endpoint or cached fallback. */
|
|
46
|
+
export declare function boundedGatewayJson(url: string, transport: ExchangeHttpTransport, options: BoundedReadOptions, request?: BoundedReadRequest): Promise<unknown>;
|
|
47
|
+
//# sourceMappingURL=bounded-read.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bounded-read.d.ts","sourceRoot":"","sources":["../src/bounded-read.ts"],"names":[],"mappings":"AACA,OAAO,EAOL,KAAK,SAAS,EACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAe,KAAK,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAE9E,8EAA8E;AAC9E,MAAM,WAAW,kBAAkB;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}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { GatewayHttpError, GatewayReadError } from "./errors.js";
|
|
2
|
+
import { hash32, I64_MAX, MAX_ERROR_BODY_WAIT_MS, MAX_READ_BYTES, MAX_READ_CHUNKS, readDeadline, } from "./read-values.js";
|
|
3
|
+
import { chainIdFromString } from "./crypto.js";
|
|
4
|
+
import { readContext } from "./http-transport.js";
|
|
5
|
+
export function decodeFinalizedReadWitness(value, expectedHeight, expectedTimeMs) {
|
|
6
|
+
const invalid = () => {
|
|
7
|
+
throw new GatewayReadError("malformed", "witness", "Invalid finalized read witness");
|
|
8
|
+
};
|
|
9
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
10
|
+
invalid();
|
|
11
|
+
const w = value;
|
|
12
|
+
const decimal = (value) => {
|
|
13
|
+
if (typeof value !== "string" ||
|
|
14
|
+
value.length > 20 ||
|
|
15
|
+
!/^[1-9][0-9]*$/.test(value))
|
|
16
|
+
invalid();
|
|
17
|
+
const n = BigInt(value);
|
|
18
|
+
if (n > I64_MAX)
|
|
19
|
+
invalid();
|
|
20
|
+
return n;
|
|
21
|
+
};
|
|
22
|
+
if (w.version !== 1 ||
|
|
23
|
+
typeof w.nodeId !== "string" ||
|
|
24
|
+
!/^[a-f0-9]{40}$/.test(w.nodeId) ||
|
|
25
|
+
/^0+$/.test(w.nodeId) ||
|
|
26
|
+
typeof w.appHash !== "string" ||
|
|
27
|
+
!/^[a-fA-F0-9]{64}$/.test(w.appHash) ||
|
|
28
|
+
/^0+$/.test(w.appHash))
|
|
29
|
+
invalid();
|
|
30
|
+
const height = decimal(w.height);
|
|
31
|
+
const finalizedBlockTimeMs = decimal(w.finalizedBlockTimeMs);
|
|
32
|
+
if ((expectedHeight !== undefined && height !== expectedHeight) ||
|
|
33
|
+
(expectedTimeMs !== undefined && finalizedBlockTimeMs !== expectedTimeMs))
|
|
34
|
+
throw new GatewayReadError("binding", "witness", "Finalized witness height/time mismatch");
|
|
35
|
+
return {
|
|
36
|
+
version: 1,
|
|
37
|
+
nodeId: w.nodeId,
|
|
38
|
+
height,
|
|
39
|
+
finalizedBlockTimeMs,
|
|
40
|
+
appHash: hash32(w.appHash),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** Run a decoder that throws plain `Error`s, re-throwing them as a malformed
|
|
44
|
+
* `GatewayReadError` with the same message so callers can branch on `kind`. */
|
|
45
|
+
export function asReadError(field, decode) {
|
|
46
|
+
try {
|
|
47
|
+
return decode();
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (error instanceof GatewayReadError)
|
|
51
|
+
throw error;
|
|
52
|
+
throw new GatewayReadError("malformed", field, error instanceof Error ? error.message : String(error), { cause: error });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Compare a witness with an H+1 header. The check is only as strong as the
|
|
56
|
+
* header's source: `reads().evidence.blockHeader` asks the same gateway that
|
|
57
|
+
* served the witness and does not check validator signatures, so pairing the
|
|
58
|
+
* two shows the gateway is self-consistent, not that the state is authentic.
|
|
59
|
+
* H+1's timestamp is NOT H's timestamp, so it is deliberately not compared. */
|
|
60
|
+
export function verifyWitness(witness, nextHeader, chainId) {
|
|
61
|
+
// The caller's pin is configuration; everything about the header is binding.
|
|
62
|
+
if (typeof chainId === "string"
|
|
63
|
+
? !chainId || chainId.length > 128
|
|
64
|
+
: !(chainId instanceof Uint8Array) || chainId.length !== 32) {
|
|
65
|
+
throw new GatewayReadError("configuration", "chainId", "Witness verification requires an explicit chain pin");
|
|
66
|
+
}
|
|
67
|
+
const expected = typeof chainId === "string" ? chainIdFromString(chainId) : chainId;
|
|
68
|
+
const bindingFault = () => {
|
|
69
|
+
throw new GatewayReadError("binding", "witness", "Finalized witness/header/chain mismatch");
|
|
70
|
+
};
|
|
71
|
+
if (typeof nextHeader.chainId !== "string" ||
|
|
72
|
+
!nextHeader.chainId ||
|
|
73
|
+
nextHeader.chainId.length > 128 ||
|
|
74
|
+
(nextHeader.appHash !== null &&
|
|
75
|
+
(typeof nextHeader.appHash !== "string" ||
|
|
76
|
+
!/^[a-fA-F0-9]{64}$/.test(nextHeader.appHash))))
|
|
77
|
+
bindingFault();
|
|
78
|
+
const actual = chainIdFromString(nextHeader.chainId);
|
|
79
|
+
if (actual.some((byte, i) => byte !== expected[i]) ||
|
|
80
|
+
witness.height < 1n ||
|
|
81
|
+
witness.height >= I64_MAX ||
|
|
82
|
+
nextHeader.height !== witness.height + 1n ||
|
|
83
|
+
nextHeader.appHash === null ||
|
|
84
|
+
hash32(witness.appHash) !== hash32(nextHeader.appHash))
|
|
85
|
+
bindingFault();
|
|
86
|
+
}
|
|
87
|
+
export function parseBoundedJson(text) {
|
|
88
|
+
const parsed = JSON.parse(text);
|
|
89
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
90
|
+
throw new GatewayReadError("malformed", "envelope");
|
|
91
|
+
// The shared parser checks top-level duplicates. Nested trade rows and
|
|
92
|
+
// witnesses must not acquire a second interpretation through repeated keys.
|
|
93
|
+
const stack = [];
|
|
94
|
+
for (let i = 0; i < text.length; i++) {
|
|
95
|
+
const char = text[i];
|
|
96
|
+
const frame = stack.at(-1);
|
|
97
|
+
if (char === '"') {
|
|
98
|
+
const start = i++;
|
|
99
|
+
for (; i < text.length; i++) {
|
|
100
|
+
if (text[i] === "\\")
|
|
101
|
+
i++;
|
|
102
|
+
else if (text[i] === '"')
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
if (frame?.keys && frame.keyExpected) {
|
|
106
|
+
const key = JSON.parse(text.slice(start, i + 1));
|
|
107
|
+
if (frame.keys.has(key))
|
|
108
|
+
throw new GatewayReadError("malformed", key, "Duplicate gateway read field");
|
|
109
|
+
frame.keys.add(key);
|
|
110
|
+
frame.keyExpected = false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
else if (char === "{" || char === "[") {
|
|
114
|
+
stack.push({
|
|
115
|
+
keys: char === "{" ? new Set() : undefined,
|
|
116
|
+
keyExpected: char === "{",
|
|
117
|
+
});
|
|
118
|
+
if (stack.length > 32)
|
|
119
|
+
throw new GatewayReadError("limit", "JSON depth");
|
|
120
|
+
}
|
|
121
|
+
else if (char === "}" || char === "]")
|
|
122
|
+
stack.pop();
|
|
123
|
+
else if (char === "," && frame?.keys)
|
|
124
|
+
frame.keyExpected = true;
|
|
125
|
+
}
|
|
126
|
+
return parsed;
|
|
127
|
+
}
|
|
128
|
+
function concat(chunks, size) {
|
|
129
|
+
const bytes = new Uint8Array(size);
|
|
130
|
+
let offset = 0;
|
|
131
|
+
for (const chunk of chunks) {
|
|
132
|
+
bytes.set(chunk, offset);
|
|
133
|
+
offset += chunk.length;
|
|
134
|
+
}
|
|
135
|
+
return bytes;
|
|
136
|
+
}
|
|
137
|
+
/** Retain a bounded, readable error body after cancelling the upstream. */
|
|
138
|
+
function httpError(response, bytes) {
|
|
139
|
+
const body = bytes.length ? bytes : null;
|
|
140
|
+
let copy;
|
|
141
|
+
try {
|
|
142
|
+
copy = new Response(body, {
|
|
143
|
+
status: response.status,
|
|
144
|
+
statusText: response.statusText,
|
|
145
|
+
headers: response.headers,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
// A custom transport can report a status (e.g. 304 with a body) that the
|
|
150
|
+
// Response constructor refuses; the real status stays on the error.
|
|
151
|
+
copy = new Response(body, { headers: response.headers });
|
|
152
|
+
}
|
|
153
|
+
return new GatewayHttpError(response.status, copy);
|
|
154
|
+
}
|
|
155
|
+
/** Internal one-shot SDK read. No retry, alternate endpoint or cached fallback. */
|
|
156
|
+
export async function boundedGatewayJson(url, transport, options, request = {}) {
|
|
157
|
+
const { timeoutMs } = readDeadline(options);
|
|
158
|
+
options.signal?.throwIfAborted();
|
|
159
|
+
const deadline = performance.now() + timeoutMs;
|
|
160
|
+
const controller = new AbortController();
|
|
161
|
+
const checkDeadline = () => {
|
|
162
|
+
controller.signal.throwIfAborted();
|
|
163
|
+
// A continuously ready stream can starve timers with resolved promises.
|
|
164
|
+
// Check monotonic elapsed time too, independent of wall-clock changes.
|
|
165
|
+
if (performance.now() >= deadline)
|
|
166
|
+
throw new GatewayReadError("deadline", "timeout", "Gateway read deadline exceeded");
|
|
167
|
+
};
|
|
168
|
+
const abort = () => controller.abort(options.signal?.reason);
|
|
169
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
170
|
+
const timer = setTimeout(() => controller.abort(new GatewayReadError("deadline", "timeout", "Gateway read deadline exceeded")), timeoutMs);
|
|
171
|
+
let response;
|
|
172
|
+
let reader;
|
|
173
|
+
let onAbort = () => { };
|
|
174
|
+
const cancelled = new Promise((_, reject) => {
|
|
175
|
+
onAbort = () => reject(controller.signal.reason);
|
|
176
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
177
|
+
});
|
|
178
|
+
try {
|
|
179
|
+
if (request.prepare) {
|
|
180
|
+
await Promise.race([request.prepare(), cancelled]);
|
|
181
|
+
checkDeadline();
|
|
182
|
+
}
|
|
183
|
+
const pending = transport(url, {
|
|
184
|
+
method: "GET",
|
|
185
|
+
cache: "no-store",
|
|
186
|
+
redirect: "error",
|
|
187
|
+
signal: controller.signal,
|
|
188
|
+
}, readContext(url, request.purpose ?? "query"));
|
|
189
|
+
// A custom transport may ignore abort. Do not leak a response arriving late.
|
|
190
|
+
void pending.then((res) => {
|
|
191
|
+
if (controller.signal.aborted)
|
|
192
|
+
void res.body?.cancel().catch(() => { });
|
|
193
|
+
}, () => { });
|
|
194
|
+
response = await Promise.race([pending, cancelled]);
|
|
195
|
+
checkDeadline();
|
|
196
|
+
if (!response.ok) {
|
|
197
|
+
// The status is the diagnosis. An error body that is oversized,
|
|
198
|
+
// fragmented, empty-chunked or slower than MAX_ERROR_BODY_WAIT_MS is
|
|
199
|
+
// truncated to what arrived in bounds; it never replaces the HTTP status
|
|
200
|
+
// or holds the caller for the whole deadline. Caller cancellation wins.
|
|
201
|
+
const chunks = [];
|
|
202
|
+
let size = 0;
|
|
203
|
+
if (response.body) {
|
|
204
|
+
reader = response.body.getReader();
|
|
205
|
+
const bodyDeadline = Math.min(deadline, performance.now() + MAX_ERROR_BODY_WAIT_MS);
|
|
206
|
+
let budgetTimer;
|
|
207
|
+
const budgetSpent = new Promise((resolve) => {
|
|
208
|
+
budgetTimer = setTimeout(() => resolve("budget"), Math.max(0, bodyDeadline - performance.now()));
|
|
209
|
+
});
|
|
210
|
+
try {
|
|
211
|
+
while (chunks.length < MAX_READ_CHUNKS && size < MAX_READ_BYTES) {
|
|
212
|
+
const part = await Promise.race([
|
|
213
|
+
reader.read(),
|
|
214
|
+
budgetSpent,
|
|
215
|
+
cancelled,
|
|
216
|
+
]);
|
|
217
|
+
if (part === "budget" || part.done || part.value.length === 0)
|
|
218
|
+
break;
|
|
219
|
+
const kept = part.value.subarray(0, MAX_READ_BYTES - size);
|
|
220
|
+
chunks.push(kept);
|
|
221
|
+
size += kept.length;
|
|
222
|
+
if (performance.now() >= bodyDeadline)
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
if (options.signal?.aborted)
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
finally {
|
|
231
|
+
clearTimeout(budgetTimer);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
throw httpError(response, concat(chunks, size));
|
|
235
|
+
}
|
|
236
|
+
const length = response.headers.get("content-length");
|
|
237
|
+
if (length !== null &&
|
|
238
|
+
(!/^(0|[1-9][0-9]*)$/.test(length) ||
|
|
239
|
+
BigInt(length) > BigInt(MAX_READ_BYTES)))
|
|
240
|
+
throw new GatewayReadError("limit", "responseBytes", "Gateway read response exceeds byte limit");
|
|
241
|
+
if (!response.body)
|
|
242
|
+
throw new GatewayReadError("malformed", "body", "Gateway read response body is missing");
|
|
243
|
+
reader = response.body.getReader();
|
|
244
|
+
const chunks = [];
|
|
245
|
+
let size = 0;
|
|
246
|
+
for (;;) {
|
|
247
|
+
const part = await Promise.race([reader.read(), cancelled]);
|
|
248
|
+
checkDeadline();
|
|
249
|
+
if (part.done)
|
|
250
|
+
break;
|
|
251
|
+
if (part.value.length === 0)
|
|
252
|
+
throw new GatewayReadError("malformed", "body", "Gateway read returned an empty body chunk");
|
|
253
|
+
if (chunks.length >= MAX_READ_CHUNKS)
|
|
254
|
+
throw new GatewayReadError("limit", "chunks", "Gateway read exceeds fragmentation limit");
|
|
255
|
+
size += part.value.length;
|
|
256
|
+
if (size > MAX_READ_BYTES)
|
|
257
|
+
throw new GatewayReadError("limit", "responseBytes", "Gateway read response exceeds byte limit");
|
|
258
|
+
chunks.push(part.value);
|
|
259
|
+
}
|
|
260
|
+
checkDeadline();
|
|
261
|
+
const bytes = concat(chunks, size);
|
|
262
|
+
let parsed;
|
|
263
|
+
try {
|
|
264
|
+
parsed = parseBoundedJson(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
if (error instanceof GatewayReadError)
|
|
268
|
+
throw error;
|
|
269
|
+
throw new GatewayReadError("malformed", "json", "Invalid gateway read JSON", { cause: error });
|
|
270
|
+
}
|
|
271
|
+
checkDeadline();
|
|
272
|
+
return parsed;
|
|
273
|
+
}
|
|
274
|
+
finally {
|
|
275
|
+
clearTimeout(timer);
|
|
276
|
+
options.signal?.removeEventListener("abort", abort);
|
|
277
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
278
|
+
if (reader) {
|
|
279
|
+
// Do not wait on an uncooperative custom stream's cancellation hook.
|
|
280
|
+
void reader.cancel().catch(() => { });
|
|
281
|
+
reader.releaseLock();
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
void response?.body?.cancel().catch(() => { });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
//# sourceMappingURL=bounded-read.js.map
|