@fangorn-network/sdk 0.1.0 → 0.1.2

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 (72) hide show
  1. package/README.md +1 -1
  2. package/lib/cli/cli.js +126 -325
  3. package/lib/cli/index.d.ts +2 -3
  4. package/lib/cli/index.js +10 -15
  5. package/lib/cli/sell.d.ts +28 -0
  6. package/lib/cli/sell.js +95 -0
  7. package/lib/cli/stage.d.ts +19 -0
  8. package/lib/cli/stage.js +94 -0
  9. package/lib/config.d.ts +71 -81
  10. package/lib/config.js +22 -38
  11. package/lib/contracts/data-registry/abi.d.ts +195 -19
  12. package/lib/contracts/data-registry/abi.js +409 -206
  13. package/lib/contracts/data-registry/index.d.ts +126 -2
  14. package/lib/contracts/data-registry/index.js +174 -1
  15. package/lib/contracts/index.d.ts +4 -7
  16. package/lib/contracts/index.js +4 -7
  17. package/lib/contracts/logs.d.ts +1 -1
  18. package/lib/contracts/logs.js +1 -1
  19. package/lib/contracts/{membership-registry → settlement-registry}/abi.d.ts +301 -636
  20. package/lib/contracts/settlement-registry/abi.js +962 -0
  21. package/lib/contracts/settlement-registry/index.d.ts +143 -0
  22. package/lib/contracts/settlement-registry/index.js +213 -0
  23. package/lib/crypto/aes.d.ts +2 -2
  24. package/lib/crypto/aes.js +4 -4
  25. package/lib/crypto/encryption.d.ts +8 -109
  26. package/lib/crypto/encryption.js +16 -114
  27. package/lib/crypto/paid.d.ts +104 -0
  28. package/lib/crypto/paid.js +147 -0
  29. package/lib/engine/car.d.ts +5 -1
  30. package/lib/engine/car.js +2 -2
  31. package/lib/engine/index.d.ts +33 -14
  32. package/lib/engine/index.js +98 -41
  33. package/lib/engine/records.d.ts +19 -8
  34. package/lib/engine/records.js +81 -7
  35. package/lib/engine/test-helpers.d.ts +2 -3
  36. package/lib/engine/test-helpers.js +7 -5
  37. package/lib/erc8004.js +6 -6
  38. package/lib/fangorn.d.ts +65 -86
  39. package/lib/fangorn.js +115 -153
  40. package/lib/feed.d.ts +7 -8
  41. package/lib/feed.js +7 -8
  42. package/lib/index.d.ts +10 -13
  43. package/lib/index.js +10 -13
  44. package/lib/providers/storage/signed-url.d.ts +2 -10
  45. package/lib/providers/storage/signed-url.js +5 -15
  46. package/lib/providers/storage/types.d.ts +1 -1
  47. package/lib/providers/storage/utils.js +5 -3
  48. package/lib/test/key-server.d.ts +12 -0
  49. package/lib/test/key-server.js +30 -0
  50. package/lib/test/mem-registry.d.ts +14 -19
  51. package/lib/test/mem-registry.js +44 -37
  52. package/lib/test/sdk-suite.d.ts +1 -4
  53. package/lib/test/sdk-suite.js +16 -87
  54. package/lib/test/testbed.d.ts +12 -22
  55. package/lib/test/testbed.js +29 -56
  56. package/lib/types/index.d.ts +6 -11
  57. package/package.json +1 -1
  58. package/lib/contracts/app-registry/abi.d.ts +0 -1265
  59. package/lib/contracts/app-registry/abi.js +0 -1454
  60. package/lib/contracts/app-registry/index.d.ts +0 -161
  61. package/lib/contracts/app-registry/index.js +0 -274
  62. package/lib/contracts/membership-registry/abi.js +0 -1333
  63. package/lib/contracts/membership-registry/index.d.ts +0 -79
  64. package/lib/contracts/membership-registry/index.js +0 -104
  65. package/lib/contracts/types.d.ts +0 -10
  66. package/lib/contracts/types.js +0 -12
  67. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +0 -1
  68. package/lib/harness/examples/hackmd/build-markdown-graph.js +0 -17
  69. package/lib/harness/index.d.ts +0 -58
  70. package/lib/harness/index.js +0 -73
  71. package/lib/registry.d.ts +0 -118
  72. package/lib/registry.js +0 -184
