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