@fangorn-network/sdk 2026.5.10 → 2026.6.16

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 (56) hide show
  1. package/README.md +87 -37
  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/ crypto/utils.d.ts +1 -0
  7. package/lib/ crypto/utils.js +1 -0
  8. package/lib/cli/cli.js +61 -156
  9. package/lib/cli/index.d.ts +171 -170
  10. package/lib/config.d.ts +258 -257
  11. package/lib/config.js +3 -3
  12. package/lib/fangorn.js +2 -2
  13. package/lib/index.d.ts +1 -3
  14. package/lib/index.js +1 -3
  15. package/lib/modules/encryption/rand.d.ts +1 -1
  16. package/lib/providers/storage/pinata.d.ts +5 -1
  17. package/lib/providers/storage/pinata.js +24 -3
  18. package/lib/providers/storage/types.d.ts +8 -0
  19. package/lib/providers/storage/utils.js +2 -1
  20. package/lib/registries/datasource-registry/abi.d.ts +34 -4
  21. package/lib/registries/datasource-registry/abi.js +40 -5
  22. package/lib/registries/datasource-registry/index.d.ts +22 -13
  23. package/lib/registries/datasource-registry/index.js +76 -76
  24. package/lib/registries/index.d.ts +1 -1
  25. package/lib/registries/schema-registry/index.d.ts +3 -3
  26. package/lib/registries/schema-registry/index.js +1 -1
  27. package/lib/registries/settlement-registry/index.d.ts +2 -2
  28. package/lib/roles/consumer/index.d.ts +3 -3
  29. package/lib/roles/consumer/index.js +19 -12
  30. package/lib/roles/publisher/builders/bundle.d.ts +32 -0
  31. package/lib/roles/publisher/builders/bundle.js +137 -0
  32. package/lib/roles/publisher/builders/record-set.d.ts +17 -0
  33. package/lib/roles/publisher/builders/record-set.js +55 -0
  34. package/lib/roles/publisher/builders/types.d.ts +38 -0
  35. package/lib/roles/publisher/builders/types.js +1 -0
  36. package/lib/roles/publisher/builders/utils.d.ts +9 -0
  37. package/lib/roles/publisher/builders/utils.js +29 -0
  38. package/lib/roles/publisher/encryption.d.ts +18 -0
  39. package/lib/roles/publisher/encryption.js +38 -0
  40. package/lib/roles/publisher/index.d.ts +54 -36
  41. package/lib/roles/publisher/index.js +137 -174
  42. package/lib/roles/publisher/types.d.ts +61 -46
  43. package/lib/roles/schema/index.d.ts +30 -4
  44. package/lib/roles/schema/index.js +81 -47
  45. package/lib/roles/schema/types.d.ts +59 -37
  46. package/lib/roles/schema/validate.d.ts +9 -0
  47. package/lib/roles/schema/validate.js +128 -0
  48. package/lib/test/cleanup-embeddings-testdata.d.ts +1 -0
  49. package/lib/test/cleanup-embeddings-testdata.js +104 -0
  50. package/lib/test/publish_mb_bundle.d.ts +1 -0
  51. package/lib/test/publish_mb_bundle.js +296 -0
  52. package/lib/test/setup-embeddings-testdata.d.ts +13 -0
  53. package/lib/test/setup-embeddings-testdata.js +209 -0
  54. package/lib/test/testbed.d.ts +14 -8
  55. package/lib/test/testbed.js +28 -24
  56. package/package.json +16 -2
