@fangorn-network/sdk 0.1.5 → 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 (46) 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 +15 -9
  4. package/lib/cli/stage.d.ts +21 -3
  5. package/lib/cli/stage.js +110 -24
  6. package/lib/config.d.ts +327 -1
  7. package/lib/config.js +11 -2
  8. package/lib/contracts/data-registry/abi.d.ts +42 -1
  9. package/lib/contracts/data-registry/abi.js +47 -1
  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/settlement-registry/abi.d.ts +1 -1
  17. package/lib/contracts/settlement-registry/abi.js +1 -1
  18. package/lib/contracts/write.d.ts +29 -5
  19. package/lib/contracts/write.js +78 -12
  20. package/lib/crypto/encryption.js +3 -0
  21. package/lib/crypto/paid.d.ts +1 -1
  22. package/lib/crypto/paid.js +4 -1
  23. package/lib/engine/index.d.ts +23 -4
  24. package/lib/engine/index.js +49 -21
  25. package/lib/engine/records.d.ts +9 -1
  26. package/lib/engine/records.js +32 -6
  27. package/lib/erc8004.d.ts +1 -1
  28. package/lib/erc8004.js +12 -4
  29. package/lib/fangorn.d.ts +12 -2
  30. package/lib/fangorn.js +38 -17
  31. package/lib/feed.d.ts +23 -2
  32. package/lib/feed.js +43 -6
  33. package/lib/index.d.ts +3 -3
  34. package/lib/index.js +4 -4
  35. package/lib/providers/storage/index.js +1 -1
  36. package/lib/providers/storage/pinata.js +14 -6
  37. package/lib/providers/storage/signed-url.js +21 -8
  38. package/lib/providers/storage/types.d.ts +9 -1
  39. package/lib/providers/storage/types.js +54 -1
  40. package/lib/providers/storage/utils.d.ts +3 -1
  41. package/lib/providers/storage/utils.js +3 -3
  42. package/lib/test/mem-registry.d.ts +3 -3
  43. package/lib/test/mem-registry.js +7 -5
  44. package/lib/test/testbed.d.ts +5190 -5190
  45. package/lib/test/testbed.js +1 -1
  46. 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
@@ -18,6 +19,11 @@ const ZERO_BYTES32 = ZERO_HEAD;
18
19
  */
19
20
  const MAX_REPO_NAME_LENGTH = 256;
20
21
  /**
22
+ * Every this many positions, a commit's CAR holds the whole state (see `checkpoint`), so a
23
+ * cold read walks back at most this many CARs (~2 fetches each: under Workers' 1000 subrequests).
24
+ */
25
+ const CHECKPOINT_EVERY = 100;
26
+ /**
21
27
  * The root of the graph, committed to IPFS, as hex
22
28
  */
23
29
  function rootHexFromCid(commitCid) {
@@ -60,9 +66,13 @@ function fileCid(uri) {
60
66
  throw new Error(`storage returned ${JSON.stringify(uri)} for a CAR file; expected its CID`);
61
67
  }
62
68
  }
