@fangorn-network/sdk 2026.3.11 → 2026.3.27

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 (87) hide show
  1. package/README.md +311 -198
  2. package/lib/builders/a2aCardBuilder.js +1 -0
  3. package/lib/cli/cli.js +406 -379
  4. package/lib/cli/index.d.ts +170 -170
  5. package/lib/cli/index.js +1 -4
  6. package/lib/config.d.ts +543 -163
  7. package/lib/config.js +11 -8
  8. package/lib/fangorn.d.ts +28 -45
  9. package/lib/fangorn.js +98 -119
  10. package/lib/index.d.ts +8 -5
  11. package/lib/index.js +8 -7
  12. package/lib/modules/encryption/index.d.ts +4 -3
  13. package/lib/modules/encryption/lit.d.ts +3 -18
  14. package/lib/modules/encryption/lit.js +20 -49
  15. package/lib/modules/encryption/rand.js +2 -2
  16. package/lib/modules/encryption/types.d.ts +23 -8
  17. package/lib/modules/gadgets/settledGadget.d.ts +26 -0
  18. package/lib/modules/gadgets/settledGadget.js +63 -0
  19. package/lib/modules/gadgets/types.d.ts +16 -4
  20. package/lib/providers/storage/index.d.ts +15 -4
  21. package/lib/providers/storage/pinata/index.d.ts +5 -4
  22. package/lib/providers/storage/pinata/index.js +17 -2
  23. package/lib/providers/storage/storacha/index.d.ts +13 -0
  24. package/lib/providers/storage/storacha/index.js +49 -0
  25. package/lib/providers/storage/storacha/readOnly.d.ts +8 -0
  26. package/lib/providers/storage/storacha/readOnly.js +16 -0
  27. package/lib/{interface → registries}/datasource-registry/abi.d.ts +29 -43
  28. package/lib/registries/datasource-registry/abi.js +16 -0
  29. package/lib/{interface/datasource-registry/dataSourceRegistry.d.ts → registries/datasource-registry/index.d.ts} +9 -9
  30. package/lib/{interface/datasource-registry/dataSourceRegistry.js → registries/datasource-registry/index.js} +35 -34
  31. package/lib/registries/index.d.ts +3 -0
  32. package/lib/registries/index.js +4 -0
  33. package/lib/registries/schema-registry/abi.d.ts +127 -0
  34. package/lib/registries/schema-registry/abi.js +19 -0
  35. package/lib/registries/schema-registry/index.d.ts +29 -0
  36. package/lib/registries/schema-registry/index.js +114 -0
  37. package/lib/registries/settlement-registry/abi.d.ts +228 -0
  38. package/lib/registries/settlement-registry/abi.js +29 -0
  39. package/lib/registries/settlement-registry/index.d.ts +72 -0
  40. package/lib/registries/settlement-registry/index.js +316 -0
  41. package/lib/registries/settlement-registry/types.d.ts +51 -0
  42. package/lib/roles/consumer/index.d.ts +64 -0
  43. package/lib/roles/consumer/index.js +114 -0
  44. package/lib/roles/consumer/types.d.ts +66 -0
  45. package/lib/roles/index.js +1 -0
  46. package/lib/roles/publisher/index.d.ts +70 -0
  47. package/lib/roles/publisher/index.js +203 -0
  48. package/lib/roles/publisher/types.d.ts +93 -0
  49. package/lib/roles/publisher/types.js +1 -0
  50. package/lib/roles/schema/index.d.ts +44 -0
  51. package/lib/roles/schema/index.js +137 -0
  52. package/lib/roles/schema/types.d.ts +67 -0
  53. package/lib/roles/schema/types.js +1 -0
  54. package/lib/test/index.d.ts +5 -2
  55. package/lib/test/index.js +5 -3
  56. package/lib/test/testbed.d.ts +54 -32
  57. package/lib/test/testbed.js +149 -135
  58. package/lib/types/index.d.ts +65 -21
  59. package/lib/types/index.js +1 -12
  60. package/lib/utils/index.d.ts +2 -3
  61. package/lib/utils/index.js +4 -18
  62. package/package.json +9 -18
  63. package/lib/cli/registry.d.ts +0 -29
  64. package/lib/cli/registry.js +0 -53
  65. package/lib/deployContract.d.ts +0 -23
  66. package/lib/deployContract.js +0 -78
  67. package/lib/interface/datasource-registry/abi.js +0 -110
  68. package/lib/interface/index.d.ts +0 -3
  69. package/lib/interface/index.js +0 -4
  70. package/lib/interface/manifest.d.ts +0 -7
  71. package/lib/interface/manifest.js +0 -10
  72. package/lib/interface/settlement-tracker/abi.d.ts +0 -26
  73. package/lib/interface/settlement-tracker/abi.js +0 -88
  74. package/lib/interface/settlement-tracker/settlementTracker.d.ts +0 -32
  75. package/lib/interface/settlement-tracker/settlementTracker.js +0 -64
  76. package/lib/modules/gadgets/acc/gadgets.d.ts +0 -7
  77. package/lib/modules/gadgets/acc/gadgets.js +0 -10
  78. package/lib/modules/gadgets/acc.d.ts +0 -15
  79. package/lib/modules/gadgets/acc.js +0 -24
  80. package/lib/modules/gadgets/builder.d.ts +0 -1
  81. package/lib/modules/gadgets/payment.d.ts +0 -23
  82. package/lib/modules/gadgets/payment.js +0 -88
  83. package/lib/test/test-gadget.d.ts +0 -7
  84. package/lib/test/test-gadget.js +0 -10
  85. /package/lib/{modules/gadgets/builder.js → registries/settlement-registry/types.js} +0 -0
  86. /package/lib/{providers/storage/s3/index.js → roles/consumer/types.js} +0 -0
  87. /package/lib/{providers/storage/s3 → roles}/index.d.ts +0 -0
