@cofhe/sdk 0.1.0 → 0.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 (121) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/adapters/ethers5.test.ts +174 -0
  3. package/adapters/ethers5.ts +36 -0
  4. package/adapters/ethers6.test.ts +169 -0
  5. package/adapters/ethers6.ts +36 -0
  6. package/adapters/hardhat-node.ts +167 -0
  7. package/adapters/hardhat.hh2.test.ts +159 -0
  8. package/adapters/hardhat.ts +36 -0
  9. package/adapters/index.test.ts +20 -0
  10. package/adapters/index.ts +5 -0
  11. package/adapters/smartWallet.ts +99 -0
  12. package/adapters/test-utils.ts +53 -0
  13. package/adapters/types.ts +6 -0
  14. package/adapters/wagmi.test.ts +156 -0
  15. package/adapters/wagmi.ts +17 -0
  16. package/chains/chains/arbSepolia.ts +14 -0
  17. package/chains/chains/baseSepolia.ts +14 -0
  18. package/chains/chains/hardhat.ts +15 -0
  19. package/chains/chains/localcofhe.ts +14 -0
  20. package/chains/chains/sepolia.ts +14 -0
  21. package/chains/chains.test.ts +50 -0
  22. package/chains/defineChain.ts +18 -0
  23. package/chains/index.ts +35 -0
  24. package/chains/types.ts +32 -0
  25. package/core/baseBuilder.ts +119 -0
  26. package/core/client.test.ts +315 -0
  27. package/core/client.ts +292 -0
  28. package/core/clientTypes.ts +108 -0
  29. package/core/config.test.ts +235 -0
  30. package/core/config.ts +220 -0
  31. package/core/decrypt/MockQueryDecrypterAbi.ts +129 -0
  32. package/core/decrypt/cofheMocksSealOutput.ts +57 -0
  33. package/core/decrypt/decryptHandleBuilder.ts +287 -0
  34. package/core/decrypt/decryptUtils.ts +28 -0
  35. package/core/decrypt/tnSealOutputV1.ts +59 -0
  36. package/core/decrypt/tnSealOutputV2.ts +298 -0
  37. package/core/encrypt/MockZkVerifierAbi.ts +106 -0
  38. package/core/encrypt/cofheMocksZkVerifySign.ts +284 -0
  39. package/core/encrypt/encryptInputsBuilder.test.ts +751 -0
  40. package/core/encrypt/encryptInputsBuilder.ts +560 -0
  41. package/core/encrypt/encryptUtils.ts +67 -0
  42. package/core/encrypt/zkPackProveVerify.ts +335 -0
  43. package/core/error.ts +168 -0
  44. package/core/fetchKeys.test.ts +195 -0
  45. package/core/fetchKeys.ts +144 -0
  46. package/core/index.ts +89 -0
  47. package/core/keyStore.test.ts +226 -0
  48. package/core/keyStore.ts +154 -0
  49. package/core/permits.test.ts +494 -0
  50. package/core/permits.ts +200 -0
  51. package/core/types.ts +398 -0
  52. package/core/utils.ts +130 -0
  53. package/dist/adapters.cjs +88 -0
  54. package/dist/adapters.d.cts +14576 -0
  55. package/dist/adapters.d.ts +14576 -0
  56. package/dist/adapters.js +83 -0
  57. package/dist/chains.cjs +114 -0
  58. package/dist/chains.d.cts +121 -0
  59. package/dist/chains.d.ts +121 -0
  60. package/dist/chains.js +1 -0
  61. package/dist/chunk-UGBVZNRT.js +818 -0
  62. package/dist/chunk-WEAZ25JO.js +105 -0
  63. package/dist/chunk-WGCRJCBR.js +2523 -0
  64. package/dist/clientTypes-5_1nwtUe.d.cts +914 -0
  65. package/dist/clientTypes-Es7fyi65.d.ts +914 -0
  66. package/dist/core.cjs +3414 -0
  67. package/dist/core.d.cts +111 -0
  68. package/dist/core.d.ts +111 -0
  69. package/dist/core.js +3 -0
  70. package/dist/node.cjs +3286 -0
  71. package/dist/node.d.cts +22 -0
  72. package/dist/node.d.ts +22 -0
  73. package/dist/node.js +91 -0
  74. package/dist/permit-fUSe6KKq.d.cts +349 -0
  75. package/dist/permit-fUSe6KKq.d.ts +349 -0
  76. package/dist/permits.cjs +871 -0
  77. package/dist/permits.d.cts +1045 -0
  78. package/dist/permits.d.ts +1045 -0
  79. package/dist/permits.js +1 -0
  80. package/dist/types-KImPrEIe.d.cts +48 -0
  81. package/dist/types-KImPrEIe.d.ts +48 -0
  82. package/dist/web.cjs +3478 -0
  83. package/dist/web.d.cts +38 -0
  84. package/dist/web.d.ts +38 -0
  85. package/dist/web.js +240 -0
  86. package/dist/zkProve.worker.cjs +93 -0
  87. package/dist/zkProve.worker.d.cts +2 -0
  88. package/dist/zkProve.worker.d.ts +2 -0
  89. package/dist/zkProve.worker.js +91 -0
  90. package/node/client.test.ts +147 -0
  91. package/node/config.test.ts +68 -0
  92. package/node/encryptInputs.test.ts +155 -0
  93. package/node/index.ts +97 -0
  94. package/node/storage.ts +51 -0
  95. package/package.json +27 -15
  96. package/permits/index.ts +68 -0
  97. package/permits/localstorage.test.ts +117 -0
  98. package/permits/permit.test.ts +477 -0
  99. package/permits/permit.ts +405 -0
  100. package/permits/sealing.test.ts +84 -0
  101. package/permits/sealing.ts +131 -0
  102. package/permits/signature.ts +79 -0
  103. package/permits/store.test.ts +128 -0
  104. package/permits/store.ts +166 -0
  105. package/permits/test-utils.ts +20 -0
  106. package/permits/types.ts +191 -0
  107. package/permits/utils.ts +62 -0
  108. package/permits/validation.test.ts +288 -0
  109. package/permits/validation.ts +369 -0
  110. package/web/client.web.test.ts +147 -0
  111. package/web/config.web.test.ts +69 -0
  112. package/web/encryptInputs.web.test.ts +172 -0
  113. package/web/index.ts +161 -0
  114. package/web/storage.ts +34 -0
  115. package/web/worker.builder.web.test.ts +148 -0
  116. package/web/worker.config.web.test.ts +329 -0
  117. package/web/worker.output.web.test.ts +84 -0
  118. package/web/workerManager.test.ts +80 -0
  119. package/web/workerManager.ts +214 -0
  120. package/web/workerManager.web.test.ts +114 -0
  121. package/web/zkProve.worker.ts +133 -0
