@pacspace-io/sdk 0.15.2 → 0.15.3

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/dist/index.js CHANGED
@@ -457,7 +457,7 @@ var HttpClient = class {
457
457
  const headers = {
458
458
  "X-Api-Key": this.apiKey,
459
459
  "Content-Type": "application/json",
460
- "User-Agent": "@pacspace-io/sdk/0.15.2"
460
+ "User-Agent": "@pacspace-io/sdk/0.15.3"
461
461
  };
462
462
  if (options?.dashboardToken) {
463
463
  headers.Authorization = `Bearer ${options.dashboardToken}`;
@@ -3228,16 +3228,10 @@ function admitRecordEntryV1(layout, entry) {
3228
3228
  }
3229
3229
 
3230
3230
  // ../shared/src/records/record-seal-history-v1.ts
3231
- var import_ethers13 = require("ethers");
3231
+ var import_ethers14 = require("ethers");
3232
3232
 
3233
3233
  // ../shared/src/demo/mirror-node-record-chain-reader.ts
3234
- var import_ethers12 = require("ethers");
3235
-
3236
- // ../shared/src/records/inspect-record-calldata-v1.ts
3237
- var MIRROR_NODE_BY_CHAIN = Object.freeze({
3238
- 296: "https://testnet.mirrornode.hedera.com",
3239
- 295: "https://mainnet-public.mirrornode.hedera.com"
3240
- });
3234
+ var import_ethers13 = require("ethers");
3241
3235
 
3242
3236
  // ../shared/src/records/ledger-write-search-v1.ts
3243
3237
  var LEDGER_WRITE_SEARCH_WINDOW_LIMIT_SECONDS = 7 * 24 * 60 * 60;
@@ -3247,7 +3241,15 @@ var HEX40 = /^0x[0-9a-f]{40}$/;
3247
3241
  var HEX642 = /^0x[0-9a-f]{64}$/;
3248
3242
  var HEX_DATA = /^0x[0-9a-f]*$/;
3249
3243
  var TIMESTAMP = /^\d+(\.\d+)?$/;
3250
- var REFUSAL_CODES = ["redirect", "too-large", "too-many-logs", "next-page"];
3244
+ var REFUSAL_CODES = {
3245
+ redirect: true,
3246
+ "too-large": true,
3247
+ "too-many-logs": true,
3248
+ "next-page": true,
3249
+ "too-slow": true,
3250
+ "too-long": true
3251
+ };
3252
+ var MIRROR_REFUSAL_CODES = Object.keys(REFUSAL_CODES);
3251
3253
  var MirrorAnswerRefused = class extends Error {
3252
3254
  constructor(code, message) {
3253
3255
  super(message);
@@ -3258,7 +3260,7 @@ var MirrorAnswerRefused = class extends Error {
3258
3260
  function mirrorRefusalOf(error) {
3259
3261
  if (!error || typeof error !== "object") return null;
3260
3262
  const { name, code } = error;
3261
- return name === "MirrorAnswerRefused" && typeof code === "string" && REFUSAL_CODES.includes(code) ? code : null;
3263
+ return name === "MirrorAnswerRefused" && typeof code === "string" && Object.prototype.hasOwnProperty.call(REFUSAL_CODES, code) ? code : null;
3262
3264
  }
3263
3265
  function pathLabel(path) {
3264
3266
  return path ? ` (${path.split("?")[0]})` : "";
@@ -3267,8 +3269,24 @@ var mirrorRefusal = {
3267
3269
  redirect: (path) => new MirrorAnswerRefused("redirect", `mirror node answered with a redirect, which is not followed${pathLabel(path)}`),
3268
3270
  tooLarge: (maxBytes, path) => new MirrorAnswerRefused("too-large", `mirror node answer is larger than ${maxBytes} bytes${pathLabel(path)}`),
3269
3271
  tooManyLogs: (asked, path) => new MirrorAnswerRefused("too-many-logs", `mirror node returned more logs than the ${asked} asked for${pathLabel(path)}`),
3270
- nextPage: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that is not this contract's log")
3272
+ nextPage: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that is not this contract's log"),
3273
+ /** A page whose logs do not come after the last log read. */
3274
+ notForward: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that does not follow the last"),
3275
+ scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `mirror node log scan did not finish in ${budgetMs}ms`),
3276
+ scanTooManyRequests: (requests) => new MirrorAnswerRefused("too-long", `mirror node log scan passed ${requests} requests`),
3277
+ scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `mirror node log scan kept more than ${logs} logs`)
3271
3278
  };
3279
+ var rpcRefusal = {
3280
+ redirect: () => new MirrorAnswerRefused("redirect", "RPC endpoint answered with a redirect, which is not followed"),
3281
+ tooLarge: (maxBytes) => new MirrorAnswerRefused("too-large", `RPC endpoint answer is larger than ${maxBytes} bytes`),
3282
+ scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `RPC log scan did not finish in ${budgetMs}ms`),
3283
+ scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `RPC log scan kept more than ${logs} logs`)
3284
+ };
3285
+ var LOG_SCAN_BUDGET_TIMEOUTS = 60;
3286
+ var LOG_SCAN_MAX_REQUESTS = 1e4;
3287
+ var LOG_SCAN_MAX_KEPT_LOGS = 1e6;
3288
+ var KEPT_LOG_DATA_MAX_CHARS = 2 + 64 * 3;
3289
+ var KEPT_LOG_MAX_TOPICS = 3;
3272
3290
  function isMirrorRedirect(response) {
3273
3291
  return response.redirected === true || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400;
3274
3292
  }
@@ -3383,7 +3401,16 @@ function parseLedgerWriteLog(log, expected) {
3383
3401
  };
3384
3402
  }
3385
3403
 
3404
+ // ../shared/src/records/inspect-record-calldata-v1.ts
3405
+ var MIRROR_NODE_BY_CHAIN = Object.freeze({
3406
+ 296: "https://testnet.mirrornode.hedera.com",
3407
+ 295: "https://mainnet-public.mirrornode.hedera.com"
3408
+ });
3409
+
3386
3410
  // ../shared/src/demo/independent-verify-records.ts
3411
+ var import_ethers12 = require("ethers");
3412
+
3413
+ // ../shared/src/chain/rpc-guarded-send.ts
3387
3414
  var import_ethers11 = require("ethers");
3388
3415
 
3389
3416
  // ../shared/src/chain/rpc-provider.ts
@@ -3584,14 +3611,35 @@ async function guardSubscriptionSend(method, send, provider, retry, secrets) {
3584
3611
  }
3585
3612
  }
