@fangorn-network/sdk 2026.5.11 → 2026.7.1-2.0

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 (101) hide show
  1. package/README.md +219 -225
  2. package/lib/ crypto/constants.d.ts +4 -0
  3. package/lib/ crypto/constants.js +5 -0
  4. package/lib/ crypto/merkle.d.ts +10 -0
  5. package/lib/ crypto/merkle.js +34 -0
  6. package/lib/cli/cli.d.ts +0 -0
  7. package/lib/cli/cli.js +234 -235
  8. package/lib/cli/index.d.ts +13 -650
  9. package/lib/config.d.ts +45 -699
  10. package/lib/config.js +6 -22
  11. package/lib/contracts/data-registry/abi.d.ts +38 -0
  12. package/lib/contracts/data-registry/abi.js +237 -0
  13. package/lib/contracts/data-registry/index.d.ts +81 -0
  14. package/lib/contracts/data-registry/index.js +184 -0
  15. package/lib/contracts/data-registry/test.d.ts +1 -0
  16. package/lib/contracts/index.d.ts +3 -0
  17. package/lib/contracts/index.js +4 -0
  18. package/lib/crypto/aes.d.ts +26 -0
  19. package/lib/crypto/aes.js +58 -0
  20. package/lib/crypto/encryption.d.ts +53 -0
  21. package/lib/crypto/encryption.js +82 -0
  22. package/lib/crypto/rand.d.ts +5 -0
  23. package/lib/{modules/encryption → crypto}/rand.js +1 -1
  24. package/lib/{modules/encryption → crypto}/types.d.ts +1 -1
  25. package/lib/engine/blockstore.d.ts +24 -0
  26. package/lib/engine/blockstore.js +85 -0
  27. package/lib/engine/index.d.ts +180 -0
  28. package/lib/engine/index.js +367 -0
  29. package/lib/fangorn.d.ts +149 -16
  30. package/lib/fangorn.js +256 -37
  31. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +1 -0
  32. package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
  33. package/lib/harness/index.d.ts +57 -0
  34. package/lib/harness/index.js +67 -0
  35. package/lib/index.d.ts +2 -4
  36. package/lib/index.js +1 -3
  37. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/_polyval.js +218 -0
  38. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js +261 -0
  39. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js +156 -0
  40. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js +299 -0
  41. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js +532 -0
  42. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js +344 -0
  43. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js +137 -0
  44. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js +262 -0
  45. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/utils.js +150 -0
  46. package/lib/providers/storage/car.d.ts +36 -0
  47. package/lib/providers/storage/car.js +80 -0
  48. package/lib/providers/storage/pinata.d.ts +34 -2
  49. package/lib/providers/storage/pinata.js +141 -5
  50. package/lib/providers/storage/types.d.ts +31 -16
  51. package/lib/providers/storage/utils.js +2 -1
  52. package/lib/roles/repo/index.d.ts +56 -0
  53. package/lib/roles/repo/index.js +73 -0
  54. package/lib/test/car_smoke.d.ts +1 -0
  55. package/lib/test/car_smoke.js +81 -0
  56. package/lib/test/cleanup-embeddings-testdata.d.ts +1 -0
  57. package/lib/test/cleanup-embeddings-testdata.js +75 -0
  58. package/lib/test/setup-embeddings-testdata.d.ts +11 -0
  59. package/lib/test/setup-embeddings-testdata.js +155 -0
  60. package/lib/test/testbed.d.ts +39 -30
  61. package/lib/test/testbed.js +43 -129
  62. package/lib/types/index.d.ts +3 -19
  63. package/lib/utils/manifest.d.ts +23 -0
  64. package/lib/utils/manifest.js +77 -0
  65. package/package.json +99 -67
  66. package/lib/modules/encryption/actions.d.ts +0 -4
  67. package/lib/modules/encryption/actions.js +0 -18
  68. package/lib/modules/encryption/aes.d.ts +0 -10
  69. package/lib/modules/encryption/aes.js +0 -51
  70. package/lib/modules/encryption/rand.d.ts +0 -5
  71. package/lib/registries/datasource-registry/abi.d.ts +0 -156
  72. package/lib/registries/datasource-registry/abi.js +0 -194
  73. package/lib/registries/datasource-registry/index.d.ts +0 -30
  74. package/lib/registries/datasource-registry/index.js +0 -158
  75. package/lib/registries/index.d.ts +0 -3
  76. package/lib/registries/index.js +0 -4
  77. package/lib/registries/schema-registry/abi.d.ts +0 -218
  78. package/lib/registries/schema-registry/abi.js +0 -246
  79. package/lib/registries/schema-registry/index.d.ts +0 -34
  80. package/lib/registries/schema-registry/index.js +0 -179
  81. package/lib/registries/settlement-registry/abi.d.ts +0 -218
  82. package/lib/registries/settlement-registry/abi.js +0 -259
  83. package/lib/registries/settlement-registry/index.d.ts +0 -63
  84. package/lib/registries/settlement-registry/index.js +0 -325
  85. package/lib/registries/settlement-registry/types.d.ts +0 -54
  86. package/lib/roles/consumer/index.d.ts +0 -39
  87. package/lib/roles/consumer/index.js +0 -143
  88. package/lib/roles/consumer/types.d.ts +0 -47
  89. package/lib/roles/consumer/types.js +0 -1
  90. package/lib/roles/publisher/index.d.ts +0 -50
  91. package/lib/roles/publisher/index.js +0 -224
  92. package/lib/roles/publisher/types.d.ts +0 -99
  93. package/lib/roles/publisher/types.js +0 -1
  94. package/lib/roles/schema/index.d.ts +0 -18
  95. package/lib/roles/schema/index.js +0 -93
  96. package/lib/roles/schema/types.d.ts +0 -91
  97. package/lib/roles/schema/types.js +0 -1
  98. /package/lib/{modules/encryption/index.d.ts → crypto/utils.d.ts} +0 -0
  99. /package/lib/{modules/encryption/index.js → crypto/utils.js} +0 -0
  100. /package/lib/{modules/encryption/types.js → contracts/data-registry/test.js} +0 -0
  101. /package/lib/{registries/settlement-registry → crypto}/types.js +0 -0
