@fangorn-network/sdk 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/lib/cli/cli.js +83 -46
  2. package/lib/cli/sell.d.ts +2 -2
  3. package/lib/cli/sell.js +14 -8
  4. package/lib/cli/stage.d.ts +21 -3
  5. package/lib/cli/stage.js +110 -24
  6. package/lib/config.d.ts +480 -154
  7. package/lib/config.js +11 -2
  8. package/lib/contracts/data-registry/abi.d.ts +41 -0
  9. package/lib/contracts/data-registry/abi.js +46 -0
  10. package/lib/contracts/data-registry/index.d.ts +45 -3
  11. package/lib/contracts/data-registry/index.js +69 -14
  12. package/lib/contracts/data-registry/mmr.d.ts +9 -2
  13. package/lib/contracts/data-registry/mmr.js +6 -2
  14. package/lib/contracts/index.d.ts +2 -2
  15. package/lib/contracts/index.js +2 -2
  16. package/lib/contracts/write.d.ts +17 -2
  17. package/lib/contracts/write.js +63 -7
  18. package/lib/crypto/encryption.js +3 -0
  19. package/lib/crypto/paid.d.ts +1 -1
  20. package/lib/crypto/paid.js +4 -1
  21. package/lib/engine/index.d.ts +9 -2
  22. package/lib/engine/index.js +33 -17
  23. package/lib/engine/records.d.ts +9 -1
  24. package/lib/engine/records.js +32 -6
  25. package/lib/erc8004.d.ts +1 -1
  26. package/lib/erc8004.js +12 -5
  27. package/lib/fangorn.d.ts +11 -1
  28. package/lib/fangorn.js +25 -11
  29. package/lib/feed.d.ts +23 -2
  30. package/lib/feed.js +43 -6
  31. package/lib/index.d.ts +3 -3
  32. package/lib/index.js +4 -4
  33. package/lib/providers/storage/index.js +1 -1
  34. package/lib/providers/storage/pinata.js +14 -6
  35. package/lib/providers/storage/signed-url.js +21 -8
  36. package/lib/providers/storage/types.d.ts +9 -1
  37. package/lib/providers/storage/types.js +54 -1
  38. package/lib/providers/storage/utils.d.ts +3 -1
  39. package/lib/providers/storage/utils.js +3 -3
  40. package/lib/test/mem-registry.d.ts +3 -3
  41. package/lib/test/mem-registry.js +7 -5
  42. package/lib/test/testbed.d.ts +5183 -5183
  43. package/package.json +6 -3
@@ -1,12 +1,13 @@
1
- import { assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, lookupMst, readMst } from "./records.js";
1
+ import { assertBlockMatches, assertStorable, assertValidRecordId, blockMatches, buildMst, decodeBlock, diffMst, encodeBlock, lookupMst, readMst } from "./records.js";
2
2
  import { packCar, readCar } from "./car.js";
3
3
  import { ZERO_HEAD } from "../contracts/data-registry/index.js";
4
4
  import { EMPTY_MMR, logLeaf, mmrAppend, mmrRoot } from "../contracts/data-registry/mmr.js";
5
5
  import "../contracts/index.js";
6
6
  import { bytesToHex, hexToBytes } from "viem";
7
7
  import { CID } from "multiformats/cid";
8
- import * as dagCbor from "@ipld/dag-cbor";
9
8
  import { sha256 } from "multiformats/hashes/sha2";
9
+ import { equals } from "multiformats/bytes";
10
+ import * as dagCbor from "@ipld/dag-cbor";
10
11
  import * as Digest from "multiformats/hashes/digest";
11
12
 
12
13
  //#region src/engine/index.ts
@@ -65,9 +66,13 @@ function fileCid(uri) {
65
66
  throw new Error(`storage returned ${JSON.stringify(uri)} for a CAR file; expected its CID`);
66
67
  }
67
68
  }
68
- /** Repos must be non-empty strings whose length does not exceed MAX_REPO_NAME_LENGTH */
69
+ /**
70
+ * Repos must be non-empty, well-formed strings whose length does not exceed MAX_REPO_NAME_LENGTH.
71
+ * Well-formed: a lone UTF-16 surrogate encodes as U+FFFD, so two such names would be one repo on chain.
72
+ */
69
73
  function assertValidRepoName(repo) {
70
74
  if (typeof repo !== "string" || repo.length === 0) throw new Error("repo must be a non-empty string");
75
+ if (!repo.isWellFormed()) throw new Error("repo must be a well-formed (UTF-16) string");
71
76
  if (repo.length > MAX_REPO_NAME_LENGTH) throw new Error(`repo exceeds the maximum length of ${MAX_REPO_NAME_LENGTH.toString()} characters (got ${repo.length.toString()}).`);
72
77
  }