63
- /** 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
+ */
64
73
  function assertValidRepoName(repo) {
65
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");
66
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()}).`);
67
77
  }
68
78
  const EMPTY_STATE = {
@@ -138,7 +148,13 @@ var FangornEngine = class {
138
148
  const bytes = await this.storage.getFile(car.toString());
139
149
  for (const block of await readCar(bytes, { verify: false })) {
140
150
  const key = block.cid.toString();
141
- 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
+ }
142
158
  }
143
159
  }
144
160
  this.loadedCars.add(linkCid.toString());
@@ -149,13 +165,17 @@ var FangornEngine = class {
149
165
  */
150
166
  async getBlock(cid, hint) {
151
167
  const key = cid.toString();
168
+ let tampered = false;
152
169
  const local = () => {
153
170
  const hit$1 = this.cache.get(key);
154
171
  if (hit$1) return hit$1;
155
172
  const raw = this.unverified.get(key);
156
173
  if (!raw) return null;
157
- assertBlockMatches(cid, raw);
158
174
  this.unverified.delete(key);
175
+ if (!blockMatches(cid, raw)) {
176
+ tampered = true;
177
+ return null;
178
+ }
159
179
  this.cache.set(key, raw);
160
180
  return raw;
161
181
  };
@@ -164,13 +184,12 @@ var FangornEngine = class {
164
184
  let cursor = hint;
165
185
  while (cursor) {
166
186
  const link = await this.chainLink(cursor);
167
- if (!this.loadedCars.has(cursor.toString())) {
168
- await this.loadCar(cursor, link.car);
169
- const found = local();
170
- if (found) return found;
171
- }
187
+ if (!this.loadedCars.has(cursor.toString())) await this.loadCar(cursor, link.car);
188
+ const found = local();
189
+ if (found) return found;
172
190
  cursor = link.parent;
173
191
  }
192
+ if (tampered) throw new Error(`block ${key} does not match its content hash`);
174
193
  throw new Error(`Block payload missing for key: ${key}`);
175
194
  }
176
195
  putLocal(block) {
@@ -218,19 +237,28 @@ var FangornEngine = class {
218
237
  const state = opts.replace ? /* @__PURE__ */ new Map() : new Map(old.state);
219
238
  for (const id of opts.deletes ?? []) state.delete(id);
220
239
  const carBlocks = [];
221
- const recordCids = {};
240
+ const recordCids = /* @__PURE__ */ new Map();
222
241
  for (const r of opts.records) {
223
242
  const id = r.id ?? globalThis.crypto.randomUUID();
224
243
  assertValidRecordId(id);
225
- 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);
226
247
  const block = await encodeBlock({
227
248
  id,
228
249
  type: r.type,
229
250
  payload: r.payload
230
251
  });
231
252
  state.set(id, block.cid);
232
- recordCids[id] = block.cid.toString();
233
- if (!oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
253
+ recordCids.set(id, block.cid.toString());
254
+ if (opts.checkpoint || !oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
255
+ }
256
+ if (opts.checkpoint) {
257
+ const staged = new Set(recordCids.values());
258
+ for (const cid of state.values()) if (!staged.has(cid.toString())) carBlocks.push({
259
+ cid,
260
+ bytes: await this.getBlock(cid, base)
261
+ });
234
262
  }
235
263
  const mst = await buildMst(state);
236
264
  const delta = /* @__PURE__ */ new Map();
@@ -240,7 +268,7 @@ var FangornEngine = class {
240
268
  const fresh = /* @__PURE__ */ new Set();
241
269
  for (const node of [...mst.nodes, ...diff.nodes]) {
242
270
  const key = node.cid.toString();
243
- if (!old.nodeCids.has(key) && !fresh.has(key)) {
271
+ if ((opts.checkpoint || !old.nodeCids.has(key)) && !fresh.has(key)) {
244
272
  fresh.add(key);
245
273
  carBlocks.push(node);
246
274
  }
@@ -262,7 +290,7 @@ var FangornEngine = class {
262
290
  return {
263
291
  commitCid: commitBlock.cid,
264
292
  root: mst.root,
265
- recordCids
293
+ recordCids: Object.fromEntries(recordCids)
266
294
  };
267
295
  }
268
296
  /**
@@ -362,10 +390,10 @@ var FangornEngine = class {
362
390
  * chain or a commit from before diff events, it diffs the two trees (`diffMst`). Either way the
363
391
  * result is the net delta an index builder needs: what to (re)embed, what to evict.
364
392
  */
365
- async repoDiff(oldRootHex, newRootHex) {
393
+ async repoDiff(oldRootHex, newRootHex, { useEventDiff = true } = {}) {
366
394
  const newCommit = newRootHex === ZERO_BYTES32 ? null : this.hexToRootCid(newRootHex);
367
395
  const oldCommit = oldRootHex && oldRootHex !== ZERO_BYTES32 ? this.hexToRootCid(oldRootHex) : null;
368
- const events = oldCommit && newCommit ? await this.eventsSince(oldCommit, newCommit) : null;
396
+ const events = useEventDiff && oldCommit && newCommit ? await this.eventsSince(oldCommit, newCommit) : null;
369
397
  if (oldCommit && newCommit && events) {
370
398
  const oldRoot = (await this.getCommit(oldCommit)).root;
371
399
  const puts$1 = [];
@@ -589,11 +617,11 @@ var FangornEngine = class {
589
617
  }
590
618
  /**
591
619
  * Fetch the current version of one record by id — one MST path from the
592
- * on-chain root, then the record block. Null if the repo has no such id.
620
+ * on-chain root, then the record block. Null if the repo has no such id, or no commits.
593
621
  */
594
622
  async readRecord(publisher, repo, id) {
595
623
  const head = await this.resolveHeadCommit(publisher, repo);
596
- if (!head) throw new Error(`publisher ${publisher} has no on-chain commits in repo ${repo}`);
624
+ if (!head) return null;
597
625
  const get = (cid$1) => this.getBlock(cid$1, head);
598
626
  const cid = await lookupMst((await this.getCommit(head)).root, id, get);
599
627
  return cid ? this.decodeRecord(id, cid, head) : null;
@@ -601,4 +629,4 @@ var FangornEngine = class {
601
629
  };
602
630
 
603
631
  //#endregion
604
- export { FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, cidFromDigest, commitHead, commitUpdate, fileCid, rootHexFromCid };
632
+ export { CHECKPOINT_EVERY, FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, cidFromDigest, commitHead, commitUpdate, fileCid, rootHexFromCid };
@@ -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,7 +123,7 @@ async function setAgentFile(c, agentId, file) {
116
123
  chain: c.chain,
117
124
  account: c.walletClient.account ?? null
118
125
  });
119
- await c.publicClient.waitForTransactionReceipt({ hash });
126
+ await confirmTx(c.publicClient, hash, "setAgentURI");
120
127
  return hash;
121
128
  }
122
129
  /** Mint an agent with no URI yet, and return its id. */
@@ -130,10 +137,11 @@ async function mintAgent(c) {
130
137
  chain: c.chain,
131
138
  account: c.walletClient.account ?? null
132
139
  });
140
+ const { receipt } = await confirmTx(c.publicClient, hash, "register");
133
141
  const minted = parseEventLogs({
134
142
  abi: ABI,
135
143
  eventName: "Registered",
136
- logs: (await c.publicClient.waitForTransactionReceipt({ hash })).logs
144
+ logs: receipt.logs
137
145
  }).find((l) => l.address.toLowerCase() === address.toLowerCase());
138
146
  if (!minted) throw new Error(`register ${hash} confirmed with no Registered event`);
139
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
@@ -91,7 +99,7 @@ declare class Fangorn {
91
99
  txHash: Hash;
92
100
  onChainTip: CID;
93
101
  }>;
94
- /** Stage records into one commit on top of `base`. */
102
+ /** Stage records into one commit on top of `base`, a checkpoint every CHECKPOINT_EVERY positions. */
95
103
  private createCommit;
96
104
  /**
97
105
  * Allocates a repo in the publisher's root map.
@@ -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
- import { FangornEngine, assertValidRepoName, commitUpdate, rootHexFromCid } from "./engine/index.js";
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;
@@ -109,11 +109,17 @@ var Fangorn = class Fangorn {
109
109
  });
110
110
  return this.engine.pushCommit(publisher, repo, commitCid);
111
111
  }
112
- /** Stage records into one commit on top of `base`. */
113
- createCommit(opts) {
112
+ /** Stage records into one commit on top of `base`, a checkpoint every CHECKPOINT_EVERY positions. */
113
+ async createCommit(opts) {
114
+ const { publisher, ...rest } = opts;
115
+ const { pos } = await this.ctx.registry.headAt({
116
+ publisher: publisher ?? this.getAddress(),
117
+ repo: opts.repo
118
+ });
114
119
  return this.engine.createCommit({
115
- ...opts,
116
- records: opts.records.map((r) => ({
120
+ ...rest,
121
+ checkpoint: (pos + 1) % CHECKPOINT_EVERY === 0,
122
+ records: rest.records.map((r) => ({
117
123
  id: r.id,
118
124
  type: r.type,
119
125
  payload: r.payload && typeof r.payload === "object" && !Array.isArray(r.payload) ? r.payload : { value: r.payload }
@@ -246,7 +252,8 @@ var Fangorn = class Fangorn {
246
252
  base: oldRoot === ZERO_BYTES32 ? null : CID.parse(this.engine.commitCidFromRootHex(oldRoot)),
247
253
  records: opts.records ?? [],
248
254
  deletes: opts.deletes,
249
- replace: opts.replace
255
+ replace: opts.replace,
256
+ publisher: opts.owner
250
257
  });
251
258
  const newRoot = rootHexFromCid(commitCid);
252
259
  return {
@@ -407,10 +414,12 @@ var Fangorn = class Fangorn {
407
414
  * anywhere more than one consumer wants the same stream.
408
415
  */
409
416
  feed(opts = {}) {
410
- this._feed ??= new CommitFeed((signal) => this.subscribeAll({
417
+ this._feed ??= new CommitFeed((signal, fromBlock, onSkip) => this.subscribeAll({
411
418
  ...opts,
412
- signal
413
- }));
419
+ signal,
420
+ fromBlock,
421
+ onSkip
422
+ }), void 0, () => this.ctx.registry.clock());
414
423
  return this._feed;
415
424
  }
416
425
  /** Walk commit history from `head` (newest first). */
@@ -528,7 +537,7 @@ var Fangorn = class Fangorn {
528
537
  if (opts.fromBlock !== void 0) for (const log of await registry.log(filter, opts.fromBlock)) {
529
538
  if (seen.has(log.id)) continue;
530
539
  seen.add(log.id);
531
- const change = await this.toRepoChange(log, lastHead);
540
+ const change = await this.readChange(log, lastHead, opts.onSkip);
532
541
  if (change) yield change;
533
542
  }
534
543
  while (!subState.stopped) {
@@ -543,7 +552,7 @@ var Fangorn = class Fangorn {
543
552
  if (!log) continue;
544
553
  if (seen.has(log.id)) continue;
545
554
  seen.add(log.id);
546
- const change = await this.toRepoChange(log, lastHead);
555
+ const change = await this.readChange(log, lastHead, opts.onSkip);
547
556
  if (change) yield change;
548
557
  }
549
558
  } finally {
@@ -551,6 +560,17 @@ var Fangorn = class Fangorn {
551
560
  opts.signal?.removeEventListener("abort", onAbort);
552
561
  }
553
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
+ }
554
574
  /**
555
575
  * Resolve a log entry into a repo change, or null if the repo's records did
556
576
  * not change.
@@ -565,12 +585,13 @@ var Fangorn = class Fangorn {
565
585
  * dropped entry changed.
566
586
  */
567
587
  async toRepoChange(log, lastHead) {
568
- const declared = await this.engine.repoOf(log.head);
569
- 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}")`);
570
588
  const key = `${log.publisher.toLowerCase()}/${log.repo}`;
571
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 });
572
594
  lastHead.set(key, log.head);
573
- const diff = await this.engine.repoDiff(oldRoot === ZERO_BYTES32 ? null : oldRoot, log.head);
574
595
  if (!diff.puts.length && !diff.deletes.length) return null;
575
596
  return {
576
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 };