@fangorn-network/sdk 2026.10.28 → 2026.11.3-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.
Files changed (65) hide show
  1. package/README.md +36 -658
  2. package/lib/cli/cli.js +30 -356
  3. package/lib/cli/index.d.ts +1 -4
  4. package/lib/cli/index.js +2 -20
  5. package/lib/config.d.ts +163 -226
  6. package/lib/config.js +8 -35
  7. package/lib/contracts/data-registry/abi.d.ts +206 -6
  8. package/lib/contracts/data-registry/abi.js +236 -7
  9. package/lib/contracts/data-registry/index.d.ts +126 -2
  10. package/lib/contracts/data-registry/index.js +174 -1
  11. package/lib/contracts/index.d.ts +5 -8
  12. package/lib/contracts/index.js +4 -7
  13. package/lib/contracts/logs.d.ts +1 -1
  14. package/lib/contracts/logs.js +1 -1
  15. package/lib/contracts/{membership-registry → settlement-registry}/abi.d.ts +288 -637
  16. package/lib/contracts/{membership-registry → settlement-registry}/abi.js +326 -712
  17. package/lib/contracts/settlement-registry/index.d.ts +141 -0
  18. package/lib/contracts/settlement-registry/index.js +209 -0
  19. package/lib/crypto/aes.d.ts +2 -2
  20. package/lib/crypto/aes.js +4 -4
  21. package/lib/crypto/encryption.d.ts +8 -109
  22. package/lib/crypto/encryption.js +16 -114
  23. package/lib/crypto/paid.d.ts +104 -0
  24. package/lib/crypto/paid.js +147 -0
  25. package/lib/engine/index.d.ts +23 -12
  26. package/lib/engine/index.js +68 -29
  27. package/lib/engine/records.d.ts +4 -7
  28. package/lib/engine/records.js +6 -6
  29. package/lib/engine/test-helpers.d.ts +2 -3
  30. package/lib/engine/test-helpers.js +7 -5
  31. package/lib/erc8004.js +1 -4
  32. package/lib/fangorn.d.ts +64 -95
  33. package/lib/fangorn.js +106 -164
  34. package/lib/feed.d.ts +7 -8
  35. package/lib/feed.js +7 -8
  36. package/lib/index.d.ts +10 -14
  37. package/lib/index.js +9 -13
  38. package/lib/providers/storage/signed-url.d.ts +2 -10
  39. package/lib/providers/storage/signed-url.js +4 -14
  40. package/lib/providers/storage/types.d.ts +1 -1
  41. package/lib/providers/storage/utils.js +5 -3
  42. package/lib/test/key-server.d.ts +12 -0
  43. package/lib/test/key-server.js +30 -0
  44. package/lib/test/mem-registry.d.ts +14 -19
  45. package/lib/test/mem-registry.js +44 -37
  46. package/lib/test/sdk-suite.d.ts +1 -4
  47. package/lib/test/sdk-suite.js +16 -87
  48. package/lib/test/testbed.d.ts +5204 -5214
  49. package/lib/test/testbed.js +29 -56
  50. package/lib/types/index.d.ts +6 -11
  51. package/package.json +1 -4
  52. package/lib/contracts/app-registry/abi.d.ts +0 -1306
  53. package/lib/contracts/app-registry/abi.js +0 -1493
  54. package/lib/contracts/app-registry/index.d.ts +0 -200
  55. package/lib/contracts/app-registry/index.js +0 -325
  56. package/lib/contracts/membership-registry/index.d.ts +0 -79
  57. package/lib/contracts/membership-registry/index.js +0 -104
  58. package/lib/contracts/types.d.ts +0 -8
  59. package/lib/contracts/types.js +0 -10
  60. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +0 -1
  61. package/lib/harness/examples/hackmd/build-markdown-graph.js +0 -17
  62. package/lib/harness/index.d.ts +0 -58
  63. package/lib/harness/index.js +0 -73
  64. package/lib/registry.d.ts +0 -118
  65. package/lib/registry.js +0 -184
package/README.md CHANGED
@@ -1,694 +1,72 @@
1
1
  # Fangorn SDK
2
2
 
