@fangorn-network/sdk 2026.4.10 → 2026.4.22

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 (44) hide show
  1. package/README.md +126 -144
  2. package/lib/cli/cli.js +42 -96
  3. package/lib/cli/index.d.ts +170 -170
  4. package/lib/config.d.ts +257 -257
  5. package/lib/config.js +3 -3
  6. package/lib/fangorn.d.ts +3 -17
  7. package/lib/fangorn.js +12 -37
  8. package/lib/index.d.ts +3 -7
  9. package/lib/index.js +3 -5
  10. package/lib/modules/encryption/aes.d.ts +3 -3
  11. package/lib/modules/encryption/index.d.ts +1 -28
  12. package/lib/modules/encryption/index.js +1 -3
  13. package/lib/modules/encryption/types.d.ts +1 -48
  14. package/lib/providers/storage/index.d.ts +4 -21
  15. package/lib/providers/storage/index.js +3 -49
  16. package/lib/providers/storage/pinata.d.ts +8 -5
  17. package/lib/providers/storage/pinata.js +16 -8
  18. package/lib/providers/storage/types.d.ts +37 -0
  19. package/lib/providers/storage/utils.d.ts +12 -0
  20. package/lib/providers/storage/utils.js +50 -0
  21. package/lib/registries/datasource-registry/index.d.ts +2 -2
  22. package/lib/registries/schema-registry/index.d.ts +2 -2
  23. package/lib/registries/settlement-registry/index.d.ts +2 -2
  24. package/lib/roles/consumer/index.d.ts +14 -18
  25. package/lib/roles/consumer/index.js +73 -24
  26. package/lib/roles/consumer/types.d.ts +13 -32
  27. package/lib/roles/publisher/index.d.ts +17 -32
  28. package/lib/roles/publisher/index.js +37 -74
  29. package/lib/roles/publisher/types.d.ts +36 -41
  30. package/lib/roles/schema/index.d.ts +4 -25
  31. package/lib/roles/schema/index.js +5 -30
  32. package/lib/roles/schema/types.d.ts +16 -2
  33. package/lib/test/testbed.d.ts +6 -5
  34. package/lib/test/testbed.js +16 -26
  35. package/lib/types/index.d.ts +12 -45
  36. package/package.json +1 -6
  37. package/lib/modules/encryption/lit.d.ts +0 -20
  38. package/lib/modules/encryption/lit.js +0 -121
  39. package/lib/modules/gadgets/index.d.ts +0 -2
  40. package/lib/modules/gadgets/index.js +0 -1
  41. package/lib/modules/gadgets/settledGadget.d.ts +0 -24
  42. package/lib/modules/gadgets/settledGadget.js +0 -63
  43. package/lib/modules/gadgets/types.d.ts +0 -27
  44. /package/lib/{modules/gadgets → providers/storage}/types.js +0 -0
@@ -1,18 +1,13 @@
1
- import { retrieveByCid } from "../../providers/storage/index.js";
2
1
  import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
2
+ import { PinataBackend } from "../../providers/storage/pinata.js";
3
+ import "../../providers/storage/index.js";
4
+ import { encodePacked, keccak256 } from "viem";
3
5
 
4
6
  //#region src/roles/consumer/index.ts