@@ -0,0 +1,316 @@
1
+ import { SETTLEMENT_REGISTRY_ABI } from "./abi.js";
2
+ import { arbitrumSepolia } from "viem/chains";
3
+ import { createWalletClient, encodePacked, http, keccak256, parseSignature } from "viem";
4
+ import { privateKeyToAccount } from "viem/accounts";
5
+ import { Group } from "@semaphore-protocol/group";
6
+ import { generateProof } from "@semaphore-protocol/proof";
7
+
8
+ //#region src/registries/settlement-registry/index.ts
9
+ /**
10
+ *
11
+ * SDK wrapper for the on-chain SettlementRegistry Stylus contract.
12
+ *
13
+ * Responsible for:
14
+ * - createResource(): owner calls once per (schemaId, tag) asset
15
+ * - register(): buyer pays + joins Semaphore group
16
+ * - settle(): buyer proves membership + fires hook (NFT/timelock)
17
+ * - isSettled(): access check — used to gate decryptFile()
18
+ * - deriveResourceId(): deterministic (owner, schemaId, tag) → bytes32
19
+ */
20
+ var SettlementRegistry = class {
21
+ constructor(contractAddress, publicClient, walletClient) {
22
+ this.contractAddress = contractAddress;
23
+ this.publicClient = publicClient;
24
+ this.walletClient = walletClient;
25
+ }
26
+ /**
27
+ * Create a Semaphore group for a resource. Called by the schema owner once per (schemaId, tag) asset.
28
+ *
29
+ * @param resourceId: The hex encoded resource id
30
+ * @param price : The USDC price for the resource
31
+ * @returns The finalized transaction hash.
32
+ */
33
+ async createResource(resourceId, price) {
34
+ const account = this.walletClient.account;
35
+ if (!account) throw new Error("The wallet client must have an account configured");
36
+ const hash = await this.walletClient.writeContract({
37
+ address: this.contractAddress,
38
+ abi: SETTLEMENT_REGISTRY_ABI,
39
+ functionName: "createResource",
40
+ args: [resourceId, price],
41
+ chain: arbitrumSepolia,
42
+ account
43
+ });
44
+ await this.publicClient.waitForTransactionReceipt({ hash });
45
+ return hash;
46
+ }
47
+ /**
48
+ * Prepares the EIP-3009 transferWithAuthorization call and signs it w/ an EIP-712 sig
49
+ * @param params The transferWithAuth params
50
+ * @returns The payload containing the signed call data
51
+ */
52
+ async prepareTransferWithAuth(params) {
53
+ const { burnerPrivateKey, paymentRecipient, amount, usdcAddress, usdcDomainName, usdcDomainVersion } = params;
54
+ const chain = this.walletClient.chain;
55
+ if (!chain) throw new Error("Wallet client must have a chain configured.");
56
+ const burner = privateKeyToAccount(burnerPrivateKey);
57
+ const burnerWallet = createWalletClient({
58
+ account: burner,
59
+ chain,
60
+ transport: http(chain.rpcUrls.default.http[0])
61
+ });
62
+ const validAfter = 0n;
63
+ const validBefore = BigInt(Math.floor(Date.now() / 1e3) + 3600);
64
+ const nonceBytes = crypto.getRandomValues(new Uint8Array(32));
65
+ const nonce = `0x${Array.from(nonceBytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
66
+ const { v, r, s } = parseSignature(await burnerWallet.signTypedData({
67
+ domain: {
68
+ name: usdcDomainName,
69
+ version: usdcDomainVersion,
70
+ chainId: chain.id,
71
+ verifyingContract: usdcAddress
72
+ },
73
+ types: { TransferWithAuthorization: [
74
+ {
75
+ name: "from",
76
+ type: "address"
77
+ },
78
+ {
79
+ name: "to",
80
+ type: "address"
81
+ },
82
+ {
83
+ name: "value",
84
+ type: "uint256"
85
+ },
86
+ {
87
+ name: "validAfter",
88
+ type: "uint256"
89
+ },
90
+ {
91
+ name: "validBefore",
92
+ type: "uint256"
93
+ },
94
+ {
95
+ name: "nonce",
96
+ type: "bytes32"
97
+ }
98
+ ] },
99
+ primaryType: "TransferWithAuthorization",
100
+ message: {
101
+ from: burner.address,
102
+ to: paymentRecipient,
103
+ value: amount,
104
+ validAfter,
105
+ validBefore,
106
+ nonce
107
+ }
108
+ }));
109
+ return {
110
+ burnerAddress: burner.address,
111
+ paymentRecipient,
112
+ amount,
113
+ validAfter,
114
+ validBefore,
115
+ nonce,
116
+ v: Number(v),
117
+ r,
118
+ s
119
+ };
120
+ }
121
+ /**
122
+ * Submit a payment and register with the specified semaphore group
123
+ * @param params
124
+ * @returns
125
+ */
126
+ async register(params) {
127
+ const { resourceId, identityCommitment, relayerPrivateKey, preparedRegister } = params;
128
+ const { burnerAddress, paymentRecipient, amount, validAfter, validBefore, nonce, v, r, s } = preparedRegister;
129
+ const chain = this.walletClient.chain;
130
+ if (!chain) throw new Error("Wallet client must have a chain configured.");
131
+ const hash = await createWalletClient({
132
+ account: privateKeyToAccount(relayerPrivateKey),
133
+ chain,
134
+ transport: http(chain.rpcUrls.default.http[0])
135
+ }).writeContract({
136
+ address: this.contractAddress,
137
+ abi: SETTLEMENT_REGISTRY_ABI,
138
+ functionName: "register",
139
+ args: [
140
+ resourceId,
141
+ identityCommitment,
142
+ burnerAddress,
143
+ paymentRecipient,
144
+ amount,
145
+ validAfter,
146
+ validBefore,
147
+ nonce,
148
+ v,
149
+ r,
150
+ s
151
+ ]
152
+ });
153
+ await this.publicClient.waitForTransactionReceipt({ hash });
154
+ return hash;
155
+ }
156
+ async prepareSettle(params) {
157
+ const { resourceId, identity, stealthAddress } = params;
158
+ const groupId = await this.publicClient.readContract({
159
+ address: this.contractAddress,
160
+ abi: SETTLEMENT_REGISTRY_ABI,
161
+ functionName: "getGroupId",
162
+ args: [resourceId]
163
+ });
164
+ if (groupId === 0n) throw new Error(`No group for resource ${resourceId} — was createResource() called?`);
165
+ const proof = await generateProof(identity, await this.fetchGroup(resourceId), BigInt(stealthAddress), groupId);
166
+ return {
167
+ resourceId,
168
+ stealthAddress,
169
+ merkleTreeDepth: BigInt(proof.merkleTreeDepth),
170
+ merkleTreeRoot: BigInt(proof.merkleTreeRoot),
171
+ nullifier: BigInt(proof.nullifier),
172
+ message: BigInt(proof.message),
173
+ points: proof.points.map(BigInt),
174
+ hookData: params.hookData ?? "0x"
175
+ };
176
+ }
177
+ async settle(params) {
178
+ const { relayerPrivateKey, preparedSettle } = params;
179
+ const { resourceId, stealthAddress, merkleTreeDepth, merkleTreeRoot, nullifier, message, points } = preparedSettle;
180
+ const chain = this.walletClient.chain;
181
+ if (!chain) throw new Error("Wallet client must have a chain configured.");
182
+ const hash = await createWalletClient({
183
+ account: privateKeyToAccount(relayerPrivateKey),
184
+ chain,
185
+ transport: http(chain.rpcUrls.default.http[0])
186
+ }).writeContract({
187
+ address: this.contractAddress,
188
+ abi: SETTLEMENT_REGISTRY_ABI,
189
+ functionName: "settle",
190
+ gas: 8000000n,
191
+ args: [
192
+ resourceId,
193
+ stealthAddress,
194
+ merkleTreeDepth,
195
+ merkleTreeRoot,
196
+ nullifier,
197
+ message,
198
+ points,
199
+ []
200
+ ],
201
+ chain: arbitrumSepolia,
202
+ account: privateKeyToAccount(relayerPrivateKey)
203
+ });
204
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
205
+ console.log("settlement status " + receipt.status);
206
+ return {
207
+ hash,
208
+ nullifier
209
+ };
210
+ }
211
+ /**
212
+ * Check if a nullifier has been settled (i.e. the user completed Phase 2).
213
+ * Used to gate decryptFile() in the Fangorn class.
214
+ */
215
+ async isSettled(stealthAddress, resourceId) {
216
+ return this.publicClient.readContract({
217
+ address: this.contractAddress,
218
+ abi: SETTLEMENT_REGISTRY_ABI,
219
+ functionName: "isSettled",
220
+ args: [stealthAddress, resourceId]
221
+ });
222
+ }
223
+ /**
224
+ * Check if an identity commitment is registered for a resource (completed Phase 1).
225
+ */
226
+ async isRegistered(resourceId, identityCommitment) {
227
+ return this.publicClient.readContract({
228
+ address: this.contractAddress,
229
+ abi: SETTLEMENT_REGISTRY_ABI,
230
+ functionName: "isRegistered",
231
+ args: [resourceId, identityCommitment]
232
+ });
233
+ }
234
+ /**
235
+ * Get the semaphore group id for a resource
236
+ * @param resourceId The resource id
237
+ * @returns The group id (if it exists), else null
238
+ */
239
+ async getGroupId(resourceId) {
240
+ return this.publicClient.readContract({
241
+ address: this.contractAddress,
242
+ abi: SETTLEMENT_REGISTRY_ABI,
243
+ functionName: "getGroupId",
244
+ args: [resourceId]
245
+ });
246
+ }
247
+ /**
248
+ * Get the price associated with a resource
249
+ * @param resourceId The resource id
250
+ * @returns The price
251
+ */
252
+ async getPrice(resourceId) {
253
+ return this.publicClient.readContract({
254
+ address: this.contractAddress,
255
+ abi: SETTLEMENT_REGISTRY_ABI,
256
+ functionName: "getPrice",
257
+ args: [resourceId]
258
+ });
259
+ }
260
+ /**
261
+ * Deterministic resource_id = keccak256(ownerAddress ++ schemaName ++ tag).
262
+ * This can be implemented in any way as long as owner/schema/tag produces a unique output
263
+ */
264
+ static deriveResourceId(owner, schemaName, tag) {
265
+ return keccak256(encodePacked([
266
+ "address",
267
+ "string",
268
+ "string"
269
+ ], [
270
+ owner,
271
+ schemaName,
272
+ tag
273
+ ]));
274
+ }
275
+ /**
276
+ * Reconstruct the Semaphore group from MemberRegistered events.
277
+ * Fetches all logs (no topic filter) and filters in JS to avoid
278
+ * viem topic-encoding edge cases with indexed params.
279
+ */
280
+ async fetchGroup(resourceId) {
281
+ const filtered = (await this.publicClient.getLogs({
282
+ address: this.contractAddress,
283
+ event: {
284
+ name: "MemberRegistered",
285
+ type: "event",
286
+ inputs: [
287
+ {
288
+ name: "resourceId",
289
+ type: "bytes32",
290
+ indexed: true
291
+ },
292
+ {
293
+ name: "groupId",
294
+ type: "uint256",
295
+ indexed: true
296
+ },
297
+ {
298
+ name: "identityCommitment",
299
+ type: "uint256",
300
+ indexed: false
301
+ }
302
+ ]
303
+ },
304
+ fromBlock: 0n
305
+ })).filter((log) => log.args.resourceId?.toLowerCase() === resourceId.toLowerCase());
306
+ const group = new Group();
307
+ for (const log of filtered) group.addMember(String(log.args.identityCommitment));
308
+ return group;
309
+ }
310
+ async waitForTransaction(hash) {
311
+ return await this.publicClient.waitForTransactionReceipt({ hash });
312
+ }
313
+ };
314
+
315
+ //#endregion
316
+ export { SettlementRegistry };
@@ -0,0 +1,51 @@
1
+ import { Address, Hex } from "viem";
2
+ import { Identity } from "@semaphore-protocol/identity";
3
+
4
+ //#region src/registries/settlement-registry/types.d.ts
5
+ interface TransferWithAuthParams {
6
+ burnerPrivateKey: Hex;
7
+ paymentRecipient: Address;
8
+ amount: bigint;
9
+ usdcAddress: Address;
10
+ usdcDomainName: string;
11
+ usdcDomainVersion: string;
12
+ }
13
+ interface TransferWithAuthPayload {
14
+ burnerAddress: Address;
15
+ paymentRecipient: Address;
16
+ amount: bigint;
17
+ validAfter: bigint;
18
+ validBefore: bigint;
19
+ nonce: Hex;
20
+ v: number;
21
+ r: Hex;
22
+ s: Hex;
23
+ }
24
+ interface RegisterParams {
25
+ resourceId: Hex;
26
+ identityCommitment: bigint;
27
+ relayerPrivateKey: Hex;
28
+ preparedRegister: TransferWithAuthPayload;
29
+ }
30
+ interface PrepareSettleParams {
31
+ resourceId: Hex;
32
+ identity: Identity;
33
+ stealthAddress: Address;
34
+ hookData?: Hex;
35
+ }
36
+ interface PrepareSettleResult {
37
+ resourceId: Hex;
38
+ stealthAddress: Address;
39
+ merkleTreeDepth: bigint;
40
+ merkleTreeRoot: bigint;
41
+ nullifier: bigint;
42
+ message: bigint;
43
+ points: [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint];
44
+ hookData: Hex;
45
+ }
46
+ interface SettleParams {
47
+ relayerPrivateKey: Hex;
48
+ preparedSettle: PrepareSettleResult;
49
+ }
50
+ //#endregion
51
+ export { PrepareSettleParams, PrepareSettleResult, RegisterParams, SettleParams, TransferWithAuthParams, TransferWithAuthPayload };
@@ -0,0 +1,64 @@
1
+ import { ReadableStorage } from "../../providers/storage/index.js";
2
+ import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
3
+ import { PrepareSettleParams, PrepareSettleResult, TransferWithAuthParams, TransferWithAuthPayload } from "../../registries/settlement-registry/types.js";
4
+ import { SettlementRegistry } from "../../registries/settlement-registry/index.js";
5
+ import { EncryptionService } from "../../modules/encryption/index.js";
6
+ import { Manifest, ManifestEntry } from "../publisher/types.js";
7
+ import { ClaimParams, ClaimResult, DecryptParams, PurchaseParams, PurchaseResult } from "./types.js";
8
+ import { Address, Hex } from "viem";
9
+ import { Identity } from "@semaphore-protocol/identity";
10
+
11
+ //#region src/roles/consumer/index.d.ts
12
+
13
+ /**
14
+ * The consumer namespace encapsulates all functionality relative to accessing and consuming data.
15
+ */
16
+ declare class ConsumerRole {
17
+ private readonly dataSourceRegistry;
18
+ private readonly settlementRegistry;
19
+ private readonly storage;
20
+ private readonly encryptionService;
21
+ private readonly domain;
22
+ constructor(dataSourceRegistry: DataSourceRegistry, settlementRegistry: SettlementRegistry, storage: ReadableStorage<unknown>, encryptionService: EncryptionService, domain: string);
23
+ /**
24
+ * Builds the transfer with auth (ERC-3009) and signs it (EIP-712)
25
+ * @param params
26
+ * @returns
27
+ */
28
+ prepareRegister(params: TransferWithAuthParams): Promise<TransferWithAuthPayload>;
29
+ /**
30
+ * Builds the zkp to prove you're in a semaphore group
31
+ * @param params
32
+ * @returns
33
+ */
34
+ prepareSettle(params: PrepareSettleParams): Promise<PrepareSettleResult>;
35
+ /**
36
+ * Purchase the resource and register in the semaphore group (on success)
37
+ * @param params
38
+ * @returns
39
+ */
40
+ register(params: PurchaseParams): Promise<PurchaseResult>;
41
+ /**
42
+ * Claim access to a resource (prove settlement)
43
+ * Must register first.
44
+ * @param params
45
+ * @returns
46
+ */
47
+ claim(params: ClaimParams): Promise<ClaimResult>;
48
+ /**
49
+ * Decrypt a specific encrypted field within a record.
50
+ *
51
+ * One purchase + claim unlocks ALL encrypted fields in the record —
52
+ * the resource is at the record (tag) level, not the field level.
53
+ * This method can be called once per encrypted field without re-purchasing.
54
+ *
55
+ * Plain fields can be read freely via getEntry() without any of this.
56
+ */
57
+ decrypt(params: DecryptParams): Promise<Uint8Array>;
58
+ getManifest(owner: Address, schemaId: Hex): Promise<Manifest | undefined>;
59
+ getEntry(owner: Address, schemaId: Hex, tag: string): Promise<ManifestEntry>;
60
+ isRegistered(owner: Address, schemaId: Hex, tag: string, identity: Identity): Promise<boolean>;
61
+ private deriveResourceId;
62
+ }
63
+ //#endregion
64
+ export { ConsumerRole };
@@ -0,0 +1,114 @@
1
+ import { SettlementRegistry } from "../../registries/settlement-registry/index.js";
2
+
3
+ //#region src/roles/consumer/index.ts
4
+ /**
5
+ * The consumer namespace encapsulates all functionality relative to accessing and consuming data.
6
+ */
7
+ var ConsumerRole = class {
8
+ constructor(dataSourceRegistry, settlementRegistry, storage, encryptionService, domain) {
9
+ this.dataSourceRegistry = dataSourceRegistry;
10
+ this.settlementRegistry = settlementRegistry;
11
+ this.storage = storage;
12
+ this.encryptionService = encryptionService;
13
+ this.domain = domain;
14
+ }
15
+ /**
16
+ * Builds the transfer with auth (ERC-3009) and signs it (EIP-712)
17
+ * @param params
18
+ * @returns
19
+ */
20
+ async prepareRegister(params) {
21
+ return this.settlementRegistry.prepareTransferWithAuth(params);
22
+ }
23
+ /**
24
+ * Builds the zkp to prove you're in a semaphore group
25
+ * @param params
26
+ * @returns
27
+ */
28
+ async prepareSettle(params) {
29
+ return this.settlementRegistry.prepareSettle(params);
30
+ }
31
+ /**
32
+ * Purchase the resource and register in the semaphore group (on success)
33
+ * @param params
34
+ * @returns
35
+ */
36
+ async register(params) {
37
+ const resourceId = this.deriveResourceId(params.owner, params.schemaId, params.tag);
38
+ return {
39
+ txHash: await this.settlementRegistry.register({
40
+ resourceId,
41
+ identityCommitment: params.identityCommitment,
42
+ relayerPrivateKey: params.relayerPrivateKey,
43
+ preparedRegister: params.preparedRegister
44
+ }),
45
+ resourceId
46
+ };
47
+ }
48
+ /**
49
+ * Claim access to a resource (prove settlement)
50
+ * Must register first.
51
+ * @param params
52
+ * @returns
53
+ */
54
+ async claim(params) {
55
+ const resourceId = this.deriveResourceId(params.owner, params.schemaId, params.tag);
56
+ const { hash, nullifier } = await this.settlementRegistry.settle({
57
+ relayerPrivateKey: params.relayerPrivateKey,
58
+ preparedSettle: params.preparedSettle
59
+ });
60
+ return {
61
+ txHash: hash,
62
+ nullifier,
63
+ resourceId
64
+ };
65
+ }
66
+ /**
67
+ * Decrypt a specific encrypted field within a record.
68
+ *
69
+ * One purchase + claim unlocks ALL encrypted fields in the record —
70
+ * the resource is at the record (tag) level, not the field level.
71
+ * This method can be called once per encrypted field without re-purchasing.
72
+ *
73
+ * Plain fields can be read freely via getEntry() without any of this.
74
+ */
75
+ async decrypt(params) {
76
+ const resourceId = this.deriveResourceId(params.owner, params.schemaId, params.tag);
77
+ if (!params.skipSettlementCheck) {
78
+ if (!params.identity) throw new Error("identity is required for settlement verification. Pass skipSettlementCheck: true for owner / out-of-band flows.");
79
+ if (!await this.settlementRegistry.isRegistered(resourceId, params.identity.commitment)) throw new Error(`Access denied: identity not registered for resource ${resourceId}. Call purchase() and wait for confirmation before decrypting.`);
80
+ }
81
+ const fieldValue = (await this.getEntry(params.owner, params.schemaId, params.tag)).fields[params.field];
82
+ if (!fieldValue || typeof fieldValue !== "object") throw new Error(`Field "${params.field}" is missing or invalid`);
83
+ const encryptedField = fieldValue;
84
+ const encrypted = await this.storage.retrieve(encryptedField.handle.cid);
85
+ const authContext = params.authContext ?? await this.encryptionService.createAuthContext(params.walletClient, this.domain, params.nullifierHash);
86
+ return (await this.encryptionService.decrypt(encrypted, authContext)).data;
87
+ }
88
+ async getManifest(owner, schemaId) {
89
+ try {
90
+ const ds = await this.dataSourceRegistry.getManifest(owner, schemaId);
91
+ if (!ds.manifestCid || ds.manifestCid === "") return void 0;
92
+ return await this.storage.retrieve(ds.manifestCid);
93
+ } catch {
94
+ return;
95
+ }
96
+ }
97
+ async getEntry(owner, schemaId, tag) {
98
+ const manifest = await this.getManifest(owner, schemaId);
99
+ if (!manifest) throw new Error(`No manifest found for owner ${owner} / schemaId ${schemaId}`);
100
+ const entry = manifest.entries.find((e) => e.tag === tag);
101
+ if (!entry) throw new Error(`Entry not found: "${tag}"`);
102
+ return entry;
103
+ }
104
+ async isRegistered(owner, schemaId, tag, identity) {
105
+ const resourceId = this.deriveResourceId(owner, schemaId, tag);
106
+ return this.settlementRegistry.isRegistered(resourceId, identity.commitment);
107
+ }
108
+ deriveResourceId(owner, schemaId, tag) {
109
+ return SettlementRegistry.deriveResourceId(owner, schemaId, tag);
110
+ }
111
+ };
112
+
113
+ //#endregion
114
+ export { ConsumerRole };
@@ -0,0 +1,66 @@
1
+ import { PrepareSettleResult, RegisterParams, SettleParams, TransferWithAuthPayload } from "../../registries/settlement-registry/types.js";
2
+ import { AuthContext } from "../../modules/encryption/index.js";
3
+ import { ManifestEntry } from "../publisher/types.js";
4
+ import { Address, Hex, WalletClient } from "viem";
5
+ import { Identity } from "@semaphore-protocol/identity";
6
+
7
+ //#region src/roles/consumer/types.d.ts
8
+ interface PurchaseParams {
9
+ owner: Address;
10
+ schemaId: Hex;
11
+ tag: string;
12
+ identityCommitment: bigint;
13
+ relayerPrivateKey: Hex;
14
+ preparedRegister: TransferWithAuthPayload;
15
+ }
16
+ interface ClaimParams {
17
+ owner: Address;
18
+ schemaId: Hex;
19
+ tag: string;
20
+ relayerPrivateKey: Hex;
21
+ preparedSettle: PrepareSettleResult;
22
+ }
23
+ interface DecryptParams {
24
+ owner: Address;
25
+ walletClient: WalletClient;
26
+ schemaId: Hex;
27
+ nullifierHash: bigint;
28
+ /** The record tag — maps to the resourceId */
29
+ tag: 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
+ tag: 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
+ interface PurchaseResult {
52
+ txHash: Hex;
53
+ resourceId: Hex;
54
+ }
55
+ interface ClaimResult {
56
+ txHash: Hex;
57
+ nullifier: bigint;
58
+ resourceId: Hex;
59
+ }
60
+ interface AccessResult {
61
+ data: Uint8Array;
62
+ resourceId: Hex;
63
+ entry: ManifestEntry;
64
+ }
65
+ //#endregion
66
+ export { AccessParams, AccessResult, ClaimParams, ClaimResult, DecryptParams, PurchaseParams, PurchaseResult };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,70 @@
1
+ import { WritableStorage } from "../../providers/storage/index.js";
2
+ import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
3
+ import { SettlementRegistry } from "../../registries/settlement-registry/index.js";
4
+ import { EncryptionService } from "../../modules/encryption/index.js";
5
+ import { CommitResult, EncryptedFieldInput, FieldInput, Manifest, ManifestEntry, PublishRecord, ResolvedEncryptedField, ResolvedField, ResolvedPlainField, UploadParams } from "./types.js";
6
+ import { Hex, WalletClient } from "viem";
7
+
8
+ //#region src/roles/publisher/index.d.ts
9
+ declare class PublisherRole {
10
+ private readonly dataSourceRegistry;
11
+ private readonly settlementRegistry;
12
+ private readonly storage;
13
+ private readonly encryptionService;
14
+ private readonly walletClient;
15
+ private pendingEntries;
16
+ constructor(dataSourceRegistry: DataSourceRegistry, settlementRegistry: SettlementRegistry, storage: WritableStorage<unknown>, encryptionService: EncryptionService, walletClient: WalletClient);
17
+ /**
18
+ * Encrypt and Upload data with Fangorn
19
+ * Validate records against the schema, encrypt encrypted
20
+ * fields, stage all resolved entries, then commit to IPFS + on-chain.
21
+ *
22
+ * Each encrypted field within a record is stored as a separate IPFS object
23
+ * (the ciphertext). The manifest entry stores the handle (CID + gateway)
24
+ * alongside the plain fields. Consumers can read plain fields freely and
25
+ * only need to purchase + decrypt for encrypted fields.
26
+ */
27
+ upload(params: UploadParams, price: bigint): Promise<CommitResult>;
28
+ /**
29
+ * Stage a pre-resolved entry manually (advanced use).
30
+ * Prefer upload() for the standard flow.
31
+ */
32
+ stage(entry: ManifestEntry): void;
33
+ remove(tag: string): boolean;
34
+ getPending(): ManifestEntry[];
35
+ clearPending(): void;
36
+ /**
37
+ * Serialize all staged entries into a manifest, create SettlementRegistry
38
+ * resources for each entry, pin the manifest to IPFS, and publish on-chain.
39
+ *
40
+ * @param schemaId: The unique id of the schema
41
+ * @param price: The USDC price required to register with the sempaphore group
42
+ * @param overwrite: If true, overwrite manifest data, else append (default: false)
43
+ *
44
+ */
45
+ commit(schemaId: Hex, price: bigint, overwrite: boolean): Promise<CommitResult>;
46
+ getManifest(schemaId: Hex): Promise<Manifest | undefined>;
47
+ getEntry(schemaId: Hex, tag: string): Promise<ManifestEntry>;
48
+ private requireAccount;
49
+ /**
50
+ * Resolve a PublishRecord into a ManifestEntry by processing each field
51
+ * according to the schema definition:
52
+ * - plain fields are stored as-is
53
+ * - encrypted fields are AES+Lit encrypted, pinned to IPFS, and replaced
54
+ * with a handle + gadgetDescriptor
55
+ */
56
+ private resolveRecord;
57
+ /**
58
+ * Validate that a record's fields match the schema before touching IPFS.
59
+ * Catches type mismatches and missing required fields early.
60
+ */
61
+ private validateRecord;
62
+ private validateField;
63
+ /**
64
+ * Load the existing manifest into pending entries for merge behaviour.
65
+ * Unpins the old manifest CID
66
+ */
67
+ private loadExistingManifest;
68
+ }
69
+ //#endregion
70
+ export { CommitResult, EncryptedFieldInput, FieldInput, Manifest, ManifestEntry, PublishRecord, PublisherRole, ResolvedEncryptedField, ResolvedField, ResolvedPlainField, UploadParams };