@@ -0,0 +1,296 @@
1
+ import { TestBed } from "./testbed.js";
2
+ import { arbitrumSepolia } from "viem/chains";
3
+ import { createWalletClient, http } from "viem";
4
+ import { privateKeyToAccount } from "viem/accounts";
5
+ import { program } from "commander";
6
+ import streamArray from "stream-json/streamers/stream-array.js";
7
+ import { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import { join, resolve } from "node:path";
9
+ import { open } from "lmdb";
10
+
11
+ //#region src/test/publish_mb_bundle.ts
12
+ /**
13
+ * Publish MusicBrainz dump data to Fangorn as a v3 bundle.
14
+ *
15
+ * This script registers the Track + TrackTaxonomy node schemas and the
16
+ * hasTaxonomy bundle schema (all idempotent — safe to re-run), then publishes
17
+ * the JSON chunk files produced by `quickbeam data mb` as a sequence of
18
+ * ManifestPublished events consumable by `quickbeam build --bundle`.
19
+ *
20
+ * ─── SETUP ───────────────────────────────────────────────────────────────────
21
+ * This file must be placed alongside setup-embeddings-testdata.ts in the
22
+ * fangorn-sdk repo (src/publish_mb_bundle.ts) to resolve its imports.
23
+ *
24
+ * Run from the fangorn-sdk root:
25
+ * pnpm dotenvx run -f .env -- tsx src/test/publish_mb_bundle.ts \
26
+ * --tracks /path/to/volume_1_tracks.json \
27
+ * --taxonomies /path/to/volume_1_taxonomies.json \
28
+ * --edges /path/to/volume_1_edges.json \
29
+ * --dataset ds.mb.v1
30
+ *
31
+ * Optional flags:
32
+ * --batch-size <n> Nodes per publishBundle call (default 2000)
33
+ * --bundle-name <name> Override bundle schema name (default fangorn.mb.bundle.v1)
34
+ * --track-schema <name> Override Track schema name
35
+ * --taxonomy-schema <name> Override TrackTaxonomy schema name
36
+ * ─────────────────────────────────────────────────────────────────────────────
37
+ */
38
+ const SK = process.env.DELEGATOR_ETH_PRIVATE_KEY;
39
+ const RPC_URL = process.env.RPC_URL ?? process.env.CHAIN_RPC_URL ?? "https://sepolia-rollup.arbitrum.io/rpc";
40
+ const WORKER_URL = process.env.WORKER_URL ?? "http://localhost:8787";
41
+ const SETTLEMENT_REGISTRY_ADDRESS = process.env.SETTLEMENT_REGISTRY_ADDRESS;
42
+ const DATA_SOURCE_REGISTRY_ADDRESS = process.env.DATA_SOURCE_REGISTRY_ADDRESS;
43
+ const SCHEMA_REGISTRY_ADDRESS = process.env.SCHEMA_REGISTRY_ADDRESS;
44
+ const USDC_ADDRESS = process.env.USDC_ADDRESS ?? process.env.USDC_CONTRACT_ADDRESS ?? "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d";
45
+ const USDC_DOMAIN = "USD Coin";
46
+ const CHAIN = arbitrumSepolia;
47
+ const TRACK_SCHEMA = {
48
+ schemaVersion: { "@type": "number" },
49
+ trackId: { "@type": "string" },
50
+ isrcCode: { "@type": "string | null" },
51
+ title: { "@type": "string" },
52
+ byArtist: { "@type": "string" },
53
+ albumName: { "@type": "string | null" },
54
+ datePublished: { "@type": "string | null" },
55
+ durationMs: { "@type": "number | null" },
56
+ contributors: {
57
+ "@type": "array",
58
+ items: {
59
+ role: { "@type": "string | null" },
60
+ name: { "@type": "string | null" },
61
+ id: { "@type": "string | null" }
62
+ }
63
+ }
64
+ };
65
+ const TAXONOMY_SCHEMA = {
66
+ schemaVersion: { "@type": "number" },
67
+ trackId: { "@type": "string" },
68
+ genres: {
69
+ "@type": "array",
70
+ items: { "@type": "string" }
71
+ },
72
+ moods: {
73
+ "@type": "array",
74
+ items: { "@type": "string" }
75
+ },
76
+ themes: {
77
+ "@type": "array",
78
+ items: { "@type": "string" }
79
+ },
80
+ contexts: {
81
+ "@type": "array",
82
+ items: { "@type": "string" }
83
+ }
84
+ };
85
+ /**
86
+ * Stream the elements of a top-level JSON array file one at a time. Avoids
87
+ * readFileSync()+JSON.parse(), which materializes the whole file as a single
88
+ * string (>512MB hits V8's ERR_STRING_TOO_LONG) plus a full object-graph copy.
89
+ */
90
+ async function* streamJsonArray(path) {
91
+ const pipeline = createReadStream(path).pipe(streamArray.withParserAsStream());
92
+ for await (const { value } of pipeline) yield value;
93
+ }
94
+ /**
95
+ * Stream a JSON-array file into an LMDB sub-database in committed batches, so the
96
+ * full index lives on disk (memory-mapped) instead of the JS heap. `keyFn`
97
+ * derives each record's key; `seq` is a per-call running counter for composite keys.
98
+ * Returns the number of records written.
99
+ */
100
+ async function bulkLoad(db, source, keyFn) {
101
+ const BATCH = 2e4;
102
+ let buf = [];
103
+ let n = 0;
104
+ const commit = () => {
105
+ const pending = buf;
106
+ buf = [];
107
+ db.transactionSync(() => {
108
+ for (const [k, v] of pending) db.putSync(k, v);
109
+ });
110
+ };
111
+ for await (const item of source) {
112
+ buf.push([keyFn(item, n), item]);
113
+ n++;
114
+ if (buf.length >= BATCH) commit();
115
+ }
116
+ if (buf.length) commit();
117
+ return n;
118
+ }
119
+ /** Strip undefined values; null is kept so nullable schema fields validate correctly. */
120
+ function cleanFields(raw) {
121
+ const out = {};
122
+ for (const [k, v] of Object.entries(raw)) if (v !== void 0) out[k] = v;
123
+ return out;
124
+ }
125
+ async function withRetry(label, maxAttempts, fn) {
126
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
127
+ return await fn();
128
+ } catch (err) {
129
+ if (attempt === maxAttempts) throw err;
130
+ const delayMs = 2e3 * attempt;
131
+ console.warn(` [retry] ${label} failed (attempt ${attempt.toString()}/${maxAttempts.toString()}), retrying in ${(delayMs / 1e3).toString()}s: ${err.message}`);
132
+ await new Promise((r) => setTimeout(r, delayMs));
133
+ }
134
+ throw new Error("unreachable");
135
+ }
136
+ function loadLedger(path) {
137
+ if (!existsSync(path)) return null;
138
+ try {
139
+ return JSON.parse(readFileSync(path, "utf8"));
140
+ } catch {
141
+ return null;
142
+ }
143
+ }
144
+ function saveLedger(path, ledger) {
145
+ mkdirSync("tmp", { recursive: true });
146
+ writeFileSync(path, JSON.stringify(ledger, null, 2));
147
+ }
148
+ program.requiredOption("--tracks <path>", "volume_N_tracks.json from quickbeam data mb").requiredOption("--taxonomies <path>", "volume_N_taxonomies.json").requiredOption("--edges <path>", "volume_N_edges.json").requiredOption("--dataset <name>", "Base dataset name, e.g. ds.mb.v1").option("--batch-size <n>", "Track nodes per publishBundle call", "2000").option("--bundle-name <name>", "Bundle schema name", "fangorn.mb.bundle.v1").option("--bundle-schema-id <hex>", "Reuse an existing bundle schema ID and skip registration").option("--track-schema <name>", "Track node schema name", "sond3r.track.invariants.v1").option("--taxonomy-schema <name>", "TrackTaxonomy node schema name", "sond3r.track.taxonomy.v1").option("--ledger <path>", "Ledger file path (default: tmp/mb-publish-<dataset>.json)").option("--index-dir <path>", "Directory for the temporary on-disk LMDB index — MUST be on real disk, not tmpfs/RAM", "tmp").option("--max-retries <n>", "Retry attempts per batch on transient failures", "5").parse();
149
+ const opts = program.opts();
150
+ function requireEnv() {
151
+ const missing = [];
152
+ if (SK === "0x") missing.push("DELEGATOR_ETH_PRIVATE_KEY");
153
+ if (DATA_SOURCE_REGISTRY_ADDRESS === "0x") missing.push("DATA_SOURCE_REGISTRY_ADDRESS");
154
+ if (SCHEMA_REGISTRY_ADDRESS === "0x") missing.push("SCHEMA_REGISTRY_ADDRESS");
155
+ if (!process.env.PINATA_JWT) missing.push("PINATA_JWT");
156
+ if (missing.length) throw new Error(`Missing env vars: ${missing.join(", ")}`);
157
+ }
158
+ async function main() {
159
+ requireEnv();
160
+ const batchSize = parseInt(opts.batchSize, 10);
161
+ const maxRetries = parseInt(opts.maxRetries, 10);
162
+ const testbed = TestBed.init(createWalletClient({
163
+ account: privateKeyToAccount(SK),
164
+ chain: CHAIN,
165
+ transport: http(RPC_URL)
166
+ }), DATA_SOURCE_REGISTRY_ADDRESS, SCHEMA_REGISTRY_ADDRESS, SETTLEMENT_REGISTRY_ADDRESS, USDC_ADDRESS, USDC_DOMAIN, RPC_URL, "arbitrumSepolia", CHAIN.id, WORKER_URL);
167
+ console.log("[publish] registering node schemas...");
168
+ await testbed.registerSchema(opts.trackSchema, TRACK_SCHEMA);
169
+ await testbed.registerSchema(opts.taxonomySchema, TAXONOMY_SCHEMA);
170
+ let bundleSchemaId;
171
+ if (opts.bundleSchemaId) {
172
+ bundleSchemaId = opts.bundleSchemaId;
173
+ console.log(`[publish] reusing bundle schema id: ${bundleSchemaId}`);
174
+ } else {
175
+ console.log("[publish] registering bundle shape...");
176
+ const bundle = {
177
+ nodes: {
178
+ Track: opts.trackSchema,
179
+ TrackTaxonomy: opts.taxonomySchema
180
+ },
181
+ edges: [{
182
+ rel: "hasTaxonomy",
183
+ from: "Track",
184
+ to: "TrackTaxonomy",
185
+ min: 1,
186
+ max: 1
187
+ }]
188
+ };
189
+ bundleSchemaId = await testbed.registerBundle(opts.bundleName, bundle);
190
+ console.log(`[publish] bundle schema id: ${bundleSchemaId}`);
191
+ }
192
+ const ledgerPath = opts.ledger ?? `tmp/mb-publish-${opts.dataset.replace(/[^a-z0-9._-]/gi, "_")}.json`;
193
+ const indexBase = resolve(opts.indexDir);
194
+ mkdirSync(indexBase, { recursive: true });
195
+ const indexDir = mkdtempSync(join(indexBase, "mb-index-"));
196
+ console.log(`[publish] LMDB index dir: ${indexDir}`);
197
+ const indexEnv = open({
198
+ path: indexDir,
199
+ compression: false,
200
+ noSync: true,
201
+ maxDbs: 2
202
+ });
203
+ const taxoDb = indexEnv.openDB({ name: "taxo" });
204
+ const edgeDb = indexEnv.openDB({ name: "edge" });
205
+ try {
206
+ console.log("[publish] indexing taxonomies + edges (on-disk LMDB)...");
207
+ const taxoCount = await bulkLoad(taxoDb, streamJsonArray(opts.taxonomies), (t) => t.name);
208
+ const edgeCount = await bulkLoad(edgeDb, streamJsonArray(opts.edges), (e, seq) => [e.from, seq]);
209
+ console.log(`[publish] ${taxoCount.toString()} taxonomies, ${edgeCount.toString()} edges indexed → ${indexDir}`);
210
+ const ledger = loadLedger(ledgerPath) ?? {
211
+ bundleName: opts.bundleName,
212
+ bundleSchemaId,
213
+ batches: []
214
+ };
215
+ ledger.batches.map((b) => b.batchIndex).sort((a, b) => a - b).forEach((idx, i) => {
216
+ if (idx !== i) throw new Error(`Ledger batch indices are not a contiguous 0..N prefix (gap near index ${idx.toString()}); offset-based resume would be unsafe. Inspect ${ledgerPath}.`);
217
+ });
218
+ const tracksDone = ledger.batches.reduce((sum, b) => sum + b.trackCount, 0);
219
+ let nextBatchIdx = ledger.batches.length;
220
+ const firstNewIdx = nextBatchIdx;
221
+ if (tracksDone > 0) console.log(`[publish] resuming: ${tracksDone.toString()} tracks already published across ${nextBatchIdx.toString()} batches — skipping those`);
222
+ console.log(`[publish] publishing remaining tracks in batches of up to ${batchSize.toString()}`);
223
+ let seen = 0;
224
+ let trackTotal = 0;
225
+ let batchTracks = [];
226
+ const flushBatch = async () => {
227
+ const tracks = batchTracks;
228
+ batchTracks = [];
229
+ if (tracks.length === 0) return;
230
+ const thisIdx = nextBatchIdx++;
231
+ const batchDataset = `${opts.dataset}.batch${thisIdx.toString()}`;
232
+ const batchNodes = [];
233
+ const batchEdges = [];
234
+ for (const track of tracks) {
235
+ batchNodes.push({
236
+ id: track.name,
237
+ type: "Track",
238
+ fields: cleanFields(track.fields)
239
+ });
240
+ const taxo = taxoDb.get(track.name);
241
+ if (taxo) batchNodes.push({
242
+ id: `taxonomy:${taxo.name}`,
243
+ type: "TrackTaxonomy",
244
+ fields: cleanFields(taxo.fields)
245
+ });
246
+ for (const { value } of edgeDb.getRange({
247
+ start: [track.name],
248
+ end: [`${track.name}\x00`]
249
+ })) batchEdges.push(value);
250
+ }
251
+ console.log(`[publish] batch ${thisIdx.toString()}: ${tracks.length.toString()} tracks → ${batchDataset}`);
252
+ const manifestUri = await withRetry(`batch ${thisIdx.toString()}`, maxRetries, () => testbed.publishBundle(opts.bundleName, batchNodes, batchEdges, batchDataset));
253
+ ledger.batches.push({
254
+ batchIndex: thisIdx,
255
+ dataset: batchDataset,
256
+ manifestUri,
257
+ trackCount: tracks.length,
258
+ publishedAt: (/* @__PURE__ */ new Date()).toISOString()
259
+ });
260
+ saveLedger(ledgerPath, ledger);
261
+ console.log(` ✓ manifest: ${manifestUri}`);
262
+ };
263
+ for await (const track of streamJsonArray(opts.tracks)) {
264
+ seen++;
265
+ if (seen <= tracksDone) continue;
266
+ batchTracks.push(track);
267
+ trackTotal++;
268
+ if (batchTracks.length >= batchSize) await flushBatch();
269
+ }
270
+ await flushBatch();
271
+ console.log(`[publish] ${trackTotal.toString()} new tracks across ${(nextBatchIdx - firstNewIdx).toString()} new batches`);
272
+ console.log("\n✅ All batches published.\n");
273
+ console.log(` bundle name : ${opts.bundleName}`);
274
+ console.log(` bundle id : ${bundleSchemaId}`);
275
+ console.log(` batches : ${ledger.batches.length.toString()}`);
276
+ console.log(` ledger : ${ledgerPath}`);
277
+ console.log("\nBuild embeddings with:\n");
278
+ console.log(` quickbeam build \\`);
279
+ console.log(` --bundle "${opts.bundleName}=${bundleSchemaId}" \\`);
280
+ console.log(` --root-type Track \\`);
281
+ console.log(` --reset\n`);
282
+ } finally {
283
+ await indexEnv.close();
284
+ rmSync(indexDir, {
285
+ recursive: true,
286
+ force: true
287
+ });
288
+ }
289
+ }
290
+ main().catch((err) => {
291
+ console.error("\n[publish] failed:", err);
292
+ process.exit(1);
293
+ });
294
+
295
+ //#endregion
296
+ export { };
@@ -0,0 +1,13 @@
1
+ import { Hex } from "viem";
2
+
3
+ //#region src/test/setup-embeddings-testdata.d.ts
4
+ declare const LEDGER_FILE: string;
5
+ interface LedgerEntry {
6
+ bundleName: string;
7
+ bundleSchemaId: Hex;
8
+ datasetName: string;
9
+ manifestUri: string;
10
+ createdAt: string;
11
+ }
12
+ //#endregion
13
+ export { LEDGER_FILE, LedgerEntry };
@@ -0,0 +1,209 @@
1
+ import { TestBed } from "./testbed.js";
2
+ import { arbitrumSepolia } from "viem/chains";
3
+ import { createWalletClient, http } from "viem";
4
+ import { privateKeyToAccount } from "viem/accounts";
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { dirname } from "node:path";
7
+
8
+ //#region src/test/setup-embeddings-testdata.ts
9
+ /**
10
+ * Test-data setup for the Python embeddings builder (embeddings.py, bundle mode).
11
+ *
12
+ * Registers a minimalist music bundle (Track + Artist) and publishes a handful
13
+ * of joined records as a single v3 bundle commitment. This is exactly the shape
14
+ * embeddings.py consumes when run as:
15
+ *
16
+ * python embeddings.py --bundle "<bundleName>=<bundleSchemaId>" --root-type Track --reset
17
+ *
18
+ * The builder walks `performed_by` edges from each Track (root) node and flattens
19
+ * the Artist neighbour's fields in, then embeds "Title: <title>. Tags: <...>" and
20
+ * indexes fields.title / fields.byArtist. We therefore put `title` + `byArtist`
21
+ * directly on the Track and add a couple of categorical fields for the Tags text.
22
+ *
23
+ * Run it (loads .env the same way the e2e suite does):
24
+ *
25
+ * pnpm dotenvx run -f .env -- tsx src/test/setup-embeddings-testdata.ts
26
+ * # or: pnpm setup:embeddings
27
+ *
28
+ * On success it prints the --bundle argument to paste into the builder.
29
+ */
30
+ const LEDGER_FILE = process.env.EMBEDDINGS_TESTDATA_LEDGER ?? "tmp/embeddings-testdata.json";
31
+ function appendLedger(entry) {
32
+ let entries = [];
33
+ if (existsSync(LEDGER_FILE)) try {
34
+ entries = JSON.parse(readFileSync(LEDGER_FILE, "utf8"));
35
+ } catch {
36
+ entries = [];
37
+ }
38
+ entries.push(entry);
39
+ mkdirSync(dirname(LEDGER_FILE), { recursive: true });
40
+ writeFileSync(LEDGER_FILE, JSON.stringify(entries, null, 2));
41
+ }
42
+ const SK = process.env.DELEGATOR_ETH_PRIVATE_KEY;
43
+ const RPC_URL = process.env.RPC_URL ?? process.env.CHAIN_RPC_URL ?? "https://sepolia-rollup.arbitrum.io/rpc";
44
+ const WORKER_URL = process.env.WORKER_URL ?? "http://localhost:8787";
45
+ const SETTLEMENT_REGISTRY_ADDRESS = process.env.SETTLEMENT_REGISTRY_ADDRESS;
46
+ const DATA_SOURCE_REGISTRY_ADDRESS = process.env.DATA_SOURCE_REGISTRY_ADDRESS;
47
+ const SCHEMA_REGISTRY_ADDRESS = process.env.SCHEMA_REGISTRY_ADDRESS;
48
+ const USDC_ADDRESS = process.env.USDC_ADDRESS ?? process.env.USDC_CONTRACT_ADDRESS ?? "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d";
49
+ const USDC_DOMAIN = "USD Coin";
50
+ const CHAIN = arbitrumSepolia;
51
+ const TRACK_SCHEMA = {
52
+ title: { "@type": "string" },
53
+ byArtist: { "@type": "string" },
54
+ genre: { "@type": "string" },
55
+ mood: { "@type": "string" }
56
+ };
57
+ const ARTIST_SCHEMA = {
58
+ name: { "@type": "string" },
59
+ country: { "@type": "string" }
60
+ };
61
+ const NODES = [
62
+ {
63
+ id: "artist-aurora",
64
+ type: "Artist",
65
+ fields: {
66
+ name: "Aurora Skies",
67
+ country: "Norway"
68
+ }
69
+ },
70
+ {
71
+ id: "artist-monsoon",
72
+ type: "Artist",
73
+ fields: {
74
+ name: "Monsoon Collective",
75
+ country: "India"
76
+ }
77
+ },
78
+ {
79
+ id: "track-northern-lights",
80
+ type: "Track",
81
+ fields: {
82
+ title: "Northern Lights",
83
+ byArtist: "Aurora Skies",
84
+ genre: "ambient",
85
+ mood: "calm"
86
+ }
87
+ },
88
+ {
89
+ id: "track-glacier",
90
+ type: "Track",
91
+ fields: {
92
+ title: "Glacier Drift",
93
+ byArtist: "Aurora Skies",
94
+ genre: "ambient",
95
+ mood: "cold"
96
+ }
97
+ },
98
+ {
99
+ id: "track-monsoon-rain",
100
+ type: "Track",
101
+ fields: {
102
+ title: "Monsoon Rain",
103
+ byArtist: "Monsoon Collective",
104
+ genre: "world",
105
+ mood: "warm"
106
+ }
107
+ },
108
+ {
109
+ id: "track-tabla-pulse",
110
+ type: "Track",
111
+ fields: {
112
+ title: "Tabla Pulse",
113
+ byArtist: "Monsoon Collective",
114
+ genre: "world",
115
+ mood: "energetic"
116
+ }
117
+ }
118
+ ];
119
+ const EDGES = [
120
+ {
121
+ rel: "performed_by",
122
+ from: "track-northern-lights",
123
+ to: "artist-aurora"
124
+ },
125
+ {
126
+ rel: "performed_by",
127
+ from: "track-glacier",
128
+ to: "artist-aurora"
129
+ },
130
+ {
131
+ rel: "performed_by",
132
+ from: "track-monsoon-rain",
133
+ to: "artist-monsoon"
134
+ },
135
+ {
136
+ rel: "performed_by",
137
+ from: "track-tabla-pulse",
138
+ to: "artist-monsoon"
139
+ }
140
+ ];
141
+ function makeWallet(key) {
142
+ return createWalletClient({
143
+ account: privateKeyToAccount(key),
144
+ chain: CHAIN,
145
+ transport: http(RPC_URL)
146
+ });
147
+ }
148
+ function requireEnv() {
149
+ const missing = [];
150
+ if (SK === "0x") missing.push("DELEGATOR_ETH_PRIVATE_KEY");
151
+ if (DATA_SOURCE_REGISTRY_ADDRESS === "0x") missing.push("DATA_SOURCE_REGISTRY_ADDRESS");
152
+ if (SCHEMA_REGISTRY_ADDRESS === "0x") missing.push("SCHEMA_REGISTRY_ADDRESS");
153
+ if (!process.env.PINATA_JWT) missing.push("PINATA_JWT");
154
+ if (missing.length) throw new Error(`Missing required env vars: ${missing.join(", ")}.\nRun via: pnpm dotenvx run -f .env -- tsx src/test/setup-embeddings-testdata.ts`);
155
+ }
156
+ async function main() {
157
+ requireEnv();
158
+ const testbed = 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);
159
+ const suffix = `${Date.now().toString()}.${Math.random().toString(36).substring(2, 5)}`;
160
+ const trackSchema = `fangorn.track.${suffix}`;
161
+ const artistSchema = `fangorn.artist.${suffix}`;
162
+ const bundleName = `fangorn.music.bundle.${suffix}`;
163
+ const datasetName = `ds.embeddings.${suffix}`;
164
+ console.log("[setup] registering node schemas ...");
165
+ await testbed.registerSchema(trackSchema, TRACK_SCHEMA);
166
+ await testbed.registerSchema(artistSchema, ARTIST_SCHEMA);
167
+ console.log("[setup] registering bundle shape ...");
168
+ const bundle = {
169
+ nodes: {
170
+ Track: trackSchema,
171
+ Artist: artistSchema
172
+ },
173
+ edges: [{
174
+ rel: "performed_by",
175
+ from: "Track",
176
+ to: "Artist",
177
+ min: 1,
178
+ max: 1
179
+ }]
180
+ };
181
+ const bundleSchemaId = await testbed.registerBundle(bundleName, bundle);
182
+ console.log(`[setup] publishing ${NODES.length.toString()} nodes / ${EDGES.length.toString()} edges as one v3 bundle ...`);
183
+ const manifestUri = await testbed.publishBundle(bundleName, NODES, EDGES, datasetName);
184
+ appendLedger({
185
+ bundleName,
186
+ bundleSchemaId,
187
+ datasetName,
188
+ manifestUri,
189
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
190
+ });
191
+ console.log("\n✅ Test data published.\n");
192
+ console.log(` bundle name : ${bundleName}`);
193
+ console.log(` bundle id : ${bundleSchemaId}`);
194
+ console.log(` dataset : ${datasetName}`);
195
+ console.log(` manifest cid: ${manifestUri}`);
196
+ console.log("\nFeed the embeddings builder with:\n");
197
+ console.log(` python embeddings.py \\`);
198
+ console.log(` --bundle "${bundleName}=${bundleSchemaId}" \\`);
199
+ console.log(` --root-type Track \\`);
200
+ console.log(` --reset\n`);
201
+ console.log(`Recorded in ${LEDGER_FILE} — unpin later with: pnpm cleanup:embeddings\n`);
202
+ }
203
+ main().catch((err) => {
204
+ console.error("\n[setup] failed:", err);
205
+ process.exit(1);
206
+ });
207
+
208
+ //#endregion
209
+ export { LEDGER_FILE };
@@ -1,12 +1,10 @@
1
- import { SchemaDefinition } from "../roles/schema/types.js";
1
+ import { BundleInput, SchemaDefinition, TypeDefinition } from "../roles/schema/types.js";
2
2
  import "../roles/schema/index.js";
