@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
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,22 +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
- if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, storage.pinata.gateway);
33
- if ("signedUrl" in storage) return new SignedUrlBackend(nonBlank(storage.signedUrl.workerUrl) ?? config.signedUrlWorker, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway, getAppId);
31
+ if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, nonBlank(storage.pinata.gateway) ?? config.ipfsGateway);
32
+ if ("signedUrl" in storage) {
33
+ const workerUrl = nonBlank(storage.signedUrl.workerUrl) ?? nonBlank(config.signedUrlWorker);
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 })`);
35
+ return new SignedUrlBackend(workerUrl, walletSigner(walletClient), nonBlank(storage.signedUrl.gateway) ?? config.ipfsGateway);
36
+ }
34
37
  throw new Error(`Invalid storage config: must be { pinata: … }, { signedUrl: … } or { backend: … }, got ${JSON.stringify(storage)}`);
35
38
  }
36
- /** The A2A extension a Fangorn app's agent card carries: it names the app the card speaks for. */
37
- 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";
38
50
  var Fangorn = class Fangorn {
39
51
  ctx;
40
52
  _engine = null;
41
53
  _feed = null;
42
- _apps = null;
43
- _membership = null;
44
- /**
54
+ _settlement = null;
55
+ /**
45
56
  * The repo cache
46
57
  * Insertion order = LRU order
47
58
  */
@@ -56,8 +67,8 @@ var Fangorn = class Fangorn {
56
67
  }
57
68
  /**
58
69
  * Static creation of a new Fangorn client
59
- *
60
- * @param options
70
+ *
71
+ * @param options
61
72
  * @returns the client
62
73
  */
63
74
  static create(options) {
@@ -72,16 +83,14 @@ var Fangorn = class Fangorn {
72
83
  chain: config.chain,
73
84
  transport: http(config.rpcUrl)
74
85
  });
75
- const chosenApp = nonBlank(options.appId);
76
86
  const ctx = {
77
87
  config,
78
88
  walletClient,
79
89
  publicClient,
80
- appId: chosenApp ? toAppId(chosenApp) : void 0,
81
90
  metadataStorage: void 0,
82
91
  registry: options.registry ?? new ChainRegistry(config, publicClient, walletClient)
83
92
  };
84
- ctx.metadataStorage = resolveStorage(options.storage, walletClient, config, () => ctx.appId);
93
+ ctx.metadataStorage = resolveStorage(options.storage, walletClient, config);
85
94
  return new Fangorn(ctx);
86
95
  }
87
96
  /**
@@ -96,7 +105,6 @@ var Fangorn = class Fangorn {
96
105
  repo,
97
106
  base: head,
98
107
  records: [],
99
- message: `Reset ${repo}`,
100
108
  replace: true
101
109
  });
102
110
  return this.engine.pushCommit(publisher, repo, commitCid);
@@ -113,7 +121,7 @@ var Fangorn = class Fangorn {
113
121
  });
114
122
  }
115
123
  /**
116
- * Allocates a repo in the publisher's root map.
124
+ * Allocates a repo in the publisher's root map.
117
125
  * A no-op (no on-chain tx) if the repo is already initialized.
118
126
  */
119
127
  async initRepo(repoName) {
@@ -129,8 +137,7 @@ var Fangorn = class Fangorn {
129
137
  const { commitCid } = await this.createCommit({
130
138
  repo: repoName,
131
139
  base: head,
132
- records: [],
133
- message: `Initialize repository workspace: ${repoName}`
140
+ records: []
134
141
  });
135
142
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
136
143
  return {
@@ -155,8 +162,7 @@ var Fangorn = class Fangorn {
155
162
  id,
156
163
  type,
157
164
  payload
158
- }],
159
- message: `Upload to repo ${repoName} as type ${type}`
165
+ }]
160
166
  });
161
167
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
162
168
  const [[recordId, payloadCid]] = Object.entries(recordCids);
@@ -183,8 +189,7 @@ var Fangorn = class Fangorn {
183
189
  repo: repoName,
184
190
  base: head,
185
191
  records,
186
- deletes,
187
- message: `Batch upload to repo ${repoName}`
192
+ deletes
188
193
  });
189
194
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
190
195
  return {
@@ -207,7 +212,6 @@ var Fangorn = class Fangorn {
207
212
  base: parentCid,
208
213
  records: opts.records ?? [],
209
214
  deletes: opts.deletes,
210
- message: opts.message,
211
215
  replace: opts.replace
212
216
  });
213
217
  return {
@@ -242,7 +246,6 @@ var Fangorn = class Fangorn {
242
246
  base: oldRoot === ZERO_BYTES32 ? null : CID.parse(this.engine.commitCidFromRootHex(oldRoot)),
243
247
  records: opts.records ?? [],
244
248
  deletes: opts.deletes,
245
- message: opts.message,
246
249
  replace: opts.replace
247
250
  });
248
251
  const newRoot = rootHexFromCid(commitCid);
@@ -254,7 +257,7 @@ var Fangorn = class Fangorn {
254
257
  records: opts.records?.length ?? 0,
255
258
  deletes: opts.deletes?.length ?? 0
256
259
  },
257
- tx: await registry.prepareUpdate(opts.owner, opts.repo, oldRoot, newRoot),
260
+ tx: await registry.prepareUpdate(opts.owner, commitUpdate(await this.engine.getCommit(commitCid))),
258
261
  recordCids
259
262
  };
260
263
  }
@@ -270,16 +273,23 @@ var Fangorn = class Fangorn {
270
273
  onChainTip: onChainTip.toString()
271
274
  };
272
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
+ }
273
286
  /** The owner's current on-chain tip for a repo, or null if they have none. */
274
287
  async onChainTip(owner, repo) {
275
288
  const cid = await this.engine.resolveHeadCommit(owner, repo);
276
289
  return cid ? cid.toString() : null;
277
290
  }
278
291
  /**
279
- * A publisher's repo as this client presents it, cached against its tip:
280
- * the publisher's latest head, or, under an app, nothing unless the app
281
- * presents the publisher (provides its storage) and excludes neither it nor
282
- * the repo.
292
+ * A publisher's repo at its latest head, cached against that head.
283
293
  *
284
294
  * Reading a repo walks its whole record tree from the root. The tip is one
285
295
  * cheap contract read and only moves on publish, so it doubles as the cache
@@ -293,7 +303,7 @@ var Fangorn = class Fangorn {
293
303
  */
294
304
  async readRepo(owner, repo) {
295
305
  const key = `${owner.toLowerCase()}/${repo}`;
296
- const tip = await this.presentedTip({
306
+ const tip = await this.headCommit({
297
307
  publisher: owner,
298
308
  repo
299
309
  });
@@ -315,36 +325,23 @@ var Fangorn = class Fangorn {
315
325
  }
316
326
  return entry;
317
327
  }
318
- /** The commit this client presents of a repo, or null for none (see `readRepo`). */
319
- async presentedTip(ref) {
320
- const app = this.ctx.appId;
321
- const registry = this.ctx.registry;
322
- if (app && !await this.presentsRepo(app, ref)) return null;
323
- 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);
324
331
  return head === ZERO_BYTES32 ? null : this.engine.commitCidFromRootHex(head);
325
332
  }
326
- /** Does `app` present `ref`: it presents the publisher, and excludes neither it nor the repo? */
327
- async presentsRepo(app, ref) {
328
- const registry = this.ctx.registry;
329
- const [presents, excluded] = await Promise.all([registry.presents(app, ref.publisher), repoExcluded(registry, app, ref)]);
330
- return presents && !excluded;
331
- }
332
333
  /**
333
- * Every (publisher, repo) this client's app presents, at its latest head, less
334
- * what it excludes — the app's directory, from ONE `getLogs` over the update
335
- * log, kept to the publishers the app presents.
336
- *
337
- * ponytail: reads every publisher's updates and drops non-members, so it costs
338
- * what the network writes, not what the app holds. Filter on-chain by the
339
- * 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.
340
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.
341
339
  */
342
- async appRepos(opts = {}) {
343
- const app = this.requireApp("appRepos");
340
+ async repos(opts = {}) {
344
341
  const entries = await this.ctx.registry.log({
345
342
  publisher: opts.owner,
346
343
  repo: opts.repo
347
- }, opts.fromBlock ?? this.ctx.config.appRegistryFromBlock);
344
+ }, opts.fromBlock ?? this.ctx.config.fromBlock);
348
345
  const latest = /* @__PURE__ */ new Map();
349
346
  for (const e of entries) latest.set(`${e.publisher.toLowerCase()}/${e.repo}`, {
350
347
  owner: e.publisher,
@@ -352,54 +349,65 @@ var Fangorn = class Fangorn {
352
349
  root: e.head,
353
350
  blockNumber: e.t
354
351
  });
355
- const all = [...latest.values()];
356
- const kept = await Promise.all(all.map((d) => this.presentsRepo(app, {
357
- publisher: d.owner,
358
- repo: d.repo
359
- })));
360
- return all.filter((_, i) => kept[i]);
352
+ return [...latest.values()];
361
353
  }
362
354
  /**
363
- * 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.
364
356
  *
365
- * The card names its app in the `FANGORN_APP_EXTENSION` A2A extension, but
366
- * anyone can serve a card that names any app. So the card is trusted only if
367
- * 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
368
360
  * back at this exact URL. The comparison is exact string equality, so a
369
361
  * trailing slash or a different host counts as a different card.
370
- *
371
- * Doesn't touch this client's app. Pass `appId` to `setAppId` to read under it.
372
362
  */
373
- async discoverApp(cardUrl) {
363
+ async discoverCard(cardUrl) {
374
364
  const res = await fetch(cardUrl, { signal: AbortSignal.timeout(1e4) });
375
365
  if (!res.ok) throw new Error(`agent card ${cardUrl}: HTTP ${String(res.status)}`);
376
366
  const card = await res.json();
377
- const ext = card.capabilities?.extensions?.find((e) => e.uri === FANGORN_APP_EXTENSION);
378
- 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`);
379
369
  const p = ext.params ?? {};
