@fangorn-network/sdk 2026.10.28 → 2026.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +37 -653
  2. package/lib/cli/cli.js +46 -357
  3. package/lib/cli/index.d.ts +1 -4
  4. package/lib/cli/index.js +2 -20
  5. package/lib/cli/sell.d.ts +28 -0
  6. package/lib/cli/sell.js +95 -0
  7. package/lib/config.d.ts +163 -226
  8. package/lib/config.js +8 -35
  9. package/lib/contracts/data-registry/abi.d.ts +206 -6
  10. package/lib/contracts/data-registry/abi.js +415 -186
  11. package/lib/contracts/data-registry/index.d.ts +126 -2
  12. package/lib/contracts/data-registry/index.js +174 -1
  13. package/lib/contracts/index.d.ts +4 -7
  14. package/lib/contracts/index.js +4 -7
  15. package/lib/contracts/logs.d.ts +1 -1
  16. package/lib/contracts/logs.js +1 -1
  17. package/lib/contracts/{membership-registry → settlement-registry}/abi.d.ts +288 -637
  18. package/lib/contracts/settlement-registry/abi.js +947 -0
  19. package/lib/contracts/settlement-registry/index.d.ts +141 -0
  20. package/lib/contracts/settlement-registry/index.js +209 -0
  21. package/lib/crypto/aes.d.ts +2 -2
  22. package/lib/crypto/aes.js +4 -4
  23. package/lib/crypto/encryption.d.ts +8 -109
  24. package/lib/crypto/encryption.js +16 -114
  25. package/lib/crypto/paid.d.ts +104 -0
  26. package/lib/crypto/paid.js +147 -0
  27. package/lib/engine/index.d.ts +23 -12
  28. package/lib/engine/index.js +68 -29
  29. package/lib/engine/records.d.ts +4 -7
  30. package/lib/engine/records.js +6 -6
  31. package/lib/engine/test-helpers.d.ts +2 -3
  32. package/lib/engine/test-helpers.js +7 -5
  33. package/lib/erc8004.js +7 -10
  34. package/lib/fangorn.d.ts +65 -96
  35. package/lib/fangorn.js +110 -168
  36. package/lib/feed.d.ts +7 -8
  37. package/lib/feed.js +7 -8
  38. package/lib/index.d.ts +10 -13
  39. package/lib/index.js +10 -13
  40. package/lib/providers/storage/signed-url.d.ts +2 -10
  41. package/lib/providers/storage/signed-url.js +5 -15
  42. package/lib/providers/storage/types.d.ts +1 -1
  43. package/lib/providers/storage/utils.js +5 -3
  44. package/lib/test/key-server.d.ts +12 -0
  45. package/lib/test/key-server.js +30 -0
  46. package/lib/test/mem-registry.d.ts +14 -19
  47. package/lib/test/mem-registry.js +44 -37
  48. package/lib/test/sdk-suite.d.ts +1 -4
  49. package/lib/test/sdk-suite.js +16 -87
  50. package/lib/test/testbed.d.ts +35 -45
  51. package/lib/test/testbed.js +29 -56
  52. package/lib/types/index.d.ts +6 -11
  53. package/package.json +2 -5
  54. package/lib/contracts/app-registry/abi.d.ts +0 -1306
  55. package/lib/contracts/app-registry/abi.js +0 -1493
  56. package/lib/contracts/app-registry/index.d.ts +0 -200
  57. package/lib/contracts/app-registry/index.js +0 -325
  58. package/lib/contracts/membership-registry/abi.js +0 -1333
  59. package/lib/contracts/membership-registry/index.d.ts +0 -79
  60. package/lib/contracts/membership-registry/index.js +0 -104
  61. package/lib/contracts/types.d.ts +0 -8
  62. package/lib/contracts/types.js +0 -10
  63. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +0 -1
  64. package/lib/harness/examples/hackmd/build-markdown-graph.js +0 -17
  65. package/lib/harness/index.d.ts +0 -58
  66. package/lib/harness/index.js +0 -73
  67. package/lib/registry.d.ts +0 -118
  68. package/lib/registry.js +0 -184
package/lib/fangorn.js CHANGED
@@ -1,13 +1,12 @@
1
- import { FangornConfig, nonBlank, toAppId } from "./config.js";
1
+ import { FangornConfig, nonBlank } from "./config.js";
2
2
  import { mcpTools, mintAgent, registrationFile, retryNonce, setAgentFile } from "./erc8004.js";
3
3
  import { SignedUrlBackend } from "./providers/storage/signed-url.js";
4
4
  import { PinataBackend } from "./providers/storage/pinata.js";
5
- import { AppRegistryClient } from "./contracts/app-registry/index.js";
6
- import { MembershipRegistryClient } from "./contracts/membership-registry/index.js";
5
+ import { ChainRegistry, ZERO_HEAD } from "./contracts/data-registry/index.js";
6
+ import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
7
7
  import "./contracts/index.js";
8
- import { ChainRegistry, ZERO_HEAD, repoExcluded } from "./registry.js";
9
- import { FangornEngine, assertValidRepoName, rootHexFromCid } from "./engine/index.js";
10
- import { AppFeed } from "./feed.js";
8
+ import { FangornEngine, assertValidRepoName, commitUpdate, rootHexFromCid } from "./engine/index.js";
9
+ import { CommitFeed } from "./feed.js";
11
10
  import { createPublicClient, createWalletClient, http } from "viem";
