@fangorn-network/sdk 2026.6.16 → 2026.7.1-2.1

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 (106) hide show
  1. package/README.md +210 -266
  2. package/lib/cli/cli.d.ts +0 -0
  3. package/lib/cli/cli.js +261 -167
  4. package/lib/cli/index.d.ts +13 -651
  5. package/lib/config.d.ts +137 -792
  6. package/lib/config.js +6 -22
  7. package/lib/contracts/data-registry/abi.d.ts +38 -0
  8. package/lib/contracts/data-registry/abi.js +237 -0
  9. package/lib/contracts/data-registry/index.d.ts +81 -0
  10. package/lib/contracts/data-registry/index.js +184 -0
  11. package/lib/contracts/index.d.ts +3 -0
  12. package/lib/contracts/index.js +4 -0
  13. package/lib/crypto/aes.d.ts +26 -0
  14. package/lib/crypto/aes.js +58 -0
  15. package/lib/crypto/encryption.d.ts +53 -0
  16. package/lib/crypto/encryption.js +82 -0
  17. package/lib/{modules/encryption → crypto}/rand.d.ts +1 -1
  18. package/lib/{modules/encryption → crypto}/rand.js +1 -1
  19. package/lib/{modules/encryption → crypto}/types.d.ts +1 -1
  20. package/lib/engine/blockstore.d.ts +24 -0
  21. package/lib/engine/blockstore.js +85 -0
  22. package/lib/engine/index.d.ts +180 -0
  23. package/lib/engine/index.js +367 -0
  24. package/lib/fangorn.d.ts +149 -16
  25. package/lib/fangorn.js +256 -37
  26. package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
  27. package/lib/harness/index.d.ts +57 -0
  28. package/lib/harness/index.js +67 -0
  29. package/lib/index.d.ts +3 -2
  30. package/lib/index.js +2 -1
  31. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/_polyval.js +218 -0
  32. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js +261 -0
  33. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js +156 -0
  34. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js +299 -0
  35. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js +532 -0
  36. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js +344 -0
  37. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js +137 -0
  38. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js +262 -0
  39. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/utils.js +150 -0
  40. package/lib/providers/storage/car.d.ts +36 -0
  41. package/lib/providers/storage/car.js +80 -0
  42. package/lib/providers/storage/pinata.d.ts +29 -1
  43. package/lib/providers/storage/pinata.js +135 -20
  44. package/lib/providers/storage/types.d.ts +25 -18
  45. package/lib/roles/repo/index.d.ts +56 -0
  46. package/lib/roles/repo/index.js +73 -0
  47. package/lib/test/car_smoke.d.ts +1 -0
  48. package/lib/test/car_smoke.js +81 -0
  49. package/lib/test/cleanup-embeddings-testdata.js +9 -38
  50. package/lib/test/setup-embeddings-testdata.d.ts +4 -6
  51. package/lib/test/setup-embeddings-testdata.js +40 -94
  52. package/lib/test/testbed.d.ts +35 -32
  53. package/lib/test/testbed.js +48 -138
  54. package/lib/types/index.d.ts +3 -19
  55. package/lib/utils/manifest.d.ts +23 -0
  56. package/lib/utils/manifest.js +77 -0
  57. package/package.json +99 -81
  58. package/lib/modules/encryption/actions.d.ts +0 -4
  59. package/lib/modules/encryption/actions.js +0 -18
  60. package/lib/modules/encryption/aes.d.ts +0 -10
  61. package/lib/modules/encryption/aes.js +0 -51
  62. package/lib/registries/datasource-registry/abi.d.ts +0 -186
  63. package/lib/registries/datasource-registry/abi.js +0 -229
  64. package/lib/registries/datasource-registry/index.d.ts +0 -39
  65. package/lib/registries/datasource-registry/index.js +0 -158
  66. package/lib/registries/index.d.ts +0 -3
  67. package/lib/registries/index.js +0 -4
  68. package/lib/registries/schema-registry/abi.d.ts +0 -218
  69. package/lib/registries/schema-registry/abi.js +0 -246
  70. package/lib/registries/schema-registry/index.d.ts +0 -34
  71. package/lib/registries/schema-registry/index.js +0 -179
  72. package/lib/registries/settlement-registry/abi.d.ts +0 -218
  73. package/lib/registries/settlement-registry/abi.js +0 -259
  74. package/lib/registries/settlement-registry/index.d.ts +0 -63
  75. package/lib/registries/settlement-registry/index.js +0 -325
  76. package/lib/registries/settlement-registry/types.d.ts +0 -54
  77. package/lib/registries/settlement-registry/types.js +0 -1
  78. package/lib/roles/consumer/index.d.ts +0 -39
  79. package/lib/roles/consumer/index.js +0 -150
  80. package/lib/roles/consumer/types.d.ts +0 -47
  81. package/lib/roles/consumer/types.js +0 -1
  82. package/lib/roles/publisher/builders/bundle.d.ts +0 -32
  83. package/lib/roles/publisher/builders/bundle.js +0 -137
  84. package/lib/roles/publisher/builders/record-set.d.ts +0 -17
  85. package/lib/roles/publisher/builders/record-set.js +0 -55
  86. package/lib/roles/publisher/builders/types.d.ts +0 -38
  87. package/lib/roles/publisher/builders/types.js +0 -1
  88. package/lib/roles/publisher/builders/utils.d.ts +0 -9
  89. package/lib/roles/publisher/builders/utils.js +0 -29
  90. package/lib/roles/publisher/encryption.d.ts +0 -18
  91. package/lib/roles/publisher/encryption.js +0 -38
  92. package/lib/roles/publisher/index.d.ts +0 -68
  93. package/lib/roles/publisher/index.js +0 -179
  94. package/lib/roles/publisher/types.d.ts +0 -114
  95. package/lib/roles/publisher/types.js +0 -1
  96. package/lib/roles/schema/index.d.ts +0 -44
  97. package/lib/roles/schema/index.js +0 -127
  98. package/lib/roles/schema/types.d.ts +0 -113
  99. package/lib/roles/schema/types.js +0 -1
  100. package/lib/roles/schema/validate.d.ts +0 -9
  101. package/lib/roles/schema/validate.js +0 -128
  102. package/lib/test/publish_mb_bundle.js +0 -296
  103. /package/lib/{modules/encryption/index.d.ts → contracts/data-registry/test.d.ts} +0 -0
  104. /package/lib/{modules/encryption/index.js → contracts/data-registry/test.js} +0 -0
  105. /package/lib/{modules/encryption → crypto}/types.js +0 -0
  106. /package/lib/{test/publish_mb_bundle.d.ts → harness/examples/hackmd/build-markdown-graph.d.ts} +0 -0