3586
3613
  }
3614
+ function requestFor(url, options) {
3615
+ const request = new import_ethers10.FetchRequest(url);
3616
+ if (options.timeoutMs !== void 0) request.timeout = options.timeoutMs;
3617
+ options.prepareRequest?.(request);
3618
+ return request;
3619
+ }
3620
+ var CHAIN_ID_RESULT = /^0x[0-9a-f]{1,13}$/i;
3621
+ async function readRpcChainId(url, options = {}) {
3622
+ const secrets = rpcUrlSecrets(url);
3623
+ try {
3624
+ const request = requestFor(url, options);
3625
+ request.body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_chainId", params: [] });
3626
+ request.setHeader("content-type", "application/json");
3627
+ const response = await request.send();
3628
+ response.assertOk();
3629
+ const answer = response.bodyJson;
3630
+ const result = answer !== null && typeof answer === "object" ? answer.result : void 0;
3631
+ if (typeof result !== "string" || !CHAIN_ID_RESULT.test(result)) throw new RpcResultUnavailableError("eth_chainId", "not a chain id");
3632
+ return Number.parseInt(result, 16);
3633
+ } catch (error) {
3634
+ throw redactRpcError(error, secrets);
3635
+ }
3636
+ }
3587
3637
  var RedactingJsonRpcProvider = class extends import_ethers10.JsonRpcProvider {
3588
3638
  #secrets;
3589
3639
  #subscriptionRetry;
3590
3640
  constructor(url, network, options) {
3591
- const { timeoutMs, subscriptionRetry, ...providerOptions } = options;
3592
- const request = new import_ethers10.FetchRequest(url);
3593
- if (timeoutMs !== void 0) request.timeout = timeoutMs;
3594
- super(request, network, providerOptions);
3641
+ const { timeoutMs, subscriptionRetry, prepareRequest, ...providerOptions } = options;
3642
+ super(requestFor(url, { timeoutMs, prepareRequest }), network, providerOptions);
3595
3643
  this.#secrets = rpcUrlSecrets(url);
3596
3644
  this.#subscriptionRetry = subscriptionRetry ?? {};
3597
3645
  }
@@ -3628,6 +3676,100 @@ function createRpcProvider(url, network, options = {}) {
3628
3676
  return new RedactingJsonRpcProvider(url, network, options);
3629
3677
  }
3630
3678
 
3679
+ // ../shared/src/chain/rpc-guarded-send.ts
3680
+ var RPC_READER_MAX_TRIES = 3;
3681
+ function basicAuthorization(username, password) {
3682
+ const decoded = (value) => {
3683
+ try {
3684
+ return decodeURIComponent(value);
3685
+ } catch {
3686
+ return value;
3687
+ }
3688
+ };
3689
+ const bytes2 = new TextEncoder().encode(`${decoded(username)}:${decoded(password)}`);
3690
+ let binary = "";
3691
+ for (const byte of bytes2) binary += String.fromCharCode(byte);
3692
+ return `Basic ${btoa(binary)}`;
3693
+ }
3694
+ function createGuardedRpcSend(options = {}) {
3695
+ const maxBytes = options.maxBytes ?? MIRROR_ANSWER_MAX_BYTES;
3696
+ return async (req, signal) => {
3697
+ if (signal?.cancelled) throw (0, import_ethers11.makeError)("request cancelled before sending", "CANCELLED");
3698
+ const fetchImpl = options.fetchImpl ?? fetch;
3699
+ const secrets = rpcUrlSecrets(req.url);
3700
+ const url = new URL(req.url);
3701
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
3702
+ throw (0, import_ethers11.makeError)(`unsupported protocol ${url.protocol.replace(/:$/, "")}`, "UNSUPPORTED_OPERATION", { operation: "request" });
3703
+ }
3704
+ const headers = {};
3705
+ for (const [name, value] of Object.entries(req.headers)) {
3706
+ const lower = name.toLowerCase();
3707
+ if (lower === "content-length" || lower === "accept-encoding") continue;
3708
+ headers[lower] = value;
3709
+ }
3710
+ if (url.username !== "" || url.password !== "") {
3711
+ if (headers.authorization === void 0) headers.authorization = basicAuthorization(url.username, url.password);
3712
+ url.username = "";
3713
+ url.password = "";
3714
+ }
3715
+ const controller = new AbortController();
3716
+ let timedOut = false;
3717
+ const timer = setTimeout(() => {
3718
+ timedOut = true;
3719
+ controller.abort();
3720
+ }, req.timeout);
3721
+ let cancelled = false;
3722
+ signal?.addListener(() => {
3723
+ cancelled = true;
3724
+ controller.abort();
3725
+ });
3726
+ try {
3727
+ const body = req.body;
3728
+ const response = await fetchImpl(url.toString(), {
3729
+ method: req.method,
3730
+ headers,
3731
+ ...body ? { body } : {},
3732
+ redirect: "manual",
3733
+ signal: controller.signal
3734
+ });
3735
+ if (isMirrorRedirect(response)) {
3736
+ await response.body?.cancel?.().catch(() => void 0);
3737
+ throw rpcRefusal.redirect();
3738
+ }
3739
+ let text;
3740
+ try {
3741
+ text = await readMirrorText(response, maxBytes);
3742
+ } catch (error) {
3743
+ if (mirrorRefusalOf(error) === "too-large") throw rpcRefusal.tooLarge(maxBytes);
3744
+ throw error;
3745
+ }
3746
+ const answered = {};
3747
+ response.headers.forEach((value, name) => {
3748
+ answered[name.toLowerCase()] = value;
3749
+ });
3750
+ return { statusCode: response.status, statusMessage: response.statusText, headers: answered, body: new TextEncoder().encode(replaceRpcSecrets(text, secrets)) };
3751
+ } catch (error) {
3752
+ if (mirrorRefusalOf(error)) throw error;
3753
+ if (cancelled) throw (0, import_ethers11.makeError)("request cancelled", "CANCELLED");
3754
+ if (timedOut) throw (0, import_ethers11.makeError)("request timeout", "TIMEOUT", { operation: "request.send", reason: "timeout" });
3755
+ throw error;
3756
+ } finally {
3757
+ clearTimeout(timer);
3758
+ }
3759
+ };
3760
+ }
3761
+ function retryAfterMs(value) {
3762
+ return typeof value === "string" && /^[1-9][0-9]*$/.test(value) ? Number.parseInt(value, 10) : null;
3763
+ }
3764
+ function holdRpcRequest(request, options = {}) {
3765
+ request.getUrlFunc = createGuardedRpcSend(options);
3766
+ request.retryFunc = async (req, response, attempt) => {
3767
+ if (attempt >= RPC_READER_MAX_TRIES - 1) return false;
3768
+ const wait = retryAfterMs(response.headers["retry-after"]);
3769
+ return wait === null || wait <= req.timeout;
3770
+ };
3771
+ }
3772
+
3631
3773
  // ../shared/src/demo/independent-verify-records.ts