package/dist/node.cjs ADDED
@@ -0,0 +1,3286 @@
1
+ 'use strict';
2
+
3
+ var vanilla = require('zustand/vanilla');
4
+ var viem = require('viem');
5
+ var chains = require('viem/chains');
6
+ var accounts = require('viem/accounts');
7
+ var zod = require('zod');
8
+ var middleware = require('zustand/middleware');
9
+ var immer = require('immer');
10
+ var nacl = require('tweetnacl');
11
+ var fs = require('fs');
12
+ var path = require('path');
13
+ var nodeTfhe = require('node-tfhe');
14
+
15
+ function _interopNamespace(e) {
16
+ if (e && e.__esModule) return e;
17
+ var n = Object.create(null);
18
+ if (e) {
19
+ Object.keys(e).forEach(function (k) {
20
+ if (k !== 'default') {
21
+ var d = Object.getOwnPropertyDescriptor(e, k);
22
+ Object.defineProperty(n, k, d.get ? d : {
23
+ enumerable: true,
24
+ get: function () { return e[k]; }
25
+ });
26
+ }
27
+ });
28
+ }
29
+ n.default = e;
30
+ return Object.freeze(n);
31
+ }
32
+
33
+ var nacl__namespace = /*#__PURE__*/_interopNamespace(nacl);
34
+
35
+ // core/client.ts
36
+
37
+ // core/error.ts
38
+ var CofhesdkError = class _CofhesdkError extends Error {
39
+ code;
40
+ cause;
41
+ hint;
42
+ context;
43
+ constructor({ code, message, cause, hint, context }) {
44
+ const fullMessage = cause ? `${message} | Caused by: ${cause.message}` : message;
45
+ super(fullMessage);
46
+ this.name = "CofhesdkError";
47
+ this.code = code;
48
+ this.cause = cause;
49
+ this.hint = hint;
50
+ this.context = context;
51
+ if (Error.captureStackTrace) {
52
+ Error.captureStackTrace(this, _CofhesdkError);
53
+ }
54
+ }
55
+ /**
56
+ * Creates a CofhesdkError from an unknown error
57
+ * If the error is a CofhesdkError, it is returned unchanged, else a new CofhesdkError is created
58
+ * If a wrapperError is provided, it is used to create the new CofhesdkError, else a default is used
59
+ */
60
+ static fromError(error, wrapperError) {
61
+ if (isCofhesdkError(error))
62
+ return error;
63
+ const cause = error instanceof Error ? error : new Error(`${error}`);
64
+ return new _CofhesdkError({
65
+ code: wrapperError?.code ?? "INTERNAL_ERROR" /* InternalError */,
66
+ message: wrapperError?.message ?? "An internal error occurred",
67
+ hint: wrapperError?.hint,
68
+ context: wrapperError?.context,
69
+ cause
70
+ });
71
+ }
72
+ /**
73
+ * Serializes the error to JSON string with proper handling of Error objects
74
+ */
75
+ serialize() {
76
+ return bigintSafeJsonStringify({
77
+ name: this.name,
78
+ code: this.code,
79
+ message: this.message,
80
+ hint: this.hint,
81
+ context: this.context,
82
+ cause: this.cause ? {
83
+ name: this.cause.name,
84
+ message: this.cause.message,
85
+ stack: this.cause.stack
86
+ } : void 0,
87
+ stack: this.stack
88
+ });
89
+ }
90
+ /**
91
+ * Returns a human-readable string representation of the error
92
+ */
93
+ toString() {
94
+ const parts = [`${this.name} [${this.code}]: ${this.message}`];
95
+ if (this.hint) {
96
+ parts.push(`Hint: ${this.hint}`);
97
+ }
98
+ if (this.context && Object.keys(this.context).length > 0) {
99
+ parts.push(`Context: ${bigintSafeJsonStringify(this.context)}`);
100
+ }
101
+ if (this.stack) {
102
+ parts.push(`
103
+ Stack trace:`);
104
+ parts.push(this.stack);
105
+ }
106
+ if (this.cause) {
107
+ parts.push(`
108
+ Caused by: ${this.cause.name}: ${this.cause.message}`);
109
+ if (this.cause.stack) {
110
+ parts.push(this.cause.stack);
111
+ }
112
+ }
113
+ return parts.join("\n");
114
+ }
115
+ };
116
+ var bigintSafeJsonStringify = (value) => {
117
+ return JSON.stringify(value, (key, value2) => {
118
+ if (typeof value2 === "bigint") {
119
+ return `${value2}n`;
120
+ }
121
+ return value2;
122
+ });
123
+ };
124
+ var isCofhesdkError = (error) => error instanceof CofhesdkError;
125
+
126
+ // core/types.ts
127
+ var FheUintUTypes = [
128
+ 2 /* Uint8 */,
129
+ 3 /* Uint16 */,
130
+ 4 /* Uint32 */,
131
+ 5 /* Uint64 */,
132
+ 6 /* Uint128 */
133
+ // [U256-DISABLED]
134
+ // FheTypes.Uint256,
135
+ ];
136
+ var toHexString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
137
+ var toBigIntOrThrow = (value) => {
138
+ if (typeof value === "bigint") {
139
+ return value;
140
+ }
141
+ try {
142
+ return BigInt(value);
143
+ } catch (error) {
144
+ throw new Error("Invalid input: Unable to convert to bigint");
145
+ }
146
+ };
147
+ var validateBigIntInRange = (value, max, min = 0n) => {
148
+ if (typeof value !== "bigint") {
149
+ throw new Error("Value must be of type bigint");
150
+ }
151
+ if (value > max || value < min) {
152
+ throw new Error(`Value out of range: ${max} - ${min}, try a different uint type`);
153
+ }
154
+ };
155
+ var hexToBytes = (hex) => {
156
+ const bytes = new Uint8Array(hex.length / 2);
157
+ for (let i = 0; i < hex.length; i += 2) {
158
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
159
+ }
160
+ return bytes;
161
+ };
162
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
163
+ async function getPublicClientChainID(publicClient) {
164
+ let chainId = null;
165
+ try {
166
+ chainId = publicClient.chain?.id ?? await publicClient.getChainId();
167
+ } catch (e) {
168
+ throw new CofhesdkError({
169
+ code: "PUBLIC_WALLET_GET_CHAIN_ID_FAILED" /* PublicWalletGetChainIdFailed */,
170
+ message: "getting chain ID from public client failed",
171
+ cause: e instanceof Error ? e : void 0
172
+ });
173
+ }
174
+ if (chainId === null) {
175
+ throw new CofhesdkError({
176
+ code: "PUBLIC_WALLET_GET_CHAIN_ID_FAILED" /* PublicWalletGetChainIdFailed */,
177
+ message: "chain ID from public client is null"
178
+ });
179
+ }
180
+ return chainId;
181
+ }
182
+ async function getWalletClientAccount(walletClient) {
183
+ let address;
184
+ try {
185
+ address = walletClient.account?.address;
186
+ if (!address) {
187
+ address = (await walletClient.getAddresses())?.[0];
188
+ }
189
+ } catch (e) {
190
+ throw new CofhesdkError({
191
+ code: "PUBLIC_WALLET_GET_ADDRESSES_FAILED" /* PublicWalletGetAddressesFailed */,
192
+ message: "getting address from wallet client failed",
193
+ cause: e instanceof Error ? e : void 0
194
+ });
195
+ }
196
+ if (!address) {
197
+ throw new CofhesdkError({
198
+ code: "PUBLIC_WALLET_GET_ADDRESSES_FAILED" /* PublicWalletGetAddressesFailed */,
199
+ message: "address from wallet client is null"
200
+ });
201
+ }
202
+ return address;
203
+ }
204
+
205
+ // core/encrypt/zkPackProveVerify.ts
206
+ var MAX_UINT8 = 255n;
207
+ var MAX_UINT16 = 65535n;
208
+ var MAX_UINT32 = 4294967295n;
209
+ var MAX_UINT64 = 18446744073709551615n;
210
+ var MAX_UINT128 = 340282366920938463463374607431768211455n;
211
+ var MAX_UINT160 = 1461501637330902918203684832716283019655932542975n;
212
+ var MAX_ENCRYPTABLE_BITS = 2048;
213
+ var zkPack = (items, builder) => {
214
+ let totalBits = 0;
215
+ for (const item of items) {
216
+ switch (item.utype) {
217
+ case 0 /* Bool */: {
218
+ builder.push_boolean(item.data);
219
+ totalBits += 1;
220
+ break;
221
+ }
222
+ case 2 /* Uint8 */: {
223
+ const bint = toBigIntOrThrow(item.data);
224
+ validateBigIntInRange(bint, MAX_UINT8);
225
+ builder.push_u8(parseInt(bint.toString()));
226
+ totalBits += 8;
227
+ break;
228
+ }
229
+ case 3 /* Uint16 */: {
230
+ const bint = toBigIntOrThrow(item.data);
231
+ validateBigIntInRange(bint, MAX_UINT16);
232
+ builder.push_u16(parseInt(bint.toString()));
233
+ totalBits += 16;
234
+ break;
235
+ }
236
+ case 4 /* Uint32 */: {
237
+ const bint = toBigIntOrThrow(item.data);
238
+ validateBigIntInRange(bint, MAX_UINT32);
239
+ builder.push_u32(parseInt(bint.toString()));
240
+ totalBits += 32;
241
+ break;
242
+ }
243
+ case 5 /* Uint64 */: {
244
+ const bint = toBigIntOrThrow(item.data);
245
+ validateBigIntInRange(bint, MAX_UINT64);
246
+ builder.push_u64(bint);
247
+ totalBits += 64;
248
+ break;
249
+ }
250
+ case 6 /* Uint128 */: {
251
+ const bint = toBigIntOrThrow(item.data);
252
+ validateBigIntInRange(bint, MAX_UINT128);
253
+ builder.push_u128(bint);
254
+ totalBits += 128;
255
+ break;
256
+ }
257
+ case 7 /* Uint160 */: {
258
+ const bint = toBigIntOrThrow(item.data);
259
+ validateBigIntInRange(bint, MAX_UINT160);
260
+ builder.push_u160(bint);
261
+ totalBits += 160;
262
+ break;
263
+ }
264
+ default: {
265
+ throw new CofhesdkError({
266
+ code: "ZK_PACK_FAILED" /* ZkPackFailed */,
267
+ message: `Invalid utype: ${item.utype}`,
268
+ hint: `Ensure that the utype is valid, using the Encryptable type, for example: Encryptable.uint128(100n)`,
269
+ context: {
270
+ item
271
+ }
272
+ });
273
+ }
274
+ }
275
+ }
276
+ if (totalBits > MAX_ENCRYPTABLE_BITS) {
277
+ throw new CofhesdkError({
278
+ code: "ZK_PACK_FAILED" /* ZkPackFailed */,
279
+ message: `Total bits ${totalBits} exceeds ${MAX_ENCRYPTABLE_BITS}`,
280
+ hint: `Ensure that the total bits of the items to encrypt does not exceed ${MAX_ENCRYPTABLE_BITS}`,
281
+ context: {
282
+ totalBits,
283
+ maxBits: MAX_ENCRYPTABLE_BITS,
284
+ items
285
+ }
286
+ });
287
+ }
288
+ return builder;
289
+ };
290
+ var zkProveWithWorker = async (workerFn, fheKeyHex, crsHex, items, metadata) => {
291
+ return await workerFn(fheKeyHex, crsHex, items, metadata);
292
+ };
293
+ var zkProve = async (builder, crs, metadata) => {
294
+ return new Promise((resolve) => {
295
+ setTimeout(() => {
296
+ const compactList = builder.build_with_proof_packed(
297
+ crs,
298
+ metadata,
299
+ 1
300
+ // ZkComputeLoad.Verify
301
+ );
302
+ resolve(compactList.serialize());
303
+ }, 0);
304
+ });
305
+ };
306
+ var constructZkPoKMetadata = (accountAddr, securityZone, chainId) => {
307
+ const accountAddrNoPrefix = accountAddr.startsWith("0x") ? accountAddr.slice(2) : accountAddr;
308
+ const accountBytes = hexToBytes(accountAddrNoPrefix);
309
+ const chainIdBytes = new Uint8Array(32);
310
+ let value = chainId;
311
+ for (let i = 31; i >= 0 && value > 0; i--) {
312
+ chainIdBytes[i] = value & 255;
313
+ value = value >>> 8;
314
+ }
315
+ const metadata = new Uint8Array(1 + accountBytes.length + 32);
316
+ metadata[0] = securityZone;
317
+ metadata.set(accountBytes, 1);
318
+ metadata.set(chainIdBytes, 1 + accountBytes.length);
319
+ return metadata;
320
+ };
321
+ var zkVerify = async (verifierUrl, serializedBytes, address, securityZone, chainId) => {
322
+ const packed_list = toHexString(serializedBytes);
323
+ const sz_byte = new Uint8Array([securityZone]);
324
+ const payload = {
325
+ packed_list,
326
+ account_addr: address,
327
+ security_zone: sz_byte[0],
328
+ chain_id: chainId
329
+ };
330
+ const body = JSON.stringify(payload);
331
+ try {
332
+ const response = await fetch(`${verifierUrl}/verify`, {
333
+ method: "POST",
334
+ headers: {
335
+ "Content-Type": "application/json"
336
+ },
337
+ body
338
+ });
339
+ if (!response.ok) {
340
+ const errorBody = await response.text();
341
+ throw new CofhesdkError({
342
+ code: "ZK_VERIFY_FAILED" /* ZkVerifyFailed */,
343
+ message: `HTTP error! ZK proof verification failed - ${errorBody}`
344
+ });
345
+ }
346
+ const json = await response.json();
347
+ if (json.status !== "success") {
348
+ throw new CofhesdkError({
349
+ code: "ZK_VERIFY_FAILED" /* ZkVerifyFailed */,
350
+ message: `ZK proof verification response malformed - ${json.error}`
351
+ });
352
+ }
353
+ return json.data.map(({ ct_hash, signature, recid }) => {
354
+ return {
355
+ ct_hash,
356
+ signature: concatSigRecid(signature, recid)
357
+ };
358
+ });
359
+ } catch (e) {
360
+ throw new CofhesdkError({
361
+ code: "ZK_VERIFY_FAILED" /* ZkVerifyFailed */,
362
+ message: `ZK proof verification failed`,
363
+ cause: e instanceof Error ? e : void 0
364
+ });
365
+ }
366
+ };
367
+ var concatSigRecid = (signature, recid) => {
368
+ return signature + (recid + 27).toString(16).padStart(2, "0");
369
+ };
370
+
371
+ // core/encrypt/MockZkVerifierAbi.ts
372
+ var MockZkVerifierAbi = [
373
+ {
374
+ type: "function",
375
+ name: "exists",
376
+ inputs: [],
377
+ outputs: [{ name: "", type: "bool", internalType: "bool" }],
378
+ stateMutability: "pure"
379
+ },
380
+ {
381
+ type: "function",
382
+ name: "insertCtHash",
383
+ inputs: [
384
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
385
+ { name: "value", type: "uint256", internalType: "uint256" }
386
+ ],
387
+ outputs: [],
388
+ stateMutability: "nonpayable"
389
+ },
390
+ {
391
+ type: "function",
392
+ name: "insertPackedCtHashes",
393
+ inputs: [
394
+ { name: "ctHashes", type: "uint256[]", internalType: "uint256[]" },
395
+ { name: "values", type: "uint256[]", internalType: "uint256[]" }
396
+ ],
397
+ outputs: [],
398
+ stateMutability: "nonpayable"
399
+ },
400
+ {
401
+ type: "function",
402
+ name: "zkVerify",
403
+ inputs: [
404
+ { name: "value", type: "uint256", internalType: "uint256" },
405
+ { name: "utype", type: "uint8", internalType: "uint8" },
406
+ { name: "user", type: "address", internalType: "address" },
407
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
408
+ { name: "", type: "uint256", internalType: "uint256" }
409
+ ],
410
+ outputs: [
411
+ {
412
+ name: "",
413
+ type: "tuple",
414
+ internalType: "struct EncryptedInput",
415
+ components: [
416
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
417
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
418
+ { name: "utype", type: "uint8", internalType: "uint8" },
419
+ { name: "signature", type: "bytes", internalType: "bytes" }
420
+ ]
421
+ }
422
+ ],
423
+ stateMutability: "nonpayable"
424
+ },
425
+ {
426
+ type: "function",
427
+ name: "zkVerifyCalcCtHash",
428
+ inputs: [
429
+ { name: "value", type: "uint256", internalType: "uint256" },
430
+ { name: "utype", type: "uint8", internalType: "uint8" },
431
+ { name: "user", type: "address", internalType: "address" },
432
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
433
+ { name: "", type: "uint256", internalType: "uint256" }
434
+ ],
435
+ outputs: [{ name: "ctHash", type: "uint256", internalType: "uint256" }],
436
+ stateMutability: "view"
437
+ },
438
+ {
439
+ type: "function",
440
+ name: "zkVerifyCalcCtHashesPacked",
441
+ inputs: [
442
+ { name: "values", type: "uint256[]", internalType: "uint256[]" },
443
+ { name: "utypes", type: "uint8[]", internalType: "uint8[]" },
444
+ { name: "user", type: "address", internalType: "address" },
445
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
446
+ { name: "chainId", type: "uint256", internalType: "uint256" }
447
+ ],
448
+ outputs: [{ name: "ctHashes", type: "uint256[]", internalType: "uint256[]" }],
449
+ stateMutability: "view"
450
+ },
451
+ {
452
+ type: "function",
453
+ name: "zkVerifyPacked",
454
+ inputs: [
455
+ { name: "values", type: "uint256[]", internalType: "uint256[]" },
456
+ { name: "utypes", type: "uint8[]", internalType: "uint8[]" },
457
+ { name: "user", type: "address", internalType: "address" },
458
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
459
+ { name: "chainId", type: "uint256", internalType: "uint256" }
460
+ ],
461
+ outputs: [
462
+ {
463
+ name: "inputs",
464
+ type: "tuple[]",
465
+ internalType: "struct EncryptedInput[]",
466
+ components: [
467
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
468
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
469
+ { name: "utype", type: "uint8", internalType: "uint8" },
470
+ { name: "signature", type: "bytes", internalType: "bytes" }
471
+ ]
472
+ }
473
+ ],
474
+ stateMutability: "nonpayable"
475
+ },
476
+ { type: "error", name: "InvalidInputs", inputs: [] }
477
+ ];
478
+ var MocksZkVerifierAddress = "0x0000000000000000000000000000000000000100";
479
+ var MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY = "0x6C8D7F768A6BB4AAFE85E8A2F5A9680355239C7E14646ED62B044E39DE154512";
480
+ function createMockZkVerifierSigner() {
481
+ return viem.createWalletClient({
482
+ chain: chains.hardhat,
483
+ transport: viem.http(),
484
+ account: accounts.privateKeyToAccount(MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY)
485
+ });
486
+ }
487
+ async function cofheMocksCheckEncryptableBits(items) {
488
+ let totalBits = 0;
489
+ for (const item of items) {
490
+ switch (item.utype) {
491
+ case 0 /* Bool */: {
492
+ totalBits += 1;
493
+ break;
494
+ }
495
+ case 2 /* Uint8 */: {
496
+ totalBits += 8;
497
+ break;
498
+ }
499
+ case 3 /* Uint16 */: {
500
+ totalBits += 16;
501
+ break;
502
+ }
503
+ case 4 /* Uint32 */: {
504
+ totalBits += 32;
505
+ break;
506
+ }
507
+ case 5 /* Uint64 */: {
508
+ totalBits += 64;
509
+ break;
510
+ }
511
+ case 6 /* Uint128 */: {
512
+ totalBits += 128;
513
+ break;
514
+ }
515
+ case 7 /* Uint160 */: {
516
+ totalBits += 160;
517
+ break;
518
+ }
519
+ }
520
+ }
521
+ if (totalBits > MAX_ENCRYPTABLE_BITS) {
522
+ throw new CofhesdkError({
523
+ code: "ZK_PACK_FAILED" /* ZkPackFailed */,
524
+ message: `Total bits ${totalBits} exceeds ${MAX_ENCRYPTABLE_BITS}`,
525
+ hint: `Ensure that the total bits of the items to encrypt does not exceed ${MAX_ENCRYPTABLE_BITS}`,
526
+ context: {
527
+ totalBits,
528
+ maxBits: MAX_ENCRYPTABLE_BITS,
529
+ items
530
+ }
531
+ });
532
+ }
533
+ }
534
+ async function calcCtHashes(items, account, securityZone, publicClient) {
535
+ const calcCtHashesArgs = [
536
+ items.map(({ data }) => BigInt(data)),
537
+ items.map(({ utype }) => utype),
538
+ account,
539
+ securityZone,
540
+ BigInt(chains.hardhat.id)
541
+ ];
542
+ let ctHashes;
543
+ try {
544
+ ctHashes = await publicClient.readContract({
545
+ address: MocksZkVerifierAddress,
546
+ abi: MockZkVerifierAbi,
547
+ functionName: "zkVerifyCalcCtHashesPacked",
548
+ args: calcCtHashesArgs
549
+ });
550
+ } catch (err) {
551
+ throw new CofhesdkError({
552
+ code: "ZK_MOCKS_CALC_CT_HASHES_FAILED" /* ZkMocksCalcCtHashesFailed */,
553
+ message: `mockZkVerifySign calcCtHashes failed while calling zkVerifyCalcCtHashesPacked`,
554
+ cause: err instanceof Error ? err : void 0,
555
+ context: {
556
+ address: MocksZkVerifierAddress,
557
+ items,
558
+ account,
559
+ securityZone,
560
+ publicClient,
561
+ calcCtHashesArgs
562
+ }
563
+ });
564
+ }
565
+ if (ctHashes.length !== items.length) {
566
+ throw new CofhesdkError({
567
+ code: "ZK_MOCKS_CALC_CT_HASHES_FAILED" /* ZkMocksCalcCtHashesFailed */,
568
+ message: `mockZkVerifySign calcCtHashes returned incorrect number of ctHashes`,
569
+ context: {
570
+ items,
571
+ account,
572
+ securityZone,
573
+ publicClient,
574
+ calcCtHashesArgs,
575
+ ctHashes
576
+ }
577
+ });
578
+ }
579
+ return items.map((item, index) => ({
580
+ ...item,
581
+ ctHash: ctHashes[index]
582
+ }));
583
+ }
584
+ async function insertCtHashes(items, walletClient) {
585
+ const insertPackedCtHashesArgs = [items.map(({ ctHash }) => ctHash), items.map(({ data }) => BigInt(data))];
586
+ try {
587
+ const account = walletClient.account;
588
+ await walletClient.writeContract({
589
+ address: MocksZkVerifierAddress,
590
+ abi: MockZkVerifierAbi,
591
+ functionName: "insertPackedCtHashes",
592
+ args: insertPackedCtHashesArgs,
593
+ chain: chains.hardhat,
594
+ account
595
+ });
596
+ } catch (err) {
597
+ throw new CofhesdkError({
598
+ code: "ZK_MOCKS_INSERT_CT_HASHES_FAILED" /* ZkMocksInsertCtHashesFailed */,
599
+ message: `mockZkVerifySign insertPackedCtHashes failed while calling insertPackedCtHashes`,
600
+ cause: err instanceof Error ? err : void 0,
601
+ context: {
602
+ items,
603
+ walletClient,
604
+ insertPackedCtHashesArgs
605
+ }
606
+ });
607
+ }
608
+ }
609
+ async function createProofSignatures(items, securityZone) {
610
+ let signatures = [];
611
+ let encInputSignerClient;
612
+ try {
613
+ encInputSignerClient = createMockZkVerifierSigner();
614
+ } catch (err) {
615
+ throw new CofhesdkError({
616
+ code: "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED" /* ZkMocksCreateProofSignatureFailed */,
617
+ message: `mockZkVerifySign createProofSignatures failed while creating wallet client`,
618
+ cause: err instanceof Error ? err : void 0,
619
+ context: {
620
+ MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY
621
+ }
622
+ });
623
+ }
624
+ try {
625
+ for (const item of items) {
626
+ const packedData = viem.encodePacked(["uint256", "int32", "uint8"], [BigInt(item.data), securityZone, item.utype]);
627
+ const messageHash = viem.keccak256(packedData);
628
+ const ethSignedHash = viem.hashMessage({ raw: viem.toBytes(messageHash) });
629
+ const signature = await encInputSignerClient.signMessage({
630
+ message: { raw: viem.toBytes(ethSignedHash) },
631
+ account: encInputSignerClient.account
632
+ });
633
+ signatures.push(signature);
634
+ }
635
+ } catch (err) {
636
+ throw new CofhesdkError({
637
+ code: "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED" /* ZkMocksCreateProofSignatureFailed */,
638
+ message: `mockZkVerifySign createProofSignatures failed while calling signMessage`,
639
+ cause: err instanceof Error ? err : void 0,
640
+ context: {
641
+ items,
642
+ securityZone
643
+ }
644
+ });
645
+ }
646
+ if (signatures.length !== items.length) {
647
+ throw new CofhesdkError({
648
+ code: "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED" /* ZkMocksCreateProofSignatureFailed */,
649
+ message: `mockZkVerifySign createProofSignatures returned incorrect number of signatures`,
650
+ context: {
651
+ items,
652
+ securityZone
653
+ }
654
+ });
655
+ }
656
+ return signatures;
657
+ }
658
+ async function cofheMocksZkVerifySign(items, account, securityZone, publicClient, walletClient, zkvWalletClient) {
659
+ const _walletClient = zkvWalletClient ?? createMockZkVerifierSigner();
660
+ const encryptableItems = await calcCtHashes(items, account, securityZone, publicClient);
661
+ await insertCtHashes(encryptableItems, _walletClient);
662
+ const signatures = await createProofSignatures(encryptableItems, securityZone);
663
+ return encryptableItems.map((item, index) => ({
664
+ ct_hash: item.ctHash.toString(),
665
+ signature: signatures[index]
666
+ }));
667
+ }
668
+ var EnvironmentSchema = zod.z.enum(["MOCK", "TESTNET", "MAINNET"]);
669
+ var CofheChainSchema = zod.z.object({
670
+ /** Chain ID */
671
+ id: zod.z.number().int().positive(),
672
+ /** Human-readable chain name */
673
+ name: zod.z.string().min(1),
674
+ /** Network identifier */
675
+ network: zod.z.string().min(1),
676
+ /** coFhe service URL */
677
+ coFheUrl: zod.z.string().url(),
678
+ /** Verifier service URL */
679
+ verifierUrl: zod.z.string().url(),
680
+ /** Threshold network service URL */
681
+ thresholdNetworkUrl: zod.z.string().url(),
682
+ /** Environment type */
683
+ environment: EnvironmentSchema
684
+ });
685
+
686
+ // chains/defineChain.ts
687
+ function defineChain(chainConfig) {
688
+ const result = CofheChainSchema.safeParse(chainConfig);
689
+ if (!result.success) {
690
+ const errorMessages = result.error.errors.map((err) => `${err.path.join(".")}: ${err.message}`);
691
+ throw new Error(`Invalid chain configuration: ${errorMessages.join(", ")}`);
692
+ }
693
+ return result.data;
694
+ }
695
+
696
+ // chains/chains/hardhat.ts
697
+ var hardhat2 = defineChain({
698
+ id: 31337,
699
+ name: "Hardhat",
700
+ network: "localhost",
701
+ // These are unused in the mock environment
702
+ coFheUrl: "http://127.0.0.1:8448",
703
+ verifierUrl: "http://127.0.0.1:3001",
704
+ thresholdNetworkUrl: "http://127.0.0.1:3000",
705
+ environment: "MOCK"
706
+ });
707
+ var CofhesdkConfigSchema = zod.z.object({
708
+ /** Environment that the SDK is running in */
709
+ environment: zod.z.enum(["node", "hardhat", "web", "react"]).optional().default("node"),
710
+ /** List of supported chain configurations */
711
+ supportedChains: zod.z.array(zod.z.custom()),
712
+ /** How permits are generated */
713
+ permitGeneration: zod.z.enum(["ON_CONNECT", "ON_DECRYPT_HANDLES", "MANUAL"]).optional().default("ON_CONNECT"),
714
+ /** Default permit expiration in seconds, default is 30 days */
715
+ defaultPermitExpiration: zod.z.number().optional().default(60 * 60 * 24 * 30),
716
+ /** Storage method for fhe keys (defaults to indexedDB on web, filesystem on node) */
717
+ fheKeyStorage: zod.z.object({
718
+ getItem: zod.z.function().args(zod.z.string()).returns(zod.z.promise(zod.z.any())),
719
+ setItem: zod.z.function().args(zod.z.string(), zod.z.any()).returns(zod.z.promise(zod.z.void())),
720
+ removeItem: zod.z.function().args(zod.z.string()).returns(zod.z.promise(zod.z.void()))
721
+ }).or(zod.z.null()).default(null),
722
+ /** Whether to use Web Workers for ZK proof generation (web platform only) */
723
+ useWorkers: zod.z.boolean().optional().default(true),
724
+ /** Mocks configs */
725
+ mocks: zod.z.object({
726
+ sealOutputDelay: zod.z.number().optional().default(0)
727
+ }).optional().default({ sealOutputDelay: 0 }),
728
+ /** Internal configuration */
729
+ _internal: zod.z.object({
730
+ zkvWalletClient: zod.z.any().optional()
731
+ }).optional()
732
+ });
733
+ function createCofhesdkConfigBase(config) {
734
+ const result = CofhesdkConfigSchema.safeParse(config);
735
+ if (!result.success) {
736
+ throw new Error(`Invalid cofhesdk configuration: ${result.error.message}`);
737
+ }
738
+ return result.data;
739
+ }
740
+ function getSupportedChainOrThrow(config, chainId) {
741
+ const supportedChain = config.supportedChains.find((chain) => chain.id === chainId);
742
+ if (!supportedChain) {
743
+ throw new CofhesdkError({
744
+ code: "UNSUPPORTED_CHAIN" /* UnsupportedChain */,
745
+ message: `Config does not support chain <${chainId}>`,
746
+ hint: "Ensure config passed to client has been created with this chain in the config.supportedChains array.",
747
+ context: {
748
+ chainId,
749
+ supportedChainIds: config.supportedChains.map((c) => c.id)
750
+ }
751
+ });
752
+ }
753
+ return supportedChain;
754
+ }
755
+ function getCoFheUrlOrThrow(config, chainId) {
756
+ const supportedChain = getSupportedChainOrThrow(config, chainId);
757
+ const url = supportedChain.coFheUrl;
758
+ if (!url) {
759
+ throw new CofhesdkError({
760
+ code: "MISSING_CONFIG" /* MissingConfig */,
761
+ message: `CoFHE URL is not configured for chain <${chainId}>`,
762
+ hint: "Ensure this chain config includes a coFheUrl property.",
763
+ context: { chainId }
764
+ });
765
+ }
766
+ return url;
767
+ }
768
+ function getZkVerifierUrlOrThrow(config, chainId) {
769
+ const supportedChain = getSupportedChainOrThrow(config, chainId);
770
+ const url = supportedChain.verifierUrl;
771
+ if (!url) {
772
+ throw new CofhesdkError({
773
+ code: "ZK_VERIFIER_URL_UNINITIALIZED" /* ZkVerifierUrlUninitialized */,
774
+ message: `ZK verifier URL is not configured for chain <${chainId}>`,
775
+ hint: "Ensure this chain config includes a verifierUrl property.",
776
+ context: { chainId }
777
+ });
778
+ }
779
+ return url;
780
+ }
781
+ function getThresholdNetworkUrlOrThrow(config, chainId) {
782
+ const supportedChain = getSupportedChainOrThrow(config, chainId);
783
+ const url = supportedChain.thresholdNetworkUrl;
784
+ if (!url) {
785
+ throw new CofhesdkError({
786
+ code: "THRESHOLD_NETWORK_URL_UNINITIALIZED" /* ThresholdNetworkUrlUninitialized */,
787
+ message: `Threshold network URL is not configured for chain <${chainId}>`,
788
+ hint: "Ensure this chain config includes a thresholdNetworkUrl property.",
789
+ context: { chainId }
790
+ });
791
+ }
792
+ return url;
793
+ }
794
+ function isValidPersistedState(state) {
795
+ if (state && typeof state === "object") {
796
+ if ("fhe" in state && "crs" in state) {
797
+ return true;
798
+ } else {
799
+ throw new Error(
800
+ "Invalid persisted state structure for KeysStore. Is object but doesn't contain required fields 'fhe' and 'crs'."
801
+ );
802
+ }
803
+ }
804
+ return false;
805
+ }
806
+ var DEFAULT_KEYS_STORE = {
807
+ fhe: {},
808
+ crs: {}
809
+ };
810
+ function isStoreWithPersist(store) {
811
+ return "persist" in store;
812
+ }
813
+ function createKeysStore(storage) {
814
+ const keysStore = storage ? createStoreWithPersit(storage) : vanilla.createStore()(() => ({
815
+ fhe: {},
816
+ crs: {}
817
+ }));
818
+ const getFheKey = (chainId, securityZone = 0) => {
819
+ if (chainId == null || securityZone == null)
820
+ return void 0;
821
+ const stored = keysStore.getState().fhe[chainId]?.[securityZone];
822
+ return stored;
823
+ };
824
+ const getCrs = (chainId) => {
825
+ if (chainId == null)
826
+ return void 0;
827
+ const stored = keysStore.getState().crs[chainId];
828
+ return stored;
829
+ };
830
+ const setFheKey = (chainId, securityZone, key) => {
831
+ keysStore.setState(
832
+ immer.produce((state) => {
833
+ if (state.fhe[chainId] == null)
834
+ state.fhe[chainId] = {};
835
+ state.fhe[chainId][securityZone] = key;
836
+ })
837
+ );
838
+ };
839
+ const setCrs = (chainId, crs) => {
840
+ keysStore.setState(
841
+ immer.produce((state) => {
842
+ state.crs[chainId] = crs;
843
+ })
844
+ );
845
+ };
846
+ const clearKeysStorage = async () => {
847
+ if (storage) {
848
+ await storage.removeItem("cofhesdk-keys");
849
+ }
850
+ };
851
+ const rehydrateKeysStore = async () => {
852
+ if (!isStoreWithPersist(keysStore))
853
+ return;
854
+ if (keysStore.persist.hasHydrated())
855
+ return;
856
+ await keysStore.persist.rehydrate();
857
+ };
858
+ return {
859
+ store: keysStore,
860
+ getFheKey,
861
+ getCrs,
862
+ setFheKey,
863
+ setCrs,
864
+ clearKeysStorage,
865
+ rehydrateKeysStore
866
+ };
867
+ }
868
+ function createStoreWithPersit(storage) {
869
+ const result = vanilla.createStore()(
870
+ middleware.persist(() => DEFAULT_KEYS_STORE, {
871
+ // because earleir tests were written with on-init hydration skipped (due to the error suppression in zustand), returning this flag to fix test (i.e. KeyStore > Storage Utilities > should rehydrate keys store)
872
+ skipHydration: true,
873
+ // if onRehydrateStorage is not passed here, the errors thrown by storage layer are swallowed by zustand here: https://github.com/pmndrs/zustand/blob/39a391b6c1ff9aa89b81694d9bdb21da37dd4ac6/src/middleware/persist.ts#L321
874
+ onRehydrateStorage: () => (_state, _error) => {
875
+ if (_error)
876
+ throw new Error(`onRehydrateStorage: Error rehydrating keys store: ${_error}`);
877
+ },
878
+ name: "cofhesdk-keys",
879
+ storage: middleware.createJSONStorage(() => storage),
880
+ merge: (persistedState, currentState) => {
881
+ const persisted = isValidPersistedState(persistedState) ? persistedState : DEFAULT_KEYS_STORE;
882
+ const current = currentState;
883
+ const mergedFhe = { ...persisted.fhe };
884
+ const allChainIds = /* @__PURE__ */ new Set([...Object.keys(current.fhe), ...Object.keys(persisted.fhe)]);
885
+ for (const chainId of allChainIds) {
886
+ const persistedZones = persisted.fhe[chainId] || {};
887
+ const currentZones = current.fhe[chainId] || {};
888
+ mergedFhe[chainId] = { ...persistedZones, ...currentZones };
889
+ }
890
+ const mergedCrs = { ...persisted.crs, ...current.crs };
891
+ return {
892
+ fhe: mergedFhe,
893
+ crs: mergedCrs
894
+ };
895
+ }
896
+ })
897
+ );
898
+ return result;
899
+ }
900
+
901
+ // core/fetchKeys.ts
902
+ var PUBLIC_KEY_LENGTH_MIN = 15e3;
903
+ var checkKeyValidity = (key, serializer) => {
904
+ if (key == null || key.length === 0)
905
+ return [false, `Key is null or empty <${key}>`];
906
+ try {
907
+ serializer(key);
908
+ return [true, `Key is valid`];
909
+ } catch (err) {
910
+ return [false, `Serialization failed <${err}> key length <${key.length}>`];
911
+ }
912
+ };
913
+ var fetchFhePublicKey = async (coFheUrl, chainId, securityZone, tfhePublicKeyDeserializer2, keysStorage) => {
914
+ const storedKey = keysStorage?.getFheKey(chainId, securityZone);
915
+ const [storedKeyValid] = checkKeyValidity(storedKey, tfhePublicKeyDeserializer2);
916
+ if (storedKeyValid)
917
+ return [storedKey, false];
918
+ let pk_data = void 0;
919
+ try {
920
+ const pk_res = await fetch(`${coFheUrl}/GetNetworkPublicKey`, {
921
+ method: "POST",
922
+ headers: {
923
+ "Content-Type": "application/json"
924
+ },
925
+ body: JSON.stringify({ securityZone })
926
+ });
927
+ const json = await pk_res.json();
928
+ pk_data = json.publicKey;
929
+ } catch (err) {
930
+ throw new Error(`Error fetching FHE publicKey; fetching from CoFHE failed with error ${err}`);
931
+ }
932
+ if (pk_data == null || typeof pk_data !== "string") {
933
+ throw new Error(`Error fetching FHE publicKey; fetched result invalid: missing or not a string`);
934
+ }
935
+ if (pk_data === "0x") {
936
+ throw new Error("Error fetching FHE publicKey; provided chain is not FHE enabled / not found");
937
+ }
938
+ if (pk_data.length < PUBLIC_KEY_LENGTH_MIN) {
939
+ throw new Error(
940
+ `Error fetching FHE publicKey; got shorter than expected key length: ${pk_data.length}. Expected length >= ${PUBLIC_KEY_LENGTH_MIN}`
941
+ );
942
+ }
943
+ try {
944
+ tfhePublicKeyDeserializer2(pk_data);
945
+ } catch (err) {
946
+ throw new Error(`Error serializing FHE publicKey; ${err}`);
947
+ }
948
+ keysStorage?.setFheKey(chainId, securityZone, pk_data);
949
+ return [pk_data, true];
950
+ };
951
+ var fetchCrs = async (coFheUrl, chainId, securityZone, compactPkeCrsDeserializer2, keysStorage) => {
952
+ const storedKey = keysStorage?.getCrs(chainId);
953
+ const [storedKeyValid] = checkKeyValidity(storedKey, compactPkeCrsDeserializer2);
954
+ if (storedKeyValid)
955
+ return [storedKey, false];
956
+ let crs_data = void 0;
957
+ try {
958
+ const crs_res = await fetch(`${coFheUrl}/GetCrs`, {
959
+ method: "POST",
960
+ headers: {
961
+ "Content-Type": "application/json"
962
+ },
963
+ body: JSON.stringify({ securityZone })
964
+ });
965
+ const json = await crs_res.json();
966
+ crs_data = json.crs;
967
+ } catch (err) {
968
+ throw new Error(`Error fetching CRS; fetching failed with error ${err}`);
969
+ }
970
+ if (crs_data == null || typeof crs_data !== "string") {
971
+ throw new Error(`Error fetching CRS; invalid: missing or not a string`);
972
+ }
973
+ try {
974
+ compactPkeCrsDeserializer2(crs_data);
975
+ } catch (err) {
976
+ console.error(`Error serializing CRS ${err}`);
977
+ throw new Error(`Error serializing CRS; ${err}`);
978
+ }
979
+ keysStorage?.setCrs(chainId, crs_data);
980
+ return [crs_data, true];
981
+ };
982
+ var fetchKeys = async (config, chainId, securityZone = 0, tfhePublicKeyDeserializer2, compactPkeCrsDeserializer2, keysStorage) => {
983
+ const coFheUrl = getCoFheUrlOrThrow(config, chainId);
984
+ return await Promise.all([
985
+ fetchFhePublicKey(coFheUrl, chainId, securityZone, tfhePublicKeyDeserializer2, keysStorage),
986
+ fetchCrs(coFheUrl, chainId, securityZone, compactPkeCrsDeserializer2, keysStorage)
987
+ ]);
988
+ };
989
+ var BaseBuilder = class {
990
+ config;
991
+ publicClient;
992
+ walletClient;
993
+ chainId;
994
+ account;
995
+ constructor(params) {
996
+ if (!params.config) {
997
+ throw new CofhesdkError({
998
+ code: "MISSING_CONFIG" /* MissingConfig */,
999
+ message: "Builder config is undefined",
1000
+ hint: "Ensure client has been created with a config.",
1001
+ context: {
1002
+ config: params.config
1003
+ }
1004
+ });
1005
+ }
1006
+ this.config = params.config;
1007
+ this.publicClient = params.publicClient;
1008
+ this.walletClient = params.walletClient;
1009
+ this.chainId = params.chainId;
1010
+ this.account = params.account;
1011
+ params.requireConnected?.();
1012
+ }
1013
+ /**
1014
+ * Asserts that this.chainId is populated
1015
+ * @throws {CofhesdkError} If chainId is not set
1016
+ */
1017
+ assertChainId() {
1018
+ if (this.chainId)
1019
+ return;
1020
+ throw new CofhesdkError({
1021
+ code: "CHAIN_ID_UNINITIALIZED" /* ChainIdUninitialized */,
1022
+ message: "Chain ID is not set",
1023
+ hint: "Ensure client.connect() has been called and awaited, or use setChainId(...) to set the chainId explicitly.",
1024
+ context: {
1025
+ chainId: this.chainId
1026
+ }
1027
+ });
1028
+ }
1029
+ /**
1030
+ * Asserts that this.account is populated
1031
+ * @throws {CofhesdkError} If account is not set
1032
+ */
1033
+ assertAccount() {
1034
+ if (this.account)
1035
+ return;
1036
+ throw new CofhesdkError({
1037
+ code: "ACCOUNT_UNINITIALIZED" /* AccountUninitialized */,
1038
+ message: "Account is not set",
1039
+ hint: "Ensure client.connect() has been called and awaited, or use setAccount(...) to set the account explicitly.",
1040
+ context: {
1041
+ account: this.account
1042
+ }
1043
+ });
1044
+ }
1045
+ /**
1046
+ * Asserts that this.publicClient is populated
1047
+ * @throws {CofhesdkError} If publicClient is not set
1048
+ */
1049
+ assertPublicClient() {
1050
+ if (this.publicClient)
1051
+ return;
1052
+ throw new CofhesdkError({
1053
+ code: "MISSING_PUBLIC_CLIENT" /* MissingPublicClient */,
1054
+ message: "Public client not found",
1055
+ hint: "Ensure client.connect() has been called with a publicClient.",
1056
+ context: {
1057
+ publicClient: this.publicClient
1058
+ }
1059
+ });
1060
+ }
1061
+ /**
1062
+ * Asserts that this.walletClient is populated
1063
+ * @throws {CofhesdkError} If walletClient is not set
1064
+ */
1065
+ assertWalletClient() {
1066
+ if (this.walletClient)
1067
+ return;
1068
+ throw new CofhesdkError({
1069
+ code: "MISSING_WALLET_CLIENT" /* MissingWalletClient */,
1070
+ message: "Wallet client not found",
1071
+ hint: "Ensure client.connect() has been called with a walletClient.",
1072
+ context: {
1073
+ walletClient: this.walletClient
1074
+ }
1075
+ });
1076
+ }
1077
+ };
1078
+
1079
+ // core/encrypt/encryptInputsBuilder.ts
1080
+ var EncryptInputsBuilder = class extends BaseBuilder {
1081
+ securityZone;
1082
+ stepCallback;
1083
+ inputItems;
1084
+ zkvWalletClient;
1085
+ tfhePublicKeyDeserializer;
1086
+ compactPkeCrsDeserializer;
1087
+ zkBuilderAndCrsGenerator;
1088
+ initTfhe;
1089
+ zkProveWorkerFn;
1090
+ keysStorage;
1091
+ // Worker configuration (from config, overrideable)
1092
+ useWorker;
1093
+ stepTimestamps = {
1094
+ ["initTfhe" /* InitTfhe */]: 0,
1095
+ ["fetchKeys" /* FetchKeys */]: 0,
1096
+ ["pack" /* Pack */]: 0,
1097
+ ["prove" /* Prove */]: 0,
1098
+ ["verify" /* Verify */]: 0
1099
+ };
1100
+ constructor(params) {
1101
+ super({
1102
+ config: params.config,
1103
+ publicClient: params.publicClient,
1104
+ walletClient: params.walletClient,
1105
+ chainId: params.chainId,
1106
+ account: params.account,
1107
+ requireConnected: params.requireConnected
1108
+ });
1109
+ this.inputItems = params.inputs;
1110
+ this.securityZone = params.securityZone ?? 0;
1111
+ this.zkvWalletClient = params.zkvWalletClient;
1112
+ if (!params.tfhePublicKeyDeserializer) {
1113
+ throw new CofhesdkError({
1114
+ code: "MISSING_TFHE_PUBLIC_KEY_DESERIALIZER" /* MissingTfhePublicKeyDeserializer */,
1115
+ message: "EncryptInputsBuilder tfhePublicKeyDeserializer is undefined",
1116
+ hint: "Ensure client has been created with a tfhePublicKeyDeserializer.",
1117
+ context: {
1118
+ tfhePublicKeyDeserializer: params.tfhePublicKeyDeserializer
1119
+ }
1120
+ });
1121
+ }
1122
+ this.tfhePublicKeyDeserializer = params.tfhePublicKeyDeserializer;
1123
+ if (!params.compactPkeCrsDeserializer) {
1124
+ throw new CofhesdkError({
1125
+ code: "MISSING_COMPACT_PKE_CRS_DESERIALIZER" /* MissingCompactPkeCrsDeserializer */,
1126
+ message: "EncryptInputsBuilder compactPkeCrsDeserializer is undefined",
1127
+ hint: "Ensure client has been created with a compactPkeCrsDeserializer.",
1128
+ context: {
1129
+ compactPkeCrsDeserializer: params.compactPkeCrsDeserializer
1130
+ }
1131
+ });
1132
+ }
1133
+ this.compactPkeCrsDeserializer = params.compactPkeCrsDeserializer;
1134
+ if (!params.zkBuilderAndCrsGenerator) {
1135
+ throw new CofhesdkError({
1136
+ code: "MISSING_ZK_BUILDER_AND_CRS_GENERATOR" /* MissingZkBuilderAndCrsGenerator */,
1137
+ message: "EncryptInputsBuilder zkBuilderAndCrsGenerator is undefined",
1138
+ hint: "Ensure client has been created with a zkBuilderAndCrsGenerator.",
1139
+ context: {
1140
+ zkBuilderAndCrsGenerator: params.zkBuilderAndCrsGenerator
1141
+ }
1142
+ });
1143
+ }
1144
+ this.zkBuilderAndCrsGenerator = params.zkBuilderAndCrsGenerator;
1145
+ this.initTfhe = params.initTfhe;
1146
+ this.zkProveWorkerFn = params.zkProveWorkerFn;
1147
+ this.keysStorage = params.keysStorage;
1148
+ this.useWorker = params.config?.useWorkers ?? true;
1149
+ }
1150
+ /**
1151
+ * @param account - Account that will create the tx using the encrypted inputs.
1152
+ *
1153
+ * If not provided, the account will be fetched from the connected walletClient.
1154
+ *
1155
+ * Example:
1156
+ * ```typescript
1157
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1158
+ * .setAccount("0x123")
1159
+ * .encrypt();
1160
+ * ```
1161
+ *
1162
+ * @returns The chainable EncryptInputsBuilder instance.
1163
+ */
1164
+ setAccount(account) {
1165
+ this.account = account;
1166
+ return this;
1167
+ }
1168
+ getAccount() {
1169
+ return this.account;
1170
+ }
1171
+ /**
1172
+ * @param chainId - Chain that will consume the encrypted inputs.
1173
+ *
1174
+ * If not provided, the chainId will be fetched from the connected publicClient.
1175
+ *
1176
+ * Example:
1177
+ * ```typescript
1178
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1179
+ * .setChainId(11155111)
1180
+ * .encrypt();
1181
+ * ```
1182
+ *
1183
+ * @returns The chainable EncryptInputsBuilder instance.
1184
+ */
1185
+ setChainId(chainId) {
1186
+ this.chainId = chainId;
1187
+ return this;
1188
+ }
1189
+ getChainId() {
1190
+ return this.chainId;
1191
+ }
1192
+ /**
1193
+ * @param securityZone - Security zone to encrypt the inputs for.
1194
+ *
1195
+ * If not provided, the default securityZone 0 will be used.
1196
+ *
1197
+ * Example:
1198
+ * ```typescript
1199
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1200
+ * .setSecurityZone(1)
1201
+ * .encrypt();
1202
+ * ```
1203
+ *
1204
+ * @returns The chainable EncryptInputsBuilder instance.
1205
+ */
1206
+ setSecurityZone(securityZone) {
1207
+ this.securityZone = securityZone;
1208
+ return this;
1209
+ }
1210
+ getSecurityZone() {
1211
+ return this.securityZone;
1212
+ }
1213
+ /**
1214
+ * @param useWorker - Whether to use Web Workers for ZK proof generation.
1215
+ *
1216
+ * Overrides the config-level useWorkers setting for this specific encryption.
1217
+ *
1218
+ * Example:
1219
+ * ```typescript
1220
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1221
+ * .setUseWorker(false)
1222
+ * .encrypt();
1223
+ * ```
1224
+ *
1225
+ * @returns The chainable EncryptInputsBuilder instance.
1226
+ */
1227
+ setUseWorker(useWorker) {
1228
+ this.useWorker = useWorker;
1229
+ return this;
1230
+ }
1231
+ /**
1232
+ * Gets the current worker configuration.
1233
+ *
1234
+ * @returns Whether Web Workers are enabled for this encryption.
1235
+ *
1236
+ * Example:
1237
+ * ```typescript
1238
+ * const builder = encryptInputs([Encryptable.uint128(10n)]);
1239
+ * console.log(builder.getUseWorker()); // true (from config)
1240
+ * builder.setUseWorker(false);
1241
+ * console.log(builder.getUseWorker()); // false (overridden)
1242
+ * ```
1243
+ */
1244
+ getUseWorker() {
1245
+ return this.useWorker;
1246
+ }
1247
+ /**
1248
+ * @param callback - Function to be called with the encryption step.
1249
+ *
1250
+ * Useful for debugging and tracking the progress of the encryption process.
1251
+ * Useful for a UI element that shows the progress of the encryption process.
1252
+ *
1253
+ * Example:
1254
+ * ```typescript
1255
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1256
+ * .setStepCallback((step: EncryptStep) => console.log(step))
1257
+ * .encrypt();
1258
+ * ```
1259
+ *
1260
+ * @returns The EncryptInputsBuilder instance.
1261
+ */
1262
+ setStepCallback(callback) {
1263
+ this.stepCallback = callback;
1264
+ return this;
1265
+ }
1266
+ getStepCallback() {
1267
+ return this.stepCallback;
1268
+ }
1269
+ /**
1270
+ * Fires the step callback if set
1271
+ */
1272
+ fireStepStart(step, context = {}) {
1273
+ if (!this.stepCallback)
1274
+ return;
1275
+ this.stepTimestamps[step] = Date.now();
1276
+ this.stepCallback(step, { ...context, isStart: true, isEnd: false, duration: 0 });
1277
+ }
1278
+ fireStepEnd(step, context = {}) {
1279
+ if (!this.stepCallback)
1280
+ return;
1281
+ const duration = Date.now() - this.stepTimestamps[step];
1282
+ this.stepCallback(step, { ...context, isStart: false, isEnd: true, duration });
1283
+ }
1284
+ /**
1285
+ * zkVerifierUrl is included in the chains exported from cofhesdk/chains for use in CofhesdkConfig.supportedChains
1286
+ * Users should generally not set this manually.
1287
+ */
1288
+ async getZkVerifierUrl() {
1289
+ this.assertChainId();
1290
+ return getZkVerifierUrlOrThrow(this.config, this.chainId);
1291
+ }
1292
+ /**
1293
+ * initTfhe is a platform-specific dependency injected into core/createCofhesdkClientBase by web/createCofhesdkClient and node/createCofhesdkClient
1294
+ * web/ uses zama "tfhe"
1295
+ * node/ uses zama "node-tfhe"
1296
+ * Users should not set this manually.
1297
+ */
1298
+ async initTfheOrThrow() {
1299
+ if (!this.initTfhe)
1300
+ return false;
1301
+ try {
1302
+ return await this.initTfhe();
1303
+ } catch (error) {
1304
+ throw CofhesdkError.fromError(error, {
1305
+ code: "INIT_TFHE_FAILED" /* InitTfheFailed */,
1306
+ message: `Failed to initialize TFHE`,
1307
+ context: {
1308
+ initTfhe: this.initTfhe
1309
+ }
1310
+ });
1311
+ }
1312
+ }
1313
+ /**
1314
+ * Fetches the FHE key and CRS from the CoFHE API
1315
+ * If the key/crs already exists in the store it is returned, else it is fetched, stored, and returned
1316
+ */
1317
+ async fetchFheKeyAndCrs() {
1318
+ this.assertChainId();
1319
+ const securityZone = this.getSecurityZone();
1320
+ try {
1321
+ await this.keysStorage?.rehydrateKeysStore();
1322
+ } catch (error) {
1323
+ throw CofhesdkError.fromError(error, {
1324
+ code: "REHYDRATE_KEYS_STORE_FAILED" /* RehydrateKeysStoreFailed */,
1325
+ message: `Failed to rehydrate keys store`,
1326
+ context: {
1327
+ keysStorage: this.keysStorage
1328
+ }
1329
+ });
1330
+ }
1331
+ let fheKey;
1332
+ let fheKeyFetchedFromCoFHE = false;
1333
+ let crs;
1334
+ let crsFetchedFromCoFHE = false;
1335
+ try {
1336
+ [[fheKey, fheKeyFetchedFromCoFHE], [crs, crsFetchedFromCoFHE]] = await fetchKeys(
1337
+ this.config,
1338
+ this.chainId,
1339
+ securityZone,
1340
+ this.tfhePublicKeyDeserializer,
1341
+ this.compactPkeCrsDeserializer,
1342
+ this.keysStorage
1343
+ );
1344
+ } catch (error) {
1345
+ throw CofhesdkError.fromError(error, {
1346
+ code: "FETCH_KEYS_FAILED" /* FetchKeysFailed */,
1347
+ message: `Failed to fetch FHE key and CRS`,
1348
+ context: {
1349
+ config: this.config,
1350
+ chainId: this.chainId,
1351
+ securityZone,
1352
+ compactPkeCrsDeserializer: this.compactPkeCrsDeserializer,
1353
+ tfhePublicKeyDeserializer: this.tfhePublicKeyDeserializer
1354
+ }
1355
+ });
1356
+ }
1357
+ if (!fheKey) {
1358
+ throw new CofhesdkError({
1359
+ code: "MISSING_FHE_KEY" /* MissingFheKey */,
1360
+ message: `FHE key not found`,
1361
+ context: {
1362
+ chainId: this.chainId,
1363
+ securityZone
1364
+ }
1365
+ });
1366
+ }
1367
+ if (!crs) {
1368
+ throw new CofhesdkError({
1369
+ code: "MISSING_CRS" /* MissingCrs */,
1370
+ message: `CRS not found for chainId <${this.chainId}>`,
1371
+ context: {
1372
+ chainId: this.chainId
1373
+ }
1374
+ });
1375
+ }
1376
+ return { fheKey, fheKeyFetchedFromCoFHE, crs, crsFetchedFromCoFHE };
1377
+ }
1378
+ /**
1379
+ * @dev Encrypt against the cofheMocks instead of CoFHE
1380
+ *
1381
+ * In the cofheMocks, the MockZkVerifier contract is deployed on hardhat to a fixed address, this contract handles mocking the zk verifying.
1382
+ * cofheMocksInsertPackedHashes - stores the ctHashes and their plaintext values for on-chain mocking of FHE operations.
1383
+ * cofheMocksZkCreateProofSignatures - creates signatures to be included in the encrypted inputs. The signers address is known and verified in the mock contracts.
1384
+ */
1385
+ async mocksEncrypt() {
1386
+ this.assertAccount();
1387
+ this.assertPublicClient();
1388
+ this.assertWalletClient();
1389
+ this.fireStepStart("initTfhe" /* InitTfhe */);
1390
+ await sleep(100);
1391
+ this.fireStepEnd("initTfhe" /* InitTfhe */, { tfheInitializationExecuted: false });
1392
+ this.fireStepStart("fetchKeys" /* FetchKeys */);
1393
+ await sleep(100);
1394
+ this.fireStepEnd("fetchKeys" /* FetchKeys */, { fheKeyFetchedFromCoFHE: false, crsFetchedFromCoFHE: false });
1395
+ this.fireStepStart("pack" /* Pack */);
1396
+ await cofheMocksCheckEncryptableBits(this.inputItems);
1397
+ await sleep(100);
1398
+ this.fireStepEnd("pack" /* Pack */);
1399
+ this.fireStepStart("prove" /* Prove */);
1400
+ await sleep(500);
1401
+ this.fireStepEnd("prove" /* Prove */);
1402
+ this.fireStepStart("verify" /* Verify */);
1403
+ await sleep(500);
1404
+ const signedResults = await cofheMocksZkVerifySign(
1405
+ this.inputItems,
1406
+ this.account,
1407
+ this.securityZone,
1408
+ this.publicClient,
1409
+ this.walletClient,
1410
+ this.zkvWalletClient
1411
+ );
1412
+ const encryptedInputs = signedResults.map(({ ct_hash, signature }, index) => ({
1413
+ ctHash: BigInt(ct_hash),
1414
+ securityZone: this.securityZone,
1415
+ utype: this.inputItems[index].utype,
1416
+ signature
1417
+ }));
1418
+ this.fireStepEnd("verify" /* Verify */);
1419
+ return encryptedInputs;
1420
+ }
1421
+ /**
1422
+ * In the production context, perform a true encryption with the CoFHE coprocessor.
1423
+ */
1424
+ async productionEncrypt() {
1425
+ this.assertAccount();
1426
+ this.assertChainId();
1427
+ this.fireStepStart("initTfhe" /* InitTfhe */);
1428
+ const tfheInitializationExecuted = await this.initTfheOrThrow();
1429
+ this.fireStepEnd("initTfhe" /* InitTfhe */, { tfheInitializationExecuted });
1430
+ this.fireStepStart("fetchKeys" /* FetchKeys */);
1431
+ const { fheKey, fheKeyFetchedFromCoFHE, crs, crsFetchedFromCoFHE } = await this.fetchFheKeyAndCrs();
1432
+ let { zkBuilder, zkCrs } = this.zkBuilderAndCrsGenerator(fheKey, crs);
1433
+ this.fireStepEnd("fetchKeys" /* FetchKeys */, { fheKeyFetchedFromCoFHE, crsFetchedFromCoFHE });
1434
+ this.fireStepStart("pack" /* Pack */);
1435
+ zkBuilder = zkPack(this.inputItems, zkBuilder);
1436
+ this.fireStepEnd("pack" /* Pack */);
1437
+ this.fireStepStart("prove" /* Prove */);
1438
+ const metadata = constructZkPoKMetadata(this.account, this.securityZone, this.chainId);
1439
+ let proof = null;
1440
+ let usedWorker = false;
1441
+ let workerFailedError;
1442
+ if (this.useWorker && this.zkProveWorkerFn) {
1443
+ try {
1444
+ proof = await zkProveWithWorker(this.zkProveWorkerFn, fheKey, crs, this.inputItems, metadata);
1445
+ usedWorker = true;
1446
+ } catch (error) {
1447
+ workerFailedError = error instanceof Error ? error.message : String(error);
1448
+ }
1449
+ }
1450
+ if (proof == null) {
1451
+ proof = await zkProve(zkBuilder, zkCrs, metadata);
1452
+ usedWorker = false;
1453
+ }
1454
+ this.fireStepEnd("prove" /* Prove */, {
1455
+ useWorker: this.useWorker,
1456
+ usedWorker,
1457
+ workerFailedError
1458
+ });
1459
+ this.fireStepStart("verify" /* Verify */);
1460
+ const zkVerifierUrl = await this.getZkVerifierUrl();
1461
+ const verifyResults = await zkVerify(zkVerifierUrl, proof, this.account, this.securityZone, this.chainId);
1462
+ const encryptedInputs = verifyResults.map(
1463
+ ({ ct_hash, signature }, index) => ({
1464
+ ctHash: BigInt(ct_hash),
1465
+ securityZone: this.securityZone,
1466
+ utype: this.inputItems[index].utype,
1467
+ signature
1468
+ })
1469
+ );
1470
+ this.fireStepEnd("verify" /* Verify */);
1471
+ return encryptedInputs;
1472
+ }
1473
+ /**
1474
+ * Final step of the encryption process. MUST BE CALLED LAST IN THE CHAIN.
1475
+ *
1476
+ * This will:
1477
+ * - Pack the encryptable items into a zk proof
1478
+ * - Prove the zk proof
1479
+ * - Verify the zk proof with CoFHE
1480
+ * - Package and return the encrypted inputs
1481
+ *
1482
+ * Example:
1483
+ * ```typescript
1484
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1485
+ * .setAccount('0x123...890') // optional
1486
+ * .setChainId(11155111) // optional
1487
+ * .encrypt(); // execute
1488
+ * ```
1489
+ *
1490
+ * @returns The encrypted inputs.
1491
+ */
1492
+ async encrypt() {
1493
+ if (this.chainId === chains.hardhat.id)
1494
+ return this.mocksEncrypt();
1495
+ return this.productionEncrypt();
1496
+ }
1497
+ };
1498
+
1499
+ // permits/utils.ts
1500
+ var fromHexString = (hexString) => {
1501
+ const cleanString = hexString.length % 2 === 1 ? `0${hexString}` : hexString;
1502
+ const arr = cleanString.replace(/^0x/, "").match(/.{1,2}/g);
1503
+ if (!arr)
1504
+ return new Uint8Array();
1505
+ return new Uint8Array(arr.map((byte) => parseInt(byte, 16)));
1506
+ };
1507
+ var toHexString2 = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
1508
+ function toBigInt(value) {
1509
+ if (typeof value === "string") {
1510
+ return BigInt(value);
1511
+ } else if (typeof value === "number") {
1512
+ return BigInt(value);
1513
+ } else if (typeof value === "object") {
1514
+ return BigInt("0x" + toHexString2(value));
1515
+ } else {
1516
+ return value;
1517
+ }
1518
+ }
1519
+ function toBeArray(value) {
1520
+ const bigIntValue = typeof value === "number" ? BigInt(value) : value;
1521
+ const hex = bigIntValue.toString(16);
1522
+ const paddedHex = hex.length % 2 === 0 ? hex : "0" + hex;
1523
+ return fromHexString(paddedHex);
1524
+ }
1525
+ function isString(value) {
1526
+ if (typeof value !== "string") {
1527
+ throw new Error(`Expected value which is \`string\`, received value of type \`${typeof value}\`.`);
1528
+ }
1529
+ }
1530
+ function isNumber(value) {
1531
+ const is = typeof value === "number" && !Number.isNaN(value);
1532
+ if (!is) {
1533
+ throw new Error(`Expected value which is \`number\`, received value of type \`${typeof value}\`.`);
1534
+ }
1535
+ }
1536
+ function isBigIntOrNumber(value) {
1537
+ const is = typeof value === "bigint";
1538
+ if (!is) {
1539
+ try {
1540
+ isNumber(value);
1541
+ } catch (e) {
1542
+ throw new Error(`Value ${value} is not a number or bigint: ${typeof value}`);
1543
+ }
1544
+ }
1545
+ }
1546
+ function is0xPrefixed(value) {
1547
+ return value.startsWith("0x");
1548
+ }
1549
+
1550
+ // permits/sealing.ts
1551
+ var PRIVATE_KEY_LENGTH = 64;
1552
+ var PUBLIC_KEY_LENGTH = 64;
1553
+ var SealingKey = class _SealingKey {
1554
+ /**
1555
+ * The private key used for decryption.
1556
+ */
1557
+ privateKey;
1558
+ /**
1559
+ * The public key used for encryption.
1560
+ */
1561
+ publicKey;
1562
+ /**
1563
+ * Constructs a SealingKey instance with the given private and public keys.
1564
+ *
1565
+ * @param {string} privateKey - The private key used for decryption.
1566
+ * @param {string} publicKey - The public key used for encryption.
1567
+ * @throws Will throw an error if the provided keys lengths do not match
1568
+ * the required lengths for private and public keys.
1569
+ */
1570
+ constructor(privateKey, publicKey) {
1571
+ if (privateKey.length !== PRIVATE_KEY_LENGTH) {
1572
+ throw new Error(`Private key must be of length ${PRIVATE_KEY_LENGTH}`);
1573
+ }
1574
+ if (publicKey.length !== PUBLIC_KEY_LENGTH) {
1575
+ throw new Error(`Public key must be of length ${PUBLIC_KEY_LENGTH}`);
1576
+ }
1577
+ this.privateKey = privateKey;
1578
+ this.publicKey = publicKey;
1579
+ }
1580
+ unseal = (parsedData) => {
1581
+ const nonce = parsedData.nonce instanceof Uint8Array ? parsedData.nonce : new Uint8Array(parsedData.nonce);
1582
+ const ephemPublicKey = parsedData.public_key instanceof Uint8Array ? parsedData.public_key : new Uint8Array(parsedData.public_key);
1583
+ const dataToDecrypt = parsedData.data instanceof Uint8Array ? parsedData.data : new Uint8Array(parsedData.data);
1584
+ const privateKeyBytes = fromHexString(this.privateKey);
1585
+ const decryptedMessage = nacl__namespace.box.open(dataToDecrypt, nonce, ephemPublicKey, privateKeyBytes);
1586
+ if (!decryptedMessage) {
1587
+ throw new Error("Failed to decrypt message");
1588
+ }
1589
+ return toBigInt(decryptedMessage);
1590
+ };
1591
+ /**
1592
+ * Serializes the SealingKey to a JSON object.
1593
+ */
1594
+ serialize = () => {
1595
+ return {
1596
+ privateKey: this.privateKey,
1597
+ publicKey: this.publicKey
1598
+ };
1599
+ };
1600
+ /**
1601
+ * Deserializes the SealingKey from a JSON object.
1602
+ */
1603
+ static deserialize = (privateKey, publicKey) => {
1604
+ return new _SealingKey(privateKey, publicKey);
1605
+ };
1606
+ /**
1607
+ * Seals (encrypts) the provided message for a receiver with the specified public key.
1608
+ *
1609
+ * @param {bigint | number} value - The message to be encrypted.
1610
+ * @param {string} publicKey - The public key of the intended recipient.
1611
+ * @returns string - The encrypted message in hexadecimal format.
1612
+ * @static
1613
+ * @throws Will throw if the provided publicKey or value do not meet defined preconditions.
1614
+ */
1615
+ static seal = (value, publicKey) => {
1616
+ isString(publicKey);
1617
+ isBigIntOrNumber(value);
1618
+ const ephemeralKeyPair = nacl__namespace.box.keyPair();
1619
+ const nonce = nacl__namespace.randomBytes(nacl__namespace.box.nonceLength);
1620
+ const encryptedMessage = nacl__namespace.box(toBeArray(value), nonce, fromHexString(publicKey), ephemeralKeyPair.secretKey);
1621
+ return {
1622
+ data: encryptedMessage,
1623
+ public_key: ephemeralKeyPair.publicKey,
1624
+ nonce
1625
+ };
1626
+ };
1627
+ };
1628
+ var GenerateSealingKey = () => {
1629
+ const sodiumKeypair = nacl__namespace.box.keyPair();
1630
+ return new SealingKey(toHexString2(sodiumKeypair.secretKey), toHexString2(sodiumKeypair.publicKey));
1631
+ };
1632
+ var SerializedSealingPair = zod.z.object({
1633
+ privateKey: zod.z.string(),
1634
+ publicKey: zod.z.string()
1635
+ });
1636
+ var DEFAULT_EXPIRATION_FN = () => Math.round(Date.now() / 1e3) + 7 * 24 * 60 * 60;
1637
+ var zPermitWithDefaults = zod.z.object({
1638
+ name: zod.z.string().optional().default("Unnamed Permit"),
1639
+ type: zod.z.enum(["self", "sharing", "recipient"]),
1640
+ issuer: zod.z.string().refine((val) => viem.isAddress(val), {
1641
+ message: "Permit issuer :: invalid address"
1642
+ }).refine((val) => val !== viem.zeroAddress, {
1643
+ message: "Permit issuer :: must not be zeroAddress"
1644
+ }),
1645
+ expiration: zod.z.number().optional().default(DEFAULT_EXPIRATION_FN),
1646
+ recipient: zod.z.string().optional().default(viem.zeroAddress).refine((val) => viem.isAddress(val), {
1647
+ message: "Permit recipient :: invalid address"
1648
+ }),
1649
+ validatorId: zod.z.number().optional().default(0),
1650
+ validatorContract: zod.z.string().optional().default(viem.zeroAddress).refine((val) => viem.isAddress(val), {
1651
+ message: "Permit validatorContract :: invalid address"
1652
+ }),
1653
+ issuerSignature: zod.z.string().optional().default("0x"),
1654
+ recipientSignature: zod.z.string().optional().default("0x")
1655
+ });
1656
+ var zPermitWithSealingPair = zPermitWithDefaults.extend({
1657
+ sealingPair: SerializedSealingPair.optional()
1658
+ });
1659
+ var ValidatorContractRefinement = [
1660
+ (data) => data.validatorId !== 0 && data.validatorContract !== viem.zeroAddress || data.validatorId === 0 && data.validatorContract === viem.zeroAddress,
1661
+ {
1662
+ message: "Permit external validator :: validatorId and validatorContract must either both be set or both be unset.",
1663
+ path: ["validatorId", "validatorContract"]
1664
+ }
1665
+ ];
1666
+ var SelfPermitOptionsValidator = zod.z.object({
1667
+ type: zod.z.literal("self").optional().default("self"),
1668
+ issuer: zod.z.string().refine((val) => viem.isAddress(val), {
1669
+ message: "Self permit issuer :: invalid address"
1670
+ }).refine((val) => is0xPrefixed(val), {
1671
+ message: "Self permit issuer :: must be 0x prefixed"
1672
+ }).refine((val) => val !== viem.zeroAddress, {
1673
+ message: "Self permit issuer :: must not be zeroAddress"
1674
+ }),
1675
+ name: zod.z.string().optional().default("Unnamed Permit"),
1676
+ expiration: zod.z.number().optional().default(DEFAULT_EXPIRATION_FN),
1677
+ recipient: zod.z.string().optional().default(viem.zeroAddress).refine((val) => viem.isAddress(val), {
1678
+ message: "Self permit recipient :: invalid address"
1679
+ }).refine((val) => is0xPrefixed(val), {
1680
+ message: "Self permit recipient :: must be 0x prefixed"
1681
+ }).refine((val) => val === viem.zeroAddress, {
1682
+ message: "Self permit recipient :: must be zeroAddress"
1683
+ }),
1684
+ validatorId: zod.z.number().optional().default(0),
1685
+ validatorContract: zod.z.string().optional().default(viem.zeroAddress).refine((val) => viem.isAddress(val), {
1686
+ message: "Self permit validatorContract :: invalid address"
1687
+ }),
1688
+ issuerSignature: zod.z.string().optional().default("0x").refine((val) => is0xPrefixed(val), {
1689
+ message: "Self permit issuerSignature :: must be 0x prefixed"
1690
+ }),
1691
+ recipientSignature: zod.z.string().optional().default("0x").refine((val) => is0xPrefixed(val), {
1692
+ message: "Self permit recipientSignature :: must be 0x prefixed"
1693
+ })
1694
+ }).refine(...ValidatorContractRefinement);
1695
+ var SelfPermitValidator = zPermitWithSealingPair.refine((data) => data.type === "self", {
1696
+ message: "Self permit :: type must be 'self'"
1697
+ }).refine((data) => data.recipient === viem.zeroAddress, {
1698
+ message: "Self permit :: recipient must be zeroAddress"
1699
+ }).refine((data) => data.issuerSignature !== "0x", {
1700
+ message: "Self permit :: issuerSignature must be populated"
1701
+ }).refine((data) => data.recipientSignature === "0x", {
1702
+ message: "Self permit :: recipientSignature must be empty"
1703
+ }).refine(...ValidatorContractRefinement);
1704
+ var SharingPermitOptionsValidator = zod.z.object({
1705
+ type: zod.z.literal("sharing").optional().default("sharing"),
1706
+ issuer: zod.z.string().refine((val) => viem.isAddress(val), {
1707
+ message: "Sharing permit issuer :: invalid address"
1708
+ }).refine((val) => is0xPrefixed(val), {
1709
+ message: "Sharing permit issuer :: must be 0x prefixed"
1710
+ }).refine((val) => val !== viem.zeroAddress, {
1711
+ message: "Sharing permit issuer :: must not be zeroAddress"
1712
+ }),
1713
+ recipient: zod.z.string().refine((val) => viem.isAddress(val), {
1714
+ message: "Sharing permit recipient :: invalid address"
1715
+ }).refine((val) => is0xPrefixed(val), {
1716
+ message: "Sharing permit recipient :: must be 0x prefixed"
1717
+ }).refine((val) => val !== viem.zeroAddress, {
1718
+ message: "Sharing permit recipient :: must not be zeroAddress"
1719
+ }),
1720
+ name: zod.z.string().optional().default("Unnamed Permit"),
1721
+ expiration: zod.z.number().optional().default(DEFAULT_EXPIRATION_FN),
1722
+ validatorId: zod.z.number().optional().default(0),
1723
+ validatorContract: zod.z.string().optional().default(viem.zeroAddress).refine((val) => viem.isAddress(val), {
1724
+ message: "Sharing permit validatorContract :: invalid address"
1725
+ }),
1726
+ issuerSignature: zod.z.string().optional().default("0x").refine((val) => is0xPrefixed(val), {
1727
+ message: "Sharing permit issuerSignature :: must be 0x prefixed"
1728
+ }),
1729
+ recipientSignature: zod.z.string().optional().default("0x").refine((val) => is0xPrefixed(val), {
1730
+ message: "Sharing permit recipientSignature :: must be 0x prefixed"
1731
+ })
1732
+ }).refine(...ValidatorContractRefinement);
1733
+ var SharingPermitValidator = zPermitWithSealingPair.refine((data) => data.type === "sharing", {
1734
+ message: "Sharing permit :: type must be 'sharing'"
1735
+ }).refine((data) => data.recipient !== viem.zeroAddress, {
1736
+ message: "Sharing permit :: recipient must not be zeroAddress"
1737
+ }).refine((data) => data.issuerSignature !== "0x", {
1738
+ message: "Sharing permit :: issuerSignature must be populated"
1739
+ }).refine((data) => data.recipientSignature === "0x", {
1740
+ message: "Sharing permit :: recipientSignature must be empty"
1741
+ }).refine(...ValidatorContractRefinement);
1742
+ var ImportPermitOptionsValidator = zod.z.object({
1743
+ type: zod.z.literal("recipient").optional().default("recipient"),
1744
+ issuer: zod.z.string().refine((val) => viem.isAddress(val), {
1745
+ message: "Import permit issuer :: invalid address"
1746
+ }).refine((val) => is0xPrefixed(val), {
1747
+ message: "Import permit issuer :: must be 0x prefixed"
1748
+ }).refine((val) => val !== viem.zeroAddress, {
1749
+ message: "Import permit issuer :: must not be zeroAddress"
1750
+ }),
1751
+ recipient: zod.z.string().refine((val) => viem.isAddress(val), {
1752
+ message: "Import permit recipient :: invalid address"
1753
+ }).refine((val) => is0xPrefixed(val), {
1754
+ message: "Import permit recipient :: must be 0x prefixed"
1755
+ }).refine((val) => val !== viem.zeroAddress, {
1756
+ message: "Import permit recipient :: must not be zeroAddress"
1757
+ }),
1758
+ issuerSignature: zod.z.string().refine((val) => is0xPrefixed(val), {
1759
+ message: "Import permit issuerSignature :: must be 0x prefixed"
1760
+ }).refine((val) => val !== "0x", {
1761
+ message: "Import permit :: issuerSignature must be provided"
1762
+ }),
1763
+ name: zod.z.string().optional().default("Unnamed Permit"),
1764
+ expiration: zod.z.number().optional().default(DEFAULT_EXPIRATION_FN),
1765
+ validatorId: zod.z.number().optional().default(0),
1766
+ validatorContract: zod.z.string().optional().default(viem.zeroAddress).refine((val) => viem.isAddress(val), {
1767
+ message: "Import permit validatorContract :: invalid address"
1768
+ }),
1769
+ recipientSignature: zod.z.string().optional().default("0x").refine((val) => is0xPrefixed(val), {
1770
+ message: "Import permit recipientSignature :: must be 0x prefixed"
1771
+ })
1772
+ }).refine(...ValidatorContractRefinement);
1773
+ var ImportPermitValidator = zPermitWithSealingPair.refine((data) => data.type === "recipient", {
1774
+ message: "Import permit :: type must be 'recipient'"
1775
+ }).refine((data) => data.recipient !== viem.zeroAddress, {
1776
+ message: "Import permit :: recipient must not be zeroAddress"
1777
+ }).refine((data) => data.issuerSignature !== "0x", {
1778
+ message: "Import permit :: issuerSignature must be populated"
1779
+ }).refine((data) => data.recipientSignature !== "0x", {
1780
+ message: "Import permit :: recipientSignature must be populated"
1781
+ }).refine(...ValidatorContractRefinement);
1782
+ var validateSelfPermitOptions = (options) => SelfPermitOptionsValidator.safeParse(options);
1783
+ var validateSharingPermitOptions = (options) => SharingPermitOptionsValidator.safeParse(options);
1784
+ var validateImportPermitOptions = (options) => ImportPermitOptionsValidator.safeParse(options);
1785
+ var validateSelfPermit = (permit) => SelfPermitValidator.safeParse(permit);
1786
+ var validateSharingPermit = (permit) => SharingPermitValidator.safeParse(permit);
1787
+ var validateImportPermit = (permit) => ImportPermitValidator.safeParse(permit);
1788
+ var ValidationUtils = {
1789
+ /**
1790
+ * Check if permit is expired
1791
+ */
1792
+ isExpired: (permit) => {
1793
+ return permit.expiration < Math.floor(Date.now() / 1e3);
1794
+ },
1795
+ /**
1796
+ * Check if permit is signed by the active party
1797
+ */
1798
+ isSigned: (permit) => {
1799
+ if (permit.type === "self" || permit.type === "sharing") {
1800
+ return permit.issuerSignature !== "0x";
1801
+ }
1802
+ if (permit.type === "recipient") {
1803
+ return permit.recipientSignature !== "0x";
1804
+ }
1805
+ return false;
1806
+ },
1807
+ /**
1808
+ * Overall validity checker of a permit
1809
+ */
1810
+ isValid: (permit) => {
1811
+ if (ValidationUtils.isExpired(permit)) {
1812
+ return { valid: false, error: "expired" };
1813
+ }
1814
+ if (!ValidationUtils.isSigned(permit)) {
1815
+ return { valid: false, error: "not-signed" };
1816
+ }
1817
+ return { valid: true, error: null };
1818
+ }
1819
+ };
1820
+
1821
+ // permits/signature.ts
1822
+ var PermitSignatureAllFields = [
1823
+ { name: "issuer", type: "address" },
1824
+ { name: "expiration", type: "uint64" },
1825
+ { name: "recipient", type: "address" },
1826
+ { name: "validatorId", type: "uint256" },
1827
+ { name: "validatorContract", type: "address" },
1828
+ { name: "sealingKey", type: "bytes32" },
1829
+ { name: "issuerSignature", type: "bytes" }
1830
+ ];
1831
+ var SignatureTypes = {
1832
+ PermissionedV2IssuerSelf: [
1833
+ "issuer",
1834
+ "expiration",
1835
+ "recipient",
1836
+ "validatorId",
1837
+ "validatorContract",
1838
+ "sealingKey"
1839
+ ],
1840
+ PermissionedV2IssuerShared: [
1841
+ "issuer",
1842
+ "expiration",
1843
+ "recipient",
1844
+ "validatorId",
1845
+ "validatorContract"
1846
+ ],
1847
+ PermissionedV2Recipient: ["sealingKey", "issuerSignature"]
1848
+ };
1849
+ var getSignatureTypesAndMessage = (primaryType, fields, values) => {
1850
+ const types = {
1851
+ [primaryType]: PermitSignatureAllFields.filter((fieldType) => fields.includes(fieldType.name))
1852
+ };
1853
+ const message = {};
1854
+ fields.forEach((field) => {
1855
+ if (field in values) {
1856
+ message[field] = values[field];
1857
+ }
1858
+ });
1859
+ return { types, primaryType, message };
1860
+ };
1861
+ var SignatureUtils = {
1862
+ /**
1863
+ * Get signature parameters for a permit
1864
+ */
1865
+ getSignatureParams: (permit, primaryType) => {
1866
+ return getSignatureTypesAndMessage(primaryType, SignatureTypes[primaryType], permit);
1867
+ },
1868
+ /**
1869
+ * Determine the required signature type based on permit type
1870
+ */
1871
+ getPrimaryType: (permitType) => {
1872
+ if (permitType === "self")
1873
+ return "PermissionedV2IssuerSelf";
1874
+ if (permitType === "sharing")
1875
+ return "PermissionedV2IssuerShared";
1876
+ if (permitType === "recipient")
1877
+ return "PermissionedV2Recipient";
1878
+ throw new Error(`Unknown permit type: ${permitType}`);
1879
+ }
1880
+ };
1881
+
1882
+ // permits/permit.ts
1883
+ var PermitUtils = {
1884
+ /**
1885
+ * Create a self permit for personal use
1886
+ */
1887
+ createSelf: (options) => {
1888
+ const validation = validateSelfPermitOptions(options);
1889
+ if (!validation.success) {
1890
+ throw new Error(
1891
+ "PermitUtils :: createSelf :: Parsing SelfPermitOptions failed " + JSON.stringify(validation.error, null, 2)
1892
+ );
1893
+ }
1894
+ const sealingPair = GenerateSealingKey();
1895
+ const permit = {
1896
+ ...validation.data,
1897
+ sealingPair,
1898
+ _signedDomain: void 0
1899
+ };
1900
+ return permit;
1901
+ },
1902
+ /**
1903
+ * Create a sharing permit to be shared with another user
1904
+ */
1905
+ createSharing: (options) => {
1906
+ const validation = validateSharingPermitOptions(options);
1907
+ if (!validation.success) {
1908
+ throw new Error(
1909
+ "PermitUtils :: createSharing :: Parsing SharingPermitOptions failed " + JSON.stringify(validation.error, null, 2)
1910
+ );
1911
+ }
1912
+ const sealingPair = GenerateSealingKey();
1913
+ const permit = {
1914
+ ...validation.data,
1915
+ sealingPair,
1916
+ _signedDomain: void 0
1917
+ };
1918
+ return permit;
1919
+ },
1920
+ /**
1921
+ * Import a shared permit from various input formats
1922
+ */
1923
+ importShared: (options) => {
1924
+ let parsedOptions;
1925
+ if (typeof options === "string") {
1926
+ try {
1927
+ parsedOptions = JSON.parse(options);
1928
+ } catch (error) {
1929
+ throw new Error(`PermitUtils :: importShared :: Failed to parse JSON string: ${error}`);
1930
+ }
1931
+ } else if (typeof options === "object" && options !== null) {
1932
+ parsedOptions = options;
1933
+ } else {
1934
+ throw new Error(
1935
+ "PermitUtils :: importShared :: Invalid input type, expected ImportSharedPermitOptions, object, or string"
1936
+ );
1937
+ }
1938
+ if (parsedOptions.type != null && parsedOptions.type !== "sharing") {
1939
+ throw new Error(`PermitUtils :: importShared :: Invalid permit type <${parsedOptions.type}>, must be "sharing"`);
1940
+ }
1941
+ const validation = validateImportPermitOptions({ ...parsedOptions, type: "recipient" });
1942
+ if (!validation.success) {
1943
+ throw new Error(
1944
+ "PermitUtils :: importShared :: Parsing ImportPermitOptions failed " + JSON.stringify(validation.error, null, 2)
1945
+ );
1946
+ }
1947
+ const sealingPair = GenerateSealingKey();
1948
+ const permit = {
1949
+ ...validation.data,
1950
+ sealingPair,
1951
+ _signedDomain: void 0
1952
+ };
1953
+ return permit;
1954
+ },
1955
+ /**
1956
+ * Sign a permit with the provided wallet client
1957
+ */
1958
+ sign: async (permit, publicClient, walletClient) => {
1959
+ if (walletClient == null || walletClient.account == null) {
1960
+ throw new Error(
1961
+ "PermitUtils :: sign - walletClient undefined, you must pass in a `walletClient` for the connected user to create a permit signature"
1962
+ );
1963
+ }
1964
+ const primaryType = SignatureUtils.getPrimaryType(permit.type);
1965
+ const domain = await PermitUtils.fetchEIP712Domain(publicClient);
1966
+ const { types, message } = SignatureUtils.getSignatureParams(PermitUtils.getPermission(permit, true), primaryType);
1967
+ const signature = await walletClient.signTypedData({
1968
+ domain,
1969
+ types,
1970
+ primaryType,
1971
+ message,
1972
+ account: walletClient.account
1973
+ });
1974
+ let updatedPermit;
1975
+ if (permit.type === "self" || permit.type === "sharing") {
1976
+ updatedPermit = {
1977
+ ...permit,
1978
+ issuerSignature: signature,
1979
+ _signedDomain: domain
1980
+ };
1981
+ } else {
1982
+ updatedPermit = {
1983
+ ...permit,
1984
+ recipientSignature: signature,
1985
+ _signedDomain: domain
1986
+ };
1987
+ }
1988
+ return updatedPermit;
1989
+ },
1990
+ /**
1991
+ * Create and sign a self permit in one operation
1992
+ */
1993
+ createSelfAndSign: async (options, publicClient, walletClient) => {
1994
+ const permit = PermitUtils.createSelf(options);
1995
+ return PermitUtils.sign(permit, publicClient, walletClient);
1996
+ },
1997
+ /**
1998
+ * Create and sign a sharing permit in one operation
1999
+ */
2000
+ createSharingAndSign: async (options, publicClient, walletClient) => {
2001
+ const permit = PermitUtils.createSharing(options);
2002
+ return PermitUtils.sign(permit, publicClient, walletClient);
2003
+ },
2004
+ /**
2005
+ * Import and sign a shared permit in one operation from various input formats
2006
+ */
2007
+ importSharedAndSign: async (options, publicClient, walletClient) => {
2008
+ const permit = PermitUtils.importShared(options);
2009
+ return PermitUtils.sign(permit, publicClient, walletClient);
2010
+ },
2011
+ /**
2012
+ * Deserialize a permit from serialized data
2013
+ */
2014
+ deserialize: (data) => {
2015
+ return {
2016
+ ...data,
2017
+ sealingPair: SealingKey.deserialize(data.sealingPair.privateKey, data.sealingPair.publicKey)
2018
+ };
2019
+ },
2020
+ /**
2021
+ * Serialize a permit for storage
2022
+ */
2023
+ serialize: (permit) => {
2024
+ return {
2025
+ name: permit.name,
2026
+ type: permit.type,
2027
+ issuer: permit.issuer,
2028
+ expiration: permit.expiration,
2029
+ recipient: permit.recipient,
2030
+ validatorId: permit.validatorId,
2031
+ validatorContract: permit.validatorContract,
2032
+ issuerSignature: permit.issuerSignature,
2033
+ recipientSignature: permit.recipientSignature,
2034
+ _signedDomain: permit._signedDomain,
2035
+ sealingPair: permit.sealingPair.serialize()
2036
+ };
2037
+ },
2038
+ /**
2039
+ * Validate a permit
2040
+ */
2041
+ validate: (permit) => {
2042
+ if (permit.type === "self") {
2043
+ return validateSelfPermit(permit);
2044
+ } else if (permit.type === "sharing") {
2045
+ return validateSharingPermit(permit);
2046
+ } else if (permit.type === "recipient") {
2047
+ return validateImportPermit(permit);
2048
+ } else {
2049
+ throw new Error("PermitUtils :: validate :: Invalid permit type");
2050
+ }
2051
+ },
2052
+ /**
2053
+ * Get the permission object from a permit (for use in contracts)
2054
+ */
2055
+ getPermission: (permit, skipValidation = false) => {
2056
+ if (!skipValidation) {
2057
+ const validationResult = PermitUtils.validate(permit);
2058
+ if (!validationResult.success) {
2059
+ throw new Error(
2060
+ `PermitUtils :: getPermission :: permit validation failed - ${JSON.stringify(validationResult.error, null, 2)} ${JSON.stringify(permit, null, 2)}`
2061
+ );
2062
+ }
2063
+ }
2064
+ return {
2065
+ issuer: permit.issuer,
2066
+ expiration: permit.expiration,
2067
+ recipient: permit.recipient,
2068
+ validatorId: permit.validatorId,
2069
+ validatorContract: permit.validatorContract,
2070
+ sealingKey: `0x${permit.sealingPair.publicKey}`,
2071
+ issuerSignature: permit.issuerSignature,
2072
+ recipientSignature: permit.recipientSignature
2073
+ };
2074
+ },
2075
+ /**
2076
+ * Get a stable hash for the permit (used as key in storage)
2077
+ */
2078
+ getHash: (permit) => {
2079
+ const data = JSON.stringify({
2080
+ type: permit.type,
2081
+ issuer: permit.issuer,
2082
+ expiration: permit.expiration,
2083
+ recipient: permit.recipient,
2084
+ validatorId: permit.validatorId,
2085
+ validatorContract: permit.validatorContract
2086
+ });
2087
+ return viem.keccak256(viem.toHex(data));
2088
+ },
2089
+ /**
2090
+ * Export permit data for sharing (removes sensitive fields)
2091
+ */
2092
+ export: (permit) => {
2093
+ const cleanedPermit = {
2094
+ name: permit.name,
2095
+ type: permit.type,
2096
+ issuer: permit.issuer,
2097
+ expiration: permit.expiration
2098
+ };
2099
+ if (permit.recipient !== viem.zeroAddress)
2100
+ cleanedPermit.recipient = permit.recipient;
2101
+ if (permit.validatorId !== 0)
2102
+ cleanedPermit.validatorId = permit.validatorId;
2103
+ if (permit.validatorContract !== viem.zeroAddress)
2104
+ cleanedPermit.validatorContract = permit.validatorContract;
2105
+ if (permit.type === "sharing" && permit.issuerSignature !== "0x")
2106
+ cleanedPermit.issuerSignature = permit.issuerSignature;
2107
+ return JSON.stringify(cleanedPermit, void 0, 2);
2108
+ },
2109
+ /**
2110
+ * Unseal encrypted data using the permit's sealing key
2111
+ */
2112
+ unseal: (permit, ciphertext) => {
2113
+ return permit.sealingPair.unseal(ciphertext);
2114
+ },
2115
+ /**
2116
+ * Check if permit is expired
2117
+ */
2118
+ isExpired: (permit) => {
2119
+ return ValidationUtils.isExpired(permit);
2120
+ },
2121
+ /**
2122
+ * Check if permit is signed
2123
+ */
2124
+ isSigned: (permit) => {
2125
+ return ValidationUtils.isSigned(permit);
2126
+ },
2127
+ /**
2128
+ * Check if permit is valid
2129
+ */
2130
+ isValid: (permit) => {
2131
+ return ValidationUtils.isValid(permit);
2132
+ },
2133
+ /**
2134
+ * Update permit name (returns new permit instance)
2135
+ */
2136
+ updateName: (permit, name) => {
2137
+ return { ...permit, name };
2138
+ },
2139
+ /**
2140
+ * Fetch EIP712 domain from the blockchain
2141
+ */
2142
+ fetchEIP712Domain: async (publicClient) => {
2143
+ const TASK_MANAGER_ADDRESS = "0xeA30c4B8b44078Bbf8a6ef5b9f1eC1626C7848D9";
2144
+ const ACL_IFACE = "function acl() view returns (address)";
2145
+ const EIP712_DOMAIN_IFACE = "function eip712Domain() public view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)";
2146
+ const aclAbi = viem.parseAbi([ACL_IFACE]);
2147
+ const aclAddress = await publicClient.readContract({
2148
+ address: TASK_MANAGER_ADDRESS,
2149
+ abi: aclAbi,
2150
+ functionName: "acl"
2151
+ });
2152
+ const domainAbi = viem.parseAbi([EIP712_DOMAIN_IFACE]);
2153
+ const domain = await publicClient.readContract({
2154
+ address: aclAddress,
2155
+ abi: domainAbi,
2156
+ functionName: "eip712Domain"
2157
+ });
2158
+ const [_fields, name, version, chainId, verifyingContract, _salt, _extensions] = domain;
2159
+ return {
2160
+ name,
2161
+ version,
2162
+ chainId: Number(chainId),
2163
+ verifyingContract
2164
+ };
2165
+ },
2166
+ /**
2167
+ * Check if permit's signed domain matches the provided domain
2168
+ */
2169
+ matchesDomain: (permit, domain) => {
2170
+ return permit._signedDomain?.name === domain.name && permit._signedDomain?.version === domain.version && permit._signedDomain?.verifyingContract === domain.verifyingContract && permit._signedDomain?.chainId === domain.chainId;
2171
+ },
2172
+ /**
2173
+ * Check if permit's signed domain is valid for the current chain
2174
+ */
2175
+ checkSignedDomainValid: async (permit, publicClient) => {
2176
+ if (permit._signedDomain == null)
2177
+ return false;
2178
+ const domain = await PermitUtils.fetchEIP712Domain(publicClient);
2179
+ return PermitUtils.matchesDomain(permit, domain);
2180
+ }
2181
+ };
2182
+ var PERMIT_STORE_DEFAULTS = {
2183
+ permits: {},
2184
+ activePermitHash: {}
2185
+ };
2186
+ var _permitStore = vanilla.createStore()(
2187
+ middleware.persist(() => PERMIT_STORE_DEFAULTS, { name: "cofhesdk-permits" })
2188
+ );
2189
+ var clearStaleStore = () => {
2190
+ const state = _permitStore.getState();
2191
+ const hasExpectedStructure = state && typeof state === "object" && "permits" in state && "activePermitHash" in state && typeof state.permits === "object" && typeof state.activePermitHash === "object";
2192
+ if (hasExpectedStructure)
2193
+ return;
2194
+ _permitStore.setState({ permits: {}, activePermitHash: {} });
2195
+ };
2196
+ var getPermit = (chainId, account, hash) => {
2197
+ clearStaleStore();
2198
+ if (chainId == null || account == null || hash == null)
2199
+ return;
2200
+ const savedPermit = _permitStore.getState().permits[chainId]?.[account]?.[hash];
2201
+ if (savedPermit == null)
2202
+ return;
2203
+ return PermitUtils.deserialize(savedPermit);
2204
+ };
2205
+ var getActivePermit = (chainId, account) => {
2206
+ clearStaleStore();
2207
+ if (chainId == null || account == null)
2208
+ return;
2209
+ const activePermitHash = _permitStore.getState().activePermitHash[chainId]?.[account];
2210
+ return getPermit(chainId, account, activePermitHash);
2211
+ };
2212
+ var getPermits = (chainId, account) => {
2213
+ clearStaleStore();
2214
+ if (chainId == null || account == null)
2215
+ return {};
2216
+ return Object.entries(_permitStore.getState().permits[chainId]?.[account] ?? {}).reduce(
2217
+ (acc, [hash, permit]) => {
2218
+ if (permit == void 0)
2219
+ return acc;
2220
+ return { ...acc, [hash]: PermitUtils.deserialize(permit) };
2221
+ },
2222
+ {}
2223
+ );
2224
+ };
2225
+ var setPermit = (chainId, account, permit) => {
2226
+ clearStaleStore();
2227
+ _permitStore.setState(
2228
+ immer.produce((state) => {
2229
+ if (state.permits[chainId] == null)
2230
+ state.permits[chainId] = {};
2231
+ if (state.permits[chainId][account] == null)
2232
+ state.permits[chainId][account] = {};
2233
+ state.permits[chainId][account][PermitUtils.getHash(permit)] = PermitUtils.serialize(permit);
2234
+ })
2235
+ );
2236
+ };
2237
+ var removePermit = (chainId, account, hash, force) => {
2238
+ clearStaleStore();
2239
+ _permitStore.setState(
2240
+ immer.produce((state) => {
2241
+ if (state.permits[chainId] == null)
2242
+ state.permits[chainId] = {};
2243
+ if (state.activePermitHash[chainId] == null)
2244
+ state.activePermitHash[chainId] = {};
2245
+ const accountPermits = state.permits[chainId][account];
2246
+ if (accountPermits == null)
2247
+ return;
2248
+ if (accountPermits[hash] == null)
2249
+ return;
2250
+ if (state.activePermitHash[chainId][account] === hash) {
2251
+ const otherPermitHash = Object.keys(accountPermits).find((key) => key !== hash && accountPermits[key] != null);
2252
+ if (otherPermitHash) {
2253
+ state.activePermitHash[chainId][account] = otherPermitHash;
2254
+ } else {
2255
+ if (!force) {
2256
+ throw new Error("Cannot remove the last permit without force flag");
2257
+ }
2258
+ state.activePermitHash[chainId][account] = void 0;
2259
+ }
2260
+ }
2261
+ accountPermits[hash] = void 0;
2262
+ })
2263
+ );
2264
+ };
2265
+ var getActivePermitHash = (chainId, account) => {
2266
+ clearStaleStore();
2267
+ if (chainId == null || account == null)
2268
+ return void 0;
2269
+ return _permitStore.getState().activePermitHash[chainId]?.[account];
2270
+ };
2271
+ var setActivePermitHash = (chainId, account, hash) => {
2272
+ clearStaleStore();
2273
+ _permitStore.setState(
2274
+ immer.produce((state) => {
2275
+ if (state.activePermitHash[chainId] == null)
2276
+ state.activePermitHash[chainId] = {};
2277
+ state.activePermitHash[chainId][account] = hash;
2278
+ })
2279
+ );
2280
+ };
2281
+ var removeActivePermitHash = (chainId, account) => {
2282
+ clearStaleStore();
2283
+ _permitStore.setState(
2284
+ immer.produce((state) => {
2285
+ if (state.activePermitHash[chainId])
2286
+ state.activePermitHash[chainId][account] = void 0;
2287
+ })
2288
+ );
2289
+ };
2290
+ var resetStore = () => {
2291
+ clearStaleStore();
2292
+ _permitStore.setState({ permits: {}, activePermitHash: {} });
2293
+ };
2294
+ var permitStore = {
2295
+ store: _permitStore,
2296
+ getPermit,
2297
+ getActivePermit,
2298
+ getPermits,
2299
+ setPermit,
2300
+ removePermit,
2301
+ getActivePermitHash,
2302
+ setActivePermitHash,
2303
+ removeActivePermitHash,
2304
+ resetStore
2305
+ };
2306
+ var storeActivePermit = async (permit, publicClient, walletClient) => {
2307
+ const chainId = await publicClient.getChainId();
2308
+ const account = walletClient.account.address;
2309
+ permitStore.setPermit(chainId, account, permit);
2310
+ permitStore.setActivePermitHash(chainId, account, PermitUtils.getHash(permit));
2311
+ };
2312
+ var createPermitWithSign = async (options, publicClient, walletClient, permitMethod) => {
2313
+ const permit = await permitMethod(options, publicClient, walletClient);
2314
+ await storeActivePermit(permit, publicClient, walletClient);
2315
+ return permit;
2316
+ };
2317
+ var createSelf = async (options, publicClient, walletClient) => {
2318
+ return createPermitWithSign(options, publicClient, walletClient, PermitUtils.createSelfAndSign);
2319
+ };
2320
+ var createSharing = async (options, publicClient, walletClient) => {
2321
+ return createPermitWithSign(options, publicClient, walletClient, PermitUtils.createSharingAndSign);
2322
+ };
2323
+ var importShared = async (options, publicClient, walletClient) => {
2324
+ return createPermitWithSign(options, publicClient, walletClient, PermitUtils.importSharedAndSign);
2325
+ };
2326
+ var getHash = (permit) => {
2327
+ return PermitUtils.getHash(permit);
2328
+ };
2329
+ var serialize = (permit) => {
2330
+ return PermitUtils.serialize(permit);
2331
+ };
2332
+ var deserialize = (serialized) => {
2333
+ return PermitUtils.deserialize(serialized);
2334
+ };
2335
+ var getPermit2 = async (chainId, account, hash) => {
2336
+ return permitStore.getPermit(chainId, account, hash);
2337
+ };
2338
+ var getPermits2 = async (chainId, account) => {
2339
+ return permitStore.getPermits(chainId, account);
2340
+ };
2341
+ var getActivePermit2 = async (chainId, account) => {
2342
+ return permitStore.getActivePermit(chainId, account);
2343
+ };
2344
+ var getActivePermitHash2 = (chainId, account) => {
2345
+ return permitStore.getActivePermitHash(chainId, account);
2346
+ };
2347
+ var selectActivePermit = (chainId, account, hash) => {
2348
+ permitStore.setActivePermitHash(chainId, account, hash);
2349
+ };
2350
+ var getOrCreateSelfPermit = async (publicClient, walletClient, chainId, account, options) => {
2351
+ const _chainId = chainId ?? await publicClient.getChainId();
2352
+ const _account = account ?? walletClient.account.address;
2353
+ const activePermit = await getActivePermit2(_chainId, _account);
2354
+ if (activePermit && activePermit.type === "self") {
2355
+ return activePermit;
2356
+ }
2357
+ return createSelf(options ?? { issuer: _account, name: "Autogenerated Self Permit" }, publicClient, walletClient);
2358
+ };
2359
+ var getOrCreateSharingPermit = async (publicClient, walletClient, options, chainId, account) => {
2360
+ const _chainId = chainId ?? await publicClient.getChainId();
2361
+ const _account = account ?? walletClient.account.address;
2362
+ const activePermit = await getActivePermit2(_chainId, _account);
2363
+ if (activePermit && activePermit.type === "sharing") {
2364
+ return activePermit;
2365
+ }
2366
+ return createSharing(options, publicClient, walletClient);
2367
+ };
2368
+ var removePermit2 = async (chainId, account, hash, force) => permitStore.removePermit(chainId, account, hash, force);
2369
+ var removeActivePermit = async (chainId, account) => permitStore.removeActivePermitHash(chainId, account);
2370
+ var permits = {
2371
+ getSnapshot: permitStore.store.getState,
2372
+ subscribe: permitStore.store.subscribe,
2373
+ createSelf,
2374
+ createSharing,
2375
+ importShared,
2376
+ getOrCreateSelfPermit,
2377
+ getOrCreateSharingPermit,
2378
+ getHash,
2379
+ serialize,
2380
+ deserialize,
2381
+ getPermit: getPermit2,
2382
+ getPermits: getPermits2,
2383
+ getActivePermit: getActivePermit2,
2384
+ getActivePermitHash: getActivePermitHash2,
2385
+ removePermit: removePermit2,
2386
+ selectActivePermit,
2387
+ removeActivePermit
2388
+ };
2389
+ function uint160ToAddress(uint160) {
2390
+ const hexStr = uint160.toString(16).padStart(40, "0");
2391
+ return viem.getAddress("0x" + hexStr);
2392
+ }
2393
+ var isValidUtype = (utype) => {
2394
+ return utype === 0 /* Bool */ || utype === 7 /* Uint160 */ || utype == null || FheUintUTypes.includes(utype);
2395
+ };
2396
+ var convertViaUtype = (utype, value) => {
2397
+ if (utype === 0 /* Bool */) {
2398
+ return !!value;
2399
+ } else if (utype === 7 /* Uint160 */) {
2400
+ return uint160ToAddress(value);
2401
+ } else if (utype == null || FheUintUTypes.includes(utype)) {
2402
+ return value;
2403
+ } else {
2404
+ throw new Error(`convertViaUtype :: invalid utype :: ${utype}`);
2405
+ }
2406
+ };
2407
+
2408
+ // core/decrypt/MockQueryDecrypterAbi.ts
2409
+ var MockQueryDecrypterAbi = [
2410
+ {
2411
+ type: "function",
2412
+ name: "acl",
2413
+ inputs: [],
2414
+ outputs: [{ name: "", type: "address", internalType: "contract ACL" }],
2415
+ stateMutability: "view"
2416
+ },
2417
+ {
2418
+ type: "function",
2419
+ name: "decodeLowLevelReversion",
2420
+ inputs: [{ name: "data", type: "bytes", internalType: "bytes" }],
2421
+ outputs: [{ name: "error", type: "string", internalType: "string" }],
2422
+ stateMutability: "pure"
2423
+ },
2424
+ {
2425
+ type: "function",
2426
+ name: "exists",
2427
+ inputs: [],
2428
+ outputs: [{ name: "", type: "bool", internalType: "bool" }],
2429
+ stateMutability: "pure"
2430
+ },
2431
+ {
2432
+ type: "function",
2433
+ name: "initialize",
2434
+ inputs: [
2435
+ { name: "_taskManager", type: "address", internalType: "address" },
2436
+ { name: "_acl", type: "address", internalType: "address" }
2437
+ ],
2438
+ outputs: [],
2439
+ stateMutability: "nonpayable"
2440
+ },
2441
+ {
2442
+ type: "function",
2443
+ name: "queryDecrypt",
2444
+ inputs: [
2445
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
2446
+ { name: "", type: "uint256", internalType: "uint256" },
2447
+ {
2448
+ name: "permission",
2449
+ type: "tuple",
2450
+ internalType: "struct Permission",
2451
+ components: [
2452
+ { name: "issuer", type: "address", internalType: "address" },
2453
+ { name: "expiration", type: "uint64", internalType: "uint64" },
2454
+ { name: "recipient", type: "address", internalType: "address" },
2455
+ { name: "validatorId", type: "uint256", internalType: "uint256" },
2456
+ {
2457
+ name: "validatorContract",
2458
+ type: "address",
2459
+ internalType: "address"
2460
+ },
2461
+ { name: "sealingKey", type: "bytes32", internalType: "bytes32" },
2462
+ { name: "issuerSignature", type: "bytes", internalType: "bytes" },
2463
+ { name: "recipientSignature", type: "bytes", internalType: "bytes" }
2464
+ ]
2465
+ }
2466
+ ],
2467
+ outputs: [
2468
+ { name: "allowed", type: "bool", internalType: "bool" },
2469
+ { name: "error", type: "string", internalType: "string" },
2470
+ { name: "", type: "uint256", internalType: "uint256" }
2471
+ ],
2472
+ stateMutability: "view"
2473
+ },
2474
+ {
2475
+ type: "function",
2476
+ name: "querySealOutput",
2477
+ inputs: [
2478
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
2479
+ { name: "", type: "uint256", internalType: "uint256" },
2480
+ {
2481
+ name: "permission",
2482
+ type: "tuple",
2483
+ internalType: "struct Permission",
2484
+ components: [
2485
+ { name: "issuer", type: "address", internalType: "address" },
2486
+ { name: "expiration", type: "uint64", internalType: "uint64" },
2487
+ { name: "recipient", type: "address", internalType: "address" },
2488
+ { name: "validatorId", type: "uint256", internalType: "uint256" },
2489
+ {
2490
+ name: "validatorContract",
2491
+ type: "address",
2492
+ internalType: "address"
2493
+ },
2494
+ { name: "sealingKey", type: "bytes32", internalType: "bytes32" },
2495
+ { name: "issuerSignature", type: "bytes", internalType: "bytes" },
2496
+ { name: "recipientSignature", type: "bytes", internalType: "bytes" }
2497
+ ]
2498
+ }
2499
+ ],
2500
+ outputs: [
2501
+ { name: "allowed", type: "bool", internalType: "bool" },
2502
+ { name: "error", type: "string", internalType: "string" },
2503
+ { name: "", type: "bytes32", internalType: "bytes32" }
2504
+ ],
2505
+ stateMutability: "view"
2506
+ },
2507
+ {
2508
+ type: "function",
2509
+ name: "seal",
2510
+ inputs: [
2511
+ { name: "input", type: "uint256", internalType: "uint256" },
2512
+ { name: "key", type: "bytes32", internalType: "bytes32" }
2513
+ ],
2514
+ outputs: [{ name: "", type: "bytes32", internalType: "bytes32" }],
2515
+ stateMutability: "pure"
2516
+ },
2517
+ {
2518
+ type: "function",
2519
+ name: "taskManager",
2520
+ inputs: [],
2521
+ outputs: [{ name: "", type: "address", internalType: "contract TaskManager" }],
2522
+ stateMutability: "view"
2523
+ },
2524
+ {
2525
+ type: "function",
2526
+ name: "unseal",
2527
+ inputs: [
2528
+ { name: "hashed", type: "bytes32", internalType: "bytes32" },
2529
+ { name: "key", type: "bytes32", internalType: "bytes32" }
2530
+ ],
2531
+ outputs: [{ name: "", type: "uint256", internalType: "uint256" }],
2532
+ stateMutability: "pure"
2533
+ },
2534
+ { type: "error", name: "NotAllowed", inputs: [] },
2535
+ { type: "error", name: "SealingKeyInvalid", inputs: [] },
2536
+ { type: "error", name: "SealingKeyMissing", inputs: [] }
2537
+ ];
2538
+
2539
+ // core/decrypt/cofheMocksSealOutput.ts
2540
+ var MockQueryDecrypterAddress = "0x0000000000000000000000000000000000000200";
2541
+ async function cofheMocksSealOutput(ctHash, utype, permit, publicClient, mocksSealOutputDelay) {
2542
+ if (mocksSealOutputDelay > 0)
2543
+ await sleep(mocksSealOutputDelay);
2544
+ const permission = PermitUtils.getPermission(permit, true);
2545
+ const permissionWithBigInts = {
2546
+ ...permission,
2547
+ expiration: BigInt(permission.expiration),
2548
+ validatorId: BigInt(permission.validatorId)
2549
+ };
2550
+ const [allowed, error, result] = await publicClient.readContract({
2551
+ address: MockQueryDecrypterAddress,
2552
+ abi: MockQueryDecrypterAbi,
2553
+ functionName: "querySealOutput",
2554
+ args: [ctHash, BigInt(utype), permissionWithBigInts]
2555
+ });
2556
+ if (error != "") {
2557
+ throw new CofhesdkError({
2558
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2559
+ message: `mocks querySealOutput call failed: ${error}`
2560
+ });
2561
+ }
2562
+ if (allowed == false) {
2563
+ throw new CofhesdkError({
2564
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2565
+ message: `mocks querySealOutput call failed: ACL Access Denied (NotAllowed)`
2566
+ });
2567
+ }
2568
+ const sealedBigInt = BigInt(result);
2569
+ const sealingKeyBigInt = BigInt(permission.sealingKey);
2570
+ const unsealed = sealedBigInt ^ sealingKeyBigInt;
2571
+ return unsealed;
2572
+ }
2573
+
2574
+ // core/decrypt/tnSealOutputV2.ts
2575
+ var POLL_INTERVAL_MS = 1e3;
2576
+ var POLL_TIMEOUT_MS = 5 * 60 * 1e3;
2577
+ function numberArrayToUint8Array(arr) {
2578
+ return new Uint8Array(arr);
2579
+ }
2580
+ function convertSealedData(sealed) {
2581
+ if (!sealed) {
2582
+ throw new CofhesdkError({
2583
+ code: "SEAL_OUTPUT_RETURNED_NULL" /* SealOutputReturnedNull */,
2584
+ message: "Sealed data is missing from completed response"
2585
+ });
2586
+ }
2587
+ return {
2588
+ data: numberArrayToUint8Array(sealed.data),
2589
+ public_key: numberArrayToUint8Array(sealed.public_key),
2590
+ nonce: numberArrayToUint8Array(sealed.nonce)
2591
+ };
2592
+ }
2593
+ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, permission) {
2594
+ const body = {
2595
+ ct_tempkey: ctHash.toString(16).padStart(64, "0"),
2596
+ host_chain_id: chainId,
2597
+ permit: permission
2598
+ };
2599
+ let response;
2600
+ try {
2601
+ response = await fetch(`${thresholdNetworkUrl}/v2/sealoutput`, {
2602
+ method: "POST",
2603
+ headers: {
2604
+ "Content-Type": "application/json"
2605
+ },
2606
+ body: JSON.stringify(body)
2607
+ });
2608
+ } catch (e) {
2609
+ throw new CofhesdkError({
2610
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2611
+ message: `sealOutput request failed`,
2612
+ hint: "Ensure the threshold network URL is valid and reachable.",
2613
+ cause: e instanceof Error ? e : void 0,
2614
+ context: {
2615
+ thresholdNetworkUrl,
2616
+ body
2617
+ }
2618
+ });
2619
+ }
2620
+ if (!response.ok) {
2621
+ let errorMessage = `HTTP ${response.status}`;
2622
+ try {
2623
+ const errorBody = await response.json();
2624
+ errorMessage = errorBody.error_message || errorBody.message || errorMessage;
2625
+ } catch {
2626
+ errorMessage = response.statusText || errorMessage;
2627
+ }
2628
+ throw new CofhesdkError({
2629
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2630
+ message: `sealOutput request failed: ${errorMessage}`,
2631
+ hint: "Check the threshold network URL and request parameters.",
2632
+ context: {
2633
+ thresholdNetworkUrl,
2634
+ status: response.status,
2635
+ statusText: response.statusText,
2636
+ body
2637
+ }
2638
+ });
2639
+ }
2640
+ let submitResponse;
2641
+ try {
2642
+ submitResponse = await response.json();
2643
+ } catch (e) {
2644
+ throw new CofhesdkError({
2645
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2646
+ message: `Failed to parse sealOutput submit response`,
2647
+ cause: e instanceof Error ? e : void 0,
2648
+ context: {
2649
+ thresholdNetworkUrl,
2650
+ body
2651
+ }
2652
+ });
2653
+ }
2654
+ if (!submitResponse.request_id) {
2655
+ throw new CofhesdkError({
2656
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2657
+ message: `sealOutput submit response missing request_id`,
2658
+ context: {
2659
+ thresholdNetworkUrl,
2660
+ body,
2661
+ submitResponse
2662
+ }
2663
+ });
2664
+ }
2665
+ return submitResponse.request_id;
2666
+ }
2667
+ async function pollSealOutputStatus(thresholdNetworkUrl, requestId) {
2668
+ const startTime = Date.now();
2669
+ let completed = false;
2670
+ while (!completed) {
2671
+ if (Date.now() - startTime > POLL_TIMEOUT_MS) {
2672
+ throw new CofhesdkError({
2673
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2674
+ message: `sealOutput polling timed out after ${POLL_TIMEOUT_MS}ms`,
2675
+ hint: "The request may still be processing. Try again later.",
2676
+ context: {
2677
+ thresholdNetworkUrl,
2678
+ requestId,
2679
+ timeoutMs: POLL_TIMEOUT_MS
2680
+ }
2681
+ });
2682
+ }
2683
+ let response;
2684
+ try {
2685
+ response = await fetch(`${thresholdNetworkUrl}/v2/sealoutput/${requestId}`, {
2686
+ method: "GET",
2687
+ headers: {
2688
+ "Content-Type": "application/json"
2689
+ }
2690
+ });
2691
+ } catch (e) {
2692
+ throw new CofhesdkError({
2693
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2694
+ message: `sealOutput status poll failed`,
2695
+ hint: "Ensure the threshold network URL is valid and reachable.",
2696
+ cause: e instanceof Error ? e : void 0,
2697
+ context: {
2698
+ thresholdNetworkUrl,
2699
+ requestId
2700
+ }
2701
+ });
2702
+ }
2703
+ if (response.status === 404) {
2704
+ throw new CofhesdkError({
2705
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2706
+ message: `sealOutput request not found: ${requestId}`,
2707
+ hint: "The request may have expired or been invalid.",
2708
+ context: {
2709
+ thresholdNetworkUrl,
2710
+ requestId
2711
+ }
2712
+ });
2713
+ }
2714
+ if (!response.ok) {
2715
+ let errorMessage = `HTTP ${response.status}`;
2716
+ try {
2717
+ const errorBody = await response.json();
2718
+ errorMessage = errorBody.error_message || errorBody.message || errorMessage;
2719
+ } catch {
2720
+ errorMessage = response.statusText || errorMessage;
2721
+ }
2722
+ throw new CofhesdkError({
2723
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2724
+ message: `sealOutput status poll failed: ${errorMessage}`,
2725
+ context: {
2726
+ thresholdNetworkUrl,
2727
+ requestId,
2728
+ status: response.status,
2729
+ statusText: response.statusText
2730
+ }
2731
+ });
2732
+ }
2733
+ let statusResponse;
2734
+ try {
2735
+ statusResponse = await response.json();
2736
+ } catch (e) {
2737
+ throw new CofhesdkError({
2738
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2739
+ message: `Failed to parse sealOutput status response`,
2740
+ cause: e instanceof Error ? e : void 0,
2741
+ context: {
2742
+ thresholdNetworkUrl,
2743
+ requestId
2744
+ }
2745
+ });
2746
+ }
2747
+ if (statusResponse.status === "COMPLETED") {
2748
+ if (statusResponse.is_succeed === false) {
2749
+ const errorMessage = statusResponse.error_message || "Unknown error";
2750
+ throw new CofhesdkError({
2751
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2752
+ message: `sealOutput request failed: ${errorMessage}`,
2753
+ context: {
2754
+ thresholdNetworkUrl,
2755
+ requestId,
2756
+ statusResponse
2757
+ }
2758
+ });
2759
+ }
2760
+ if (!statusResponse.sealed) {
2761
+ throw new CofhesdkError({
2762
+ code: "SEAL_OUTPUT_RETURNED_NULL" /* SealOutputReturnedNull */,
2763
+ message: `sealOutput request completed but returned no sealed data`,
2764
+ context: {
2765
+ thresholdNetworkUrl,
2766
+ requestId,
2767
+ statusResponse
2768
+ }
2769
+ });
2770
+ }
2771
+ return convertSealedData(statusResponse.sealed);
2772
+ }
2773
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
2774
+ }
2775
+ throw new CofhesdkError({
2776
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2777
+ message: "Polling loop exited unexpectedly",
2778
+ context: {
2779
+ thresholdNetworkUrl,
2780
+ requestId
2781
+ }
2782
+ });
2783
+ }
2784
+ async function tnSealOutputV2(ctHash, chainId, permission, thresholdNetworkUrl) {
2785
+ const requestId = await submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, permission);
2786
+ return await pollSealOutputStatus(thresholdNetworkUrl, requestId);
2787
+ }
2788
+
2789
+ // core/decrypt/decryptHandleBuilder.ts
2790
+ var DecryptHandlesBuilder = class extends BaseBuilder {
2791
+ ctHash;
2792
+ utype;
2793
+ permitHash;
2794
+ permit;
2795
+ constructor(params) {
2796
+ super({
2797
+ config: params.config,
2798
+ publicClient: params.publicClient,
2799
+ walletClient: params.walletClient,
2800
+ chainId: params.chainId,
2801
+ account: params.account,
2802
+ requireConnected: params.requireConnected
2803
+ });
2804
+ this.ctHash = params.ctHash;
2805
+ this.utype = params.utype;
2806
+ this.permitHash = params.permitHash;
2807
+ this.permit = params.permit;
2808
+ }
2809
+ /**
2810
+ * @param chainId - Chain to decrypt values from. Used to fetch the threshold network URL and use the correct permit.
2811
+ *
2812
+ * If not provided, the chainId will be fetched from the connected publicClient.
2813
+ *
2814
+ * Example:
2815
+ * ```typescript
2816
+ * const unsealed = await decryptHandle(ctHash, utype)
2817
+ * .setChainId(11155111)
2818
+ * .decrypt();
2819
+ * ```
2820
+ *
2821
+ * @returns The chainable DecryptHandlesBuilder instance.
2822
+ */
2823
+ setChainId(chainId) {
2824
+ this.chainId = chainId;
2825
+ return this;
2826
+ }
2827
+ getChainId() {
2828
+ return this.chainId;
2829
+ }
2830
+ /**
2831
+ * @param account - Account to decrypt values from. Used to fetch the correct permit.
2832
+ *
2833
+ * If not provided, the account will be fetched from the connected walletClient.
2834
+ *
2835
+ * Example:
2836
+ * ```typescript
2837
+ * const unsealed = await decryptHandle(ctHash, utype)
2838
+ * .setAccount('0x1234567890123456789012345678901234567890')
2839
+ * .decrypt();
2840
+ * ```
2841
+ *
2842
+ * @returns The chainable DecryptHandlesBuilder instance.
2843
+ */
2844
+ setAccount(account) {
2845
+ this.account = account;
2846
+ return this;
2847
+ }
2848
+ getAccount() {
2849
+ return this.account;
2850
+ }
2851
+ /**
2852
+ * @param permitHash - Permit hash to decrypt values from. Used to fetch the correct permit.
2853
+ *
2854
+ * If not provided, the active permit for the chainId and account will be used.
2855
+ * If `setPermit()` is called, it will be used regardless of chainId, account, or permitHash.
2856
+ *
2857
+ * Example:
2858
+ * ```typescript
2859
+ * const unsealed = await decryptHandle(ctHash, utype)
2860
+ * .setPermitHash('0x1234567890123456789012345678901234567890')
2861
+ * .decrypt();
2862
+ * ```
2863
+ *
2864
+ * @returns The chainable DecryptHandlesBuilder instance.
2865
+ */
2866
+ setPermitHash(permitHash) {
2867
+ this.permitHash = permitHash;
2868
+ return this;
2869
+ }
2870
+ getPermitHash() {
2871
+ return this.permitHash;
2872
+ }
2873
+ /**
2874
+ * @param permit - Permit to decrypt values with. If provided, it will be used regardless of chainId, account, or permitHash.
2875
+ *
2876
+ * If not provided, the permit will be determined by chainId, account, and permitHash.
2877
+ *
2878
+ * Example:
2879
+ * ```typescript
2880
+ * const unsealed = await decryptHandle(ctHash, utype)
2881
+ * .setPermit(permit)
2882
+ * .decrypt();
2883
+ * ```
2884
+ *
2885
+ * @returns The chainable DecryptHandlesBuilder instance.
2886
+ */
2887
+ setPermit(permit) {
2888
+ this.permit = permit;
2889
+ return this;
2890
+ }
2891
+ getPermit() {
2892
+ return this.permit;
2893
+ }
2894
+ async getThresholdNetworkUrl() {
2895
+ this.assertChainId();
2896
+ return getThresholdNetworkUrlOrThrow(this.config, this.chainId);
2897
+ }
2898
+ validateUtypeOrThrow() {
2899
+ if (!isValidUtype(this.utype))
2900
+ throw new CofhesdkError({
2901
+ code: "INVALID_UTYPE" /* InvalidUtype */,
2902
+ message: `Invalid utype to decrypt to`,
2903
+ context: {
2904
+ utype: this.utype
2905
+ }
2906
+ });
2907
+ }
2908
+ async getResolvedPermit() {
2909
+ if (this.permit)
2910
+ return this.permit;
2911
+ this.assertChainId();
2912
+ this.assertAccount();
2913
+ if (this.permitHash) {
2914
+ const permit2 = await permits.getPermit(this.chainId, this.account, this.permitHash);
2915
+ if (!permit2) {
2916
+ throw new CofhesdkError({
2917
+ code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
2918
+ message: `Permit with hash <${this.permitHash}> not found for account <${this.account}> and chainId <${this.chainId}>`,
2919
+ hint: "Ensure the permit exists and is valid.",
2920
+ context: {
2921
+ chainId: this.chainId,
2922
+ account: this.account,
2923
+ permitHash: this.permitHash
2924
+ }
2925
+ });
2926
+ }
2927
+ return permit2;
2928
+ }
2929
+ const permit = await permits.getActivePermit(this.chainId, this.account);
2930
+ if (!permit) {
2931
+ throw new CofhesdkError({
2932
+ code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
2933
+ message: `Active permit not found for chainId <${this.chainId}> and account <${this.account}>`,
2934
+ hint: "Ensure a permit exists for this account on this chain.",
2935
+ context: {
2936
+ chainId: this.chainId,
2937
+ account: this.account
2938
+ }
2939
+ });
2940
+ }
2941
+ return permit;
2942
+ }
2943
+ /**
2944
+ * On hardhat, interact with MockZkVerifier contract instead of CoFHE
2945
+ */
2946
+ async mocksSealOutput(permit) {
2947
+ this.assertPublicClient();
2948
+ const mocksSealOutputDelay = this.config.mocks.sealOutputDelay;
2949
+ return cofheMocksSealOutput(this.ctHash, this.utype, permit, this.publicClient, mocksSealOutputDelay);
2950
+ }
2951
+ /**
2952
+ * In the production context, perform a true decryption with the CoFHE coprocessor.
2953
+ */
2954
+ async productionSealOutput(permit) {
2955
+ this.assertChainId();
2956
+ this.assertPublicClient();
2957
+ const thresholdNetworkUrl = await this.getThresholdNetworkUrl();
2958
+ const permission = PermitUtils.getPermission(permit, true);
2959
+ const sealed = await tnSealOutputV2(this.ctHash, this.chainId, permission, thresholdNetworkUrl);
2960
+ return PermitUtils.unseal(permit, sealed);
2961
+ }
2962
+ /**
2963
+ * Final step of the decryption process. MUST BE CALLED LAST IN THE CHAIN.
2964
+ *
2965
+ * This will:
2966
+ * - Use a permit based on provided permit OR chainId + account + permitHash
2967
+ * - Check permit validity
2968
+ * - Call CoFHE `/sealoutput` with the permit, which returns a sealed (encrypted) item
2969
+ * - Unseal the sealed item with the permit
2970
+ * - Return the unsealed item
2971
+ *
2972
+ * Example:
2973
+ * ```typescript
2974
+ * const unsealed = await decryptHandle(ctHash, utype)
2975
+ * .setChainId(11155111) // optional
2976
+ * .setAccount('0x123...890') // optional
2977
+ * .decrypt(); // execute
2978
+ * ```
2979
+ *
2980
+ * @returns The unsealed item.
2981
+ */
2982
+ async decrypt() {
2983
+ this.validateUtypeOrThrow();
2984
+ const permit = await this.getResolvedPermit();
2985
+ PermitUtils.validate(permit);
2986
+ PermitUtils.isValid(permit);
2987
+ const chainId = permit._signedDomain.chainId;
2988
+ let unsealed;
2989
+ if (chainId === hardhat2.id) {
2990
+ unsealed = await this.mocksSealOutput(permit);
2991
+ } else {
2992
+ unsealed = await this.productionSealOutput(permit);
2993
+ }
2994
+ return convertViaUtype(this.utype, unsealed);
2995
+ }
2996
+ };
2997
+
2998
+ // core/client.ts
2999
+ var InitialConnectStore = {
3000
+ connected: false,
3001
+ connecting: false,
3002
+ connectError: void 0,
3003
+ chainId: void 0,
3004
+ account: void 0,
3005
+ publicClient: void 0,
3006
+ walletClient: void 0
3007
+ };
3008
+ function createCofhesdkClientBase(opts) {
3009
+ const keysStorage = createKeysStore(opts.config.fheKeyStorage);
3010
+ const connectStore = vanilla.createStore(() => InitialConnectStore);
3011
+ const updateConnectState = (partial) => {
3012
+ connectStore.setState((state) => ({ ...state, ...partial }));
3013
+ };
3014
+ const _requireConnected = () => {
3015
+ const state = connectStore.getState();
3016
+ const notConnected = !state.connected || !state.account || !state.chainId || !state.publicClient || !state.walletClient;
3017
+ if (notConnected) {
3018
+ throw new CofhesdkError({
3019
+ code: "NOT_CONNECTED" /* NotConnected */,
3020
+ message: "Client must be connected, account and chainId must be initialized",
3021
+ hint: "Ensure client.connect() has been called and awaited.",
3022
+ context: {
3023
+ connected: state.connected,
3024
+ account: state.account,
3025
+ chainId: state.chainId,
3026
+ publicClient: state.publicClient,
3027
+ walletClient: state.walletClient
3028
+ }
3029
+ });
3030
+ }
3031
+ };
3032
+ async function connect(publicClient, walletClient) {
3033
+ const state = connectStore.getState();
3034
+ if (state.connected && state.publicClient === publicClient && state.walletClient === walletClient)
3035
+ return;
3036
+ updateConnectState({
3037
+ ...InitialConnectStore,
3038
+ connecting: true
3039
+ });
3040
+ try {
3041
+ const chainId = await getPublicClientChainID(publicClient);
3042
+ const account = await getWalletClientAccount(walletClient);
3043
+ updateConnectState({
3044
+ connected: true,
3045
+ connecting: false,
3046
+ connectError: void 0,
3047
+ chainId,
3048
+ account,
3049
+ publicClient,
3050
+ walletClient
3051
+ });
3052
+ } catch (e) {
3053
+ updateConnectState({
3054
+ ...InitialConnectStore,
3055
+ connectError: e
3056
+ });
3057
+ throw e;
3058
+ }
3059
+ }
3060
+ function encryptInputs(inputs) {
3061
+ const state = connectStore.getState();
3062
+ return new EncryptInputsBuilder({
3063
+ inputs,
3064
+ account: state.account ?? void 0,
3065
+ chainId: state.chainId ?? void 0,
3066
+ config: opts.config,
3067
+ publicClient: state.publicClient ?? void 0,
3068
+ walletClient: state.walletClient ?? void 0,
3069
+ zkvWalletClient: opts.config._internal?.zkvWalletClient,
3070
+ tfhePublicKeyDeserializer: opts.tfhePublicKeyDeserializer,
3071
+ compactPkeCrsDeserializer: opts.compactPkeCrsDeserializer,
3072
+ zkBuilderAndCrsGenerator: opts.zkBuilderAndCrsGenerator,
3073
+ initTfhe: opts.initTfhe,
3074
+ zkProveWorkerFn: opts.zkProveWorkerFn,
3075
+ keysStorage,
3076
+ requireConnected: _requireConnected
3077
+ });
3078
+ }
3079
+ function decryptHandle(ctHash, utype) {
3080
+ const state = connectStore.getState();
3081
+ return new DecryptHandlesBuilder({
3082
+ ctHash,
3083
+ utype,
3084
+ chainId: state.chainId ?? void 0,
3085
+ account: state.account ?? void 0,
3086
+ config: opts.config,
3087
+ publicClient: state.publicClient ?? void 0,
3088
+ walletClient: state.walletClient ?? void 0,
3089
+ requireConnected: _requireConnected
3090
+ });
3091
+ }
3092
+ const _getChainIdAndAccount = (chainId, account) => {
3093
+ const state = connectStore.getState();
3094
+ const _chainId = chainId ?? state.chainId;
3095
+ const _account = account ?? state.account;
3096
+ if (_chainId == null || _account == null) {
3097
+ throw new CofhesdkError({
3098
+ code: "NOT_CONNECTED" /* NotConnected */,
3099
+ message: "ChainId or account not available.",
3100
+ hint: "Ensure client.connect() has been called, or provide chainId and account explicitly.",
3101
+ context: {
3102
+ chainId: _chainId,
3103
+ account: _account
3104
+ }
3105
+ });
3106
+ }
3107
+ return { chainId: _chainId, account: _account };
3108
+ };
3109
+ const clientPermits = {
3110
+ // Pass through store access
3111
+ getSnapshot: permits.getSnapshot,
3112
+ subscribe: permits.subscribe,
3113
+ // Creation methods (require connection)
3114
+ createSelf: async (options, clients) => {
3115
+ _requireConnected();
3116
+ const { publicClient, walletClient } = clients ?? connectStore.getState();
3117
+ return permits.createSelf(options, publicClient, walletClient);
3118
+ },
3119
+ createSharing: async (options, clients) => {
3120
+ _requireConnected();
3121
+ const { publicClient, walletClient } = clients ?? connectStore.getState();
3122
+ return permits.createSharing(options, publicClient, walletClient);
3123
+ },
3124
+ importShared: async (options, clients) => {
3125
+ _requireConnected();
3126
+ const { publicClient, walletClient } = clients ?? connectStore.getState();
3127
+ return permits.importShared(options, publicClient, walletClient);
3128
+ },
3129
+ // Get or create methods (require connection)
3130
+ getOrCreateSelfPermit: async (chainId, account, options) => {
3131
+ _requireConnected();
3132
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
3133
+ const { publicClient, walletClient } = connectStore.getState();
3134
+ return permits.getOrCreateSelfPermit(publicClient, walletClient, _chainId, _account, options);
3135
+ },
3136
+ getOrCreateSharingPermit: async (options, chainId, account) => {
3137
+ _requireConnected();
3138
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
3139
+ const { publicClient, walletClient } = connectStore.getState();
3140
+ return permits.getOrCreateSharingPermit(publicClient, walletClient, options, _chainId, _account);
3141
+ },
3142
+ // Retrieval methods (auto-fill chainId/account)
3143
+ getPermit: async (hash, chainId, account) => {
3144
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
3145
+ return permits.getPermit(_chainId, _account, hash);
3146
+ },
3147
+ getPermits: async (chainId, account) => {
3148
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
3149
+ return permits.getPermits(_chainId, _account);
3150
+ },
3151
+ getActivePermit: async (chainId, account) => {
3152
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
3153
+ return permits.getActivePermit(_chainId, _account);
3154
+ },
3155
+ getActivePermitHash: async (chainId, account) => {
3156
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
3157
+ return permits.getActivePermitHash(_chainId, _account);
3158
+ },
3159
+ // Mutation methods (auto-fill chainId/account)
3160
+ selectActivePermit: (hash, chainId, account) => {
3161
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
3162
+ return permits.selectActivePermit(_chainId, _account, hash);
3163
+ },
3164
+ removePermit: async (hash, chainId, account, force) => {
3165
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
3166
+ return permits.removePermit(_chainId, _account, hash, force);
3167
+ },
3168
+ removeActivePermit: async (chainId, account) => {
3169
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
3170
+ return permits.removeActivePermit(_chainId, _account);
3171
+ },
3172
+ // Utils (no context needed)
3173
+ getHash: permits.getHash,
3174
+ serialize: permits.serialize,
3175
+ deserialize: permits.deserialize
3176
+ };
3177
+ return {
3178
+ // Zustand reactive accessors (don't export store directly to prevent mutation)
3179
+ getSnapshot: connectStore.getState,
3180
+ subscribe: connectStore.subscribe,
3181
+ // flags (read-only: reflect snapshot)
3182
+ get connected() {
3183
+ return connectStore.getState().connected;
3184
+ },
3185
+ get connecting() {
3186
+ return connectStore.getState().connecting;
3187
+ },
3188
+ // config & platform-specific (read-only)
3189
+ config: opts.config,
3190
+ connect,
3191
+ encryptInputs,
3192
+ decryptHandle,
3193
+ permits: clientPermits
3194
+ // Add SDK-specific methods below that require connection
3195
+ // Example:
3196
+ // async encryptData(data: unknown) {
3197
+ // requireConnected();
3198
+ // // Use state.publicClient and state.walletClient for implementation
3199
+ // },
3200
+ };
3201
+ }
3202
+ var memoryStorage = {};
3203
+ var createNodeStorage = () => {
3204
+ return {
3205
+ getItem: async (name) => {
3206
+ try {
3207
+ const storageDir = path.join(process.env.HOME || process.env.USERPROFILE || ".", ".cofhesdk");
3208
+ await fs.promises.mkdir(storageDir, { recursive: true });
3209
+ const filePath = path.join(storageDir, `${name}.json`);
3210
+ const data = await fs.promises.readFile(filePath, "utf8").catch(() => null);
3211
+ return data ? JSON.parse(data) : null;
3212
+ } catch (e) {
3213
+ console.warn("Node.js filesystem modules not available, falling back to memory storage" + e);
3214
+ return memoryStorage[name] || null;
3215
+ }
3216
+ },
3217
+ setItem: async (name, value) => {
3218
+ try {
3219
+ const storageDir = path.join(process.env.HOME || process.env.USERPROFILE || ".", ".cofhesdk");
3220
+ await fs.promises.mkdir(storageDir, { recursive: true });
3221
+ const filePath = path.join(storageDir, `${name}.json`);
3222
+ await fs.promises.writeFile(filePath, JSON.stringify(value));
3223
+ } catch (e) {
3224
+ console.warn("Node.js filesystem modules not available, falling back to memory storage" + e);
3225
+ memoryStorage[name] = JSON.stringify(value);
3226
+ }
3227
+ },
3228
+ removeItem: async (name) => {
3229
+ try {
3230
+ const storageDir = path.join(process.env.HOME || process.env.USERPROFILE || ".", ".cofhesdk");
3231
+ const filePath = path.join(storageDir, `${name}.json`);
3232
+ await fs.promises.unlink(filePath).catch(() => {
3233
+ });
3234
+ } catch (e) {
3235
+ console.warn("Node.js filesystem modules not available, falling back to memory storage" + e);
3236
+ delete memoryStorage[name];
3237
+ }
3238
+ }
3239
+ };
3240
+ };
3241
+ var tfheInitialized = false;
3242
+ async function initTfhe() {
3243
+ if (tfheInitialized)
3244
+ return false;
3245
+ await nodeTfhe.init_panic_hook();
3246
+ tfheInitialized = true;
3247
+ return true;
3248
+ }
3249
+ var fromHexString2 = (hexString) => {
3250
+ const cleanString = hexString.length % 2 === 1 ? `0${hexString}` : hexString;
3251
+ const arr = cleanString.replace(/^0x/, "").match(/.{1,2}/g);
3252
+ if (!arr)
3253
+ return new Uint8Array();
3254
+ return new Uint8Array(arr.map((byte) => parseInt(byte, 16)));
3255
+ };
3256
+ var tfhePublicKeyDeserializer = (buff) => {
3257
+ nodeTfhe.TfheCompactPublicKey.deserialize(fromHexString2(buff));
3258
+ };
3259
+ var compactPkeCrsDeserializer = (buff) => {
3260
+ nodeTfhe.CompactPkeCrs.deserialize(fromHexString2(buff));
3261
+ };
3262
+ var zkBuilderAndCrsGenerator = (fhe, crs) => {
3263
+ const fhePublicKey = nodeTfhe.TfheCompactPublicKey.deserialize(fromHexString2(fhe));
3264
+ const zkBuilder = nodeTfhe.ProvenCompactCiphertextList.builder(fhePublicKey);
3265
+ const zkCrs = nodeTfhe.CompactPkeCrs.deserialize(fromHexString2(crs));
3266
+ return { zkBuilder, zkCrs };
3267
+ };
3268
+ function createCofhesdkConfig(config) {
3269
+ return createCofhesdkConfigBase({
3270
+ environment: "node",
3271
+ ...config,
3272
+ fheKeyStorage: config.fheKeyStorage === null ? null : config.fheKeyStorage ?? createNodeStorage()
3273
+ });
3274
+ }
3275
+ function createCofhesdkClient(config) {
3276
+ return createCofhesdkClientBase({
3277
+ config,
3278
+ zkBuilderAndCrsGenerator,
3279
+ tfhePublicKeyDeserializer,
3280
+ compactPkeCrsDeserializer,
3281
+ initTfhe
3282
+ });
3283
+ }
3284
+
3285
+ exports.createCofhesdkClient = createCofhesdkClient;
3286
+ exports.createCofhesdkConfig = createCofhesdkConfig;