380
- 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`);
381
- if (typeof p.fromBlock !== "string" || !/^\d+$/.test(p.fromBlock)) throw new Error(`agent card ${cardUrl}: fromBlock is not a decimal block number`);
382
- const repos = p.repos ?? p.namespaces ?? [];
383
- if (!Array.isArray(repos) || !repos.every((n) => typeof n === "string")) throw new Error(`agent card ${cardUrl}: repos is not a list of strings`);
384
- const apps = this.getAppRegistry();
385
- 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`);
386
- const appId = p.appId;
387
- const bound = await apps.appAgentUri(appId);
388
- 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"}`);
389
377
  return {
390
378
  card,
391
- appId,
392
- fromBlock: BigInt(p.fromBlock),
393
- repos
379
+ publisher,
380
+ repo: p.repo
394
381
  };
395
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
+ }
396
392
  /**
397
- * The app's commit stream as ONE shared, ref-counted subscription (see
398
- * `AppFeed`). Prefer this over `subscribeApp` anywhere more than one consumer
399
- * wants the same feed — a server fanning out to connections, say.
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.
400
395
  */
401
- appFeed(opts = {}) {
402
- this._feed ??= new AppFeed((signal) => this.subscribeApp({
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
+ }
405
+ /**
406
+ * `subscribeAll` as ONE shared, ref-counted subscription (see `CommitFeed`), for
407
+ * anywhere more than one consumer wants the same stream.
408
+ */
409
+ feed(opts = {}) {
410
+ this._feed ??= new CommitFeed((signal) => this.subscribeAll({
403
411
  ...opts,
404
412
  signal
405
413
  }));
@@ -411,7 +419,6 @@ var Fangorn = class Fangorn {
411
419
  cid: cid.toString(),
412
420
  parent: commit.parent?.toString() ?? null,
413
421
  epoch: commit.epoch,
414
- message: commit.message,
415
422
  root: commit.root.toString()
416
423
  };
417
424
  }
@@ -440,18 +447,16 @@ var Fangorn = class Fangorn {
440
447
  }, opts);
441
448
  }
442
449
  /**
443
- * Stream changes across the *whole app* — every repo of every publisher it
444
- * presents, less its exclusions. Narrow it with `repo` (every publisher's `docs`) or
445
- * `owner` (one publisher's whole app footprint). With no app, every update by
446
- * 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).
447
452
  */
448
- subscribeApp(opts = {}) {
453
+ subscribeAll(opts = {}) {
449
454
  return this.streamCommits({
450
455
  publisher: opts.owner,
451
456
  repo: opts.repo
452
457
  }, opts);
453
458
  }
454
- /** Shared catch-up-then-live loop behind `subscribe` and `subscribeApp`. */
459
+ /** Shared catch-up-then-live loop behind `subscribe` and `subscribeAll`. */
455
460
  async *streamCommits(filter, opts) {
456
461
  const registry = this.ctx.registry;
457
462
  const seen = /* @__PURE__ */ new Set();
@@ -507,8 +512,8 @@ var Fangorn = class Fangorn {
507
512
  }
508
513
  }
509
514
  /**
510
- * Resolve a log entry into a repo change, or null if nothing presented
511
- * 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.
512
517
  *
513
518
  * The commit itself names its repo, which must be the one the entry was
514
519
  * logged under, or the publisher settled a commit for one repo against
@@ -522,11 +527,6 @@ var Fangorn = class Fangorn {
522
527
  async toRepoChange(log, lastHead) {
523
528
  const declared = await this.engine.repoOf(log.head);
524
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}")`);
525
- const ref = {
526
- publisher: log.publisher,
527
- repo: log.repo
528
- };
529
- if (this.ctx.appId && !await this.presentsRepo(this.ctx.appId, ref)) return null;
530
530
  const key = `${log.publisher.toLowerCase()}/${log.repo}`;
531
531
  const oldRoot = lastHead.get(key) ?? log.parent;
532
532
  lastHead.set(key, log.head);
@@ -545,34 +545,26 @@ var Fangorn = class Fangorn {
545
545
  getConfig() {
546
546
  return this.ctx.config;
547
547
  }
548
- /** 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. */
549
549
  getRegistry() {
550
550
  return this.ctx.registry;
551
551
  }
552
- /**
553
- * App management: claiming an app (its storage subscription), terms,
554
- * invitations and membership, the agent card, and the protocol admin's powers.
555
- * The owner accepts a publisher (`acceptPublisher()`); from then its uploads
556
- * bill the app's subscription, and the app presents its repos.
557
- */
558
- getAppRegistry() {
559
- this._apps ??= new AppRegistryClient(this.ctx.config.appRegistryContractAddress, this.ctx.appId, this.ctx.publicClient, this.ctx.walletClient, this.ctx.config.logWindow);
560
- return this._apps;
561
- }
562
- getMembershipRegistry() {
563
- this._membership ??= new MembershipRegistryClient(this.ctx.config.membershipRegistryContractAddress, this.ctx.publicClient, this.ctx.walletClient);
564
- 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;
565
557
  }
566
558
  /**
567
- * Register the app as an ERC-8004 agent from its card, and point the app at the card
568
- * (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
569
561
  * browser wallet on signed-URL storage needs no Pinata JWT.
570
562
  *
571
563
  * `update` re-files an agent already minted (its token id) from the card as it is
572
564
  * now, minting nothing. `skipRegister` only binds the card. A binding that already
573
565
  * points at `cardUrl` is left alone.
574
566
  */
575
- async registerAgent(cardUrl, opts = {}) {
567
+ async registerAgent(cardUrl, opts) {
576
568
  const res = await fetch(cardUrl);
577
569
  if (!res.ok) throw new Error(`card at ${cardUrl} returned ${String(res.status)}`);
578
570
  const card = await res.json();
@@ -616,43 +608,13 @@ var Fangorn = class Fangorn {
616
608
  }
617
609
  }
618
610
  }
619
- const apps = this.getAppRegistry();
620
- if (await apps.appAgentUri().catch(() => "") === cardUrl) return {
621
- card: named,
622
- agentId
623
- };
624
- const txHash = await retryNonce(() => apps.setAppAgentUri(cardUrl));
611
+ const txHash = await retryNonce(() => this.setCard(opts.repo, cardUrl));
625
612
  return {
626
613
  card: named,
627
614
  agentId,
628
615
  txHash
629
616
  };
630
617
  }
631
- /** The app this client reads and publishes under, or undefined for none. */
632
- getAppId() {
633
- return this.ctx.appId;
634
- }
635
- requireApp(what) {
636
- if (!this.ctx.appId) throw new Error(`${what} needs an app: pass \`appId\` to Fangorn.create() or call setAppId()`);
637
- return this.ctx.appId;
638
- }
639
- /**
640
- * Point this client at a different app — by name (`"my-app"`) or by app id —
641
- * or at none, without rebuilding it. Every read, publish and subscription
642
- * after this call is in the new context.
643
- *
644
- * Repo reads are dropped from the cache (its keys are app-agnostic) and
645
- * the shared `appFeed` is released: a feed watches one app's commit stream, so
646
- * the next `appFeed()` opens a fresh subscription. Generators already running
647
- * from `subscribe`/`subscribeApp` keep their original filter until aborted.
648
- */
649
- setAppId(nameOrId) {
650
- const chosen = nonBlank(nameOrId);
651
- this.ctx.appId = chosen ? toAppId(chosen) : void 0;
652
- this._apps?.setAppId(this.ctx.appId);
653
- this.nsCache.clear();
654
- this._feed = null;
655
- }
656
618
  getStorage() {
657
619
  if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } or { signedUrl: { ... } } to Fangorn.create()");
658
620
  return this.ctx.metadataStorage;
@@ -663,7 +625,7 @@ var Fangorn = class Fangorn {
663
625
  * picks up the new backend.
664
626
  */
665
627
  setStorage(storage) {
666
- 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);
667
629
  this._engine = null;
668
630
  }
669
631
  getWalletClient() {
@@ -677,4 +639,4 @@ var Fangorn = class Fangorn {
677
639
  };
678
640
 
679
641
  //#endregion
680
- 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 { ArbitrumSepoliaConfig, 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, ArbitrumSepoliaConfig, 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 { ArbitrumSepoliaConfig, 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 { ArbitrumSepoliaConfig, 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 };