3
- import { PublishRecord } from "../roles/publisher/types.js";
4
- import "../roles/publisher/index.js";
3
+ import { FieldInput, PublishRecord } from "../roles/publisher/types.js";
5
4
  import { PrepareSettleResult, TransferWithAuthPayload } from "../registries/settlement-registry/types.js";
6
5
  import { SettlementRegistry } from "../registries/settlement-registry/index.js";
7
6
  import { Fangorn } from "../fangorn.js";
8
7
  import { Address, Hex, WalletClient } from "viem";
9
- import { Identity } from "@semaphore-protocol/identity";
10
8
 
11
9
  //#region src/test/testbed.d.ts
12
10
  declare class TestBed {
@@ -18,18 +16,26 @@ declare class TestBed {
18
16
  private readonly workerUrl;
19
17
  private constructor();
20
18
  static init(delegatorWalletClient: WalletClient, dataSourceRegistryContractAddress: Hex, schemaRegistryContractAddress: Hex, settlementRegistryContractAddress: Hex, usdcContractAddress: Hex, usdcDomainName: string, rpcUrl: string, chain: string, caip2: number, workerUrl: string): TestBed;
21
- registerSchema(name: string, definition: SchemaDefinition, agentId: string): Promise<Hex>;
22
- fileUpload(records: PublishRecord[], schemaName: string, price: bigint): Promise<string>;
19
+ registerSchema(name: string, definition: SchemaDefinition, types?: Record<string, TypeDefinition>): Promise<Hex>;
20
+ publish(records: PublishRecord[], schemaName: string, datasetName: string, chunkSize?: number, concurrency?: number): Promise<string>;
21
+ registerBundle(name: string, bundle: BundleInput): Promise<Hex>;
22
+ publishBundle(bundleName: string, nodes: {
23
+ id: string;
24
+ type: string;
25
+ fields: Record<string, FieldInput>;
26
+ }[], edges: {
27
+ rel: string;
28
+ from: string;
29
+ to: string;
30
+ }[], datasetName?: string): Promise<string>;
23
31
  prepareRegister(burnerPrivateKey: Hex, paymentRecipient: Address, amount: bigint): Promise<TransferWithAuthPayload>;
24
32
  register(owner: Address, schemaId: Hex, name: string, identityCommitment: bigint, relayerPrivateKey: Hex, preparedRegister: TransferWithAuthPayload): Promise<Hex>;
25
- prepareSettle(owner: Address, schemaId: Hex, name: string, identity: Identity, stealthAddress: Address): Promise<PrepareSettleResult>;
26
33
  settle(owner: Address, schemaId: Hex, name: string, relayerPrivateKey: Hex, preparedSettle: PrepareSettleResult): Promise<{
27
34
  txHash: Hex;
28
35
  nullifier: bigint;
29
36
  }>;
30
37
  fetchContent(owner: Address, schemaId: Hex, name: string, field: string, nullifier: string, stealthPrivateKey: Hex): Promise<Uint8Array>;
31
38
  checkManifestExists(who: Address, schemaId: Hex, name: string): Promise<boolean>;
32
- checkEntryExists(who: Address, schemaId: Hex, name: string): Promise<boolean>;
33
39
  getDelegatorAddress(): Address;
34
40
  getDelegatorFangorn(): Fangorn;
35
41
  getDelegateeFangorn(): Fangorn;
@@ -1,4 +1,3 @@
1
- import { DataSourceRegistry } from "../registries/datasource-registry/index.js";
2
1
  import { Fangorn } from "../fangorn.js";
3
2
  import { arbitrumSepolia, baseSepolia } from "viem/chains";
4
3
  import { createWalletClient, http } from "viem";
@@ -25,7 +24,7 @@ var TestBed = class TestBed {
25
24
  chain: chainImpl,
26
25
  rpcUrl,
27
26
  caip2,
28
- ipfsGateway: "https://ipfs.io"
27
+ ipfsGateway: process.env.PINATA_GATEWAY ?? "https://ipfs.io"
29
28
  };
30
29
  const delegatorFangorn = Fangorn.create({
31
30
  privateKey: process.env.DELEGATOR_ETH_PRIVATE_KEY ?? "0x0",
@@ -44,19 +43,39 @@ var TestBed = class TestBed {
44
43
  if (!delegatorWalletClient.account) throw new Error("Delegator account not found");
45
44
  return new TestBed(delegatorWalletClient.account.address, delegatorFangorn, delegateeFangorn, usdcContractAddress, usdcDomainName, workerUrl);
46
45
  }
47
- async registerSchema(name, definition, agentId) {
46
+ async registerSchema(name, definition, types) {
48
47
  const { schemaId } = await this.delegatorFangorn.schema.register({
49
48
  name,
50
49
  definition,
51
- agentId
50
+ types
52
51
  });
53
52
  return schemaId;
54
53
  }
55
- async fileUpload(records, schemaName, price) {
56
- const { manifestUri } = await this.delegatorFangorn.publisher.upload({
54
+ async publish(records, schemaName, datasetName, chunkSize, concurrency) {
55
+ const { manifestUri } = await this.delegatorFangorn.publisher.publishRecords({
57
56
  records,
58
- schemaName
59
- }, price);
57
+ schemaName,
58
+ datasetName,
59
+ chunkSize,
60
+ concurrency
61
+ });
62
+ return manifestUri;
63
+ }
64
+ async registerBundle(name, bundle) {
65
+ const { schemaId } = await this.delegatorFangorn.schema.register({
66
+ kind: "bundle",
67
+ name,
68
+ bundle
69
+ });
70
+ return schemaId;
71
+ }
72
+ async publishBundle(bundleName, nodes, edges, datasetName) {
73
+ const { manifestUri } = await this.getDelegatorFangorn().publisher.publishBundle({
74
+ bundleName,
75
+ nodes,
76
+ edges,
77
+ datasetName
78
+ });
60
79
  return manifestUri;
61
80
  }
62
81
  async prepareRegister(burnerPrivateKey, paymentRecipient, amount) {
@@ -85,13 +104,6 @@ var TestBed = class TestBed {
85
104
  });
86
105
  return txHash;
87
106
  }
88
- async prepareSettle(owner, schemaId, name, identity, stealthAddress) {
89
- return this.delegateeFangorn.consumer.prepareSettle({
90
- resourceId: DataSourceRegistry.resourceIdLocal(owner, schemaId, name),
91
- identity,
92
- stealthAddress
93
- });
94
- }
95
107
  async settle(owner, schemaId, name, relayerPrivateKey, preparedSettle) {
96
108
  const { txHash, nullifier } = await this.delegateeFangorn.consumer.claim({
97
109
  owner,
@@ -115,15 +127,7 @@ var TestBed = class TestBed {
115
127
  return data;
116
128
  }
117
129
  async checkManifestExists(who, schemaId, name) {
118
- return await this.delegatorFangorn.consumer.getManifest(who, schemaId, name) !== void 0;
119
- }
120
- async checkEntryExists(who, schemaId, name) {
121
- try {
122
- await this.delegatorFangorn.consumer.getEntry(who, schemaId, name);
123
- return true;
124
- } catch {
125
- return false;
126
- }
130
+ return await this.delegatorFangorn.consumer.checkManifestExists(who, schemaId, name);
127
131
  }
128
132
  getDelegatorAddress() {
129
133
  return this.delegatorAddress;