@fangorn-network/sdk 2026.7.27 → 2026.7.28

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/README.md CHANGED
@@ -10,7 +10,7 @@ Data is a **metagraph** — **vertices** (a JSON payload tagged by a free-form s
10
10
 
11
11
  Datasets are versioned like git, down to the storage model: each update is a **commit** that points at its parent and at a single **CAR file** (a packfile) holding only the blocks that commit introduced. The registry stores only the pointer to the latest commit; full history lives in IPFS — reconstructible from the on-chain tip alone, no indexer required. `commit` builds the graph in memory and persists it as **exactly two uploads** (one CAR + one small commit block), regardless of graph size; `push` moves the on-chain pointer (the single permissioned step, fast-forward checked). Unchanged data re-derives identical CIDs and is never re-uploaded.
12
12
 
13
- > **Note:** access-controlled (encrypted) fields and the purchase → claim → fetch settlement flow are being built on top of this registry and are **not available in the current release**. Registration, namespaces, and the git-native commit / push / log / clone rail are live.
13
+ Fields that shouldn't be public are **sealed** under a **gadget** — a named pairing of a sealing scheme and the condition under which it opens. Two ship today: `self-hkdf-v1` (fully private, only you can re-derive the key) and `worker-usdc-v1` (settlement-gated, released by the access worker once the reader has paid). See [Encryption & gadgets](#encryption--gadgets).
14
14
 
15
15
  ## Supported Networks
16
16
 
@@ -38,8 +38,9 @@ fangorn init
38
38
  `fangorn init` prompts for:
39
39
 
40
40
  - Wallet private key
41
- - Pinata JWT + gateway URL (content + commit-object storage)
42
- - Fangorn access worker URL (reserved for the upcoming access-control flow)
41
+ - Pinata JWT + gateway URL (content + commit-object storage; both optional)
42
+ - Access-gating worker URL (optional — stores sealed ciphertext and enforces the read gate)
43
+ - Presigned-URL worker URL (optional — issues short-lived Pinata upload URLs so no JWT is needed)
43
44
 
44
45
  Config is written to `~/.fangorn/config.json`.
45
46
 
@@ -50,9 +51,12 @@ ETH_PRIVATE_KEY=0x...
50
51
  PINATA_JWT=...
51
52
  PINATA_GATEWAY=https://your-gateway.mypinata.cloud
52
53
  CHAIN_NAME=arbitrumSepolia
53
- WORKER_URL=https://your-worker.workers.dev # optional (future access control)
54
+ ACCESS_WORKER_URL=https://access-worker.your-subdomain.workers.dev # optional (sealed fields)
55
+ SIGNED_URL_WORKER_URL=https://pinata-url-provider.your-subdomain.workers.dev # optional
54
56
  ```
55
57
 
58
+ > The **access worker** and the **presigned-URL worker** are two different services: the first gates reads of sealed fields, the second hands out Pinata upload URLs. Don't conflate them.
59
+
56
60
  ### Register as a publisher
57
61
 
58
62
  Register once before committing anything. This records your wallet as a data publisher in the DataRegistry (the registration fee is currently zero).
@@ -253,7 +257,7 @@ const c1 = await fangorn.commit({
253
257
  });
254
258
 
255
259
  // Settle it on-chain (fast-forward from "no tip yet")
256
- await fangorn.push(c1.commitCid);
260
+ await fangorn.push("rusty-anchor", c1.commitCid);
257
261
 
258
262
  // A follow-up commit builds on the previous one
259
263
  const c2 = await fangorn.commit({
@@ -264,7 +268,7 @@ const c2 = await fangorn.commit({
264
268
  { id: "t2", tag: "track", payload: { title: "Otra", artist: "Alice" } },
265
269
  ],
266
270
  });
267
- await fangorn.push(c2.commitCid); // refuses unless it fast-forwards the on-chain tip (pass { force: true } to override)
271
+ await fangorn.push("rusty-anchor", c2.commitCid); // refuses unless it fast-forwards the on-chain tip (pass { force: true } to override)
268
272
  ```
269
273
 
270
274
  ### History, diff & read
@@ -272,7 +276,7 @@ await fangorn.push(c2.commitCid); // refuses unless it fast-forwards the on-chai
272
276
  Walk history from the on-chain tip (IPFS only, no indexer), and read the current namespace contents:
273
277
 
274
278
  ```ts
275
- const tip = await fangorn.onChainTip(fangorn.getAddress());
279
+ const tip = await fangorn.onChainTip(fangorn.getAddress(), "rusty-anchor");
276
280
 
277
281
  // Walk commits, newest first
278
282
  for await (const c of fangorn.log(tip!)) {
@@ -332,6 +336,31 @@ The pure diff primitive is also exposed on the engine —
332
336
  `engine.namespaceDiff(oldRootHex, newRootHex, namespace)` — if you want to diff
333
337
  two arbitrary roots without watching.
334
338
 
339
+ ### Subscribe to a whole app
340
+
341
+ Namespaces are hierarchical: every commit lands under `app:publisher:namespace`,
342
+ and each triple is its own on-chain timeline. Two publishers — or one publisher's
343
+ two namespaces — never contend for the same compare-and-swap.
344
+
345
+ The registry indexes all three parts, so an app-wide feed is one topic filter
346
+ rather than a per-publisher fan-out. `subscribeApp` yields the same
347
+ `NamespaceChange` values as `subscribe`, from every publisher in the app:
348
+
349
+ ```ts
350
+ // Everything published under this app, by anyone
351
+ for await (const change of fangorn.subscribeApp({ signal: controller.signal })) {
352
+ console.log(change.owner, change.namespace, change.addedVertices.length);
353
+ }
354
+
355
+ // Narrow it: every publisher's "reviews" namespace, or one publisher's whole app footprint
356
+ fangorn.subscribeApp({ namespace: "reviews" });
357
+ fangorn.subscribeApp({ owner: "0x..." });
358
+ ```
359
+
360
+ The app id comes from config (`appId("my-app")`), and must be claimed once
361
+ on-chain with `fangorn.getDataRegistry().registerApp()` before any publisher can
362
+ commit under it.
363
+
335
364
  ### Storage
336
365
 
337
366
  Fangorn operates on a 'Bring Your Own Storage' basis. Each commit is persisted as
@@ -342,6 +371,130 @@ The backend never needs to understand IPLD — any blob store can implement the
342
371
 
343
372
  ---
344
373
 
374
+ ## Encryption & gadgets
375
+
376
+ Not every field belongs in public IPFS. Fangorn lets you **seal** a value and commit
377
+ only an opaque reference to it, keeping the graph — its shape, its edges, its
378
+ addressability — fully public while the payload stays closed.
379
+
380
+ A **gadget** names *how* a value is sealed and *under what condition* it opens. Two
381
+ ship today, both exported from the package root (`@fangorn-network/sdk`):
382
+
383
+ | Gadget | Key derivation | Who can open it |
384
+ | ---------------- | ------------------------------------------- | ----------------------------------------------------------------------------------- |
385
+ | `self-hkdf-v1` | HKDF from your own 32-byte secret | Only you. No ECDH, no recipient, no gate — nobody else can re-derive the key. |
386
+ | `worker-usdc-v1` | X25519 ECDH to the access worker's static key | Anyone who has settled for the resource; the worker checks the Settlement Registry. |
387
+
388
+ Every key is bound to a 32-byte **`resourceId`**, which doubles as the Settlement
389
+ Registry key. The same secret cannot cross-open a different resource, and changing
390
+ *who can read* means re-sealing under a new gadget/`resourceId` and committing a
391
+ vertex that points at the new bytes.
392
+
393
+ ### `self-hkdf-v1` — fully private
394
+
395
+ The simplest path is entirely out of band: seal before ingestion, unseal after
396
+ retrieval. Fangorn never sees plaintext or a key — it commits the ciphertext like any
397
+ other payload. No worker, no settlement, no R2 involved.
398
+
399
+ ```ts
400
+ import { sealSelf, unsealSelf, GADGET_SELF_HKDF_V1 } from "@fangorn-network/sdk";
401
+ import { keccak256, stringToBytes, hexToBytes, bytesToHex } from "viem";
402
+
403
+ const ownSecret = hexToBytes(privateKey); // your own 32 bytes
404
+ const resourceId = keccak256(stringToBytes("rusty-anchor:secret-msg"));
405
+
406
+ const ciphertext = sealSelf(
407
+ new TextEncoder().encode("the eagles are coming"),
408
+ ownSecret,
409
+ resourceId,
410
+ );
411
+
412
+ // commit the opaque bytes like anything else
413
+ await fangorn.upload("rusty-anchor", {
414
+ gadget: GADGET_SELF_HKDF_V1,
415
+ resourceId,
416
+ ciphertext: bytesToHex(ciphertext),
417
+ }, "secret-msg");
418
+
419
+ // later, after `read` / `inspectNamespace` hands the payload back:
420
+ const plaintext = unsealSelf(hexToBytes(stored.ciphertext), ownSecret, stored.resourceId);
421
+ ```
422
+
423
+ ### `worker-usdc-v1` — settlement-gated
424
+
425
+ For paid or conditionally-readable data, seal to the **access worker's** static X25519
426
+ public key and hand the ciphertext to the worker, which stores the opaque bytes in R2
427
+ (never IPFS — a large, frequently-fetched ciphertext shouldn't burn public gateway
428
+ egress). `encryptAndUpload` does both and returns a **handle**:
429
+
430
+ ```ts
431
+ import { encryptAndUpload, GADGET_WORKER_USDC_V1 } from "@fangorn-network/sdk";
432
+
433
+ const handle = await encryptAndUpload({
434
+ gadget: GADGET_WORKER_USDC_V1,
435
+ plaintext: new TextEncoder().encode("the full dataset"),
436
+ resourceId,
437
+ workerPubkey, // the access worker's static X25519 key (32 bytes)
438
+ storage: {
439
+ workerUrl: process.env.ACCESS_WORKER_URL!,
440
+ authToken: process.env.ACCESS_WORKER_TOKEN!,
441
+ contentType: "application/octet-stream",
442
+ },
443
+ });
444
+ ```
445
+
446
+ The handle is what you commit in place of the plaintext value — the engine treats it
447
+ as an ordinary opaque object in the vertex payload:
448
+
449
+ ```jsonc
450
+ {
451
+ "@type": "handle",
452
+ "objectKey": "…", // R2 object key
453
+ "workerUrl": "https://access-worker.example.workers.dev",
454
+ "encryption": {
455
+ "gadget": "worker-usdc-v1",
456
+ "resourceId": "0x…", // Settlement Registry key + HKDF binding
457
+ "ciphertextHash": "0x…", // sha256 of the sealed bytes
458
+ "workerPubkey": "0x…", // worker-usdc-v1 only
459
+ },
460
+ }
461
+ ```
462
+
463
+ ### Reading a handle
464
+
465
+ Both gadgets resolve through the worker's `POST /access`. `decryptHandle` signs the
466
+ request (the worker recovers the signer's address and checks the Settlement Registry
467
+ for `resourceId`), fetches the bytes, and returns plaintext:
468
+
469
+ ```ts
470
+ import { decryptHandle } from "@fangorn-network/sdk";
471
+
472
+ const plaintext = await decryptHandle({
473
+ handle,
474
+ signer, // any viem LocalAccount / WalletClient — the address settlement is checked for
475
+ nullifier, // per-read nullifier (replay / anonymity)
476
+ // ownSecret, // self-hkdf-v1 only
477
+ });
478
+ ```
479
+
480
+ - **`self-hkdf-v1`** — the resource is priced 0, so any signed request passes; the bytes
481
+ come back *still sealed*, are checked against `ciphertextHash`, and are unsealed
482
+ locally with `ownSecret`.
483
+ - **`worker-usdc-v1`** — the worker streams bytes only once the signer has settled,
484
+ having unsealed with its own key; the bytes arrive as plaintext.
485
+
486
+ `buildAccessRequest` / `accessMessageHash` are exported if you want to drive the
487
+ `/access` endpoint yourself, and `SettlementRegistryClient` (`isSettled`, `getPrice`)
488
+ reads the settlement rail directly.
489
+
490
+ **Trust model.** For `worker-usdc-v1` the access worker is the "somewhat trusted" party:
491
+ it holds the unsealing key and sees plaintext at release time. That is deliberate for
492
+ v1 — no TEE, no threshold network. Swapping in a stronger backend later is a *new
493
+ gadget* behind the same handle shape, so committed data doesn't change form.
494
+ `self-hkdf-v1` trusts nobody: the worker is dumb storage and never holds a key.
495
+
496
+ ---
497
+
345
498
  ## Contracts
346
499
 
347
500
  ### Arbitrum Sepolia
@@ -385,7 +538,9 @@ The publisher must be registered (`fangorn register`, or `registry.register()`)
385
538
 
386
539
  ## Limitations / Future Work
387
540
 
388
- - Access-controlled (encrypted) fields and the purchase → claim → fetch settlement flow are being built on this registry — not available this release.
541
+ - Sealed fields are live (`self-hkdf-v1`, `worker-usdc-v1`), but which fields to seal is expressed per-call at stage time — there is no schema-level `sealedFields` hint yet, and no CLI command for sealing.
542
+ - The SDK reads the settlement rail (`isSettled` / `getPrice`); the pay/settle **write** path is a separate payment rail and is not modeled here.
543
+ - `worker-usdc-v1` trusts the access worker with the unsealing key. A TEE- or threshold-backed replacement would ship as a new gadget, and the on-chain gadget registry (`gadget → resolver`) is still future work.
389
544
  - Vertex/edge schema validation is client-side only — no on-chain enforcement.
390
545
  - Push authorization is client-side in this release; on-chain write policies and non-fast-forward rejection are planned.
391
546
  - Reads target one publisher's namespace at a time; cross-publisher discovery is a higher layer.
package/lib/cli/cli.js CHANGED
@@ -60,7 +60,10 @@ function getFangorn() {
60
60
  const storage = cfg.pinataJwt ? { pinata: {
61
61
  jwt: cfg.pinataJwt,
62
62
  gateway: cfg.pinataGateway
63
- } } : { signedUrl: { workerUrl: cfg.signedUrlWorkerUrl } };
63
+ } } : { signedUrl: {
64
+ workerUrl: cfg.signedUrlWorkerUrl,
65
+ gateway: cfg.pinataGateway
66
+ } };
64
67
  _fangorn = Fangorn.create({
65
68
  privateKey: cfg.privateKey,
66
69
  storage,
@@ -184,7 +187,7 @@ program.command("repo").description("Repository operations").command("init").des
184
187
  const s = spinner();
185
188
  s.start(`Initializing namespace "${namespace}"...`);
186
189
  const result = await fangorn.initRepo(namespace);
187
- const head = result.alreadyInitialized ? await fangorn.onChainTip(owner) : result.commitCid;
190
+ const head = result.alreadyInitialized ? await fangorn.onChainTip(owner, namespace) : result.commitCid;
188
191
  const repo = LocalRepo.init({
189
192
  namespace,
190
193
  owner,
@@ -238,12 +241,13 @@ program.command("commit").description("Snapshot a namespace's vertices/edges int
238
241
  });
239
242
  program.command("push").description("Settle the local tip commit as the on-chain state root (the permissioned step)").option("--force", "Push even if it does not fast-forward the on-chain tip").action(async (options) => {
240
243
  try {
241
- const head = LocalRepo.open().head();
244
+ const repo = LocalRepo.open();
245
+ const head = repo.head();
242
246
  if (!head) throw new Error("nothing to push — no commits yet");
243
247
  const fangorn = getFangorn();
244
248
  const s = spinner();
245
249
  s.start("Pushing...");
246
- const { txHash, onChainTip } = await fangorn.push(head, { force: options.force });
250
+ const { txHash, onChainTip } = await fangorn.push(repo.namespace(), head, { force: options.force });
247
251
  s.stop();
248
252
  console.log(`Tx: ${txHash}`);
249
253
  console.log(`Tip: ${onChainTip}`);
@@ -258,7 +262,7 @@ program.command("status").description("Compare the local tip with the on-chain t
258
262
  const repo = LocalRepo.open();
259
263
  const fangorn = getFangorn();
260
264
  const localHead = repo.head();
261
- const onChainTip = await fangorn.onChainTip(repo.owner());
265
+ const onChainTip = await fangorn.onChainTip(repo.owner(), repo.namespace());
262
266
  const state = localHead === onChainTip ? "up to date" : localHead && !onChainTip ? "local commits not yet pushed" : localHead !== onChainTip ? "local tip differs from on-chain tip (push to fast-forward)" : "no local commits";
263
267
  console.log(`Namespace: ${repo.namespace()}`);
264
268
  console.log(`Owner: ${repo.owner()}`);
@@ -316,7 +320,7 @@ program.command("clone").description("Track an existing on-chain namespace by re
316
320
  const fangorn = getFangorn();
317
321
  const s = spinner();
318
322
  s.start(`Resolving on-chain tip for ${owner}...`);
319
- const tip = await fangorn.onChainTip(owner);
323
+ const tip = await fangorn.onChainTip(owner, namespace);
320
324
  const repo = LocalRepo.init({
321
325
  namespace,
322
326
  owner,
@@ -397,7 +401,7 @@ program.command("read").description("List every vertex and edge committed under
397
401
  namespace = namespace ?? repo.namespace();
398
402
  owner = owner ?? repo.owner();
399
403
  }
400
- const [head, contents] = await Promise.all([fangorn.onChainTip(owner), fangorn.engine.listNamespace(namespace, owner)]);
404
+ const [head, contents] = await Promise.all([fangorn.onChainTip(owner, namespace), fangorn.engine.listNamespace(namespace, owner)]);
401
405
  const out = {
402
406
  owner,
403
407
  namespace,
@@ -411,15 +415,16 @@ program.command("read").description("List every vertex and edge committed under
411
415
  process.exit(1);
412
416
  }
413
417
  });
414
- program.command("reset").description("DANGER!: reset your on-chain head to zero (abandons all prior commits)").action(async () => {
415
- const confirmFirst = await confirm({ message: "Are you sure? Your onchain head will reset to 0x0000..." });
418
+ program.command("reset").description("DANGER!: reset this namespace's on-chain head to zero (abandons all prior commits)").action(async () => {
419
+ const namespace = LocalRepo.open().namespace();
420
+ const confirmFirst = await confirm({ message: `Are you sure? The on-chain head for "${namespace}" will reset to 0x0000...` });
416
421
  handleCancel(confirmFirst);
417
422
  if (!confirmFirst) {
418
423
  console.log("Reset aborted.");
419
424
  process.exit(0);
420
425
  }
421
- await getFangorn().reset();
422
- console.log("On-chain head reset to zero. `repo init` will now start fresh.");
426
+ await getFangorn().reset(namespace);
427
+ console.log(`On-chain head for "${namespace}" reset to zero. \`repo init\` will now start fresh.`);
423
428
  process.exit(0);