3632
3774
  var RECORD_LANE_ABI_V38 = [
3633
3775
  "function getRecord(bytes32 recordKey) view returns (uint256)",
@@ -3639,18 +3781,20 @@ var RECORD_LANE_ABI_V38 = [
3639
3781
  "event RecordWritten(bytes32 indexed recordKey, address indexed operator, uint8 encodingVersion, uint256 previousWord, uint256 newWord)",
3640
3782
  "event LedgerHeadAdvanced(uint256 indexed batchId, bytes32 merkleRoot, bytes32 previousHead, bytes32 newHead)"
3641
3783
  ];
3642
- var LEDGER_HEAD_ADVANCED_TOPIC = import_ethers11.ethers.id("LedgerHeadAdvanced(uint256,bytes32,bytes32,bytes32)");
3643
- var RECORD_WRITTEN_TOPIC = import_ethers11.ethers.id("RecordWritten(bytes32,address,uint8,uint256,uint256)");
3784
+ var LEDGER_HEAD_ADVANCED_TOPIC = import_ethers12.ethers.id("LedgerHeadAdvanced(uint256,bytes32,bytes32,bytes32)");
3785
+ var RECORD_WRITTEN_TOPIC = import_ethers12.ethers.id("RecordWritten(bytes32,address,uint8,uint256,uint256)");
3644
3786
  function normalizeRpcUrl(url) {
3645
3787
  const trimmed = String(url || "").trim();
3646
3788
  if (trimmed.startsWith("wss://")) return trimmed.replace(/^wss:\/\//, "https://");
3647
3789
  if (trimmed.startsWith("ws://")) return trimmed.replace(/^ws:\/\//, "http://");
3648
3790
  return trimmed;
3649
3791
  }
3792
+ var ReadTimedOut = class extends Error {
3793
+ };
3650
3794
  async function withTimeout(p, ms, label) {
3651
3795
  let timer;
3652
3796
  const timeout = new Promise((_, reject) => {
3653
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
3797
+ timer = setTimeout(() => reject(new ReadTimedOut(`${label} timed out after ${ms}ms`)), ms);
3654
3798
  });
3655
3799
  try {
3656
3800
  return await Promise.race([p, timeout]);
@@ -3661,24 +3805,71 @@ async function withTimeout(p, ms, label) {
3661
3805
  function createRpcRecordChainReader(options) {
3662
3806
  const rpcUrl = normalizeRpcUrl(options.rpcUrl);
3663
3807
  if (!rpcUrl) throw new Error("rpcUrl is required.");
3664
- const contractAddress = import_ethers11.ethers.getAddress(options.contractAddress).toLowerCase();
3808
+ const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
3665
3809
  const timeoutMs = Number(options.timeoutMs || 1e4);
3666
3810
  const chunk = Math.max(1, Number(options.logsChunkSize || 2e3));
3667
- const network = options.chainId != null ? new import_ethers11.ethers.Network(`chain-${options.chainId}`, options.chainId) : void 0;
3668
- const provider = network ? createRpcProvider(rpcUrl, network, { staticNetwork: network }) : createRpcProvider(rpcUrl);
3669
- const contract = new import_ethers11.ethers.Contract(contractAddress, RECORD_LANE_ABI_V38, provider);
3670
- const iface = new import_ethers11.ethers.Interface(RECORD_LANE_ABI_V38);
3811
+ const now = options.scan?.now ?? Date.now;
3812
+ const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
3813
+ const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
3814
+ const prepareRequest = (request) => holdRpcRequest(request);
3815
+ const endpointFor = (chainId) => {
3816
+ const network = new import_ethers12.ethers.Network(`chain-${chainId}`, chainId);
3817
+ const provider = createRpcProvider(rpcUrl, network, { staticNetwork: network, timeoutMs, prepareRequest });
3818
+ return { provider, contract: new import_ethers12.ethers.Contract(contractAddress, RECORD_LANE_ABI_V38, provider) };
3819
+ };
3820
+ let ready = options.chainId != null ? Promise.resolve(endpointFor(options.chainId)) : null;
3821
+ function endpoint() {
3822
+ if (!ready) {
3823
+ const pending = readRpcChainId(rpcUrl, { timeoutMs, prepareRequest }).then(endpointFor);
3824
+ ready = pending;
3825
+ pending.catch(() => {
3826
+ if (ready === pending) ready = null;
3827
+ });
3828
+ }
3829
+ return ready;
3830
+ }
3831
+ function keptLog(log, topic0) {
3832
+ 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;
3833
+ }
3671
3834
  async function scanLogs(topics, fromBlock, toBlock, label) {
3672
- const latest = toBlock === "latest" ? await withTimeout(provider.getBlockNumber(), timeoutMs, "getBlockNumber") : toBlock;
3835
+ const { provider } = await endpoint();
3836
+ const budgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
3837
+ const deadline = now() + budgetMs;
3838
+ const topic0 = String(topics[0] ?? "").toLowerCase();
3839
+ const ask = async (send, what) => {
3840
+ const left = deadline - now();
3841
+ if (left <= 0) throw rpcRefusal.scanTooSlow(budgetMs);
3842
+ const allowed = Math.min(timeoutMs, left);
3843
+ try {
3844
+ return await withTimeout(send(), allowed, what);
3845
+ } catch (error) {
3846
+ if (error instanceof ReadTimedOut && allowed < timeoutMs) throw rpcRefusal.scanTooSlow(budgetMs);
3847
+ if (!mirrorRefusalOf(error) && now() >= deadline) throw rpcRefusal.scanTooSlow(budgetMs);
3848
+ throw error;
3849
+ }
3850
+ };
3851
+ const latest = toBlock === "latest" ? await ask(() => provider.getBlockNumber(), "getBlockNumber") : toBlock;
3673
3852
  const out = [];
3853
+ const pending = [];
3674
3854
  for (let start = fromBlock; start <= latest; start += chunk) {
3675
- const end = Math.min(latest, start + chunk - 1);
3676
- const logs = await withTimeout(
3677
- provider.getLogs({ address: contractAddress, topics, fromBlock: start, toBlock: end }),
3678
- timeoutMs,
3679
- `getLogs ${label} (${start}-${end})`
3680
- );
3681
- out.push(...logs);
3855
+ pending.push([start, Math.min(latest, start + chunk - 1)]);
3856
+ while (pending.length > 0) {
3857
+ const [from, to] = pending.pop();
3858
+ let logs;
3859
+ try {
3860
+ logs = await ask(() => provider.getLogs({ address: contractAddress, topics, fromBlock: from, toBlock: to }), `getLogs ${label} (${from}-${to})`);
3861
+ } catch (error) {
3862
+ if (mirrorRefusalOf(error) !== "too-large" || from >= to) throw error;
3863
+ const middle = from + Math.floor((to - from) / 2);
3864
+ pending.push([middle + 1, to], [from, middle]);
3865
+ continue;
3866
+ }
3867
+ for (const log of logs) {
3868
+ if (!keptLog(log, topic0)) continue;
3869
+ if (out.length >= maxKeptLogs) throw rpcRefusal.scanTooManyLogs(maxKeptLogs);
3870
+ out.push(log);
3871
+ }
3872
+ }
3682
3873
  }
3683
3874
  return out;
3684
3875
  }
@@ -3686,10 +3877,12 @@ function createRpcRecordChainReader(options) {
3686
3877
  contractAddress,
3687
3878
  async getRecord(recordKey) {
3688
3879
  const key = normalizeProofHash(recordKey, "recordKey");
3880
+ const { contract } = await endpoint();
3689
3881
  const word = await withTimeout(contract.getRecord(key), timeoutMs, "getRecord");
3690
3882
  return hex256(BigInt(word));
3691
3883
  },
3692
3884
  async getLayout(layoutId) {
3885
+ const { contract } = await endpoint();
3693
3886
  const l = await withTimeout(contract.getLayout(layoutId), timeoutMs, "getLayout");
3694
3887
  return {
3695
3888
  layoutDigest: String(l[0]).toLowerCase(),
@@ -3699,10 +3892,12 @@ function createRpcRecordChainReader(options) {
3699
3892
  };
3700
3893
  },
3701
3894
  async getBatchRoot(batchId) {
3895
+ const { contract } = await endpoint();
3702
3896
  const root = await withTimeout(contract.getBatchRoot(BigInt(batchId)), timeoutMs, "getBatchRoot");
3703
3897
  return normalizeProofHash(String(root), "observedProofRoot");
3704
3898
  },
3705
3899
  async getLedgerHead() {
3900
+ const { contract } = await endpoint();
3706
3901
  const head = await withTimeout(contract.getLedgerHead(), timeoutMs, "getLedgerHead");
3707
3902
  return normalizeProofHash(String(head), "ledgerHead");
3708
3903
  },
@@ -3745,14 +3940,14 @@ function createRpcRecordChainReader(options) {
3745
3940
  },
3746
3941
  async findRecordWrites(recordKey, search) {
3747
3942
  const key = normalizeProofHash(recordKey, "recordKey");
3748
- const now = search.now ?? Date.now;
3749
- const deadline = now() + search.budgetMs;
3943
+ const now2 = search.now ?? Date.now;
3944
+ const deadline = now2() + search.budgetMs;
3750
3945
  const writes = [];
3751
3946
  const blockTimes = /* @__PURE__ */ new Map();
3752
3947
  let requests = 0;
3753
3948
  const CUT = Symbol("cut");
3754
3949
  const within = async (p) => {
3755
- const left = deadline - now();
3950
+ const left = deadline - now2();
3756
3951
  if (left <= 0) return CUT;
3757
3952
  let timer;
3758
3953
  const cut = new Promise((resolve) => {
@@ -3767,12 +3962,15 @@ function createRpcRecordChainReader(options) {
3767
3962
  };
3768
3963
  const end = (ended) => ({ writes, ended, requests });
3769
3964
  if (search.maxRequests < 1) return end("limit");
3965
+ const found = await within(endpoint());
3966
+ if (found === CUT) return end("timeout");
3967
+ const { provider } = found;
3770
3968
  requests += 1;
3771
3969
  const latest = await within(provider.getBlockNumber());
3772
3970
  if (latest === CUT) return end("timeout");
3773
3971
  for (let to = latest; to >= 0; to -= chunk) {
3774
3972
  if (search.done(writes)) return end("done");
3775
- if (requests >= search.maxRequests || now() >= deadline) return end("limit");
3973
+ if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
3776
3974
  requests += 1;
3777
3975
  const logs = await within(provider.getLogs({ address: contractAddress, topics: [RECORD_WRITTEN_TOPIC, key], fromBlock: Math.max(0, to - chunk + 1), toBlock: to }));
3778
3976
  if (logs === CUT) return end("timeout");
@@ -3781,7 +3979,7 @@ function createRpcRecordChainReader(options) {
3781
3979
  if (!parsed) continue;
3782
3980
  let committedAt = blockTimes.get(log.blockNumber);
3783
3981
  if (committedAt === void 0) {
3784
- if (requests >= search.maxRequests || now() >= deadline) return end("limit");
3982
+ if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
3785
3983
  requests += 1;
3786
3984
  const block = await within(provider.getBlock(log.blockNumber));
3787
3985
  if (block === CUT) return end("timeout");
@@ -3817,12 +4015,32 @@ function committedAtOf(timestamp) {
3817
4015
  return new Date(Number(seconds) * 1e3 + Number(fraction.slice(0, 3))).toISOString();
3818
4016
  }
3819
4017
  var KEPT_TOPICS = [RECORD_WRITTEN_TOPIC.toLowerCase(), LEDGER_HEAD_ADVANCED_TOPIC.toLowerCase()];
3820
- function keptMirrorLog(raw) {
4018
+ var HEX_DATA2 = /^0x[0-9a-fA-F]*$/;
4019
+ function mirrorLogPosition(raw) {
4020
+ if (!raw || typeof raw !== "object") return null;
4021
+ const { timestamp, index } = raw;
4022
+ if (typeof timestamp !== "string" || !CONSENSUS_TIMESTAMP.test(timestamp)) return null;
4023
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return null;
4024
+ const [seconds, fraction] = timestamp.split(".");
4025
+ return { nanos: BigInt(seconds) * 1000000000n + BigInt(fraction), index };
4026
+ }
4027
+ function mirrorLogFollows(last, next) {
4028
+ return last === null || next.nanos > last.nanos || next.nanos === last.nanos && next.index > last.index;
4029
+ }
4030
+ function keptMirrorLog(raw, contract) {
3821
4031
  if (!raw || typeof raw !== "object") return null;
3822
4032
  const log = raw;
3823
4033
  if (!Array.isArray(log.topics) || typeof log.data !== "string") return null;
4034
+ if (log.topics.length > KEPT_LOG_MAX_TOPICS || log.data.length > KEPT_LOG_DATA_MAX_CHARS || !HEX_DATA2.test(log.data)) return null;
3824
4035
  const topics = log.topics.map((topic) => String(topic));
3825
4036
  if (!KEPT_TOPICS.includes((topics[0] ?? "").toLowerCase())) return null;
4037
+ if (topics.some((topic) => topic.length > 66)) return null;
4038
+ if (contract !== void 0) {
4039
+ if (typeof log.address !== "string" || log.address.toLowerCase() !== contract) return null;
4040
+ if (!mirrorLogPosition(raw)) return null;
4041
+ if (typeof log.block_number !== "number" || !Number.isSafeInteger(log.block_number)) return null;
4042
+ if (typeof log.transaction_hash !== "string" || log.transaction_hash.length > 98) return null;
4043
+ }
3826
4044
  return {
3827
4045
  address: log.address,
3828
4046
  data: log.data,
@@ -3837,18 +4055,25 @@ function createMirrorNodeRecordChainReader(options) {
3837
4055
  const chainId = options.chainId ?? 296;
3838
4056
  const base = (options.mirrorBaseUrl ?? MIRROR_NODE_BY_CHAIN[chainId] ?? "").replace(/\/+$/, "");
3839
4057
  if (!base) throw new Error(`No mirror node known for chain ${chainId}; pass mirrorBaseUrl.`);
3840
- const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
4058
+ const contractAddress = import_ethers13.ethers.getAddress(options.contractAddress).toLowerCase();
3841
4059
  const timeoutMs = Number(options.timeoutMs || 1e4);
3842
4060
  const pageSize = Math.min(100, Math.max(1, Number(options.pageSize || 100)));
3843
4061
  const attempts = Math.max(1, options.attempts ?? 3);
3844
4062
  const fetchImpl = options.fetchImpl ?? fetch;
3845
- const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
3846
- async function request(path, init) {
4063
+ const iface = new import_ethers13.ethers.Interface(RECORD_LANE_ABI_V38);
4064
+ const now = options.scan?.now ?? Date.now;
4065
+ const maxScanRequests = options.scan?.maxRequests ?? LOG_SCAN_MAX_REQUESTS;
4066
+ const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
4067
+ const scanBudgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
4068
+ async function request(path, init, deadline) {
3847
4069
  const url = `${base}${path}`;
3848
4070
  let lastError = null;
3849
4071
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
4072
+ const left = deadline === void 0 ? timeoutMs : deadline - now();
4073
+ if (left <= 0) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
4074
+ const allowed = Math.min(timeoutMs, left);
3850
4075
  const controller = new AbortController();
3851
- const timer = setTimeout(() => controller.abort(), timeoutMs);
4076
+ const timer = setTimeout(() => controller.abort(), allowed);
3852
4077
  try {
3853
4078
  const response = await fetchImpl(url, { ...init, redirect: "manual", signal: controller.signal });
3854
4079
  if (isMirrorRedirect(response)) {
@@ -3866,14 +4091,17 @@ function createMirrorNodeRecordChainReader(options) {
3866
4091
  }
3867
4092
  } catch (error) {
3868
4093
  if (mirrorRefusalOf(error)) throw error;
3869
- if (error.name === "AbortError") lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
3870
- else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
4094
+ if (error.name === "AbortError") {
4095
+ if (deadline !== void 0 && allowed < timeoutMs) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
4096
+ lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
4097
+ } else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
3871
4098
  else lastError = error;
3872
4099
  } finally {
3873
4100
  clearTimeout(timer);
3874
4101
  }
3875
4102
  if (attempt < attempts) await new Promise((resolve) => setTimeout(resolve, 250 * attempt));
3876
4103
  }
4104
+ if (deadline !== void 0 && now() >= deadline) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
3877
4105
  throw lastError ?? new Error(`mirror node request failed (${path})`);
3878
4106
  }
3879
4107
  async function call(fn, args = []) {
@@ -3909,16 +4137,23 @@ function createMirrorNodeRecordChainReader(options) {
3909
4137
  params.set("limit", String(pageSize));
3910
4138
  let next = `${contractLogPath(contractAddress)}?${params.toString()}`;
3911
4139
  const out = [];
3912
- let pages = 0;
4140
+ const scan = { deadline: now() + scanBudgetMs, requests: 0 };
4141
+ let last = null;
3913
4142
  let size = pageSize;
3914
4143
  while (next) {
3915
- const { page, asked } = await readLogPage(next, size);
4144
+ const { page, asked } = await readLogPage(next, size, scan);
3916
4145
  size = Math.min(pageSize, asked * 2);
3917
4146
  const logs = Array.isArray(page.logs) ? page.logs : [...page.logs ?? []];
3918
4147
  if (logs.length > asked) throw mirrorRefusal.tooManyLogs(asked, next);
3919
4148
  for (const raw of logs) {
3920
- const log = keptMirrorLog(raw);
3921
- if (log) out.push(log);
4149
+ const position = mirrorLogPosition(raw);
4150
+ if (!position) continue;
4151
+ if (!mirrorLogFollows(last, position)) throw mirrorRefusal.notForward();
4152
+ last = position;
4153
+ const log = keptMirrorLog(raw, contractAddress);
4154
+ if (!log) continue;
4155
+ if (out.length >= maxKeptLogs) throw mirrorRefusal.scanTooManyLogs(maxKeptLogs);
4156
+ out.push(log);
3922
4157
  }
3923
4158
  const link = page.links?.next;
3924
4159
  if (link === null || link === void 0 || link === "") {
@@ -3928,16 +4163,16 @@ function createMirrorNodeRecordChainReader(options) {
3928
4163
  if (!path) throw mirrorRefusal.nextPage();
3929
4164
  next = withLogPageLimit(path, size);
3930
4165
  }
3931
- pages += 1;
3932
- if (pages > 1e4) throw new Error("mirror node log scan exceeded 10,000 pages");
3933
4166
  }
3934
4167
  return out;
3935
4168
  }
3936
- async function readLogPage(path, start) {
4169
+ async function readLogPage(path, start, scan) {
3937
4170
  let asked = start;
3938
4171
  for (; ; ) {
4172
+ if (scan.requests >= maxScanRequests) throw mirrorRefusal.scanTooManyRequests(maxScanRequests);
4173
+ scan.requests += 1;
3939
4174
  try {
3940
- return { page: await request(withLogPageLimit(path, asked)), asked };
4175
+ return { page: await request(withLogPageLimit(path, asked), void 0, scan.deadline), asked };
3941
4176
  } catch (error) {
3942
4177
  if (mirrorRefusalOf(error) !== "too-large" || asked <= 1) throw error;
3943
4178
  asked = Math.max(1, Math.floor(asked / 2));
@@ -4039,10 +4274,10 @@ function createMirrorNodeRecordChainReader(options) {
4039
4274
  async findRecordWrites(recordKey, search) {
4040
4275
  const key = normalizeProofHash(recordKey, "recordKey").toLowerCase();
4041
4276
  const topic0 = RECORD_WRITTEN_TOPIC.toLowerCase();
4042
- const now = search.now ?? Date.now;
4043
- const deadline = now() + search.budgetMs;
4277
+ const now2 = search.now ?? Date.now;
4278
+ const deadline = now2() + search.budgetMs;
4044
4279
  const windowSeconds = Math.max(1, Math.floor(search.windowSeconds ?? RECORD_WRITE_SEARCH_WINDOW_SECONDS));
4045
- const nowSeconds = Math.floor(now() / 1e3);
4280
+ const nowSeconds = Math.floor(now2() / 1e3);
4046
4281
  const hint = search.startAt ? Date.parse(search.startAt) : Number.NaN;
4047
4282
  let upper = Math.min(Number.isFinite(hint) ? Math.floor(hint / 1e3) : nowSeconds, nowSeconds) + DAY_SECONDS;
4048
4283
  const writes = [];
@@ -4053,7 +4288,7 @@ function createMirrorNodeRecordChainReader(options) {
4053
4288
  const lower = Math.max(0, upper - windowSeconds);
4054
4289
  let path = ledgerWriteSearchPath({ contractAddress, topic0, recordKey: key, lower, upper });
4055
4290
  while (path) {
4056
- const left = deadline - now();
4291
+ const left = deadline - now2();
4057
4292
  if (requests >= search.maxRequests || left <= 0) return end("limit");
4058
4293
  requests += 1;
4059
4294
  const page = await searchPage(path, left);
@@ -4399,7 +4634,7 @@ var hasOnly = (v, required, optional = []) => required.every((k) => Object.proto
4399
4634
  function computeSealHistoryDigestV1(form) {
4400
4635
  const rest = { ...form };
4401
4636
  delete rest.digest;
4402
- return import_ethers13.ethers.keccak256(import_ethers13.ethers.toUtf8Bytes(canonicalizeJcs(rest)));
4637
+ return import_ethers14.ethers.keccak256(import_ethers14.ethers.toUtf8Bytes(canonicalizeJcs(rest)));
4403
4638
  }
4404
4639
  function entryShapeOk2(e) {
4405
4640
  if (!isPlainObject5(e) || !hasOnly(e, ENTRY_KEYS, ["recordHash"])) return false;