5
- /**
6
- * The consumer namespace encapsulates all functionality relative to
7
- * accessing and consuming data.
8
- */
9
7
  var ConsumerRole = class {
10
- constructor(dataSourceRegistry, settlementRegistry, encryptionService, domain, ipfsGateway) {
8
+ constructor(dataSourceRegistry, settlementRegistry) {
11
9
  this.dataSourceRegistry = dataSourceRegistry;
12
10
  this.settlementRegistry = settlementRegistry;
13
- this.encryptionService = encryptionService;
14
- this.domain = domain;
15
- this.ipfsGateway = ipfsGateway;
16
11
  }
17
12
  async prepareRegister(params) {
18
13
  return this.settlementRegistry.prepareTransferWithAuth(params);
@@ -45,31 +40,61 @@ var ConsumerRole = class {
45
40
  };
46
41
  }
47
42
  /**
48
- * Decrypt a specific encrypted field within a record.
43
+ * Fetch a handle field's content from the Fangorn access worker.
49
44
  *
50
- * One purchase + claim unlocks ALL encrypted fields in the record —
51
- * the resource is at the record (name) level, not the field level.
52
- * This method can be called once per encrypted field without re-purchasing.
45
+ * The consumer signs { nullifier, resourceId, objectKey, timestamp } with
46
+ * their stealth address private key. The worker recovers the address,
47
+ * verifies is_settled() on-chain, and proxies the R2 bytes.
53
48
  *
54
49
  * Plain fields can be read freely via getEntry() without any of this.
55
50
  */
56
- async decrypt(params) {
57
- const resourceId = this.deriveResourceId(params.owner, params.schemaId, params.name);
58
- if (!params.skipSettlementCheck) {
59
- if (!params.identity) throw new Error("identity is required for settlement verification. Pass skipSettlementCheck: true for owner / out-of-band flows.");
60
- if (!await this.settlementRegistry.isRegistered(resourceId, params.identity.commitment)) throw new Error(`Access denied: identity not registered for resource ${resourceId}. Call register() and wait for confirmation before decrypting.`);
51
+ async fetch(params) {
52
+ const { nullifier, resourceId, objectKey, workerUrl, walletClient } = params;
53
+ const timestamp = Math.floor(Date.now() / 1e3);
54
+ const msgHash = keccak256(encodePacked([
55
+ "uint256",
56
+ "bytes32",
57
+ "string",
58
+ "uint64"
59
+ ], [
60
+ BigInt(nullifier),
61
+ resourceId,
62
+ objectKey,
63
+ BigInt(timestamp)
64
+ ]));
65
+ const account = walletClient.account;
66
+ if (!account) throw new Error("walletClient account must be defined");
67
+ const signature = await walletClient.signMessage({
68
+ message: { raw: msgHash },
69
+ account
70
+ });
71
+ const res = await globalThis.fetch(`${workerUrl}/access`, {
72
+ method: "POST",
73
+ headers: { "Content-Type": "application/json" },
74
+ body: JSON.stringify({
75
+ nullifier,
76
+ resourceId,
77
+ objectKey,
78
+ timestamp,
79
+ signature
80
+ })
81
+ });
82
+ if (!res.ok) {
83
+ const data = await res.json().catch(() => ({}));
84
+ const message = data && typeof data === "object" && "error" in data && typeof data.error === "string" ? data.error : res.statusText;
85
+ throw new Error(`Worker fetch failed: ${message}`);
61
86
  }
62
- const fieldValue = (await this.getEntry(params.owner, params.schemaId, params.name)).fields[params.field];
63
- if (!fieldValue || typeof fieldValue !== "object") throw new Error(`Field "${params.field}" is missing or invalid`);
64
- const encrypted = await retrieveByCid(fieldValue.handle.cid, this.ipfsGateway);
65
- const authContext = params.authContext ?? await this.encryptionService.createAuthContext(params.walletClient, this.domain, params.nullifierHash);
66
- return (await this.encryptionService.decrypt(encrypted, authContext)).data;
87
+ const buffer = await res.arrayBuffer();
88
+ return {
89
+ data: new Uint8Array(buffer),
90
+ contentType: res.headers.get("Content-Type") ?? "application/octet-stream"
91
+ };
67
92
  }
68
93
  async getManifest(owner, schemaId, name) {
69
94
  try {
70
95
  const ds = await this.dataSourceRegistry.get(owner, schemaId, name);
71
96
  if (!ds.manifestCid || ds.manifestCid === "") return void 0;
72
- return await retrieveByCid(ds.manifestCid, this.ipfsGateway);
97
+ return await PinataBackend.getStatic(ds.manifestCid);
73
98
  } catch {
74
99
  return;
75
100
  }
@@ -81,6 +106,25 @@ var ConsumerRole = class {
81
106
  if (!entry) throw new Error(`Entry not found: "${name}"`);
82
107
  return entry;
83
108
  }
109
+ /**
110
+ * Resolves the handle URI for a specific field
111
+ * and fetches it via the worker in one call.
112
+ */
113
+ async fetchField(owner, schemaId, name, field, nullifier, walletClient) {
114
+ const fieldValue = (await this.getEntry(owner, schemaId, name)).fields[field];
115
+ if (!fieldValue || typeof fieldValue !== "object" || !("@type" in fieldValue)) throw new Error(`Field "${field}" is missing or is not a handle field`);
116
+ const handleField = fieldValue;
117
+ if (handleField["@type"] !== "handle") throw new Error(`Field "${field}" is not a handle field. Read it directly from the entry`);
118
+ const objectKey = parseObjectKey(handleField.uri);
119
+ const resourceId = this.deriveResourceId(owner, schemaId, name);
120
+ return this.fetch({
121
+ nullifier,
122
+ resourceId,
123
+ objectKey,
124
+ workerUrl: handleField.workerUrl,
125
+ walletClient
126
+ });
127
+ }
84
128
  async isRegistered(owner, schemaId, name, identity) {
85
129
  const resourceId = this.deriveResourceId(owner, schemaId, name);
86
130
  return this.settlementRegistry.isRegistered(resourceId, identity.commitment);
@@ -89,6 +133,11 @@ var ConsumerRole = class {
89
133
  return DataSourceRegistry.resourceIdLocal(owner, schemaId, name);
90
134
  }
91
135
  };
136
+ function parseObjectKey(uri) {
137
+ if (uri.startsWith("r2://")) return uri.slice(5);
138
+ if (uri.startsWith("ipfs://")) return uri.slice(7);
139
+ return uri;
140
+ }
92
141
 
93
142
  //#endregion
94
143
  export { ConsumerRole };
@@ -1,8 +1,6 @@
1
- import { PrepareSettleResult, RegisterParams, SettleParams, TransferWithAuthPayload } from "../../registries/settlement-registry/types.js";
2
- import { AuthContext } from "../../modules/encryption/index.js";
3
1
  import { ManifestEntry } from "../publisher/types.js";
2
+ import { PrepareSettleResult, TransferWithAuthPayload } from "../../registries/settlement-registry/types.js";
4
3
  import { Address, Hex, WalletClient } from "viem";
5
- import { Identity } from "@semaphore-protocol/identity";
6
4
 
7
5
  //#region src/roles/consumer/types.d.ts
8
6
  interface PurchaseParams {
@@ -20,34 +18,6 @@ interface ClaimParams {
20
18
  relayerPrivateKey: Hex;
21
19
  preparedSettle: PrepareSettleResult;
22
20
  }
23
- interface DecryptParams {
24
- owner: Address;
25
- walletClient: WalletClient;
26
- schemaId: Hex;
27
- nullifierHash: bigint;
28
- /** The record tag — maps to the resourceId */
29
- name: string;
30
- /** The specific encrypted field within the record to decrypt */
31
- field: string;
32
- identity?: Identity;
33
- /**
34
- * When true, skips settlement verification.
35
- * Use for owner self-access or out-of-band flows only.
36
- */
37
- skipSettlementCheck?: boolean;
38
- authContext?: AuthContext;
39
- }
40
- interface AccessParams {
41
- owner: Address;
42
- schemaId: Hex;
43
- name: string;
44
- /** The encrypted field to decrypt after settling */
45
- field: string;
46
- identity: Identity;
47
- payment: Omit<RegisterParams, "resourceId">;
48
- proof: Omit<SettleParams, "resourceId">;
49
- authContext?: AuthContext;
50
- }
51
21
  interface PurchaseResult {
52
22
  txHash: Hex;
53
23
  resourceId: Hex;
@@ -62,5 +32,16 @@ interface AccessResult {
62
32
  resourceId: Hex;
63
33
  entry: ManifestEntry;
64
34
  }
35
+ interface FetchParams {
36
+ nullifier: string;
37
+ resourceId: Hex;
38
+ objectKey: string;
39
+ workerUrl: string;
40
+ walletClient: WalletClient;
41
+ }
42
+ interface FetchResult {
43
+ data: Uint8Array;
44
+ contentType: string;
45
+ }
65
46
  //#endregion
66
- export { AccessParams, AccessResult, ClaimParams, ClaimResult, DecryptParams, PurchaseParams, PurchaseResult };
47
+ export { AccessResult, ClaimParams, ClaimResult, FetchParams, FetchResult, PurchaseParams, PurchaseResult };
@@ -1,9 +1,8 @@
1
1
  import { AppConfig } from "../../config.js";
2
2
  import { SchemaRegistry } from "../../registries/schema-registry/index.js";
3
- import { PinningService } from "../../providers/storage/index.js";
3
+ import { MetadataStorage } from "../../providers/storage/types.js";
4
4
  import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
5
- import { EncryptionService } from "../../modules/encryption/index.js";
6
- import { CommitResult, EncryptedFieldInput, FieldInput, Manifest, ManifestEntry, PublishRecord, ResolvedEncryptedField, ResolvedField, ResolvedPlainField, UploadParams } from "./types.js";
5
+ import { CommitResult, FieldInput, HandleFieldInput, Manifest, ManifestEntry, PublishRecord, ResolvedField, ResolvedHandleField, ResolvedPlainField, UploadParams } from "./types.js";
7
6
  import { Hex, WalletClient } from "viem";
8
7
 
9
8
  //#region src/roles/publisher/index.d.ts
@@ -11,22 +10,19 @@ declare class PublisherRole {
11
10
  private readonly dataSourceRegistry;
12
11
  private readonly schemaRegistry;
13
12
  private readonly storage;
14
- private readonly encryptionService;
15
13
  private readonly walletClient;
16
14
  private readonly config;
17
15
  private pendingEntries;
18
16
  private readonly schemaCache;
19
- constructor(dataSourceRegistry: DataSourceRegistry, schemaRegistry: SchemaRegistry, storage: PinningService, encryptionService: EncryptionService, walletClient: WalletClient, config: AppConfig);
17
+ constructor(dataSourceRegistry: DataSourceRegistry, schemaRegistry: SchemaRegistry, storage: MetadataStorage, walletClient: WalletClient, config: AppConfig);
20
18
  /**
21
- * Encrypt and upload schema-conformant data.
19
+ * Validate and stage schema-conformant records, then commit to storage
20
+ * and publish on-chain.
22
21
  *
23
- * Validates records against the schema, encrypts fields as required,
24
- * stages all resolved entries, then commits to IPFS and publishes on-chain.
22
+ * Fields with a HandleFieldInput are written to the manifest as-is.
23
+ * The content is assumed to already exist at the supplied URI (e.g. pre-uploaded to R2).
25
24
  *
26
- * Each encrypted field within a record is stored as a separate IPFS object.
27
- * The manifest entry stores the handle (CID + gateway) alongside plain fields.
28
- * Consumers can read plain fields freely and only need to purchase and decrypt
29
- * for encrypted fields.
25
+ * Plain fields are stored inline in the manifest.
30
26
  */
31
27
  upload(params: UploadParams, price: bigint): Promise<CommitResult>;
32
28
  stage(entry: ManifestEntry): void;
@@ -35,39 +31,28 @@ declare class PublisherRole {
35
31
  clearPending(): void;
36
32
  /**
37
33
  * Serialize all staged entries into a manifest, publish each entry
38
- * on-chain via the DataSourceRegistry (which calls into the
39
- * SettlementRegistry to create/update the Semaphore group), pin the
40
- * manifest to IPFS, and record the manifest CID on-chain.
34
+ * on-chain via the DataSourceRegistry, and record the manifest URI on-chain.
41
35
  */
42
36
  commit(schemaId: Hex, price: bigint, overwrite: boolean): Promise<CommitResult>;
43
37
  getManifest(schemaId: Hex, name: string): Promise<Manifest | undefined>;
44
38
  getEntry(schemaId: Hex, name: string): Promise<ManifestEntry>;
45
39
  private requireAccount;
46
40
  /**
47
- * Resolve the schema definition and id by name, with in-memory caching.
48
- * Concurrent calls for the same name share a single in-flight promise.
41
+ * Fetch the schema by name from the schema registry/cache
42
+ * @param name The name of the schema
43
+ * @returns The schema and schema id, if they exist
49
44
  */
50
45
  private resolveSchema;
51
46
  /**
52
- * Resolve a PublishRecord into a ManifestEntry by processing each field
53
- * according to the schema definition:
54
- * - plain fields are stored as-is
55
- * - encrypted fields are encrypted, pinned to IPFS, and replaced
56
- * with a handle + gadgetDescriptor
47
+ * Resolve a PublishRecord into a ManifestEntry.
48
+ *
49
+ * Handle fields are passed through directly
50
+ * Plain fields are stored inline.
57
51
  */
58
52
  private resolveRecord;
59
- /**
60
- * Validate that a record's fields match the schema before touching IPFS.
61
- */
62
53
  private validateRecord;
63
54
  private validateField;
64
- /**
65
- * Load existing entries for merge behaviour, keyed by name.
66
- * Unpins the old manifest CID after loading.
67
- * Pending entries take precedence — existing entries with the same name
68
- * are overwritten.
69
- */
70
55
  private loadExistingEntries;
71
56
  }
72
57
  //#endregion
73
- export { CommitResult, EncryptedFieldInput, FieldInput, Manifest, ManifestEntry, PublishRecord, PublisherRole, ResolvedEncryptedField, ResolvedField, ResolvedPlainField, UploadParams };
58
+ export { CommitResult, FieldInput, HandleFieldInput, Manifest, ManifestEntry, PublishRecord, PublisherRole, ResolvedField, ResolvedHandleField, ResolvedPlainField, UploadParams };
@@ -1,45 +1,29 @@
1
- import { retrieveByCid } from "../../providers/storage/index.js";
2
- import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
3
- import { SettledGadget } from "../../modules/gadgets/settledGadget.js";
4
-
5
1
  //#region src/roles/publisher/index.ts
6
2
  var PublisherRole = class {
7
3
  pendingEntries = /* @__PURE__ */ new Map();
8
4
  schemaCache = /* @__PURE__ */ new Map();
9
- constructor(dataSourceRegistry, schemaRegistry, storage, encryptionService, walletClient, config) {
5
+ constructor(dataSourceRegistry, schemaRegistry, storage, walletClient, config) {
10
6
  this.dataSourceRegistry = dataSourceRegistry;
11
7
  this.schemaRegistry = schemaRegistry;
12
8
  this.storage = storage;
13
- this.encryptionService = encryptionService;
14
9
  this.walletClient = walletClient;
15
10
  this.config = config;
16
11
  }
17
12
  /**
18
- * Encrypt and upload schema-conformant data.
13
+ * Validate and stage schema-conformant records, then commit to storage
14
+ * and publish on-chain.
19
15
  *
20
- * Validates records against the schema, encrypts fields as required,
21
- * stages all resolved entries, then commits to IPFS and publishes on-chain.
16
+ * Fields with a HandleFieldInput are written to the manifest as-is.
17
+ * The content is assumed to already exist at the supplied URI (e.g. pre-uploaded to R2).
22
18
  *
23
- * Each encrypted field within a record is stored as a separate IPFS object.
24
- * The manifest entry stores the handle (CID + gateway) alongside plain fields.
25
- * Consumers can read plain fields freely and only need to purchase and decrypt
26
- * for encrypted fields.
19
+ * Plain fields are stored inline in the manifest.
27
20
  */
28
21
  async upload(params, price) {
29
- const { records, schemaName, gateway, options } = params;
30
- const address = this.requireAccount();
22
+ const { records, schemaName, options } = params;
31
23
  const { schema, schemaId } = await this.resolveSchema(schemaName);
32
- const gadgetFactory = (name) => {
33
- return new SettledGadget({
34
- resourceId: DataSourceRegistry.resourceIdLocal(address, schemaId, name),
35
- settlementRegistryAddress: this.config.settlementRegistryContractAddress,
36
- chainName: this.config.chainName
37
- });
38
- };
39
24
  for (const record of records) {
40
25
  this.validateRecord(record, schema);
41
- const gadget = gadgetFactory(record.name);
42
- const entry = await this.resolveRecord(record, schema, gadget, gateway);
26
+ const entry = this.resolveRecord(record, schema, price);
43
27
  this.pendingEntries.set(record.name, entry);
44
28
  }
45
29
  return this.commit(schemaId, price, options?.overwrite ?? false);
@@ -58,9 +42,7 @@ var PublisherRole = class {
58
42
  }
59
43
  /**
60
44
  * Serialize all staged entries into a manifest, publish each entry
61
- * on-chain via the DataSourceRegistry (which calls into the
62
- * SettlementRegistry to create/update the Semaphore group), pin the
63
- * manifest to IPFS, and record the manifest CID on-chain.
45
+ * on-chain via the DataSourceRegistry, and record the manifest URI on-chain.
64
46
  */
65
47
  async commit(schemaId, price, overwrite) {
66
48
  const owner = this.requireAccount();
@@ -71,15 +53,15 @@ var PublisherRole = class {
71
53
  entries = [...Array.from(existingEntriesMap.values()), ...entries];
72
54
  }
73
55
  const manifest = {
74
- version: 1,
56
+ version: 2,
75
57
  schemaId,
76
58
  entries
77
59
  };
78
- const manifestCid = await this.storage.store(manifest, { metadata: { name: `manifest:${schemaId}` } });
79
- for (const entry of entries) await this.dataSourceRegistry.publish(manifestCid, schemaId, entry.name, price);
60
+ const manifestUri = await this.storage.put(manifest, { name: `manifest:${schemaId}` });
61
+ for (const entry of entries) await this.dataSourceRegistry.publish(manifestUri, schemaId, entry.name, price);
80
62
  this.pendingEntries.clear();
81
63
  return {
82
- manifestCid,
64
+ manifestUri,
83
65
  schemaId,
84
66
  owner,
85
67
  entryCount: entries.length
@@ -90,7 +72,7 @@ var PublisherRole = class {
90
72
  try {
91
73
  const ds = await this.dataSourceRegistry.get(owner, schemaId, name);
92
74
  if (!ds.manifestCid || ds.manifestCid === "") return void 0;
93
- return await retrieveByCid(ds.manifestCid, this.config.ipfsGateway);
75
+ return await this.storage.get(ds.manifestCid);
94
76
  } catch {
95
77
  return;
96
78
  }
@@ -108,14 +90,15 @@ var PublisherRole = class {
108
90
  return address;
109
91
  }
110
92
  /**
111
- * Resolve the schema definition and id by name, with in-memory caching.
112
- * Concurrent calls for the same name share a single in-flight promise.
93
+ * Fetch the schema by name from the schema registry/cache
94
+ * @param name The name of the schema
95
+ * @returns The schema and schema id, if they exist
113
96
  */
114
97
  resolveSchema(name) {
115
98
  if (!this.schemaCache.has(name)) {
116
99
  const p = Promise.all([this.schemaRegistry.getSchema(name), this.schemaRegistry.schemaId(name)]).then(async ([{ specCid }, schemaId]) => {
117
100
  return {
118
- schema: (await retrieveByCid(specCid, this.config.ipfsGateway)).definition,
101
+ schema: (await this.storage.get(specCid)).definition,
119
102
  schemaId
120
103
  };
121
104
  }).catch((err) => {
@@ -129,43 +112,28 @@ var PublisherRole = class {
129
112
  return cached;
130
113
  }
131
114
  /**
132
- * Resolve a PublishRecord into a ManifestEntry by processing each field
133
- * according to the schema definition:
134
- * - plain fields are stored as-is
135
- * - encrypted fields are encrypted, pinned to IPFS, and replaced
136
- * with a handle + gadgetDescriptor
115
+ * Resolve a PublishRecord into a ManifestEntry.
116
+ *
117
+ * Handle fields are passed through directly
118
+ * Plain fields are stored inline.
137
119
  */
138
- async resolveRecord(record, schema, gadget, gateway) {
120
+ resolveRecord(record, schema, price) {
139
121
  const resolvedFields = {};
140
- for (const [fieldName, fieldDef] of Object.entries(schema)) {
122
+ for (const [fieldName] of Object.entries(schema)) {
141
123
  const value = record.fields[fieldName];
142
- if (fieldDef["@type"] === "encrypted") {
143
- const input = value;
144
- const encrypted = await this.encryptionService.encrypt({
145
- tag: `${record.name}:${fieldName}`,
146
- data: input.data,
147
- extension: input.extension ?? "",
148
- fileType: input.fileType ?? "application/octet-stream"
149
- }, gadget);
150
- const cid = await this.storage.store(encrypted, { metadata: { name: `${record.name}:${fieldName}` } });
151
- resolvedFields[fieldName] = {
152
- "@type": "encrypted",
153
- handle: {
154
- cid,
155
- gateway
156
- },
157
- gadgetDescriptor: gadget.toDescriptor()
158
- };
159
- } else resolvedFields[fieldName] = value;
124
+ if (isHandleFieldInput(value)) resolvedFields[fieldName] = {
125
+ "@type": "handle",
126
+ uri: value.uri,
127
+ workerUrl: value.workerUrl,
128
+ price: price.toString()
129
+ };
130
+ else resolvedFields[fieldName] = value;
160
131
  }
161
132
  return {
162
133
  name: record.name,
163
134
  fields: resolvedFields
164
135
  };
165
136
  }
166
- /**
167
- * Validate that a record's fields match the schema before touching IPFS.
168
- */
169
137
  validateRecord(record, schema) {
170
138
  const errors = [];
171
139
  for (const [fieldName, fieldDef] of Object.entries(schema)) this.validateField(record.name, fieldName, fieldDef, record.fields[fieldName], errors);
@@ -173,6 +141,7 @@ var PublisherRole = class {
173
141
  if (errors.length > 0) throw new Error(`Validation failed for record "${record.name}":\n` + errors.map((e) => ` • ${e}`).join("\n"));
174
142
  }
175
143
  validateField(name, fieldName, fieldDef, value, errors) {
144
+ if (isHandleFieldInput(value)) return;
176
145
  switch (fieldDef["@type"]) {
177
146
  case "string":
178
147
  if (typeof value !== "string") errors.push(`"${fieldName}" must be a string, got ${typeof value}`);
@@ -186,17 +155,8 @@ var PublisherRole = class {
186
155
  case "bytes":
187
156
  if (!(value instanceof Uint8Array)) errors.push(`"${fieldName}" must be Uint8Array`);
188
157
  break;
189
- case "encrypted":
190
- if (typeof value !== "object" || !("data" in value) || !(value.data instanceof Uint8Array)) errors.push(`"${fieldName}" is encrypted — expected EncryptedFieldInput { data: Uint8Array }`);
191
- break;
192
158
  }
193
159
  }
194
- /**
195
- * Load existing entries for merge behaviour, keyed by name.
196
- * Unpins the old manifest CID after loading.
197
- * Pending entries take precedence — existing entries with the same name
198
- * are overwritten.
199
- */
200
160
  async loadExistingEntries(owner, schemaId, pendingEntries) {
201
161
  const existingMap = /* @__PURE__ */ new Map();
202
162
  const pendingNames = new Set(pendingEntries.map((e) => e.name));
@@ -205,17 +165,20 @@ var PublisherRole = class {
205
165
  try {
206
166
  const ds = await this.dataSourceRegistry.get(owner, schemaId, firstName);
207
167
  if (!ds.manifestCid) return existingMap;
208
- const manifest = await retrieveByCid(ds.manifestCid, this.config.ipfsGateway);
168
+ const manifest = await this.storage.get(ds.manifestCid);
209
169
  for (const entry of manifest.entries) if (!pendingNames.has(entry.name)) existingMap.set(entry.name, entry);
210
170
  try {
211
171
  await this.storage.delete(ds.manifestCid);
212
172
  } catch (e) {
213
- console.warn(`Failed to unpin old manifest ${ds.manifestCid}:`, e);
173
+ console.warn(`Failed to delete old manifest ${ds.manifestCid}:`, e);
214
174
  }
215
175
  } catch {}
216
176
  return existingMap;
217
177
  }
218
178
  };
179
+ function isHandleFieldInput(value) {
180
+ return typeof value === "object" && "@type" in value && value["@type"] === "handle";
181
+ }
219
182
 
220
183
  //#endregion
221
184
  export { PublisherRole };
@@ -1,23 +1,24 @@
1
- import { Gadget, GadgetDescriptor } from "../../modules/gadgets/types.js";
2
- import "../../modules/gadgets/index.js";
3
1
  import { Address, Hex } from "viem";
4
2
 
5
3
  //#region src/roles/publisher/types.d.ts
6
4
 
7
5
  /**
8
- * A field value the publisher wants to store encrypted.
9
- * The `data` bytes are what get AES-encrypted and threshold-keyed via Lit.
6
+ * A single field value supplied by the publisher.
7
+ * If the value is already stored externally, use a HandleFieldInput instead.
10
8
  */
11
- interface EncryptedFieldInput {
12
- data: Uint8Array;
13
- fileType?: string;
14
- extension?: string;
15
- }
9
+ type FieldInput = string | number | boolean | Uint8Array | HandleFieldInput;
16
10
  /**
17
- * A single field value supplied by the publisher.
18
- * Plain types are stored as-is; EncryptedFieldInput goes through encryption.
11
+ * A field whose content already lives in a storage backend.
12
+ * The publisher supplies the URI directly — no encrypt/store step occurs.
13
+ * Examples:
14
+ * "r2://tracks/song.mp3"
15
+ * "ipfs://QmXyz..." [future]
19
16
  */
20
- type FieldInput = string | number | boolean | Uint8Array | EncryptedFieldInput;
17
+ interface HandleFieldInput {
18
+ "@type": "handle";
19
+ uri: string;
20
+ workerUrl: string;
21
+ }
21
22
  /**
22
23
  * One schema-conformant record to publish.
23
24
  * `name` uniquely identifies this record within (owner, schemaId) —
@@ -27,65 +28,59 @@ interface PublishRecord {
27
28
  name: string;
28
29
  fields: Record<string, FieldInput>;
29
30
  }
30
- /** A resolved encrypted field — what actually gets stored in the manifest entry */
31
- interface ResolvedEncryptedField {
32
- "@type": "encrypted";
33
- handle: {
34
- cid: string;
35
- gateway: string;
36
- };
37
- gadgetDescriptor: GadgetDescriptor;
31
+ /**
32
+ * A resolved handle field — points to content in a storage backend.
33
+ * The URI scheme identifies the backend:
34
+ * r2:// → Fangorn access worker (requires settlement proof)
35
+ * ipfs:// → public IPFS gateway [future]
36
+ */
37
+ interface ResolvedHandleField {
38
+ "@type": "handle";
39
+ uri: string;
40
+ workerUrl: string;
41
+ price: string;
38
42
  }
39
- /** A resolved plain field value — stored as-is */
43
+ /** A resolved plain field, stored inline in the manifest */
40
44
  type ResolvedPlainField = string | number | boolean | Uint8Array;
41
- type ResolvedField = ResolvedPlainField | ResolvedEncryptedField;
45
+ type ResolvedField = ResolvedPlainField | ResolvedHandleField;
42
46
  /**
43
- * A manifest entry — one schema-conformant record with all fields resolved.
44
- * Plain fields are readable by anyone. Encrypted fields carry a handle
45
- * pointing to the ciphertext in IPFS and the gadget descriptor describing
46
- * the access condition.
47
+ * A manifest entry; one schema-conformant record with all fields resolved.
48
+ * Plain fields are readable by anyone directly from the manifest.
49
+ * Handle fields require the consumer to fetch via the appropriate backend.
47
50
  */
48
51
  interface ManifestEntry {
49
52
  name: string;
50
53
  fields: Record<string, ResolvedField>;
51
54
  }
52
55
  interface Manifest {
53
- version: 1;
56
+ version: 2;
54
57
  schemaId: Hex;
55
58
  entries: ManifestEntry[];
56
59
  }
57
60
  interface UploadParams {
58
61
  records: PublishRecord[];
59
- schemaName: string;
60
62
  /**
61
- * Called once per record to produce the gadget for that record's encrypted
62
- * fields. All encrypted fields within a record share the same gadget —
63
- * and therefore the same resourceId and access condition.
63
+ * The unique name of the schema the records must conform to.
64
64
  */
65
- gadgetFactory?: (tag: string) => Gadget | Promise<Gadget>;
65
+ schemaName: string;
66
66
  /**
67
- * Configurable gas for sending the call
67
+ * Configurable gas for the on-chain publish call.
68
68
  */
69
69
  gas?: bigint;
70
- /**
71
- * IPFS gateway URL written into each encrypted field handle so consumers
72
- * can retrieve ciphertexts without knowing the storage provider.
73
- */
74
- gateway: string;
75
70
  options?: {
76
71
  /**
77
72
  * When false (default) the existing manifest for this (owner, schemaId)
78
- * is loaded and merged — existing records not in this upload are kept.
73
+ * is loaded and merged. Existing records not in this upload are kept.
79
74
  * When true the manifest is fully replaced.
80
75
  */
81
76
  overwrite?: boolean;
82
77
  };
83
78
  }
84
79
  interface CommitResult {
85
- manifestCid: string;
80
+ manifestUri: string;
86
81
  schemaId: Hex;
87
82
  owner: Address;
88
83
  entryCount: number;
89
84
  }
90
85
  //#endregion
91
- export { CommitResult, EncryptedFieldInput, FieldInput, Manifest, ManifestEntry, PublishRecord, ResolvedEncryptedField, ResolvedField, ResolvedPlainField, UploadParams };
86
+ export { CommitResult, FieldInput, HandleFieldInput, Manifest, ManifestEntry, PublishRecord, ResolvedField, ResolvedHandleField, ResolvedPlainField, UploadParams };