3
- The Fangorn SDK is a decentralized "git for data" protocol. It follows an app <> publisher paradigm. An "app" is synonymous with gauranteed data availability and a 'view' of its underlying data. For publishers, it lets you cryptographically commit to to a version controlled "repo", which is data stored as a Merkle search tree in IPFS. Published data exists independently of an app, and apps emerge on top of data that they sponsor (pin).
4
-
5
- A **repo** belongs to its publisher, keyed **`publisher : repo`**. Its state is a map of **records** (`{ id, type, payload }`, content-addressed), and its head is the digest of the latest commit block. Any wallet can update its own repos; updating a head is a compare-and-swap on the parent (i.e. a git ref update), and an update names no app.
6
-
7
- An **app** is sponsored storage. Its owner accepts publishers; an accepted publisher uploads with the app's storage, and the app presents that publisher's repos at their latest heads.
8
-
9
- **Version Control**
10
-
11
- Repos are versioned like git. Each update is a **commit** that points at its parent (previous state) and at a single **CAR file** (a packfile) holding only the blocks that were introduced in the commit. The on-chain data registry stores the head of each repo, with full history living in IPFS. Full history is reconstructible from the on-chain head without an indexer.
12
-
13
- - `commit` (local) builds the new state in memory and persists it in two uploads, one CAR (the data) + one small commit block.
14
- - `push` (remote) moves the on-chain head to the latest staged commit
15
-
16
- > Since commits and records are native IPLD links, the DAG (directed acyclic graph) is easily 'diffable' and verifiable from the head stored on-chain, though it is not easily queryable (see: [quickbeam](https://github.com/fangorn-network/quickbeam))
17
-
18
- **Storage**
19
-
20
- Repos are stored in IPFS. The SDK currently expects Pinata to be used to ensure data availability, which will be relaxed in the future.
21
-
22
- #### What it is not
23
-
24
- This is not a graph database. There is no query langauge here and there is no native indexer.
25
-
26
- ## Supported Networks
27
- ---
28
-
29
- ## Installation
3
+ Fangorn is git for published data. You publish **repos** of records, and you can make any field paid. Each repo's head is anchored on chain and its history lives in IPFS. Anyone can read, verify, diff, subscribe to, or buy from your repos without asking you, an indexer, or a platform.
30
4
 
31
5
  ```sh
32
6
  npm i @fangorn-network/sdk
33
7
  ```
34
8
 
35
- ---
36
-
37
- ## CLI Quickstart
38
-
39
- ```sh
40
- npm i -g @fangorn-network/sdk
41
- fangorn init
42
- ```
43
-
44
- `fangorn init` prompts for:
45
-
46
- - Wallet private key
47
- - Pinata JWT + gateway URL (content + commit-object storage; both optional)
48
- - Access-gating worker URL (optional — stores sealed ciphertext and enforces the read gate)
49
- - Presigned-URL worker URL (optional — issues short-lived Pinata upload URLs so no JWT is needed)
50
-
51
- Config is written to `~/.fangorn/config.json`.
52
-
53
- You can also configure via environment variables (these take precedence over the config file):
54
-
55
- ```sh
56
- ETH_PRIVATE_KEY=0x...
57
- PINATA_JWT=...
58
- PINATA_GATEWAY=https://your-gateway.mypinata.cloud
59
- CHAIN_NAME=baseSepolia # the default; or arbitrumSepolia
60
- SIGNED_URL_WORKER_URL=https://pinata-url-provider.your-subdomain.workers.dev # optional; defaults to the network's hosted worker
61
- ```
62
-
63
- > 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.
64
-
65
- ### Check your wallet
66
-
67
- ```sh
68
- fangorn wallet show # address, public key, balance, network, current app
69
- fangorn wallet show --reveal # also prints the PRIVATE key — it grants full control
70
- ```
71
-
72
- The private key is never printed without `--reveal`: terminal scrollback, shell
73
- logs and screen shares all outlive the command.
74
-
75
- ### Pick an app
76
-
77
- Publishing needs no app: any wallet updates its own repos, and an update names
78
- no app. **An app is sponsored storage for the publishers it accepts**: its owner
79
- accepts a publisher, the app pays for that publisher's uploads, and it includes
80
- their repos at their latest heads, less what the owner withdraws
81
- (`registry.exclude`).
82
-
83
- ```sh
84
- fangorn set-app my-app # persists the app; --app <name-or-id> overrides per command
85
- fangorn app info # owner, subscription, and where you stand in it
86
- fangorn app claim # claim it, if nobody owns it yet (irreversible; pays the subscription)
87
- ```
88
-
89
- The protocol admin can ban a wallet network-wide: it can't claim an app or be
90
- accepted into one, and no app stores or presents it.
91
-
92
- **An app is a storage subscription** (ERC-5643; the app is a token that cannot
93
- be transferred). `fangorn app claim` pays one period of the subscription fee in
94
- USDC (the client approves exactly the fee for you), and `fangorn app renew` pays
95
- the next once less than a period is left. An expired app stores and presents nothing
96
- until it is renewed. **Apps provide storage**: you upload relative to
97
- an app, and hosted uploads (`storage: { signedUrl: {} }`, through the network's
98
- hosted worker, `config.signedUrlWorker`) are billed to the client's app, which must have accepted you. There is no app-less hosted upload — with no
99
- app, bring your own Pinata (`{ pinata }`) and pin your own data. A publisher that
100
- pays for its own storage claims a one-member app.
101
-
102
- **The owner accepts publishers.** `fangorn app accept <address>` is the whole
103
- membership: no invitation, terms or join fee. The owner is their own first
104
- publisher.
105
-
106
- Owning an app comes with its own commands:
107
-
108
- ```sh
109
- fangorn app accept <address> # accept a publisher: the app stores and includes its data
110
- fangorn app suspend <address> # suspend a member from THIS app only
111
- fangorn app reinstate <address>
112
- fangorn app renew # pay for the next period
113
- fangorn app cancel # end the subscription now, no refund
114
- fangorn app agent --access-worker <url> # register the worker's agent card with ERC-8004 (or pass a card URL)
115
- fangorn app rename <name> # give the app a new name; the old ones keep working
116
- ```
117
-
118
- **Renaming moves nothing.** `fangorn app rename` (SDK: `fangorn.renameApp(name)`)
119
- makes the new name's id an alias of the id the app was claimed under, its
120
- *canonical* id. Publishers, exclusions, the subscription and the token carry on,
121
- and every name the app has gone by still resolves to it and stays the owner's:
122
- nobody can claim one, and clients still using an old name keep working. The token
123
- id, the app listings and the contract's events keep the canonical id;
124
- `getAppRegistry().canonicalAppId()` and `.currentAppId()` translate between them,
125
- and `fangorn app info` shows both when they differ. The CLI saves the new name to
126
- its config file, unless the app came from `--app` or `FANGORN_APP_ID`, which you
127
- update yourself.
128
-
129
- ### Track a repo
130
-
131
- `repo init` creates the repo with an empty first commit, pushes it, and starts tracking it in a local `.fangorn/` pointer file (just a HEAD ref — there is no local object store; commit objects and their CARs live in IPFS).
132
-
133
- ```sh
134
- # Create the repo on-chain (no-op if it already exists) and track it here
135
- fangorn repo init rusty-anchor
136
- ```
137
-
138
- ### Commit → push
139
-
140
- `commit` puts and deletes a repo's records in a new commit (one CAR upload to IPFS, advances your local HEAD) — it does **not** touch the chain. `push` fast-forwards the on-chain head to your local tip.
141
-
142
- ```sh
143
- # Stage records into a new local commit — does NOT push
144
- fangorn commit records.json -m "initial import"
145
-
146
- # Settle the local tip on-chain (permission + fast-forward checked here)
147
- fangorn push
148
- fangorn push --force # push even if it doesn't fast-forward the on-chain tip
149
- ```
150
-
151
- `records.json` lists the records to put (an `id` is generated when omitted, and an existing `id` is overwritten) and the ids to delete:
152
-
153
- ```json
154
- {
155
- "records": [
156
- { "id": "t1", "type": "track", "payload": { "title": "Locura", "artist": "Alice" } },
157
- { "id": "a1", "type": "artist", "payload": { "name": "Alice" } }
158
- ],
159
- "deletes": ["t0"]
160
- }
161
- ```
162
-
163
- Each commit records its parent, so history is real and walkable. By default a commit is **additive** (the staged records join the repo's existing contents); pass `--replace` for snapshot semantics, where the file _is_ the repo's new state and anything omitted is removed — earlier history is retained either way. Blocks are content-addressed, so unchanged records are reused byte-for-byte across commits and never re-uploaded.
164
-
165
- ### Builders
166
-
167
- Turning your source data into records is application logic, but the SDK ships a small **harness** for the common "a directory of files → records" case, exported from the package root:
168
-
169
- ```ts
170
- import { buildAssetGraph, extractMarkdownLinks } from "@fangorn-network/sdk";
171
-
172
- // One processor per file extension. Return the vertex tag/payload and the
173
- // ids this file links to; buildAssetGraph wires the edges (rel: "links"),
174
- // dropping self-links and links to files that don't exist.
175
- const { vertices } = buildAssetGraph("./docs", {
176
- processors: {
177
- ".md": (file) => ({
178
- tag: "note",
179
- payload: { title: file.nameNoExt, body: file.readText() },
180
- links: extractMarkdownLinks(file.readText()), // markdown links + [[wikilinks]]
181
- }),
182
- },
183
- });
184
-
185
- await fangorn.commit({
186
- repo: "rusty-anchor",
187
- message: "import docs",
188
- records: vertices.map((v) => ({ id: v.id, type: v.tag, payload: v.payload })),
189
- });
190
- ```
191
-
192
- Each `id` is the filename without extension. The harness also returns the links between files as `edges`; records have no edges, so keep links you need in the payload. For anything that isn't "files in a folder," build the records yourself and pass them straight to `commit` / `uploadBatch` — the harness is a convenience, not a requirement.
193
-
194
- ### Inspect
195
-
196
- ```sh
197
- fangorn status # local tip vs on-chain tip
198
- fangorn log # walk commit history from the tip (newest first)
199
- fangorn log -n 5 # limit
200
- fangorn show # the tip commit + what it changed vs its parent
201
- fangorn show <commitCid> # a specific commit
202
-
203
- # List every record in a repo, as JSON
204
- fangorn read # defaults to the current repo + owner
205
- fangorn read rusty-anchor --owner 0x... --pretty
206
- ```
207
-
208
- ### Clone
209
-
210
- Reconstruct tracking of a published repo from its on-chain head alone. History and contents are then fetched on demand from IPFS.
211
-
212
- ```sh
213
- fangorn clone <owner> rusty-anchor
214
- fangorn clone <owner> rusty-anchor --dir ./somewhere
215
- ```
216
-
217
- ### Subscribe (light client)
218
-
219
- Watch a repo for on-chain updates and stream the diffs — **no subgraph, no
220
- indexer**. Each `publisher:repo` pair is its own timeline, and the registry's
221
- `Updated` event indexes both, so this reads exactly that timeline straight from
222
- the RPC node and, for each new head, diffs the repo's records against the
223
- previous one. Under an app, only what the app presents is emitted. Each push's
224
- blocks arrive as one CAR download, resolved from IPFS on demand.
225
-
226
- ```sh
227
- # Watch the current repo; each change is one JSON line on stdout.
228
- fangorn subscribe
229
-
230
- # Watch any publisher's repo explicitly.
231
- fangorn subscribe rusty-anchor --owner 0x...
232
-
233
- # Feed an embeddings/index builder directly.
234
- fangorn subscribe rusty-anchor --owner 0x... | my-index-builder
235
- ```
236
-
237
- Each emitted line is a repo change:
238
-
239
- ```jsonc
240
- {
241
- "repo": "rusty-anchor",
242
- "owner": "0x...",
243
- "commitCid": "bafy...", // the new on-chain head
244
- "oldRoot": "0x...",
245
- "newRoot": "0x...",
246
- "blockNumber": "12345678", // persist this to resume
247
- "puts": [
248
- { "id": "t1", "cid": "bafy...", "type": "track", "payload": { "title": "Locura" } },
249
- ],
250
- "deletes": ["t0"],
251
- }
252
- ```
253
-
254
- `fangorn subscribe --all` watches the whole app instead (every presented publisher and repo); a repo name or `--owner` narrows it.
9
+ ## The model
255
10
 
256
- **Resumability.** The last processed block is saved to
257
- `.fangorn/subscribe-<owner>-<repo>.json` after each change, so restarting
258
- replays only what you missed (via `eth_getLogs`) before going live. Override or
259
- reset:
11
+ - **Publisher.** A wallet address. Publishers own their repos, and nobody admits or approves them.
12
+ - **Repo.** Keyed `publisher : repo`. Its state is a map of **records** `{ id, type, payload }`, stored as a content-addressed Merkle search tree.
13
+ - **Commit.** Each commit points at its parent and at one CAR file holding the blocks it introduced. History can be walked and diffed from the head alone.
14
+ - **Push.** Moves the on-chain head with a compare-and-swap on the parent, like a git ref update. The registry stores only heads.
15
+ - **Paid fields.** A publisher seals a field and signs a price for it in the record. Buyers pay through the SettlementRegistry, and a key server releases the key.
16
+ - **Apps are just repos.** An app is a publisher's repo of records that **cite** other publishers' records at named heads. It selects and arranges data, but it never holds or gates that data. When a citation leads to a sale, the app's publisher address receives the referral share.
260
17
 
261
- ```sh
262
- fangorn subscribe --from-block 12000000 # replay from a specific block
263
- fangorn subscribe --from-start # replay the repo's full history
264
- ```
265
-
266
- Without a saved cursor, subscribe starts **live from the current tip** — seed
267
- your initial index from `fangorn read` first, then subscribe for the deltas.
268
-
269
- ---
18
+ What Fangorn is not: it is not a database. It has no query language and no indexer. You build those on top with `subscribe` (see [westmarch](https://github.com/fangorn-network/westmarch)).
270
19
 
271
- ## SDK Usage
272
-
273
- ### Initialization
274
-
275
- `Fangorn.create` is synchronous. Pass Pinata storage for any commit/read operation. Supply either a `privateKey` (the SDK builds the wallet client for you) or your own viem `walletClient`.
20
+ ## Quickstart (SDK)
276
21
 
277
22
  ```ts
278
- import { Fangorn, FangornConfig } from "@fangorn-network/sdk";
23
+ import { Fangorn } from "@fangorn-network/sdk";
279
24
 
280
25
  const fangorn = Fangorn.create({
281
26
  privateKey: "0x...",
282
- storage: {
283
- pinata: {
284
- jwt: process.env.PINATA_JWT!,
285
- gateway: process.env.PINATA_GATEWAY!,
286
- },
287
- },
288
- config: FangornConfig, // the default, Base Sepolia; or ArbitrumSepoliaConfig
289
- appId: "my-app", // optional for reads (no app: each publisher's latest head); hosted uploads need one
27
+ storage: { signedUrl: {} }, // hosted uploads on Base Sepolia; or { pinata: { jwt, gateway } }
290
28
  });
291
29
 
292
- // The app stores and presents your repos once its owner accepts this wallet
293
- // (`apps.acceptPublisher`). A non-member's update still lands; the app just
294
- // presents nothing of it.
295
- const apps = fangorn.getAppRegistry();
296
- await apps.canPublish(fangorn.getAddress());
297
- ```
298
-
299
- The storage paywall lives on the same client, because an app is its
300
- subscription: `apps.subscriptionFee()`, `apps.expiresAt()`,
301
- `apps.renewSubscription()`, `apps.cancelSubscription()`, and
302
- `apps.access(publisher)` — the `{ canPublish, owner, expiresAt }` the upload gate
303
- reads. The contract enforces the expiry itself: `canPublish` is false once it
304
- has passed.
305
-
306
- `fangorn.getMembershipRegistry()` (consumer access to an app's paid records)
307
- hangs off the same object. It takes the app id per call, so `setAppId`
308
- deliberately leaves it alone.
309
-
310
- ### Repos & the git-native flow
311
-
312
- `initRepo` creates a repo with an empty first commit (idempotent). Then split building from settling:
313
- `commit` writes a commit object (durable in IPFS, HEAD not yet on-chain), and
314
- `push` fast-forwards the on-chain head to it.
315
-
316
- ```ts
317
- // Create the repo (no-op if it already exists)
318
30
  await fangorn.initRepo("rusty-anchor");
319
- let tip = await fangorn.onChainTip(fangorn.getAddress(), "rusty-anchor");
31
+ await fangorn.uploadBatch("rusty-anchor", [
32
+ { id: "t1", type: "track", payload: { title: "Locura", artist: "Alice" } },
33
+ ]);
320
34
 
321
- const c1 = await fangorn.commit({
322
- repo: "rusty-anchor",
323
- parent: tip!,
324
- message: "initial import",
325
- records: [
326
- { id: "t1", type: "track", payload: { title: "Locura", artist: "Alice" } },
327
- { id: "a1", type: "artist", payload: { name: "Alice" } },
328
- ],
329
- });
330
- await fangorn.push("rusty-anchor", c1.commitCid);
331
-
332
- // A follow-up commit builds on the previous one
333
- const c2 = await fangorn.commit({
334
- repo: "rusty-anchor",
335
- parent: c1.commitCid,
336
- message: "add a track, drop the artist",
337
- records: [{ id: "t2", type: "track", payload: { title: "Otra", artist: "Alice" } }],
338
- deletes: ["a1"],
339
- });
340
- await fangorn.push("rusty-anchor", c2.commitCid); // the chain rejects it unless the parent is the current head
341
- ```
342
-
343
- ### History, diff & read
344
-
345
- Walk history from the on-chain tip (IPFS only, no indexer), and read the current contents:
346
-
347
- ```ts
348
- const tip = await fangorn.onChainTip(fangorn.getAddress(), "rusty-anchor");
349
-
350
- // Walk commits, newest first
351
- for await (const c of fangorn.log(tip!)) {
352
- console.log(c.cid, c.message);
353
- }
354
-
355
- // What a commit changed vs. its parent ({ puts, deletes })
356
- const diff = await fangorn.show(tip!);
357
-
358
- // Every record currently in one of your repos
359
- const { records } = await fangorn.inspectRepo("rusty-anchor"); // { id, cid, type, payload }[]
360
-
361
- // Someone else's repo, as this client's app presents it
362
- const { tip: head, contents } = await fangorn.readRepo("0x...", "rusty-anchor");
363
- ```
364
-
365
- ### Immediate-write helpers
366
-
367
- For the common "stage and settle in one shot" case, `upload` (one record) and `uploadBatch`
368
- (many records, plus deletes) run the whole commit-and-push atomically:
369
-
370
- ```ts
371
- await fangorn.upload("rusty-anchor", { title: "Locura" }, "track");
372
-
373
- await fangorn.uploadBatch(
374
- "rusty-anchor",
375
- [{ id: "t1", type: "track", payload: { title: "Locura" } }],
376
- ["t0"], // ids to delete
377
- );
378
- ```
379
-
380
- ### Subscribe (light client)
381
-
382
- `subscribe` is an async generator over one repo's changes. It optionally
383
- replays from a block cursor (`fromBlock`) and then watches live until the
384
- `AbortSignal` fires. Each change carries `blockNumber` — persist it to resume.
385
-
386
- ```ts
387
- const controller = new AbortController();
388
-
389
- for await (const change of fangorn.subscribe({
390
- repo: "rusty-anchor",
391
- owner: "0x...", // defaults to your own address
392
- fromBlock: savedCursor, // omit to start live from the current tip
393
- signal: controller.signal,
394
- })) {
395
- for (const r of change.puts) index.upsert(r.id, r.payload);
396
- for (const id of change.deletes) index.remove(id);
397
- persistCursor(change.blockNumber);
398
- }
399
- ```
400
-
401
- The pure diff primitive is also exposed on the engine —
402
- `engine.repoDiff(oldRootHex, newRootHex)` — if you want to diff
403
- two arbitrary roots without watching.
404
-
405
- ### Subscribe to a whole app
406
-
407
- Every update lands under `publisher:repo`, and each pair is its own on-chain
408
- timeline. Two publishers — or one publisher's two repos — never contend for the
409
- same compare-and-swap.
35
+ // Anyone, from the head alone:
36
+ const { contents } = await fangorn.readRepo(fangorn.getAddress(), "rusty-anchor");
410
37
 
411
- `subscribeApp` yields the same `RepoChange` values as `subscribe`, from every
412
- publisher the app presents, less its exclusions. With no app it is every update
413
- by anyone:
414
-
415
- ```ts
416
- // Everything the app presents
417
- for await (const change of fangorn.subscribeApp({
418
- signal: controller.signal,
419
- })) {
420
- console.log(change.owner, change.repo, change.puts.length);
38
+ for await (const change of fangorn.subscribe({ repo: "rusty-anchor", owner: fangorn.getAddress() })) {
39
+ console.log(change.puts, change.deletes);
421
40
  }
422
-
423
- // Narrow it: every publisher's "reviews" repo, or one publisher's whole footprint
424
- fangorn.subscribeApp({ repo: "reviews" });
425
- fangorn.subscribeApp({ owner: "0x..." });
426
- ```
427
-
428
- The app is per-client state, not part of the network config — set it when you
429
- create the client, or switch at runtime:
430
-
431
- ```ts
432
- const fangorn = Fangorn.create({ privateKey, storage, appId: "my-app" });
433
- fangorn.setAppId("my-other-app"); // by name, or by 32-byte app id
434
- fangorn.getAppId(); // 0x… — what the registry keys on
435
- ```
436
-
437
- Under an app, reads (`readRepo`, `appRepos`, `subscribe`) are what the app
438
- presents: its members' latest heads (`canPublish`), less its exclusions. With
439
- no app they are each publisher's latest heads.
440
-
441
- Apps live in the AppRegistry, and membership of one is what gets your storage
442
- paid for and your repos presented:
443
-
444
- ```ts
445
- const apps = fangorn.getAppRegistry();
446
-
447
- await apps.registerApp(); // claim it — pays the subscription fee (USDC); you are its first publisher
448
- await apps.acceptPublisher(publisher); // owner: accept a publisher
449
- await apps.setPublisherSuspended(publisher, true); // owner: suspend them from this app
450
- await apps.renewSubscription(); // owner: pay for the next period
451
41
  ```
452
42
 
453
- See the [CLI quickstart](#pick-an-app) for the same flow from the
454
- command line.
455
-
456
- ### Storage
457
-
458
- Fangorn operates on a 'Bring Your Own Storage' basis. Each commit is persisted as
459
- one CAR file (an opaque packfile of the commit's new blocks) plus one small commit
460
- block, pinned to IPFS via Pinata; the chain holds only the 32-byte commit pointer.
461
- The backend never needs to understand IPLD — any blob store can implement the
462
- `MetadataStorage` interface.
463
-
464
- ---
465
-
466
- ## Encryption & gadgets
467
-
468
- Not every field belongs in public IPFS. Fangorn lets you **seal** a value and commit
469
- only an opaque reference to it, keeping the repo — its records, their ids and types, their
470
- addressability — fully public while the payload stays closed.
471
-
472
- A **gadget** names _how_ a value is sealed and _under what condition_ it opens. Two
473
- ship today, both exported from the package root (`@fangorn-network/sdk`):
474
-
475
- | Gadget | Key derivation | Who can open it |
476
- | ---------------- | --------------------------------------------- | ----------------------------------------------------------------------------------- |
477
- | `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. |
478
- | `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. |
479
-
480
- Every key is bound to a 32-byte **`resourceId`**, which doubles as the Settlement
481
- Registry key. The same secret cannot cross-open a different resource, and changing
482
- _who can read_ means re-sealing under a new gadget/`resourceId` and committing a
483
- record that points at the new bytes.
484
-
485
- ### `self-hkdf-v1` — fully private
43
+ ## Quickstart (CLI)
486
44
 
487
- The simplest path is entirely out of band: seal before ingestion, unseal after
488
- retrieval. Fangorn never sees plaintext or a key — it commits the ciphertext like any
489
- other payload. No worker, no settlement, no R2 involved.
490
-
491
- ```ts
492
- import {
493
- sealSelf,
494
- unsealSelf,
495
- GADGET_SELF_HKDF_V1,
496
- } from "@fangorn-network/sdk";
497
- import { keccak256, stringToBytes, hexToBytes, bytesToHex } from "viem";
498
-
499
- const ownSecret = hexToBytes(privateKey); // your own 32 bytes
500
- const resourceId = keccak256(stringToBytes("rusty-anchor:secret-msg"));
501
-
502
- const ciphertext = sealSelf(
503
- new TextEncoder().encode("the eagles are coming"),
504
- ownSecret,
505
- resourceId,
506
- );
507
-
508
- // commit the opaque bytes like anything else
509
- await fangorn.upload(
510
- "rusty-anchor",
511
- {
512
- gadget: GADGET_SELF_HKDF_V1,
513
- resourceId,
514
- ciphertext: bytesToHex(ciphertext),
515
- },
516
- "secret-msg",
517
- );
518
-
519
- // later, after `read` / `inspectRepo` hands the payload back:
520
- const plaintext = unsealSelf(
521
- hexToBytes(stored.ciphertext),
522
- ownSecret,
523
- stored.resourceId,
524
- );
525
- ```
526
-
527
- ### `worker-usdc-v1` — settlement-gated
528
-
529
- For paid or conditionally-readable data, seal to the **access worker's** static X25519
530
- public key and hand the ciphertext to the worker, which stores the opaque bytes in R2
531
- (never IPFS — a large, frequently-fetched ciphertext shouldn't burn public gateway
532
- egress). `encryptAndUpload` does both and returns a **handle**:
533
-
534
- ```ts
535
- import { encryptAndUpload, GADGET_WORKER_USDC_V1 } from "@fangorn-network/sdk";
536
-
537
- const handle = await encryptAndUpload({
538
- gadget: GADGET_WORKER_USDC_V1,
539
- plaintext: new TextEncoder().encode("the full dataset"),
540
- resourceId,
541
- workerPubkey, // the access worker's static X25519 key (32 bytes)
542
- storage: {
543
- workerUrl: process.env.ACCESS_WORKER_URL!,
544
- authToken: process.env.ACCESS_WORKER_TOKEN!,
545
- contentType: "application/octet-stream",
546
- },
547
- });
548
- ```
549
-
550
- The handle is what you commit in place of the plaintext value — the engine treats it
551
- as an ordinary opaque object in the record payload:
552
-
553
- ```jsonc
554
- {
555
- "@type": "handle",
556
- "objectKey": "…", // R2 object key
557
- "workerUrl": "https://access-worker.example.workers.dev",
558
- "encryption": {
559
- "gadget": "worker-usdc-v1",
560
- "resourceId": "0x…", // Settlement Registry key + HKDF binding
561
- "ciphertextHash": "0x…", // sha256 of the sealed bytes
562
- "workerPubkey": "0x…", // worker-usdc-v1 only
563
- },
564
- }
565
- ```
566
-
567
- ### Reading a handle
568
-
569
- Both gadgets resolve through the worker's `POST /access`. `decryptHandle` signs the
570
- request (the worker recovers the signer's address and checks the Settlement Registry
571
- for `resourceId`), fetches the bytes, and returns plaintext:
572
-
573
- ```ts
574
- import { decryptHandle } from "@fangorn-network/sdk";
575
-
576
- const plaintext = await decryptHandle({
577
- handle,
578
- signer, // any viem LocalAccount / WalletClient — the address settlement is checked for
579
- nullifier, // per-read nullifier (replay / anonymity)
580
- // ownSecret, // self-hkdf-v1 only
581
- });
45
+ ```sh
46
+ npm i -g @fangorn-network/sdk
47
+ fangorn init # wallet key, storage → ~/.fangorn/config.json
48
+ fangorn repo init rusty-anchor # create on chain, track in ./.fangorn
49
+ fangorn commit records.json # local commit (IPFS only)
50
+ fangorn push # move the on-chain head
51
+ fangorn subscribe --owner 0x... rusty-anchor # stream diffs as JSON lines
582
52
  ```
583
53
 
584
- - **`self-hkdf-v1`** — the resource is priced 0, so any signed request passes; the bytes
585
- come back _still sealed_, are checked against `ciphertextHash`, and are unsealed
586
- locally with `ownSecret`.
587
- - **`worker-usdc-v1`** — the worker streams bytes only once the signer has settled,
588
- having unsealed with its own key; the bytes arrive as plaintext.
54
+ The [Guide](docs/GUIDE.md) covers the full flow: commit vs push, epochs, history, subscribing, agent cards, storage, and sealed and paid fields.
589
55
 
590
- `buildAccessRequest` / `accessMessageHash` are exported if you want to drive the
591
- `/access` endpoint yourself, and `MembershipRegistryClient` (`canRead`, `planOf`)
592
- reads the membership rail directly.
56
+ ## Network
593
57
 
594
- **Trust model.** For `worker-usdc-v1` the access worker is the "somewhat trusted" party:
595
- it holds the unsealing key and sees plaintext at release time. That is deliberate for
596
- v1 — no TEE, no threshold network. Swapping in a stronger backend later is a _new
597
- gadget_ behind the same handle shape, so committed data doesn't change form.
598
- `self-hkdf-v1` trusts nobody: the worker is dumb storage and never holds a key.
58
+ Fangorn runs on **Base Sepolia**. The DataRegistry, SettlementRegistry, and hosted upload worker are all deployed there. Addresses are in [`src/config.ts`](src/config.ts) (`BaseSepoliaConfig`). To use a local anvil or a private deployment, pass your own `NetworkConfig` to `Fangorn.create`, or set the `FANGORN_*` overrides for the CLI (see the [Guide](docs/GUIDE.md#configure)). Contract sources are in [fangorn-network/contracts](https://github.com/fangorn-network/contracts).
599
59
 
600
- ---
601
-
602
- ## Contracts
603
-
604
- ### Base Sepolia (the default)
605
-
606
- | Contract | Address | What it owns |
607
- | -------------------- | -------------------------------------------- | --------------------------------------------------- |
608
- | DataRegistry | `0xE9183f768865dd2Cde5f1B71F8446F0Cd798ebe0` | Every repo's head, and the update log |
609
- | AppRegistry | `0x0D3e98399df41b558048Cdd7D71723c37A3A9D6F` | Apps: owner, accepted publishers, bans, storage subscription (ERC-5643, USDC); what each app excludes |
610
- | MembershipRegistry | `0x0e96C012b5c53622EcDAA82F342E31C2623A04f5` | Time-limited, unlinkable access to an app's paid records (USDC + Semaphore) |
611
-
612
- `Fangorn.create` uses it when given no `config`, and the CLI when `CHAIN_NAME` is unset.
613
-
614
- ### Arbitrum Sepolia
615
-
616
- | Contract | Address |
617
- | -------------------- | -------------------------------------------- |
618
- | DataRegistry | `0x72B5f83526F3893aF9f1eE0f32A27218EA09f8aE` |
619
- | AppRegistry | `0x55e6209ea1833ceD900989a3b3b22466934E04A5` |
620
- | MembershipRegistry | `0xDF17030Cd65435C86eb043F31DDACa99E819E347` |
621
-
622
- Still runs an older version of the contracts, which this SDK's ABIs do not match.
623
- Select it with `Fangorn.create({ config: ArbitrumSepoliaConfig, ... })`, or from the
624
- CLI with `CHAIN_NAME=arbitrumSepolia` (or pick it in `fangorn init`).
625
-
626
- Its default RPC is `base-sepolia-rpc.publicnode.com`, not `sepolia.base.org`: the
627
- official endpoint caps `eth_getLogs` at 200 blocks, too narrow to scan the registry's
628
- history. Each config's `logWindow` is the most blocks one log query spans on its RPC
629
- (Base 10,000, Arbitrum 100,000); `FANGORN_LOG_WINDOW` overrides it for a private RPC.
630
-
631
- The CLI takes the chosen network's RPC and contracts from the environment when set:
632
- `FANGORN_RPC_URL`, `FANGORN_APP_REGISTRY` and `FANGORN_DATA_REGISTRY`, for a private
633
- RPC or a local `anvil` with the contracts deployed.
634
-
635
- `BaseSepoliaConfig` (also exported as `FangornConfig`, the default) and `ArbitrumSepoliaConfig` in `src/config.ts` are the authoritative list and what the SDK
636
- uses — prefer it over any address copied out of a document,
637
- including this table. The sources are `fangorn-network/contracts`
638
- (`solidity/script/Deployments.sol`); regenerate the ABIs with `pnpm abis`.
639
-
640
- Neither contract calls the other: an update names no app, and an app presents
641
- its members (`canPublish`).
642
-
643
- ---
644
-
645
- ## Testing
646
-
647
- ### Unit Tests
648
-
649
- ```sh
650
- pnpm test
651
- ```
652
-
653
- ### E2E Tests
654
-
655
- The SDK suite (`src/test/sdk-suite.ts`) runs twice: in memory with the unit
656
- tests, and against the contracts, built from source in a sibling checkout of
657
- `fangorn-network/contracts` (`FANGORN_CONTRACTS_DIR` to point elsewhere) and
658
- deployed to a fresh `anvil`. Nothing touches a real chain.
60
+ ## Development
659
61
 
660
62
  ```sh
661
- pnpm test:e2e
63
+ pnpm i
64
+ pnpm test # unit tests + the SDK suite in memory
65
+ pnpm test:e2e # the same suite against the contracts on a fresh anvil
66
+ pnpm abis # regenerate ABIs from the contracts repo
662
67
  ```
663
68
 
664
- | File | Runs against | Needs |
665
- | ------------------------------ | ---------------------------- | ------------------------ |
666
- | `src/e2e/sdk.e2e.test.ts` | the contracts on anvil | `anvil`, `forge` |
667
- | `src/e2e/apps.e2e.test.ts` | the contracts on anvil | `anvil`, `forge` |
668
- | `src/e2e/admin.e2e.test.ts` | the contracts on anvil | `anvil`, `forge` |
669
- | `src/e2e/cli.e2e.test.ts` | the CLI, on anvil | `anvil`, `forge` |
670
- | `src/e2e/live.e2e.test.ts` | Base Sepolia, read-only | nothing |
671
-
672
- Without `anvil`, `forge` or the contracts checkout the anvil suites are skipped
673
- (in CI they fail). The deployer is the protocol admin, so the admin suite needs
674
- no real key. Storage is in memory; `E2E_STORAGE=pinata` runs the same suites
675
- against Pinata (`PINATA_JWT`, `PINATA_GATEWAY`).
676
-
677
- **The live suite** only reads: that the registries point at each other, and that
678
- the config's start block is the AppRegistry's deployment.
679
-
680
- ---
681
-
682
- ## Limitations / Future Work
683
-
684
- - 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.
685
- - The SDK covers the **app owner** half of the membership rail (`setPlan`, plus the reads and the relayed `join`/`claim`). The **buyer** half — Semaphore identity, the ERC-3009 authorization, membership proofs — lives in [`@fangorn-network/fetch`](https://github.com/fangorn-network/x402f), which relays both writes through a facilitator so the buyer needs no gas. This package deliberately carries no proving dependency.
686
- - `fangorn subscribe` is the event stream, not the storage paywall — that is `fangorn app claim` / `fangorn app renew`.
687
- - `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.
688
- - Record schema validation is client-side only — no on-chain enforcement.
689
- - An app presents each accepted publisher's latest head; the data itself is unverified, so accept publishers you trust.
690
-
691
- ---
69
+ The e2e tests need `anvil`, `forge`, and a sibling checkout of `fangorn-network/contracts` (set `FANGORN_CONTRACTS_DIR` to use another location). Without them, the tests are skipped locally and fail in CI. `E2E_STORAGE=pinata` runs the tests against Pinata (`PINATA_JWT`, `PINATA_GATEWAY`). `pnpm test:live` runs read-only checks against Base Sepolia.
692
70
 
693
71
  ## License
694
72