@fangorn-network/sdk 0.2.2 → 0.2.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/lib/config.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as viem_chains0 from "viem/chains";
2
2
  import * as viem0 from "viem";
3
- import { Chain, Hex } from "viem";
3
+ import { Chain, Hex, HttpTransportConfig } from "viem";
4
4
 
5
5
  //#region src/config.d.ts
6
6
 
@@ -19,6 +19,7 @@ interface NetworkConfig {
19
19
  caip2: number;
20
20
  ipfsGateway: string;
21
21
  logWindow?: bigint;
22
+ rpcRetry?: Pick<HttpTransportConfig, "retryCount" | "retryDelay">;
22
23
  signedUrlWorker?: string;
23
24
  keyServer?: string;
24
25
  }
@@ -146,7 +146,9 @@ declare class ChainRegistry implements Registry {
146
146
  log(filter: LogFilter, from: bigint, to?: bigint): Promise<UpdateEntry[]>;
147
147
  /**
148
148
  * Old-version logs don't carry their block's timestamp: one block read per
149
- * distinct block. New-version logs carry it.
149
+ * distinct block. New-version logs carry it. At most TIMESTAMP_READS at a time:
150
+ * a first catch-up reads hundreds, and a public RPC throttles them all at once
151
+ * (each retry wave was another burst). A failed read stops the rest.
150
152
  */
151
153
  private withTimestamps;
152
154
  watch(filter: LogFilter, onEntry: (entry: UpdateEntry) => void, onError?: (err: Error) => void, pollingInterval?: number): () => void;
@@ -13,6 +13,8 @@ const ZERO_HEAD = "0x00000000000000000000000000000000000000000000000000000000000
13
13
  const EPOCH_SECONDS = 3600;
14
14
  /** W: how many epochs a commit may lag the ordering's clock. */
15
15
  const WINDOW = 24;
16
+ /** How many block reads `log` keeps in flight for old-version timestamps. */
17
+ const TIMESTAMP_READS = 8;
16
18
  function epochOf(unixSeconds) {
17
19
  return Math.floor(Number(unixSeconds) / EPOCH_SECONDS);
18
20
  }
@@ -154,11 +156,23 @@ var ChainRegistry = class {
154
156
  }
155
157
  /**
156
158
  * Old-version logs don't carry their block's timestamp: one block read per
157
- * distinct block. New-version logs carry it.
159
+ * distinct block. New-version logs carry it. At most TIMESTAMP_READS at a time:
160
+ * a first catch-up reads hundreds, and a public RPC throttles them all at once
161
+ * (each retry wave was another burst). A failed read stops the rest.
158
162
  */
159
163
  async withTimestamps(logs) {
160
- const blocks = [...new Set(logs.filter((l) => l.args.timestamp === void 0).map((l) => l.blockNumber))];
161
- const times = new Map(await Promise.all(blocks.map(async (n) => [n, (await this.publicClient.getBlock({ blockNumber: n })).timestamp])));
164
+ const queue = [...new Set(logs.filter((l) => l.args.timestamp === void 0).map((l) => l.blockNumber))];
165
+ const times = /* @__PURE__ */ new Map();
166
+ const read = async () => {
167
+ for (let n = queue.shift(); n !== void 0; n = queue.shift()) try {
168
+ const block = await this.publicClient.getBlock({ blockNumber: n });
169
+ times.set(n, block.timestamp);
170
+ } catch (e) {
171
+ queue.length = 0;
172
+ throw e;
173
+ }
174
+ };
175
+ await Promise.all(Array.from({ length: Math.min(TIMESTAMP_READS, queue.length) }, read));
162
176
  return logs.map((l) => toEntry(l, l.args.timestamp ?? times.get(l.blockNumber) ?? 0n));
163
177
  }
164
178
  watch(filter, onEntry, onError, pollingInterval) {
@@ -232,12 +232,22 @@ declare class FangornEngine {
232
232
  * stitch to read only the log since it, and upload only the nodes it doesn't have
233
233
  * (one CAR). Returns the stitch block's CID, its name; with nothing new, `prev`.
234
234
  * Use the same `filter` every time for one stitch. `fromBlock` is where the log
235
- * starts (the registry's deploy block).
235
+ * starts (the registry's deploy block). `upTo` stops the fold at that block (the
236
+ * head if later or unset), so a long catch-up can be taken in bounded steps: a
237
+ * step always moves the stitch to its end, even with nothing in it.
238
+ * Throws, writing nothing, if the folded log doesn't match the contract's log root
239
+ * at the fold's end: an RPC that left out or altered an entry (a lagging node
240
+ * behind a load balancer). The next restitch from `prev` folds that range again.
241
+ * That check reads the log root as of the fold's end block, so a step that ends
242
+ * before the head needs an RPC that serves historical state (an archive node; Base
243
+ * Sepolia's default, publicnode, does). Most RPCs keep only recent state, and on
244
+ * those an older step fails with the RPC's error rather than skipping the check.
236
245
  * ponytail: rehashes the whole tree (O(repos)); and readers walk back one CAR per
237
246
  * stitch to find old nodes, so checkpoint with a full CAR (`prev = null`) when the
238
247
  * chain gets long.
239
248
  */
240
- restitch(prev: CID | null, filter?: (publisher: Address, repo: RepoName) => boolean, fromBlock?: bigint): Promise<CID>;
249
+ restitch(prev: CID | null, filter?: (publisher: Address, repo: RepoName) => boolean, fromBlock?: bigint, upTo?: bigint): Promise<CID>;
250
+ private writeStitch;
241
251
  /** A stitch block: its tree root, and the log it was folded from (n entries, root `logRoot`). */
242
252
  readStitch(stitch: CID): Promise<{
243
253
  root: CID;
@@ -476,38 +476,60 @@ var FangornEngine = class {
476
476
  * stitch to read only the log since it, and upload only the nodes it doesn't have
477
477
  * (one CAR). Returns the stitch block's CID, its name; with nothing new, `prev`.
478
478
  * Use the same `filter` every time for one stitch. `fromBlock` is where the log
479
- * starts (the registry's deploy block).
479
+ * starts (the registry's deploy block). `upTo` stops the fold at that block (the
480
+ * head if later or unset), so a long catch-up can be taken in bounded steps: a
481
+ * step always moves the stitch to its end, even with nothing in it.
482
+ * Throws, writing nothing, if the folded log doesn't match the contract's log root
483
+ * at the fold's end: an RPC that left out or altered an entry (a lagging node
484
+ * behind a load balancer). The next restitch from `prev` folds that range again.
485
+ * That check reads the log root as of the fold's end block, so a step that ends
486
+ * before the head needs an RPC that serves historical state (an archive node; Base
487
+ * Sepolia's default, publicnode, does). Most RPCs keep only recent state, and on
488
+ * those an older step fails with the RPC's error rather than skipping the check.
480
489
  * ponytail: rehashes the whole tree (O(repos)); and readers walk back one CAR per
481
490
  * stitch to find old nodes, so checkpoint with a full CAR (`prev = null`) when the
482
491
  * chain gets long.
483
492
  */
484
- async restitch(prev, filter, fromBlock = 0n) {
493
+ async restitch(prev, filter, fromBlock = 0n, upTo) {
485
494
  const base = prev ? await this.readStitch(prev) : null;
486
- const to = await this.registry.clock();
495
+ const head = await this.registry.clock();
496
+ const to = upTo !== void 0 && upTo < head ? upTo : head;
487
497
  const entries = await this.registry.log({}, base ? base.t + 1n : fromBlock, to);
488
- if (prev && entries.length === 0) return prev;
498
+ if (prev && entries.length === 0 && to === head) return prev;
499
+ let mmr = base ?? EMPTY_MMR;
500
+ for (const e of entries) mmr = mmrAppend(mmr, logLeaf(e));
501
+ const onChain = await this.registry.logRoot(to);
502
+ if (mmrRoot(mmr) !== onChain) throw new Error(`the log read up to block ${String(to)} (${String(mmr.n)} entries) doesn't match the contract's log root there: an entry is missing or altered`);
503
+ if (base && prev && entries.length === 0) return this.writeStitch({
504
+ parent: prev,
505
+ root: base.root,
506
+ car: null,
507
+ n: mmr.n,
508
+ t: Number(to),
509
+ peaks: mmr.peaks
510
+ });
489
511
  const old = base && prev ? await readMst(base.root, (c) => this.getBlock(c, prev)) : {
490
512
  state: /* @__PURE__ */ new Map(),
491
513
  nodeCids: /* @__PURE__ */ new Set()
492
514
  };
493
515
  const state = new Map(old.state);
494
- let mmr = base ?? EMPTY_MMR;
495
- for (const e of entries) {
496
- mmr = mmrAppend(mmr, logLeaf(e));
497
- if (!filter || filter(e.publisher, e.repo)) state.set(stitchKey(e.publisher, e.repo), this.hexToRootCid(e.head));
498
- }
516
+ for (const e of entries) if (!filter || filter(e.publisher, e.repo)) state.set(stitchKey(e.publisher, e.repo), this.hexToRootCid(e.head));
499
517
  const { root, nodes } = await buildMst(state);
500
518
  const fresh = /* @__PURE__ */ new Map();
501
519
  for (const n of nodes) if (!old.nodeCids.has(n.cid.toString())) fresh.set(n.cid.toString(), n);
502
520
  for (const n of fresh.values()) this.putLocal(n);
503
- const block = await encodeBlock({
521
+ const car = fresh.size ? fileCid(await this.storage.putFile(await packCar(root, fresh.values()), `${root.toString()}.car`)) : null;
522
+ return this.writeStitch({
504
523
  parent: prev,
505
524
  root,
506
- car: fresh.size ? fileCid(await this.storage.putFile(await packCar(root, fresh.values()), `${root.toString()}.car`)) : null,
525
+ car,
507
526
  n: mmr.n,
508
527
  t: Number(to),
509
528
  peaks: mmr.peaks
510
529
  });
530
+ }
531
+ async writeStitch(stitch) {
532
+ const block = await encodeBlock(stitch);
511
533
  await this.storage.putBlock(block);
512
534
  this.putLocal(block);
513
535
  this.loadedCars.add(block.cid.toString());
package/lib/fangorn.d.ts CHANGED
@@ -289,12 +289,19 @@ declare class Fangorn {
289
289
  /**
290
290
  * Build or update a stitch across the repos `patterns` match (see `stitchFilter`),
291
291
  * from the update log. Pass the previous stitch to update it. Returns the stitch's CID.
292
+ * `upTo` folds only up to that block, for a catch-up in bounded steps; a step that ends
293
+ * before the head needs an RPC that serves historical state. Throws if the log read
294
+ * doesn't match the contract's log root (see `FangornEngine.restitch`).
295
+ */
296
+ restitch(patterns: string[], prev?: string, upTo?: bigint): Promise<string>;
297
+ /**
298
+ * A stitch's tree root, and the log it was folded from: n entries up to block t,
299
+ * with root `logRoot`.
292
300
  */
293
- restitch(patterns: string[], prev?: string): Promise<string>;
294
- /** A stitch's tree root, and the log it was folded from: n entries, with root `logRoot`. */
295
301
  readStitch(stitch: string): Promise<{
296
302
  root: string;
297
303
  n: number;
304
+ t: bigint;
298
305
  logRoot: `0x${string}`;
299
306
  }>;
300
307
  /** Check a stitch against the contract's log root, rebuilding it under the same patterns. */
package/lib/fangorn.js CHANGED
@@ -77,7 +77,7 @@ var Fangorn = class Fangorn {
77
77
  });
78
78
  const publicClient = createPublicClient({
79
79
  chain: config.chain,
80
- transport: http(config.rpcUrl)
80
+ transport: http(config.rpcUrl, config.rpcRetry)
81
81
  });
82
82
  const ctx = {
83
83
  config,
@@ -442,16 +442,23 @@ var Fangorn = class Fangorn {
442
442
  /**
443
443
  * Build or update a stitch across the repos `patterns` match (see `stitchFilter`),
444
444
  * from the update log. Pass the previous stitch to update it. Returns the stitch's CID.
445
+ * `upTo` folds only up to that block, for a catch-up in bounded steps; a step that ends
446
+ * before the head needs an RPC that serves historical state. Throws if the log read
447
+ * doesn't match the contract's log root (see `FangornEngine.restitch`).
445
448
  */
446
- async restitch(patterns, prev) {
447
- return (await this.engine.restitch(prev ? CID.parse(prev) : null, stitchFilter(patterns), this.ctx.config.fromBlock)).toString();
449
+ async restitch(patterns, prev, upTo) {
450
+ return (await this.engine.restitch(prev ? CID.parse(prev) : null, stitchFilter(patterns), this.ctx.config.fromBlock, upTo)).toString();
448
451
  }
449
- /** A stitch's tree root, and the log it was folded from: n entries, with root `logRoot`. */
452
+ /**
453
+ * A stitch's tree root, and the log it was folded from: n entries up to block t,
454
+ * with root `logRoot`.
455
+ */
450
456
  async readStitch(stitch) {
451
457
  const s = await this.engine.readStitch(CID.parse(stitch));
452
458
  return {
453
459
  root: s.root.toString(),
454
460
  n: s.n,
461
+ t: s.t,
455
462
  logRoot: s.logRoot
456
463
  };
457
464
  }
@@ -3,12 +3,12 @@ import { CommitUpdate, LogFilter, Registry, RepoRef, UpdateEntry } from "../cont
3
3
  import { Mmr } from "../contracts/data-registry/mmr.js";
4
4
  import "../contracts/index.js";
5
5
  import "../index.js";
6
- import * as viem237 from "viem";
6
+ import * as viem6075 from "viem";
7
7
  import { Address, Hash, Hex, LocalAccount } from "viem";
8
8
 
9
9
  //#region src/test/mem-registry.d.ts
10
10
  /** The EIP-712 domain a MemRegistry signs under. */
11
- declare const MEM_DOMAIN: viem237.TypedDataDomain;
11
+ declare const MEM_DOMAIN: viem6075.TypedDataDomain;
12
12
  /** One ordering and the registry state over it, shared by every signer of a MemRegistry. */
13
13
  declare class MemLedger {
14
14
  /** H: position and head */