12
11
  import { privateKeyToAccount } from "viem/accounts";
13
12
  import { CID } from "multiformats/cid";
@@ -26,26 +25,34 @@ function walletSigner(walletClient) {
26
25
  })
27
26
  };
28
27
  }
29
- function resolveStorage(storage, walletClient, config, getAppId) {
28
+ function resolveStorage(storage, walletClient, config) {
30
29
  if (!storage) return void 0;
31
30
  if ("backend" in storage) return storage.backend;
32
31
  if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, storage.pinata.gateway);
33
32
  if ("signedUrl" in storage) {
34
33
  const workerUrl = nonBlank(storage.signedUrl.workerUrl) ?? nonBlank(config.signedUrlWorker);
35
34
  if (!workerUrl) throw new Error(`no hosted upload worker on chain ${config.caip2.toString()}: pass storage.signedUrl.workerUrl, or bring your own storage ({ pinata } or { backend })`);
36
- return new SignedUrlBackend(workerUrl, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway, getAppId);
35
+ return new SignedUrlBackend(workerUrl, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway);
37
36
  }
38
37
  throw new Error(`Invalid storage config: must be { pinata: … }, { signedUrl: … } or { backend: … }, got ${JSON.stringify(storage)}`);
39
38
  }
40
- /** The A2A extension a Fangorn app's agent card carries: it names the app the card speaks for. */
41
- const FANGORN_APP_EXTENSION = "https://fangorn.network/a2a/app/v1";
39
+ /**
40
+ * The A2A extension a repo's agent card carries. Its params name the repo the
41
+ * card speaks for: `{ chainId, dataRegistry, publisher, repo }`.
42
+ */
43
+ const FANGORN_REPO_EXTENSION = "https://fangorn.network/a2a/repo/v1";
44
+ /**
45
+ * The record that binds a repo to its agent card: `{ url }`, at this id in the
46
+ * repo. Only the publisher can commit it, so it plays the part an on-chain
47
+ * pointer would.
48
+ */
49
+ const CARD_RECORD = "@card";
42
50
  var Fangorn = class Fangorn {
43
51
  ctx;
44
52
  _engine = null;
45
53
  _feed = null;
46
- _apps = null;
47
- _membership = null;
48
- /**
54
+ _settlement = null;
55
+ /**
49
56
  * The repo cache
50
57
  * Insertion order = LRU order
51
58
  */
@@ -60,8 +67,8 @@ var Fangorn = class Fangorn {
60
67
  }
61
68
  /**
62
69
  * Static creation of a new Fangorn client
63
- *
64
- * @param options
70
+ *
71
+ * @param options
65
72
  * @returns the client
66
73
  */
67
74
  static create(options) {
@@ -76,16 +83,14 @@ var Fangorn = class Fangorn {
76
83
  chain: config.chain,
77
84
  transport: http(config.rpcUrl)
78
85
  });
79
- const chosenApp = nonBlank(options.appId);
80
86
  const ctx = {
81
87
  config,
82
88
  walletClient,
83
89
  publicClient,
84
- appId: chosenApp ? toAppId(chosenApp) : void 0,
85
90
  metadataStorage: void 0,
86
91
  registry: options.registry ?? new ChainRegistry(config, publicClient, walletClient)
87
92
  };
88
- ctx.metadataStorage = resolveStorage(options.storage, walletClient, config, () => ctx.appId);
93
+ ctx.metadataStorage = resolveStorage(options.storage, walletClient, config);
89
94
  return new Fangorn(ctx);
90
95
  }
91
96
  /**
@@ -100,7 +105,6 @@ var Fangorn = class Fangorn {
100
105
  repo,
101
106
  base: head,
102
107
  records: [],
103
- message: `Reset ${repo}`,
104
108
  replace: true
105
109
  });
106
110
  return this.engine.pushCommit(publisher, repo, commitCid);
@@ -117,7 +121,7 @@ var Fangorn = class Fangorn {
117
121
  });
118
122
  }
119
123
  /**
120
- * Allocates a repo in the publisher's root map.
124
+ * Allocates a repo in the publisher's root map.
121
125
  * A no-op (no on-chain tx) if the repo is already initialized.
122
126
  */
123
127
  async initRepo(repoName) {
@@ -133,8 +137,7 @@ var Fangorn = class Fangorn {
133
137
  const { commitCid } = await this.createCommit({
134
138
  repo: repoName,
135
139
  base: head,
136
- records: [],
137
- message: `Initialize repository workspace: ${repoName}`
140
+ records: []
138
141
  });
139
142
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
140
143
  return {
@@ -159,8 +162,7 @@ var Fangorn = class Fangorn {
159
162
  id,
160
163
  type,
161
164
  payload
162
- }],
163
- message: `Upload to repo ${repoName} as type ${type}`
165
+ }]
164
166
  });
165
167
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
166
168
  const [[recordId, payloadCid]] = Object.entries(recordCids);
@@ -187,8 +189,7 @@ var Fangorn = class Fangorn {
187
189
  repo: repoName,
188
190
  base: head,
189
191
  records,
190
- deletes,
191
- message: `Batch upload to repo ${repoName}`
192
+ deletes
192
193
  });
