@fangorn-network/sdk 2026.7.27 → 2026.7.29-dev

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.
package/lib/fangorn.js CHANGED
@@ -1,14 +1,18 @@
1
- import { FangornConfig } from "./config.js";
1
+ import { DEFAULT_APP, FangornConfig, toAppId } from "./config.js";
2
2
  import { SignedUrlBackend } from "./providers/storage/signed-url.js";
3
3
  import { PinataBackend } from "./providers/storage/pinata.js";
4
- import { FangornEngine, MetagraphRegistry, assertValidNamespace } from "./engine/index.js";
5
- import { DataRegistryClient } from "./contracts/data-registry/index.js";
4
+ import { FangornEngine, MetagraphRegistry, assertValidNamespace, rootHexFromCid } from "./engine/index.js";
5
+ import { DataRegistryClient, subspaceId } from "./contracts/data-registry/index.js";
6
+ import "./contracts/index.js";
7
+ import { AppFeed } from "./feed.js";
6
8
  import { createPublicClient, createWalletClient, http } from "viem";
7
9
  import { privateKeyToAccount } from "viem/accounts";
8
10
  import { CID } from "multiformats/cid";
9
11
 
10
12
  //#region src/fangorn.ts
11
13
  const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
14
+ /** Max namespaces held in `readNamespace`'s tip-keyed cache. */
15
+ const NS_CACHE_MAX = 256;
12
16
  /** Build a signer for the access worker's ownership handshake from a wallet. */
13
17
  function walletSigner(walletClient) {
14
18
  const account = walletClient.account;
@@ -31,6 +35,9 @@ var Fangorn = class Fangorn {
31
35
  ctx;
32
36
  _engine = null;
33
37
  _metagraph = new MetagraphRegistry();
38
+ _feed = null;
39
+ /** Insertion order = LRU order; see `readNamespace`. */
40
+ nsCache = /* @__PURE__ */ new Map();
34
41
  constructor(ctx) {
35
42
  this.ctx = ctx;
36
43
  }
@@ -57,14 +64,14 @@ var Fangorn = class Fangorn {
57
64
  walletClient,
58
65
  metadataStorage,
59
66
  domain,
60
- dataRegistry: new DataRegistryClient(resolvedConfig.dataRegistryContractAddress, publicClient, walletClient),
67
+ dataRegistry: new DataRegistryClient(resolvedConfig.dataRegistryContractAddress, toAppId(options.appId ?? DEFAULT_APP), publicClient, walletClient),
61
68
  config: resolvedConfig
62
69
  });
63
70
  }