424
429
  });
425
430
  program.parse();
@@ -1,5 +1,5 @@
1
1
  import "./cli.js";
2
- import * as viem89 from "viem";
2
+ import * as viem0 from "viem";
3
3
 
4
4
  //#region src/cli/index.d.ts
5
5
  declare const getChain: (chainStr: string) => {
@@ -35,17 +35,17 @@ declare const getChain: (chainStr: string) => {
35
35
  testnet: true;
36
36
  custom?: Record<string, unknown> | undefined;
37
37
  extendSchema?: Record<string, unknown> | undefined;
38
- fees?: viem89.ChainFees<undefined> | undefined;
38
+ fees?: viem0.ChainFees<undefined> | undefined;
39
39
  formatters?: undefined;
40
- prepareTransactionRequest?: ((args: viem89.PrepareTransactionRequestParameters, options: {
40
+ prepareTransactionRequest?: ((args: viem0.PrepareTransactionRequestParameters, options: {
41
41
  phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
42
- }) => Promise<viem89.PrepareTransactionRequestParameters>) | [fn: ((args: viem89.PrepareTransactionRequestParameters, options: {
42
+ }) => Promise<viem0.PrepareTransactionRequestParameters>) | [fn: ((args: viem0.PrepareTransactionRequestParameters, options: {
43
43
  phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
44
- }) => Promise<viem89.PrepareTransactionRequestParameters>) | undefined, options: {
44
+ }) => Promise<viem0.PrepareTransactionRequestParameters>) | undefined, options: {
45
45
  runAt: readonly ("beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters")[];
46
46
  }] | undefined;
47
- serializers?: viem89.ChainSerializers<undefined, viem89.TransactionSerializable> | undefined;
48
- verifyHash?: ((client: viem89.Client, parameters: viem89.VerifyHashActionParameters) => Promise<viem89.VerifyHashActionReturnType>) | undefined;
47
+ serializers?: viem0.ChainSerializers<undefined, viem0.TransactionSerializable> | undefined;
48
+ verifyHash?: ((client: viem0.Client, parameters: viem0.VerifyHashActionParameters) => Promise<viem0.VerifyHashActionReturnType>) | undefined;
49
49
  };
50
50
  declare const handleCancel: (value: unknown) => void;
51
51
  declare const selectChain: () => Promise<{
@@ -81,17 +81,17 @@ declare const selectChain: () => Promise<{
81
81
  testnet: true;
82
82
  custom?: Record<string, unknown> | undefined;
83
83
  extendSchema?: Record<string, unknown> | undefined;
84
- fees?: viem89.ChainFees<undefined> | undefined;
84
+ fees?: viem0.ChainFees<undefined> | undefined;
85
85
  formatters?: undefined;
86
- prepareTransactionRequest?: ((args: viem89.PrepareTransactionRequestParameters, options: {
86
+ prepareTransactionRequest?: ((args: viem0.PrepareTransactionRequestParameters, options: {
87
87
  phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
88
- }) => Promise<viem89.PrepareTransactionRequestParameters>) | [fn: ((args: viem89.PrepareTransactionRequestParameters, options: {
88
+ }) => Promise<viem0.PrepareTransactionRequestParameters>) | [fn: ((args: viem0.PrepareTransactionRequestParameters, options: {
89
89
  phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
90
- }) => Promise<viem89.PrepareTransactionRequestParameters>) | undefined, options: {
90
+ }) => Promise<viem0.PrepareTransactionRequestParameters>) | undefined, options: {
91
91
  runAt: readonly ("beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters")[];
92
92
  }] | undefined;
93
- serializers?: viem89.ChainSerializers<undefined, viem89.TransactionSerializable> | undefined;
94
- verifyHash?: ((client: viem89.Client, parameters: viem89.VerifyHashActionParameters) => Promise<viem89.VerifyHashActionReturnType>) | undefined;
93
+ serializers?: viem0.ChainSerializers<undefined, viem0.TransactionSerializable> | undefined;
94
+ verifyHash?: ((client: viem0.Client, parameters: viem0.VerifyHashActionParameters) => Promise<viem0.VerifyHashActionReturnType>) | undefined;
95
95
  }>;
96
96
  declare function parseGadgetArg(raw: string): {
97
97
  type: string;