@pacspace-io/check 0.5.5 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/README.md +36 -2
  3. package/dist/check.d.ts +6 -1
  4. package/dist/cli.d.ts +5 -1
  5. package/dist/cli.js +2496 -380
  6. package/dist/index.js +518 -91
  7. package/dist/inputs.txt +12 -0
  8. package/dist/open-io.d.ts +38 -0
  9. package/dist/open.d.ts +16 -15
  10. package/dist/records-crypto-types/records/flag-threads-v1.d.ts +53 -0
  11. package/dist/records-crypto-types/records/labels.d.ts +37 -0
  12. package/dist/records-crypto-types/records/link-handle-v1.d.ts +16 -0
  13. package/dist/records-crypto-types/records/reader-crypto-v1.d.ts +198 -0
  14. package/dist/records-crypto-types/records/reader-link-v1.d.ts +164 -0
  15. package/dist/records-crypto-types/records/shared-record-ack-v2.d.ts +72 -0
  16. package/dist/records-crypto-types/records/trail-index-v1.d.ts +89 -0
  17. package/dist/records-crypto-types/records/trail-rule.d.ts +54 -0
  18. package/dist/records-crypto-types/records-crypto/asymmetric/ack-flag-notes-v1.d.ts +57 -0
  19. package/dist/records-crypto-types/records-crypto/asymmetric/flag-notes-v1.d.ts +55 -0
  20. package/dist/records-crypto-types/records-crypto/asymmetric/index.d.ts +3 -0
  21. package/dist/records-crypto-types/records-crypto/asymmetric/reader-wraps-v1.d.ts +83 -0
  22. package/dist/records-crypto-types/records-crypto/disclosure-envelope-v1.d.ts +1 -1
  23. package/dist/records-crypto-types/records-crypto/index.d.ts +1 -1
  24. package/dist/records-crypto-types/records-crypto/records-encryption-v1.d.ts +1 -0
  25. package/dist/records-crypto.js +547 -66
  26. package/dist/report.d.ts +20 -1
  27. package/dist/shared-record-link.d.ts +121 -0
  28. package/dist/shared-record-words.d.ts +97 -0
  29. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2097,16 +2097,10 @@ async function readRecordCopyV1(file) {
2097
2097
  }
2098
2098
 
2099
2099
  // ../shared/src/records/record-seal-history-v1.ts
2100
- var import_ethers13 = require("ethers");
2100
+ var import_ethers14 = require("ethers");
2101
2101
 
2102
2102
  // ../shared/src/demo/mirror-node-record-chain-reader.ts
2103
- var import_ethers12 = require("ethers");
2104
-
2105
- // ../shared/src/records/inspect-record-calldata-v1.ts
2106
- var MIRROR_NODE_BY_CHAIN = Object.freeze({
2107
- 296: "https://testnet.mirrornode.hedera.com",
2108
- 295: "https://mainnet-public.mirrornode.hedera.com"
2109
- });
2103
+ var import_ethers13 = require("ethers");
2110
2104
 
2111
2105
  // ../shared/src/records/ledger-write-search-v1.ts
2112
2106
  var LEDGER_WRITE_SEARCH_WINDOW_LIMIT_SECONDS = 7 * 24 * 60 * 60;
@@ -2116,7 +2110,15 @@ var HEX40 = /^0x[0-9a-f]{40}$/;
2116
2110
  var HEX642 = /^0x[0-9a-f]{64}$/;
2117
2111
  var HEX_DATA = /^0x[0-9a-f]*$/;
2118
2112
  var TIMESTAMP = /^\d+(\.\d+)?$/;
2119
- var REFUSAL_CODES = ["redirect", "too-large", "too-many-logs", "next-page"];
2113
+ var REFUSAL_CODES = {
2114
+ redirect: true,
2115
+ "too-large": true,
2116
+ "too-many-logs": true,
2117
+ "next-page": true,
2118
+ "too-slow": true,
2119
+ "too-long": true
2120
+ };
2121
+ var MIRROR_REFUSAL_CODES = Object.keys(REFUSAL_CODES);
2120
2122
  var MirrorAnswerRefused = class extends Error {
2121
2123
  constructor(code, message) {
2122
2124
  super(message);
@@ -2127,7 +2129,7 @@ var MirrorAnswerRefused = class extends Error {
2127
2129
  function mirrorRefusalOf(error) {
2128
2130
  if (!error || typeof error !== "object") return null;
2129
2131
  const { name, code } = error;
2130
- return name === "MirrorAnswerRefused" && typeof code === "string" && REFUSAL_CODES.includes(code) ? code : null;
2132
+ return name === "MirrorAnswerRefused" && typeof code === "string" && Object.prototype.hasOwnProperty.call(REFUSAL_CODES, code) ? code : null;
2131
2133
  }
2132
2134
  function pathLabel(path) {
2133
2135
  return path ? ` (${path.split("?")[0]})` : "";
@@ -2136,8 +2138,24 @@ var mirrorRefusal = {
2136
2138
  redirect: (path) => new MirrorAnswerRefused("redirect", `mirror node answered with a redirect, which is not followed${pathLabel(path)}`),
2137
2139
  tooLarge: (maxBytes, path) => new MirrorAnswerRefused("too-large", `mirror node answer is larger than ${maxBytes} bytes${pathLabel(path)}`),
2138
2140
  tooManyLogs: (asked, path) => new MirrorAnswerRefused("too-many-logs", `mirror node returned more logs than the ${asked} asked for${pathLabel(path)}`),
2139
- nextPage: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that is not this contract's log")
2141
+ nextPage: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that is not this contract's log"),
2142
+ /** A page whose logs do not come after the last log read. */
2143
+ notForward: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that does not follow the last"),
2144
+ scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `mirror node log scan did not finish in ${budgetMs}ms`),
2145
+ scanTooManyRequests: (requests) => new MirrorAnswerRefused("too-long", `mirror node log scan passed ${requests} requests`),
2146
+ scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `mirror node log scan kept more than ${logs} logs`)
2140
2147
  };
2148
+ var rpcRefusal = {
2149
+ redirect: () => new MirrorAnswerRefused("redirect", "RPC endpoint answered with a redirect, which is not followed"),
2150
+ tooLarge: (maxBytes) => new MirrorAnswerRefused("too-large", `RPC endpoint answer is larger than ${maxBytes} bytes`),
2151
+ scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `RPC log scan did not finish in ${budgetMs}ms`),
2152
+ scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `RPC log scan kept more than ${logs} logs`)
2153
+ };
2154
+ var LOG_SCAN_BUDGET_TIMEOUTS = 60;
2155
+ var LOG_SCAN_MAX_REQUESTS = 1e4;
2156
+ var LOG_SCAN_MAX_KEPT_LOGS = 1e6;
2157
+ var KEPT_LOG_DATA_MAX_CHARS = 2 + 64 * 3;
2158
+ var KEPT_LOG_MAX_TOPICS = 3;
2141
2159
  function isMirrorRedirect(response) {
2142
2160
  return response.redirected === true || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400;
2143
2161
  }
@@ -2252,7 +2270,16 @@ function parseLedgerWriteLog(log, expected) {
2252
2270
  };
2253
2271
  }
2254
2272
 
2273
+ // ../shared/src/records/inspect-record-calldata-v1.ts
2274
+ var MIRROR_NODE_BY_CHAIN = Object.freeze({
2275
+ 296: "https://testnet.mirrornode.hedera.com",
2276
+ 295: "https://mainnet-public.mirrornode.hedera.com"
2277
+ });
2278
+
2255
2279
  // ../shared/src/demo/independent-verify-records.ts
2280
+ var import_ethers12 = require("ethers");
2281
+
2282
+ // ../shared/src/chain/rpc-guarded-send.ts
2256
2283
  var import_ethers11 = require("ethers");
2257
2284
 
2258
2285
  // ../shared/src/chain/rpc-provider.ts