64
- async reset() {
71
+ async reset(namespace) {
65
72
  const registry = this.getDataRegistry();
66
- const currentRoot = await registry.getNamespaceHead(this.getAddress());
67
- await registry.commitStateRoot(currentRoot, ZERO_BYTES32);
73
+ const currentRoot = await registry.getNamespaceHead(this.getAddress(), namespace);
74
+ await registry.commitStateRoot(namespace, currentRoot, ZERO_BYTES32);
68
75
  }
69
76
  /**
70
77
  * Register permissive (no required fields) schemas for every tag/relation a
@@ -128,7 +135,7 @@ var Fangorn = class Fangorn {
128
135
  txHash: void 0,
129
136
  alreadyInitialized: true
130
137
  };
131
- const head = await this.engine.resolveHeadCommit(publisher);
138
+ const head = await this.engine.resolveHeadCommit(publisher, repoName);
132
139
  const { commitCid } = await this.createCommit({
133
140
  namespace: repoName,
134
141
  base: head,
@@ -136,7 +143,7 @@ var Fangorn = class Fangorn {
136
143
  edges: [],
137
144
  message: `Initialize repository workspace: ${repoName}`
138
145
  });
139
- const { txHash } = await this.engine.pushCommit(publisher, commitCid);
146
+ const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
140
147
  return {
141
148
  cid: commitCid.toString(),
142
149
  commitCid: commitCid.toString(),
@@ -149,7 +156,7 @@ var Fangorn = class Fangorn {
149
156
  */
150
157
  async upload(repoName, payload, schemaId) {
151
158
  const publisher = this.getAddress();
152
- const head = await this.engine.resolveHeadCommit(publisher);
159
+ const head = await this.engine.resolveHeadCommit(publisher, repoName);
153
160
  if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
154
161
  const { commitCid, vertexCids } = await this.createCommit({
155
162
  namespace: repoName,
@@ -162,7 +169,7 @@ var Fangorn = class Fangorn {
162
169
  edges: [],
163
170
  message: `Upload to namespace ${repoName} under schema ${schemaId}`
164
171
  });
165
- const { txHash } = await this.engine.pushCommit(publisher, commitCid);
172
+ const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
166
173
  return {
167
174
  payloadCid: vertexCids.v0,
168
175
  commitCid: commitCid.toString(),
@@ -179,7 +186,7 @@ var Fangorn = class Fangorn {
179
186
  assertValidNamespace(repoName);
180
187
  if (vertices.length === 0 && edges.length === 0) throw new Error("uploadBatch requires at least one vertex or edge");
181
188
  const publisher = this.getAddress();
182
- const head = await this.engine.resolveHeadCommit(publisher);
189
+ const head = await this.engine.resolveHeadCommit(publisher, repoName);
183
190
  if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
184
191
  const { commitCid, vertexCids } = await this.createCommit({
185
192
  namespace: repoName,
@@ -188,7 +195,7 @@ var Fangorn = class Fangorn {
188
195
  edges,
189
196
  message: `Batch upload to namespace ${repoName}`
190
197
  });
191
- const { txHash } = await this.engine.pushCommit(publisher, commitCid);
198
+ const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
192
199
  return {
193
200
  commitCid: commitCid.toString(),
194
201
  txHash,
@@ -219,19 +226,136 @@ var Fangorn = class Fangorn {
219
226
  vertexCids
220
227
  };
221
228
  }
222
- /** Settle a local commit as the on-chain head (fast-forward unless `force`). */
223
- async push(commitCid, opts) {
224
- const { txHash, onChainTip } = await this.engine.pushCommit(this.getAddress(), CID.parse(commitCid), opts);
229
+ /**
230
+ * Build a commit on top of `owner`'s current on-chain head and return it
231
+ * together with the UNSIGNED settlement tx — the self-custodial publish path.
232
+ *
233
+ * `commit` + `push` assume the caller holds the publishing key. A relay server
234
+ * doesn't: it builds and pins the commit with a keyless service wallet, then
235
+ * hands the tx to the user's browser wallet to sign. The head only moves when
236
+ * the publisher themselves signs, so the server is never a trusted party.
237
+ *
238
+ * Nothing is on-chain when this returns. The commit and its CAR are durable in
239
+ * storage, so if the user never signs, the result is an orphaned commit — junk
240
+ * in IPFS, not a corrupted timeline.
241
+ */
242
+ async prepareCommit(opts) {
243
+ assertValidNamespace(opts.namespace);
244
+ const registry = this.getDataRegistry();
245
+ const oldRoot = await registry.getNamespaceHead(opts.owner, opts.namespace);
246
+ const { commitCid, vertexCids } = await this.createCommit({
247
+ namespace: opts.namespace,
248
+ base: oldRoot === ZERO_BYTES32 ? null : CID.parse(this.engine.commitCidFromRootHex(oldRoot)),
249
+ vertices: opts.vertices ?? [],
250
+ edges: opts.edges ?? [],
251
+ message: opts.message,
252
+ replace: opts.replace
253
+ });
254
+ const newRoot = rootHexFromCid(commitCid);
255
+ return {
256
+ commitCid: commitCid.toString(),
257
+ oldRoot,
258
+ newRoot,
259
+ staged: {
260
+ vertices: opts.vertices?.length ?? 0,
261
+ edges: opts.edges?.length ?? 0
262
+ },
263
+ tx: await registry.prepareCommitStateRoot(opts.owner, opts.namespace, oldRoot, newRoot),
264
+ vertexCids
265
+ };
266
+ }
267
+ /**
268
+ * Settle a local commit as the on-chain head of `namespace` (fast-forward
269
+ * unless `force`). Each namespace has its own timeline, so pushes to
270
+ * different namespaces never contend for the same compare-and-swap.
271
+ */
272
+ async push(namespace, commitCid, opts) {
273
+ const { txHash, onChainTip } = await this.engine.pushCommit(this.getAddress(), namespace, CID.parse(commitCid), opts);
225
274
  return {
226
275
  txHash,
227
276
  onChainTip: onChainTip.toString()
228
277
  };
229
278
  }
230
- /** The owner's current on-chain tip commit CID, or null if they have no commits. */
231
- async onChainTip(owner) {
232
- const cid = await this.engine.resolveHeadCommit(owner);
279
+ /** The owner's current on-chain tip for a namespace, or null if they have none. */
280
+ async onChainTip(owner, namespace) {
281
+ const cid = await this.engine.resolveHeadCommit(owner, namespace);
233
282
  return cid ? cid.toString() : null;
234
283
  }
284
+ /**
285
+ * A publisher's namespace contents, cached against its on-chain tip.
286
+ *
287
+ * Reading a namespace walks the pail tree from the root — many sequential
288
+ * gateway fetches. The tip is one cheap contract read and only moves on
289
+ * publish, so it doubles as the cache key: no TTL to tune, no invalidation
290
+ * to remember after a settle, and never stale.
291
+ *
292
+ * LRU-bounded so an always-on process can't accumulate every namespace it
293
+ * ever touched. The durable copy is on-chain — an evicted entry re-walks.
294
+ * ponytail: fixed entry count, not byte-aware; switch to a size budget if a
295
+ * few huge namespaces blow memory before the count cap bites.
296
+ */
297
+ async readNamespace(owner, namespace) {
298
+ const key = `${owner.toLowerCase()}/${namespace}`;
299
+ const tip = await this.onChainTip(owner, namespace);
300
+ const hit = this.nsCache.get(key);
301
+ if (hit?.tip === tip) {
302
+ this.nsCache.delete(key);
303
+ this.nsCache.set(key, hit);
304
+ return hit;
305
+ }
306
+ const entry = {
307
+ tip,
308
+ contents: await this.engine.listNamespace(namespace, owner)
309
+ };
310
+ this.nsCache.delete(key);
311
+ this.nsCache.set(key, entry);
312
+ if (this.nsCache.size > NS_CACHE_MAX) {
313
+ const oldest = this.nsCache.keys().next().value;
314
+ if (oldest !== void 0) this.nsCache.delete(oldest);
315
+ }
316
+ return entry;
317
+ }
318
+ /**
319
+ * Every (publisher, namespace) pair that has ever committed under this app,
320
+ * at its latest root — the app's directory, from ONE `getLogs`.
321
+ *
322
+ * This is what cross-publisher discovery looks like now: the registry already
323
+ * indexes `app_id`, so the commit log IS the index. No per-publisher fan-out,
324
+ * no separate registration sweep, no central list — and unlike a publisher
325
+ * roster it only surfaces publishers with actual content.
326
+ *
327
+ * Namespaces come back as `subspaceId` (the hash), not the name, because the
328
+ * event never carries the name — recovering it costs one content fetch per
329
+ * entry. Pass `namespace` when you know the name you're after (the usual
330
+ * case: an app with one well-known namespace) and the filter is applied
331
+ * on-chain instead.
332
+ */
333
+ async appNamespaces(opts = {}) {
334
+ const logs = await this.getDataRegistry().getStateCommittedLogs({
335
+ publisher: opts.owner,
336
+ namespace: opts.namespace
337
+ }, opts.fromBlock ?? 0n);
338
+ const latest = /* @__PURE__ */ new Map();
339
+ for (const log of logs) latest.set(log.namespaceKey, {
340
+ owner: log.publisher,
341
+ subspaceId: log.subspaceId,
342
+ root: log.newRoot,
343
+ blockNumber: log.blockNumber
344
+ });
345
+ return [...latest.values()];
346
+ }
347
+ /**
348
+ * The app's commit stream as ONE shared, ref-counted subscription (see
349
+ * `AppFeed`). Prefer this over `subscribeApp` anywhere more than one consumer
350
+ * wants the same feed — a server fanning out to connections, say.
351
+ */
352
+ appFeed(opts = {}) {
353
+ this._feed ??= new AppFeed((signal) => this.subscribeApp({
354
+ ...opts,
355
+ signal
356
+ }));
357
+ return this._feed;
358
+ }
235
359
  /** Walk commit history from `head` (newest first). */
236
360
  async *log(head, max) {
237
361
  for await (const { cid, commit } of this.engine.walkParents(CID.parse(head), max)) yield {
@@ -255,14 +379,31 @@ var Fangorn = class Fangorn {
255
379
  return this.engine.listNamespace(repoName, this.getAddress());
256
380
  }
257
381
  /**
258
- * Stream namespace-scoped changes as the on-chain root advances. Optionally
259
- * replays from `fromBlock` first (resume cursor), then watches live until the
260
- * `signal` aborts. Each yielded change carries `blockNumber` — persist it to
261
- * resume exactly where you left off.
382
+ * Stream changes to one publisher's namespace. Optionally replays from
383
+ * `fromBlock` first (resume cursor), then watches live until the `signal`
384
+ * aborts. Each yielded change carries `blockNumber` — persist it to resume
385
+ * exactly where you left off.
262
386
  */
263
- async *subscribe(opts) {
264
- const owner = opts.owner ?? this.getAddress();
265
- const ns = opts.namespace;
387
+ subscribe(opts) {
388
+ return this.streamCommits({
389
+ publisher: opts.owner ?? this.getAddress(),
390
+ namespace: opts.namespace
391
+ }, opts);
392
+ }
393
+ /**
394
+ * Stream changes across the *whole app* — every publisher, every namespace.
395
+ * The app-level feed: one topic filter on `app_id`, no per-publisher fan-out
396
+ * and no global root to keep in sync. Narrow it with `namespace` (every
397
+ * publisher's `docs`) or `owner` (one publisher's whole app footprint).
398
+ */
399
+ subscribeApp(opts = {}) {
400
+ return this.streamCommits({
401
+ publisher: opts.owner,
402
+ namespace: opts.namespace
403
+ }, opts);
404
+ }
405
+ /** Shared catch-up-then-live loop behind `subscribe` and `subscribeApp`. */
406
+ async *streamCommits(filter, opts) {
266
407
  const registry = this.getDataRegistry();
267
408
  const seen = /* @__PURE__ */ new Set();
268
409
  const buffer = [];
@@ -276,7 +417,7 @@ var Fangorn = class Fangorn {
276
417
  wake = null;
277
418
  w?.();
278
419
  };
279
- const unwatch = registry.watchStateCommitted(owner, (log) => {
420
+ const unwatch = registry.watchStateCommitted(filter, (log) => {
280
421
  buffer.push(log);
281
422
  signal();
282
423
  }, (err) => {
@@ -289,10 +430,10 @@ var Fangorn = class Fangorn {
289
430
  };
290
431
  opts.signal?.addEventListener("abort", onAbort);
291
432
  try {
292
- if (opts.fromBlock !== void 0) for (const log of await registry.getStateCommittedLogs(owner, opts.fromBlock)) {
433
+ if (opts.fromBlock !== void 0) for (const log of await registry.getStateCommittedLogs(filter, opts.fromBlock)) {
293
434
  if (seen.has(log.logId)) continue;
294
435
  seen.add(log.logId);
295
- const change = await this.toNamespaceChange(log, ns, owner);
436
+ const change = await this.toNamespaceChange(log);
296
437
  if (change) yield change;
297
438
  }
298
439
  while (!subState.stopped) {
@@ -307,7 +448,7 @@ var Fangorn = class Fangorn {
307
448
  if (!log) continue;
308
449
  if (seen.has(log.logId)) continue;
309
450
  seen.add(log.logId);
310
- const change = await this.toNamespaceChange(log, ns, owner);
451
+ const change = await this.toNamespaceChange(log);
311
452
  if (change) yield change;
312
453
  }
313
454
  } finally {
@@ -315,13 +456,23 @@ var Fangorn = class Fangorn {
315
456
  opts.signal?.removeEventListener("abort", onAbort);
316
457
  }
317
458
  }
318
- /** Resolve a raw `StateCommitted` log into a namespace change, or null if the namespace slice was untouched. */
319
- async toNamespaceChange(log, namespace, owner) {
459
+ /**
460
+ * Resolve a raw `StateCommitted` log into a namespace change, or null if the
461
+ * namespace slice was untouched.
462
+ *
463
+ * The event carries `keccak256(namespace)`, never the name, so the name comes
464
+ * from the commit's own root map — and must hash back to the subspace the
465
+ * commit was published into, or the publisher settled a commit for one
466
+ * namespace against another's timeline.
467
+ */
468
+ async toNamespaceChange(log) {
469
+ const namespace = await this.engine.namespaceOf(log.newRoot);
470
+ if (subspaceId(namespace) !== log.subspaceId) throw new Error(`commit ${log.newRoot} declares namespace "${namespace}", which does not match the subspace it was committed to (${log.subspaceId})`);
320
471
  const diff = await this.engine.namespaceDiff(log.oldRoot === ZERO_BYTES32 ? null : log.oldRoot, log.newRoot, namespace);
321
472
  if (!(diff.addedVertices.length || diff.removedVertexCids.length || diff.addedEdges.length || diff.removedEdges.length)) return null;
322
473
  return {
323
474
  namespace,
324
- owner,
475
+ owner: log.publisher,
325
476
  commitCid: this.engine.commitCidFromRootHex(log.newRoot),
326
477
  oldRoot: log.oldRoot,
327
478
  newRoot: log.newRoot,
@@ -335,6 +486,25 @@ var Fangorn = class Fangorn {
335
486
  getDataRegistry() {
336
487
  return this.ctx.dataRegistry;
337
488
  }
489
+ /** The app (global namespace) this client publishes and reads under. */
490
+ getAppId() {
491
+ return this.ctx.dataRegistry.getAppId();
492
+ }
493
+ /**
494
+ * Point this client at a different app — by name (`"my-app"`) or by app id —
495
+ * without rebuilding it. The app id prefixes every namespace key, so every
496
+ * read, publish and subscription after this call lands in the new app.
497
+ *
498
+ * Namespace reads are dropped from the cache (its keys are app-agnostic) and
499
+ * the shared `appFeed` is released: a feed watches one app's commit stream, so
500
+ * the next `appFeed()` opens a fresh subscription. Generators already running
501
+ * from `subscribe`/`subscribeApp` keep their original filter until aborted.
502
+ */
503
+ setAppId(nameOrId) {
504
+ this.ctx.dataRegistry.setAppId(toAppId(nameOrId));
505
+ this.nsCache.clear();
506
+ this._feed = null;
507
+ }
338
508
  getStorage() {
339
509
  if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } or { signedUrl: { ... } } to Fangorn.create()");
340
510
  return this.ctx.metadataStorage;
package/lib/feed.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { NamespaceChange } from "./fangorn.js";
2
+
3
+ //#region src/feed.d.ts
4
+
5
+ /**
6
+ * One shared app-wide commit stream, fanned out to many consumers.
7
+ *
8
+ * `subscribeApp` opens a fresh RPC watch per call. A server that subscribes per
9
+ * connection × per tracked namespace 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.
13
+ */
14
+ declare class AppFeed {
15
+ private readonly open;
16
+ /** Delay before reopening the watch after it fails or ends. */
17
+ private readonly restartDelayMs;
18
+ private readonly listeners;
19
+ private abort;
20
+ constructor(open: (signal: AbortSignal) => AsyncGenerator<NamespaceChange>, /** Delay before reopening the watch after it fails or ends. */
21
+ restartDelayMs?: number);
22
+ /** Number of live listeners — 0 means the underlying watch is closed. */
23
+ get size(): number;
24
+ /**
25
+ * Register a listener, starting the feed if it was idle. Returns the
26
+ * unsubscribe function; the feed stops once the last listener leaves.
27
+ */
28
+ on(onChange: (change: NamespaceChange) => void, onError?: (err: Error) => void): () => void;
29
+ private run;
30
+ }
31
+ //#endregion
32
+ export { AppFeed };
package/lib/feed.js ADDED
@@ -0,0 +1,65 @@
1
+ //#region src/feed.ts
2
+ /**
3
+ * One shared app-wide commit stream, fanned out to many consumers.
4
+ *
5
+ * `subscribeApp` opens a fresh RPC watch per call. A server that subscribes per
6
+ * connection × per tracked namespace 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.
10
+ */
11
+ var AppFeed = class {
12
+ listeners = /* @__PURE__ */ new Set();
13
+ abort = null;
14
+ constructor(open, restartDelayMs = 2e3) {
15
+ this.open = open;
16
+ this.restartDelayMs = restartDelayMs;
17
+ }
18
+ /** Number of live listeners — 0 means the underlying watch is closed. */
19
+ get size() {
20
+ return this.listeners.size;
21
+ }
22
+ /**
23
+ * Register a listener, starting the feed if it was idle. Returns the
24
+ * unsubscribe function; the feed stops once the last listener leaves.
25
+ */
26
+ on(onChange, onError) {
27
+ const listener = {
28
+ onChange,
29
+ onError
30
+ };
31
+ this.listeners.add(listener);
32
+ if (!this.abort) this.run();
33
+ return () => {
34
+ this.listeners.delete(listener);
35
+ if (this.listeners.size === 0) {
36
+ this.abort?.abort();
37
+ this.abort = null;
38
+ }
39
+ };
40
+ }
41
+ run() {
42
+ const abort = new AbortController();
43
+ this.abort = abort;
44
+ const stopped = () => abort.signal.aborted;
45
+ (async () => {
46
+ while (!stopped()) {
47
+ try {
48
+ for await (const change of this.open(abort.signal)) for (const l of [...this.listeners]) try {
49
+ l.onChange(change);
50
+ } catch (err) {
51
+ l.onError?.(asError(err));
52
+ }
53
+ } catch (err) {
54
+ if (stopped()) return;
55
+ for (const l of [...this.listeners]) l.onError?.(asError(err));
56
+ }
57
+ if (!stopped()) await new Promise((r) => setTimeout(r, this.restartDelayMs));
58
+ }
59
+ })();
60
+ }
61
+ };
62
+ const asError = (err) => err instanceof Error ? err : new Error(String(err));
63
+
64
+ //#endregion
65
+ export { AppFeed };
package/lib/index.d.ts CHANGED
@@ -1,9 +1,15 @@
1
- import { AppConfig, FangornConfig, SupportedNetworks } from "./config.js";
1
+ import { AppConfig, DEFAULT_APP, FangornConfig, SupportedNetworks, appId, toAppId } from "./config.js";
2
+ import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
3
+ import { CommitFilter, DataRegistryClient, PreparedTx, PublisherStatus, StateCommittedLog, namespaceKey, subspaceId } from "./contracts/data-registry/index.js";
4
+ import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
5
+ import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
6
+ import "./contracts/index.js";
2
7
  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";
3
8
  import { FangornContext, FangornCreateOptions, StorageConfig } from "./types/index.js";
9
+ import { AppFeed } from "./feed.js";
4
10
  import { Fangorn, NamespaceChange, SubscribeOptions } from "./fangorn.js";
5
11
  import { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
6
12
  import { PinataBackend } from "./providers/storage/pinata.js";
7
13
  import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./providers/storage/signed-url.js";
8
14
  import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
9
- export { AccessRequest, AccessSigner, AppConfig, AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, DEFAULT_SIGNED_URL_WORKER, DecryptHandleParams, Edge, EncryptAndUploadParams, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FileFacade, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, MAX_UPLOAD_ATTEMPTS, NamespaceChange, PinataBackend, ProcessorResult, SignedUrlBackend, SignedUrlSigner, StorageConfig, SubscribeOptions, SupportedNetworks, Vertex, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, retrieveByCid, seal, sealSelf, serialize, sha256Hex, unseal, unsealSelf, withUploadRetry };
15
+ export { AccessRequest, AccessSigner, AppConfig, AppFeed, AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, CommitFilter, DATA_REGISTRY_ABI, DEFAULT_APP, DEFAULT_SIGNED_URL_WORKER, DataRegistryClient, DecryptHandleParams, Edge, EncryptAndUploadParams, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FileFacade, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, MAX_UPLOAD_ATTEMPTS, NamespaceChange, PinataBackend, PreparedTx, ProcessorResult, PublisherStatus, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, SignedUrlBackend, SignedUrlSigner, StateCommittedLog, StorageConfig, SubscribeOptions, SupportedNetworks, Vertex, X25519_PUBKEY_LENGTH, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, namespaceKey, retrieveByCid, seal, sealSelf, serialize, sha256Hex, subspaceId, toAppId, unseal, unsealSelf, withUploadRetry };
package/lib/index.js CHANGED
@@ -1,9 +1,15 @@
1
- import { FangornConfig, SupportedNetworks } from "./config.js";
1
+ import { DEFAULT_APP, FangornConfig, SupportedNetworks, appId, toAppId } 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 { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
6
+ import { DataRegistryClient, PublisherStatus, namespaceKey, subspaceId } from "./contracts/data-registry/index.js";
7
+ import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
8
+ import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
9
+ import "./contracts/index.js";
10
+ import { AppFeed } from "./feed.js";
5
11
  import { Fangorn } from "./fangorn.js";
6
12
  import { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
7
13
  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";
8
14
 
9
- export { DEFAULT_SIGNED_URL_WORKER, Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, MAX_UPLOAD_ATTEMPTS, PinataBackend, SignedUrlBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, retrieveByCid, seal, sealSelf, serialize, sha256Hex, unseal, unsealSelf, withUploadRetry };
15
+ export { AppFeed, DATA_REGISTRY_ABI, DEFAULT_APP, DEFAULT_SIGNED_URL_WORKER, DataRegistryClient, Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, MAX_UPLOAD_ATTEMPTS, PinataBackend, PublisherStatus, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, SignedUrlBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, namespaceKey, retrieveByCid, seal, sealSelf, serialize, sha256Hex, subspaceId, toAppId, unseal, unsealSelf, withUploadRetry };
@@ -6,9 +6,23 @@ import { Hex } from "viem";
6
6
  declare class TestBed {
7
7
  private readonly f_list;
8
8
  private constructor();
9
- static init(sks: Hex[]): TestBed;
9
+ /**
10
+ * @param sks one wallet per publisher in the forest
11
+ * @param appName the app namespace to publish under; defaults to the SDK's
12
+ * own. Pass an unclaimed name to exercise the AppNotFound path.
13
+ */
14
+ static init(sks: Hex[], appName?: string): TestBed;
10
15
  getFangorn(index: number): Fangorn;
11
- resetContractState(index: number): Promise<void>;
16
+ /**
17
+ * Claim the configured app namespace, if nobody has yet.
18
+ *
19
+ * Orthogonal to `register`: an app claims a unique namespace prefix that
20
+ * publishers may write under, while a publisher registers for the right to
21
+ * write at all. Neither implies the other — one app hosts many publishers,
22
+ * and one publisher writes into many apps. Idempotent, and safe when someone
23
+ * else already owns it: apps are shared, not per-test.
24
+ */
25
+ registerApp(index: number): Promise<void>;
12
26
  register(index: number): Promise<void>;
13
27
  initRepo(index: number, name: string): Promise<{
14
28
  cid: undefined;
@@ -39,11 +53,15 @@ declare class TestBed {
39
53
  txHash: `0x${string}`;
40
54
  vertexCids: Record<string, string>;
41
55
  }>;
42
- fetch(index: number, cid: string): Promise<{
56
+ fetch(index: number, cid: string, namespace: string): Promise<{
43
57
  cid: string;
44
58
  schemaId: SchemaID;
45
59
  payload: Record<string, unknown>;
46
60
  }>;
61
+ /** Owner of the configured app namespace, or the zero address if unclaimed. */
62
+ appOwner(index: number): Promise<`0x${string}`>;
63
+ /** The raw on-chain head of one namespace — the slot the CAS actually guards. */
64
+ head(index: number, namespace: string): Promise<`0x${string}`>;
47
65
  inspect(index: number, namespace: string): Promise<NamespaceContents>;
48
66
  }
49
67
  //#endregion
@@ -1,3 +1,4 @@
1
+ import { FangornConfig } from "../config.js";
1
2
  import { Fangorn } from "../fangorn.js";
2
3
 
3
4
  //#region src/test/testbed.ts
@@ -5,11 +6,18 @@ var TestBed = class TestBed {
5
6
  constructor(f_list) {
6
7
  this.f_list = f_list;
7
8
  }
8
- static init(sks) {
9
+ /**
10
+ * @param sks one wallet per publisher in the forest
11
+ * @param appName the app namespace to publish under; defaults to the SDK's
12
+ * own. Pass an unclaimed name to exercise the AppNotFound path.
13
+ */
14
+ static init(sks, appName) {
9
15
  const f_list = [];
10
16
  sks.forEach((sk) => {
11
17
  f_list.push(Fangorn.create({
12
18
  privateKey: sk,
19
+ config: FangornConfig,
20
+ appId: appName,
13
21
  storage: { pinata: {
14
22
  jwt: process.env.PINATA_JWT ?? "",
15
23
  gateway: process.env.PINATA_GATEWAY ?? ""
@@ -22,10 +30,21 @@ var TestBed = class TestBed {
22
30
  if (index > this.f_list.length) throw new Error("index out of bounds");
23
31
  return this.f_list[index];
24
32
  }
25
- async resetContractState(index) {
26
- const fangorn = this.getFangorn(index);
27
- const currentRoot = await fangorn.getDataRegistry().getNamespaceHead(fangorn.getAddress());
28
- await fangorn.getDataRegistry().commitStateRoot(currentRoot, "0x0000000000000000000000000000000000000000000000000000000000000000");
33
+ /**
34
+ * Claim the configured app namespace, if nobody has yet.
35
+ *
36
+ * Orthogonal to `register`: an app claims a unique namespace prefix that
37
+ * publishers may write under, while a publisher registers for the right to
38
+ * write at all. Neither implies the other — one app hosts many publishers,
39
+ * and one publisher writes into many apps. Idempotent, and safe when someone
40
+ * else already owns it: apps are shared, not per-test.
41
+ */
42
+ async registerApp(index) {
43
+ const registry = this.getFangorn(index).getDataRegistry();
44
+ if (await registry.getAppOwner() === "0x0000000000000000000000000000000000000000") {
45
+ console.log(`Registering app ${registry.getAppId()} on-chain...`);
46
+ await registry.registerApp();
47
+ }
29
48
  }
30
49
  async register(index) {
31
50
  const fangorn = this.getFangorn(index);
@@ -45,9 +64,18 @@ var TestBed = class TestBed {
45
64
  async uploadBatch(index, namespace, vertices, edges = []) {
46
65
  return this.getFangorn(index).uploadBatch(namespace, vertices, edges);
47
66
  }
48
- async fetch(index, cid) {
67
+ async fetch(index, cid, namespace) {
68
+ const fangorn = this.getFangorn(index);
69
+ return fangorn.engine.readVertex(cid, fangorn.getAddress(), namespace);
70
+ }
71
+ /** Owner of the configured app namespace, or the zero address if unclaimed. */
72
+ async appOwner(index) {
73
+ return this.getFangorn(index).getDataRegistry().getAppOwner();
74
+ }
75
+ /** The raw on-chain head of one namespace — the slot the CAS actually guards. */
76
+ async head(index, namespace) {
49
77
  const fangorn = this.getFangorn(index);
50
- return fangorn.engine.readVertex(cid, fangorn.getAddress());
78
+ return fangorn.getDataRegistry().getNamespaceHead(fangorn.getAddress(), namespace);
51
79
  }
52
80
  async inspect(index, namespace) {
53
81
  return this.getFangorn(index).inspectNamespace(namespace);
@@ -25,6 +25,7 @@ type StorageConfig = {
25
25
  interface FangornCreateOptions {
26
26
  storage?: StorageConfig;
27
27
  config?: AppConfig;
28
+ appId?: string;
28
29
  domain?: string;
29
30
  privateKey?: Hex;
30
31
  walletClient?: WalletClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fangorn-network/sdk",
3
- "version": "2026.07.27",
3
+ "version": "2026.07.29-dev",
4
4
  "description": "Git for knowledge graphs",
5
5
  "repository": {
6
6
  "type": "git",