193
194
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
194
195
  return {
@@ -211,7 +212,6 @@ var Fangorn = class Fangorn {
211
212
  base: parentCid,
212
213
  records: opts.records ?? [],
213
214
  deletes: opts.deletes,
214
- message: opts.message,
215
215
  replace: opts.replace
216
216
  });
217
217
  return {
@@ -246,7 +246,6 @@ var Fangorn = class Fangorn {
246
246
  base: oldRoot === ZERO_BYTES32 ? null : CID.parse(this.engine.commitCidFromRootHex(oldRoot)),
247
247
  records: opts.records ?? [],
248
248
  deletes: opts.deletes,
249
- message: opts.message,
250
249
  replace: opts.replace
251
250
  });
252
251
  const newRoot = rootHexFromCid(commitCid);
@@ -258,7 +257,7 @@ var Fangorn = class Fangorn {
258
257
  records: opts.records?.length ?? 0,
259
258
  deletes: opts.deletes?.length ?? 0
260
259
  },
261
- tx: await registry.prepareUpdate(opts.owner, opts.repo, oldRoot, newRoot),
260
+ tx: await registry.prepareUpdate(opts.owner, commitUpdate(await this.engine.getCommit(commitCid))),
262
261
  recordCids
263
262
  };
264
263
  }
@@ -274,16 +273,23 @@ var Fangorn = class Fangorn {
274
273
  onChainTip: onChainTip.toString()
275
274
  };
276
275
  }
276
+ /**
277
+ * `push`, signed instead of sent: anyone holding the result can settle it with
278
+ * `relayPush`, paying the gas.
279
+ */
280
+ async signPush(repo, commitCid) {
281
+ return this.engine.signCommit(this.getAddress(), repo, CID.parse(commitCid));
282
+ }
283
+ relayPush(signed) {
284
+ return this.engine.relayCommit(signed);
285
+ }
277
286
  /** The owner's current on-chain tip for a repo, or null if they have none. */
278
287
  async onChainTip(owner, repo) {
279
288
  const cid = await this.engine.resolveHeadCommit(owner, repo);
280
289
  return cid ? cid.toString() : null;
281
290
  }
282
291
  /**
283
- * A publisher's repo as this client presents it, cached against its tip:
284
- * the publisher's latest head, or, under an app, nothing unless the app
285
- * presents the publisher (provides its storage) and excludes neither it nor
286
- * the repo.
292
+ * A publisher's repo at its latest head, cached against that head.
287
293
  *
288
294
  * Reading a repo walks its whole record tree from the root. The tip is one
289
295
  * cheap contract read and only moves on publish, so it doubles as the cache
@@ -297,7 +303,7 @@ var Fangorn = class Fangorn {
297
303
  */