@@ -1,8 +1,10 @@
1
- import { assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, encodeBlock, lookupMst, readMst } from "./records.js";
1
+ import { assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, lookupMst, readMst } from "./records.js";
2
2
  import { packCar, readCar } from "./car.js";
3
- import { ZERO_HEAD } from "../registry.js";
3
+ import { ZERO_HEAD } from "../contracts/data-registry/index.js";
4
+ import "../contracts/index.js";
5
+ import { bytesToHex, hexToBytes } from "viem";
4
6
  import { CID } from "multiformats/cid";
5
- import { randomUUID } from "crypto";
7
+ import * as dagCbor from "@ipld/dag-cbor";
6
8
  import { sha256 } from "multiformats/hashes/sha2";
7
9
  import * as Digest from "multiformats/hashes/digest";
8
10
 
@@ -18,7 +20,36 @@ const MAX_REPO_NAME_LENGTH = 256;
18
20
  * The root of the graph, committed to IPFS, as hex
19
21
  */
20
22
  function rootHexFromCid(commitCid) {
21
- return `0x${Buffer.from(commitCid.multihash.digest).toString("hex")}`;
23
+ return bytesToHex(commitCid.multihash.digest);
24
+ }
25
+ /** The update that settles `commit`. */
26
+ function commitUpdate(commit) {
27
+ return {
28
+ repo: commit.repo,
29
+ epoch: commit.epoch,
30
+ parent: commit.parent ? rootHexFromCid(commit.parent) : ZERO_HEAD,
31
+ root: rootHexFromCid(commit.root),
32
+ car: bytesToHex(commit.car.bytes)
33
+ };
34
+ }
35
+ /** The head the registry computes for `u`. */
36
+ async function commitHead(u) {
37
+ const link = (digest) => CID.createV1(dagCbor.code, Digest.create(sha256.code, hexToBytes(digest)));
38
+ return rootHexFromCid((await encodeBlock({
39
+ epoch: u.epoch,
40
+ parent: u.parent === ZERO_HEAD ? null : link(u.parent),
41
+ root: link(u.root),
42
+ repo: u.repo,
43
+ car: CID.decode(hexToBytes(u.car))
44
+ })).cid);
45
+ }
46
+ /** The CID a storage backend returned for a file, with or without an `ipfs://` prefix. */
47
+ function fileCid(uri) {
48
+ try {
49
+ return CID.parse(uri.replace(/^ipfs:\/\//, ""));
50
+ } catch {
51
+ throw new Error(`storage returned ${JSON.stringify(uri)} for a CAR file; expected its CID`);
52
+ }
22
53
  }
23
54
  /** Repos must be non-empty strings whose length does not exceed MAX_REPO_NAME_LENGTH */
24
55
  function assertValidRepoName(repo) {
@@ -38,6 +69,12 @@ var FangornEngine = class {
38
69
  cache = /* @__PURE__ */ new Map();
39
70
  /** Commits whose CAR has already been loaded into the cache. */
40
71
  loadedCars = /* @__PURE__ */ new Set();
72
+ /**
73
+ * Blocks from a loaded CAR, not yet hash-checked. A CAR holds every block its commit introduced
74
+ * (the first commit of a 50k-record repo: all of them), and a diff reads a handful: each block is
75
+ * checked when `getBlock` first hands it out, then moves to `cache`.
76
+ */
77
+ unverified = /* @__PURE__ */ new Map();
41
78
  constructor(storage, registry) {
42
79
  this.storage = storage;
43
80
  this.registry = registry;
@@ -49,8 +86,7 @@ var FangornEngine = class {
49
86
  * with sha256.digest() would produce an unrelated CID pointing at nothing.
50
87
  */
51
88
  hexToRootCid(hex) {
52
- const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
53
- const rawDigestBytes = Uint8Array.from(Buffer.from(cleanHex, "hex"));
89
+ const rawDigestBytes = hexToBytes(`0x${hex.startsWith("0x") ? hex.slice(2) : hex}`);
54
90
  const multihash = Digest.create(sha256.code, rawDigestBytes);
55
91
  return CID.createV1(113, multihash);
56
92
  }
@@ -70,14 +106,16 @@ var FangornEngine = class {
70
106
  parent: decoded.parent ? CID.parse(String(decoded.parent)) : null,
71
107
  root: CID.parse(String(decoded.root)),
72
108
  repo: decoded.repo,
73
- message: decoded.message ?? "",
74
- car: decoded.car ?? ""
109
+ car: CID.parse(String(decoded.car))
75
110
  };
76
111
  }
77
112
  /** Pull every block of `commit`'s CAR into the local cache. */
78
113
  async loadCar(commitCid, commit) {
79
- const bytes = await this.storage.getFile(commit.car);
80
- for (const block of await readCar(bytes)) this.cache.set(block.cid.toString(), block.bytes);
114
+ const bytes = await this.storage.getFile(commit.car.toString());
115
+ for (const block of await readCar(bytes, { verify: false })) {
116
+ const key = block.cid.toString();
117
+ if (!this.cache.has(key)) this.unverified.set(key, block.bytes);
118
+ }
81
119
  this.loadedCars.add(commitCid.toString());
82
120
  }
83
121
  /**
@@ -86,14 +124,24 @@ var FangornEngine = class {
86
124
  */
87
125
  async getBlock(cid, hint) {
88
126
  const key = cid.toString();
89
- const hit = this.cache.get(key);
127
+ const local = () => {
128
+ const hit$1 = this.cache.get(key);
129
+ if (hit$1) return hit$1;
130
+ const raw = this.unverified.get(key);
131
+ if (!raw) return null;
132
+ assertBlockMatches(cid, raw);
133
+ this.unverified.delete(key);
134
+ this.cache.set(key, raw);
135
+ return raw;
136
+ };
137
+ const hit = local();
90
138
  if (hit) return hit;
91
139
  let cursor = hint;
92
140
  while (cursor) {
93
141
  const commit = await this.getCommit(cursor);
94
142
  if (!this.loadedCars.has(cursor.toString())) {
95
143
  await this.loadCar(cursor, commit);
96
- const found = this.cache.get(key);
144
+ const found = local();
97
145
  if (found) return found;
98
146
  }
99
147
  cursor = commit.parent;
@@ -118,7 +166,7 @@ var FangornEngine = class {
118
166
  }
119
167
  /**
120
168
  * Which repo a commit belongs to. Events carry only `keccak256(name)`, so
121
- * this is how an app-wide subscriber recovers the name.
169
+ * this is how a subscriber to every repo recovers the name.
122
170
  */
123
171
  async repoOf(rootHex) {
124
172
  return (await this.getCommit(this.hexToRootCid(rootHex))).repo;
@@ -147,7 +195,7 @@ var FangornEngine = class {
147
195
  const carBlocks = [];
148
196
  const recordCids = {};
149
197
  for (const r of opts.records) {
150
- const id = r.id ?? randomUUID();
198
+ const id = r.id ?? globalThis.crypto.randomUUID();
151
199
  assertValidRecordId(id);
152
200
  if (id in recordCids) throw new Error(`record id ${id} staged twice`);
153
201
  const block = await encodeBlock({
@@ -163,14 +211,13 @@ var FangornEngine = class {
163
211
  for (const node of mst.nodes) if (!old.nodeCids.has(node.cid.toString())) carBlocks.push(node);
164
212
  for (const block of carBlocks) this.putLocal(block);
165
213
  const carBytes = await packCar(mst.root, carBlocks);
166
- const carUri = await this.storage.putFile(carBytes, `${mst.root.toString()}.car`);
214
+ const car = fileCid(await this.storage.putFile(carBytes, `${mst.root.toString()}.car`));
167
215
  const commitBlock = await encodeBlock({
168
216
  epoch: await this.registry.epoch(),
169
217
  parent: base,
170
218
  root: mst.root,
171
219
  repo,
172
- message: opts.message,
173
- car: carUri
220
+ car
174
221
  });
175
222
  await this.storage.putBlock(commitBlock);
176
223
  this.putLocal(commitBlock);
@@ -185,26 +232,38 @@ var FangornEngine = class {
185
232
  * Settle a local commit as the on-chain head of one repo — the `update` of
186
233
  * WHITEPAPER_1 §3.2. The commit and its CAR are already durable in storage
187
234
  * (createCommit uploads them), so this is just the compare-and-swap.
188
- *
189
- * The commit's parent must BE the current head, not merely an ancestor of
190
- * it: then the parent chain and the registry's log are one history
191
- * (Theorem 3). Today's contract only checks the old root, so the parent is
192
- * checked here.
193
235
  */
194
236
  async pushCommit(publisher, repo, commitCid) {
195
- const head = await this.registry.head({
196
- publisher,
197
- repo
198
- });
199
- const commit = await this.getCommit(commitCid);
200
- const parentHex = commit.parent ? rootHexFromCid(commit.parent) : ZERO_BYTES32;
201
- if (commit.repo !== repo) throw new Error(`commit ${commitCid.toString()} is a commit of ${commit.repo}, not ${repo}`);
202
- if (parentHex !== head) throw new Error("stale parent: this commit's parent is not the on-chain head — rebuild it onto the current head.");
237
+ const update = await this.settleable(publisher, repo, commitCid);
203
238
  return {
204
- txHash: await this.registry.update(repo, head, rootHexFromCid(commitCid)),
239
+ txHash: await this.registry.update(update),
205
240
  onChainTip: commitCid
206
241
  };
207
242
  }
243
+ /** `pushCommit`, signed by this registry's wallet for anyone to submit with `relayCommit`. */
244
+ async signCommit(publisher, repo, commitCid) {
245
+ const update = await this.settleable(publisher, repo, commitCid);
246
+ return {
247
+ publisher,
248
+ update,
249
+ signature: await this.registry.signUpdate(update)
250
+ };
251
+ }
252
+ relayCommit(s) {
253
+ return this.registry.updateBySig(s.publisher, s.update, s.signature);
254
+ }
255
+ /** The update for `commitCid`, once it is one the registry will take as the next head. */
256
+ async settleable(publisher, repo, commitCid) {
257
+ const commit = await this.getCommit(commitCid);
258
+ if (commit.repo !== repo) throw new Error(`commit ${commitCid.toString()} is a commit of ${commit.repo}, not ${repo}`);
259
+ const update = commitUpdate(commit);
260
+ if (update.parent !== await this.registry.head({
261
+ publisher,
262
+ repo
263
+ })) throw new Error("stale parent: this commit's parent is not the on-chain head — rebuild it onto the current head.");
264
+ if (await commitHead(update) !== rootHexFromCid(commitCid)) throw new Error(`commit ${commitCid.toString()} is not in the current commit format — rebuild it`);
265
+ return update;
266
+ }
208
267
  /** Walk the parent chain from `tip` toward the root, newest first. */
209
268
  async *walkParents(tip, max) {
210
269
  let cursor = tip;
@@ -244,21 +303,20 @@ var FangornEngine = class {
244
303
  * Diffing root-to-root (rather than walking commits) is deliberately robust:
245
304
  * it yields the correct net delta even across a force-push / non-fast-forward
246
305
  * reorg — exactly what an index builder needs (what to (re)embed, what to evict).
247
- * ponytail: reads both whole trees; skip subtrees with equal CIDs if diffs
248
- * of large repos get slow.
306
+ * Reads only the nodes on changed paths (`diffMst`): 10 new records in a
307
+ * 50k-record repo cost ~10 × depth nodes, not two 50k-key walks.
249
308
  */
250
309
  async repoDiff(oldRootHex, newRootHex) {
251
310
  const newCommit = newRootHex === ZERO_BYTES32 ? null : this.hexToRootCid(newRootHex);
252
311
  const oldCommit = oldRootHex && oldRootHex !== ZERO_BYTES32 ? this.hexToRootCid(oldRootHex) : null;
253
- const after = newCommit ? (await this.stateAt(newCommit)).state : /* @__PURE__ */ new Map();
254
- const before = oldCommit ? (await this.stateAt(oldCommit)).state : /* @__PURE__ */ new Map();
312
+ const root = async (c) => c ? (await this.getCommit(c)).root : null;
313
+ const diff = await diffMst(await root(oldCommit), await root(newCommit), (cid) => this.getBlock(cid, oldCommit), (cid) => this.getBlock(cid, newCommit));
255
314
  const puts = [];
256
- if (newCommit) {
257
- for (const [id, cid] of after) if (before.get(id)?.toString() !== cid.toString()) puts.push(await this.decodeRecord(id, cid, newCommit));
258
- }
315
+ if (newCommit) for (const [id, cid] of diff.puts) puts.push(await this.decodeRecord(id, cid, newCommit));
259
316
  return {
260
317
  puts,
261
- deletes: [...before.keys()].filter((id) => !after.has(id))
318
+ deletes: diff.deletes,
319
+ superseded: [...diff.before.values()].map(String)
262
320
  };
263
321
  }
264
322
  /** Diff a commit against its parent. */
@@ -277,7 +335,6 @@ var FangornEngine = class {
277
335
  }
278
336
  for (const id of par.keys()) if (!child.has(id)) removed.push(`${ns}/${id}`);
279
337
  return {
280
- message: commit.message,
281
338
  parent: commit.parent?.toString() ?? null,
282
339
  epoch: commit.epoch,
283
340
  repo: ns,
@@ -317,4 +374,4 @@ var FangornEngine = class {
317
374
  };
318
375
 
319
376
  //#endregion
320
- export { FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, rootHexFromCid };
377
+ export { FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, commitHead, commitUpdate, fileCid, rootHexFromCid };
@@ -37,12 +37,10 @@ type Ref = {
37
37
  * Commit block: γ = (e, parent, root) of WHITEPAPER_1 §3.1, whose name is the
38
38
  * on-chain head. `root` is the repo's MST root.
39
39
  *
40
- * Three more fields, until the registry computes heads from (e, parent, root)
41
- * itself (docs/REGISTRY_SPEC.md):
40
+ * Two more fields:
42
41
  * • `repo`: the repo's name, which events carry only as keccak256(name);
43
- * • `message`: a commit note;
44
- * • `car`: the opaque storage URI of the CAR file holding every block this
45
- * commit introduced. The commit block itself is stored OUTSIDE that CAR
42
+ * • `car`: the CID of the CAR file holding every block this commit
43
+ * introduced. The commit block itself is stored OUTSIDE that CAR
46
44
  * (individually addressable), so a reader goes digest → commit → CAR with
47
45
  * no index lookups.
48
46
  */
@@ -51,8 +49,7 @@ interface CommitBlock {
51
49
  parent: CID | null;
52
50
  root: CID;
53
51
  repo: string;
54
- message: string;
55
- car: string;
52
+ car: CID;
56
53
  }
57
54
  /** Upper bound on a record id's length. */
58
55
  declare const MAX_RECORD_ID_LENGTH = 256;
@@ -99,6 +96,20 @@ declare function readMst(root: CID, getBlock: (cid: CID) => Promise<Uint8Array>)
99
96
  state: Map<string, CID>;
100
97
  nodeCids: Set<string>;
101
98
  }>;
99
+ /**
100
+ * What changed from one tree to another: `puts` (new keys, and keys with a new value) and `deletes`
101
+ * (keys gone), each with its old value in `before`. Both trees are read as in-order streams of entries
102
+ * and unopened subtrees; a subtree with the same CID at the head of both streams holds the same keys
103
+ * and values, so it is dropped unread. Only nodes on changed paths are fetched: ~changes × depth,
104
+ * not the size of either tree.
105
+ * ponytail: unlike readMst, does not prove either tree canonical (that needs every key). Blocks are
106
+ * still hash-checked by `getBlock`; a publisher's malformed tree can only misreport its own records.
107
+ */
108
+ declare function diffMst(oldRoot: CID | null, newRoot: CID | null, getOld: (cid: CID) => Promise<Uint8Array>, getNew: (cid: CID) => Promise<Uint8Array>): Promise<{
109
+ puts: Map<string, CID>;
110
+ deletes: string[];
111
+ before: Map<string, CID>;
112
+ }>;
102
113
  /**
103
114
  * The record CID stored under `key`, or null if absent — one node per level.
104
115
  * ponytail: trusts node ordering on the path, so a malformed tree can hide a
@@ -107,4 +118,4 @@ declare function readMst(root: CID, getBlock: (cid: CID) => Promise<Uint8Array>)
107
118
  */
108
119
  declare function lookupMst(root: CID, key: string, getBlock: (cid: CID) => Promise<Uint8Array>): Promise<CID | null>;
109
120
  //#endregion
110
- export { Block, CommitBlock, MAX_RECORD_ID_LENGTH, MST_BITS, MstEntry, MstNode, RecordBlock, Ref, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, encodeBlock, keyLevel, lookupMst, readMst };
121
+ export { Block, CommitBlock, MAX_RECORD_ID_LENGTH, MST_BITS, MstEntry, MstNode, RecordBlock, Ref, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };
@@ -1,13 +1,14 @@
1
1
  import { CID } from "multiformats/cid";
2
2
  import * as dagCbor from "@ipld/dag-cbor";
3
- import { createHash } from "crypto";
4
- import { sha256 } from "multiformats/hashes/sha2";
3
+ import { sha256 } from "@noble/hashes/sha2.js";
4
+ import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
5
+ import { sha256 as sha256$1 } from "multiformats/hashes/sha2";
5
6
 
6
7
  //#region src/engine/records.ts
7
8
  /** Encode any value as canonical dag-cbor and derive its CIDv1 (sha256). */
8
9
  async function encodeBlock(obj) {
9
10
  const bytes = dagCbor.encode(obj);
10
- const hash = await sha256.digest(bytes);
11
+ const hash = await sha256$1.digest(bytes);
11
12
  return {
12
13
  cid: CID.createV1(dagCbor.code, hash),
13
14
  bytes
@@ -22,8 +23,7 @@ function decodeBlock(bytes) {
22
23
  }
23
24
  /** Throw unless `bytes` hash to `cid`. Hosts are untrusted; every fetched block goes through this. */
24
25
  function assertBlockMatches(cid, bytes) {
25
- const digest = createHash("sha256").update(bytes).digest();
26
- if (!Buffer.from(cid.multihash.digest).equals(digest)) throw new Error(`block ${cid.toString()} does not match its content hash`);
26
+ if (bytesToHex(cid.multihash.digest) !== bytesToHex(sha256(bytes))) throw new Error(`block ${cid.toString()} does not match its content hash`);
27
27
  }
28
28
  /** Upper bound on a record id's length. */
29
29
  const MAX_RECORD_ID_LENGTH = 256;
@@ -41,7 +41,7 @@ const MST_BITS = 4;
41
41
  const MAX_DEPTH = 256 / MST_BITS + 1;
42
42
  /** level(k) = ⌊leading zero bits of sha256(k) / b⌋ */
43
43
  function keyLevel(key) {
44
- const digest = createHash("sha256").update(key).digest();
44
+ const digest = sha256(utf8ToBytes(key));
45
45
  let zeros = 0;
46
46
  for (const byte of digest) {
47
47
  if (byte !== 0) {
@@ -141,6 +141,80 @@ async function readMst(root, getBlock) {
141
141
  };
142
142
  }
143
143
  /**
144
+ * What changed from one tree to another: `puts` (new keys, and keys with a new value) and `deletes`
145
+ * (keys gone), each with its old value in `before`. Both trees are read as in-order streams of entries
146
+ * and unopened subtrees; a subtree with the same CID at the head of both streams holds the same keys
147
+ * and values, so it is dropped unread. Only nodes on changed paths are fetched: ~changes × depth,
148
+ * not the size of either tree.
149
+ * ponytail: unlike readMst, does not prove either tree canonical (that needs every key). Blocks are
150
+ * still hash-checked by `getBlock`; a publisher's malformed tree can only misreport its own records.
151
+ */
152
+ async function diffMst(oldRoot, newRoot, getOld, getNew) {
153
+ const a = oldRoot ? [{
154
+ sub: oldRoot,
155
+ level: Infinity
156
+ }] : [];
157
+ const b = newRoot ? [{
158
+ sub: newRoot,
159
+ level: Infinity
160
+ }] : [];
161
+ const open = async (s, get) => {
162
+ const { sub } = s.pop();
163
+ const node = decodeBlock(await get(sub));
164
+ const items = node.left ? [{
165
+ sub: node.left,
166
+ level: node.level - 1
167
+ }] : [];
168
+ for (const e of node.entries) {
169
+ items.push({
170
+ key: e.key,
171
+ value: e.value
172
+ });
173
+ if (e.right) items.push({
174
+ sub: e.right,
175
+ level: node.level - 1
176
+ });
177
+ }
178
+ s.push(...items.reverse());
179
+ };
180
+ const puts = /* @__PURE__ */ new Map(), before = /* @__PURE__ */ new Map(), deletes = [];
181
+ for (let steps = 0; a.length || b.length; steps++) {
182
+ if (steps > 1e8) throw new Error("MST diff did not terminate");
183
+ const x = a.at(-1), y = b.at(-1);
184
+ if (x && y && "sub" in x && "sub" in y) if (x.sub.equals(y.sub)) {
185
+ a.pop();
186
+ b.pop();
187
+ } else if (x.level > y.level) await open(a, getOld);
188
+ else if (y.level > x.level) await open(b, getNew);
189
+ else {
190
+ await open(a, getOld);
191
+ await open(b, getNew);
192
+ }
193
+ else if (x && "sub" in x) await open(a, getOld);
194
+ else if (y && "sub" in y) await open(b, getNew);
195
+ else if (x && (!y || x.key < y.key)) {
196
+ a.pop();
197
+ deletes.push(x.key);
198
+ before.set(x.key, x.value);
199
+ } else if (y && (!x || y.key < x.key)) {
200
+ b.pop();
201
+ puts.set(y.key, y.value);
202
+ } else if (x && y) {
203
+ a.pop();
204
+ b.pop();
205
+ if (!x.value.equals(y.value)) {
206
+ puts.set(y.key, y.value);
207
+ before.set(x.key, x.value);
208
+ }
209
+ }
210
+ }
211
+ return {
212
+ puts,
213
+ deletes,
214
+ before
215
+ };
216
+ }
217
+ /**
144
218
  * The record CID stored under `key`, or null if absent — one node per level.
145
219
  * ponytail: trusts node ordering on the path, so a malformed tree can hide a
146
220
  * record (never forge one: the caller checks the record's id). Run `readMst`
@@ -162,4 +236,4 @@ async function lookupMst(root, key, getBlock) {
162
236
  }
163
237
 
164
238
  //#endregion
165
- export { MAX_RECORD_ID_LENGTH, MST_BITS, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, encodeBlock, keyLevel, lookupMst, readMst };
239
+ export { MAX_RECORD_ID_LENGTH, MST_BITS, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };
@@ -20,7 +20,7 @@ declare class MemStorage implements MetadataStorage {
20
20
  /** Remote fetches performed (getRawBlock + getFile). */
21
21
  reads: number;
22
22
  putBlock(block: RawBlock): Promise<void>;
23
- putFile(bytes: Uint8Array, name: string): Promise<string>;
23
+ putFile(bytes: Uint8Array): Promise<string>;
24
24
  getFile(uri: string): Promise<Uint8Array>;
25
25
  getRawBlock(uri: string): Promise<Uint8Array>;
26
26
  put(_data: unknown, _meta?: StorageMeta): Promise<string>;
@@ -33,7 +33,6 @@ declare class MemStorage implements MetadataStorage {
33
33
  }
34
34
  /** The paper's registry in memory, signing as PUBLISHER. */
35
35
  declare const PUBLISHER: Hex;
36
- declare const APP: Hex;
37
36
  declare const newRegistry: () => MemRegistry;
38
37
  //#endregion
39
- export { APP, MemStorage, PUBLISHER, ZERO_BYTES32, newRegistry, rootHex };
38
+ export { MemStorage, PUBLISHER, ZERO_BYTES32, newRegistry, rootHex };
@@ -1,4 +1,7 @@
1
1
  import { MemRegistry } from "../test/mem-registry.js";
2
+ import { CID } from "multiformats/cid";
3
+ import { sha256 } from "multiformats/hashes/sha2";
4
+ import * as raw from "multiformats/codecs/raw";
2
5
 
3
6
  //#region src/engine/test-helpers.ts
4
7
  const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
@@ -21,11 +24,11 @@ var MemStorage = class {
21
24
  this.blocks.set(block.cid.toString(), block.bytes);
22
25
  return Promise.resolve();
23
26
  }
24
- putFile(bytes, name) {
27
+ async putFile(bytes) {
25
28
  this.writes++;
26
- const uri = `mem://${this.files.size.toString()}/${name}`;
29
+ const uri = CID.createV1(raw.code, await sha256.digest(bytes)).toString();
27
30
  this.files.set(uri, bytes);
28
- return Promise.resolve(uri);
31
+ return uri;
29
32
  }
30
33
  getFile(uri) {
31
34
  const bytes = this.files.get(uri);
@@ -54,8 +57,7 @@ var MemStorage = class {
54
57
  };
55
58
  /** The paper's registry in memory, signing as PUBLISHER. */
56
59
  const PUBLISHER = "0x0000000000000000000000000000000000000001";
57
- const APP = `0x${"a".repeat(64)}`;
58
60
  const newRegistry = () => new MemRegistry(PUBLISHER);
59
61
 
60
62
  //#endregion
61
- export { APP, MemStorage, PUBLISHER, ZERO_BYTES32, newRegistry, rootHex };
63
+ export { MemStorage, PUBLISHER, ZERO_BYTES32, newRegistry, rootHex };
package/lib/erc8004.js CHANGED
@@ -14,12 +14,12 @@ const ABI = parseAbi([
14
14
  /**
15
15
  * Get the agent card URL based on the access worker if defined, else return the carUrl
16
16
  * Both params are optional, but at least one must be defined.
17
- *
17
+ *
18
18
  * Agent cards must live at accessWorker/.well-known/agent-card.json
19
- *
19
+ *
20
20
  * @param cardUrl The cardUrl (passthrough when defined)
21
- * @param accessWorker The (optional) access worker url
22
- * @returns
21
+ * @param accessWorker The (optional) access worker url
22
+ * @returns
23
23
  */
24
24
  function agentCardUrl(cardUrl, accessWorker) {
25
25
  if (cardUrl) return cardUrl;
@@ -51,8 +51,8 @@ async function mcpTools(endpoint) {
51
51
  }
52
52
  }
53
53
  /**
54
- * Build a registration file
55
- * Since it desfines its own agent id,
54
+ * Build a registration file
55
+ * Since it desfines its own agent id,
56
56
  * first registration mints without an agent URI and must be set retroactively.
57
57
  */
58
58
  function registrationFile(opts) {