@@ -2262,7 +2289,7 @@ var MIN_SECRET_LENGTH = 8;
2262
2289
  var URL_IN_TEXT = /[a-z][a-z0-9+.-]*:\/\/[^\s"'<>\\`]+/gi;
2263
2290
  var RAW_SEPARATORS = /[/?&=#;@:]/;
2264
2291
  var ETHERS_ERROR_EXTRA_FIELDS = ["operation", "reason", "event"];
2265
- function normalizeRpcUrl(value) {
2292
+ function rpcHttpUrl(value) {
2266
2293
  const trimmed = value.trim();
2267
2294
  if (trimmed.startsWith("wss://")) return trimmed.replace(/^wss:\/\//, "https://");
2268
2295
  if (trimmed.startsWith("ws://")) return trimmed.replace(/^ws:\/\//, "http://");
@@ -2270,7 +2297,7 @@ function normalizeRpcUrl(value) {
2270
2297
  }
2271
2298
  function rpcEndpointLabel(value) {
2272
2299
  try {
2273
- return new URL(normalizeRpcUrl(value)).hostname.toLowerCase();
2300
+ return new URL(rpcHttpUrl(value)).hostname.toLowerCase();
2274
2301
  } catch {
2275
2302
  return "unparseable-rpc-endpoint";
2276
2303
  }
@@ -2369,14 +2396,124 @@ function redactRpcError(error, secrets) {
2369
2396
  }
2370
2397
  return new Error(cleanText(String(error), secrets));
2371
2398
  }
2399
+ var RpcResultUnavailableError = class extends Error {
2400
+ constructor(what, reason) {
2401
+ super(`${what} from the RPC is incomplete: ${reason}`);
2402
+ this.code = "RPC_RESULT_UNAVAILABLE";
2403
+ this.name = "RpcResultUnavailableError";
2404
+ }
2405
+ };
2406
+ var HEX_QUANTITY = /^0x[0-9a-f]+$/i;
2407
+ function parseRpcQuantity(value, what) {
2408
+ if (typeof value !== "string" || !HEX_QUANTITY.test(value)) {
2409
+ throw new RpcResultUnavailableError(what, "not a hex quantity");
2410
+ }
2411
+ return BigInt(value);
2412
+ }
2413
+ var QUANTITY_RESULTS = {
2414
+ getBlockNumber: "eth_blockNumber",
2415
+ getTransactionCount: "eth_getTransactionCount",
2416
+ getBalance: "eth_getBalance",
2417
+ getGasPrice: "eth_gasPrice",
2418
+ getPriorityFee: "eth_maxPriorityFeePerGas",
2419
+ estimateGas: "eth_estimateGas"
2420
+ };
2421
+ function incompleteReason(error) {
2422
+ const short = String(error?.shortMessage ?? error?.message ?? error);
2423
+ const field = /^invalid value for value\.(\w+) \(([^(]*)/.exec(short);
2424
+ return field ? `${field[1]}: ${field[2].trim()}` : short.split(" (")[0];
2425
+ }
2426
+ function formatted(what, format) {
2427
+ try {
2428
+ return format();
2429
+ } catch (error) {
2430
+ throw new RpcResultUnavailableError(what, incompleteReason(error));
2431
+ }
2432
+ }
2433
+ var SUBSCRIBE_METHODS = /* @__PURE__ */ new Set(["eth_subscribe", "eth_newFilter"]);
2434
+ var UNSUBSCRIBE_METHODS = /* @__PURE__ */ new Set(["eth_unsubscribe", "eth_uninstallFilter"]);
2435
+ var SUBSCRIBE_RETRY_BASE_MS = 1e3;
2436
+ var SUBSCRIBE_RETRY_MAX_MS = 6e4;
2437
+ var REJECTION_MESSAGE_MAX = 300;
2438
+ function rejectionMessage(error, secrets) {
2439
+ const inner = error?.error?.message;
2440
+ let text;
2441
+ if (typeof inner === "string") text = inner;
2442
+ else if (isEthersError(error)) text = error.shortMessage;
2443
+ else if (isErrorLike(error)) text = error.message;
2444
+ else text = String(error);
2445
+ return cleanText(text, secrets).slice(0, REJECTION_MESSAGE_MAX);
2446
+ }
2447
+ function pause(ms) {
2448
+ return new Promise((resolve) => {
2449
+ const timer = setTimeout(resolve, ms);
2450
+ timer.unref?.();
2451
+ });
2452
+ }
2453
+ async function guardSubscriptionSend(method, send, provider, retry, secrets) {
2454
+ const report = (rejection) => {
2455
+ try {
2456
+ retry.onRejected?.(rejection);
2457
+ } catch {
2458
+ }
2459
+ };
2460
+ if (UNSUBSCRIBE_METHODS.has(method)) {
2461
+ try {
2462
+ return await send();
2463
+ } catch (error) {
2464
+ report({ method, attempt: 1, retryInMs: null, message: rejectionMessage(error, secrets) });
2465
+ return false;
2466
+ }
2467
+ }
2468
+ if (!SUBSCRIBE_METHODS.has(method)) return send();
2469
+ const base = retry.baseDelayMs ?? SUBSCRIBE_RETRY_BASE_MS;
2470
+ const max = retry.maxDelayMs ?? SUBSCRIBE_RETRY_MAX_MS;
2471
+ for (let attempt = 1; ; attempt += 1) {
2472
+ try {
2473
+ return await send();
2474
+ } catch (error) {
2475
+ if (provider.destroyed) return new Promise(() => void 0);
2476
+ const retryInMs = Math.min(base * 2 ** (attempt - 1), max);
2477
+ report({ method, attempt, retryInMs, message: rejectionMessage(error, secrets) });
2478
+ await pause(retryInMs);
2479
+ if (provider.destroyed) return new Promise(() => void 0);
2480
+ }
2481
+ }
2482
+ }
2483
+ function requestFor(url, options) {
2484
+ const request = new import_ethers10.FetchRequest(url);
2485
+ if (options.timeoutMs !== void 0) request.timeout = options.timeoutMs;
2486
+ options.prepareRequest?.(request);
2487
+ return request;
2488
+ }
2489
+ var CHAIN_ID_RESULT = /^0x[0-9a-f]{1,13}$/i;
2490
+ async function readRpcChainId(url, options = {}) {
2491
+ const secrets = rpcUrlSecrets(url);
2492
+ try {
2493
+ const request = requestFor(url, options);
2494
+ request.body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_chainId", params: [] });
2495
+ request.setHeader("content-type", "application/json");
2496
+ const response = await request.send();
2497
+ response.assertOk();
2498
+ const answer = response.bodyJson;
2499
+ const result = answer !== null && typeof answer === "object" ? answer.result : void 0;
2500
+ if (typeof result !== "string" || !CHAIN_ID_RESULT.test(result)) throw new RpcResultUnavailableError("eth_chainId", "not a chain id");
2501
+ return Number.parseInt(result, 16);
2502
+ } catch (error) {
2503
+ throw redactRpcError(error, secrets);
2504
+ }
2505
+ }
2372
2506
  var RedactingJsonRpcProvider = class extends import_ethers10.JsonRpcProvider {
2373
2507
  #secrets;
2508
+ #subscriptionRetry;
2374
2509
  constructor(url, network, options) {
2375
- const { timeoutMs, ...providerOptions } = options;
2376
- const request = new import_ethers10.FetchRequest(url);
2377
- if (timeoutMs !== void 0) request.timeout = timeoutMs;
2378
- super(request, network, providerOptions);
2510
+ const { timeoutMs, subscriptionRetry, prepareRequest, ...providerOptions } = options;
2511
+ super(requestFor(url, { timeoutMs, prepareRequest }), network, providerOptions);
2379
2512
  this.#secrets = rpcUrlSecrets(url);
2513
+ this.#subscriptionRetry = subscriptionRetry ?? {};
2514
+ }
2515
+ send(method, params) {
2516
+ return guardSubscriptionSend(method, () => super.send(method, params), this, this.#subscriptionRetry, this.#secrets);
2380
2517
  }
2381
2518
  async _send(payload) {
2382
2519
  try {
@@ -2385,11 +2522,123 @@ var RedactingJsonRpcProvider = class extends import_ethers10.JsonRpcProvider {
2385
2522
  throw redactRpcError(error, this.#secrets);
2386
2523
  }
2387
2524
  }
2525
+ async _perform(req) {
2526
+ const result = await super._perform(req);
2527
+ const method = QUANTITY_RESULTS[req.method];
2528
+ if (method) parseRpcQuantity(result, method);
2529
+ return result;
2530
+ }
2531
+ _wrapTransactionResponse(tx, network) {
2532
+ return formatted("transaction", () => super._wrapTransactionResponse(tx, network));
2533
+ }
2534
+ _wrapTransactionReceipt(value, network) {
2535
+ return formatted("transaction receipt", () => super._wrapTransactionReceipt(value, network));
2536
+ }
2537
+ _wrapBlock(value, network) {
2538
+ return formatted("block", () => super._wrapBlock(value, network));
2539
+ }
2540
+ _wrapLog(value, network) {
2541
+ return formatted("log", () => super._wrapLog(value, network));
2542
+ }
2388
2543
  };
2389
2544
  function createRpcProvider(url, network, options = {}) {
2390
2545
  return new RedactingJsonRpcProvider(url, network, options);
2391
2546
  }
2392
2547
 
2548
+ // ../shared/src/chain/rpc-guarded-send.ts
2549
+ var RPC_READER_MAX_TRIES = 3;
2550
+ function basicAuthorization(username, password) {
2551
+ const decoded = (value) => {
2552
+ try {
2553
+ return decodeURIComponent(value);
2554
+ } catch {
2555
+ return value;
2556
+ }
2557
+ };
2558
+ const bytes2 = new TextEncoder().encode(`${decoded(username)}:${decoded(password)}`);
2559
+ let binary = "";
2560
+ for (const byte of bytes2) binary += String.fromCharCode(byte);
2561
+ return `Basic ${btoa(binary)}`;
2562
+ }
2563
+ function createGuardedRpcSend(options = {}) {
2564
+ const maxBytes = options.maxBytes ?? MIRROR_ANSWER_MAX_BYTES;
2565
+ return async (req, signal) => {
2566
+ if (signal?.cancelled) throw (0, import_ethers11.makeError)("request cancelled before sending", "CANCELLED");
2567
+ const fetchImpl = options.fetchImpl ?? fetch;
2568
+ const secrets = rpcUrlSecrets(req.url);
2569
+ const url = new URL(req.url);
2570
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
2571
+ throw (0, import_ethers11.makeError)(`unsupported protocol ${url.protocol.replace(/:$/, "")}`, "UNSUPPORTED_OPERATION", { operation: "request" });
2572
+ }
2573
+ const headers = {};
2574
+ for (const [name, value] of Object.entries(req.headers)) {
2575
+ const lower = name.toLowerCase();
2576
+ if (lower === "content-length" || lower === "accept-encoding") continue;
2577
+ headers[lower] = value;
2578
+ }
2579
+ if (url.username !== "" || url.password !== "") {
2580
+ if (headers.authorization === void 0) headers.authorization = basicAuthorization(url.username, url.password);
2581
+ url.username = "";
2582
+ url.password = "";
2583
+ }
2584
+ const controller = new AbortController();
2585
+ let timedOut = false;
2586
+ const timer = setTimeout(() => {
2587
+ timedOut = true;
2588
+ controller.abort();
2589
+ }, req.timeout);
2590
+ let cancelled = false;
2591
+ signal?.addListener(() => {
2592
+ cancelled = true;
2593
+ controller.abort();
2594
+ });
2595
+ try {
2596
+ const body = req.body;
2597
+ const response = await fetchImpl(url.toString(), {
2598
+ method: req.method,
2599
+ headers,
2600
+ ...body ? { body } : {},
2601
+ redirect: "manual",
2602
+ signal: controller.signal
2603
+ });
2604
+ if (isMirrorRedirect(response)) {
2605
+ await response.body?.cancel?.().catch(() => void 0);
2606
+ throw rpcRefusal.redirect();
2607
+ }
2608
+ let text;
2609
+ try {
2610
+ text = await readMirrorText(response, maxBytes);
2611
+ } catch (error) {
2612
+ if (mirrorRefusalOf(error) === "too-large") throw rpcRefusal.tooLarge(maxBytes);
2613
+ throw error;
2614
+ }
2615
+ const answered = {};
2616
+ response.headers.forEach((value, name) => {
2617
+ answered[name.toLowerCase()] = value;
2618
+ });
2619
+ return { statusCode: response.status, statusMessage: response.statusText, headers: answered, body: new TextEncoder().encode(replaceRpcSecrets(text, secrets)) };
2620
+ } catch (error) {
2621
+ if (mirrorRefusalOf(error)) throw error;
2622
+ if (cancelled) throw (0, import_ethers11.makeError)("request cancelled", "CANCELLED");
2623
+ if (timedOut) throw (0, import_ethers11.makeError)("request timeout", "TIMEOUT", { operation: "request.send", reason: "timeout" });
2624
+ throw error;
2625
+ } finally {
2626
+ clearTimeout(timer);
2627
+ }
2628
+ };
2629
+ }
2630
+ function retryAfterMs(value) {
2631
+ return typeof value === "string" && /^[1-9][0-9]*$/.test(value) ? Number.parseInt(value, 10) : null;
2632
+ }
2633
+ function holdRpcRequest(request, options = {}) {
2634
+ request.getUrlFunc = createGuardedRpcSend(options);
2635
+ request.retryFunc = async (req, response, attempt) => {
2636
+ if (attempt >= RPC_READER_MAX_TRIES - 1) return false;
2637
+ const wait = retryAfterMs(response.headers["retry-after"]);
2638
+ return wait === null || wait <= req.timeout;
2639
+ };
2640
+ }
2641
+
2393
2642
  // ../shared/src/demo/independent-verify-records.ts
2394
2643
  var RECORD_LANE_ABI_V38 = [
2395
2644
  "function getRecord(bytes32 recordKey) view returns (uint256)",
@@ -2401,23 +2650,25 @@ var RECORD_LANE_ABI_V38 = [
2401
2650
  "event RecordWritten(bytes32 indexed recordKey, address indexed operator, uint8 encodingVersion, uint256 previousWord, uint256 newWord)",
2402
2651
  "event LedgerHeadAdvanced(uint256 indexed batchId, bytes32 merkleRoot, bytes32 previousHead, bytes32 newHead)"
2403
2652
  ];
2404
- var LEDGER_HEAD_ADVANCED_TOPIC = import_ethers11.ethers.id("LedgerHeadAdvanced(uint256,bytes32,bytes32,bytes32)");
2405
- var RECORD_WRITTEN_TOPIC = import_ethers11.ethers.id("RecordWritten(bytes32,address,uint8,uint256,uint256)");
2653
+ var LEDGER_HEAD_ADVANCED_TOPIC = import_ethers12.ethers.id("LedgerHeadAdvanced(uint256,bytes32,bytes32,bytes32)");
2654
+ var RECORD_WRITTEN_TOPIC = import_ethers12.ethers.id("RecordWritten(bytes32,address,uint8,uint256,uint256)");
2406
2655
  var LAYOUT_NOT_REGISTERED = "layout-not-registered";
2407
2656
  function checkLayoutOnChain(onChainLayout, published) {
2408
2657
  const matchesPublished = !!published && onChainLayout.registered && onChainLayout.layoutDigest === published.digest;
2409
2658
  return { ...onChainLayout, matchesPublished, failure: matchesPublished ? null : LAYOUT_NOT_REGISTERED };
2410
2659
  }
2411
- function normalizeRpcUrl2(url) {
2660
+ function normalizeRpcUrl(url) {
2412
2661
  const trimmed = String(url || "").trim();
2413
2662
  if (trimmed.startsWith("wss://")) return trimmed.replace(/^wss:\/\//, "https://");
2414
2663
  if (trimmed.startsWith("ws://")) return trimmed.replace(/^ws:\/\//, "http://");
2415
2664
  return trimmed;
2416
2665
  }
2666
+ var ReadTimedOut = class extends Error {
2667
+ };
2417
2668
  async function withTimeout(p, ms, label) {
2418
2669
  let timer;
2419
2670
  const timeout = new Promise((_, reject) => {
2420
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
2671
+ timer = setTimeout(() => reject(new ReadTimedOut(`${label} timed out after ${ms}ms`)), ms);
2421
2672
  });
2422
2673
  try {
2423
2674
  return await Promise.race([p, timeout]);
@@ -2426,26 +2677,73 @@ async function withTimeout(p, ms, label) {
2426
2677
  }
2427
2678
  }
2428
2679
  function createRpcRecordChainReader(options) {
2429
- const rpcUrl = normalizeRpcUrl2(options.rpcUrl);
2680
+ const rpcUrl = normalizeRpcUrl(options.rpcUrl);
2430
2681
  if (!rpcUrl) throw new Error("rpcUrl is required.");
2431
- const contractAddress = import_ethers11.ethers.getAddress(options.contractAddress).toLowerCase();
2682
+ const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
2432
2683
  const timeoutMs = Number(options.timeoutMs || 1e4);
2433
2684
  const chunk = Math.max(1, Number(options.logsChunkSize || 2e3));
2434
- const network = options.chainId != null ? new import_ethers11.ethers.Network(`chain-${options.chainId}`, options.chainId) : void 0;
2435
- const provider = network ? createRpcProvider(rpcUrl, network, { staticNetwork: network }) : createRpcProvider(rpcUrl);
2436
- const contract = new import_ethers11.ethers.Contract(contractAddress, RECORD_LANE_ABI_V38, provider);
2437
- const iface = new import_ethers11.ethers.Interface(RECORD_LANE_ABI_V38);
2685
+ const now = options.scan?.now ?? Date.now;
2686
+ const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
2687
+ const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
2688
+ const prepareRequest = (request) => holdRpcRequest(request);
2689
+ const endpointFor = (chainId) => {
2690
+ const network = new import_ethers12.ethers.Network(`chain-${chainId}`, chainId);
2691
+ const provider = createRpcProvider(rpcUrl, network, { staticNetwork: network, timeoutMs, prepareRequest });
2692
+ return { provider, contract: new import_ethers12.ethers.Contract(contractAddress, RECORD_LANE_ABI_V38, provider) };
2693
+ };
2694
+ let ready = options.chainId != null ? Promise.resolve(endpointFor(options.chainId)) : null;
2695
+ function endpoint() {
2696
+ if (!ready) {
2697
+ const pending = readRpcChainId(rpcUrl, { timeoutMs, prepareRequest }).then(endpointFor);
2698
+ ready = pending;
2699
+ pending.catch(() => {
2700
+ if (ready === pending) ready = null;
2701
+ });
2702
+ }
2703
+ return ready;
2704
+ }
2705
+ function keptLog(log, topic0) {
2706
+ return String(log.address).toLowerCase() === contractAddress && log.topics.length <= KEPT_LOG_MAX_TOPICS && String(log.topics[0] ?? "").toLowerCase() === topic0 && typeof log.data === "string" && log.data.length <= KEPT_LOG_DATA_MAX_CHARS;
2707
+ }
2438
2708
  async function scanLogs(topics, fromBlock, toBlock, label) {
2439
- const latest = toBlock === "latest" ? await withTimeout(provider.getBlockNumber(), timeoutMs, "getBlockNumber") : toBlock;
2709
+ const { provider } = await endpoint();
2710
+ const budgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
2711
+ const deadline = now() + budgetMs;
2712
+ const topic0 = String(topics[0] ?? "").toLowerCase();
2713
+ const ask = async (send, what) => {
2714
+ const left = deadline - now();
2715
+ if (left <= 0) throw rpcRefusal.scanTooSlow(budgetMs);
2716
+ const allowed = Math.min(timeoutMs, left);
2717
+ try {
2718
+ return await withTimeout(send(), allowed, what);
2719
+ } catch (error) {
2720
+ if (error instanceof ReadTimedOut && allowed < timeoutMs) throw rpcRefusal.scanTooSlow(budgetMs);
2721
+ if (!mirrorRefusalOf(error) && now() >= deadline) throw rpcRefusal.scanTooSlow(budgetMs);
2722
+ throw error;
2723
+ }
2724
+ };
2725
+ const latest = toBlock === "latest" ? await ask(() => provider.getBlockNumber(), "getBlockNumber") : toBlock;
2440
2726
  const out = [];
2727
+ const pending = [];
2441
2728
  for (let start = fromBlock; start <= latest; start += chunk) {
2442
- const end = Math.min(latest, start + chunk - 1);
2443
- const logs = await withTimeout(
2444
- provider.getLogs({ address: contractAddress, topics, fromBlock: start, toBlock: end }),
2445
- timeoutMs,
2446
- `getLogs ${label} (${start}-${end})`
2447
- );
2448
- out.push(...logs);
2729
+ pending.push([start, Math.min(latest, start + chunk - 1)]);
2730
+ while (pending.length > 0) {
2731
+ const [from, to] = pending.pop();
2732
+ let logs;
2733
+ try {
2734
+ logs = await ask(() => provider.getLogs({ address: contractAddress, topics, fromBlock: from, toBlock: to }), `getLogs ${label} (${from}-${to})`);
2735
+ } catch (error) {
2736
+ if (mirrorRefusalOf(error) !== "too-large" || from >= to) throw error;
2737
+ const middle = from + Math.floor((to - from) / 2);
2738
+ pending.push([middle + 1, to], [from, middle]);
2739
+ continue;
2740
+ }
2741
+ for (const log of logs) {
2742
+ if (!keptLog(log, topic0)) continue;
2743
+ if (out.length >= maxKeptLogs) throw rpcRefusal.scanTooManyLogs(maxKeptLogs);
2744
+ out.push(log);
2745
+ }
2746
+ }
2449
2747
  }
2450
2748
  return out;
2451
2749
  }
@@ -2453,10 +2751,12 @@ function createRpcRecordChainReader(options) {
2453
2751
  contractAddress,
2454
2752
  async getRecord(recordKey) {
2455
2753
  const key = normalizeProofHash(recordKey, "recordKey");
2754
+ const { contract } = await endpoint();
2456
2755
  const word = await withTimeout(contract.getRecord(key), timeoutMs, "getRecord");
2457
2756
  return hex256(BigInt(word));
2458
2757
  },
2459
2758
  async getLayout(layoutId) {
2759
+ const { contract } = await endpoint();
2460
2760
  const l = await withTimeout(contract.getLayout(layoutId), timeoutMs, "getLayout");
2461
2761
  return {
2462
2762
  layoutDigest: String(l[0]).toLowerCase(),
@@ -2466,10 +2766,12 @@ function createRpcRecordChainReader(options) {
2466
2766
  };
2467
2767
  },
2468
2768
  async getBatchRoot(batchId) {
2769
+ const { contract } = await endpoint();
2469
2770
  const root = await withTimeout(contract.getBatchRoot(BigInt(batchId)), timeoutMs, "getBatchRoot");
2470
2771
  return normalizeProofHash(String(root), "observedProofRoot");
2471
2772
  },
2472
2773
  async getLedgerHead() {
2774
+ const { contract } = await endpoint();
2473
2775
  const head = await withTimeout(contract.getLedgerHead(), timeoutMs, "getLedgerHead");
2474
2776
  return normalizeProofHash(String(head), "ledgerHead");
2475
2777
  },
@@ -2512,14 +2814,18 @@ function createRpcRecordChainReader(options) {
2512
2814
  },
2513
2815
  async findRecordWrites(recordKey, search) {
2514
2816
  const key = normalizeProofHash(recordKey, "recordKey");
2515
- const now = search.now ?? Date.now;
2516
- const deadline = now() + search.budgetMs;
2817
+ const now2 = search.now ?? Date.now;
2818
+ const deadline = now2() + search.budgetMs;
2517
2819
  const writes = [];
2518
2820
  const blockTimes = /* @__PURE__ */ new Map();
2519
2821
  let requests = 0;
2822
+ const asked = () => {
2823
+ requests += 1;
2824
+ search.onRequest?.();
2825
+ };
2520
2826
  const CUT = Symbol("cut");
2521
2827
  const within2 = async (p) => {
2522
- const left = deadline - now();
2828
+ const left = deadline - now2();
2523
2829
  if (left <= 0) return CUT;
2524
2830
  let timer;
2525
2831
  const cut = new Promise((resolve) => {
@@ -2534,13 +2840,16 @@ function createRpcRecordChainReader(options) {
2534
2840
  };
2535
2841
  const end = (ended) => ({ writes, ended, requests });
2536
2842
  if (search.maxRequests < 1) return end("limit");
2537
- requests += 1;
2843
+ const found = await within2(endpoint());
2844
+ if (found === CUT) return end("timeout");
2845
+ const { provider } = found;
2846
+ asked();
2538
2847
  const latest = await within2(provider.getBlockNumber());
2539
2848
  if (latest === CUT) return end("timeout");
2540
2849
  for (let to = latest; to >= 0; to -= chunk) {
2541
2850
  if (search.done(writes)) return end("done");
2542
- if (requests >= search.maxRequests || now() >= deadline) return end("limit");
2543
- requests += 1;
2851
+ if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
2852
+ asked();
2544
2853
  const logs = await within2(provider.getLogs({ address: contractAddress, topics: [RECORD_WRITTEN_TOPIC, key], fromBlock: Math.max(0, to - chunk + 1), toBlock: to }));
2545
2854
  if (logs === CUT) return end("timeout");
2546
2855
  for (const log of [...logs].reverse()) {
@@ -2548,8 +2857,8 @@ function createRpcRecordChainReader(options) {
2548
2857
  if (!parsed) continue;
2549
2858
  let committedAt = blockTimes.get(log.blockNumber);
2550
2859
  if (committedAt === void 0) {
2551
- if (requests >= search.maxRequests || now() >= deadline) return end("limit");
2552
- requests += 1;
2860
+ if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
2861
+ asked();
2553
2862
  const block = await within2(provider.getBlock(log.blockNumber));
2554
2863
  if (block === CUT) return end("timeout");
2555
2864
  if (!block || !Number.isSafeInteger(block.timestamp)) throw new Error(`getBlock ${log.blockNumber} returned no time`);
@@ -2593,7 +2902,7 @@ async function readLedgerMaterial(reader, log, options) {
2593
2902
  log,
2594
2903
  `eth_getLogs LedgerHeadAdvanced from block ${options.fromBlock ?? 0}`
2595
2904
  );
2596
- const genesisHead = options.genesisHead ?? (advances[0]?.previousHead ?? import_ethers11.ethers.ZeroHash);
2905
+ const genesisHead = options.genesisHead ?? (advances[0]?.previousHead ?? import_ethers12.ethers.ZeroHash);
2597
2906
  return {
2598
2907
  genesisHead,
2599
2908
  batches: advances.map((a) => ({ batchId: a.batchId, merkleRoot: a.merkleRoot })),
@@ -2658,13 +2967,42 @@ function committedAtOf(timestamp) {
2658
2967
  const [seconds, fraction] = timestamp.split(".");
2659
2968
  return new Date(Number(seconds) * 1e3 + Number(fraction.slice(0, 3))).toISOString();
2660
2969
  }
2970
+ var SearchLimited = class {
2971
+ constructor(retryAfterMs2) {
2972
+ this.retryAfterMs = retryAfterMs2;
2973
+ }
2974
+ };
2975
+ function retryAfterMsOf(response) {
2976
+ const value = response.headers?.get?.("retry-after");
2977
+ return typeof value === "string" && /^\d{1,6}$/.test(value.trim()) ? Number(value.trim()) * 1e3 : null;
2978
+ }
2661
2979
  var KEPT_TOPICS = [RECORD_WRITTEN_TOPIC.toLowerCase(), LEDGER_HEAD_ADVANCED_TOPIC.toLowerCase()];
2662
- function keptMirrorLog(raw) {
2980
+ var HEX_DATA2 = /^0x[0-9a-fA-F]*$/;
2981
+ function mirrorLogPosition(raw) {
2982
+ if (!raw || typeof raw !== "object") return null;
2983
+ const { timestamp, index } = raw;
2984
+ if (typeof timestamp !== "string" || !CONSENSUS_TIMESTAMP.test(timestamp)) return null;
2985
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return null;
2986
+ const [seconds, fraction] = timestamp.split(".");
2987
+ return { nanos: BigInt(seconds) * 1000000000n + BigInt(fraction), index };
2988
+ }
2989
+ function mirrorLogFollows(last, next) {
2990
+ return last === null || next.nanos > last.nanos || next.nanos === last.nanos && next.index > last.index;
2991
+ }
2992
+ function keptMirrorLog(raw, contract) {
2663
2993
  if (!raw || typeof raw !== "object") return null;
2664
2994
  const log = raw;
2665
2995
  if (!Array.isArray(log.topics) || typeof log.data !== "string") return null;
2996
+ if (log.topics.length > KEPT_LOG_MAX_TOPICS || log.data.length > KEPT_LOG_DATA_MAX_CHARS || !HEX_DATA2.test(log.data)) return null;
2666
2997
  const topics = log.topics.map((topic) => String(topic));
2667
2998
  if (!KEPT_TOPICS.includes((topics[0] ?? "").toLowerCase())) return null;
2999
+ if (topics.some((topic) => topic.length > 66)) return null;
3000
+ if (contract !== void 0) {
3001
+ if (typeof log.address !== "string" || log.address.toLowerCase() !== contract) return null;
3002
+ if (!mirrorLogPosition(raw)) return null;
3003
+ if (typeof log.block_number !== "number" || !Number.isSafeInteger(log.block_number)) return null;
3004
+ if (typeof log.transaction_hash !== "string" || log.transaction_hash.length > 98) return null;
3005
+ }
2668
3006
  return {
2669
3007
  address: log.address,
2670
3008
  data: log.data,
@@ -2679,18 +3017,25 @@ function createMirrorNodeRecordChainReader(options) {
2679
3017
  const chainId = options.chainId ?? 296;
2680
3018
  const base = (options.mirrorBaseUrl ?? MIRROR_NODE_BY_CHAIN[chainId] ?? "").replace(/\/+$/, "");
2681
3019
  if (!base) throw new Error(`No mirror node known for chain ${chainId}; pass mirrorBaseUrl.`);
2682
- const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
3020
+ const contractAddress = import_ethers13.ethers.getAddress(options.contractAddress).toLowerCase();
2683
3021
  const timeoutMs = Number(options.timeoutMs || 1e4);
2684
3022
  const pageSize = Math.min(100, Math.max(1, Number(options.pageSize || 100)));
2685
3023
  const attempts = Math.max(1, options.attempts ?? 3);
2686
3024
  const fetchImpl = options.fetchImpl ?? fetch;
2687
- const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
2688
- async function request(path, init) {
3025
+ const iface = new import_ethers13.ethers.Interface(RECORD_LANE_ABI_V38);
3026
+ const now = options.scan?.now ?? Date.now;
3027
+ const maxScanRequests = options.scan?.maxRequests ?? LOG_SCAN_MAX_REQUESTS;
3028
+ const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
3029
+ const scanBudgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
3030
+ async function request(path, init, deadline) {
2689
3031
  const url = `${base}${path}`;
2690
3032
  let lastError = null;
2691
3033
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
3034
+ const left = deadline === void 0 ? timeoutMs : deadline - now();
3035
+ if (left <= 0) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
3036
+ const allowed = Math.min(timeoutMs, left);
2692
3037
  const controller = new AbortController();
2693
- const timer = setTimeout(() => controller.abort(), timeoutMs);
3038
+ const timer = setTimeout(() => controller.abort(), allowed);
2694
3039
  try {
2695
3040
  const response = await fetchImpl(url, { ...init, redirect: "manual", signal: controller.signal });
2696
3041
  if (isMirrorRedirect(response)) {
@@ -2708,14 +3053,17 @@ function createMirrorNodeRecordChainReader(options) {
2708
3053
  }
2709
3054
  } catch (error) {
2710
3055
  if (mirrorRefusalOf(error)) throw error;
2711
- if (error.name === "AbortError") lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
2712
- else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
3056
+ if (error.name === "AbortError") {
3057
+ if (deadline !== void 0 && allowed < timeoutMs) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
3058
+ lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
3059
+ } else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
2713
3060
  else lastError = error;
2714
3061
  } finally {
2715
3062
  clearTimeout(timer);
2716
3063
  }
2717
3064
  if (attempt < attempts) await new Promise((resolve) => setTimeout(resolve, 250 * attempt));
2718
3065
  }
3066
+ if (deadline !== void 0 && now() >= deadline) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
2719
3067
  throw lastError ?? new Error(`mirror node request failed (${path})`);
2720
3068
  }
2721
3069
  async function call(fn, args = []) {
@@ -2751,16 +3099,23 @@ function createMirrorNodeRecordChainReader(options) {
2751
3099
  params.set("limit", String(pageSize));
2752
3100
  let next = `${contractLogPath(contractAddress)}?${params.toString()}`;
2753
3101
  const out = [];
2754
- let pages = 0;
3102
+ const scan = { deadline: now() + scanBudgetMs, requests: 0 };
3103
+ let last = null;
2755
3104
  let size = pageSize;
2756
3105
  while (next) {
2757
- const { page, asked } = await readLogPage(next, size);
3106
+ const { page, asked } = await readLogPage(next, size, scan);
2758
3107
  size = Math.min(pageSize, asked * 2);
2759
3108
  const logs = Array.isArray(page.logs) ? page.logs : [...page.logs ?? []];
2760
3109
  if (logs.length > asked) throw mirrorRefusal.tooManyLogs(asked, next);
2761
3110
  for (const raw of logs) {
2762
- const log = keptMirrorLog(raw);
2763
- if (log) out.push(log);
3111
+ const position = mirrorLogPosition(raw);
3112
+ if (!position) continue;
3113
+ if (!mirrorLogFollows(last, position)) throw mirrorRefusal.notForward();
3114
+ last = position;
3115
+ const log = keptMirrorLog(raw, contractAddress);
3116
+ if (!log) continue;
3117
+ if (out.length >= maxKeptLogs) throw mirrorRefusal.scanTooManyLogs(maxKeptLogs);
3118
+ out.push(log);
2764
3119
  }
2765
3120
  const link = page.links?.next;
2766
3121
  if (link === null || link === void 0 || link === "") {
@@ -2770,16 +3125,16 @@ function createMirrorNodeRecordChainReader(options) {
2770
3125
  if (!path) throw mirrorRefusal.nextPage();
2771
3126
  next = withLogPageLimit(path, size);
2772
3127
  }
2773
- pages += 1;
2774
- if (pages > 1e4) throw new Error("mirror node log scan exceeded 10,000 pages");
2775
3128
  }
2776
3129
  return out;
2777
3130
  }
2778
- async function readLogPage(path, start) {
3131
+ async function readLogPage(path, start, scan) {
2779
3132
  let asked = start;
2780
3133
  for (; ; ) {
3134
+ if (scan.requests >= maxScanRequests) throw mirrorRefusal.scanTooManyRequests(maxScanRequests);
3135
+ scan.requests += 1;
2781
3136
  try {
2782
- return { page: await request(withLogPageLimit(path, asked)), asked };
3137
+ return { page: await request(withLogPageLimit(path, asked), void 0, scan.deadline), asked };
2783
3138
  } catch (error) {
2784
3139
  if (mirrorRefusalOf(error) !== "too-large" || asked <= 1) throw error;
2785
3140
  asked = Math.max(1, Math.floor(asked / 2));
@@ -2803,6 +3158,10 @@ function createMirrorNodeRecordChainReader(options) {
2803
3158
  try {
2804
3159
  const response = await fetchImpl(`${base}${path}`, { headers: { accept: "application/json" }, redirect: "error", signal: controller.signal });
2805
3160
  if (isMirrorRedirect(response)) throw mirrorRefusal.redirect(path);
3161
+ if (response.status === 429) {
3162
+ await response.body?.cancel?.().catch(() => void 0);
3163
+ return new SearchLimited(retryAfterMsOf(response));
3164
+ }
2806
3165
  if (!response.ok) throw new Error(`mirror node ${response.status} for a record's writes`);
2807
3166
  const page = await readMirrorJson(response, MIRROR_ANSWER_MAX_BYTES, path);
2808
3167
  if (Array.isArray(page.logs) && page.logs.length > LEDGER_WRITE_SEARCH_PAGE_LIMIT) throw mirrorRefusal.tooManyLogs(LEDGER_WRITE_SEARCH_PAGE_LIMIT, path);
@@ -2873,7 +3232,8 @@ function createMirrorNodeRecordChainReader(options) {
2873
3232
  transactionHash: log.transaction_hash,
2874
3233
  logIndex: log.index,
2875
3234
  committedAt: committedAtOf(log.timestamp),
2876
- contractAddress: typeof log.address === "string" ? log.address.toLowerCase() : void 0
3235
+ contractAddress: typeof log.address === "string" ? log.address.toLowerCase() : void 0,
3236
+ ...typeof log.timestamp === "string" && CONSENSUS_TIMESTAMP.test(log.timestamp) ? { consensusTimestamp: log.timestamp } : {}
2877
3237
  });
2878
3238
  }
2879
3239
  return out;
@@ -2881,25 +3241,36 @@ function createMirrorNodeRecordChainReader(options) {
2881
3241
  async findRecordWrites(recordKey, search) {
2882
3242
  const key = normalizeProofHash(recordKey, "recordKey").toLowerCase();
2883
3243
  const topic0 = RECORD_WRITTEN_TOPIC.toLowerCase();
2884
- const now = search.now ?? Date.now;
2885
- const deadline = now() + search.budgetMs;
3244
+ const now2 = search.now ?? Date.now;
3245
+ const deadline = now2() + search.budgetMs;
2886
3246
  const windowSeconds = Math.max(1, Math.floor(search.windowSeconds ?? RECORD_WRITE_SEARCH_WINDOW_SECONDS));
2887
- const nowSeconds = Math.floor(now() / 1e3);
3247
+ const nowSeconds = Math.floor(now2() / 1e3);
2888
3248
  const hint = search.startAt ? Date.parse(search.startAt) : Number.NaN;
2889
3249
  let upper = Math.min(Number.isFinite(hint) ? Math.floor(hint / 1e3) : nowSeconds, nowSeconds) + DAY_SECONDS;
2890
3250
  const writes = [];
2891
3251
  let requests = 0;
3252
+ let waits = 0;
2892
3253
  const end = (ended) => ({ writes, ended, requests });
2893
3254
  while (!search.done(writes)) {
2894
3255
  if (upper <= 0) return end("limit");
2895
3256
  const lower = Math.max(0, upper - windowSeconds);
2896
3257
  let path = ledgerWriteSearchPath({ contractAddress, topic0, recordKey: key, lower, upper });
2897
3258
  while (path) {
2898
- const left = deadline - now();
3259
+ const left = deadline - now2();
2899
3260
  if (requests >= search.maxRequests || left <= 0) return end("limit");
2900
3261
  requests += 1;
3262
+ search.onRequest?.();
2901
3263
  const page = await searchPage(path, left);
2902
3264
  if (page === "timeout") return end("timeout");
3265
+ if (page instanceof SearchLimited) {
3266
+ const waitOut = search.waitOut;
3267
+ if (!waitOut || waits >= waitOut.times) throw new Error("mirror node 429 for a record's writes");
3268
+ waits += 1;
3269
+ const wait = Math.max(0, Math.min(waitOut.maxWaitMs, page.retryAfterMs ?? waitOut.waitMs));
3270
+ if (wait >= deadline - now2()) return end("limit");
3271
+ await (waitOut.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(wait);
3272
+ continue;
3273
+ }
2903
3274
  for (const log of Array.isArray(page?.logs) ? page.logs : []) {
2904
3275
  const write = parseLedgerWriteLog(log, { topic0, recordKey: key, contractAddress });
2905
3276
  if (!write || !CONSENSUS_TIMESTAMP.test(write.timestamp)) continue;
@@ -2912,10 +3283,11 @@ function createMirrorNodeRecordChainReader(options) {
2912
3283
  transactionHash: write.transactionHash,
2913
3284
  logIndex: write.logIndex ?? void 0,
2914
3285
  committedAt: write.committedAt,
2915
- contractAddress: write.address
3286
+ contractAddress: write.address,
3287
+ consensusTimestamp: write.timestamp
2916
3288
  });
2917
3289
  }
2918
- if (search.done(writes)) return end("done");
3290
+ if (!search.wholeWindows && search.done(writes)) return end("done");
2919
3291
  const link = page?.links?.next;
2920
3292
  path = nextLogPath(link, { base, contract: contractAddress });
2921
3293
  if (!path && link !== null && link !== void 0 && link !== "") throw mirrorRefusal.nextPage();
@@ -3151,7 +3523,7 @@ var hasOnly = (v, required, optional = []) => required.every((k) => Object.proto
3151
3523
  function computeSealHistoryDigestV1(form) {
3152
3524
  const rest = { ...form };
3153
3525
  delete rest.digest;
3154
- return import_ethers13.ethers.keccak256(import_ethers13.ethers.toUtf8Bytes(canonicalizeJcs(rest)));
3526
+ return import_ethers14.ethers.keccak256(import_ethers14.ethers.toUtf8Bytes(canonicalizeJcs(rest)));
3155
3527
  }
3156
3528
  function entryShapeOk2(e) {
3157
3529
  if (!isPlainObject4(e) || !hasOnly(e, ENTRY_KEYS, ["recordHash"])) return false;
@@ -3490,13 +3862,55 @@ var HEADER_BYTES = 1 + IV_BYTES2;
3490
3862
  // ../shared/src/records-crypto/wrap-shapes-v1.ts
3491
3863
  var SEP5 = new Uint8Array([0]);
3492
3864
 
3865
+ // ../shared/src/records/reader-crypto-v1.ts
3866
+ var SEP6 = new Uint8Array([0]);
3867
+ var P256_SPKI_PREFIX = Uint8Array.from([
3868
+ 48,
3869
+ 89,
3870
+ 48,
3871
+ 19,
3872
+ 6,
3873
+ 7,
3874
+ 42,
3875
+ 134,
3876
+ 72,
3877
+ 206,
3878
+ 61,
3879
+ 2,
3880
+ 1,
3881
+ 6,
3882
+ 8,
3883
+ 42,
3884
+ 134,
3885
+ 72,
3886
+ 206,
3887
+ 61,
3888
+ 3,
3889
+ 1,
3890
+ 7,
3891
+ 3,
3892
+ 66,
3893
+ 0
3894
+ ]);
3895
+
3896
+ // ../shared/src/records/shared-record-list-v1.ts
3897
+ var import_ethers15 = require("ethers");
3898
+
3899
+ // ../shared/src/records/shared-record-check-v1.ts
3900
+ var ZERO_WORD = `0x${"0".repeat(64)}`;
3901
+
3902
+ // ../shared/src/records/shared-record-copy-v1.ts
3903
+ var import_ethers16 = require("ethers");
3904
+
3493
3905
  // src/report.ts
3494
3906
  var REPORT_SCHEMA = "pacspace-check-report/v1";
3495
3907
  var SOURCE_REFUSAL_REASONS = {
3496
3908
  redirect: "its source answered with a redirect, which is not followed",
3497
3909
  "too-large": "its source gave an answer larger than this checker reads",
3498
3910
  "too-many-logs": "its source returned a longer page than was asked for",
3499
- "next-page": "its source pointed somewhere else for the next page"
3911
+ "next-page": "its source pointed somewhere else for the next page",
3912
+ "too-slow": "its source did not finish answering in the time allowed",
3913
+ "too-long": "it holds more than this checker reads in one run"
3500
3914
  };
3501
3915
  var ENCRYPTED_OPENED_SENTENCE = "Each entry was opened on this machine and matches its sealed record hash.";
3502
3916
  function refusedUnopenedSentence(k) {
@@ -3665,6 +4079,9 @@ function heldFileField(held) {
3665
4079
  return held ? { matched: held.matched, entries: held.entries, blinded: held.blinded } : void 0;
3666
4080
  }
3667
4081
  function buildReport(input) {
4082
+ return buildReportWithFacts(input).report;
4083
+ }
4084
+ function buildReportWithFacts(input) {
3668
4085
  const history = input.verification.history;
3669
4086
  const matched = history?.verifiedRecords ?? 0;
3670
4087
  const entries = history?.expectedRecords ?? (history ? matched : null);
@@ -3682,7 +4099,7 @@ function buildReport(input) {
3682
4099
  exportedAt: input.exportedAt
3683
4100
  };
3684
4101
  const statementFingerprint = statementFingerprintOf(input.statementFingerprint, intact, file.fingerprint);
3685
- const passed = input.verification.verified && (input.source.compared ? input.source.matches : true);
4102
+ const entriesMatch = input.verification.verified && (input.source.compared ? input.source.matches : true);
3686
4103
  const sentences = [];
3687
4104
  if (!intact) {
3688
4105
  sentences.push(FILE_CHANGED_SENTENCE);
@@ -3700,16 +4117,16 @@ function buildReport(input) {
3700
4117
  const fingerprintLine = fingerprintSentence(intact, statementFingerprint);
3701
4118
  if (fingerprintLine) sentences.push(fingerprintLine);
3702
4119
  if (input.heldFile) sentences.push(...heldFileSentences(input.heldFile));
3703
- const failed = !passed || input.dailyStatement?.matches === false || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
4120
+ const failed = !entriesMatch || input.dailyStatement?.matches === false || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3704
4121
  const unreachable = !input.source.compared && input.source.reason === "unreachable";
3705
4122
  const exitCode = exitCodeOf(unreachable, failed);
3706
4123
  if (closesWithBoundary(exitCode)) sentences.push(HONESTY_SENTENCE);
3707
- return {
4124
+ const report = {
3708
4125
  schema: REPORT_SCHEMA,
3709
4126
  checker: input.checker,
3710
4127
  ...input.form ? { form: input.form } : {},
3711
4128
  record,
3712
- passed,
4129
+ passed: exitCode === 0,
3713
4130
  file,
3714
4131
  source: input.source,
3715
4132
  dailyStatement: input.dailyStatement,
@@ -3719,8 +4136,12 @@ function buildReport(input) {
3719
4136
  sentences,
3720
4137
  exitCode
3721
4138
  };
4139
+ return { report, entriesMatch };
3722
4140
  }
3723
4141
  function buildSealsReport(input) {
4142
+ return buildSealsReportWithFacts(input).report;
4143
+ }
4144
+ function buildSealsReportWithFacts(input) {
3724
4145
  const v = input.verification;
3725
4146
  const failedCount = v.failedSeq.length;
3726
4147
  const record = {
@@ -3736,7 +4157,7 @@ function buildSealsReport(input) {
3736
4157
  const verdict = sealsVerdict(input.entries, v, input.queued);
3737
4158
  const disclosure = input.disclosure;
3738
4159
  const disclosureOk = !disclosure || disclosure.kind === "verified";
3739
- const passed = verdict.passed && v.verified && (input.source.compared ? input.source.matches : true) && disclosureOk;
4160
+ const entriesMatch = verdict.passed && v.verified && (input.source.compared ? input.source.matches : true) && disclosureOk;
3740
4161
  const sentences = [intact ? verdict.sentence : FILE_CHANGED_SENTENCE];
3741
4162
  if (disclosure?.kind === "verified") {
3742
4163
  sentences.push(revealedLine(disclosure.revealed.length, input.entries ?? disclosure.revealed.length));
@@ -3750,16 +4171,16 @@ function buildSealsReport(input) {
3750
4171
  const fingerprintLine = fingerprintSentence(intact, statementFingerprint);
3751
4172
  if (fingerprintLine) sentences.push(fingerprintLine);
3752
4173
  if (input.heldFile && disclosure?.kind === "verified") sentences.push(...heldFileSentences(input.heldFile));
3753
- const failed = !passed || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
4174
+ const failed = !entriesMatch || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3754
4175
  const unreachable = !input.source.compared && input.source.reason === "unreachable" || disclosure?.kind === "root-not-read";
3755
4176
  const exitCode = exitCodeOf(unreachable, failed);
3756
4177
  if (closesWithBoundary(exitCode)) sentences.push(SEALS_BOUNDARY_SENTENCE);
3757
- return {
4178
+ const report = {
3758
4179
  schema: REPORT_SCHEMA,
3759
4180
  checker: input.checker,
3760
4181
  form: input.form,
3761
4182
  record,
3762
- passed,
4183
+ passed: exitCode === 0,
3763
4184
  file,
3764
4185
  source: input.source,
3765
4186
  dailyStatement: null,
@@ -3770,6 +4191,7 @@ function buildSealsReport(input) {
3770
4191
  sentences,
3771
4192
  exitCode
3772
4193
  };
4194
+ return { report, entriesMatch };
3773
4195
  }
3774
4196
  var WRITES_HEADING = "Where each entry was committed on the proof layer:";
3775
4197
  var WRITES_NOT_READ_SENTENCE = "Where each entry was committed could not be read from the proof layer this time. The check above does not depend on it.";
@@ -3940,7 +4362,7 @@ async function lookUpWrites(input) {
3940
4362
 
3941
4363
  // src/check.ts
3942
4364
  var CHECKER_NAME = "@pacspace-io/check";
3943
- var CHECKER_VERSION = true ? "0.5.5" : "0.0.0-dev";
4365
+ var CHECKER_VERSION = true ? "0.6.0" : "0.0.0-dev";
3944
4366
  var HISTORY_SCHEMAS = [
3945
4367
  RECORD_HISTORY_BUNDLE_SCHEMA_V1,
3946
4368
  RECORD_HISTORY_BUNDLE_SCHEMA_V2,
@@ -4052,8 +4474,9 @@ function readerFor(chain, options) {
4052
4474
  readsFrom: mirrorBaseUrl
4053
4475
  };
4054
4476
  }
4055
- async function withWrites(report, bundle, verification, reader, options) {
4056
- if (!options.writes || !reader || !report.passed || !report.file.intact || !report.source.compared || !report.source.matches) return report;
4477
+ async function withWrites(checked, bundle, verification, reader, options) {
4478
+ const { report } = checked;
4479
+ if (!options.writes || !reader || !checked.entriesMatch || !report.file.intact || !report.source.compared || !report.source.matches) return checked;
4057
4480
  let writes;
4058
4481
  try {
4059
4482
  const source = options.source ?? "mirror";
@@ -4073,7 +4496,7 @@ async function withWrites(report, bundle, verification, reader, options) {
4073
4496
  } catch {
4074
4497
  writes = { read: false, reason: "unreachable" };
4075
4498
  }
4076
- return { ...report, writes };
4499
+ return { ...checked, report: { ...report, writes } };
4077
4500
  }
4078
4501
  var PAYLOAD_POINTER = /^\/payloads\/(0|[1-9][0-9]*)$/;
4079
4502
  function disclosureNamesAFile(disclosure) {
@@ -4104,6 +4527,9 @@ function refuseLayoutNotRead(result) {
4104
4527
  if (result.code === RECORDS_LAYOUT_NOT_READ) throw new HistoryFileError(RECORDS_LAYOUT_NOT_READ_SENTENCE);
4105
4528
  }
4106
4529
  async function checkHistory(file, options = {}) {
4530
+ return (await checkHistoryWithFacts(file, options)).report;
4531
+ }
4532
+ async function checkHistoryWithFacts(file, options = {}) {
4107
4533
  if (options.source === "offline" && needsLedgerRoots(file)) throw new HistoryFileError(DISCLOSURE_OFFLINE_SENTENCE);
4108
4534
  if (options.heldFile && !revealsFileFingerprint(file)) throw new HistoryFileError(NOTHING_REVEALED_SENTENCE);
4109
4535
  if (options.recordKey && file.schema !== RECORD_HISTORY_BUNDLE_SCHEMA_V3) throw new HistoryFileError(KEY_ONLY_FOR_ENCRYPTED_SENTENCE);
@@ -4228,7 +4654,7 @@ async function checkBundle(file, options) {
4228
4654
  };
4229
4655
  const heldOf = (verification2, offlineRun) => options.heldFile ? heldFileOutcome(options.heldFile, verifiedPayloads(file, verification2), offlineRun) : null;
4230
4656
  if (options.source === "offline" || !offline.schemaOk || !offline.digestOk) {
4231
- return buildReport({
4657
+ return buildReportWithFacts({
4232
4658
  ...base,
4233
4659
  verification: offline,
4234
4660
  source: { compared: false, reason: "offline" },
@@ -4264,7 +4690,7 @@ async function checkBundle(file, options) {
4264
4690
  if (error instanceof HistoryFileError) throw error;
4265
4691
  source = notReached(error);
4266
4692
  }
4267
- const report = buildReport({
4693
+ const report = buildReportWithFacts({
4268
4694
  ...base,
4269
4695
  verification,
4270
4696
  source,
@@ -4314,7 +4740,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4314
4740
  const refused = (refusal) => {
4315
4741
  refuseLayoutNotRead(refusal);
4316
4742
  if (refusal.code === "RECORD_HISTORY_DIGEST") {
4317
- return buildReport({
4743
+ return buildReportWithFacts({
4318
4744
  ...base,
4319
4745
  verification: { verified: false, digestOk: false, reason: "", history: null },
4320
4746
  source: { compared: false, reason: "offline" },
@@ -4323,7 +4749,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4323
4749
  }
4324
4750
  const sentence = encryptedRefusalSentence(refusal);
4325
4751
  if (sentence === null) throw new HistoryFileError(notThisForm);
4326
- return buildReport({
4752
+ return buildReportWithFacts({
4327
4753
  ...base,
4328
4754
  verification: { verified: false, digestOk: true, reason: sentence, history: null },
4329
4755
  source: { compared: false, reason: "offline" },
@@ -4340,7 +4766,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4340
4766
  if (!offline.ok) return refused(offline);
4341
4767
  const encrypted = { refusedUnopened: offline.refused.filter((r) => !r.opened).length };
4342
4768
  if (options.source === "offline" || !offline.verification.schemaOk || !offline.verification.digestOk) {
4343
- return buildReport({
4769
+ return buildReportWithFacts({
4344
4770
  ...base,
4345
4771
  verification: offline.verification,
4346
4772
  source: { compared: false, reason: "offline" },
@@ -4387,7 +4813,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4387
4813
  if (error instanceof HistoryFileError) throw error;
4388
4814
  source = notReached(error);
4389
4815
  }
4390
- const report = buildReport({
4816
+ const report = buildReportWithFacts({
4391
4817
  ...base,
4392
4818
  verification: result.verification,
4393
4819
  source,
@@ -4492,7 +4918,7 @@ async function checkSeals(formName, form, disclosure, options) {
4492
4918
  };
4493
4919
  const entries = entryCountOf(form, layouts);
4494
4920
  if (options.source === "offline" || !verification.schemaOk || !verification.digestOk) {
4495
- return buildSealsReport({
4921
+ return buildSealsReportWithFacts({
4496
4922
  ...base,
4497
4923
  entries,
4498
4924
  verification,
@@ -4530,7 +4956,7 @@ async function checkSeals(formName, form, disclosure, options) {
4530
4956
  disclosureOutcome = verification.verified ? await checkDisclosure(form, disclosure, reader, options.onRevealed) : { kind: "not-checked" };
4531
4957
  }
4532
4958
  const held = options.heldFile ? heldFileOutcome(options.heldFile, disclosureOutcome?.kind === "verified" ? disclosureOutcome.payloads : [], false) : null;
4533
- return buildSealsReport({
4959
+ return buildSealsReportWithFacts({
4534
4960
  ...base,
4535
4961
  entries,
4536
4962
  verification,
@@ -4748,13 +5174,14 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
4748
5174
  }
4749
5175
  base.commit = manifest.commit;
4750
5176
  let report;
5177
+ let entriesMatch;
4751
5178
  try {
4752
- report = await checkHistory(history, {
5179
+ ({ report, entriesMatch } = await checkHistoryWithFacts(history, {
4753
5180
  source: source ?? "mirror",
4754
5181
  timeoutMs,
4755
5182
  fetchImpl,
4756
5183
  heldFile: { sha256: await sha256Hex(manifestRead.bytes), byteLength: String(manifestRead.bytes.length) }
4757
- });
5184
+ }));
4758
5185
  } catch (error) {
4759
5186
  if (error instanceof HistoryFileError) return differs([{ kind: "differs", path: historyPath }]);
4760
5187
  throw error;
@@ -4762,7 +5189,7 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
4762
5189
  if (report.exitCode === 3 || report.source.compared === false && report.source.reason === "unreachable") {
4763
5190
  return unreachable(refusedOf(report.source));
4764
5191
  }
4765
- if (!report.passed) return differs([{ kind: "differs", path: historyPath }]);
5192
+ if (!entriesMatch) return differs([{ kind: "differs", path: historyPath }]);
4766
5193
  const latest = report.record.entries;
4767
5194
  base.latestEntry = latest;
4768
5195
  const matched = report.heldFile?.entries ?? [];