@@ -1,7 +1,30 @@
1
1
  import { retrieveByCid, serialize } from "./utils.js";
2
+ import { packCar } from "./car.js";
3
+ import { keccak256, stringToBytes } from "viem";
4
+ import { CID } from "multiformats/cid";
2
5
  import { PinataSDK } from "pinata";
6
+ import * as dagCbor from "@ipld/dag-cbor";
3
7
 
4
8
  //#region src/providers/storage/pinata.ts
9
+ const RAW_CODE = 85;
10
+ const MAX_UPLOAD_ATTEMPTS = Math.max(1, Number(process.env.PINATA_UPLOAD_RETRIES ?? 6));
11
+ function isTransientUpload(err) {
12
+ const e = err;
13
+ const s = typeof e.statusCode === "number" ? e.statusCode : 0;
14
+ if (s === 408 || s === 425 || s === 429 || s >= 500) return true;
15
+ const m = `${e.code ?? ""} ${e.message ?? ""}`;
16
+ return /HTTP_ERROR|disconnect|timed?\s?out|timeout|ECONN|ETIMEDOUT|EAI_AGAIN|socket hang up|network|fetch failed|terminated|aborted|429|408|50\d/i.test(m);
17
+ }
18
+ async function withUploadRetry(label, fn) {
19
+ for (let attempt = 1;; attempt++) try {
20
+ return await fn();
21
+ } catch (err) {
22
+ if (attempt >= MAX_UPLOAD_ATTEMPTS || !isTransientUpload(err)) throw err;
23
+ const delay = Math.min(3e4, 500 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 500);
24
+ console.warn(` [pinata] upload "${label}" failed (attempt ${attempt.toString()}/${MAX_UPLOAD_ATTEMPTS.toString()}), retrying in ${(delay / 1e3).toFixed(1)}s: ${err.message}`);
25
+ await new Promise((r) => setTimeout(r, delay));
26
+ }
27
+ }
5
28
  var PinataBackend = class {
6
29
  pinata;
7
30
  gateway;
@@ -14,36 +37,128 @@ var PinataBackend = class {
14
37
  }
15
38
  async put(data, meta) {
16
39
  const content = serialize(data);
17
- const file = new File([content], meta?.name ?? "file", { type: "text/plain" });
18
- return (await this.pinata.upload.public.file(file, { metadata: meta })).cid;
40
+ const name = meta?.name ?? "file";
41
+ return withUploadRetry(name, async () => {
42
+ const file = new File([content], name, { type: "text/plain" });
43
+ return (await this.pinata.upload.public.file(file, { metadata: meta })).cid;
44
+ });
19
45
  }
46
+ async update(data, meta) {
47
+ const content = serialize(data);
48
+ const name = meta?.name ?? "file";
49
+ return withUploadRetry(name, async () => {
50
+ const file = new File([content], name, { type: "text/plain" });
51
+ const upload = await this.pinata.upload.public.file(file).name(name);
52
+ const stateRoot = keccak256(stringToBytes(upload.cid)).toLowerCase();
53
+ await this.pinata.files.public.update({
54
+ id: upload.id,
55
+ keyvalues: { stateRoot }
56
+ });
57
+ return upload.cid;
58
+ });
59
+ }
60
+ /**
61
+ * Pack every item into ONE locally-built CAR and upload it as a single pin,
62
+ * collapsing N uploads into one request. Returns each item's `ipfs://<root>/<name>`
63
+ * path URI: a CAR upload registers only the directory root as a "file", so the
64
+ * dedicated gateway serves chunks by path through that root (bare sub-block CIDs
65
+ * 403). Callers must bound batch size — the CAR is built in memory.
66
+ */
20
67
  async putMany(items) {
21
68
  if (items.length === 0) return {};
22
- const uriMap = {};
23
- const PINATA_MAX_FILES = 500;
24
- for (let i = 0; i < items.length; i += PINATA_MAX_FILES) {
25
- const subBatch = items.slice(i, i + PINATA_MAX_FILES);
26
- const filesToUpload = subBatch.map(({ data, name }) => {
27
- const content = typeof data === "string" ? data : JSON.stringify(data);
28
- return new File([content], `manifests/${name}.json`, { type: "application/json" });
29
- });
30
- try {
31
- const batchName = `batch-${Date.now().toString()}-${i.toString()}`;
32
- const folderCid = (await this.pinata.upload.public.fileArray(filesToUpload).name(batchName)).cid;
33
- for (const { name } of subBatch) uriMap[name] = `ipfs://${folderCid}/manifests/${name}.json`;
34
- } catch (error) {
35
- console.error(`❌ Pinata sub-batch upload failure at offset ${i.toString()}:`, error);
36
- throw error;
69
+ const { bytes, uriByName } = await packCar(items);
70
+ await withUploadRetry(`car[${items.length.toString()}f/${(bytes.length / 1e6).toFixed(1)}MB]`, async () => {
71
+ const file = new File([bytes], "data.car", { type: "application/vnd.ipld.car" });
72
+ await this.pinata.upload.public.file(file).car();
73
+ });
74
+ return uriByName;
75
+ }
76
+ /**
77
+ * Upload precomputed (cid, bytes) blocks, each as its own plain-file pin,
78
+ * so every block is individually addressable on the dedicated gateway
79
+ * (see RAW_CODE comment above for why this can't go through `.car()`).
80
+ * A single pail commit can touch many shard blocks at once (pail shards
81
+ * key-by-character over shared prefixes, so one write under a namespace
82
+ * that already has sibling keys can split into a whole chain of shard
83
+ * blocks) — upload with bounded concurrency rather than one at a time.
84
+ */
85
+ async putBlocks(blocks) {
86
+ const queue = [...blocks];
87
+ const worker = async () => {
88
+ let next;
89
+ while (next = queue.shift()) {
90
+ const { cid, bytes } = next;
91
+ await withUploadRetry(cid.toString(), async () => {
92
+ const file = new File([bytes], cid.toString(), { type: "application/octet-stream" });
93
+ await this.pinata.upload.public.file(file);
94
+ });
37
95
  }
38
- }
39
- return uriMap;
96
+ };
97
+ await Promise.all(Array.from({ length: Math.min(8, blocks.length) }, worker));
40
98
  }
41
99
  async get(uri) {
42
- return retrieveByCid(uri, this.gateway);
100
+ const { bytes, isDagCborCid, contentType } = await this.fetchRaw(uri);
101
+ if (isDagCborCid || contentType === "application/octet-stream") return dagCbor.decode(bytes);
102
+ const text = new TextDecoder().decode(bytes);
103
+ try {
104
+ return JSON.parse(text);
105
+ } catch {
106
+ return text;
107
+ }
108
+ }
109
+ /** Raw bytes for a block CID, with no decoding — what blockstore traversal needs. */
110
+ async getRawBlock(uri) {
111
+ const { bytes } = await this.fetchRaw(uri);
112
+ return bytes;
113
+ }
114
+ /**
115
+ * Shared fetch-with-retry: resolves the raw-codec sibling CID for blocks
116
+ * uploaded via putBlocks(), fetches from the dedicated gateway, and returns
117
+ * the exact bytes (never pre-decoded) plus enough context for get<T>() to
118
+ * decide how to decode them.
119
+ */
120
+ async fetchRaw(uri) {
121
+ let attempts = 5;
122
+ let lastError;
123
+ let fetchUri = uri;
124
+ const isDagCborCid = uri.startsWith("bafyrei");
125
+ if (isDagCborCid) try {
126
+ fetchUri = CID.createV1(RAW_CODE, CID.parse(uri).multihash).toString();
127
+ } catch {
128
+ fetchUri = uri;
129
+ }
130
+ while (attempts > 0) try {
131
+ const { data, contentType } = await this.pinata.gateways.public.get(fetchUri);
132
+ return {
133
+ bytes: data instanceof Blob ? new Uint8Array(await data.arrayBuffer()) : data instanceof ArrayBuffer ? new Uint8Array(data) : data instanceof Uint8Array ? data : new TextEncoder().encode(typeof data === "string" ? data : JSON.stringify(data)),
134
+ isDagCborCid,
135
+ contentType
136
+ };
137
+ } catch (error) {
138
+ lastError = error;
139
+ attempts--;
140
+ if (attempts === 0) break;
141
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
142
+ }
143
+ throw new Error(`Pinata SDK failed to retrieve block ${uri} after multiple attempts. Internal Error: ${lastError?.message || lastError}`);
43
144
  }
44
145
  static async getStatic(uri, gateway) {
45
146
  return retrieveByCid(uri, gateway);
46
147
  }
148
+ async getCidByStateRoot(stateRoot, retries = 5, delay = 1e3) {
149
+ const formattedRoot = stateRoot.toLowerCase();
150
+ for (let i = 0; i < retries; i++) {
151
+ const response = await this.pinata.files.public.list().keyvalues({ stateRoot: formattedRoot });
152
+ if (response && response.files && response.files.length > 0) return response.files[0].cid;
153
+ if (i < retries - 1) {
154
+ console.warn(`
155
+ [Pinata] Indexing lag detected for root ${formattedRoot}. Retrying in ${delay * (i + 1)}ms...
156
+ `);
157
+ await new Promise((resolve) => setTimeout(resolve, delay * (i + 1)));
158
+ }
159
+ }
160
+ throw new Error(`No matching IPFS CID found for state root: ${stateRoot} after ${retries} retrieval attempts.`);
161
+ }
47
162
  async delete(uri) {
48
163
  await this.pinata.files.public.delete([uri]);
49
164
  }
@@ -1,45 +1,52 @@
1
+ import { CID } from "multiformats/cid";
2
+
1
3
  //#region src/providers/storage/types.d.ts
4
+
2
5
  /**
3
- * StorageBackend — backend-agnostic interface for storing and retrieving
4
- * opaque content. The URI returned by put() is the only thing callers
5
- * hold onto; get() knows how to resolve it.
6
+ * A backend-agnostic interface for storing and retrieving opaque content.
6
7
  */
7
8
  interface StorageMeta {
8
9
  name?: string;
9
10
  [key: string]: unknown;
10
11
  }
12
+ /** A content-addressed block whose CID is already known to the caller. */
13
+ interface RawBlock {
14
+ cid: CID;
15
+ bytes: Uint8Array;
16
+ }
11
17
  interface MetadataStorage {
12
18
  /**
13
19
  * Store content and return an opaque URI.
14
- * Callers never construct or parse URIs — treat them as handles.
20
+ * Callers never construct or parse URIs, they should be treated as handles.
15
21
  */
16
22
  put(data: unknown, meta?: StorageMeta): Promise<string>;
17
23
  /**
18
- * Pack multiple items into a single CAR and upload as one pin.
19
- * Returns a map of { name -> CID } for each item.
24
+ * Pack multiple items into a single upload
25
+ * Returns a map of { name -> identifier } for each item
20
26
  */
21
27
  putMany(items: {
22
28
  data: unknown;
23
29
  name: string;
24
30
  }[]): Promise<Record<string, string>>;
31
+ /**
32
+ * Upload precomputed (cid, bytes) blocks, preserving their exact CIDs so
33
+ * they remain retrievable by `get(cid.toString())`.
34
+ */
35
+ putBlocks(blocks: RawBlock[]): Promise<void>;
25
36
  /**
26
37
  * Retrieve content by URI previously returned from put().
27
38
  */
28
39
  get<T>(uri: string): Promise<T>;
29
40
  /**
30
- * Delete content by URI. Best-effort — implementations may no-op.
41
+ * Retrieve the exact raw bytes for a block CID, with no decoding applied —
42
+ * what content-addressed tree traversal (e.g. the Pail blockstore adapter)
43
+ * needs, as opposed to get()'s already-decoded logical payload.
44
+ */
45
+ getRawBlock(uri: string): Promise<Uint8Array>;
46
+ /**
47
+ * Delete content by URI
31
48
  */
32
49
  delete(uri: string): Promise<void>;
33
50
  }
34
- /**
35
- * Proof required by access-controlled backends (e.g. R2 via the Fangorn worker).
36
- * Plain backends (e.g. IPFS) ignore this entirely.
37
- */
38
- interface AccessProof {
39
- nullifier: string;
40
- resourceId: string;
41
- timestamp: number;
42
- signature: `0x${string}`;
43
- }
44
51
  //#endregion
45
- export { AccessProof, MetadataStorage, StorageMeta };
52
+ export { MetadataStorage, RawBlock, StorageMeta };
@@ -0,0 +1,56 @@
1
+ import { Address, Hex } from "viem";
2
+
3
+ //#region src/roles/repo/index.d.ts
4
+
5
+ /**
6
+ * The local working repo — a `.fangorn/` directory, the analogue of `.git/`.
7
+ *
8
+ * It records just enough to identify the on-chain dataset this working copy
9
+ * tracks and where local history currently points:
10
+ *
11
+ * .fangorn/
12
+ * config.json — { name, schemaId, owner }: the (owner, schemaId, name)
13
+ * triple that keys the dataset in the DataSource registry.
14
+ * HEAD — the CID of the local tip commit, or empty before the first
15
+ * commit. This is what `push` compares against the on-chain
16
+ * tip, and what the next `commit` uses as its parent.
17
+ *
18
+ * `commit` moves HEAD locally (permissionless). `push` reconciles HEAD with the
19
+ * on-chain ref (the permissioned step). See docs/PROTOCOL.md §5, §7.
20
+ */
21
+ declare const REPO_DIR = ".fangorn";
22
+ interface RepoConfig {
23
+ /** Dataset name — the human-facing repo name, part of the on-chain key. */
24
+ name: string;
25
+ /** Schema reference as given at init (name or bytes32 id) — used to resolve
26
+ * the schema shape when building commits. */
27
+ schema: string;
28
+ /** Resolved schema id — the on-chain key component. */
29
+ schemaId: Hex;
30
+ /** Owner address (the wallet that keys the on-chain dataset). */
31
+ owner: Address;
32
+ }
33
+ declare class LocalRepo {
34
+ private readonly root;
35
+ /** @param root the directory containing `.fangorn/` (the working dir). */
36
+ private constructor();
37
+ private get dir();
38
+ private get configPath();
39
+ private get headPath();
40
+ /** True if `dir` already contains a `.fangorn/` repo. */
41
+ static exists(root?: string): boolean;
42
+ /**
43
+ * Initialize a new repo in `root`. Throws if one already exists so we never
44
+ * silently clobber an existing HEAD/config.
45
+ */
46
+ static init(config: RepoConfig, root?: string): LocalRepo;
47
+ /** Open an existing repo. Throws if there isn't one. */
48
+ static open(root?: string): LocalRepo;
49
+ config(): RepoConfig;
50
+ /** Local tip commit CID, or undefined before the first commit. */
51
+ head(): string | undefined;
52
+ /** Move the local tip to `cid`. */
53
+ setHead(cid: string): void;
54
+ }
55
+ //#endregion
56
+ export { LocalRepo, REPO_DIR, RepoConfig };
@@ -0,0 +1,73 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
2
+ import { join } from "path";
3
+
4
+ //#region src/roles/repo/index.ts
5
+ /**
6
+ * The local working repo — a `.fangorn/` directory, the analogue of `.git/`.
7
+ *
8
+ * It records just enough to identify the on-chain dataset this working copy
9
+ * tracks and where local history currently points:
10
+ *
11
+ * .fangorn/
12
+ * config.json — { name, schemaId, owner }: the (owner, schemaId, name)
13
+ * triple that keys the dataset in the DataSource registry.
14
+ * HEAD — the CID of the local tip commit, or empty before the first
15
+ * commit. This is what `push` compares against the on-chain
16
+ * tip, and what the next `commit` uses as its parent.
17
+ *
18
+ * `commit` moves HEAD locally (permissionless). `push` reconciles HEAD with the
19
+ * on-chain ref (the permissioned step). See docs/PROTOCOL.md §5, §7.
20
+ */
21
+ const REPO_DIR = ".fangorn";
22
+ var LocalRepo = class LocalRepo {
23
+ /** @param root the directory containing `.fangorn/` (the working dir). */
24
+ constructor(root) {
25
+ this.root = root;
26
+ }
27
+ get dir() {
28
+ return join(this.root, REPO_DIR);
29
+ }
30
+ get configPath() {
31
+ return join(this.dir, "config.json");
32
+ }
33
+ get headPath() {
34
+ return join(this.dir, "HEAD");
35
+ }
36
+ /** True if `dir` already contains a `.fangorn/` repo. */
37
+ static exists(root = process.cwd()) {
38
+ return existsSync(join(root, REPO_DIR, "config.json"));
39
+ }
40
+ /**
41
+ * Initialize a new repo in `root`. Throws if one already exists so we never
42
+ * silently clobber an existing HEAD/config.
43
+ */
44
+ static init(config, root = process.cwd()) {
45
+ const repo = new LocalRepo(root);
46
+ if (existsSync(repo.configPath)) throw new Error(`a Fangorn repo already exists at ${repo.dir}`);
47
+ mkdirSync(repo.dir, { recursive: true });
48
+ writeFileSync(repo.configPath, JSON.stringify(config, null, 2), "utf-8");
49
+ writeFileSync(repo.headPath, "", "utf-8");
50
+ return repo;
51
+ }
52
+ /** Open an existing repo. Throws if there isn't one. */
53
+ static open(root = process.cwd()) {
54
+ const repo = new LocalRepo(root);
55
+ if (!existsSync(repo.configPath)) throw new Error(`not a Fangorn repo (no ${REPO_DIR}/ found in ${root}). Run \`fangorn init\`.`);
56
+ return repo;
57
+ }
58
+ config() {
59
+ return JSON.parse(readFileSync(this.configPath, "utf-8"));
60
+ }
61
+ /** Local tip commit CID, or undefined before the first commit. */
62
+ head() {
63
+ const raw = readFileSync(this.headPath, "utf-8").trim();
64
+ return raw.length > 0 ? raw : void 0;
65
+ }
66
+ /** Move the local tip to `cid`. */
67
+ setHead(cid) {
68
+ writeFileSync(this.headPath, cid, "utf-8");
69
+ }
70
+ };
71
+
72
+ //#endregion
73
+ export { LocalRepo, REPO_DIR };
@@ -0,0 +1 @@
1
+ import "dotenv/config";
@@ -0,0 +1,81 @@
1
+ import { PinataBackend } from "../providers/storage/pinata.js";
2
+ import "dotenv/config";
3
+
4
+ //#region src/test/car_smoke.ts
5
+ async function main() {
6
+ const jwt = process.env.PINATA_JWT;
7
+ const gateway = process.env.PINATA_GATEWAY;
8
+ if (!jwt || !gateway) throw new Error("Set PINATA_JWT and PINATA_GATEWAY");
9
+ const backend = new PinataBackend(jwt, gateway);
10
+ const items = [
11
+ {
12
+ name: "chunk-small:0",
13
+ data: [{
14
+ id: "a",
15
+ v: 1
16
+ }, {
17
+ id: "b",
18
+ v: 2
19
+ }]
20
+ },
21
+ {
22
+ name: "chunk-big:1",
23
+ data: Array.from({ length: 4e4 }, (_, i) => ({
24
+ id: `r${i.toString()}`,
25
+ blob: "x".repeat(40)
26
+ }))
27
+ },
28
+ {
29
+ name: "chunk-bytes:2",
30
+ data: {
31
+ tag: "u8",
32
+ bytes: new Uint8Array([
33
+ 1,
34
+ 2,
35
+ 3,
36
+ 250,
37
+ 255
38
+ ])
39
+ }
40
+ }
41
+ ];
42
+ console.log(`[smoke] packing + uploading ${items.length.toString()} chunks as one CAR...`);
43
+ const t0 = Date.now();
44
+ const cidByName = await backend.putMany(items);
45
+ console.log(`[smoke] uploaded in ${((Date.now() - t0) / 1e3).toFixed(1)}s`);
46
+ for (const { name } of items) console.log(` ${name} -> ${cidByName[name]}`);
47
+ console.log(`[smoke] retrieving each chunk by its standalone CID...`);
48
+ let ok = true;
49
+ for (const { name, data } of items) {
50
+ const cid = cidByName[name];
51
+ if (!cid) {
52
+ console.error(` ✘ ${name}: no CID returned`);
53
+ ok = false;
54
+ continue;
55
+ }
56
+ try {
57
+ const got = await backend.get(cid);
58
+ const match = JSON.stringify(got) === JSON.stringify(data);
59
+ console.log(` ${match ? "✓" : "✘"} ${name} (${cid})`);
60
+ if (!match) {
61
+ ok = false;
62
+ console.error(` expected ${JSON.stringify(data).slice(0, 80)}\n got ${JSON.stringify(got).slice(0, 80)}`);
63
+ }
64
+ } catch (err) {
65
+ ok = false;
66
+ console.error(` ✘ ${name} (${cid}): ${err.message}`);
67
+ }
68
+ }
69
+ if (!ok) {
70
+ console.error("\n[smoke] FAILED — CAR sub-blocks are not independently retrievable");
71
+ process.exit(1);
72
+ }
73
+ console.log("\n[smoke] ✅ CAR path verified: every chunk CID resolves via the gateway.");
74
+ }
75
+ main().catch((err) => {
76
+ console.error("[smoke] failed:", err);
77
+ process.exit(1);
78
+ });
79
+
80
+ //#endregion
81
+ export { };
@@ -1,18 +1,17 @@
1
- import { TestBed } from "./testbed.js";
2
1
  import { LEDGER_FILE } from "./setup-embeddings-testdata.js";
3
- import { arbitrumSepolia } from "viem/chains";
4
- import { createWalletClient, http } from "viem";
5
- import { privateKeyToAccount } from "viem/accounts";
6
2
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
7
3
 
8
4
  //#region src/test/cleanup-embeddings-testdata.ts
9
5
  /**
10
6
  * Cleanup counterpart to setup-embeddings-testdata.ts.
11
7
  *
12
- * Reads the ledger written by the setup script and unpins, for every recorded
13
- * run, the v3 bundle manifest plus all of its node + edge chunk CIDs from
14
- * Pinata. Schema registrations are on-chain and cannot be removed; this only
15
- * reclaims the IPFS pins the test data created.
8
+ * Reads the ledger written by the setup script and best-effort unpins, for
9
+ * every recorded run, the vertex CIDs it uploaded from Pinata. On-chain state
10
+ * (the namespace root) is not rewound — only `fangorn.reset()` (destructive,
11
+ * wipes ALL namespaces for that owner) can do that; this script only reclaims
12
+ * the IPFS pins for the vertex payloads themselves. Intermediate Pail shard
13
+ * blocks created alongside them are not individually tracked and are left
14
+ * pinned (they're small, content-addressed, and shared across commits).
16
15
  *
17
16
  * Run it:
18
17
  *
@@ -21,23 +20,7 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs";
21
20
  *
22
21
  * The ledger is deleted only if every CID unpinned cleanly.
23
22
  */
24
- const SK = process.env.DELEGATOR_ETH_PRIVATE_KEY;
25
- const RPC_URL = process.env.RPC_URL ?? process.env.CHAIN_RPC_URL ?? "https://sepolia-rollup.arbitrum.io/rpc";
26
- const WORKER_URL = process.env.WORKER_URL ?? "http://localhost:8787";
27
23
  const PINATA_JWT = process.env.PINATA_JWT ?? "";
28
- const SETTLEMENT_REGISTRY_ADDRESS = process.env.SETTLEMENT_REGISTRY_ADDRESS;
29
- const DATA_SOURCE_REGISTRY_ADDRESS = process.env.DATA_SOURCE_REGISTRY_ADDRESS;
30
- const SCHEMA_REGISTRY_ADDRESS = process.env.SCHEMA_REGISTRY_ADDRESS;
31
- const USDC_ADDRESS = process.env.USDC_ADDRESS ?? process.env.USDC_CONTRACT_ADDRESS ?? "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d";
32
- const USDC_DOMAIN = "USD Coin";
33
- const CHAIN = arbitrumSepolia;
34
- function makeWallet(key) {
35
- return createWalletClient({
36
- account: privateKeyToAccount(key),
37
- chain: CHAIN,
38
- transport: http(RPC_URL)
39
- });
40
- }
41
24
  async function unpinFromPinata(cid) {
42
25
  try {
43
26
  const response = await fetch(`https://api.pinata.cloud/pinning/unpin/${cid}`, {
@@ -70,22 +53,10 @@ async function main() {
70
53
  console.log("[cleanup] ledger is empty — nothing to clean up.");
71
54
  return;
72
55
  }
73
- const publisher = TestBed.init(makeWallet(SK), DATA_SOURCE_REGISTRY_ADDRESS, SCHEMA_REGISTRY_ADDRESS, SETTLEMENT_REGISTRY_ADDRESS, USDC_ADDRESS, USDC_DOMAIN, RPC_URL, "arbitrumSepolia", CHAIN.id, WORKER_URL).getDelegatorFangorn().publisher;
74
56
  let allOk = true;
75
57
  for (const entry of entries) {
76
- console.log(`\n[cleanup] ${entry.bundleName} (manifest ${entry.manifestUri})`);
77
- const cids = [];
78
- try {
79
- const manifest = await publisher.getBundleManifestByCid(entry.manifestUri);
80
- if (manifest) {
81
- for (const c of manifest.nodeChunks) cids.push(c.dataCid);
82
- if (manifest.edgeChunk.dataCid) cids.push(manifest.edgeChunk.dataCid);
83
- } else console.warn(" (could not read manifest — unpinning manifest CID only)");
84
- } catch (err) {
85
- console.warn(" (failed to read manifest — unpinning manifest CID only)", err);
86
- }
87
- cids.push(entry.manifestUri);
88
- for (const cid of cids) {
58
+ console.log(`\n[cleanup] ${entry.owner}/${entry.namespace} (commit ${entry.commitCid})`);
59
+ for (const cid of entry.vertexCids) {
89
60
  const ok = await unpinFromPinata(cid);
90
61
  allOk = allOk && ok;
91
62
  }
@@ -1,12 +1,10 @@
1
- import { Hex } from "viem";
2
-
3
1
  //#region src/test/setup-embeddings-testdata.d.ts
4
2
  declare const LEDGER_FILE: string;
5
3
  interface LedgerEntry {
6
- bundleName: string;
7
- bundleSchemaId: Hex;
8
- datasetName: string;
9
- manifestUri: string;
4
+ owner: string;
5
+ namespace: string;
6
+ commitCid: string;
7
+ vertexCids: string[];
10
8
  createdAt: string;
11
9
  }
12
10
  //#endregion