73
78
  const EMPTY_STATE = {
@@ -143,7 +148,13 @@ var FangornEngine = class {
143
148
  const bytes = await this.storage.getFile(car.toString());
144
149
  for (const block of await readCar(bytes, { verify: false })) {
145
150
  const key = block.cid.toString();
146
- if (!this.cache.has(key)) this.unverified.set(key, block.bytes);
151
+ if (this.cache.has(key)) continue;
152
+ const prev = this.unverified.get(key);
153
+ if (!prev) this.unverified.set(key, block.bytes);
154
+ else if (!equals(prev, block.bytes) && blockMatches(block.cid, block.bytes)) {
155
+ this.unverified.delete(key);
156
+ this.cache.set(key, block.bytes);
157
+ }
147
158
  }
148
159
  }
149
160
  this.loadedCars.add(linkCid.toString());
@@ -154,13 +165,17 @@ var FangornEngine = class {
154
165
  */
155
166
  async getBlock(cid, hint) {
156
167
  const key = cid.toString();
168
+ let tampered = false;
157
169
  const local = () => {
158
170
  const hit$1 = this.cache.get(key);
159
171
  if (hit$1) return hit$1;
160
172
  const raw = this.unverified.get(key);
161
173
  if (!raw) return null;
162
- assertBlockMatches(cid, raw);
163
174
  this.unverified.delete(key);
175
+ if (!blockMatches(cid, raw)) {
176
+ tampered = true;
177
+ return null;
178
+ }
164
179
  this.cache.set(key, raw);
165
180
  return raw;
166
181
  };
@@ -169,13 +184,12 @@ var FangornEngine = class {
169
184
  let cursor = hint;
170
185
  while (cursor) {
171
186
  const link = await this.chainLink(cursor);
172
- if (!this.loadedCars.has(cursor.toString())) {
173
- await this.loadCar(cursor, link.car);
174
- const found = local();
175
- if (found) return found;
176
- }
187
+ if (!this.loadedCars.has(cursor.toString())) await this.loadCar(cursor, link.car);
188
+ const found = local();
189
+ if (found) return found;
177
190
  cursor = link.parent;
178
191
  }
192
+ if (tampered) throw new Error(`block ${key} does not match its content hash`);
179
193
  throw new Error(`Block payload missing for key: ${key}`);
180
194
  }
181
195
  putLocal(block) {
@@ -223,22 +237,24 @@ var FangornEngine = class {
223
237
  const state = opts.replace ? /* @__PURE__ */ new Map() : new Map(old.state);
224
238
  for (const id of opts.deletes ?? []) state.delete(id);
225
239
  const carBlocks = [];
226
- const recordCids = {};
240
+ const recordCids = /* @__PURE__ */ new Map();
227
241
  for (const r of opts.records) {
228
242
  const id = r.id ?? globalThis.crypto.randomUUID();
229
243
  assertValidRecordId(id);
230
- if (id in recordCids) throw new Error(`record id ${id} staged twice`);
244
+ if (recordCids.has(id)) throw new Error(`record id ${id} staged twice`);
245
+ assertStorable(r.type, "type");
246
+ assertStorable(r.payload);
231
247
  const block = await encodeBlock({
232
248
  id,
233
249
  type: r.type,
234
250
  payload: r.payload
235
251
  });
236
252
  state.set(id, block.cid);
237
- recordCids[id] = block.cid.toString();
253
+ recordCids.set(id, block.cid.toString());
238
254
  if (opts.checkpoint || !oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
239
255
  }
240
256
  if (opts.checkpoint) {
241
- const staged = new Set(Object.values(recordCids));
257
+ const staged = new Set(recordCids.values());
242
258
  for (const cid of state.values()) if (!staged.has(cid.toString())) carBlocks.push({
243
259
  cid,
244
260
  bytes: await this.getBlock(cid, base)
@@ -274,7 +290,7 @@ var FangornEngine = class {
274
290
  return {
275
291
  commitCid: commitBlock.cid,
276
292
  root: mst.root,
277
- recordCids
293
+ recordCids: Object.fromEntries(recordCids)
278
294
  };
279
295
  }
280
296
  /**
@@ -374,10 +390,10 @@ var FangornEngine = class {
374
390
  * chain or a commit from before diff events, it diffs the two trees (`diffMst`). Either way the
375
391
  * result is the net delta an index builder needs: what to (re)embed, what to evict.
376
392
  */
377
- async repoDiff(oldRootHex, newRootHex) {
393
+ async repoDiff(oldRootHex, newRootHex, { useEventDiff = true } = {}) {
378
394
  const newCommit = newRootHex === ZERO_BYTES32 ? null : this.hexToRootCid(newRootHex);
379
395
  const oldCommit = oldRootHex && oldRootHex !== ZERO_BYTES32 ? this.hexToRootCid(oldRootHex) : null;
380
- const events = oldCommit && newCommit ? await this.eventsSince(oldCommit, newCommit) : null;
396
+ const events = useEventDiff && oldCommit && newCommit ? await this.eventsSince(oldCommit, newCommit) : null;
381
397
  if (oldCommit && newCommit && events) {
382
398
  const oldRoot = (await this.getCommit(oldCommit)).root;
383
399
  const puts$1 = [];
@@ -13,8 +13,16 @@ declare function encodeBlock(obj: unknown): Promise<Block>;
13
13
  * map keys), so a block has one accepted byte form (FOUNDATIONS P1).
14
14
  */
15
15
  declare function decodeBlock<T>(bytes: Uint8Array): T;
16
+ /** Whether `bytes` hash to `cid`. */
17
+ declare function blockMatches(cid: CID, bytes: Uint8Array): boolean;
16
18
  /** Throw unless `bytes` hash to `cid`. Hosts are untrusted; every fetched block goes through this. */
17
19
  declare function assertBlockMatches(cid: CID, bytes: Uint8Array): void;
20
+ /**
21
+ * Throw on a value dag-cbor would store as something else: a string (or map key) with a lone
22
+ * UTF-16 surrogate, which encodes as U+FFFD, and an own `__proto__` key, which decodes as
23
+ * the object's prototype instead of a field. Either would change a record between put and read.
24
+ */
25
+ declare function assertStorable(value: unknown, path?: string): void;
18
26
  /** Record block: one version of an entity. `id` is repeated so a record can't be filed under another key. */
19
27
  interface RecordBlock {
20
28
  id: string;
@@ -134,4 +142,4 @@ declare function diffMst(oldRoot: CID | null, newRoot: CID | null, getOld: (cid:
134
142
  */
135
143
  declare function lookupMst(root: CID, key: string, getBlock: (cid: CID) => Promise<Uint8Array>): Promise<CID | null>;
136
144
  //#endregion
137
- export { Block, CommitBlock, MAX_RECORD_ID_LENGTH, MST_BITS, MstEntry, MstNode, RecordBlock, Ref, Stitch, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };
145
+ export { Block, CommitBlock, MAX_RECORD_ID_LENGTH, MST_BITS, MstEntry, MstNode, RecordBlock, Ref, Stitch, assertBlockMatches, assertStorable, assertValidRecordId, blockMatches, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };
@@ -1,14 +1,14 @@
1
1
  import { CID } from "multiformats/cid";
2
+ import { sha256 } from "multiformats/hashes/sha2";
2
3
  import * as dagCbor from "@ipld/dag-cbor";
3
- import { sha256 } from "@noble/hashes/sha2.js";
4
+ import { sha256 as sha256$1 } from "@noble/hashes/sha2.js";
4
5
  import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
5
- import { sha256 as sha256$1 } from "multiformats/hashes/sha2";
6
6
 
7
7
  //#region src/engine/records.ts
8
8
  /** Encode any value as canonical dag-cbor and derive its CIDv1 (sha256). */
9
9
  async function encodeBlock(obj) {
10
10
  const bytes = dagCbor.encode(obj);
11
- const hash = await sha256$1.digest(bytes);
11
+ const hash = await sha256.digest(bytes);
12
12
  return {
13
13
  cid: CID.createV1(dagCbor.code, hash),
14
14
  bytes
@@ -21,9 +21,30 @@ async function encodeBlock(obj) {
21
21
  function decodeBlock(bytes) {
22
22
  return dagCbor.decode(bytes);
23
23
  }
24
+ /** Whether `bytes` hash to `cid`. */
25
+ function blockMatches(cid, bytes) {
26
+ return bytesToHex(cid.multihash.digest) === bytesToHex(sha256$1(bytes));
27
+ }
24
28
  /** Throw unless `bytes` hash to `cid`. Hosts are untrusted; every fetched block goes through this. */
25
29
  function assertBlockMatches(cid, bytes) {
26
- if (bytesToHex(cid.multihash.digest) !== bytesToHex(sha256(bytes))) throw new Error(`block ${cid.toString()} does not match its content hash`);
30
+ if (!blockMatches(cid, bytes)) throw new Error(`block ${cid.toString()} does not match its content hash`);
31
+ }
32
+ /**
33
+ * Throw on a value dag-cbor would store as something else: a string (or map key) with a lone
34
+ * UTF-16 surrogate, which encodes as U+FFFD, and an own `__proto__` key, which decodes as
35
+ * the object's prototype instead of a field. Either would change a record between put and read.
36
+ */
37
+ function assertStorable(value, path = "payload") {
38
+ if (typeof value === "string") {
39
+ if (!value.isWellFormed()) throw new Error(`${path} is not a well-formed (UTF-16) string`);
40
+ } else if (Array.isArray(value)) value.forEach((v, i) => {
41
+ assertStorable(v, `${path}[${i.toString()}]`);
42
+ });
43
+ else if (value && typeof value === "object" && !(value instanceof Uint8Array) && !CID.asCID(value)) for (const [k, v] of Object.entries(value)) {
44
+ if (k === "__proto__") throw new Error(`${path} has a __proto__ key`);
45
+ assertStorable(k, `${path} key`);
46
+ assertStorable(v, `${path}.${k}`);
47
+ }
27
48
  }
28
49
  /** Upper bound on a record id's length. */
29
50
  const MAX_RECORD_ID_LENGTH = 256;
@@ -41,7 +62,7 @@ const MST_BITS = 4;
41
62
  const MAX_DEPTH = 256 / MST_BITS + 1;
42
63
  /** level(k) = ⌊leading zero bits of sha256(k) / b⌋ */
43
64
  function keyLevel(key) {
44
- const digest = sha256(utf8ToBytes(key));
65
+ const digest = sha256$1(utf8ToBytes(key));
45
66
  let zeros = 0;
46
67
  for (const byte of digest) {
47
68
  if (byte !== 0) {
@@ -124,6 +145,7 @@ async function readMst(root, getBlock) {
124
145
  const nodeCids = /* @__PURE__ */ new Set();
125
146
  const walk = async (cid, depth) => {
126
147
  if (depth > MAX_DEPTH) throw new Error(`MST at ${root.toString()} is deeper than ${MAX_DEPTH.toString()}`);
148
+ if (nodeCids.has(cid.toString())) throw new Error(`MST at ${root.toString()} repeats node ${cid.toString()}`);
127
149
  nodeCids.add(cid.toString());
128
150
  const node = decodeBlock(await getBlock(cid));
129
151
  if (!Array.isArray(node.entries)) throw new Error(`${cid.toString()} is not a record tree node — graph-era data (vertices/edges) is no longer readable. Reset the on-chain head (\`fangorn reset\`) and re-publish.`);
@@ -158,8 +180,12 @@ async function diffMst(oldRoot, newRoot, getOld, getNew) {
158
180
  sub: newRoot,
159
181
  level: Infinity
160
182
  }] : [];
183
+ const opened = /* @__PURE__ */ new Set();
161
184
  const open = async (s, get) => {
162
185
  const { sub } = s.pop();
186
+ const seen = `${s === a ? "a" : "b"}${sub.toString()}`;
187
+ if (opened.has(seen)) throw new Error(`MST repeats node ${sub.toString()}`);
188
+ opened.add(seen);
163
189
  const node = decodeBlock(await get(sub));
164
190
  const items = node.left ? [{
165
191
  sub: node.left,
@@ -237,4 +263,4 @@ async function lookupMst(root, key, getBlock) {
237
263
  }
238
264
 
239
265
  //#endregion
240
- export { MAX_RECORD_ID_LENGTH, MST_BITS, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };
266
+ export { MAX_RECORD_ID_LENGTH, MST_BITS, assertBlockMatches, assertStorable, assertValidRecordId, blockMatches, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };
package/lib/erc8004.d.ts CHANGED
@@ -45,7 +45,7 @@ interface Erc8004Clients {
45
45
  chain: Chain;
46
46
  publicClient: PublicClient;
47
47
  walletClient: WalletClient;
48
- storage: Pick<MetadataStorage, "put">;
48
+ storage: Pick<MetadataStorage, "put"> & Partial<Pick<MetadataStorage, "getRawBlock">>;
49
49
  }
50
50
  declare function retryNonce<T>(f: () => Promise<T>, tries?: number): Promise<T>;
51
51
  /** Pin `file` and point agent `agentId` at it. */
package/lib/erc8004.js CHANGED
@@ -1,10 +1,15 @@
1
+ import { assertStoredFile } from "./providers/storage/types.js";
2
+ import { serialize } from "./providers/storage/utils.js";
3
+ import { confirmTx } from "./contracts/write.js";
1
4
  import { parseAbi, parseEventLogs } from "viem";
2
5
 
3
6
  //#region src/erc8004.ts
4
7
  /** The ERC-8004 identity registry by chain id */
5
8
  const IDENTITY_REGISTRY = {
6
9
  84532: "0x8004A818BFB912233c491871b3d84c89A494BD9e",
7
- 421614: "0x8004A818BFB912233c491871b3d84c89A494BD9e"
10
+ 421614: "0x8004A818BFB912233c491871b3d84c89A494BD9e",
11
+ 8453: "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432",
12
+ 42161: "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"
8
13
  };
9
14
  const ABI = parseAbi([
10
15
  "function register(string agentURI, (string metadataKey, bytes metadataValue)[] metadata) returns (uint256 agentId)",
@@ -107,7 +112,9 @@ function registry(chain) {
107
112
  }
108
113
  /** Pin `file` and point agent `agentId` at it. */
109
114
  async function setAgentFile(c, agentId, file) {
110
- const cid = await c.storage.put(file, { name: "agent-registration.json" });
115
+ const bytes = new TextEncoder().encode(serialize(file));
116
+ const cid = (await c.storage.put(file, { name: "agent-registration.json" })).replace(/^ipfs:\/\//, "");
117
+ await assertStoredFile(cid, bytes, c.storage);
111
118
  const hash = await c.walletClient.writeContract({
112
119
  address: registry(c.chain),
113
120
  abi: ABI,
@@ -116,8 +123,7 @@ async function setAgentFile(c, agentId, file) {
116
123
  chain: c.chain,
117
124
  account: c.walletClient.account ?? null
118
125
  });
119
- const { status } = await c.publicClient.waitForTransactionReceipt({ hash });
120
- if (status !== "success") throw new Error(`setAgentURI reverted in tx ${hash}`);
126
+ await confirmTx(c.publicClient, hash, "setAgentURI");
121
127
  return hash;
122
128
  }
123
129
  /** Mint an agent with no URI yet, and return its id. */
@@ -131,10 +137,11 @@ async function mintAgent(c) {
131
137
  chain: c.chain,
132
138
  account: c.walletClient.account ?? null
133
139
  });
140
+ const { receipt } = await confirmTx(c.publicClient, hash, "register");
134
141
  const minted = parseEventLogs({
135
142
  abi: ABI,
136
143
  eventName: "Registered",
137
- logs: (await c.publicClient.waitForTransactionReceipt({ hash })).logs
144
+ logs: receipt.logs
138
145
  }).find((l) => l.address.toLowerCase() === address.toLowerCase());
139
146
  if (!minted) throw new Error(`register ${hash} confirmed with no Registered event`);
140
147
  return minted.args.agentId;
package/lib/fangorn.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PreparedTx } from "./contracts/write.js";
2
- import { Registry } from "./contracts/data-registry/index.js";
2
+ import { Registry, UpdateEntry } from "./contracts/data-registry/index.js";
3
3
  import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
4
4
  import "./contracts/index.js";
5
5
  import { MetadataStorage } from "./providers/storage/types.js";
@@ -35,6 +35,14 @@ interface SubscribeOptions {
35
35
  pollingInterval?: number;
36
36
  /** Abort to stop the subscription and release the watch. */
37
37
  signal?: AbortSignal;
38
+ /**
39
+ * Called for a log entry the stream skips because its commit can't be read
40
+ * (blocks missing from storage, or not what they claim). Anyone can log such
41
+ * an entry. Other repos continue streaming. When the same repo next has
42
+ * readable state, the stream reports its net changes since the last readable
43
+ * head (or the first observed parent). Defaults to a warning.
44
+ */
45
+ onSkip?: (err: Error, entry: UpdateEntry) => void;
38
46
  }
39
47
  /**
40
48
  * The A2A extension a repo's agent card carries. Its params name the repo the
@@ -321,6 +329,8 @@ declare class Fangorn {
321
329
  }): AsyncGenerator<RepoChange>;
322
330
  /** Shared catch-up-then-live loop behind `subscribe` and `subscribeAll`. */
323
331
  private streamCommits;
332
+ /** `toRepoChange`, skipping (and reporting) an entry whose commit can't be read. */
333
+ private readChange;
324
334
  /**
325
335
  * Resolve a log entry into a repo change, or null if the repo's records did
326
336
  * not change.
package/lib/fangorn.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import { FangornConfig, nonBlank } from "./config.js";
2
- import { mcpTools, mintAgent, registrationFile, retryNonce, setAgentFile } from "./erc8004.js";
3
- import { SignedUrlBackend } from "./providers/storage/signed-url.js";
4
2
  import { PinataBackend } from "./providers/storage/pinata.js";
3
+ import { SignedUrlBackend } from "./providers/storage/signed-url.js";
4
+ import { mcpTools, mintAgent, registrationFile, retryNonce, setAgentFile } from "./erc8004.js";
5
5
  import { ChainRegistry, ZERO_HEAD } from "./contracts/data-registry/index.js";
6
6
  import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
7
7
  import "./contracts/index.js";
8
8
  import { CHECKPOINT_EVERY, FangornEngine, assertValidRepoName, commitUpdate, rootHexFromCid } from "./engine/index.js";
9
9
  import { CommitFeed } from "./feed.js";
10
10
  import { createPublicClient, createWalletClient, http, toHex } from "viem";
11
- import { privateKeyToAccount } from "viem/accounts";
12
11
  import { CID } from "multiformats/cid";
12
+ import { privateKeyToAccount } from "viem/accounts";
13
13
 
14
14
  //#region src/fangorn.ts
15
15
  const ZERO_BYTES32 = ZERO_HEAD;
@@ -414,10 +414,12 @@ var Fangorn = class Fangorn {
414
414
  * anywhere more than one consumer wants the same stream.
415
415
  */
416
416
  feed(opts = {}) {
417
- this._feed ??= new CommitFeed((signal) => this.subscribeAll({
417
+ this._feed ??= new CommitFeed((signal, fromBlock, onSkip) => this.subscribeAll({
418
418
  ...opts,
419
- signal
420
- }));
419
+ signal,
420
+ fromBlock,
421
+ onSkip
422
+ }), void 0, () => this.ctx.registry.clock());
421
423
  return this._feed;
422
424
  }
423
425
  /** Walk commit history from `head` (newest first). */
@@ -535,7 +537,7 @@ var Fangorn = class Fangorn {
535
537
  if (opts.fromBlock !== void 0) for (const log of await registry.log(filter, opts.fromBlock)) {
536
538
  if (seen.has(log.id)) continue;
537
539
  seen.add(log.id);
538
- const change = await this.toRepoChange(log, lastHead);
540
+ const change = await this.readChange(log, lastHead, opts.onSkip);
539
541
  if (change) yield change;
540
542
  }
541
543
  while (!subState.stopped) {
@@ -550,7 +552,7 @@ var Fangorn = class Fangorn {
550
552
  if (!log) continue;
551
553
  if (seen.has(log.id)) continue;
552
554
  seen.add(log.id);
553
- const change = await this.toRepoChange(log, lastHead);
555
+ const change = await this.readChange(log, lastHead, opts.onSkip);
554
556
  if (change) yield change;
555
557
  }
556
558
  } finally {
@@ -558,6 +560,17 @@ var Fangorn = class Fangorn {
558
560
  opts.signal?.removeEventListener("abort", onAbort);
559
561
  }
560
562
  }
563
+ /** `toRepoChange`, skipping (and reporting) an entry whose commit can't be read. */
564
+ async readChange(log, lastHead, onSkip) {
565
+ try {
566
+ return await this.toRepoChange(log, lastHead);
567
+ } catch (e) {
568
+ const err = e instanceof Error ? e : new Error(String(e));
569
+ if (onSkip) onSkip(err, log);
570
+ else console.warn(`[fangorn] skipped ${log.publisher}/${log.repo} head ${log.head} (block ${log.t.toString()}): ${err.message}`);
571
+ return null;
572
+ }
573
+ }
561
574
  /**
562
575
  * Resolve a log entry into a repo change, or null if the repo's records did
563
576
  * not change.
@@ -572,12 +585,13 @@ var Fangorn = class Fangorn {
572
585
  * dropped entry changed.
573
586
  */
574
587
  async toRepoChange(log, lastHead) {
575
- const declared = await this.engine.repoOf(log.head);
576
- if (declared !== log.repo) throw new Error(`commit ${log.head} declares repo "${declared}", which does not match the repo it was committed to ("${log.repo}")`);
577
588
  const key = `${log.publisher.toLowerCase()}/${log.repo}`;
578
589
  const oldRoot = lastHead.get(key) ?? log.parent;
590
+ lastHead.set(key, oldRoot);
591
+ const declared = await this.engine.repoOf(log.head);
592
+ if (declared !== log.repo) throw new Error(`commit ${log.head} declares repo "${declared}", which does not match the repo it was committed to ("${log.repo}")`);
593
+ const diff = await this.engine.repoDiff(oldRoot === ZERO_BYTES32 ? null : oldRoot, log.head, { useEventDiff: oldRoot === log.parent });
579
594
  lastHead.set(key, log.head);
580
- const diff = await this.engine.repoDiff(oldRoot === ZERO_BYTES32 ? null : oldRoot, log.head);
581
595
  if (!diff.puts.length && !diff.deletes.length) return null;
582
596
  return {
583
597
  repo: log.repo,
package/lib/feed.d.ts CHANGED
@@ -14,13 +14,32 @@ import { RepoChange } from "./fangorn.js";
14
14
  * only shares the stream. fangorn-md's server fans it out to its connections.
15
15
  */
16
16
  declare class CommitFeed {
17
+ /**
18
+ * Open the stream: from `fromBlock` when given (a restart), live otherwise.
19
+ * `onSkip` reports an entry the stream skipped (an unreadable commit) without
20
+ * ending it; the feed hands it to every listener's `onError`.
21
+ */
17
22
  private readonly open;
18
23
  /** Delay before reopening the watch after it fails or ends. */
19
24
  private readonly restartDelayMs;
25
+ /** Read the current block before opening a replayable chain source. */
26
+ private readonly clock?;
20
27
  private readonly listeners;
21
28
  private abort;
22
- constructor(open: (signal: AbortSignal) => AsyncGenerator<RepoChange>, /** Delay before reopening the watch after it fails or ends. */
23
- restartDelayMs?: number);
29
+ /**
30
+ * The last block a change was delivered from, and the changes delivered from it:
31
+ * a restart resumes there instead of at the tip, and skips what it already sent.
32
+ */
33
+ private cursor;
34
+ constructor(
35
+ /**
36
+ * Open the stream: from `fromBlock` when given (a restart), live otherwise.
37
+ * `onSkip` reports an entry the stream skipped (an unreadable commit) without
38
+ * ending it; the feed hands it to every listener's `onError`.
39
+ */
40
+ open: (signal: AbortSignal, fromBlock?: bigint, onSkip?: (err: Error) => void) => AsyncGenerator<RepoChange>, /** Delay before reopening the watch after it fails or ends. */
41
+ restartDelayMs?: number, /** Read the current block before opening a replayable chain source. */
42
+ clock?: (() => Promise<bigint>) | undefined);
24
43
  /** Number of live listeners — 0 means the underlying watch is closed. */
25
44
  get size(): number;
26
45
  /**
@@ -29,6 +48,8 @@ declare class CommitFeed {
29
48
  */
30
49
  on(onChange: (change: RepoChange) => void, onError?: (err: Error) => void): () => void;
31
50
  private run;
51
+ /** Move the cursor past `change`; false if it was already delivered (a restart's replay). */
52
+ private advance;
32
53
  }
33
54
  //#endregion
34
55
  export { CommitFeed };
package/lib/feed.js CHANGED
@@ -13,9 +13,15 @@
13
13
  var CommitFeed = class {
14
14
  listeners = /* @__PURE__ */ new Set();
15
15
  abort = null;
16
- constructor(open, restartDelayMs = 2e3) {
16
+ /**
17
+ * The last block a change was delivered from, and the changes delivered from it:
18
+ * a restart resumes there instead of at the tip, and skips what it already sent.
19
+ */
20
+ cursor = null;
21
+ constructor(open, restartDelayMs = 2e3, clock) {
17
22
  this.open = open;
18
23
  this.restartDelayMs = restartDelayMs;
24
+ this.clock = clock;
19
25
  }
20
26
  /** Number of live listeners — 0 means the underlying watch is closed. */
21
27
  get size() {
@@ -37,6 +43,7 @@ var CommitFeed = class {
37
43
  if (this.listeners.size === 0) {
38
44
  this.abort?.abort();
39
45
  this.abort = null;
46
+ this.cursor = null;
40
47
  }
41
48
  };
42
49
  }
@@ -44,22 +51,52 @@ var CommitFeed = class {
44
51
  const abort = new AbortController();
45
52
  this.abort = abort;
46
53
  const stopped = () => abort.signal.aborted;
54
+ const report = (err) => {
55
+ for (const l of [...this.listeners]) l.onError?.(err);
56
+ };
47
57
  (async () => {
48
58
  while (!stopped()) {
49
59
  try {
50
- for await (const change of this.open(abort.signal)) for (const l of [...this.listeners]) try {
51
- l.onChange(change);
52
- } catch (err) {
53
- l.onError?.(asError(err));
60
+ if (!this.cursor && this.clock) {
61
+ const tip = await this.clock();
62
+ if (stopped()) return;
63
+ this.cursor = {
64
+ block: tip + 1n,
65
+ sent: /* @__PURE__ */ new Set()
66
+ };
67
+ }
68
+ for await (const change of this.open(abort.signal, this.cursor?.block, report)) {
69
+ if (stopped()) return;
70
+ if (!this.advance(change)) continue;
71
+ for (const l of [...this.listeners]) try {
72
+ l.onChange(change);
73
+ } catch (err) {
74
+ l.onError?.(asError(err));
75
+ }
54
76
  }
55
77
  } catch (err) {
56
78
  if (stopped()) return;
57
- for (const l of [...this.listeners]) l.onError?.(asError(err));
79
+ report(asError(err));
58
80
  }
59
81
  if (!stopped()) await new Promise((r) => setTimeout(r, this.restartDelayMs));
60
82
  }
61
83
  })();
62
84
  }
85
+ /** Move the cursor past `change`; false if it was already delivered (a restart's replay). */
86
+ advance(change) {
87
+ if (typeof change.blockNumber !== "bigint") return true;
88
+ const key = `${change.owner}/${change.commitCid}`;
89
+ const c = this.cursor;
90
+ if (c && change.blockNumber < c.block) return false;
91
+ if (c && change.blockNumber === c.block) {
92
+ if (c.sent.has(key)) return false;
93
+ c.sent.add(key);
94
+ } else this.cursor = {
95
+ block: change.blockNumber,
96
+ sent: new Set([key])
97
+ };
98
+ return true;
99
+ }
63
100
  };
64
101
  const asError = (err) => err instanceof Error ? err : new Error(String(err));
65
102
 
package/lib/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { PreparedTx } from "./contracts/write.js";
2
- import { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFilter, Registry, RepoRef, UPDATE_TYPES, UpdateEntry, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./contracts/data-registry/index.js";
2
+ import { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFilter, Registry, RepoRef, UPDATED_V0, UPDATE_TYPES, UpdateEntry, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./contracts/data-registry/index.js";
3
3
  import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
4
4
  import { RegisterArgs, SettleArgs, SettlementPayment, SettlementRegistryClient, TERMS_TYPES, Terms, TermsJson, WHOLE_REPO, recordKey, registerNonce, settlementDomain, subjectOf, termsFromJson, termsToJson } from "./contracts/settlement-registry/index.js";
5
5
  import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
@@ -7,7 +7,7 @@ import { EMPTY_MMR, Mmr, logLeaf, mmrAppend, mmrRoot } from "./contracts/data-re
7
7
  import "./contracts/index.js";
8
8
  import { Ref, Stitch } from "./engine/records.js";
9
9
  import "./engine/index.js";
10
- import { ArbitrumSepoliaConfig, BaseSepoliaConfig, FangornConfig, NetworkConfig, SupportedNetworks, nonBlank } from "./config.js";
10
+ import { ArbitrumSepoliaConfig, BaseConfig, BaseSepoliaConfig, FangornConfig, NetworkConfig, SupportedNetworks, nonBlank } from "./config.js";
11
11
  import { FangornContext, FangornCreateOptions, StorageConfig } from "./types/index.js";
12
12
  import { CommitFeed } from "./feed.js";
13
13
  import { AgentCard, CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn, RepoChange, SubscribeOptions, stitchFilter } from "./fangorn.js";
@@ -17,4 +17,4 @@ import { AccessRequest, Deposit, FieldHandle, GADGET_FIELD_V1, PaidScope, access
17
17
  import { PinataBackend } from "./providers/storage/pinata.js";
18
18
  import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./providers/storage/signed-url.js";
19
19
  import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
20
- export { AccessRequest, AccessSigner, AgentCard, ArbitrumSepoliaConfig, BaseSepoliaConfig, CARD_RECORD, ChainRegistry, ChainRegistryConfig, CommitFeed, CommitUpdate, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, Deposit, EMPTY_MMR, EPOCH_SECONDS, FANGORN_REPO_EXTENSION, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FieldHandle, GADGET_FIELD_V1, GADGET_SELF_HKDF_V1, LogFilter, MAX_UPLOAD_ATTEMPTS, Mmr, NetworkConfig, PaidScope, PinataBackend, PreparedTx, type Ref, RegisterArgs, Registry, RepoChange, RepoRef, SETTLEMENT_REGISTRY_ABI, SellOptions, SettleArgs, SettlementPayment, SettlementRegistryClient, SignedUrlBackend, SignedUrlSigner, type Stitch, StorageConfig, SubscribeOptions, SupportedNetworks, TERMS_TYPES, Terms, TermsJson, UPDATE_TYPES, UpdateEntry, WHOLE_REPO, WINDOW, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessage, buildAccessRequest, dataDomain, decryptField, deriveRecordKey, deserialize, encryptField, epochOf, fetchRawByCid, isTransientUpload, logLeaf, makeDeposit, mmrAppend, mmrRoot, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, stitchFilter, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };
20
+ export { AccessRequest, AccessSigner, AgentCard, ArbitrumSepoliaConfig, BaseConfig, BaseSepoliaConfig, CARD_RECORD, ChainRegistry, ChainRegistryConfig, CommitFeed, CommitUpdate, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, Deposit, EMPTY_MMR, EPOCH_SECONDS, FANGORN_REPO_EXTENSION, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FieldHandle, GADGET_FIELD_V1, GADGET_SELF_HKDF_V1, LogFilter, MAX_UPLOAD_ATTEMPTS, Mmr, NetworkConfig, PaidScope, PinataBackend, PreparedTx, type Ref, RegisterArgs, Registry, RepoChange, RepoRef, SETTLEMENT_REGISTRY_ABI, SellOptions, SettleArgs, SettlementPayment, SettlementRegistryClient, SignedUrlBackend, SignedUrlSigner, type Stitch, StorageConfig, SubscribeOptions, SupportedNetworks, TERMS_TYPES, Terms, TermsJson, UPDATED_V0, UPDATE_TYPES, UpdateEntry, WHOLE_REPO, WINDOW, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessage, buildAccessRequest, dataDomain, decryptField, deriveRecordKey, deserialize, encryptField, epochOf, fetchRawByCid, isTransientUpload, logLeaf, makeDeposit, mmrAppend, mmrRoot, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, stitchFilter, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };
package/lib/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { ArbitrumSepoliaConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, nonBlank } from "./config.js";
1
+ import { ArbitrumSepoliaConfig, BaseConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, nonBlank } from "./config.js";
2
+ import { PinataBackend } from "./providers/storage/pinata.js";
2
3
  import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./providers/storage/signed-url.js";
3
4
  import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
4
- import { PinataBackend } from "./providers/storage/pinata.js";
5
5
  import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
6
- import { ChainRegistry, EPOCH_SECONDS, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./contracts/data-registry/index.js";
6
+ import { ChainRegistry, EPOCH_SECONDS, UPDATED_V0, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./contracts/data-registry/index.js";
7
7
  import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
8
8
  import { SettlementRegistryClient, TERMS_TYPES, WHOLE_REPO, recordKey, registerNonce, settlementDomain, subjectOf, termsFromJson, termsToJson } from "./contracts/settlement-registry/index.js";
9
9
  import { EMPTY_MMR, logLeaf, mmrAppend, mmrRoot } from "./contracts/data-registry/mmr.js";
@@ -14,4 +14,4 @@ import { GADGET_SELF_HKDF_V1, X25519_PUBKEY_LENGTH, seal, sealSelf, unseal, unse
14
14
  import { GADGET_FIELD_V1, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement } from "./crypto/paid.js";
15
15
  import { sealRecords } from "./cli/sell.js";
16
16
 
17
- export { ArbitrumSepoliaConfig, BaseSepoliaConfig, CARD_RECORD, ChainRegistry, CommitFeed, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, EMPTY_MMR, EPOCH_SECONDS, FANGORN_REPO_EXTENSION, Fangorn, FangornConfig, GADGET_FIELD_V1, GADGET_SELF_HKDF_V1, MAX_UPLOAD_ATTEMPTS, PinataBackend, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, SignedUrlBackend, SupportedNetworks, TERMS_TYPES, UPDATE_TYPES, WHOLE_REPO, WINDOW, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessage, buildAccessRequest, dataDomain, decryptField, deriveRecordKey, deserialize, encryptField, epochOf, fetchRawByCid, isTransientUpload, logLeaf, makeDeposit, mmrAppend, mmrRoot, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, stitchFilter, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };
17
+ export { ArbitrumSepoliaConfig, BaseConfig, BaseSepoliaConfig, CARD_RECORD, ChainRegistry, CommitFeed, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, EMPTY_MMR, EPOCH_SECONDS, FANGORN_REPO_EXTENSION, Fangorn, FangornConfig, GADGET_FIELD_V1, GADGET_SELF_HKDF_V1, MAX_UPLOAD_ATTEMPTS, PinataBackend, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, SignedUrlBackend, SupportedNetworks, TERMS_TYPES, UPDATED_V0, UPDATE_TYPES, WHOLE_REPO, WINDOW, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessage, buildAccessRequest, dataDomain, decryptField, deriveRecordKey, deserialize, encryptField, epochOf, fetchRawByCid, isTransientUpload, logLeaf, makeDeposit, mmrAppend, mmrRoot, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, stitchFilter, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };
@@ -1,5 +1,5 @@
1
+ import { PinataBackend } from "./pinata.js";
1
2
  import { SignedUrlBackend } from "./signed-url.js";
2
3
  import { deserialize, retrieveByCid, serialize } from "./utils.js";
3
- import { PinataBackend } from "./pinata.js";
4
4
 
5
5
  export { PinataBackend, SignedUrlBackend, deserialize, retrieveByCid, serialize };