package/README.md CHANGED
@@ -1,13 +1,22 @@
1
1
  # Fangorn SDK
2
2
 
3
- Programmable access control for the agentic web.
3
+ commit → push → discover → fetch
4
4
 
5
- Fangorn lets you publish data under programmable access conditions. Access is enforced on-chain through settlement verification, so your content is only retrievable by those who have provably paid for it. Data is organized by schemas, enabling agent-based discovery across any number of publishers.
6
- Content is stored in your own storage backend (Cloudflare R2, IPFS, or any compatible future backend). The Fangorn protocol coordinates access without ever touching your content directly.
5
+ Intent-bound data for the agentic web.
6
+
7
+ Fangorn lets you publish content-addressed graph data, organized into namespaces, so that agents can discover and verify it across any number of publishers. Content is stored in your own storage backend (IPFS via Pinata today); the on-chain **DataRegistry** holds only a single cryptographic pointer per publisher. The protocol coordinates commitment and discovery without ever touching your content directly.
8
+
9
+ Each publisher owns exactly **one on-chain state root** — the root of a content-addressed Pail tree (`@web3-storage/pail`), wrapped in a commit. Everything you publish lives as key-prefixed **namespaces** inside that one tree. Advancing the root is a compare-and-swap: it *is* a git ref update.
10
+
11
+ Data is a **metagraph** — **vertices** (a JSON payload tagged by a free-form schema id) and **edges** (a labeled relation between two vertex CIDs) — committed under a namespace.
12
+
13
+ Datasets are versioned like git: each update is a **commit** that points at its parent, the registry stores only the pointer to the latest commit, and full history lives in IPFS — reconstructible from the on-chain tip alone, no indexer required. `commit` builds locally (permissionless); `push` moves the on-chain pointer (the single permissioned step, fast-forward checked).
14
+
15
+ > **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.
7
16
 
8
17
  ## Supported Networks
9
18
 
10
- Arbitrum Sepolia (Base Sepolia in progress).
19
+ - Arbitrum Sepolia
11
20
 
12
21
  ---
13
22
 
@@ -30,279 +39,271 @@ fangorn init
30
39
 
31
40
  `fangorn init` prompts for:
32
41
  - Wallet private key
33
- - Pinata JWT + gateway URL (for schema/manifest storage)
34
- - Fangorn access worker URL (for content retrieval)
35
- - Default chain
42
+ - Pinata JWT + gateway URL (content + commit-object storage)
43
+ - Fangorn access worker URL (reserved for the upcoming access-control flow)
36
44
 
37
45
  Config is written to `~/.fangorn/config.json`.
38
46
 
39
- You can also configure via environment variables:
47
+ You can also configure via environment variables (these take precedence over the config file):
40
48
 
41
49
  ```sh
42
- DELEGATOR_ETH_PRIVATE_KEY=0x...
50
+ ETH_PRIVATE_KEY=0x...
43
51
  PINATA_JWT=...
44
52
  PINATA_GATEWAY=https://your-gateway.mypinata.cloud
45
- WORKER_URL=https://your-worker.workers.dev
46
53
  CHAIN_NAME=arbitrumSepolia
54
+ WORKER_URL=https://your-worker.workers.dev # optional (future access control)
47
55
  ```
48
56
 
49
- ### Register a Schema
57
+ ### Register as a publisher
58
+
59
+ Register once before committing anything. This records your wallet as a data publisher in the DataRegistry (the registration fee is currently zero).
50
60
 
51
61
  ```sh
52
- # Register a schema on-chain
53
- fangorn schema register <name>
62
+ fangorn register
63
+ ```
64
+
65
+ ### Track a namespace (git-native repo)
54
66
 
55
- # Fetch a registered schema by name
56
- fangorn schema get schema.name.v1
67
+ A **namespace** is a key prefix inside your on-chain tree. `repo init` allocates it and starts tracking it in a local `.fangorn/` pointer file (just a HEAD ref — there is no local object store; commit objects live in IPFS).
68
+
69
+ ```sh
70
+ # Allocate a namespace on-chain (no-op if it already exists) and track it here
71
+ fangorn repo init rusty-anchor
57
72
  ```
58
73
 
59
- ### Publish Data
74
+ ### Commit → push
75
+
76
+ `commit` snapshots a namespace's vertices/edges into a new commit **locally** (pins the blocks to IPFS, advances your local HEAD) — it does **not** touch the chain. `push` fast-forwards the on-chain state root to your local tip: the single permissioned step.
60
77
 
61
78
  ```sh
62
- # Publish records under a schema, priced at 1 USDC unit
63
- fangorn publish upload records.json -s schema.name.v1 -p 1
79
+ # Snapshot graph data into a new local commit — does NOT push
80
+ fangorn commit graph.json -m "initial import"
64
81
 
65
- # Inspect a specific entry
66
- fangorn publish entry track1 -s schema.name.v1
82
+ # Settle the local tip on-chain (permission + fast-forward checked here)
83
+ fangorn push
84
+ fangorn push --force # push even if it doesn't fast-forward the on-chain tip
67
85
  ```
68
86
 
69
- Records are JSON files containing `PublishRecord` objects. Handle fields point to content already uploaded to your storage backend:
87
+ `graph.json` is a JSON file of vertices and (optionally) the edges between them. Edges reference vertices by their local `id`:
70
88
 
71
89
  ```json
72
90
  {
73
- "name": "track1",
74
- "fields": {
75
- "title": "Locura",
76
- "artist": "Alice",
77
- "audio": { "@type": "handle", "uri": "r2://my-dir/locura.mp3" }
78
- }
91
+ "vertices": [
92
+ { "id": "t1", "tag": "track", "payload": { "title": "Locura", "artist": "Alice" } },
93
+ { "id": "a1", "tag": "artist", "payload": { "name": "Alice" } }
94
+ ],
95
+ "edges": [
96
+ { "rel": "performed_by", "from": "t1", "to": "a1" }
97
+ ]
79
98
  }
80
99
  ```
81
100
 
82
- > A price of `1` equals the smallest USDC unit (0.000001 USDC).
101
+ Each commit records its parent, so history is real and walkable. Deleting a vertex is just a later commit that omits it — earlier history is retained. Blocks are content-addressed, so unchanged data is reused byte-for-byte across commits.
102
+
83
103
 
84
- ### Consume Data
104
+ ### Graph Builders
85
105
 
86
- The consumer flow is three phases: **purchase → claim → fetch**.
106
+ A graph builders are delegated to the application layer. Developers are responsible for implementing functions that take input and transform it into a set of edges and vertices. See [examples/hackmd](./examples/hackmd/) for an example.
107
+
108
+ ### Inspect
87
109
 
88
110
  ```sh
89
- # Phase 1: pay and join the Semaphore group
90
- fangorn consume purchase <owner> <name> \
91
- -s schema.name.v1 \
92
- --burner-key 0x... \
93
- --amount 1 \
94
- --usdc 0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d
95
-
96
- # Save the identity string printed by purchase — required for claim.
97
-
98
- # Phase 2: prove membership and claim access (generates a Groth16 ZK proof)
99
- fangorn consume claim <owner> <name> \
100
- -s schema.name.v1 \
101
- --identity '<identity-string>' \
102
- --stealth <stealth-address>
103
-
104
- # Phase 3: fetch content via the access worker
105
- fangorn consume fetch <owner> <name> \
106
- -s schema.name.v1 \
107
- -f audio \
108
- --nullifier <nullifier> \
109
- --stealth-key 0x... \
110
- -o output.mp3
111
-
112
- # List a publisher's manifest
113
- fangorn consume list -s schema.name.v1 --owner <address>
114
-
115
- # Inspect a publisher's entry
116
- fangorn consume entry track1 -s schema.name.v1 --owner <address>
111
+ fangorn status # local tip vs on-chain tip
112
+ fangorn log # walk commit history from the tip (newest first)
113
+ fangorn log -n 5 # limit
114
+ fangorn show # the tip commit + which keys it changed vs its parent
115
+ fangorn show <commitCid> # a specific commit
116
+
117
+ # List every vertex and edge committed under a namespace, as JSON
118
+ fangorn read # defaults to the current repo's namespace + owner
119
+ fangorn read rusty-anchor --owner 0x... --pretty
117
120
  ```
118
121
 
119
- ---
122
+ ### Clone
120
123
 
121
- ## SDK Usage
122
-
123
- ### Initialization
124
+ Reconstruct tracking of a published namespace from its on-chain tip alone. History and contents are then fetched on demand from IPFS.
124
125
 
125
- ```ts
126
- import { Fangorn, FangornConfig } from "@fangorn-network/sdk";
127
-
128
- const fangorn = await Fangorn.create({
129
- privateKey: "0x...",
130
- workerUrl: "https://your-worker.workers.dev",
131
- config: FangornConfig.ArbitrumSepolia,
132
- domain: "localhost",
133
- });
126
+ ```sh
127
+ fangorn clone <owner> rusty-anchor
128
+ fangorn clone <owner> rusty-anchor --dir ./somewhere
134
129
  ```
135
130
 
136
- ### Storage
131
+ ### Subscribe (light client)
137
132
 
138
- Fangorn operates on a 'Bring Your Own Storage' basis.
133
+ Watch a namespace for on-chain updates and stream the diffs — **no subgraph, no
134
+ indexer**. A publisher owns exactly one on-chain root, so this watches that
135
+ publisher's `StateCommitted` event (read straight from the RPC node) and, for
136
+ each new root, diffs the tree against the previous one restricted to your
137
+ namespace's key prefix. Only pushes that actually changed the namespace are
138
+ emitted. Diffs are resolved from IPFS on demand.
139
+
140
+ ```sh
141
+ # Watch the current repo's namespace; each change is one JSON line on stdout.
142
+ fangorn subscribe
139
143
 
140
- - Schema definitions and schema-conformant data sets live in IPFS using Pinata.
141
- - Storage of data that should be guarded via Fangorn can live in any database desired, be it S3 or within IPFS. At present, the implementation only supports Cloudflare R2.
144
+ # Watch any publisher's namespace explicitly.
145
+ fangorn subscribe rusty-anchor --owner 0x...
142
146
 
143
- Storage is used for schemas and manifests only. Content itself lives in your storage backend (R2 etc.) and is never handled by the SDK directly.
147
+ # Feed an embeddings/index builder directly.
148
+ fangorn subscribe rusty-anchor --owner 0x... | my-index-builder
149
+ ```
144
150
 
145
- ### Schemas
151
+ Each emitted line is a namespace change:
146
152
 
147
- A `SchemaDefinition` is a JSON object where each field declares its type. Fields marked `@type: "handle"` point to content in an external storage backend — access is enforced by the Fangorn access worker. All other fields are stored inline in the manifest and are publicly readable.
153
+ ```jsonc
154
+ {
155
+ "namespace": "rusty-anchor",
156
+ "owner": "0x...",
157
+ "commitCid": "bafy...", // the new on-chain tip
158
+ "blockNumber": "12345678", // persist this to resume
159
+ "addedVertices": [{ "cid": "bafy...", "schemaId": "track", "payload": { "title": "Locura" } }],
160
+ "addedEdges": [{ "sourceCid": "bafy...", "relation": "by", "targetCid": "bafy..." }],
161
+ "removedVertexCids": ["bafy..."],
162
+ "removedEdges": []
163
+ }
164
+ ```
148
165
 
149
- ```ts
150
- const definition: SchemaDefinition = {
151
- title: { "@type": "string" },
152
- artist: { "@type": "string" },
153
- audio: { "@type": "handle" }, // content lives in R2, access-controlled by worker
154
- };
155
-
156
- // Register the schema on-chain
157
- const { schemaId, schemaCid } = await fangorn.schema.register({
158
- name: "schema.name.v1",
159
- definition,
160
- agentId: "",
161
- });
166
+ **Resumability.** The last processed block is saved to
167
+ `.fangorn/subscribe-<owner>-<namespace>.json` after each change, so restarting
168
+ replays only what you missed (via `eth_getLogs`) before going live. Override or
169
+ reset:
162
170
 
163
- // Fetch a schema by name
164
- const schema = await fangorn.schema.get("schema.name.v1");
171
+ ```sh
172
+ fangorn subscribe --from-block 12000000 # replay from a specific block
173
+ fangorn subscribe --from-start # replay the namespace's full history
165
174
  ```
166
175
 
167
- ### Publishing
176
+ Without a saved cursor, subscribe starts **live from the current tip** — seed
177
+ your initial index from `fangorn read` first, then subscribe for the deltas.
168
178
 
169
- Upload content to your R2 bucket out-of-band (via Cloudflare dashboard, wrangler CLI, or your own tooling), then publish a manifest pointing at it. The SDK stores the manifest on IPFS and commits the CID on-chain.
179
+ ---
180
+
181
+ ## SDK Usage
182
+
183
+ ### Initialization
184
+
185
+ `Fangorn.create` is synchronous. Pass Pinata storage for any commit/read operation.
170
186
 
171
187
  ```ts
172
- await fangorn.publisher.upload(
173
- {
174
- records: [
175
- {
176
- name: "track1",
177
- fields: {
178
- title: "Locura",
179
- artist: "Alice",
180
- audio: { "@type": "handle", uri: "r2://my-dir/locura.mp3" },
181
- },
182
- },
183
- ],
184
- schemaName: "schema.name.v1",
185
- },
186
- 1n, // price in smallest USDC units
187
- );
188
- ```
188
+ import { Fangorn, FangornConfig } from "@fangorn-network/sdk";
189
189
 
190
- The manifest stored on-chain looks like:
190
+ const fangorn = Fangorn.create({
191
+ privateKey: "0x...",
192
+ storage: { pinata: { jwt: process.env.PINATA_JWT!, gateway: process.env.PINATA_GATEWAY! } },
193
+ config: FangornConfig, // defaults to Arbitrum Sepolia
194
+ domain: "localhost",
195
+ });
191
196
 
192
- ```json
193
- {
194
- "version": 2,
195
- "schemaId": "0x...",
196
- "entries": [
197
- {
198
- "name": "track1",
199
- "fields": {
200
- "title": "Locura",
201
- "artist": "Alice",
202
- "audio": {
203
- "@type": "handle",
204
- "uri": "r2://my-dir/locura.mp3"
205
- }
206
- }
207
- }
208
- ]
197
+ // Register once before committing.
198
+ const registry = fangorn.getDataRegistry();
199
+ if (!(await registry.isRegistered(fangorn.getAddress()))) {
200
+ await registry.register();
209
201
  }
210
202
  ```
211
203
 
212
- Plain fields (`title`, `artist`) are readable by anyone directly from the manifest. Handle fields require a valid on-chain settlement to retrieve via the access worker.
213
-
214
- ### Consuming
204
+ ### Namespaces & the git-native flow
215
205
 
216
- #### Phase 1: Purchase
206
+ `initRepo` allocates a namespace on-chain (idempotent). Then split building from settling:
207
+ `commit` writes a commit object locally (durable in IPFS, HEAD not yet on-chain), and
208
+ `push` fast-forwards the on-chain root to it.
217
209
 
218
210
  ```ts
219
- import { Identity } from "@semaphore-protocol/identity";
220
-
221
- const identity = new Identity();
222
-
223
- const preparedRegister = await fangorn.consumer.prepareRegister({
224
- walletClient,
225
- paymentRecipient: ownerAddress,
226
- amount: 1n,
227
- usdcAddress: "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
228
- usdcDomainName: "USD Coin",
229
- usdcDomainVersion: "2",
211
+ // Allocate the namespace (no-op if it already exists)
212
+ await fangorn.initRepo("rusty-anchor");
213
+
214
+ // First commit — no parent
215
+ const c1 = await fangorn.commit({
216
+ namespace: "rusty-anchor",
217
+ message: "initial import",
218
+ vertices: [
219
+ { id: "t1", tag: "track", payload: { title: "Locura", artist: "Alice" } },
220
+ { id: "a1", tag: "artist", payload: { name: "Alice" } },
221
+ ],
222
+ edges: [{ rel: "performed_by", from: "t1", to: "a1" }],
230
223
  });
231
224
 
232
- const { txHash } = await fangorn.consumer.register({
233
- owner: ownerAddress,
234
- schemaId,
235
- name: "track1",
236
- identityCommitment: identity.commitment,
237
- relayerPrivateKey: "0x...",
238
- preparedRegister,
239
- });
225
+ // Settle it on-chain (fast-forward from "no tip yet")
226
+ await fangorn.push(c1.commitCid);
240
227
 
241
- // Save identity.export() — required for Phase 2
228
+ // A follow-up commit builds on the previous one
229
+ const c2 = await fangorn.commit({
230
+ namespace: "rusty-anchor",
231
+ parent: c1.commitCid,
232
+ message: "add another track",
233
+ vertices: [{ id: "t2", tag: "track", payload: { title: "Otra", artist: "Alice" } }],
234
+ });
235
+ await fangorn.push(c2.commitCid); // refuses unless it fast-forwards the on-chain tip (pass { force: true } to override)
242
236
  ```
243
237
 
244
- #### Phase 2: Claim
238
+ ### History, diff & read
239
+
240
+ Walk history from the on-chain tip (IPFS only, no indexer), and read the current namespace contents:
245
241
 
246
242
  ```ts
247
- const preparedSettle = await fangorn.consumer.prepareSettle({
248
- resourceId: DataSourceRegistry.resourceIdLocal(ownerAddress, schemaId, "track1"),
249
- identity,
250
- stealthAddress: "0x...",
251
- });
243
+ const tip = await fangorn.onChainTip(fangorn.getAddress());
252
244
 
253
- const { txHash, nullifier } = await fangorn.consumer.claim({
254
- owner: ownerAddress,
255
- schemaId,
256
- name: "track1",
257
- relayerPrivateKey: "0x...",
258
- preparedSettle,
259
- });
245
+ // Walk commits, newest first
246
+ for await (const c of fangorn.log(tip!)) {
247
+ console.log(c.cid, c.message);
248
+ }
249
+
250
+ // What a commit changed vs. its first parent (namespaced pail keys added/removed)
251
+ const diff = await fangorn.show(tip!);
260
252
 
261
- // Save nullifier — required for Phase 3
253
+ // Every vertex and edge currently committed under a namespace
254
+ const contents = await fangorn.inspectNamespace("rusty-anchor");
255
+ // contents.vertices: { cid, schemaId, payload }[] contents.edges: { sourceCid, relation, targetCid }[]
262
256
  ```
263
257
 
264
- #### Phase 3: Fetch
258
+ > The fast-forward check in `push` is enforced client-side against the on-chain
259
+ > head in this release; on-chain write-authorization lands in a later slice.
260
+
261
+ ### Immediate-write helpers
262
+
263
+ For the common "stage and settle in one shot" case, `upload` (one vertex) and `uploadBatch`
264
+ (many vertices + edges) run the whole commit-and-push atomically:
265
265
 
266
266
  ```ts
267
- import { createWalletClient, http } from "viem";
268
- import { privateKeyToAccount } from "viem/accounts";
269
- import { arbitrumSepolia } from "viem/chains";
270
-
271
- const stealthWalletClient = createWalletClient({
272
- account: privateKeyToAccount(stealthPrivateKey),
273
- chain: arbitrumSepolia,
274
- transport: http(rpcUrl),
275
- });
267
+ await fangorn.upload("rusty-anchor", { title: "Locura" }, "track");
276
268
 
277
- const { data, contentType } = await fangorn.consumer.fetchField(
278
- ownerAddress,
279
- schemaId,
280
- "track1",
281
- "audio",
282
- nullifier.toString(),
283
- stealthWalletClient,
269
+ await fangorn.uploadBatch(
270
+ "rusty-anchor",
271
+ [{ id: "t1", tag: "track", payload: { title: "Locura" } }],
272
+ [/* edges */],
284
273
  );
285
274
  ```
286
275
 
287
- The consumer signs `{ nullifier, resourceId, objectKey, timestamp }` with their stealth key. The access worker verifies the signature, checks `is_settled()` on-chain, and proxies the content bytes directly from R2. The content URL is never exposed to the client.
288
-
289
- ---
290
-
291
- ## Access Worker
276
+ ### Subscribe (light client)
292
277
 
293
- The Fangorn access worker is a Cloudflare Worker that gates R2 content behind on-chain settlement verification. Publishers deploy their own worker, with one worker per R2 bucket.
278
+ `subscribe` is an async generator over namespace-scoped changes. It optionally
279
+ replays from a block cursor (`fromBlock`) and then watches live until the
280
+ `AbortSignal` fires. Each change carries `blockNumber` — persist it to resume.
294
281
 
295
- ### How it works
282
+ ```ts
283
+ const controller = new AbortController();
284
+
285
+ for await (const change of fangorn.subscribe({
286
+ namespace: "rusty-anchor",
287
+ owner: "0x...", // defaults to your own address
288
+ fromBlock: savedCursor, // omit to start live from the current tip
289
+ signal: controller.signal,
290
+ })) {
291
+ for (const v of change.addedVertices) index.upsert(v.cid, v.payload);
292
+ for (const cid of change.removedVertexCids) index.remove(cid);
293
+ persistCursor(change.blockNumber);
294
+ }
295
+ ```
296
296
 
297
- 1. Consumer signs `{ nullifier, resourceId, objectKey, timestamp }` with their stealth address private key
298
- 2. Worker recovers the stealth address from the signature
299
- 3. Worker calls `is_settled(stealthAddress, resourceId)` on the Settlement Registry
300
- 4. If settled → bytes proxied directly from R2
301
- 5. If not → 401
297
+ The pure diff primitive is also exposed on the engine —
298
+ `engine.namespaceDiff(oldRootHex, newRootHex, namespace)` — if you want to diff
299
+ two arbitrary roots without watching.
302
300
 
303
- The worker is stateless, open-source, and has no logging. Its only capability is verifying settlement and proxying bytes. The content URL is never exposed to the consumer.
301
+ ### Storage
304
302
 
305
- See the [fangorn-access-worker](https://github.com/fangorn-network/webworker) repo for deployment instructions.
303
+ Fangorn operates on a 'Bring Your Own Storage' basis. Content-addressed blocks
304
+ (vertices, edges, pail shards, commit objects) are pinned to IPFS via Pinata; the chain
305
+ holds only the 32-byte commit pointer. Additional backends can be added behind the
306
+ `MetadataStorage` interface.
306
307
 
307
308
  ---
308
309
 
@@ -310,11 +311,11 @@ See the [fangorn-access-worker](https://github.com/fangorn-network/webworker) re
310
311
 
311
312
  ### Arbitrum Sepolia
312
313
 
313
- | Contract | Address |
314
- | ------------------- | -------------------------------------------- |
315
- | DataSource Registry | `0xe8a5906825680a5816a7f28f2a0fa2d9ceec3755` |
316
- | Schema Registry | `0x267084865813550d9d97d3842c4a2d33a872908f` |
317
- | Settlement Registry | `0x1d21545f536a2f026348477960ca59f9f1d7fabd` |
314
+ | Contract | Address |
315
+ | ------------- | -------------------------------------------- |
316
+ | DataRegistry | `0x9a3811b365a4aeea1626eaad185b273424ae5e48` |
317
+
318
+ This is the address in `FangornConfig`; the SDK uses it by default.
318
319
 
319
320
  ---
320
321
 
@@ -328,6 +329,8 @@ pnpm test
328
329
 
329
330
  ### E2E Tests
330
331
 
332
+ Runs the storage + on-chain anchor flow against live IPFS + the deployed contract.
333
+
331
334
  ```sh
332
335
  cp env.example .env
333
336
  pnpm test:e2e
@@ -335,34 +338,25 @@ pnpm test:e2e
335
338
 
336
339
  Required variables:
337
340
 
338
- | Variable | Description |
339
- | ------------------------------ | ----------------------------------------- |
340
- | `DELEGATOR_ETH_PRIVATE_KEY` | Publisher private key (needs testnet ETH) |
341
- | `DELEGATEE_ETH_PRIVATE_KEY` | Consumer private key |
342
- | `PINATA_JWT` | Pinata API JWT |
343
- | `PINATA_GATEWAY` | Pinata gateway URL |
344
- | `WORKER_URL` | Access worker URL (optional for Phase 3) |
345
- | `CHAIN_NAME` | `arbitrumSepolia` |
346
- | `CAIP2` | `421614` |
347
- | `RPC_URL` | RPC endpoint |
348
- | `USDC_ADDRESS` | USDC contract address |
349
- | `DATA_SOURCE_REGISTRY_ADDRESS` | DataSourceRegistry address |
350
- | `SCHEMA_REGISTRY_ADDRESS` | SchemaRegistry address |
351
- | `SETTLEMENT_REGISTRY_ADDRESS` | SettlementRegistry address |
352
-
353
- Phase 3 tests are skipped unless `WORKER_URL` is set. Run the access worker locally with `wrangler dev --local` and set `WORKER_URL=http://localhost:8787` to enable them.
341
+ | Variable | Description |
342
+ | ----------------------- | ----------------------------------------- |
343
+ | `ETH_PRIVATE_KEY` | Publisher private key (needs testnet ETH) |
344
+ | `PINATA_JWT` | Pinata API JWT |
345
+ | `PINATA_GATEWAY` | Pinata gateway URL |
346
+
347
+ The publisher must be registered (`fangorn register`, or `registry.register()`) on the target key.
354
348
 
355
349
  ---
356
350
 
357
351
  ## Limitations / Future Work
358
352
 
359
- - Schema validation is client-side only — no on-chain enforcement.
360
- - The access worker is a trusted component. Future versions will replace it with a TEE or protocol-native verification layer.
361
- - One worker per R2 bucket. Multi-bucket support is planned.
362
- - Purchase ledger is in-memory only. Persistent ledger backed by IPFS is in progress.
353
+ - Access-controlled (encrypted) fields and the purchase → claim → fetch settlement flow are being built on this registry — not available this release.
354
+ - Vertex/edge schema validation is client-side only — no on-chain enforcement.
355
+ - Push authorization is client-side in this release; on-chain write policies and non-fast-forward rejection are planned.
356
+ - Reads target one publisher's namespace at a time; cross-publisher discovery is a higher layer.
363
357
 
364
358
  ---
365
359
 
366
360
  ## License
367
361
 
368
- MITSonnet 4.6Claude is AI and can make mistakes. Please double-check responses.
362
+ MIT
@@ -0,0 +1,4 @@
1
+ //#region src/ crypto/constants.d.ts
2
+ declare const TREE_DEPTH = 8;
3
+ //#endregion
4
+ export { TREE_DEPTH };
@@ -0,0 +1,5 @@
1
+ //#region src/ crypto/constants.ts
2
+ const TREE_DEPTH = 8;
3
+
4
+ //#endregion
5
+ export { TREE_DEPTH };
@@ -0,0 +1,10 @@
1
+ //#region src/ crypto/merkle.d.ts
2
+ declare function hashCidToField(cid: string): bigint;
3
+ declare function getProof(layers: bigint[][], index: number): {
4
+ path: bigint[];
5
+ indices: number[];
6
+ };
7
+ declare function fieldToHex(field: bigint): `0x${string}`;
8
+ declare function hexToField(hex: string): bigint;
9
+ //#endregion
10
+ export { fieldToHex, getProof, hashCidToField, hexToField };
@@ -0,0 +1,34 @@
1
+ import { TREE_DEPTH } from "./constants.js";
2
+
3
+ //#region src/ crypto/merkle.ts
4
+ function hashCidToField(cid) {
5
+ const bytes = new TextEncoder().encode(cid);
6
+ let value = 0n;
7
+ for (let i = 0; i < Math.min(bytes.length, 31); i++) value = value << 8n | BigInt(bytes[i]);
8
+ return value;
9
+ }
10
+ function getProof(layers, index) {
11
+ const path = [];
12
+ const indices = [];
13
+ for (let i = 0; i < TREE_DEPTH; i++) {
14
+ const isRight = index % 2 === 1;
15
+ const siblingIndex = isRight ? index - 1 : index + 1;
16
+ path.push(layers[i][siblingIndex] ?? 0n);
17
+ indices.push(isRight ? 1 : 0);
18
+ index = Math.floor(index / 2);
19
+ }
20
+ return {
21
+ path,
22
+ indices
23
+ };
24
+ }
25
+ function fieldToHex(field) {
26
+ return `0x${field.toString(16).padStart(64, "0")}`;
27
+ }
28
+ function hexToField(hex) {
29
+ const cleanHex = hex.startsWith("0x") ? hex : `0x${hex}`;
30
+ return BigInt(cleanHex);
31
+ }
32
+
33
+ //#endregion
34
+ export { fieldToHex, getProof, hashCidToField, hexToField };
package/lib/cli/cli.d.ts CHANGED
File without changes