298
304
  async readRepo(owner, repo) {
299
305
  const key = `${owner.toLowerCase()}/${repo}`;
300
- const tip = await this.presentedTip({
306
+ const tip = await this.headCommit({
301
307
  publisher: owner,
302
308
  repo
303
309
  });
@@ -319,36 +325,23 @@ var Fangorn = class Fangorn {
319
325
  }
320
326
  return entry;
321
327
  }
322
- /** The commit this client presents of a repo, or null for none (see `readRepo`). */
323
- async presentedTip(ref) {
324
- const app = this.ctx.appId;
325
- const registry = this.ctx.registry;
326
- if (app && !await this.presentsRepo(app, ref)) return null;
327
- const head = await registry.head(ref);
328
+ /** The commit at a repo's head, or null for a repo never written. */
329
+ async headCommit(ref) {
330
+ const head = await this.ctx.registry.head(ref);
328
331
  return head === ZERO_BYTES32 ? null : this.engine.commitCidFromRootHex(head);
329
332
  }
330
- /** Does `app` present `ref`: it presents the publisher, and excludes neither it nor the repo? */
331
- async presentsRepo(app, ref) {
332
- const registry = this.ctx.registry;
333
- const [presents, excluded] = await Promise.all([registry.presents(app, ref.publisher), repoExcluded(registry, app, ref)]);
334
- return presents && !excluded;
335
- }
336
333
  /**
337
- * Every (publisher, repo) this client's app presents, at its latest head, less
338
- * what it excludes — the app's directory, from ONE `getLogs` over the update
339
- * log, kept to the publishers the app presents.
340
- *
341
- * ponytail: reads every publisher's updates and drops non-members, so it costs
342
- * what the network writes, not what the app holds. Filter on-chain by the
343
- * app's members (a `publisher` topic list) once that is too slow.
334
+ * Every (publisher, repo) at its latest head, from one scan of the update log.
344
335
  * Narrow it with `repo` (every publisher's `docs`) or `owner`, filtered on-chain.
336
+ *
337
+ * ponytail: scans the whole log from `fromBlock`; an indexer's sub-log once
338
+ * that is too slow.
345
339
  */
346
- async appRepos(opts = {}) {
347
- const app = this.requireApp("appRepos");
340
+ async repos(opts = {}) {
348
341
  const entries = await this.ctx.registry.log({
349
342
  publisher: opts.owner,
350
343
  repo: opts.repo
351
- }, opts.fromBlock ?? this.ctx.config.appRegistryFromBlock);
344
+ }, opts.fromBlock ?? this.ctx.config.fromBlock);
352
345
  const latest = /* @__PURE__ */ new Map();
353
346
  for (const e of entries) latest.set(`${e.publisher.toLowerCase()}/${e.repo}`, {
354
347
  owner: e.publisher,
@@ -356,54 +349,65 @@ var Fangorn = class Fangorn {
356
349
  root: e.head,
357
350
  blockNumber: e.t
358
351
  });
359
- const all = [...latest.values()];
360
- const kept = await Promise.all(all.map((d) => this.presentsRepo(app, {
361
- publisher: d.owner,
362
- repo: d.repo
363
- })));
364
- return all.filter((_, i) => kept[i]);
352
+ return [...latest.values()];
365
353
  }
366
354
  /**
367
- * Resolve an app from its agent card URL alone, and prove the card speaks for it.
355
+ * Resolve a repo from its agent card URL alone, and prove the card speaks for it.
368
356
  *
369
- * The card names its app in the `FANGORN_APP_EXTENSION` A2A extension, but
370
- * anyone can serve a card that names any app. So the card is trusted only if
371
- * the app's on-chain `agent_uri`, which only the app owner can set, points
357
+ * The card names its repo in the `FANGORN_REPO_EXTENSION` A2A extension, but
358
+ * anyone can serve a card that names any repo. So the card is trusted only if
359
+ * the repo's `@card` record, which only its publisher can commit, points
372
360
  * back at this exact URL. The comparison is exact string equality, so a
373
361
  * trailing slash or a different host counts as a different card.
374
- *
375
- * Doesn't touch this client's app. Pass `appId` to `setAppId` to read under it.
376
362
  */
377
- async discoverApp(cardUrl) {
363
+ async discoverCard(cardUrl) {
378
364
  const res = await fetch(cardUrl, { signal: AbortSignal.timeout(1e4) });
379
365
  if (!res.ok) throw new Error(`agent card ${cardUrl}: HTTP ${String(res.status)}`);
380
366
  const card = await res.json();
381
- const ext = card.capabilities?.extensions?.find((e) => e.uri === FANGORN_APP_EXTENSION);
382
- if (!ext) throw new Error(`agent card ${cardUrl} has no ${FANGORN_APP_EXTENSION} extension`);
367
+ const ext = card.capabilities?.extensions?.find((e) => e.uri === FANGORN_REPO_EXTENSION);
368
+ if (!ext) throw new Error(`agent card ${cardUrl} has no ${FANGORN_REPO_EXTENSION} extension`);
383
369
  const p = ext.params ?? {};
384
- if (typeof p.appId !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(p.appId)) throw new Error(`agent card ${cardUrl}: appId is not a 32-byte hex string`);
385
- if (typeof p.fromBlock !== "string" || !/^\d+$/.test(p.fromBlock)) throw new Error(`agent card ${cardUrl}: fromBlock is not a decimal block number`);
386
- const repos = p.repos ?? p.namespaces ?? [];
387
- if (!Array.isArray(repos) || !repos.every((n) => typeof n === "string")) throw new Error(`agent card ${cardUrl}: repos is not a list of strings`);
388
- const apps = this.getAppRegistry();
389
- if (p.chainId !== this.ctx.config.caip2 || typeof p.appRegistry !== "string" || p.appRegistry.toLowerCase() !== apps.getAddress().toLowerCase()) throw new Error(`agent card ${cardUrl} is for chain ${String(p.chainId)} / AppRegistry ${String(p.appRegistry)}, not this client's`);
390
- const appId = p.appId;
391
- const bound = await apps.appAgentUri(appId);
392
- if (bound !== cardUrl) throw new Error(`agent card ${cardUrl} is not bound to app ${appId}: its on-chain agent_uri is ${bound ? `"${bound}"` : "unset"}`);
370
+ if (typeof p.publisher !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(p.publisher)) throw new Error(`agent card ${cardUrl}: publisher is not an address`);
371
+ if (typeof p.repo !== "string" || !p.repo) throw new Error(`agent card ${cardUrl}: repo is not a repo name`);
372
+ const registry = this.ctx.config.dataRegistryContractAddress;
373
+ if (p.chainId !== this.ctx.config.caip2 || typeof p.dataRegistry !== "string" || p.dataRegistry.toLowerCase() !== registry.toLowerCase()) throw new Error(`agent card ${cardUrl} is for chain ${String(p.chainId)} / DataRegistry ${String(p.dataRegistry)}, not this client's`);
374
+ const publisher = p.publisher;
375
+ const bound = await this.cardOf(publisher, p.repo);
376
+ if (bound !== cardUrl) throw new Error(`agent card ${cardUrl} is not bound to ${publisher}/${p.repo}: its ${CARD_RECORD} record is ${bound ? `"${bound}"` : "unset"}`);
393
377
  return {
394
378
  card,
395
- appId,
396
- fromBlock: BigInt(p.fromBlock),
397
- repos
379
+ publisher,
380
+ repo: p.repo
398
381
  };
399
382
  }
383
+ /** The card URL a repo's `@card` record points at, or undefined for none. */
384
+ async cardOf(publisher, repo) {
385
+ if (!await this.headCommit({
386
+ publisher,
387
+ repo
388
+ })) return void 0;
389
+ const url = (await this.engine.readRecord(publisher, repo, CARD_RECORD))?.payload.url;
390
+ return typeof url === "string" ? url : void 0;
391
+ }
392
+ /**
393
+ * Point one of your repos at its agent card, by committing its `@card` record.
394
+ * Returns the transaction, or undefined if it already points there.
395
+ */
396
+ async setCard(repo, cardUrl) {
397
+ if (await this.cardOf(this.getAddress(), repo) === cardUrl) return void 0;
398
+ const { txHash } = await this.uploadBatch(repo, [{
399
+ id: CARD_RECORD,
400
+ type: "card",
401
+ payload: { url: cardUrl }
402
+ }]);
403
+ return txHash;
404
+ }
400
405
  /**
401
- * The app's commit stream as ONE shared, ref-counted subscription (see
402
- * `AppFeed`). Prefer this over `subscribeApp` anywhere more than one consumer
403
- * wants the same feed — a server fanning out to connections, say.
406
+ * `subscribeAll` as ONE shared, ref-counted subscription (see `CommitFeed`), for
407
+ * anywhere more than one consumer wants the same stream.
404
408
  */
405
- appFeed(opts = {}) {
406
- this._feed ??= new AppFeed((signal) => this.subscribeApp({
409
+ feed(opts = {}) {
410
+ this._feed ??= new CommitFeed((signal) => this.subscribeAll({
407
411
  ...opts,
408
412
  signal
409
413
  }));
@@ -415,7 +419,6 @@ var Fangorn = class Fangorn {
415
419
  cid: cid.toString(),
416
420
  parent: commit.parent?.toString() ?? null,
417
421
  epoch: commit.epoch,
418
- message: commit.message,
419
422
  root: commit.root.toString()
420
423
  };
421
424
  }
@@ -444,18 +447,16 @@ var Fangorn = class Fangorn {
444
447
  }, opts);
445
448
  }
446
449
  /**
447
- * Stream changes across the *whole app* — every repo of every publisher it
448
- * presents, less its exclusions. Narrow it with `repo` (every publisher's `docs`) or
449
- * `owner` (one publisher's whole app footprint). With no app, every update by
450
- * anyone: a firehose.
450
+ * Stream changes to every repo of every publisher. Narrow it with `repo`
451
+ * (every publisher's `docs`) or `owner` (one publisher's repos).
451
452
  */
452
- subscribeApp(opts = {}) {
453
+ subscribeAll(opts = {}) {
453
454
  return this.streamCommits({
454
455
  publisher: opts.owner,
455
456
  repo: opts.repo
456
457
  }, opts);
457
458
  }
458
- /** Shared catch-up-then-live loop behind `subscribe` and `subscribeApp`. */
459
+ /** Shared catch-up-then-live loop behind `subscribe` and `subscribeAll`. */
459
460
  async *streamCommits(filter, opts) {
460
461
  const registry = this.ctx.registry;
461
462
  const seen = /* @__PURE__ */ new Set();
@@ -511,8 +512,8 @@ var Fangorn = class Fangorn {
511
512
  }
512
513
  }
513
514
  /**
514
- * Resolve a log entry into a repo change, or null if nothing presented
515
- * changed: the repo slice was untouched, or the app excludes it.
515
+ * Resolve a log entry into a repo change, or null if the repo's records did
516
+ * not change.
516
517
  *
517
518
  * The commit itself names its repo, which must be the one the entry was
518
519
  * logged under, or the publisher settled a commit for one repo against
@@ -526,11 +527,6 @@ var Fangorn = class Fangorn {
526
527
  async toRepoChange(log, lastHead) {
527
528
  const declared = await this.engine.repoOf(log.head);
528
529
  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}")`);
529
- const ref = {
530
- publisher: log.publisher,
531
- repo: log.repo
532
- };
533
- if (this.ctx.appId && !await this.presentsRepo(this.ctx.appId, ref)) return null;
534
530
  const key = `${log.publisher.toLowerCase()}/${log.repo}`;
535
531
  const oldRoot = lastHead.get(key) ?? log.parent;
536
532
  lastHead.set(key, log.head);
@@ -549,34 +545,26 @@ var Fangorn = class Fangorn {
549
545
  getConfig() {
550
546
  return this.ctx.config;
551
547
  }
552
- /** Heads, membership, exclusions and logs: the registry of WHITEPAPER_1 §3.2. */
548
+ /** Heads and the update log: the registry of WHITEPAPER_1 §3.2. */
553
549
  getRegistry() {
554
550
  return this.ctx.registry;
555
551
  }
556
- /**
557
- * App management: claiming an app (its storage subscription), terms,
558
- * invitations and membership, the agent card, and the protocol admin's powers.
559
- * The owner accepts a publisher (`acceptPublisher()`); from then its uploads
560
- * bill the app's subscription, and the app presents its repos.
561
- */
562
- getAppRegistry() {
563
- this._apps ??= new AppRegistryClient(this.ctx.config.appRegistryContractAddress, this.ctx.appId, this.ctx.publicClient, this.ctx.walletClient, this.ctx.config.logWindow);
564
- return this._apps;
565
- }
566
- getMembershipRegistry() {
567
- this._membership ??= new MembershipRegistryClient(this.ctx.config.membershipRegistryContractAddress, this.ctx.publicClient, this.ctx.walletClient);
568
- return this._membership;
552
+ getSettlementRegistry() {
553
+ const address = this.ctx.config.settlementRegistryContractAddress;
554
+ if (!address) throw new Error("No SettlementRegistry is deployed on this network.");
555
+ this._settlement ??= new SettlementRegistryClient(address, this.ctx.publicClient, this.ctx.walletClient);
556
+ return this._settlement;
569
557
  }
570
558
  /**
571
- * Register the app as an ERC-8004 agent from its card, and point the app at the card
572
- * (owner only). The registration file is pinned with this client's storage, so a
559
+ * Register a repo as an ERC-8004 agent from its card, and point the repo at
560
+ * the card (`setCard`). The registration file is pinned with this client's storage, so a
573
561
  * browser wallet on signed-URL storage needs no Pinata JWT.
574
562
  *
575
563
  * `update` re-files an agent already minted (its token id) from the card as it is
576
564
  * now, minting nothing. `skipRegister` only binds the card. A binding that already
577
565
  * points at `cardUrl` is left alone.
578
566
  */
579
- async registerAgent(cardUrl, opts = {}) {
567
+ async registerAgent(cardUrl, opts) {
580
568
  const res = await fetch(cardUrl);
581
569
  if (!res.ok) throw new Error(`card at ${cardUrl} returned ${String(res.status)}`);
582
570
  const card = await res.json();
@@ -620,59 +608,13 @@ var Fangorn = class Fangorn {
620
608
  }
621
609
  }
622
610
  }
623
- const apps = this.getAppRegistry();
624
- if (await apps.appAgentUri().catch(() => "") === cardUrl) return {
625
- card: named,
626
- agentId
627
- };
628
- const txHash = await retryNonce(() => apps.setAppAgentUri(cardUrl));
611
+ const txHash = await retryNonce(() => this.setCard(opts.repo, cardUrl));
629
612
  return {
630
613
  card: named,
631
614
  agentId,
632
615
  txHash
633
616
  };
634
617
  }
635
- /** The app this client reads and publishes under, or undefined for none. */
636
- getAppId() {
637
- return this.ctx.appId;
638
- }
639
- requireApp(what) {
640
- if (!this.ctx.appId) throw new Error(`${what} needs an app: pass \`appId\` to Fangorn.create() or call setAppId()`);
641
- return this.ctx.appId;
642
- }
643
- /**
644
- * Point this client at a different app — by name (`"my-app"`) or by app id —
645
- * or at none, without rebuilding it. Every read, publish and subscription
646
- * after this call is in the new context.
647
- *
648
- * Repo reads are dropped from the cache (its keys are app-agnostic) and
649
- * the shared `appFeed` is released: a feed watches one app's commit stream, so
650
- * the next `appFeed()` opens a fresh subscription. Generators already running
651
- * from `subscribe`/`subscribeApp` keep their original filter until aborted.
652
- */
653
- setAppId(nameOrId) {
654
- const chosen = nonBlank(nameOrId);
655
- this.ctx.appId = chosen ? toAppId(chosen) : void 0;
656
- this._apps?.setAppId(this.ctx.appId);
657
- this.nsCache.clear();
658
- this._feed = null;
659
- }
660
- /**
661
- * Rename this client's app (owner only) — to a name (`"my-app"`) or an app id —
662
- * and point this client at the new id.
663
- *
664
- * Nothing moves on chain: the new id is an alias of the id the app was claimed
665
- * under, so its publishers, exclusions, subscription and token carry on, and
666
- * clients still on an old id keep working. The new id must be unclaimed, or one
667
- * this app already went by (renaming back).
668
- */
669
- async renameApp(nameOrId) {
670
- const chosen = nonBlank(nameOrId);
671
- if (!chosen) throw new Error("the new app name must not be blank");
672
- const txHash = await this.getAppRegistry().renameApp(toAppId(chosen));
673
- this.setAppId(chosen);
674
- return txHash;
675
- }
676
618
  getStorage() {
677
619
  if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } or { signedUrl: { ... } } to Fangorn.create()");
678
620
  return this.ctx.metadataStorage;
@@ -683,7 +625,7 @@ var Fangorn = class Fangorn {
683
625
  * picks up the new backend.
684
626
  */
685
627
  setStorage(storage) {
686
- this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config, () => this.ctx.appId);
628
+ this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config);
687
629
  this._engine = null;
688
630
  }
689
631
  getWalletClient() {
@@ -697,4 +639,4 @@ var Fangorn = class Fangorn {
697
639
  };
698
640
 
699
641
  //#endregion
700
- export { FANGORN_APP_EXTENSION, Fangorn };
642
+ export { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn };
package/lib/feed.d.ts CHANGED
@@ -3,18 +3,17 @@ import { RepoChange } from "./fangorn.js";
3
3
  //#region src/feed.d.ts
4
4
 
5
5
  /**
6
- * One shared app-wide commit stream, fanned out to many consumers.
6
+ * One shared commit stream, fanned out to many consumers.
7
7
  *
8
- * `subscribeApp` opens a fresh RPC watch per call. A server that subscribes per
9
- * connection × per tracked repo opens N×M pollers for what is the *same*
10
- * app-level topic filter. This opens exactly one, ref-counted: it starts with
11
- * the first listener and stops with the last. Consumers filter in memory — the
12
- * events are already narrowed to the app on-chain.
8
+ * `subscribeAll` opens a fresh RPC watch per call. A server that subscribes per
9
+ * connection × per tracked repo opens N×M pollers for the *same* topic filter.
10
+ * This opens exactly one, ref-counted: it starts with the first listener and
11
+ * stops with the last. Consumers filter in memory.
13
12
  *
14
13
  * Not a lens (WHITEPAPER_1 §3.4): a lens computes a view over the stream, this
15
14
  * only shares the stream. fangorn-md's server fans it out to its connections.
16
15
  */
17
- declare class AppFeed {
16
+ declare class CommitFeed {
18
17
  private readonly open;
19
18
  /** Delay before reopening the watch after it fails or ends. */
20
19
  private readonly restartDelayMs;
@@ -32,4 +31,4 @@ declare class AppFeed {
32
31
  private run;
33
32
  }
34
33
  //#endregion
35
- export { AppFeed };
34
+ export { CommitFeed };
package/lib/feed.js CHANGED
@@ -1,17 +1,16 @@
1
1
  //#region src/feed.ts
2
2
  /**
3
- * One shared app-wide commit stream, fanned out to many consumers.
3
+ * One shared commit stream, fanned out to many consumers.
4
4
  *
5
- * `subscribeApp` opens a fresh RPC watch per call. A server that subscribes per
6
- * connection × per tracked repo opens N×M pollers for what is the *same*
7
- * app-level topic filter. This opens exactly one, ref-counted: it starts with
8
- * the first listener and stops with the last. Consumers filter in memory — the
9
- * events are already narrowed to the app on-chain.
5
+ * `subscribeAll` opens a fresh RPC watch per call. A server that subscribes per
6
+ * connection × per tracked repo opens N×M pollers for the *same* topic filter.
7
+ * This opens exactly one, ref-counted: it starts with the first listener and
8
+ * stops with the last. Consumers filter in memory.
10
9
  *
11
10
  * Not a lens (WHITEPAPER_1 §3.4): a lens computes a view over the stream, this
12
11
  * only shares the stream. fangorn-md's server fans it out to its connections.
13
12
  */
14
- var AppFeed = class {
13
+ var CommitFeed = class {
15
14
  listeners = /* @__PURE__ */ new Set();
16
15
  abort = null;
17
16
  constructor(open, restartDelayMs = 2e3) {
@@ -65,4 +64,4 @@ var AppFeed = class {
65
64
  const asError = (err) => err instanceof Error ? err : new Error(String(err));
66
65
 
67
66
  //#endregion
68
- export { AppFeed };
67
+ export { CommitFeed };
package/lib/index.d.ts CHANGED
@@ -1,20 +1,17 @@
1
- import { AppConfig, ArbitrumSepoliaConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, appId, nonBlank, toAppId } from "./config.js";
2
- import { APP_REGISTRY_ABI } from "./contracts/app-registry/abi.js";
3
- import { PublisherStatus } from "./contracts/types.js";
4
1
  import { PreparedTx } from "./contracts/write.js";
5
- import { AppAccess, AppAgentLog, AppRegistryClient } from "./contracts/app-registry/index.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";
6
3
  import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
7
- import { repoId } from "./contracts/data-registry/index.js";
8
- import { ClaimArgs, JoinArgs, MembershipPayment, MembershipRegistryClient, joinNonce, membershipScope, membershipTokenId } from "./contracts/membership-registry/index.js";
9
- import { MEMBERSHIP_REGISTRY_ABI } from "./contracts/membership-registry/abi.js";
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
+ import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
10
6
  import "./contracts/index.js";
11
- import { AccessRequest, AccessSigner, DecryptHandleParams, EncryptAndUploadParams, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf } from "./crypto/encryption.js";
12
- import { ChainRegistry, ChainRegistryConfig, EPOCH_SECONDS, Exclusion, LogFilter, Registry, RepoRef, UpdateEntry, ZERO_HEAD, covers, epochOf, exclusionId, repoExcluded } from "./registry.js";
7
+ import { BaseSepoliaConfig, FangornConfig, NetworkConfig, SupportedNetworks, nonBlank } from "./config.js";
13
8
  import { FangornContext, FangornCreateOptions, StorageConfig } from "./types/index.js";
14
- import { AppFeed } from "./feed.js";
15
- import { AgentCard, FANGORN_APP_EXTENSION, Fangorn, RepoChange, SubscribeOptions } from "./fangorn.js";
16
- import { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
9
+ import { CommitFeed } from "./feed.js";
10
+ import { AgentCard, CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn, RepoChange, SubscribeOptions } from "./fangorn.js";
11
+ import { SellOptions, sealRecords } from "./cli/sell.js";
12
+ import { AccessSigner, GADGET_SELF_HKDF_V1, X25519_PUBKEY_LENGTH, seal, sealSelf, unseal, unsealSelf } from "./crypto/encryption.js";
13
+ import { AccessRequest, Deposit, FieldHandle, GADGET_FIELD_V1, PaidScope, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement } from "./crypto/paid.js";
17
14
  import { PinataBackend } from "./providers/storage/pinata.js";
18
15
  import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./providers/storage/signed-url.js";
19
16
  import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
20
- export { APP_REGISTRY_ABI, AccessRequest, AccessSigner, AgentCard, AppAccess, AppAgentLog, AppConfig, AppFeed, AppRegistryClient, ArbitrumSepoliaConfig, AssetProcessor, BaseSepoliaConfig, BuildAssetGraphOptions, ChainRegistry, ChainRegistryConfig, ClaimArgs, CommitFileGraph, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, DecryptHandleParams, EPOCH_SECONDS, Edge, EncryptAndUploadParams, Exclusion, FANGORN_APP_EXTENSION, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FileFacade, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, JoinArgs, LogFilter, MAX_UPLOAD_ATTEMPTS, MEMBERSHIP_REGISTRY_ABI, MembershipPayment, MembershipRegistryClient, PinataBackend, PreparedTx, ProcessorResult, PublisherStatus, Registry, RepoChange, RepoRef, SignedUrlBackend, SignedUrlSigner, StorageConfig, SubscribeOptions, SupportedNetworks, UpdateEntry, Vertex, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, covers, decryptHandle, deserialize, encryptAndUpload, epochOf, exclusionId, extractMarkdownLinks, fetchRawByCid, isTransientUpload, joinNonce, membershipScope, membershipTokenId, nonBlank, repoExcluded, repoId, retrieveByCid, seal, sealSelf, serialize, sha256Hex, toAppId, unseal, unsealSelf, withUploadRetry };
17
+ export { AccessRequest, AccessSigner, AgentCard, BaseSepoliaConfig, CARD_RECORD, ChainRegistry, ChainRegistryConfig, CommitFeed, CommitUpdate, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, Deposit, EPOCH_SECONDS, FANGORN_REPO_EXTENSION, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FieldHandle, GADGET_FIELD_V1, GADGET_SELF_HKDF_V1, LogFilter, MAX_UPLOAD_ATTEMPTS, NetworkConfig, PaidScope, PinataBackend, PreparedTx, RegisterArgs, Registry, RepoChange, RepoRef, SETTLEMENT_REGISTRY_ABI, SellOptions, SettleArgs, SettlementPayment, SettlementRegistryClient, SignedUrlBackend, SignedUrlSigner, 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, makeDeposit, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };
package/lib/index.js CHANGED
@@ -1,19 +1,16 @@
1
- import { ArbitrumSepoliaConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, appId, nonBlank, toAppId } from "./config.js";
1
+ import { BaseSepoliaConfig, FangornConfig, SupportedNetworks, nonBlank } from "./config.js";
2
2
  import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./providers/storage/signed-url.js";
3
3
  import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
4
4
  import { PinataBackend } from "./providers/storage/pinata.js";
5
- import { APP_REGISTRY_ABI } from "./contracts/app-registry/abi.js";
6
- import { AppRegistryClient } from "./contracts/app-registry/index.js";
7
- import { repoId } from "./contracts/data-registry/index.js";
8
5
  import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
9
- import { MEMBERSHIP_REGISTRY_ABI } from "./contracts/membership-registry/abi.js";
10
- import { MembershipRegistryClient, joinNonce, membershipScope, membershipTokenId } from "./contracts/membership-registry/index.js";
11
- import { PublisherStatus } from "./contracts/types.js";
6
+ import { ChainRegistry, EPOCH_SECONDS, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./contracts/data-registry/index.js";
7
+ import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
8
+ import { SettlementRegistryClient, TERMS_TYPES, WHOLE_REPO, recordKey, registerNonce, settlementDomain, subjectOf, termsFromJson, termsToJson } from "./contracts/settlement-registry/index.js";
12
9
  import "./contracts/index.js";
13
- import { ChainRegistry, EPOCH_SECONDS, ZERO_HEAD, covers, epochOf, exclusionId, repoExcluded } from "./registry.js";
14
- import { AppFeed } from "./feed.js";
15
- import { FANGORN_APP_EXTENSION, Fangorn } from "./fangorn.js";
16
- import { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
17
- import { GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf } from "./crypto/encryption.js";
10
+ import { CommitFeed } from "./feed.js";
11
+ import { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn } from "./fangorn.js";
12
+ import { GADGET_SELF_HKDF_V1, X25519_PUBKEY_LENGTH, seal, sealSelf, unseal, unsealSelf } from "./crypto/encryption.js";
13
+ import { GADGET_FIELD_V1, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement } from "./crypto/paid.js";
14
+ import { sealRecords } from "./cli/sell.js";
18
15
 
19
- export { APP_REGISTRY_ABI, AppFeed, AppRegistryClient, ArbitrumSepoliaConfig, BaseSepoliaConfig, ChainRegistry, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, EPOCH_SECONDS, FANGORN_APP_EXTENSION, Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, MAX_UPLOAD_ATTEMPTS, MEMBERSHIP_REGISTRY_ABI, MembershipRegistryClient, PinataBackend, PublisherStatus, SignedUrlBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, covers, decryptHandle, deserialize, encryptAndUpload, epochOf, exclusionId, extractMarkdownLinks, fetchRawByCid, isTransientUpload, joinNonce, membershipScope, membershipTokenId, nonBlank, repoExcluded, repoId, retrieveByCid, seal, sealSelf, serialize, sha256Hex, toAppId, unseal, unsealSelf, withUploadRetry };
16
+ export { BaseSepoliaConfig, CARD_RECORD, ChainRegistry, CommitFeed, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, 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, makeDeposit, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };