@fangorn-network/sdk 2026.5.11 → 2026.7.1-2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +219 -225
  2. package/lib/ crypto/constants.d.ts +4 -0
  3. package/lib/ crypto/constants.js +5 -0
  4. package/lib/ crypto/merkle.d.ts +10 -0
  5. package/lib/ crypto/merkle.js +34 -0
  6. package/lib/cli/cli.d.ts +0 -0
  7. package/lib/cli/cli.js +234 -235
  8. package/lib/cli/index.d.ts +13 -650
  9. package/lib/config.d.ts +45 -699
  10. package/lib/config.js +6 -22
  11. package/lib/contracts/data-registry/abi.d.ts +38 -0
  12. package/lib/contracts/data-registry/abi.js +237 -0
  13. package/lib/contracts/data-registry/index.d.ts +81 -0
  14. package/lib/contracts/data-registry/index.js +184 -0
  15. package/lib/contracts/data-registry/test.d.ts +1 -0
  16. package/lib/contracts/index.d.ts +3 -0
  17. package/lib/contracts/index.js +4 -0
  18. package/lib/crypto/aes.d.ts +26 -0
  19. package/lib/crypto/aes.js +58 -0
  20. package/lib/crypto/encryption.d.ts +53 -0
  21. package/lib/crypto/encryption.js +82 -0
  22. package/lib/crypto/rand.d.ts +5 -0
  23. package/lib/{modules/encryption → crypto}/rand.js +1 -1
  24. package/lib/{modules/encryption → crypto}/types.d.ts +1 -1
  25. package/lib/engine/blockstore.d.ts +24 -0
  26. package/lib/engine/blockstore.js +85 -0
  27. package/lib/engine/index.d.ts +180 -0
  28. package/lib/engine/index.js +367 -0
  29. package/lib/fangorn.d.ts +149 -16
  30. package/lib/fangorn.js +256 -37
  31. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +1 -0
  32. package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
  33. package/lib/harness/index.d.ts +57 -0
  34. package/lib/harness/index.js +67 -0
  35. package/lib/index.d.ts +2 -4
  36. package/lib/index.js +1 -3
  37. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/_polyval.js +218 -0
  38. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js +261 -0
  39. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js +156 -0
  40. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js +299 -0
  41. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js +532 -0
  42. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js +344 -0
  43. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js +137 -0
  44. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js +262 -0
  45. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/utils.js +150 -0
  46. package/lib/providers/storage/car.d.ts +36 -0
  47. package/lib/providers/storage/car.js +80 -0
  48. package/lib/providers/storage/pinata.d.ts +34 -2
  49. package/lib/providers/storage/pinata.js +141 -5
  50. package/lib/providers/storage/types.d.ts +31 -16
  51. package/lib/providers/storage/utils.js +2 -1
  52. package/lib/roles/repo/index.d.ts +56 -0
  53. package/lib/roles/repo/index.js +73 -0
  54. package/lib/test/car_smoke.d.ts +1 -0
  55. package/lib/test/car_smoke.js +81 -0
  56. package/lib/test/cleanup-embeddings-testdata.d.ts +1 -0
  57. package/lib/test/cleanup-embeddings-testdata.js +75 -0
  58. package/lib/test/setup-embeddings-testdata.d.ts +11 -0
  59. package/lib/test/setup-embeddings-testdata.js +155 -0
  60. package/lib/test/testbed.d.ts +39 -30
  61. package/lib/test/testbed.js +43 -129
  62. package/lib/types/index.d.ts +3 -19
  63. package/lib/utils/manifest.d.ts +23 -0
  64. package/lib/utils/manifest.js +77 -0
  65. package/package.json +99 -67
  66. package/lib/modules/encryption/actions.d.ts +0 -4
  67. package/lib/modules/encryption/actions.js +0 -18
  68. package/lib/modules/encryption/aes.d.ts +0 -10
  69. package/lib/modules/encryption/aes.js +0 -51
  70. package/lib/modules/encryption/rand.d.ts +0 -5
  71. package/lib/registries/datasource-registry/abi.d.ts +0 -156
  72. package/lib/registries/datasource-registry/abi.js +0 -194
  73. package/lib/registries/datasource-registry/index.d.ts +0 -30
  74. package/lib/registries/datasource-registry/index.js +0 -158
  75. package/lib/registries/index.d.ts +0 -3
  76. package/lib/registries/index.js +0 -4
  77. package/lib/registries/schema-registry/abi.d.ts +0 -218
  78. package/lib/registries/schema-registry/abi.js +0 -246
  79. package/lib/registries/schema-registry/index.d.ts +0 -34
  80. package/lib/registries/schema-registry/index.js +0 -179
  81. package/lib/registries/settlement-registry/abi.d.ts +0 -218
  82. package/lib/registries/settlement-registry/abi.js +0 -259
  83. package/lib/registries/settlement-registry/index.d.ts +0 -63
  84. package/lib/registries/settlement-registry/index.js +0 -325
  85. package/lib/registries/settlement-registry/types.d.ts +0 -54
  86. package/lib/roles/consumer/index.d.ts +0 -39
  87. package/lib/roles/consumer/index.js +0 -143
  88. package/lib/roles/consumer/types.d.ts +0 -47
  89. package/lib/roles/consumer/types.js +0 -1
  90. package/lib/roles/publisher/index.d.ts +0 -50
  91. package/lib/roles/publisher/index.js +0 -224
  92. package/lib/roles/publisher/types.d.ts +0 -99
  93. package/lib/roles/publisher/types.js +0 -1
  94. package/lib/roles/schema/index.d.ts +0 -18
  95. package/lib/roles/schema/index.js +0 -93
  96. package/lib/roles/schema/types.d.ts +0 -91
  97. package/lib/roles/schema/types.js +0 -1
  98. /package/lib/{modules/encryption/index.d.ts → crypto/utils.d.ts} +0 -0
  99. /package/lib/{modules/encryption/index.js → crypto/utils.js} +0 -0
  100. /package/lib/{modules/encryption/types.js → contracts/data-registry/test.js} +0 -0
  101. /package/lib/{registries/settlement-registry → crypto}/types.js +0 -0
@@ -1,325 +0,0 @@
1
- import { SETTLEMENT_REGISTRY_ABI } from "./abi.js";
2
- import { createWalletClient, http, parseSignature } from "viem";
3
- import { privateKeyToAccount } from "viem/accounts";
4
- import { Group } from "@semaphore-protocol/group";
5
- import { generateProof } from "@semaphore-protocol/proof";
6
-
7
- //#region src/registries/settlement-registry/index.ts
8
- var SettlementRegistry = class {
9
- constructor(contractAddress, publicClient, walletClient) {
10
- this.contractAddress = contractAddress;
11
- this.publicClient = publicClient;
12
- this.walletClient = walletClient;
13
- }
14
- getAccount() {
15
- const account = this.walletClient.account;
16
- if (!account) throw new Error("Wallet client must have an account configured");
17
- return account;
18
- }
19
- getChain() {
20
- const chain = this.walletClient.chain;
21
- if (!chain) throw new Error("Wallet client must have a chain configured");
22
- return chain;
23
- }
24
- /**
25
- * Authorize or revoke a DataSourceRegistry contract.
26
- * Only callable by the contract admin.
27
- */
28
- async setRegistry(registry, authorized) {
29
- const account = this.getAccount();
30
- const hash = await this.walletClient.writeContract({
31
- address: this.contractAddress,
32
- abi: SETTLEMENT_REGISTRY_ABI,
33
- functionName: "setRegistry",
34
- args: [registry, authorized],
35
- chain: this.getChain(),
36
- account
37
- });
38
- await this.publicClient.waitForTransactionReceipt({ hash });
39
- return hash;
40
- }
41
- /**
42
- * Create a Semaphore group for a resource.
43
- * In production this is called by the DataSourceRegistry, which passes
44
- * the publisher wallet as `owner`. Direct calls require the caller to
45
- * be an authorized registry.
46
- */
47
- async createResource(resourceId, price, owner) {
48
- const account = this.getAccount();
49
- const hash = await this.walletClient.writeContract({
50
- address: this.contractAddress,
51
- abi: SETTLEMENT_REGISTRY_ABI,
52
- functionName: "createResource",
53
- args: [
54
- resourceId,
55
- price,
56
- owner
57
- ],
58
- chain: this.getChain(),
59
- account
60
- });
61
- await this.publicClient.waitForTransactionReceipt({ hash });
62
- return hash;
63
- }
64
- /**
65
- * Update the price for a resource.
66
- * In production this is called by the DataSourceRegistry.
67
- */
68
- async updatePrice(resourceId, hook, price) {
69
- const account = this.getAccount();
70
- const hash = await this.walletClient.writeContract({
71
- address: this.contractAddress,
72
- abi: SETTLEMENT_REGISTRY_ABI,
73
- functionName: "updateResource",
74
- args: [
75
- resourceId,
76
- hook,
77
- price
78
- ],
79
- chain: this.getChain(),
80
- account
81
- });
82
- await this.publicClient.waitForTransactionReceipt({ hash });
83
- return hash;
84
- }
85
- /**
86
- * Prepare the EIP-3009 transferWithAuthorization signature.
87
- */
88
- async prepareTransferWithAuth(params) {
89
- const { paymentRecipient, amount, usdcAddress, usdcDomainName, usdcDomainVersion } = params;
90
- const walletClient = params.walletClient ?? this.walletClient;
91
- const chain = walletClient.chain;
92
- if (!chain) throw new Error("Wallet client must have a chain configured.");
93
- const account = walletClient.account;
94
- if (!account) throw new Error("Wallet client must have an account configured.");
95
- const validAfter = 0n;
96
- const validBefore = BigInt(Math.floor(Date.now() / 1e3) + 3600);
97
- const nonceBytes = crypto.getRandomValues(new Uint8Array(32));
98
- const nonce = `0x${Array.from(nonceBytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
99
- const { v, r, s } = parseSignature(await walletClient.signTypedData({
100
- account,
101
- domain: {
102
- name: usdcDomainName,
103
- version: usdcDomainVersion,
104
- chainId: chain.id,
105
- verifyingContract: usdcAddress
106
- },
107
- types: { TransferWithAuthorization: [
108
- {
109
- name: "from",
110
- type: "address"
111
- },
112
- {
113
- name: "to",
114
- type: "address"
115
- },
116
- {
117
- name: "value",
118
- type: "uint256"
119
- },
120
- {
121
- name: "validAfter",
122
- type: "uint256"
123
- },
124
- {
125
- name: "validBefore",
126
- type: "uint256"
127
- },
128
- {
129
- name: "nonce",
130
- type: "bytes32"
131
- }
132
- ] },
133
- primaryType: "TransferWithAuthorization",
134
- message: {
135
- from: account.address,
136
- to: paymentRecipient,
137
- value: amount,
138
- validAfter,
139
- validBefore,
140
- nonce
141
- }
142
- }));
143
- return {
144
- sender: account.address,
145
- paymentRecipient,
146
- amount,
147
- validAfter,
148
- validBefore,
149
- nonce,
150
- v: Number(v),
151
- r,
152
- s
153
- };
154
- }
155
- /**
156
- * Phase 1 — submit payment and join the Semaphore group.
157
- * Submitted via a relayer so the buyer's burner wallet is never linked
158
- * to their identity commitment on-chain.
159
- */
160
- async register(params) {
161
- const { resourceId, identityCommitment, relayerPrivateKey, preparedRegister } = params;
162
- const { sender, paymentRecipient, amount, validAfter, validBefore, nonce, v, r, s } = preparedRegister;
163
- const chain = this.getChain();
164
- const hash = await createWalletClient({
165
- account: privateKeyToAccount(relayerPrivateKey),
166
- chain,
167
- transport: http(chain.rpcUrls.default.http[0])
168
- }).writeContract({
169
- address: this.contractAddress,
170
- abi: SETTLEMENT_REGISTRY_ABI,
171
- functionName: "register",
172
- args: [
173
- resourceId,
174
- identityCommitment,
175
- sender,
176
- paymentRecipient,
177
- amount,
178
- validAfter,
179
- validBefore,
180
- nonce,
181
- v,
182
- r,
183
- s
184
- ],
185
- chain,
186
- account: privateKeyToAccount(relayerPrivateKey)
187
- });
188
- await this.publicClient.waitForTransactionReceipt({ hash });
189
- return hash;
190
- }
191
- /**
192
- * Build the Semaphore proof for Phase 2.
193
- */
194
- async prepareSettle(params) {
195
- const { resourceId, identity, stealthAddress } = params;
196
- const groupId = await this.publicClient.readContract({
197
- address: this.contractAddress,
198
- abi: SETTLEMENT_REGISTRY_ABI,
199
- functionName: "getGroupId",
200
- args: [resourceId]
201
- });
202
- if (groupId === 0n) throw new Error(`No group for resource ${resourceId} — was createResource() called?`);
203
- const proof = await generateProof(identity, await this.fetchGroup(resourceId), BigInt(stealthAddress), groupId);
204
- return {
205
- resourceId,
206
- stealthAddress,
207
- merkleTreeDepth: BigInt(proof.merkleTreeDepth),
208
- merkleTreeRoot: BigInt(proof.merkleTreeRoot),
209
- nullifier: BigInt(proof.nullifier),
210
- message: BigInt(proof.message),
211
- points: proof.points.map(BigInt),
212
- hookData: params.hookData ?? "0x"
213
- };
214
- }
215
- /**
216
- * Phase 2 — prove group membership and claim access.
217
- * Submitted via a relayer for unlinkability.
218
- */
219
- async settle(params) {
220
- const { relayerPrivateKey, preparedSettle } = params;
221
- const { resourceId, stealthAddress, merkleTreeDepth, merkleTreeRoot, nullifier, message, points, hookData } = preparedSettle;
222
- const chain = this.getChain();
223
- const submitter = createWalletClient({
224
- account: privateKeyToAccount(relayerPrivateKey),
225
- chain,
226
- transport: http(chain.rpcUrls.default.http[0])
227
- });
228
- const hookBytes = hookData !== "0x" ? Array.from(Buffer.from(hookData.slice(2), "hex")) : [];
229
- const hash = await submitter.writeContract({
230
- address: this.contractAddress,
231
- abi: SETTLEMENT_REGISTRY_ABI,
232
- functionName: "settle",
233
- gas: 8000000n,
234
- args: [
235
- resourceId,
236
- stealthAddress,
237
- merkleTreeDepth,
238
- merkleTreeRoot,
239
- nullifier,
240
- message,
241
- points,
242
- hookBytes
243
- ],
244
- chain,
245
- account: privateKeyToAccount(relayerPrivateKey)
246
- });
247
- const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
248
- console.log("settlement status " + receipt.status);
249
- return {
250
- hash,
251
- nullifier
252
- };
253
- }
254
- async isSettled(stealthAddress, resourceId) {
255
- return this.publicClient.readContract({
256
- address: this.contractAddress,
257
- abi: SETTLEMENT_REGISTRY_ABI,
258
- functionName: "isSettled",
259
- args: [stealthAddress, resourceId]
260
- });
261
- }
262
- async isRegistered(resourceId, identityCommitment) {
263
- return this.publicClient.readContract({
264
- address: this.contractAddress,
265
- abi: SETTLEMENT_REGISTRY_ABI,
266
- functionName: "isRegistered",
267
- args: [resourceId, identityCommitment]
268
- });
269
- }
270
- async getGroupId(resourceId) {
271
- return this.publicClient.readContract({
272
- address: this.contractAddress,
273
- abi: SETTLEMENT_REGISTRY_ABI,
274
- functionName: "getGroupId",
275
- args: [resourceId]
276
- });
277
- }
278
- async getPrice(resourceId) {
279
- return this.publicClient.readContract({
280
- address: this.contractAddress,
281
- abi: SETTLEMENT_REGISTRY_ABI,
282
- functionName: "getPrice",
283
- args: [resourceId]
284
- });
285
- }
286
- async waitForTransaction(hash) {
287
- return this.publicClient.waitForTransactionReceipt({ hash });
288
- }
289
- /**
290
- * Reconstruct the Semaphore group from MemberRegistered events.
291
- */
292
- async fetchGroup(resourceId) {
293
- const logs = await this.publicClient.getLogs({
294
- address: this.contractAddress,
295
- event: {
296
- name: "MemberRegistered",
297
- type: "event",
298
- inputs: [
299
- {
300
- name: "resourceId",
301
- type: "bytes32",
302
- indexed: true
303
- },
304
- {
305
- name: "groupId",
306
- type: "uint256",
307
- indexed: true
308
- },
309
- {
310
- name: "identityCommitment",
311
- type: "uint256",
312
- indexed: false
313
- }
314
- ]
315
- },
316
- fromBlock: 0n
317
- });
318
- const group = new Group();
319
- for (const log of logs.filter((l) => l.args.resourceId?.toLowerCase() === resourceId.toLowerCase())) group.addMember(String(log.args.identityCommitment));
320
- return group;
321
- }
322
- };
323
-
324
- //#endregion
325
- export { SettlementRegistry };
@@ -1,54 +0,0 @@
1
- import { Address, Hex, WalletClient } from "viem";
2
- import { Identity } from "@semaphore-protocol/identity";
3
-
4
- //#region src/registries/settlement-registry/types.d.ts
5
- interface TransferWithAuthParams {
6
- walletClient?: WalletClient;
7
- paymentRecipient: Address;
8
- amount: bigint;
9
- usdcAddress: Address;
10
- usdcDomainName: string;
11
- usdcDomainVersion: string;
12
- }
13
- interface TransferWithAuthPayload {
14
- sender: 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
- /**
25
- * The params for registering with a semaphore group
26
- */
27
- interface RegisterParams {
28
- resourceId: Hex;
29
- identityCommitment: bigint;
30
- relayerPrivateKey: Hex;
31
- preparedRegister: TransferWithAuthPayload;
32
- }
33
- interface PrepareSettleParams {
34
- resourceId: Hex;
35
- identity: Identity;
36
- stealthAddress: Address;
37
- hookData?: Hex;
38
- }
39
- interface PrepareSettleResult {
40
- resourceId: Hex;
41
- stealthAddress: Address;
42
- merkleTreeDepth: bigint;
43
- merkleTreeRoot: bigint;
44
- nullifier: bigint;
45
- message: bigint;
46
- points: [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint];
47
- hookData: Hex;
48
- }
49
- interface SettleParams {
50
- relayerPrivateKey: Hex;
51
- preparedSettle: PrepareSettleResult;
52
- }
53
- //#endregion
54
- export { PrepareSettleParams, PrepareSettleResult, RegisterParams, SettleParams, TransferWithAuthParams, TransferWithAuthPayload };
@@ -1,39 +0,0 @@
1
- import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
2
- import { Manifest, ManifestEntry } from "../publisher/types.js";
3
- import { PrepareSettleParams, PrepareSettleResult, TransferWithAuthParams, TransferWithAuthPayload } from "../../registries/settlement-registry/types.js";
4
- import { SettlementRegistry } from "../../registries/settlement-registry/index.js";
5
- import { ClaimParams, ClaimResult, FetchParams, FetchResult, PurchaseParams, PurchaseResult } from "./types.js";
6
- import { Address, Hex, WalletClient } from "viem";
7
- import { Identity } from "@semaphore-protocol/identity";
8
-
9
- //#region src/roles/consumer/index.d.ts
10
- declare class ConsumerRole {
11
- private readonly dataSourceRegistry;
12
- private readonly settlementRegistry;
13
- constructor(dataSourceRegistry: DataSourceRegistry, settlementRegistry: SettlementRegistry);
14
- prepareRegister(params: TransferWithAuthParams): Promise<TransferWithAuthPayload>;
15
- prepareSettle(params: PrepareSettleParams): Promise<PrepareSettleResult>;
16
- register(params: PurchaseParams): Promise<PurchaseResult>;
17
- claim(params: ClaimParams): Promise<ClaimResult>;
18
- /**
19
- * Fetch a handle field's content from the Fangorn access worker.
20
- *
21
- * The consumer signs { nullifier, resourceId, objectKey, timestamp } with
22
- * their stealth address private key. The worker recovers the address,
23
- * verifies is_settled() on-chain, and proxies the R2 bytes.
24
- *
25
- * Plain fields can be read freely via getEntry() without any of this.
26
- */
27
- fetch(params: FetchParams): Promise<FetchResult>;
28
- getManifest(owner: Address, schemaId: Hex, name: string): Promise<Manifest | undefined>;
29
- getEntry(owner: Address, schemaId: Hex, name: string): Promise<ManifestEntry>;
30
- /**
31
- * Resolves the handle URI for a specific field
32
- * and fetches it via the worker in one call.
33
- */
34
- fetchField(owner: Address, schemaId: Hex, name: string, field: string, nullifier: string, walletClient: WalletClient): Promise<FetchResult>;
35
- isRegistered(owner: Address, schemaId: Hex, name: string, identity: Identity): Promise<boolean>;
36
- private deriveResourceId;
37
- }
38
- //#endregion
39
- export { ConsumerRole };
@@ -1,143 +0,0 @@
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";
5
-
6
- //#region src/roles/consumer/index.ts
7
- var ConsumerRole = class {
8
- constructor(dataSourceRegistry, settlementRegistry) {
9
- this.dataSourceRegistry = dataSourceRegistry;
10
- this.settlementRegistry = settlementRegistry;
11
- }
12
- async prepareRegister(params) {
13
- return this.settlementRegistry.prepareTransferWithAuth(params);
14
- }
15
- async prepareSettle(params) {
16
- return this.settlementRegistry.prepareSettle(params);
17
- }
18
- async register(params) {
19
- const resourceId = this.deriveResourceId(params.owner, params.schemaId, params.name);
20
- return {
21
- txHash: await this.settlementRegistry.register({
22
- resourceId,
23
- identityCommitment: params.identityCommitment,
24
- relayerPrivateKey: params.relayerPrivateKey,
25
- preparedRegister: params.preparedRegister
26
- }),
27
- resourceId
28
- };
29
- }
30
- async claim(params) {
31
- const resourceId = this.deriveResourceId(params.owner, params.schemaId, params.name);
32
- const { hash, nullifier } = await this.settlementRegistry.settle({
33
- relayerPrivateKey: params.relayerPrivateKey,
34
- preparedSettle: params.preparedSettle
35
- });
36
- return {
37
- txHash: hash,
38
- nullifier,
39
- resourceId
40
- };
41
- }
42
- /**
43
- * Fetch a handle field's content from the Fangorn access worker.
44
- *
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.
48
- *
49
- * Plain fields can be read freely via getEntry() without any of this.
50
- */
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}`);
86
- }
87
- const buffer = await res.arrayBuffer();
88
- return {
89
- data: new Uint8Array(buffer),
90
- contentType: res.headers.get("Content-Type") ?? "application/octet-stream"
91
- };
92
- }
93
- async getManifest(owner, schemaId, name) {
94
- try {
95
- const ds = await this.dataSourceRegistry.get(owner, schemaId, name);
96
- if (!ds.manifestCid || ds.manifestCid === "") return void 0;
97
- return await PinataBackend.getStatic(ds.manifestCid);
98
- } catch {
99
- return;
100
- }
101
- }
102
- async getEntry(owner, schemaId, name) {
103
- const manifest = await this.getManifest(owner, schemaId, name);
104
- if (!manifest) throw new Error(`No manifest found for owner ${owner} / schemaId ${schemaId} / name ${name}`);
105
- const entry = manifest.entries.find((e) => e.name === name);
106
- if (!entry) throw new Error(`Entry not found: "${name}"`);
107
- return entry;
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
- if (fieldValue["@type"] !== "handle") throw new Error(`Field "${field}" is not a handle field. Read it directly from the entry`);
117
- const handle = fieldValue;
118
- const objectKey = parseObjectKey(handle.uri);
119
- const resourceId = this.deriveResourceId(owner, schemaId, name);
120
- return this.fetch({
121
- nullifier,
122
- resourceId,
123
- objectKey,
124
- workerUrl: handle.workerUrl,
125
- walletClient
126
- });
127
- }
128
- async isRegistered(owner, schemaId, name, identity) {
129
- const resourceId = this.deriveResourceId(owner, schemaId, name);
130
- return this.settlementRegistry.isRegistered(resourceId, identity.commitment);
131
- }
132
- deriveResourceId(owner, schemaId, name) {
133
- return DataSourceRegistry.resourceIdLocal(owner, schemaId, name);
134
- }
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
- }
141
-
142
- //#endregion
143
- export { ConsumerRole };
@@ -1,47 +0,0 @@
1
- import { ManifestEntry } from "../publisher/types.js";
2
- import { PrepareSettleResult, TransferWithAuthPayload } from "../../registries/settlement-registry/types.js";
3
- import { Address, Hex, WalletClient } from "viem";
4
-
5
- //#region src/roles/consumer/types.d.ts
6
- interface PurchaseParams {
7
- owner: Address;
8
- schemaId: Hex;
9
- name: string;
10
- identityCommitment: bigint;
11
- relayerPrivateKey: Hex;
12
- preparedRegister: TransferWithAuthPayload;
13
- }
14
- interface ClaimParams {
15
- owner: Address;
16
- schemaId: Hex;
17
- name: string;
18
- relayerPrivateKey: Hex;
19
- preparedSettle: PrepareSettleResult;
20
- }
21
- interface PurchaseResult {
22
- txHash: Hex;
23
- resourceId: Hex;
24
- }
25
- interface ClaimResult {
26
- txHash: Hex;
27
- nullifier: bigint;
28
- resourceId: Hex;
29
- }
30
- interface AccessResult {
31
- data: Uint8Array;
32
- resourceId: Hex;
33
- entry: ManifestEntry;
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
- }
46
- //#endregion
47
- export { AccessResult, ClaimParams, ClaimResult, FetchParams, FetchResult, PurchaseParams, PurchaseResult };
@@ -1 +0,0 @@
1
- export { };
@@ -1,50 +0,0 @@
1
- import { AppConfig } from "../../config.js";
2
- import { SchemaRegistry } from "../../registries/schema-registry/index.js";
3
- import { MetadataStorage } from "../../providers/storage/types.js";
4
- import { DataSourceRegistry } from "../../registries/datasource-registry/index.js";
5
- import { CommitResult, FieldInput, FieldInputObject, HandleArray, HandleFieldInput, Manifest, ManifestEntry, PublishRecord, ResolvedField, ResolvedHandleArray, ResolvedHandleField, ResolvedObject, 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 schemaRegistry;
12
- private readonly storage;
13
- private readonly walletClient;
14
- private readonly config;
15
- private pendingEntries;
16
- private readonly schemaCache;
17
- constructor(dataSourceRegistry: DataSourceRegistry, schemaRegistry: SchemaRegistry, storage: MetadataStorage, walletClient: WalletClient, config: AppConfig);
18
- /**
19
- * Validate and stage schema-conformant records, then commit to storage
20
- * and publish on-chain.
21
- */
22
- upload(params: UploadParams, price: bigint): Promise<CommitResult>;
23
- stage(entry: ManifestEntry): void;
24
- remove(name: string): boolean;
25
- getPending(): ManifestEntry[];
26
- clearPending(): void;
27
- /**
28
- * Serialize all staged entries into manifests, upload to storage,
29
- * and publish each manifest CID on-chain.
30
- */
31
- commit(schemaId: Hex, price: bigint, overwrite: boolean): Promise<CommitResult>;
32
- getManifest(schemaId: Hex, name: string): Promise<Manifest | undefined>;
33
- getEntry(schemaId: Hex, name: string): Promise<ManifestEntry>;
34
- private requireAccount;
35
- private resolveSchema;
36
- /**
37
- * Resolve a PublishRecord into a ManifestEntry.
38
- * Handle fields are passed through directly; plain fields stored inline.
39
- */
40
- private resolveRecord;
41
- private validateRecord;
42
- private validateField;
43
- /**
44
- * Return only entries whose names do not already exist on-chain
45
- * for this (owner, schemaId) pair.
46
- */
47
- private filterNewEntries;
48
- }
49
- //#endregion
50
- export { CommitResult, FieldInput, FieldInputObject, HandleArray, HandleFieldInput, Manifest, ManifestEntry, PublishRecord, PublisherRole, ResolvedField, ResolvedHandleArray, ResolvedHandleField, ResolvedObject, ResolvedPlainField, UploadParams };