@cofhe/sdk 0.0.0-alpha-20260409113701

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 (132) hide show
  1. package/CHANGELOG.md +146 -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 +429 -0
  27. package/core/client.ts +341 -0
  28. package/core/clientTypes.ts +119 -0
  29. package/core/config.test.ts +242 -0
  30. package/core/config.ts +225 -0
  31. package/core/consts.ts +22 -0
  32. package/core/decrypt/MockThresholdNetworkAbi.ts +179 -0
  33. package/core/decrypt/cofheMocksDecryptForTx.ts +84 -0
  34. package/core/decrypt/cofheMocksDecryptForView.ts +48 -0
  35. package/core/decrypt/decryptForTxBuilder.ts +359 -0
  36. package/core/decrypt/decryptForViewBuilder.ts +332 -0
  37. package/core/decrypt/decryptUtils.ts +28 -0
  38. package/core/decrypt/pollCallbacks.test.ts +194 -0
  39. package/core/decrypt/polling.ts +14 -0
  40. package/core/decrypt/tnDecryptUtils.ts +65 -0
  41. package/core/decrypt/tnDecryptV1.ts +171 -0
  42. package/core/decrypt/tnDecryptV2.ts +365 -0
  43. package/core/decrypt/tnSealOutputV1.ts +59 -0
  44. package/core/decrypt/tnSealOutputV2.ts +324 -0
  45. package/core/decrypt/verifyDecryptResult.ts +52 -0
  46. package/core/encrypt/MockZkVerifierAbi.ts +106 -0
  47. package/core/encrypt/cofheMocksZkVerifySign.ts +281 -0
  48. package/core/encrypt/encryptInputsBuilder.test.ts +747 -0
  49. package/core/encrypt/encryptInputsBuilder.ts +583 -0
  50. package/core/encrypt/encryptUtils.ts +67 -0
  51. package/core/encrypt/zkPackProveVerify.ts +335 -0
  52. package/core/error.ts +168 -0
  53. package/core/fetchKeys.test.ts +195 -0
  54. package/core/fetchKeys.ts +144 -0
  55. package/core/index.ts +106 -0
  56. package/core/keyStore.test.ts +226 -0
  57. package/core/keyStore.ts +154 -0
  58. package/core/permits.test.ts +493 -0
  59. package/core/permits.ts +201 -0
  60. package/core/types.ts +419 -0
  61. package/core/utils.ts +130 -0
  62. package/dist/adapters.cjs +88 -0
  63. package/dist/adapters.d.cts +14576 -0
  64. package/dist/adapters.d.ts +14576 -0
  65. package/dist/adapters.js +83 -0
  66. package/dist/chains.cjs +111 -0
  67. package/dist/chains.d.cts +121 -0
  68. package/dist/chains.d.ts +121 -0
  69. package/dist/chains.js +1 -0
  70. package/dist/chunk-36FBWLUS.js +3310 -0
  71. package/dist/chunk-7HLGHV67.js +990 -0
  72. package/dist/chunk-TBLR7NNE.js +102 -0
  73. package/dist/clientTypes-AVSCBet7.d.cts +998 -0
  74. package/dist/clientTypes-flH1ju82.d.ts +998 -0
  75. package/dist/core.cjs +4362 -0
  76. package/dist/core.d.cts +138 -0
  77. package/dist/core.d.ts +138 -0
  78. package/dist/core.js +3 -0
  79. package/dist/node.cjs +4225 -0
  80. package/dist/node.d.cts +22 -0
  81. package/dist/node.d.ts +22 -0
  82. package/dist/node.js +91 -0
  83. package/dist/permit-jRirYqFt.d.cts +376 -0
  84. package/dist/permit-jRirYqFt.d.ts +376 -0
  85. package/dist/permits.cjs +1025 -0
  86. package/dist/permits.d.cts +353 -0
  87. package/dist/permits.d.ts +353 -0
  88. package/dist/permits.js +1 -0
  89. package/dist/types-YiAC4gig.d.cts +33 -0
  90. package/dist/types-YiAC4gig.d.ts +33 -0
  91. package/dist/web.cjs +4434 -0
  92. package/dist/web.d.cts +42 -0
  93. package/dist/web.d.ts +42 -0
  94. package/dist/web.js +256 -0
  95. package/dist/zkProve.worker.cjs +93 -0
  96. package/dist/zkProve.worker.d.cts +2 -0
  97. package/dist/zkProve.worker.d.ts +2 -0
  98. package/dist/zkProve.worker.js +91 -0
  99. package/node/client.test.ts +159 -0
  100. package/node/config.test.ts +68 -0
  101. package/node/encryptInputs.test.ts +155 -0
  102. package/node/index.ts +97 -0
  103. package/node/storage.ts +51 -0
  104. package/package.json +121 -0
  105. package/permits/index.ts +68 -0
  106. package/permits/localstorage.test.ts +113 -0
  107. package/permits/onchain-utils.ts +221 -0
  108. package/permits/permit.test.ts +534 -0
  109. package/permits/permit.ts +386 -0
  110. package/permits/sealing.test.ts +84 -0
  111. package/permits/sealing.ts +131 -0
  112. package/permits/signature.ts +79 -0
  113. package/permits/store.test.ts +88 -0
  114. package/permits/store.ts +156 -0
  115. package/permits/test-utils.ts +28 -0
  116. package/permits/types.ts +204 -0
  117. package/permits/utils.ts +58 -0
  118. package/permits/validation.test.ts +361 -0
  119. package/permits/validation.ts +327 -0
  120. package/web/client.web.test.ts +159 -0
  121. package/web/config.web.test.ts +69 -0
  122. package/web/const.ts +2 -0
  123. package/web/encryptInputs.web.test.ts +172 -0
  124. package/web/index.ts +166 -0
  125. package/web/storage.ts +49 -0
  126. package/web/worker.builder.web.test.ts +148 -0
  127. package/web/worker.config.web.test.ts +329 -0
  128. package/web/worker.output.web.test.ts +84 -0
  129. package/web/workerManager.test.ts +80 -0
  130. package/web/workerManager.ts +214 -0
  131. package/web/workerManager.web.test.ts +114 -0
  132. package/web/zkProve.worker.ts +133 -0
package/dist/web.cjs ADDED
@@ -0,0 +1,4434 @@
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
+ var nacl__default = /*#__PURE__*/_interopDefault(nacl);
18
+ var init__default = /*#__PURE__*/_interopDefault(init);
19
+
20
+ // core/client.ts
21
+
22
+ // core/error.ts
23
+ var CofheError = class _CofheError extends Error {
24
+ code;
25
+ cause;
26
+ hint;
27
+ context;
28
+ constructor({ code, message, cause, hint, context }) {
29
+ const fullMessage = cause ? `${message} | Caused by: ${cause.message}` : message;
30
+ super(fullMessage);
31
+ this.name = "CofheError";
32
+ this.code = code;
33
+ this.cause = cause;
34
+ this.hint = hint;
35
+ this.context = context;
36
+ if (Error.captureStackTrace) {
37
+ Error.captureStackTrace(this, _CofheError);
38
+ }
39
+ }
40
+ /**
41
+ * Creates a CofheError from an unknown error
42
+ * If the error is a CofheError, it is returned unchanged, else a new CofheError is created
43
+ * If a wrapperError is provided, it is used to create the new CofheError, else a default is used
44
+ */
45
+ static fromError(error, wrapperError) {
46
+ if (isCofheError(error))
47
+ return error;
48
+ const cause = error instanceof Error ? error : new Error(`${error}`);
49
+ return new _CofheError({
50
+ code: wrapperError?.code ?? "INTERNAL_ERROR" /* InternalError */,
51
+ message: wrapperError?.message ?? "An internal error occurred",
52
+ hint: wrapperError?.hint,
53
+ context: wrapperError?.context,
54
+ cause
55
+ });
56
+ }
57
+ /**
58
+ * Serializes the error to JSON string with proper handling of Error objects
59
+ */
60
+ serialize() {
61
+ return bigintSafeJsonStringify({
62
+ name: this.name,
63
+ code: this.code,
64
+ message: this.message,
65
+ hint: this.hint,
66
+ context: this.context,
67
+ cause: this.cause ? {
68
+ name: this.cause.name,
69
+ message: this.cause.message,
70
+ stack: this.cause.stack
71
+ } : void 0,
72
+ stack: this.stack
73
+ });
74
+ }
75
+ /**
76
+ * Returns a human-readable string representation of the error
77
+ */
78
+ toString() {
79
+ const parts = [`${this.name} [${this.code}]: ${this.message}`];
80
+ if (this.hint) {
81
+ parts.push(`Hint: ${this.hint}`);
82
+ }
83
+ if (this.context && Object.keys(this.context).length > 0) {
84
+ parts.push(`Context: ${bigintSafeJsonStringify(this.context)}`);
85
+ }
86
+ if (this.stack) {
87
+ parts.push(`
88
+ Stack trace:`);
89
+ parts.push(this.stack);
90
+ }
91
+ if (this.cause) {
92
+ parts.push(`
93
+ Caused by: ${this.cause.name}: ${this.cause.message}`);
94
+ if (this.cause.stack) {
95
+ parts.push(this.cause.stack);
96
+ }
97
+ }
98
+ return parts.join("\n");
99
+ }
100
+ };
101
+ var bigintSafeJsonStringify = (value) => {
102
+ return JSON.stringify(value, (key, value2) => {
103
+ if (typeof value2 === "bigint") {
104
+ return `${value2}n`;
105
+ }
106
+ return value2;
107
+ });
108
+ };
109
+ var isCofheError = (error) => error instanceof CofheError;
110
+
111
+ // core/types.ts
112
+ var FheUintUTypes = [
113
+ 2 /* Uint8 */,
114
+ 3 /* Uint16 */,
115
+ 4 /* Uint32 */,
116
+ 5 /* Uint64 */,
117
+ 6 /* Uint128 */
118
+ // [U256-DISABLED]
119
+ // FheTypes.Uint256,
120
+ ];
121
+ var toHexString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
122
+ var toBigIntOrThrow = (value) => {
123
+ if (typeof value === "bigint") {
124
+ return value;
125
+ }
126
+ try {
127
+ return BigInt(value);
128
+ } catch (error) {
129
+ throw new Error("Invalid input: Unable to convert to bigint");
130
+ }
131
+ };
132
+ var validateBigIntInRange = (value, max, min = 0n) => {
133
+ if (typeof value !== "bigint") {
134
+ throw new Error("Value must be of type bigint");
135
+ }
136
+ if (value > max || value < min) {
137
+ throw new Error(`Value out of range: ${max} - ${min}, try a different uint type`);
138
+ }
139
+ };
140
+ var hexToBytes = (hex) => {
141
+ const bytes = new Uint8Array(hex.length / 2);
142
+ for (let i = 0; i < hex.length; i += 2) {
143
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
144
+ }
145
+ return bytes;
146
+ };
147
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
148
+ async function getPublicClientChainID(publicClient) {
149
+ let chainId = null;
150
+ try {
151
+ chainId = publicClient.chain?.id ?? await publicClient.getChainId();
152
+ } catch (e) {
153
+ throw new CofheError({
154
+ code: "PUBLIC_WALLET_GET_CHAIN_ID_FAILED" /* PublicWalletGetChainIdFailed */,
155
+ message: "getting chain ID from public client failed",
156
+ cause: e instanceof Error ? e : void 0
157
+ });
158
+ }
159
+ if (chainId === null) {
160
+ throw new CofheError({
161
+ code: "PUBLIC_WALLET_GET_CHAIN_ID_FAILED" /* PublicWalletGetChainIdFailed */,
162
+ message: "chain ID from public client is null"
163
+ });
164
+ }
165
+ return chainId;
166
+ }
167
+ async function getWalletClientAccount(walletClient) {
168
+ let address;
169
+ try {
170
+ address = walletClient.account?.address;
171
+ if (!address) {
172
+ address = (await walletClient.getAddresses())?.[0];
173
+ }
174
+ } catch (e) {
175
+ throw new CofheError({
176
+ code: "PUBLIC_WALLET_GET_ADDRESSES_FAILED" /* PublicWalletGetAddressesFailed */,
177
+ message: "getting address from wallet client failed",
178
+ cause: e instanceof Error ? e : void 0
179
+ });
180
+ }
181
+ if (!address) {
182
+ throw new CofheError({
183
+ code: "PUBLIC_WALLET_GET_ADDRESSES_FAILED" /* PublicWalletGetAddressesFailed */,
184
+ message: "address from wallet client is null"
185
+ });
186
+ }
187
+ return address;
188
+ }
189
+ function fheTypeToString(utype) {
190
+ switch (utype) {
191
+ case 0 /* Bool */:
192
+ return "bool";
193
+ case 1 /* Uint4 */:
194
+ return "uint4";
195
+ case 2 /* Uint8 */:
196
+ return "uint8";
197
+ case 3 /* Uint16 */:
198
+ return "uint16";
199
+ case 4 /* Uint32 */:
200
+ return "uint32";
201
+ case 5 /* Uint64 */:
202
+ return "uint64";
203
+ case 6 /* Uint128 */:
204
+ return "uint128";
205
+ case 7 /* Uint160 */:
206
+ return "uint160";
207
+ case 8 /* Uint256 */:
208
+ return "uint256";
209
+ case 9 /* Uint512 */:
210
+ return "uint512";
211
+ case 10 /* Uint1024 */:
212
+ return "uint1024";
213
+ case 11 /* Uint2048 */:
214
+ return "uint2048";
215
+ case 12 /* Uint2 */:
216
+ return "uint2";
217
+ case 13 /* Uint6 */:
218
+ return "uint6";
219
+ case 14 /* Uint10 */:
220
+ return "uint10";
221
+ default:
222
+ throw new Error(`Unknown FheType: ${utype}`);
223
+ }
224
+ }
225
+
226
+ // core/encrypt/zkPackProveVerify.ts
227
+ var MAX_UINT8 = 255n;
228
+ var MAX_UINT16 = 65535n;
229
+ var MAX_UINT32 = 4294967295n;
230
+ var MAX_UINT64 = 18446744073709551615n;
231
+ var MAX_UINT128 = 340282366920938463463374607431768211455n;
232
+ var MAX_UINT160 = 1461501637330902918203684832716283019655932542975n;
233
+ var MAX_ENCRYPTABLE_BITS = 2048;
234
+ var zkPack = (items, builder) => {
235
+ let totalBits = 0;
236
+ for (const item of items) {
237
+ switch (item.utype) {
238
+ case 0 /* Bool */: {
239
+ builder.push_boolean(item.data);
240
+ totalBits += 1;
241
+ break;
242
+ }
243
+ case 2 /* Uint8 */: {
244
+ const bint = toBigIntOrThrow(item.data);
245
+ validateBigIntInRange(bint, MAX_UINT8);
246
+ builder.push_u8(parseInt(bint.toString()));
247
+ totalBits += 8;
248
+ break;
249
+ }
250
+ case 3 /* Uint16 */: {
251
+ const bint = toBigIntOrThrow(item.data);
252
+ validateBigIntInRange(bint, MAX_UINT16);
253
+ builder.push_u16(parseInt(bint.toString()));
254
+ totalBits += 16;
255
+ break;
256
+ }
257
+ case 4 /* Uint32 */: {
258
+ const bint = toBigIntOrThrow(item.data);
259
+ validateBigIntInRange(bint, MAX_UINT32);
260
+ builder.push_u32(parseInt(bint.toString()));
261
+ totalBits += 32;
262
+ break;
263
+ }
264
+ case 5 /* Uint64 */: {
265
+ const bint = toBigIntOrThrow(item.data);
266
+ validateBigIntInRange(bint, MAX_UINT64);
267
+ builder.push_u64(bint);
268
+ totalBits += 64;
269
+ break;
270
+ }
271
+ case 6 /* Uint128 */: {
272
+ const bint = toBigIntOrThrow(item.data);
273
+ validateBigIntInRange(bint, MAX_UINT128);
274
+ builder.push_u128(bint);
275
+ totalBits += 128;
276
+ break;
277
+ }
278
+ case 7 /* Uint160 */: {
279
+ const bint = toBigIntOrThrow(item.data);
280
+ validateBigIntInRange(bint, MAX_UINT160);
281
+ builder.push_u160(bint);
282
+ totalBits += 160;
283
+ break;
284
+ }
285
+ default: {
286
+ throw new CofheError({
287
+ code: "ZK_PACK_FAILED" /* ZkPackFailed */,
288
+ message: `Invalid utype: ${item.utype}`,
289
+ hint: `Ensure that the utype is valid, using the Encryptable type, for example: Encryptable.uint128(100n)`,
290
+ context: {
291
+ item
292
+ }
293
+ });
294
+ }
295
+ }
296
+ }
297
+ if (totalBits > MAX_ENCRYPTABLE_BITS) {
298
+ throw new CofheError({
299
+ code: "ZK_PACK_FAILED" /* ZkPackFailed */,
300
+ message: `Total bits ${totalBits} exceeds ${MAX_ENCRYPTABLE_BITS}`,
301
+ hint: `Ensure that the total bits of the items to encrypt does not exceed ${MAX_ENCRYPTABLE_BITS}`,
302
+ context: {
303
+ totalBits,
304
+ maxBits: MAX_ENCRYPTABLE_BITS,
305
+ items
306
+ }
307
+ });
308
+ }
309
+ return builder;
310
+ };
311
+ var zkProveWithWorker = async (workerFn, fheKeyHex, crsHex, items, metadata) => {
312
+ return await workerFn(fheKeyHex, crsHex, items, metadata);
313
+ };
314
+ var zkProve = async (builder, crs, metadata) => {
315
+ return new Promise((resolve) => {
316
+ setTimeout(() => {
317
+ const compactList = builder.build_with_proof_packed(
318
+ crs,
319
+ metadata,
320
+ 1
321
+ // ZkComputeLoad.Verify
322
+ );
323
+ resolve(compactList.serialize());
324
+ }, 0);
325
+ });
326
+ };
327
+ var constructZkPoKMetadata = (accountAddr, securityZone, chainId) => {
328
+ const accountAddrNoPrefix = accountAddr.startsWith("0x") ? accountAddr.slice(2) : accountAddr;
329
+ const accountBytes = hexToBytes(accountAddrNoPrefix);
330
+ const chainIdBytes = new Uint8Array(32);
331
+ let value = chainId;
332
+ for (let i = 31; i >= 0 && value > 0; i--) {
333
+ chainIdBytes[i] = value & 255;
334
+ value = value >>> 8;
335
+ }
336
+ const metadata = new Uint8Array(1 + accountBytes.length + 32);
337
+ metadata[0] = securityZone;
338
+ metadata.set(accountBytes, 1);
339
+ metadata.set(chainIdBytes, 1 + accountBytes.length);
340
+ return metadata;
341
+ };
342
+ var zkVerify = async (verifierUrl, serializedBytes, address, securityZone, chainId) => {
343
+ const packed_list = toHexString(serializedBytes);
344
+ const sz_byte = new Uint8Array([securityZone]);
345
+ const payload = {
346
+ packed_list,
347
+ account_addr: address,
348
+ security_zone: sz_byte[0],
349
+ chain_id: chainId
350
+ };
351
+ const body = JSON.stringify(payload);
352
+ try {
353
+ const response = await fetch(`${verifierUrl}/verify`, {
354
+ method: "POST",
355
+ headers: {
356
+ "Content-Type": "application/json"
357
+ },
358
+ body
359
+ });
360
+ if (!response.ok) {
361
+ const errorBody = await response.text();
362
+ throw new CofheError({
363
+ code: "ZK_VERIFY_FAILED" /* ZkVerifyFailed */,
364
+ message: `HTTP error! ZK proof verification failed - ${errorBody}`
365
+ });
366
+ }
367
+ const json = await response.json();
368
+ if (json.status !== "success") {
369
+ throw new CofheError({
370
+ code: "ZK_VERIFY_FAILED" /* ZkVerifyFailed */,
371
+ message: `ZK proof verification response malformed - ${json.error}`
372
+ });
373
+ }
374
+ return json.data.map(({ ct_hash, signature, recid }) => {
375
+ return {
376
+ ct_hash,
377
+ signature: concatSigRecid(signature, recid)
378
+ };
379
+ });
380
+ } catch (e) {
381
+ throw new CofheError({
382
+ code: "ZK_VERIFY_FAILED" /* ZkVerifyFailed */,
383
+ message: `ZK proof verification failed`,
384
+ cause: e instanceof Error ? e : void 0
385
+ });
386
+ }
387
+ };
388
+ var concatSigRecid = (signature, recid) => {
389
+ return signature + (recid + 27).toString(16).padStart(2, "0");
390
+ };
391
+
392
+ // core/encrypt/MockZkVerifierAbi.ts
393
+ var MockZkVerifierAbi = [
394
+ {
395
+ type: "function",
396
+ name: "exists",
397
+ inputs: [],
398
+ outputs: [{ name: "", type: "bool", internalType: "bool" }],
399
+ stateMutability: "pure"
400
+ },
401
+ {
402
+ type: "function",
403
+ name: "insertCtHash",
404
+ inputs: [
405
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
406
+ { name: "value", type: "uint256", internalType: "uint256" }
407
+ ],
408
+ outputs: [],
409
+ stateMutability: "nonpayable"
410
+ },
411
+ {
412
+ type: "function",
413
+ name: "insertPackedCtHashes",
414
+ inputs: [
415
+ { name: "ctHashes", type: "uint256[]", internalType: "uint256[]" },
416
+ { name: "values", type: "uint256[]", internalType: "uint256[]" }
417
+ ],
418
+ outputs: [],
419
+ stateMutability: "nonpayable"
420
+ },
421
+ {
422
+ type: "function",
423
+ name: "zkVerify",
424
+ inputs: [
425
+ { name: "value", type: "uint256", internalType: "uint256" },
426
+ { name: "utype", type: "uint8", internalType: "uint8" },
427
+ { name: "user", type: "address", internalType: "address" },
428
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
429
+ { name: "", type: "uint256", internalType: "uint256" }
430
+ ],
431
+ outputs: [
432
+ {
433
+ name: "",
434
+ type: "tuple",
435
+ internalType: "struct EncryptedInput",
436
+ components: [
437
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
438
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
439
+ { name: "utype", type: "uint8", internalType: "uint8" },
440
+ { name: "signature", type: "bytes", internalType: "bytes" }
441
+ ]
442
+ }
443
+ ],
444
+ stateMutability: "nonpayable"
445
+ },
446
+ {
447
+ type: "function",
448
+ name: "zkVerifyCalcCtHash",
449
+ inputs: [
450
+ { name: "value", type: "uint256", internalType: "uint256" },
451
+ { name: "utype", type: "uint8", internalType: "uint8" },
452
+ { name: "user", type: "address", internalType: "address" },
453
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
454
+ { name: "", type: "uint256", internalType: "uint256" }
455
+ ],
456
+ outputs: [{ name: "ctHash", type: "uint256", internalType: "uint256" }],
457
+ stateMutability: "view"
458
+ },
459
+ {
460
+ type: "function",
461
+ name: "zkVerifyCalcCtHashesPacked",
462
+ inputs: [
463
+ { name: "values", type: "uint256[]", internalType: "uint256[]" },
464
+ { name: "utypes", type: "uint8[]", internalType: "uint8[]" },
465
+ { name: "user", type: "address", internalType: "address" },
466
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
467
+ { name: "chainId", type: "uint256", internalType: "uint256" }
468
+ ],
469
+ outputs: [{ name: "ctHashes", type: "uint256[]", internalType: "uint256[]" }],
470
+ stateMutability: "view"
471
+ },
472
+ {
473
+ type: "function",
474
+ name: "zkVerifyPacked",
475
+ inputs: [
476
+ { name: "values", type: "uint256[]", internalType: "uint256[]" },
477
+ { name: "utypes", type: "uint8[]", internalType: "uint8[]" },
478
+ { name: "user", type: "address", internalType: "address" },
479
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
480
+ { name: "chainId", type: "uint256", internalType: "uint256" }
481
+ ],
482
+ outputs: [
483
+ {
484
+ name: "inputs",
485
+ type: "tuple[]",
486
+ internalType: "struct EncryptedInput[]",
487
+ components: [
488
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
489
+ { name: "securityZone", type: "uint8", internalType: "uint8" },
490
+ { name: "utype", type: "uint8", internalType: "uint8" },
491
+ { name: "signature", type: "bytes", internalType: "bytes" }
492
+ ]
493
+ }
494
+ ],
495
+ stateMutability: "nonpayable"
496
+ },
497
+ { type: "error", name: "InvalidInputs", inputs: [] }
498
+ ];
499
+
500
+ // core/consts.ts
501
+ var TASK_MANAGER_ADDRESS = "0xeA30c4B8b44078Bbf8a6ef5b9f1eC1626C7848D9";
502
+ var MOCKS_ZK_VERIFIER_ADDRESS = "0x0000000000000000000000000000000000005001";
503
+ var MOCKS_THRESHOLD_NETWORK_ADDRESS = "0x0000000000000000000000000000000000005002";
504
+ var MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY = "0x6C8D7F768A6BB4AAFE85E8A2F5A9680355239C7E14646ED62B044E39DE154512";
505
+ var MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY = "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d";
506
+
507
+ // core/encrypt/cofheMocksZkVerifySign.ts
508
+ function createMockZkVerifierSigner() {
509
+ return viem.createWalletClient({
510
+ chain: chains.hardhat,
511
+ transport: viem.http(),
512
+ account: accounts.privateKeyToAccount(MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY)
513
+ });
514
+ }
515
+ async function cofheMocksCheckEncryptableBits(items) {
516
+ let totalBits = 0;
517
+ for (const item of items) {
518
+ switch (item.utype) {
519
+ case 0 /* Bool */: {
520
+ totalBits += 1;
521
+ break;
522
+ }
523
+ case 2 /* Uint8 */: {
524
+ totalBits += 8;
525
+ break;
526
+ }
527
+ case 3 /* Uint16 */: {
528
+ totalBits += 16;
529
+ break;
530
+ }
531
+ case 4 /* Uint32 */: {
532
+ totalBits += 32;
533
+ break;
534
+ }
535
+ case 5 /* Uint64 */: {
536
+ totalBits += 64;
537
+ break;
538
+ }
539
+ case 6 /* Uint128 */: {
540
+ totalBits += 128;
541
+ break;
542
+ }
543
+ case 7 /* Uint160 */: {
544
+ totalBits += 160;
545
+ break;
546
+ }
547
+ }
548
+ }
549
+ if (totalBits > MAX_ENCRYPTABLE_BITS) {
550
+ throw new CofheError({
551
+ code: "ZK_PACK_FAILED" /* ZkPackFailed */,
552
+ message: `Total bits ${totalBits} exceeds ${MAX_ENCRYPTABLE_BITS}`,
553
+ hint: `Ensure that the total bits of the items to encrypt does not exceed ${MAX_ENCRYPTABLE_BITS}`,
554
+ context: {
555
+ totalBits,
556
+ maxBits: MAX_ENCRYPTABLE_BITS,
557
+ items
558
+ }
559
+ });
560
+ }
561
+ }
562
+ async function calcCtHashes(items, account, securityZone, publicClient) {
563
+ const calcCtHashesArgs = [
564
+ items.map(({ data }) => BigInt(data)),
565
+ items.map(({ utype }) => utype),
566
+ account,
567
+ securityZone,
568
+ BigInt(chains.hardhat.id)
569
+ ];
570
+ let ctHashes;
571
+ try {
572
+ ctHashes = await publicClient.readContract({
573
+ address: MOCKS_ZK_VERIFIER_ADDRESS,
574
+ abi: MockZkVerifierAbi,
575
+ functionName: "zkVerifyCalcCtHashesPacked",
576
+ args: calcCtHashesArgs
577
+ });
578
+ } catch (err) {
579
+ throw new CofheError({
580
+ code: "ZK_MOCKS_CALC_CT_HASHES_FAILED" /* ZkMocksCalcCtHashesFailed */,
581
+ message: `mockZkVerifySign calcCtHashes failed while calling zkVerifyCalcCtHashesPacked`,
582
+ cause: err instanceof Error ? err : void 0,
583
+ context: {
584
+ address: MOCKS_ZK_VERIFIER_ADDRESS,
585
+ items,
586
+ account,
587
+ securityZone,
588
+ publicClient,
589
+ calcCtHashesArgs
590
+ }
591
+ });
592
+ }
593
+ if (ctHashes.length !== items.length) {
594
+ throw new CofheError({
595
+ code: "ZK_MOCKS_CALC_CT_HASHES_FAILED" /* ZkMocksCalcCtHashesFailed */,
596
+ message: `mockZkVerifySign calcCtHashes returned incorrect number of ctHashes`,
597
+ context: {
598
+ items,
599
+ account,
600
+ securityZone,
601
+ publicClient,
602
+ calcCtHashesArgs,
603
+ ctHashes
604
+ }
605
+ });
606
+ }
607
+ return items.map((item, index) => ({
608
+ ...item,
609
+ ctHash: ctHashes[index]
610
+ }));
611
+ }
612
+ async function insertCtHashes(items, walletClient) {
613
+ const insertPackedCtHashesArgs = [items.map(({ ctHash }) => ctHash), items.map(({ data }) => BigInt(data))];
614
+ try {
615
+ const account = walletClient.account;
616
+ await walletClient.writeContract({
617
+ address: MOCKS_ZK_VERIFIER_ADDRESS,
618
+ abi: MockZkVerifierAbi,
619
+ functionName: "insertPackedCtHashes",
620
+ args: insertPackedCtHashesArgs,
621
+ chain: chains.hardhat,
622
+ account
623
+ });
624
+ } catch (err) {
625
+ throw new CofheError({
626
+ code: "ZK_MOCKS_INSERT_CT_HASHES_FAILED" /* ZkMocksInsertCtHashesFailed */,
627
+ message: `mockZkVerifySign insertPackedCtHashes failed while calling insertPackedCtHashes`,
628
+ cause: err instanceof Error ? err : void 0,
629
+ context: {
630
+ items,
631
+ walletClient,
632
+ insertPackedCtHashesArgs
633
+ }
634
+ });
635
+ }
636
+ }
637
+ async function createProofSignatures(items, securityZone, account) {
638
+ let signatures = [];
639
+ let encInputSignerClient;
640
+ try {
641
+ encInputSignerClient = createMockZkVerifierSigner();
642
+ } catch (err) {
643
+ throw new CofheError({
644
+ code: "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED" /* ZkMocksCreateProofSignatureFailed */,
645
+ message: `mockZkVerifySign createProofSignatures failed while creating wallet client`,
646
+ cause: err instanceof Error ? err : void 0,
647
+ context: {
648
+ MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY
649
+ }
650
+ });
651
+ }
652
+ try {
653
+ for (const item of items) {
654
+ const packedData = viem.encodePacked(
655
+ ["uint256", "uint8", "uint8", "address", "uint256"],
656
+ [BigInt(item.ctHash), item.utype, securityZone, account, BigInt(chains.hardhat.id)]
657
+ );
658
+ const messageHash = viem.keccak256(packedData);
659
+ const signature = await accounts.sign({
660
+ hash: messageHash,
661
+ privateKey: MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY,
662
+ to: "hex"
663
+ });
664
+ signatures.push(signature);
665
+ }
666
+ } catch (err) {
667
+ throw new CofheError({
668
+ code: "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED" /* ZkMocksCreateProofSignatureFailed */,
669
+ message: `mockZkVerifySign createProofSignatures failed while calling signMessage`,
670
+ cause: err instanceof Error ? err : void 0,
671
+ context: {
672
+ items,
673
+ securityZone
674
+ }
675
+ });
676
+ }
677
+ if (signatures.length !== items.length) {
678
+ throw new CofheError({
679
+ code: "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED" /* ZkMocksCreateProofSignatureFailed */,
680
+ message: `mockZkVerifySign createProofSignatures returned incorrect number of signatures`,
681
+ context: {
682
+ items,
683
+ securityZone
684
+ }
685
+ });
686
+ }
687
+ return signatures;
688
+ }
689
+ async function cofheMocksZkVerifySign(items, account, securityZone, publicClient, walletClient, zkvWalletClient) {
690
+ const _walletClient = zkvWalletClient ?? createMockZkVerifierSigner();
691
+ const encryptableItems = await calcCtHashes(items, account, securityZone, publicClient);
692
+ await insertCtHashes(encryptableItems, _walletClient);
693
+ const signatures = await createProofSignatures(encryptableItems, securityZone, account);
694
+ return encryptableItems.map((item, index) => ({
695
+ ct_hash: item.ctHash.toString(),
696
+ signature: signatures[index]
697
+ }));
698
+ }
699
+ var EnvironmentSchema = zod.z.enum(["MOCK", "TESTNET", "MAINNET"]);
700
+ var CofheChainSchema = zod.z.object({
701
+ /** Chain ID */
702
+ id: zod.z.number().int().positive(),
703
+ /** Human-readable chain name */
704
+ name: zod.z.string().min(1),
705
+ /** Network identifier */
706
+ network: zod.z.string().min(1),
707
+ /** coFhe service URL */
708
+ coFheUrl: zod.z.url(),
709
+ /** Verifier service URL */
710
+ verifierUrl: zod.z.url(),
711
+ /** Threshold network service URL */
712
+ thresholdNetworkUrl: zod.z.url(),
713
+ /** Environment type */
714
+ environment: EnvironmentSchema
715
+ });
716
+ function defineChain(chainConfig) {
717
+ const result = CofheChainSchema.safeParse(chainConfig);
718
+ if (!result.success) {
719
+ throw new Error(`Invalid chain configuration: ${zod.z.prettifyError(result.error)}`, { cause: result.error });
720
+ }
721
+ return result.data;
722
+ }
723
+
724
+ // chains/chains/hardhat.ts
725
+ var hardhat2 = defineChain({
726
+ id: 31337,
727
+ name: "Hardhat",
728
+ network: "localhost",
729
+ // These are unused in the mock environment
730
+ coFheUrl: "http://127.0.0.1:8448",
731
+ verifierUrl: "http://127.0.0.1:3001",
732
+ thresholdNetworkUrl: "http://127.0.0.1:3000",
733
+ environment: "MOCK"
734
+ });
735
+ var CofheConfigSchema = zod.z.object({
736
+ /** Environment that the SDK is running in */
737
+ environment: zod.z.enum(["node", "hardhat", "web", "react"]).optional().default("node"),
738
+ /** List of supported chain configurations */
739
+ supportedChains: zod.z.array(zod.z.custom()),
740
+ /** Default permit expiration in seconds, default is 30 days */
741
+ defaultPermitExpiration: zod.z.number().optional().default(60 * 60 * 24 * 30),
742
+ /** Storage method for fhe keys (defaults to indexedDB on web, filesystem on node) */
743
+ fheKeyStorage: zod.z.object({
744
+ getItem: zod.z.custom((val) => typeof val === "function", {
745
+ message: "getItem must be a function"
746
+ }),
747
+ setItem: zod.z.custom((val) => typeof val === "function", {
748
+ message: "setItem must be a function"
749
+ }),
750
+ removeItem: zod.z.custom((val) => typeof val === "function", {
751
+ message: "removeItem must be a function"
752
+ })
753
+ }).or(zod.z.null()).default(null),
754
+ /** Whether to use Web Workers for ZK proof generation (web platform only) */
755
+ useWorkers: zod.z.boolean().optional().default(true),
756
+ /** Mocks configs */
757
+ mocks: zod.z.object({
758
+ decryptDelay: zod.z.number().optional().default(0),
759
+ encryptDelay: zod.z.union([zod.z.number(), zod.z.tuple([zod.z.number(), zod.z.number(), zod.z.number(), zod.z.number(), zod.z.number()])]).optional().default([100, 100, 100, 500, 500])
760
+ }).optional().default({ decryptDelay: 0, encryptDelay: [100, 100, 100, 500, 500] }),
761
+ /** Internal configuration */
762
+ _internal: zod.z.object({
763
+ zkvWalletClient: zod.z.any().optional()
764
+ }).optional()
765
+ });
766
+ function createCofheConfigBase(config) {
767
+ const result = CofheConfigSchema.safeParse(config);
768
+ if (!result.success) {
769
+ throw new Error(`Invalid cofhe configuration: ${zod.z.prettifyError(result.error)}`, { cause: result.error });
770
+ }
771
+ return result.data;
772
+ }
773
+ function getSupportedChainOrThrow(config, chainId) {
774
+ const supportedChain = config.supportedChains.find((chain) => chain.id === chainId);
775
+ if (!supportedChain) {
776
+ throw new CofheError({
777
+ code: "UNSUPPORTED_CHAIN" /* UnsupportedChain */,
778
+ message: `Config does not support chain <${chainId}>`,
779
+ hint: "Ensure config passed to client has been created with this chain in the config.supportedChains array.",
780
+ context: {
781
+ chainId,
782
+ supportedChainIds: config.supportedChains.map((c) => c.id)
783
+ }
784
+ });
785
+ }
786
+ return supportedChain;
787
+ }
788
+ function getCoFheUrlOrThrow(config, chainId) {
789
+ const supportedChain = getSupportedChainOrThrow(config, chainId);
790
+ const url = supportedChain.coFheUrl;
791
+ if (!url) {
792
+ throw new CofheError({
793
+ code: "MISSING_CONFIG" /* MissingConfig */,
794
+ message: `CoFHE URL is not configured for chain <${chainId}>`,
795
+ hint: "Ensure this chain config includes a coFheUrl property.",
796
+ context: { chainId }
797
+ });
798
+ }
799
+ return url;
800
+ }
801
+ function getZkVerifierUrlOrThrow(config, chainId) {
802
+ const supportedChain = getSupportedChainOrThrow(config, chainId);
803
+ const url = supportedChain.verifierUrl;
804
+ if (!url) {
805
+ throw new CofheError({
806
+ code: "ZK_VERIFIER_URL_UNINITIALIZED" /* ZkVerifierUrlUninitialized */,
807
+ message: `ZK verifier URL is not configured for chain <${chainId}>`,
808
+ hint: "Ensure this chain config includes a verifierUrl property.",
809
+ context: { chainId }
810
+ });
811
+ }
812
+ return url;
813
+ }
814
+ function getThresholdNetworkUrlOrThrow(config, chainId) {
815
+ const supportedChain = getSupportedChainOrThrow(config, chainId);
816
+ const url = supportedChain.thresholdNetworkUrl;
817
+ if (!url) {
818
+ throw new CofheError({
819
+ code: "THRESHOLD_NETWORK_URL_UNINITIALIZED" /* ThresholdNetworkUrlUninitialized */,
820
+ message: `Threshold network URL is not configured for chain <${chainId}>`,
821
+ hint: "Ensure this chain config includes a thresholdNetworkUrl property.",
822
+ context: { chainId }
823
+ });
824
+ }
825
+ return url;
826
+ }
827
+ function isValidPersistedState(state) {
828
+ if (state && typeof state === "object") {
829
+ if ("fhe" in state && "crs" in state) {
830
+ return true;
831
+ } else {
832
+ throw new Error(
833
+ "Invalid persisted state structure for KeysStore. Is object but doesn't contain required fields 'fhe' and 'crs'."
834
+ );
835
+ }
836
+ }
837
+ return false;
838
+ }
839
+ var DEFAULT_KEYS_STORE = {
840
+ fhe: {},
841
+ crs: {}
842
+ };
843
+ function isStoreWithPersist(store) {
844
+ return "persist" in store;
845
+ }
846
+ function createKeysStore(storage) {
847
+ const keysStore = storage ? createStoreWithPersit(storage) : vanilla.createStore()(() => ({
848
+ fhe: {},
849
+ crs: {}
850
+ }));
851
+ const getFheKey = (chainId, securityZone = 0) => {
852
+ if (chainId == null || securityZone == null)
853
+ return void 0;
854
+ const stored = keysStore.getState().fhe[chainId]?.[securityZone];
855
+ return stored;
856
+ };
857
+ const getCrs = (chainId) => {
858
+ if (chainId == null)
859
+ return void 0;
860
+ const stored = keysStore.getState().crs[chainId];
861
+ return stored;
862
+ };
863
+ const setFheKey = (chainId, securityZone, key) => {
864
+ keysStore.setState(
865
+ immer.produce((state) => {
866
+ if (state.fhe[chainId] == null)
867
+ state.fhe[chainId] = {};
868
+ state.fhe[chainId][securityZone] = key;
869
+ })
870
+ );
871
+ };
872
+ const setCrs = (chainId, crs) => {
873
+ keysStore.setState(
874
+ immer.produce((state) => {
875
+ state.crs[chainId] = crs;
876
+ })
877
+ );
878
+ };
879
+ const clearKeysStorage = async () => {
880
+ if (storage) {
881
+ await storage.removeItem("cofhesdk-keys");
882
+ }
883
+ };
884
+ const rehydrateKeysStore = async () => {
885
+ if (!isStoreWithPersist(keysStore))
886
+ return;
887
+ if (keysStore.persist.hasHydrated())
888
+ return;
889
+ await keysStore.persist.rehydrate();
890
+ };
891
+ return {
892
+ store: keysStore,
893
+ getFheKey,
894
+ getCrs,
895
+ setFheKey,
896
+ setCrs,
897
+ clearKeysStorage,
898
+ rehydrateKeysStore
899
+ };
900
+ }
901
+ function createStoreWithPersit(storage) {
902
+ const result = vanilla.createStore()(
903
+ middleware.persist(() => DEFAULT_KEYS_STORE, {
904
+ // 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)
905
+ skipHydration: true,
906
+ // 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
907
+ onRehydrateStorage: () => (_state, _error) => {
908
+ if (_error)
909
+ throw new Error(`onRehydrateStorage: Error rehydrating keys store: ${_error}`);
910
+ },
911
+ name: "cofhesdk-keys",
912
+ storage: middleware.createJSONStorage(() => storage),
913
+ merge: (persistedState, currentState) => {
914
+ const persisted = isValidPersistedState(persistedState) ? persistedState : DEFAULT_KEYS_STORE;
915
+ const current = currentState;
916
+ const mergedFhe = { ...persisted.fhe };
917
+ const allChainIds = /* @__PURE__ */ new Set([...Object.keys(current.fhe), ...Object.keys(persisted.fhe)]);
918
+ for (const chainId of allChainIds) {
919
+ const persistedZones = persisted.fhe[chainId] || {};
920
+ const currentZones = current.fhe[chainId] || {};
921
+ mergedFhe[chainId] = { ...persistedZones, ...currentZones };
922
+ }
923
+ const mergedCrs = { ...persisted.crs, ...current.crs };
924
+ return {
925
+ fhe: mergedFhe,
926
+ crs: mergedCrs
927
+ };
928
+ }
929
+ })
930
+ );
931
+ return result;
932
+ }
933
+
934
+ // core/fetchKeys.ts
935
+ var PUBLIC_KEY_LENGTH_MIN = 15e3;
936
+ var checkKeyValidity = (key, serializer) => {
937
+ if (key == null || key.length === 0)
938
+ return [false, `Key is null or empty <${key}>`];
939
+ try {
940
+ serializer(key);
941
+ return [true, `Key is valid`];
942
+ } catch (err) {
943
+ return [false, `Serialization failed <${err}> key length <${key.length}>`];
944
+ }
945
+ };
946
+ var fetchFhePublicKey = async (coFheUrl, chainId, securityZone, tfhePublicKeyDeserializer2, keysStorage) => {
947
+ const storedKey = keysStorage?.getFheKey(chainId, securityZone);
948
+ const [storedKeyValid] = checkKeyValidity(storedKey, tfhePublicKeyDeserializer2);
949
+ if (storedKeyValid)
950
+ return [storedKey, false];
951
+ let pk_data = void 0;
952
+ try {
953
+ const pk_res = await fetch(`${coFheUrl}/GetNetworkPublicKey`, {
954
+ method: "POST",
955
+ headers: {
956
+ "Content-Type": "application/json"
957
+ },
958
+ body: JSON.stringify({ securityZone })
959
+ });
960
+ const json = await pk_res.json();
961
+ pk_data = json.publicKey;
962
+ } catch (err) {
963
+ throw new Error(`Error fetching FHE publicKey; fetching from CoFHE failed with error ${err}`);
964
+ }
965
+ if (pk_data == null || typeof pk_data !== "string") {
966
+ throw new Error(`Error fetching FHE publicKey; fetched result invalid: missing or not a string`);
967
+ }
968
+ if (pk_data === "0x") {
969
+ throw new Error("Error fetching FHE publicKey; provided chain is not FHE enabled / not found");
970
+ }
971
+ if (pk_data.length < PUBLIC_KEY_LENGTH_MIN) {
972
+ throw new Error(
973
+ `Error fetching FHE publicKey; got shorter than expected key length: ${pk_data.length}. Expected length >= ${PUBLIC_KEY_LENGTH_MIN}`
974
+ );
975
+ }
976
+ try {
977
+ tfhePublicKeyDeserializer2(pk_data);
978
+ } catch (err) {
979
+ throw new Error(`Error serializing FHE publicKey; ${err}`);
980
+ }
981
+ keysStorage?.setFheKey(chainId, securityZone, pk_data);
982
+ return [pk_data, true];
983
+ };
984
+ var fetchCrs = async (coFheUrl, chainId, securityZone, compactPkeCrsDeserializer2, keysStorage) => {
985
+ const storedKey = keysStorage?.getCrs(chainId);
986
+ const [storedKeyValid] = checkKeyValidity(storedKey, compactPkeCrsDeserializer2);
987
+ if (storedKeyValid)
988
+ return [storedKey, false];
989
+ let crs_data = void 0;
990
+ try {
991
+ const crs_res = await fetch(`${coFheUrl}/GetCrs`, {
992
+ method: "POST",
993
+ headers: {
994
+ "Content-Type": "application/json"
995
+ },
996
+ body: JSON.stringify({ securityZone })
997
+ });
998
+ const json = await crs_res.json();
999
+ crs_data = json.crs;
1000
+ } catch (err) {
1001
+ throw new Error(`Error fetching CRS; fetching failed with error ${err}`);
1002
+ }
1003
+ if (crs_data == null || typeof crs_data !== "string") {
1004
+ throw new Error(`Error fetching CRS; invalid: missing or not a string`);
1005
+ }
1006
+ try {
1007
+ compactPkeCrsDeserializer2(crs_data);
1008
+ } catch (err) {
1009
+ console.error(`Error serializing CRS ${err}`);
1010
+ throw new Error(`Error serializing CRS; ${err}`);
1011
+ }
1012
+ keysStorage?.setCrs(chainId, crs_data);
1013
+ return [crs_data, true];
1014
+ };
1015
+ var fetchKeys = async (config, chainId, securityZone = 0, tfhePublicKeyDeserializer2, compactPkeCrsDeserializer2, keysStorage) => {
1016
+ const coFheUrl = getCoFheUrlOrThrow(config, chainId);
1017
+ return await Promise.all([
1018
+ fetchFhePublicKey(coFheUrl, chainId, securityZone, tfhePublicKeyDeserializer2, keysStorage),
1019
+ fetchCrs(coFheUrl, chainId, securityZone, compactPkeCrsDeserializer2, keysStorage)
1020
+ ]);
1021
+ };
1022
+ var BaseBuilder = class {
1023
+ config;
1024
+ publicClient;
1025
+ walletClient;
1026
+ chainId;
1027
+ account;
1028
+ constructor(params) {
1029
+ if (!params.config) {
1030
+ throw new CofheError({
1031
+ code: "MISSING_CONFIG" /* MissingConfig */,
1032
+ message: "Builder config is undefined",
1033
+ hint: "Ensure client has been created with a config.",
1034
+ context: {
1035
+ config: params.config
1036
+ }
1037
+ });
1038
+ }
1039
+ this.config = params.config;
1040
+ this.publicClient = params.publicClient;
1041
+ this.walletClient = params.walletClient;
1042
+ this.chainId = params.chainId;
1043
+ this.account = params.account;
1044
+ params.requireConnected?.();
1045
+ }
1046
+ /**
1047
+ * Asserts that this.chainId is populated
1048
+ * @throws {CofheError} If chainId is not set
1049
+ */
1050
+ assertChainId() {
1051
+ if (this.chainId)
1052
+ return;
1053
+ throw new CofheError({
1054
+ code: "CHAIN_ID_UNINITIALIZED" /* ChainIdUninitialized */,
1055
+ message: "Chain ID is not set",
1056
+ hint: "Ensure client.connect() has been called and awaited, or use setChainId(...) to set the chainId explicitly.",
1057
+ context: {
1058
+ chainId: this.chainId
1059
+ }
1060
+ });
1061
+ }
1062
+ /**
1063
+ * Asserts that this.account is populated
1064
+ * @throws {CofheError} If account is not set
1065
+ */
1066
+ assertAccount() {
1067
+ if (this.account)
1068
+ return;
1069
+ throw new CofheError({
1070
+ code: "ACCOUNT_UNINITIALIZED" /* AccountUninitialized */,
1071
+ message: "Account is not set",
1072
+ hint: "Ensure client.connect() has been called and awaited, or use setAccount(...) to set the account explicitly.",
1073
+ context: {
1074
+ account: this.account
1075
+ }
1076
+ });
1077
+ }
1078
+ /**
1079
+ * Asserts that this.publicClient is populated
1080
+ * @throws {CofheError} If publicClient is not set
1081
+ */
1082
+ assertPublicClient() {
1083
+ if (this.publicClient)
1084
+ return;
1085
+ throw new CofheError({
1086
+ code: "MISSING_PUBLIC_CLIENT" /* MissingPublicClient */,
1087
+ message: "Public client not found",
1088
+ hint: "Ensure client.connect() has been called with a publicClient.",
1089
+ context: {
1090
+ publicClient: this.publicClient
1091
+ }
1092
+ });
1093
+ }
1094
+ /**
1095
+ * Asserts that this.walletClient is populated
1096
+ * @throws {CofheError} If walletClient is not set
1097
+ */
1098
+ assertWalletClient() {
1099
+ if (this.walletClient)
1100
+ return;
1101
+ throw new CofheError({
1102
+ code: "MISSING_WALLET_CLIENT" /* MissingWalletClient */,
1103
+ message: "Wallet client not found",
1104
+ hint: "Ensure client.connect() has been called with a walletClient.",
1105
+ context: {
1106
+ walletClient: this.walletClient
1107
+ }
1108
+ });
1109
+ }
1110
+ };
1111
+
1112
+ // core/encrypt/encryptInputsBuilder.ts
1113
+ var EncryptInputsBuilder = class extends BaseBuilder {
1114
+ securityZone;
1115
+ stepCallback;
1116
+ inputItems;
1117
+ zkvWalletClient;
1118
+ tfhePublicKeyDeserializer;
1119
+ compactPkeCrsDeserializer;
1120
+ zkBuilderAndCrsGenerator;
1121
+ initTfhe;
1122
+ zkProveWorkerFn;
1123
+ keysStorage;
1124
+ // Worker configuration (from config, overrideable)
1125
+ useWorker;
1126
+ stepTimestamps = {
1127
+ ["initTfhe" /* InitTfhe */]: 0,
1128
+ ["fetchKeys" /* FetchKeys */]: 0,
1129
+ ["pack" /* Pack */]: 0,
1130
+ ["prove" /* Prove */]: 0,
1131
+ ["verify" /* Verify */]: 0
1132
+ };
1133
+ constructor(params) {
1134
+ super({
1135
+ config: params.config,
1136
+ publicClient: params.publicClient,
1137
+ walletClient: params.walletClient,
1138
+ chainId: params.chainId,
1139
+ account: params.account,
1140
+ requireConnected: params.requireConnected
1141
+ });
1142
+ this.inputItems = params.inputs;
1143
+ this.securityZone = params.securityZone ?? 0;
1144
+ this.zkvWalletClient = params.zkvWalletClient;
1145
+ if (!params.tfhePublicKeyDeserializer) {
1146
+ throw new CofheError({
1147
+ code: "MISSING_TFHE_PUBLIC_KEY_DESERIALIZER" /* MissingTfhePublicKeyDeserializer */,
1148
+ message: "EncryptInputsBuilder tfhePublicKeyDeserializer is undefined",
1149
+ hint: "Ensure client has been created with a tfhePublicKeyDeserializer.",
1150
+ context: {
1151
+ tfhePublicKeyDeserializer: params.tfhePublicKeyDeserializer
1152
+ }
1153
+ });
1154
+ }
1155
+ this.tfhePublicKeyDeserializer = params.tfhePublicKeyDeserializer;
1156
+ if (!params.compactPkeCrsDeserializer) {
1157
+ throw new CofheError({
1158
+ code: "MISSING_COMPACT_PKE_CRS_DESERIALIZER" /* MissingCompactPkeCrsDeserializer */,
1159
+ message: "EncryptInputsBuilder compactPkeCrsDeserializer is undefined",
1160
+ hint: "Ensure client has been created with a compactPkeCrsDeserializer.",
1161
+ context: {
1162
+ compactPkeCrsDeserializer: params.compactPkeCrsDeserializer
1163
+ }
1164
+ });
1165
+ }
1166
+ this.compactPkeCrsDeserializer = params.compactPkeCrsDeserializer;
1167
+ if (!params.zkBuilderAndCrsGenerator) {
1168
+ throw new CofheError({
1169
+ code: "MISSING_ZK_BUILDER_AND_CRS_GENERATOR" /* MissingZkBuilderAndCrsGenerator */,
1170
+ message: "EncryptInputsBuilder zkBuilderAndCrsGenerator is undefined",
1171
+ hint: "Ensure client has been created with a zkBuilderAndCrsGenerator.",
1172
+ context: {
1173
+ zkBuilderAndCrsGenerator: params.zkBuilderAndCrsGenerator
1174
+ }
1175
+ });
1176
+ }
1177
+ this.zkBuilderAndCrsGenerator = params.zkBuilderAndCrsGenerator;
1178
+ this.initTfhe = params.initTfhe;
1179
+ this.zkProveWorkerFn = params.zkProveWorkerFn;
1180
+ this.keysStorage = params.keysStorage;
1181
+ this.useWorker = params.config?.useWorkers ?? true;
1182
+ }
1183
+ /**
1184
+ * @param account - Account that will create the tx using the encrypted inputs.
1185
+ *
1186
+ * If not provided, the account will be fetched from the connected walletClient.
1187
+ *
1188
+ * Example:
1189
+ * ```typescript
1190
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1191
+ * .setAccount("0x123")
1192
+ * .execute();
1193
+ * ```
1194
+ *
1195
+ * @returns The chainable EncryptInputsBuilder instance.
1196
+ */
1197
+ setAccount(account) {
1198
+ this.account = account;
1199
+ return this;
1200
+ }
1201
+ getAccount() {
1202
+ return this.account;
1203
+ }
1204
+ /**
1205
+ * @param chainId - Chain that will consume the encrypted inputs.
1206
+ *
1207
+ * If not provided, the chainId will be fetched from the connected publicClient.
1208
+ *
1209
+ * Example:
1210
+ * ```typescript
1211
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1212
+ * .setChainId(11155111)
1213
+ * .execute();
1214
+ * ```
1215
+ *
1216
+ * @returns The chainable EncryptInputsBuilder instance.
1217
+ */
1218
+ setChainId(chainId) {
1219
+ this.chainId = chainId;
1220
+ return this;
1221
+ }
1222
+ getChainId() {
1223
+ return this.chainId;
1224
+ }
1225
+ /**
1226
+ * @param securityZone - Security zone to encrypt the inputs for.
1227
+ *
1228
+ * If not provided, the default securityZone 0 will be used.
1229
+ *
1230
+ * Example:
1231
+ * ```typescript
1232
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1233
+ * .setSecurityZone(1)
1234
+ * .execute();
1235
+ * ```
1236
+ *
1237
+ * @returns The chainable EncryptInputsBuilder instance.
1238
+ */
1239
+ setSecurityZone(securityZone) {
1240
+ this.securityZone = securityZone;
1241
+ return this;
1242
+ }
1243
+ getSecurityZone() {
1244
+ return this.securityZone;
1245
+ }
1246
+ /**
1247
+ * @param useWorker - Whether to use Web Workers for ZK proof generation.
1248
+ *
1249
+ * Overrides the config-level useWorkers setting for this specific encryption.
1250
+ *
1251
+ * Example:
1252
+ * ```typescript
1253
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1254
+ * .setUseWorker(false)
1255
+ * .execute();
1256
+ * ```
1257
+ *
1258
+ * @returns The chainable EncryptInputsBuilder instance.
1259
+ */
1260
+ setUseWorker(useWorker) {
1261
+ this.useWorker = useWorker;
1262
+ return this;
1263
+ }
1264
+ /**
1265
+ * Gets the current worker configuration.
1266
+ *
1267
+ * @returns Whether Web Workers are enabled for this encryption.
1268
+ *
1269
+ * Example:
1270
+ * ```typescript
1271
+ * const builder = encryptInputs([Encryptable.uint128(10n)]);
1272
+ * console.log(builder.getUseWorker()); // true (from config)
1273
+ * builder.setUseWorker(false);
1274
+ * console.log(builder.getUseWorker()); // false (overridden)
1275
+ * ```
1276
+ */
1277
+ getUseWorker() {
1278
+ return this.useWorker;
1279
+ }
1280
+ /**
1281
+ * @param callback - Function to be called with the encryption step.
1282
+ *
1283
+ * Useful for debugging and tracking the progress of the encryption process.
1284
+ * Useful for a UI element that shows the progress of the encryption process.
1285
+ *
1286
+ * Example:
1287
+ * ```typescript
1288
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1289
+ * .onStep((step: EncryptStep) => console.log(step))
1290
+ * .execute();
1291
+ * ```
1292
+ *
1293
+ * @returns The EncryptInputsBuilder instance.
1294
+ */
1295
+ onStep(callback) {
1296
+ this.stepCallback = callback;
1297
+ return this;
1298
+ }
1299
+ getStepCallback() {
1300
+ return this.stepCallback;
1301
+ }
1302
+ /**
1303
+ * Fires the step callback if set
1304
+ */
1305
+ fireStepStart(step, context = {}) {
1306
+ if (!this.stepCallback)
1307
+ return;
1308
+ this.stepTimestamps[step] = Date.now();
1309
+ this.stepCallback(step, { ...context, isStart: true, isEnd: false, duration: 0 });
1310
+ }
1311
+ fireStepEnd(step, context = {}) {
1312
+ if (!this.stepCallback)
1313
+ return;
1314
+ const duration = Date.now() - this.stepTimestamps[step];
1315
+ this.stepCallback(step, { ...context, isStart: false, isEnd: true, duration });
1316
+ }
1317
+ /**
1318
+ * zkVerifierUrl is included in the chains exported from @cofhe/sdk/chains for use in CofheConfig.supportedChains
1319
+ * Users should generally not set this manually.
1320
+ */
1321
+ async getZkVerifierUrl() {
1322
+ this.assertChainId();
1323
+ return getZkVerifierUrlOrThrow(this.config, this.chainId);
1324
+ }
1325
+ /**
1326
+ * initTfhe is a platform-specific dependency injected into core/createCofheClientBase by web/createCofheClient and node/createCofheClient
1327
+ * web/ uses zama "tfhe"
1328
+ * node/ uses zama "node-tfhe"
1329
+ * Users should not set this manually.
1330
+ */
1331
+ async initTfheOrThrow() {
1332
+ if (!this.initTfhe)
1333
+ return false;
1334
+ try {
1335
+ return await this.initTfhe();
1336
+ } catch (error) {
1337
+ throw CofheError.fromError(error, {
1338
+ code: "INIT_TFHE_FAILED" /* InitTfheFailed */,
1339
+ message: `Failed to initialize TFHE`,
1340
+ context: {
1341
+ initTfhe: this.initTfhe
1342
+ }
1343
+ });
1344
+ }
1345
+ }
1346
+ /**
1347
+ * Fetches the FHE key and CRS from the CoFHE API
1348
+ * If the key/crs already exists in the store it is returned, else it is fetched, stored, and returned
1349
+ */
1350
+ async fetchFheKeyAndCrs() {
1351
+ this.assertChainId();
1352
+ const securityZone = this.getSecurityZone();
1353
+ try {
1354
+ await this.keysStorage?.rehydrateKeysStore();
1355
+ } catch (error) {
1356
+ throw CofheError.fromError(error, {
1357
+ code: "REHYDRATE_KEYS_STORE_FAILED" /* RehydrateKeysStoreFailed */,
1358
+ message: `Failed to rehydrate keys store`,
1359
+ context: {
1360
+ keysStorage: this.keysStorage
1361
+ }
1362
+ });
1363
+ }
1364
+ let fheKey;
1365
+ let fheKeyFetchedFromCoFHE = false;
1366
+ let crs;
1367
+ let crsFetchedFromCoFHE = false;
1368
+ try {
1369
+ [[fheKey, fheKeyFetchedFromCoFHE], [crs, crsFetchedFromCoFHE]] = await fetchKeys(
1370
+ this.config,
1371
+ this.chainId,
1372
+ securityZone,
1373
+ this.tfhePublicKeyDeserializer,
1374
+ this.compactPkeCrsDeserializer,
1375
+ this.keysStorage
1376
+ );
1377
+ } catch (error) {
1378
+ throw CofheError.fromError(error, {
1379
+ code: "FETCH_KEYS_FAILED" /* FetchKeysFailed */,
1380
+ message: `Failed to fetch FHE key and CRS`,
1381
+ context: {
1382
+ config: this.config,
1383
+ chainId: this.chainId,
1384
+ securityZone,
1385
+ compactPkeCrsDeserializer: this.compactPkeCrsDeserializer,
1386
+ tfhePublicKeyDeserializer: this.tfhePublicKeyDeserializer
1387
+ }
1388
+ });
1389
+ }
1390
+ if (!fheKey) {
1391
+ throw new CofheError({
1392
+ code: "MISSING_FHE_KEY" /* MissingFheKey */,
1393
+ message: `FHE key not found`,
1394
+ context: {
1395
+ chainId: this.chainId,
1396
+ securityZone
1397
+ }
1398
+ });
1399
+ }
1400
+ if (!crs) {
1401
+ throw new CofheError({
1402
+ code: "MISSING_CRS" /* MissingCrs */,
1403
+ message: `CRS not found for chainId <${this.chainId}>`,
1404
+ context: {
1405
+ chainId: this.chainId
1406
+ }
1407
+ });
1408
+ }
1409
+ return { fheKey, fheKeyFetchedFromCoFHE, crs, crsFetchedFromCoFHE };
1410
+ }
1411
+ /**
1412
+ * Resolves the encryptDelay config into an array of 5 per-step delays.
1413
+ * A single number is broadcast to all steps; a tuple is used as-is.
1414
+ */
1415
+ resolveEncryptDelays() {
1416
+ const encryptDelay = this.config?.mocks?.encryptDelay ?? [100, 100, 100, 500, 500];
1417
+ if (typeof encryptDelay === "number") {
1418
+ return [encryptDelay, encryptDelay, encryptDelay, encryptDelay, encryptDelay];
1419
+ }
1420
+ return encryptDelay;
1421
+ }
1422
+ /**
1423
+ * @dev Encrypt against the cofheMocks instead of CoFHE
1424
+ *
1425
+ * In the cofheMocks, the MockZkVerifier contract is deployed on hardhat to a fixed address, this contract handles mocking the zk verifying.
1426
+ * cofheMocksInsertPackedHashes - stores the ctHashes and their plaintext values for on-chain mocking of FHE operations.
1427
+ * cofheMocksZkCreateProofSignatures - creates signatures to be included in the encrypted inputs. The signers address is known and verified in the mock contracts.
1428
+ */
1429
+ async mocksExecute() {
1430
+ this.assertAccount();
1431
+ this.assertPublicClient();
1432
+ this.assertWalletClient();
1433
+ const [initTfheDelay, fetchKeysDelay, packDelay, proveDelay, verifyDelay] = this.resolveEncryptDelays();
1434
+ this.fireStepStart("initTfhe" /* InitTfhe */);
1435
+ await sleep(initTfheDelay);
1436
+ this.fireStepEnd("initTfhe" /* InitTfhe */, {
1437
+ tfheInitializationExecuted: false,
1438
+ isMocks: true,
1439
+ mockSleep: initTfheDelay
1440
+ });
1441
+ this.fireStepStart("fetchKeys" /* FetchKeys */);
1442
+ await sleep(fetchKeysDelay);
1443
+ this.fireStepEnd("fetchKeys" /* FetchKeys */, {
1444
+ fheKeyFetchedFromCoFHE: false,
1445
+ crsFetchedFromCoFHE: false,
1446
+ isMocks: true,
1447
+ mockSleep: fetchKeysDelay
1448
+ });
1449
+ this.fireStepStart("pack" /* Pack */);
1450
+ await cofheMocksCheckEncryptableBits(this.inputItems);
1451
+ await sleep(packDelay);
1452
+ this.fireStepEnd("pack" /* Pack */, { isMocks: true, mockSleep: packDelay });
1453
+ this.fireStepStart("prove" /* Prove */);
1454
+ await sleep(proveDelay);
1455
+ this.fireStepEnd("prove" /* Prove */, { isMocks: true, mockSleep: proveDelay });
1456
+ this.fireStepStart("verify" /* Verify */);
1457
+ await sleep(verifyDelay);
1458
+ const signedResults = await cofheMocksZkVerifySign(
1459
+ this.inputItems,
1460
+ this.account,
1461
+ this.securityZone,
1462
+ this.publicClient,
1463
+ this.walletClient,
1464
+ this.zkvWalletClient
1465
+ );
1466
+ const encryptedInputs = signedResults.map(({ ct_hash, signature }, index) => ({
1467
+ ctHash: BigInt(ct_hash),
1468
+ securityZone: this.securityZone,
1469
+ utype: this.inputItems[index].utype,
1470
+ signature
1471
+ }));
1472
+ this.fireStepEnd("verify" /* Verify */, { isMocks: true, mockSleep: verifyDelay });
1473
+ return encryptedInputs;
1474
+ }
1475
+ /**
1476
+ * In the production context, perform a true encryption with the CoFHE coprocessor.
1477
+ */
1478
+ async productionExecute() {
1479
+ this.assertAccount();
1480
+ this.assertChainId();
1481
+ this.fireStepStart("initTfhe" /* InitTfhe */);
1482
+ const tfheInitializationExecuted = await this.initTfheOrThrow();
1483
+ this.fireStepEnd("initTfhe" /* InitTfhe */, { tfheInitializationExecuted });
1484
+ this.fireStepStart("fetchKeys" /* FetchKeys */);
1485
+ const { fheKey, fheKeyFetchedFromCoFHE, crs, crsFetchedFromCoFHE } = await this.fetchFheKeyAndCrs();
1486
+ let { zkBuilder, zkCrs } = this.zkBuilderAndCrsGenerator(fheKey, crs);
1487
+ this.fireStepEnd("fetchKeys" /* FetchKeys */, { fheKeyFetchedFromCoFHE, crsFetchedFromCoFHE });
1488
+ this.fireStepStart("pack" /* Pack */);
1489
+ zkBuilder = zkPack(this.inputItems, zkBuilder);
1490
+ this.fireStepEnd("pack" /* Pack */);
1491
+ this.fireStepStart("prove" /* Prove */);
1492
+ const metadata = constructZkPoKMetadata(this.account, this.securityZone, this.chainId);
1493
+ let proof = null;
1494
+ let usedWorker = false;
1495
+ let workerFailedError;
1496
+ if (this.useWorker && this.zkProveWorkerFn) {
1497
+ try {
1498
+ proof = await zkProveWithWorker(this.zkProveWorkerFn, fheKey, crs, this.inputItems, metadata);
1499
+ usedWorker = true;
1500
+ } catch (error) {
1501
+ workerFailedError = error instanceof Error ? error.message : String(error);
1502
+ }
1503
+ }
1504
+ if (proof == null) {
1505
+ proof = await zkProve(zkBuilder, zkCrs, metadata);
1506
+ usedWorker = false;
1507
+ }
1508
+ this.fireStepEnd("prove" /* Prove */, {
1509
+ useWorker: this.useWorker,
1510
+ usedWorker,
1511
+ workerFailedError
1512
+ });
1513
+ this.fireStepStart("verify" /* Verify */);
1514
+ const zkVerifierUrl = await this.getZkVerifierUrl();
1515
+ const verifyResults = await zkVerify(zkVerifierUrl, proof, this.account, this.securityZone, this.chainId);
1516
+ const encryptedInputs = verifyResults.map(
1517
+ ({ ct_hash, signature }, index) => ({
1518
+ ctHash: BigInt(ct_hash),
1519
+ securityZone: this.securityZone,
1520
+ utype: this.inputItems[index].utype,
1521
+ signature
1522
+ })
1523
+ );
1524
+ this.fireStepEnd("verify" /* Verify */);
1525
+ return encryptedInputs;
1526
+ }
1527
+ /**
1528
+ * Final step of the encryption process. MUST BE CALLED LAST IN THE CHAIN.
1529
+ *
1530
+ * This will:
1531
+ * - Pack the encryptable items into a zk proof
1532
+ * - Prove the zk proof
1533
+ * - Verify the zk proof with CoFHE
1534
+ * - Package and return the encrypted inputs
1535
+ *
1536
+ * Example:
1537
+ * ```typescript
1538
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1539
+ * .setAccount('0x123...890') // optional
1540
+ * .setChainId(11155111) // optional
1541
+ * .execute(); // execute
1542
+ * ```
1543
+ *
1544
+ * @returns The encrypted inputs.
1545
+ */
1546
+ async execute() {
1547
+ if (this.chainId === chains.hardhat.id)
1548
+ return this.mocksExecute();
1549
+ return this.productionExecute();
1550
+ }
1551
+ };
1552
+
1553
+ // permits/utils.ts
1554
+ var fromHexString = (hexString) => {
1555
+ const cleanString = hexString.length % 2 === 1 ? `0${hexString}` : hexString;
1556
+ const arr = cleanString.replace(/^0x/, "").match(/.{1,2}/g);
1557
+ if (!arr)
1558
+ return new Uint8Array();
1559
+ return new Uint8Array(arr.map((byte) => parseInt(byte, 16)));
1560
+ };
1561
+ var toHexString2 = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
1562
+ function toBigInt(value) {
1563
+ if (typeof value === "string") {
1564
+ return BigInt(value);
1565
+ } else if (typeof value === "number") {
1566
+ return BigInt(value);
1567
+ } else if (typeof value === "object") {
1568
+ return BigInt("0x" + toHexString2(value));
1569
+ } else {
1570
+ return value;
1571
+ }
1572
+ }
1573
+ function toBeArray(value) {
1574
+ const bigIntValue = typeof value === "number" ? BigInt(value) : value;
1575
+ const hex = bigIntValue.toString(16);
1576
+ const paddedHex = hex.length % 2 === 0 ? hex : "0" + hex;
1577
+ return fromHexString(paddedHex);
1578
+ }
1579
+ function isString(value) {
1580
+ if (typeof value !== "string") {
1581
+ throw new Error(`Expected value which is \`string\`, received value of type \`${typeof value}\`.`);
1582
+ }
1583
+ }
1584
+ function isNumber(value) {
1585
+ const is = typeof value === "number" && !Number.isNaN(value);
1586
+ if (!is) {
1587
+ throw new Error(`Expected value which is \`number\`, received value of type \`${typeof value}\`.`);
1588
+ }
1589
+ }
1590
+ function isBigIntOrNumber(value) {
1591
+ const is = typeof value === "bigint";
1592
+ if (!is) {
1593
+ try {
1594
+ isNumber(value);
1595
+ } catch (e) {
1596
+ throw new Error(`Value ${value} is not a number or bigint: ${typeof value}`);
1597
+ }
1598
+ }
1599
+ }
1600
+
1601
+ // permits/sealing.ts
1602
+ var PRIVATE_KEY_LENGTH = 64;
1603
+ var PUBLIC_KEY_LENGTH = 64;
1604
+ var SealingKey = class _SealingKey {
1605
+ /**
1606
+ * The private key used for decryption.
1607
+ */
1608
+ privateKey;
1609
+ /**
1610
+ * The public key used for encryption.
1611
+ */
1612
+ publicKey;
1613
+ /**
1614
+ * Constructs a SealingKey instance with the given private and public keys.
1615
+ *
1616
+ * @param {string} privateKey - The private key used for decryption.
1617
+ * @param {string} publicKey - The public key used for encryption.
1618
+ * @throws Will throw an error if the provided keys lengths do not match
1619
+ * the required lengths for private and public keys.
1620
+ */
1621
+ constructor(privateKey, publicKey) {
1622
+ if (privateKey.length !== PRIVATE_KEY_LENGTH) {
1623
+ throw new Error(`Private key must be of length ${PRIVATE_KEY_LENGTH}`);
1624
+ }
1625
+ if (publicKey.length !== PUBLIC_KEY_LENGTH) {
1626
+ throw new Error(`Public key must be of length ${PUBLIC_KEY_LENGTH}`);
1627
+ }
1628
+ this.privateKey = privateKey;
1629
+ this.publicKey = publicKey;
1630
+ }
1631
+ unseal = (parsedData) => {
1632
+ const nonce = parsedData.nonce instanceof Uint8Array ? parsedData.nonce : new Uint8Array(parsedData.nonce);
1633
+ const ephemPublicKey = parsedData.public_key instanceof Uint8Array ? parsedData.public_key : new Uint8Array(parsedData.public_key);
1634
+ const dataToDecrypt = parsedData.data instanceof Uint8Array ? parsedData.data : new Uint8Array(parsedData.data);
1635
+ const privateKeyBytes = fromHexString(this.privateKey);
1636
+ const decryptedMessage = nacl__default.default.box.open(dataToDecrypt, nonce, ephemPublicKey, privateKeyBytes);
1637
+ if (!decryptedMessage) {
1638
+ throw new Error("Failed to decrypt message");
1639
+ }
1640
+ return toBigInt(decryptedMessage);
1641
+ };
1642
+ /**
1643
+ * Serializes the SealingKey to a JSON object.
1644
+ */
1645
+ serialize = () => {
1646
+ return {
1647
+ privateKey: this.privateKey,
1648
+ publicKey: this.publicKey
1649
+ };
1650
+ };
1651
+ /**
1652
+ * Deserializes the SealingKey from a JSON object.
1653
+ */
1654
+ static deserialize = (privateKey, publicKey) => {
1655
+ return new _SealingKey(privateKey, publicKey);
1656
+ };
1657
+ /**
1658
+ * Seals (encrypts) the provided message for a receiver with the specified public key.
1659
+ *
1660
+ * @param {bigint | number} value - The message to be encrypted.
1661
+ * @param {string} publicKey - The public key of the intended recipient.
1662
+ * @returns string - The encrypted message in hexadecimal format.
1663
+ * @static
1664
+ * @throws Will throw if the provided publicKey or value do not meet defined preconditions.
1665
+ */
1666
+ static seal = (value, publicKey) => {
1667
+ isString(publicKey);
1668
+ isBigIntOrNumber(value);
1669
+ const ephemeralKeyPair = nacl__default.default.box.keyPair();
1670
+ const nonce = nacl__default.default.randomBytes(nacl__default.default.box.nonceLength);
1671
+ const encryptedMessage = nacl__default.default.box(toBeArray(value), nonce, fromHexString(publicKey), ephemeralKeyPair.secretKey);
1672
+ return {
1673
+ data: encryptedMessage,
1674
+ public_key: ephemeralKeyPair.publicKey,
1675
+ nonce
1676
+ };
1677
+ };
1678
+ };
1679
+ var GenerateSealingKey = () => {
1680
+ const sodiumKeypair = nacl__default.default.box.keyPair();
1681
+ return new SealingKey(toHexString2(sodiumKeypair.secretKey), toHexString2(sodiumKeypair.publicKey));
1682
+ };
1683
+ var SerializedSealingPair = zod.z.object({
1684
+ privateKey: zod.z.string(),
1685
+ publicKey: zod.z.string()
1686
+ });
1687
+ var addressSchema = zod.z.string().refine((val) => viem.isAddress(val), {
1688
+ error: "Invalid address"
1689
+ }).transform((val) => viem.getAddress(val));
1690
+ var addressNotZeroSchema = addressSchema.refine((val) => val !== viem.zeroAddress, {
1691
+ error: "Must not be zeroAddress"
1692
+ });
1693
+ var bytesSchema = zod.z.custom(
1694
+ (val) => {
1695
+ return typeof val === "string" && viem.isHex(val);
1696
+ },
1697
+ {
1698
+ message: "Invalid hex value"
1699
+ }
1700
+ );
1701
+ var bytesNotEmptySchema = bytesSchema.refine((val) => val !== "0x", {
1702
+ error: "Must not be empty"
1703
+ });
1704
+ var DEFAULT_EXPIRATION_FN = () => Math.round(Date.now() / 1e3) + 7 * 24 * 60 * 60;
1705
+ var zPermitWithDefaults = zod.z.object({
1706
+ name: zod.z.string().optional().default("Unnamed Permit"),
1707
+ type: zod.z.enum(["self", "sharing", "recipient"]),
1708
+ issuer: addressNotZeroSchema,
1709
+ expiration: zod.z.int().optional().default(DEFAULT_EXPIRATION_FN),
1710
+ recipient: addressSchema.optional().default(viem.zeroAddress),
1711
+ validatorId: zod.z.int().optional().default(0),
1712
+ validatorContract: addressSchema.optional().default(viem.zeroAddress),
1713
+ issuerSignature: bytesSchema.optional().default("0x"),
1714
+ recipientSignature: bytesSchema.optional().default("0x")
1715
+ });
1716
+ var zPermitWithSealingPair = zPermitWithDefaults.extend({
1717
+ sealingPair: SerializedSealingPair.optional()
1718
+ });
1719
+ var ExternalValidatorRefinement = [
1720
+ (data) => data.validatorId !== 0 && data.validatorContract !== viem.zeroAddress || data.validatorId === 0 && data.validatorContract === viem.zeroAddress,
1721
+ {
1722
+ error: "Permit external validator :: validatorId and validatorContract must either both be set or both be unset.",
1723
+ path: ["validatorId", "validatorContract"]
1724
+ }
1725
+ ];
1726
+ var RecipientRefinement = [
1727
+ (data) => data.issuer !== data.recipient,
1728
+ {
1729
+ error: "Sharing permit :: issuer and recipient must not be the same",
1730
+ path: ["issuer", "recipient"]
1731
+ }
1732
+ ];
1733
+ var SelfPermitOptionsValidator = zod.z.object({
1734
+ type: zod.z.literal("self").optional().default("self"),
1735
+ issuer: addressNotZeroSchema,
1736
+ name: zod.z.string().optional().default("Unnamed Permit"),
1737
+ expiration: zod.z.int().optional().default(DEFAULT_EXPIRATION_FN),
1738
+ recipient: addressSchema.optional().default(viem.zeroAddress),
1739
+ validatorId: zod.z.int().optional().default(0),
1740
+ validatorContract: addressSchema.optional().default(viem.zeroAddress),
1741
+ issuerSignature: bytesSchema.optional().default("0x"),
1742
+ recipientSignature: bytesSchema.optional().default("0x")
1743
+ }).refine(...ExternalValidatorRefinement);
1744
+ var SelfPermitValidator = zPermitWithSealingPair.refine((data) => data.type === "self", {
1745
+ error: "Type must be 'self'"
1746
+ }).refine((data) => data.recipient === viem.zeroAddress, {
1747
+ error: "Recipient must be zeroAddress"
1748
+ }).refine((data) => data.issuerSignature !== "0x", {
1749
+ error: "IssuerSignature must be populated"
1750
+ }).refine((data) => data.recipientSignature === "0x", {
1751
+ error: "RecipientSignature must be empty"
1752
+ }).refine(...ExternalValidatorRefinement);
1753
+ var SharingPermitOptionsValidator = zod.z.object({
1754
+ type: zod.z.literal("sharing").optional().default("sharing"),
1755
+ issuer: addressNotZeroSchema,
1756
+ recipient: addressNotZeroSchema,
1757
+ name: zod.z.string().optional().default("Unnamed Permit"),
1758
+ expiration: zod.z.int().optional().default(DEFAULT_EXPIRATION_FN),
1759
+ validatorId: zod.z.int().optional().default(0),
1760
+ validatorContract: addressSchema.optional().default(viem.zeroAddress),
1761
+ issuerSignature: bytesSchema.optional().default("0x"),
1762
+ recipientSignature: bytesSchema.optional().default("0x")
1763
+ }).refine(...RecipientRefinement).refine(...ExternalValidatorRefinement);
1764
+ var SharingPermitValidator = zPermitWithSealingPair.refine((data) => data.type === "sharing", {
1765
+ error: "Type must be 'sharing'"
1766
+ }).refine((data) => data.recipient !== viem.zeroAddress, {
1767
+ error: "Recipient must not be zeroAddress"
1768
+ }).refine((data) => data.issuerSignature !== "0x", {
1769
+ error: "IssuerSignature must be populated"
1770
+ }).refine((data) => data.recipientSignature === "0x", {
1771
+ error: "RecipientSignature must be empty"
1772
+ }).refine(...ExternalValidatorRefinement);
1773
+ var ImportPermitOptionsValidator = zod.z.object({
1774
+ type: zod.z.literal("recipient").optional().default("recipient"),
1775
+ issuer: addressNotZeroSchema,
1776
+ recipient: addressNotZeroSchema,
1777
+ name: zod.z.string().optional().default("Unnamed Permit"),
1778
+ expiration: zod.z.int(),
1779
+ validatorId: zod.z.int().optional().default(0),
1780
+ validatorContract: addressSchema.optional().default(viem.zeroAddress),
1781
+ issuerSignature: bytesNotEmptySchema,
1782
+ recipientSignature: bytesSchema.optional().default("0x")
1783
+ }).refine(...ExternalValidatorRefinement);
1784
+ var ImportPermitValidator = zPermitWithSealingPair.refine((data) => data.type === "recipient", {
1785
+ error: "Type must be 'recipient'"
1786
+ }).refine((data) => data.recipient !== viem.zeroAddress, {
1787
+ error: "Recipient must not be zeroAddress"
1788
+ }).refine((data) => data.issuerSignature !== "0x", {
1789
+ error: "IssuerSignature must be populated"
1790
+ }).refine((data) => data.recipientSignature !== "0x", {
1791
+ error: "RecipientSignature must be populated"
1792
+ }).refine(...ExternalValidatorRefinement);
1793
+ var safeParseAndThrowFormatted = (schema, data, message) => {
1794
+ const result = schema.safeParse(data);
1795
+ if (!result.success) {
1796
+ throw new Error(`${message}: ${zod.z.prettifyError(result.error)}`, { cause: result.error });
1797
+ }
1798
+ return result.data;
1799
+ };
1800
+ var validateSelfPermitOptions = (options) => {
1801
+ return safeParseAndThrowFormatted(SelfPermitOptionsValidator, options, "Invalid self permit options");
1802
+ };
1803
+ var validateSharingPermitOptions = (options) => {
1804
+ return safeParseAndThrowFormatted(SharingPermitOptionsValidator, options, "Invalid sharing permit options");
1805
+ };
1806
+ var validateImportPermitOptions = (options) => {
1807
+ return safeParseAndThrowFormatted(ImportPermitOptionsValidator, options, "Invalid import permit options");
1808
+ };
1809
+ var validateSelfPermit = (permit) => {
1810
+ return safeParseAndThrowFormatted(SelfPermitValidator, permit, "Invalid self permit");
1811
+ };
1812
+ var validateSharingPermit = (permit) => {
1813
+ return safeParseAndThrowFormatted(SharingPermitValidator, permit, "Invalid sharing permit");
1814
+ };
1815
+ var validateImportPermit = (permit) => {
1816
+ return safeParseAndThrowFormatted(ImportPermitValidator, permit, "Invalid import permit");
1817
+ };
1818
+ var ValidationUtils = {
1819
+ /**
1820
+ * Check if permit is expired
1821
+ */
1822
+ isExpired: (permit) => {
1823
+ return permit.expiration < Math.floor(Date.now() / 1e3);
1824
+ },
1825
+ /**
1826
+ * Check if permit is signed by the active party
1827
+ */
1828
+ isSigned: (permit) => {
1829
+ if (permit.type === "self" || permit.type === "sharing") {
1830
+ return permit.issuerSignature !== "0x";
1831
+ }
1832
+ if (permit.type === "recipient") {
1833
+ return permit.recipientSignature !== "0x";
1834
+ }
1835
+ return false;
1836
+ },
1837
+ /**
1838
+ * Checks that a permit is signed and not expired.
1839
+ */
1840
+ isSignedAndNotExpired: (permit) => {
1841
+ if (ValidationUtils.isExpired(permit)) {
1842
+ return { valid: false, error: "expired" };
1843
+ }
1844
+ if (!ValidationUtils.isSigned(permit)) {
1845
+ return { valid: false, error: "not-signed" };
1846
+ }
1847
+ return { valid: true, error: null };
1848
+ },
1849
+ /**
1850
+ * Asserts that a permit is signed and not expired.
1851
+ *
1852
+ * Throws `Error` with message:
1853
+ * - `Permit is expired`
1854
+ * - `Permit is not signed`
1855
+ */
1856
+ assertSignedAndNotExpired: (permit) => {
1857
+ const result = ValidationUtils.isSignedAndNotExpired(permit);
1858
+ if (result.valid)
1859
+ return;
1860
+ if (result.error === "expired") {
1861
+ throw new Error("Permit is expired");
1862
+ }
1863
+ if (result.error === "not-signed") {
1864
+ throw new Error("Permit is not signed");
1865
+ }
1866
+ throw new Error("Permit is invalid");
1867
+ },
1868
+ isValid: (permit) => {
1869
+ const schema = permit.type === "self" ? SelfPermitValidator : permit.type === "sharing" ? SharingPermitValidator : permit.type === "recipient" ? ImportPermitValidator : null;
1870
+ if (schema == null)
1871
+ return { valid: false, error: "invalid-schema" };
1872
+ const schemaResult = schema.safeParse(permit);
1873
+ if (!schemaResult.success)
1874
+ return { valid: false, error: "invalid-schema" };
1875
+ return ValidationUtils.isSignedAndNotExpired(permit);
1876
+ }
1877
+ };
1878
+
1879
+ // permits/signature.ts
1880
+ var PermitSignatureAllFields = [
1881
+ { name: "issuer", type: "address" },
1882
+ { name: "expiration", type: "uint64" },
1883
+ { name: "recipient", type: "address" },
1884
+ { name: "validatorId", type: "uint256" },
1885
+ { name: "validatorContract", type: "address" },
1886
+ { name: "sealingKey", type: "bytes32" },
1887
+ { name: "issuerSignature", type: "bytes" }
1888
+ ];
1889
+ var SignatureTypes = {
1890
+ PermissionedV2IssuerSelf: [
1891
+ "issuer",
1892
+ "expiration",
1893
+ "recipient",
1894
+ "validatorId",
1895
+ "validatorContract",
1896
+ "sealingKey"
1897
+ ],
1898
+ PermissionedV2IssuerShared: [
1899
+ "issuer",
1900
+ "expiration",
1901
+ "recipient",
1902
+ "validatorId",
1903
+ "validatorContract"
1904
+ ],
1905
+ PermissionedV2Recipient: ["sealingKey", "issuerSignature"]
1906
+ };
1907
+ var getSignatureTypesAndMessage = (primaryType, fields, values) => {
1908
+ const types = {
1909
+ [primaryType]: PermitSignatureAllFields.filter((fieldType) => fields.includes(fieldType.name))
1910
+ };
1911
+ const message = {};
1912
+ fields.forEach((field) => {
1913
+ if (field in values) {
1914
+ message[field] = values[field];
1915
+ }
1916
+ });
1917
+ return { types, primaryType, message };
1918
+ };
1919
+ var SignatureUtils = {
1920
+ /**
1921
+ * Get signature parameters for a permit
1922
+ */
1923
+ getSignatureParams: (permit, primaryType) => {
1924
+ return getSignatureTypesAndMessage(primaryType, SignatureTypes[primaryType], permit);
1925
+ },
1926
+ /**
1927
+ * Determine the required signature type based on permit type
1928
+ */
1929
+ getPrimaryType: (permitType) => {
1930
+ if (permitType === "self")
1931
+ return "PermissionedV2IssuerSelf";
1932
+ if (permitType === "sharing")
1933
+ return "PermissionedV2IssuerShared";
1934
+ if (permitType === "recipient")
1935
+ return "PermissionedV2Recipient";
1936
+ throw new Error(`Unknown permit type: ${permitType}`);
1937
+ }
1938
+ };
1939
+ var getAclAddress = async (publicClient) => {
1940
+ const ACL_IFACE = "function acl() view returns (address)";
1941
+ const aclAbi = viem.parseAbi([ACL_IFACE]);
1942
+ return await publicClient.readContract({
1943
+ address: TASK_MANAGER_ADDRESS,
1944
+ abi: aclAbi,
1945
+ functionName: "acl"
1946
+ });
1947
+ };
1948
+ var getAclEIP712Domain = async (publicClient) => {
1949
+ const aclAddress = await getAclAddress(publicClient);
1950
+ const EIP712_DOMAIN_IFACE = "function eip712Domain() public view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)";
1951
+ const domainAbi = viem.parseAbi([EIP712_DOMAIN_IFACE]);
1952
+ const domain = await publicClient.readContract({
1953
+ address: aclAddress,
1954
+ abi: domainAbi,
1955
+ functionName: "eip712Domain"
1956
+ });
1957
+ const [_fields, name, version, chainId, verifyingContract, _salt, _extensions] = domain;
1958
+ return {
1959
+ name,
1960
+ version,
1961
+ chainId: Number(chainId),
1962
+ verifyingContract
1963
+ };
1964
+ };
1965
+ var checkPermitValidityOnChain = async (permission, publicClient) => {
1966
+ const aclAddress = await getAclAddress(publicClient);
1967
+ try {
1968
+ await publicClient.simulateContract({
1969
+ address: aclAddress,
1970
+ abi: checkPermitValidityAbi,
1971
+ functionName: "checkPermitValidity",
1972
+ args: [
1973
+ {
1974
+ issuer: permission.issuer,
1975
+ expiration: BigInt(permission.expiration),
1976
+ recipient: permission.recipient,
1977
+ validatorId: BigInt(permission.validatorId),
1978
+ validatorContract: permission.validatorContract,
1979
+ sealingKey: permission.sealingKey,
1980
+ issuerSignature: permission.issuerSignature,
1981
+ recipientSignature: permission.recipientSignature
1982
+ }
1983
+ ]
1984
+ });
1985
+ return true;
1986
+ } catch (err) {
1987
+ if (err instanceof viem.BaseError) {
1988
+ const revertError = err.walk((err2) => err2 instanceof viem.ContractFunctionRevertedError);
1989
+ if (revertError instanceof viem.ContractFunctionRevertedError) {
1990
+ const errorName = revertError.data?.errorName ?? "";
1991
+ throw new Error(errorName);
1992
+ }
1993
+ }
1994
+ const customErrorName = extractCustomErrorFromDetails(err, checkPermitValidityAbi);
1995
+ if (customErrorName) {
1996
+ throw new Error(customErrorName);
1997
+ }
1998
+ const hhDetailsData = extractReturnData(err);
1999
+ if (hhDetailsData != null) {
2000
+ const decoded = viem.decodeErrorResult({
2001
+ abi: checkPermitValidityAbi,
2002
+ data: hhDetailsData
2003
+ });
2004
+ throw new Error(decoded.errorName);
2005
+ }
2006
+ throw err;
2007
+ }
2008
+ };
2009
+ function extractCustomErrorFromDetails(err, abi) {
2010
+ const anyErr = err;
2011
+ const details = anyErr?.details ?? anyErr?.cause?.details;
2012
+ if (typeof details === "string") {
2013
+ const customErrorMatch = details.match(/reverted with custom error '(\w+)\(\)'/);
2014
+ if (customErrorMatch) {
2015
+ const errorName = customErrorMatch[1];
2016
+ const errorExists = abi.some((item) => item.type === "error" && item.name === errorName);
2017
+ if (errorExists) {
2018
+ return errorName;
2019
+ }
2020
+ }
2021
+ }
2022
+ return void 0;
2023
+ }
2024
+ function extractReturnData(err) {
2025
+ const anyErr = err;
2026
+ const s = anyErr?.details ?? anyErr?.cause?.details ?? anyErr?.shortMessage ?? anyErr?.message ?? String(err);
2027
+ return s.match(/return data:\s*(0x[a-fA-F0-9]+)/)?.[1];
2028
+ }
2029
+ var checkPermitValidityAbi = [
2030
+ {
2031
+ type: "function",
2032
+ name: "checkPermitValidity",
2033
+ inputs: [
2034
+ {
2035
+ name: "permission",
2036
+ type: "tuple",
2037
+ internalType: "struct Permission",
2038
+ components: [
2039
+ {
2040
+ name: "issuer",
2041
+ type: "address",
2042
+ internalType: "address"
2043
+ },
2044
+ {
2045
+ name: "expiration",
2046
+ type: "uint64",
2047
+ internalType: "uint64"
2048
+ },
2049
+ {
2050
+ name: "recipient",
2051
+ type: "address",
2052
+ internalType: "address"
2053
+ },
2054
+ {
2055
+ name: "validatorId",
2056
+ type: "uint256",
2057
+ internalType: "uint256"
2058
+ },
2059
+ {
2060
+ name: "validatorContract",
2061
+ type: "address",
2062
+ internalType: "address"
2063
+ },
2064
+ {
2065
+ name: "sealingKey",
2066
+ type: "bytes32",
2067
+ internalType: "bytes32"
2068
+ },
2069
+ {
2070
+ name: "issuerSignature",
2071
+ type: "bytes",
2072
+ internalType: "bytes"
2073
+ },
2074
+ {
2075
+ name: "recipientSignature",
2076
+ type: "bytes",
2077
+ internalType: "bytes"
2078
+ }
2079
+ ]
2080
+ }
2081
+ ],
2082
+ outputs: [
2083
+ {
2084
+ name: "",
2085
+ type: "bool",
2086
+ internalType: "bool"
2087
+ }
2088
+ ],
2089
+ stateMutability: "view"
2090
+ },
2091
+ {
2092
+ type: "error",
2093
+ name: "PermissionInvalid_Disabled",
2094
+ inputs: []
2095
+ },
2096
+ {
2097
+ type: "error",
2098
+ name: "PermissionInvalid_Expired",
2099
+ inputs: []
2100
+ },
2101
+ {
2102
+ type: "error",
2103
+ name: "PermissionInvalid_IssuerSignature",
2104
+ inputs: []
2105
+ },
2106
+ {
2107
+ type: "error",
2108
+ name: "PermissionInvalid_RecipientSignature",
2109
+ inputs: []
2110
+ }
2111
+ ];
2112
+
2113
+ // permits/permit.ts
2114
+ var PermitUtils = {
2115
+ /**
2116
+ * Create a self permit for personal use
2117
+ */
2118
+ createSelf: (options) => {
2119
+ const validation = validateSelfPermitOptions(options);
2120
+ const sealingPair = GenerateSealingKey();
2121
+ const permit = {
2122
+ hash: PermitUtils.getHash(validation),
2123
+ ...validation,
2124
+ sealingPair,
2125
+ _signedDomain: void 0
2126
+ };
2127
+ return permit;
2128
+ },
2129
+ /**
2130
+ * Create a sharing permit to be shared with another user
2131
+ */
2132
+ createSharing: (options) => {
2133
+ const validation = validateSharingPermitOptions(options);
2134
+ const sealingPair = GenerateSealingKey();
2135
+ const permit = {
2136
+ hash: PermitUtils.getHash(validation),
2137
+ ...validation,
2138
+ sealingPair,
2139
+ _signedDomain: void 0
2140
+ };
2141
+ return permit;
2142
+ },
2143
+ /**
2144
+ * Import a shared permit from various input formats
2145
+ */
2146
+ importShared: (options) => {
2147
+ let parsedOptions;
2148
+ if (typeof options === "string") {
2149
+ try {
2150
+ parsedOptions = JSON.parse(options);
2151
+ } catch (error) {
2152
+ throw new Error(`Failed to parse JSON string: ${error}`);
2153
+ }
2154
+ } else if (typeof options === "object" && options !== null) {
2155
+ parsedOptions = options;
2156
+ } else {
2157
+ throw new Error("Invalid input type, expected ImportSharedPermitOptions, object, or string");
2158
+ }
2159
+ if (parsedOptions.type != null && parsedOptions.type !== "sharing") {
2160
+ throw new Error(`Invalid permit type <${parsedOptions.type}>, must be "sharing"`);
2161
+ }
2162
+ const validation = validateImportPermitOptions({ ...parsedOptions, type: "recipient" });
2163
+ const sealingPair = GenerateSealingKey();
2164
+ const permit = {
2165
+ hash: PermitUtils.getHash(validation),
2166
+ ...validation,
2167
+ sealingPair,
2168
+ _signedDomain: void 0
2169
+ };
2170
+ return permit;
2171
+ },
2172
+ /**
2173
+ * Sign a permit with the provided wallet client
2174
+ */
2175
+ sign: async (permit, publicClient, walletClient) => {
2176
+ if (walletClient == null || walletClient.account == null) {
2177
+ throw new Error(
2178
+ "Missing walletClient, you must pass in a `walletClient` for the connected user to create a permit signature"
2179
+ );
2180
+ }
2181
+ const primaryType = SignatureUtils.getPrimaryType(permit.type);
2182
+ const domain = await getAclEIP712Domain(publicClient);
2183
+ const { types, message } = SignatureUtils.getSignatureParams(PermitUtils.getPermission(permit, true), primaryType);
2184
+ const signature = await walletClient.signTypedData({
2185
+ domain,
2186
+ types,
2187
+ primaryType,
2188
+ message,
2189
+ account: walletClient.account
2190
+ });
2191
+ let updatedPermit;
2192
+ if (permit.type === "self" || permit.type === "sharing") {
2193
+ updatedPermit = {
2194
+ ...permit,
2195
+ issuerSignature: signature,
2196
+ _signedDomain: domain
2197
+ };
2198
+ } else {
2199
+ updatedPermit = {
2200
+ ...permit,
2201
+ recipientSignature: signature,
2202
+ _signedDomain: domain
2203
+ };
2204
+ }
2205
+ return updatedPermit;
2206
+ },
2207
+ /**
2208
+ * Create and sign a self permit in one operation
2209
+ */
2210
+ createSelfAndSign: async (options, publicClient, walletClient) => {
2211
+ const permit = PermitUtils.createSelf(options);
2212
+ return PermitUtils.sign(permit, publicClient, walletClient);
2213
+ },
2214
+ /**
2215
+ * Create and sign a sharing permit in one operation
2216
+ */
2217
+ createSharingAndSign: async (options, publicClient, walletClient) => {
2218
+ const permit = PermitUtils.createSharing(options);
2219
+ return PermitUtils.sign(permit, publicClient, walletClient);
2220
+ },
2221
+ /**
2222
+ * Import and sign a shared permit in one operation from various input formats
2223
+ */
2224
+ importSharedAndSign: async (options, publicClient, walletClient) => {
2225
+ const permit = PermitUtils.importShared(options);
2226
+ return PermitUtils.sign(permit, publicClient, walletClient);
2227
+ },
2228
+ /**
2229
+ * Deserialize a permit from serialized data
2230
+ */
2231
+ deserialize: (data) => {
2232
+ return {
2233
+ ...data,
2234
+ sealingPair: SealingKey.deserialize(data.sealingPair.privateKey, data.sealingPair.publicKey)
2235
+ };
2236
+ },
2237
+ /**
2238
+ * Serialize a permit for storage
2239
+ */
2240
+ serialize: (permit) => {
2241
+ return {
2242
+ hash: permit.hash,
2243
+ name: permit.name,
2244
+ type: permit.type,
2245
+ issuer: permit.issuer,
2246
+ expiration: permit.expiration,
2247
+ recipient: permit.recipient,
2248
+ validatorId: permit.validatorId,
2249
+ validatorContract: permit.validatorContract,
2250
+ issuerSignature: permit.issuerSignature,
2251
+ recipientSignature: permit.recipientSignature,
2252
+ _signedDomain: permit._signedDomain,
2253
+ sealingPair: permit.sealingPair.serialize()
2254
+ };
2255
+ },
2256
+ /**
2257
+ * Validate a permit (schema-level validation)
2258
+ */
2259
+ validateSchema: (permit) => {
2260
+ if (permit.type === "self") {
2261
+ return validateSelfPermit(permit);
2262
+ } else if (permit.type === "sharing") {
2263
+ return validateSharingPermit(permit);
2264
+ } else if (permit.type === "recipient") {
2265
+ return validateImportPermit(permit);
2266
+ } else {
2267
+ throw new Error("Invalid permit type");
2268
+ }
2269
+ },
2270
+ /**
2271
+ * Validate a permit (holistic validation).
2272
+ *
2273
+ * This validates:
2274
+ * - Permit schema (shape + invariants)
2275
+ * - Permit is signed
2276
+ * - Permit is not expired
2277
+ *
2278
+ * For schema-only validation, use `validateSchema(permit)`.
2279
+ */
2280
+ validate: (permit) => {
2281
+ const validated = PermitUtils.validateSchema(permit);
2282
+ ValidationUtils.assertSignedAndNotExpired(validated);
2283
+ return validated;
2284
+ },
2285
+ /**
2286
+ * Get the permission object from a permit (for use in contracts)
2287
+ */
2288
+ getPermission: (permit, skipValidation = false) => {
2289
+ if (!skipValidation) {
2290
+ PermitUtils.validateSchema(permit);
2291
+ }
2292
+ return {
2293
+ issuer: permit.issuer,
2294
+ expiration: permit.expiration,
2295
+ recipient: permit.recipient,
2296
+ validatorId: permit.validatorId,
2297
+ validatorContract: permit.validatorContract,
2298
+ sealingKey: `0x${permit.sealingPair.publicKey}`,
2299
+ issuerSignature: permit.issuerSignature,
2300
+ recipientSignature: permit.recipientSignature
2301
+ };
2302
+ },
2303
+ /**
2304
+ * Get a stable hash for the permit (used as key in storage)
2305
+ */
2306
+ getHash: (permit) => {
2307
+ const data = JSON.stringify({
2308
+ type: permit.type,
2309
+ issuer: permit.issuer,
2310
+ expiration: permit.expiration,
2311
+ recipient: permit.recipient,
2312
+ validatorId: permit.validatorId,
2313
+ validatorContract: permit.validatorContract
2314
+ });
2315
+ return viem.keccak256(viem.toHex(data));
2316
+ },
2317
+ /**
2318
+ * Export permit data for sharing (removes sensitive fields)
2319
+ */
2320
+ export: (permit) => {
2321
+ const cleanedPermit = {
2322
+ name: permit.name,
2323
+ type: permit.type,
2324
+ issuer: permit.issuer,
2325
+ expiration: permit.expiration
2326
+ };
2327
+ if (permit.recipient !== viem.zeroAddress)
2328
+ cleanedPermit.recipient = permit.recipient;
2329
+ if (permit.validatorId !== 0)
2330
+ cleanedPermit.validatorId = permit.validatorId;
2331
+ if (permit.validatorContract !== viem.zeroAddress)
2332
+ cleanedPermit.validatorContract = permit.validatorContract;
2333
+ if (permit.type === "sharing" && permit.issuerSignature !== "0x")
2334
+ cleanedPermit.issuerSignature = permit.issuerSignature;
2335
+ return JSON.stringify(cleanedPermit, void 0, 2);
2336
+ },
2337
+ /**
2338
+ * Unseal encrypted data using the permit's sealing key
2339
+ */
2340
+ unseal: (permit, ciphertext) => {
2341
+ return permit.sealingPair.unseal(ciphertext);
2342
+ },
2343
+ /**
2344
+ * Check if permit is expired
2345
+ */
2346
+ isExpired: (permit) => {
2347
+ return ValidationUtils.isExpired(permit);
2348
+ },
2349
+ /**
2350
+ * Check if permit is signed
2351
+ */
2352
+ isSigned: (permit) => {
2353
+ return ValidationUtils.isSigned(permit);
2354
+ },
2355
+ /**
2356
+ * Check if permit is signed and not expired
2357
+ */
2358
+ isSignedAndNotExpired: (permit) => {
2359
+ return ValidationUtils.isSignedAndNotExpired(permit);
2360
+ },
2361
+ /**
2362
+ * Assert that permit is signed and not expired
2363
+ */
2364
+ assertSignedAndNotExpired: (permit) => {
2365
+ return ValidationUtils.assertSignedAndNotExpired(permit);
2366
+ },
2367
+ isValid: (permit) => {
2368
+ return ValidationUtils.isValid(permit);
2369
+ },
2370
+ /**
2371
+ * Update permit name (returns new permit instance)
2372
+ */
2373
+ updateName: (permit, name) => {
2374
+ return { ...permit, name };
2375
+ },
2376
+ /**
2377
+ * Fetch EIP712 domain from the blockchain
2378
+ */
2379
+ fetchEIP712Domain: async (publicClient) => {
2380
+ return getAclEIP712Domain(publicClient);
2381
+ },
2382
+ /**
2383
+ * Check if permit's signed domain matches the provided domain
2384
+ */
2385
+ matchesDomain: (permit, domain) => {
2386
+ return permit._signedDomain?.name === domain.name && permit._signedDomain?.version === domain.version && permit._signedDomain?.verifyingContract === domain.verifyingContract && permit._signedDomain?.chainId === domain.chainId;
2387
+ },
2388
+ /**
2389
+ * Check if permit's signed domain is valid for the current chain
2390
+ */
2391
+ checkSignedDomainValid: async (permit, publicClient) => {
2392
+ if (permit._signedDomain == null)
2393
+ return false;
2394
+ const domain = await getAclEIP712Domain(publicClient);
2395
+ return PermitUtils.matchesDomain(permit, domain);
2396
+ },
2397
+ /**
2398
+ * Check if permit passes the on-chain validation
2399
+ */
2400
+ checkValidityOnChain: async (permit, publicClient) => {
2401
+ const permission = PermitUtils.getPermission(permit);
2402
+ return checkPermitValidityOnChain(permission, publicClient);
2403
+ }
2404
+ };
2405
+ var PERMIT_STORE_DEFAULTS = {
2406
+ permits: {},
2407
+ activePermitHash: {}
2408
+ };
2409
+ var _permitStore = vanilla.createStore()(
2410
+ middleware.persist(() => PERMIT_STORE_DEFAULTS, { name: "cofhesdk-permits" })
2411
+ );
2412
+ var clearStaleStore = () => {
2413
+ const state = _permitStore.getState();
2414
+ const hasExpectedStructure = state && typeof state === "object" && "permits" in state && "activePermitHash" in state && typeof state.permits === "object" && typeof state.activePermitHash === "object";
2415
+ if (hasExpectedStructure)
2416
+ return;
2417
+ _permitStore.setState({ permits: {}, activePermitHash: {} });
2418
+ };
2419
+ var getPermit = (chainId, account, hash) => {
2420
+ clearStaleStore();
2421
+ if (chainId == null || account == null || hash == null)
2422
+ return;
2423
+ const savedPermit = _permitStore.getState().permits[chainId]?.[account]?.[hash];
2424
+ if (savedPermit == null)
2425
+ return;
2426
+ return PermitUtils.deserialize(savedPermit);
2427
+ };
2428
+ var getActivePermit = (chainId, account) => {
2429
+ clearStaleStore();
2430
+ if (chainId == null || account == null)
2431
+ return;
2432
+ const activePermitHash = _permitStore.getState().activePermitHash[chainId]?.[account];
2433
+ return getPermit(chainId, account, activePermitHash);
2434
+ };
2435
+ var getPermits = (chainId, account) => {
2436
+ clearStaleStore();
2437
+ if (chainId == null || account == null)
2438
+ return {};
2439
+ return Object.entries(_permitStore.getState().permits[chainId]?.[account] ?? {}).reduce(
2440
+ (acc, [hash, permit]) => {
2441
+ if (permit == void 0)
2442
+ return acc;
2443
+ return { ...acc, [hash]: PermitUtils.deserialize(permit) };
2444
+ },
2445
+ {}
2446
+ );
2447
+ };
2448
+ var setPermit = (chainId, account, permit) => {
2449
+ clearStaleStore();
2450
+ _permitStore.setState(
2451
+ immer.produce((state) => {
2452
+ if (state.permits[chainId] == null)
2453
+ state.permits[chainId] = {};
2454
+ if (state.permits[chainId][account] == null)
2455
+ state.permits[chainId][account] = {};
2456
+ state.permits[chainId][account][permit.hash] = PermitUtils.serialize(permit);
2457
+ })
2458
+ );
2459
+ };
2460
+ var removePermit = (chainId, account, hash) => {
2461
+ clearStaleStore();
2462
+ _permitStore.setState(
2463
+ immer.produce((state) => {
2464
+ if (state.permits[chainId] == null)
2465
+ state.permits[chainId] = {};
2466
+ if (state.activePermitHash[chainId] == null)
2467
+ state.activePermitHash[chainId] = {};
2468
+ const accountPermits = state.permits[chainId][account];
2469
+ if (accountPermits == null)
2470
+ return;
2471
+ if (accountPermits[hash] == null)
2472
+ return;
2473
+ if (state.activePermitHash[chainId][account] === hash) {
2474
+ state.activePermitHash[chainId][account] = void 0;
2475
+ }
2476
+ accountPermits[hash] = void 0;
2477
+ })
2478
+ );
2479
+ };
2480
+ var getActivePermitHash = (chainId, account) => {
2481
+ clearStaleStore();
2482
+ if (chainId == null || account == null)
2483
+ return void 0;
2484
+ return _permitStore.getState().activePermitHash[chainId]?.[account];
2485
+ };
2486
+ var setActivePermitHash = (chainId, account, hash) => {
2487
+ clearStaleStore();
2488
+ _permitStore.setState(
2489
+ immer.produce((state) => {
2490
+ if (state.activePermitHash[chainId] == null)
2491
+ state.activePermitHash[chainId] = {};
2492
+ state.activePermitHash[chainId][account] = hash;
2493
+ })
2494
+ );
2495
+ };
2496
+ var removeActivePermitHash = (chainId, account) => {
2497
+ clearStaleStore();
2498
+ _permitStore.setState(
2499
+ immer.produce((state) => {
2500
+ if (state.activePermitHash[chainId])
2501
+ state.activePermitHash[chainId][account] = void 0;
2502
+ })
2503
+ );
2504
+ };
2505
+ var resetStore = () => {
2506
+ clearStaleStore();
2507
+ _permitStore.setState({ permits: {}, activePermitHash: {} });
2508
+ };
2509
+ var permitStore = {
2510
+ store: _permitStore,
2511
+ getPermit,
2512
+ getActivePermit,
2513
+ getPermits,
2514
+ setPermit,
2515
+ removePermit,
2516
+ getActivePermitHash,
2517
+ setActivePermitHash,
2518
+ removeActivePermitHash,
2519
+ resetStore
2520
+ };
2521
+ var storeActivePermit = async (permit, publicClient, walletClient) => {
2522
+ const chainId = await publicClient.getChainId();
2523
+ const account = walletClient.account.address;
2524
+ permitStore.setPermit(chainId, account, permit);
2525
+ permitStore.setActivePermitHash(chainId, account, permit.hash);
2526
+ };
2527
+ var createPermitWithSign = async (options, publicClient, walletClient, permitMethod) => {
2528
+ const permit = await permitMethod(options, publicClient, walletClient);
2529
+ await storeActivePermit(permit, publicClient, walletClient);
2530
+ return permit;
2531
+ };
2532
+ var createSelf = async (options, publicClient, walletClient) => {
2533
+ return createPermitWithSign(options, publicClient, walletClient, PermitUtils.createSelfAndSign);
2534
+ };
2535
+ var createSharing = async (options, publicClient, walletClient) => {
2536
+ return createPermitWithSign(options, publicClient, walletClient, PermitUtils.createSharingAndSign);
2537
+ };
2538
+ var importShared = async (options, publicClient, walletClient) => {
2539
+ return createPermitWithSign(options, publicClient, walletClient, PermitUtils.importSharedAndSign);
2540
+ };
2541
+ var getHash = (permit) => {
2542
+ return PermitUtils.getHash(permit);
2543
+ };
2544
+ var serialize = (permit) => {
2545
+ return PermitUtils.serialize(permit);
2546
+ };
2547
+ var deserialize = (serialized) => {
2548
+ return PermitUtils.deserialize(serialized);
2549
+ };
2550
+ var getPermit2 = (chainId, account, hash) => {
2551
+ return permitStore.getPermit(chainId, account, hash);
2552
+ };
2553
+ var getPermits2 = (chainId, account) => {
2554
+ return permitStore.getPermits(chainId, account);
2555
+ };
2556
+ var getActivePermit2 = (chainId, account) => {
2557
+ return permitStore.getActivePermit(chainId, account);
2558
+ };
2559
+ var getActivePermitHash2 = (chainId, account) => {
2560
+ return permitStore.getActivePermitHash(chainId, account);
2561
+ };
2562
+ var selectActivePermit = (chainId, account, hash) => {
2563
+ permitStore.setActivePermitHash(chainId, account, hash);
2564
+ };
2565
+ var getOrCreateSelfPermit = async (publicClient, walletClient, chainId, account, options) => {
2566
+ const _chainId = chainId ?? await publicClient.getChainId();
2567
+ const _account = account ?? walletClient.account.address;
2568
+ const activePermit = await getActivePermit2(_chainId, _account);
2569
+ if (activePermit && activePermit.type === "self") {
2570
+ return activePermit;
2571
+ }
2572
+ return createSelf(options ?? { issuer: _account, name: "Autogenerated Self Permit" }, publicClient, walletClient);
2573
+ };
2574
+ var getOrCreateSharingPermit = async (publicClient, walletClient, options, chainId, account) => {
2575
+ const _chainId = chainId ?? await publicClient.getChainId();
2576
+ const _account = account ?? walletClient.account.address;
2577
+ const activePermit = await getActivePermit2(_chainId, _account);
2578
+ if (activePermit && activePermit.type === "sharing") {
2579
+ return activePermit;
2580
+ }
2581
+ return createSharing(options, publicClient, walletClient);
2582
+ };
2583
+ var removePermit2 = async (chainId, account, hash) => permitStore.removePermit(chainId, account, hash);
2584
+ var removeActivePermit = async (chainId, account) => permitStore.removeActivePermitHash(chainId, account);
2585
+ var permits = {
2586
+ getSnapshot: permitStore.store.getState,
2587
+ subscribe: permitStore.store.subscribe,
2588
+ createSelf,
2589
+ createSharing,
2590
+ importShared,
2591
+ getOrCreateSelfPermit,
2592
+ getOrCreateSharingPermit,
2593
+ getHash,
2594
+ serialize,
2595
+ deserialize,
2596
+ getPermit: getPermit2,
2597
+ getPermits: getPermits2,
2598
+ getActivePermit: getActivePermit2,
2599
+ getActivePermitHash: getActivePermitHash2,
2600
+ removePermit: removePermit2,
2601
+ selectActivePermit,
2602
+ removeActivePermit
2603
+ };
2604
+ function uint160ToAddress(uint160) {
2605
+ const hexStr = uint160.toString(16).padStart(40, "0");
2606
+ return viem.getAddress("0x" + hexStr);
2607
+ }
2608
+ var isValidUtype = (utype) => {
2609
+ return utype === 0 /* Bool */ || utype === 7 /* Uint160 */ || utype == null || FheUintUTypes.includes(utype);
2610
+ };
2611
+ var convertViaUtype = (utype, value) => {
2612
+ if (utype === 0 /* Bool */) {
2613
+ return !!value;
2614
+ } else if (utype === 7 /* Uint160 */) {
2615
+ return uint160ToAddress(value);
2616
+ } else if (utype == null || FheUintUTypes.includes(utype)) {
2617
+ return value;
2618
+ } else {
2619
+ throw new Error(`convertViaUtype :: invalid utype :: ${utype}`);
2620
+ }
2621
+ };
2622
+
2623
+ // core/decrypt/MockThresholdNetworkAbi.ts
2624
+ var MockThresholdNetworkAbi = [
2625
+ {
2626
+ type: "function",
2627
+ name: "acl",
2628
+ inputs: [],
2629
+ outputs: [{ name: "", type: "address", internalType: "contract ACL" }],
2630
+ stateMutability: "view"
2631
+ },
2632
+ {
2633
+ type: "function",
2634
+ name: "decodeLowLevelReversion",
2635
+ inputs: [{ name: "data", type: "bytes", internalType: "bytes" }],
2636
+ outputs: [{ name: "error", type: "string", internalType: "string" }],
2637
+ stateMutability: "pure"
2638
+ },
2639
+ {
2640
+ type: "function",
2641
+ name: "exists",
2642
+ inputs: [],
2643
+ outputs: [{ name: "", type: "bool", internalType: "bool" }],
2644
+ stateMutability: "pure"
2645
+ },
2646
+ {
2647
+ type: "function",
2648
+ name: "initialize",
2649
+ inputs: [
2650
+ { name: "_taskManager", type: "address", internalType: "address" },
2651
+ { name: "_acl", type: "address", internalType: "address" }
2652
+ ],
2653
+ outputs: [],
2654
+ stateMutability: "nonpayable"
2655
+ },
2656
+ {
2657
+ type: "function",
2658
+ name: "queryDecrypt",
2659
+ inputs: [
2660
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
2661
+ { name: "", type: "uint256", internalType: "uint256" },
2662
+ {
2663
+ name: "permission",
2664
+ type: "tuple",
2665
+ internalType: "struct Permission",
2666
+ components: [
2667
+ { name: "issuer", type: "address", internalType: "address" },
2668
+ { name: "expiration", type: "uint64", internalType: "uint64" },
2669
+ { name: "recipient", type: "address", internalType: "address" },
2670
+ { name: "validatorId", type: "uint256", internalType: "uint256" },
2671
+ { name: "validatorContract", type: "address", internalType: "address" },
2672
+ { name: "sealingKey", type: "bytes32", internalType: "bytes32" },
2673
+ { name: "issuerSignature", type: "bytes", internalType: "bytes" },
2674
+ { name: "recipientSignature", type: "bytes", internalType: "bytes" }
2675
+ ]
2676
+ }
2677
+ ],
2678
+ outputs: [
2679
+ { name: "allowed", type: "bool", internalType: "bool" },
2680
+ { name: "error", type: "string", internalType: "string" },
2681
+ { name: "", type: "uint256", internalType: "uint256" }
2682
+ ],
2683
+ stateMutability: "view"
2684
+ },
2685
+ {
2686
+ type: "function",
2687
+ name: "querySealOutput",
2688
+ inputs: [
2689
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
2690
+ { name: "", type: "uint256", internalType: "uint256" },
2691
+ {
2692
+ name: "permission",
2693
+ type: "tuple",
2694
+ internalType: "struct Permission",
2695
+ components: [
2696
+ { name: "issuer", type: "address", internalType: "address" },
2697
+ { name: "expiration", type: "uint64", internalType: "uint64" },
2698
+ { name: "recipient", type: "address", internalType: "address" },
2699
+ { name: "validatorId", type: "uint256", internalType: "uint256" },
2700
+ { name: "validatorContract", type: "address", internalType: "address" },
2701
+ { name: "sealingKey", type: "bytes32", internalType: "bytes32" },
2702
+ { name: "issuerSignature", type: "bytes", internalType: "bytes" },
2703
+ { name: "recipientSignature", type: "bytes", internalType: "bytes" }
2704
+ ]
2705
+ }
2706
+ ],
2707
+ outputs: [
2708
+ { name: "allowed", type: "bool", internalType: "bool" },
2709
+ { name: "error", type: "string", internalType: "string" },
2710
+ { name: "", type: "bytes32", internalType: "bytes32" }
2711
+ ],
2712
+ stateMutability: "view"
2713
+ },
2714
+ {
2715
+ type: "function",
2716
+ name: "seal",
2717
+ inputs: [
2718
+ { name: "input", type: "uint256", internalType: "uint256" },
2719
+ { name: "key", type: "bytes32", internalType: "bytes32" }
2720
+ ],
2721
+ outputs: [{ name: "", type: "bytes32", internalType: "bytes32" }],
2722
+ stateMutability: "pure"
2723
+ },
2724
+ {
2725
+ type: "function",
2726
+ name: "unseal",
2727
+ inputs: [
2728
+ { name: "hashed", type: "bytes32", internalType: "bytes32" },
2729
+ { name: "key", type: "bytes32", internalType: "bytes32" }
2730
+ ],
2731
+ outputs: [{ name: "", type: "uint256", internalType: "uint256" }],
2732
+ stateMutability: "pure"
2733
+ },
2734
+ {
2735
+ type: "function",
2736
+ name: "mockAcl",
2737
+ inputs: [],
2738
+ outputs: [{ name: "", type: "address", internalType: "contract MockACL" }],
2739
+ stateMutability: "view"
2740
+ },
2741
+ {
2742
+ type: "function",
2743
+ name: "mockTaskManager",
2744
+ inputs: [],
2745
+ outputs: [{ name: "", type: "address", internalType: "contract MockTaskManager" }],
2746
+ stateMutability: "view"
2747
+ },
2748
+ {
2749
+ type: "function",
2750
+ name: "mockQueryDecrypt",
2751
+ inputs: [
2752
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
2753
+ { name: "", type: "uint256", internalType: "uint256" },
2754
+ { name: "issuer", type: "address", internalType: "address" }
2755
+ ],
2756
+ outputs: [
2757
+ { name: "allowed", type: "bool", internalType: "bool" },
2758
+ { name: "error", type: "string", internalType: "string" },
2759
+ { name: "", type: "uint256", internalType: "uint256" }
2760
+ ],
2761
+ stateMutability: "view"
2762
+ },
2763
+ {
2764
+ type: "function",
2765
+ name: "decryptForTxWithPermit",
2766
+ inputs: [
2767
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
2768
+ {
2769
+ name: "permission",
2770
+ type: "tuple",
2771
+ internalType: "struct Permission",
2772
+ components: [
2773
+ { name: "issuer", type: "address", internalType: "address" },
2774
+ { name: "expiration", type: "uint64", internalType: "uint64" },
2775
+ { name: "recipient", type: "address", internalType: "address" },
2776
+ { name: "validatorId", type: "uint256", internalType: "uint256" },
2777
+ { name: "validatorContract", type: "address", internalType: "address" },
2778
+ { name: "sealingKey", type: "bytes32", internalType: "bytes32" },
2779
+ { name: "issuerSignature", type: "bytes", internalType: "bytes" },
2780
+ { name: "recipientSignature", type: "bytes", internalType: "bytes" }
2781
+ ]
2782
+ }
2783
+ ],
2784
+ outputs: [
2785
+ { name: "allowed", type: "bool", internalType: "bool" },
2786
+ { name: "error", type: "string", internalType: "string" },
2787
+ { name: "decryptedValue", type: "uint256", internalType: "uint256" }
2788
+ ],
2789
+ stateMutability: "view"
2790
+ },
2791
+ {
2792
+ type: "function",
2793
+ name: "decryptForTxWithoutPermit",
2794
+ inputs: [{ name: "ctHash", type: "uint256", internalType: "uint256" }],
2795
+ outputs: [
2796
+ { name: "allowed", type: "bool", internalType: "bool" },
2797
+ { name: "error", type: "string", internalType: "string" },
2798
+ { name: "decryptedValue", type: "uint256", internalType: "uint256" }
2799
+ ],
2800
+ stateMutability: "view"
2801
+ }
2802
+ ];
2803
+
2804
+ // core/decrypt/cofheMocksDecryptForView.ts
2805
+ async function cofheMocksDecryptForView(ctHash, utype, permit, publicClient) {
2806
+ const permission = PermitUtils.getPermission(permit, true);
2807
+ const permissionWithBigInts = {
2808
+ ...permission,
2809
+ expiration: BigInt(permission.expiration),
2810
+ validatorId: BigInt(permission.validatorId)
2811
+ };
2812
+ const [allowed, error, result] = await publicClient.readContract({
2813
+ address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
2814
+ abi: MockThresholdNetworkAbi,
2815
+ functionName: "querySealOutput",
2816
+ args: [BigInt(ctHash), BigInt(utype), permissionWithBigInts]
2817
+ });
2818
+ if (error != "") {
2819
+ throw new CofheError({
2820
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2821
+ message: `mocks querySealOutput call failed: ${error}`
2822
+ });
2823
+ }
2824
+ if (allowed == false) {
2825
+ throw new CofheError({
2826
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2827
+ message: `mocks querySealOutput call failed: ACL Access Denied (NotAllowed)`
2828
+ });
2829
+ }
2830
+ const sealedBigInt = BigInt(result);
2831
+ const sealingKeyBigInt = BigInt(permission.sealingKey);
2832
+ const unsealed = sealedBigInt ^ sealingKeyBigInt;
2833
+ return unsealed;
2834
+ }
2835
+
2836
+ // core/decrypt/polling.ts
2837
+ function computeMinuteRampPollIntervalMs(elapsedMs, params) {
2838
+ const elapsedSeconds = Math.floor(elapsedMs / 1e3);
2839
+ const intervalSeconds = 1 + Math.floor(elapsedSeconds / 60);
2840
+ const intervalMs = intervalSeconds * 1e3;
2841
+ return Math.min(params.maxIntervalMs, Math.max(params.minIntervalMs, intervalMs));
2842
+ }
2843
+
2844
+ // core/decrypt/tnSealOutputV2.ts
2845
+ var POLL_INTERVAL_MS = 1e3;
2846
+ var POLL_MAX_INTERVAL_MS = 1e4;
2847
+ var POLL_TIMEOUT_MS = 5 * 60 * 1e3;
2848
+ function numberArrayToUint8Array(arr) {
2849
+ return new Uint8Array(arr);
2850
+ }
2851
+ function convertSealedData(sealed) {
2852
+ if (!sealed) {
2853
+ throw new CofheError({
2854
+ code: "SEAL_OUTPUT_RETURNED_NULL" /* SealOutputReturnedNull */,
2855
+ message: "Sealed data is missing from completed response"
2856
+ });
2857
+ }
2858
+ return {
2859
+ data: numberArrayToUint8Array(sealed.data),
2860
+ public_key: numberArrayToUint8Array(sealed.public_key),
2861
+ nonce: numberArrayToUint8Array(sealed.nonce)
2862
+ };
2863
+ }
2864
+ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, permission) {
2865
+ const body = {
2866
+ ct_tempkey: BigInt(ctHash).toString(16).padStart(64, "0"),
2867
+ host_chain_id: chainId,
2868
+ permit: permission
2869
+ };
2870
+ let response;
2871
+ try {
2872
+ response = await fetch(`${thresholdNetworkUrl}/v2/sealoutput`, {
2873
+ method: "POST",
2874
+ headers: {
2875
+ "Content-Type": "application/json"
2876
+ },
2877
+ body: JSON.stringify(body)
2878
+ });
2879
+ } catch (e) {
2880
+ throw new CofheError({
2881
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2882
+ message: `sealOutput request failed`,
2883
+ hint: "Ensure the threshold network URL is valid and reachable.",
2884
+ cause: e instanceof Error ? e : void 0,
2885
+ context: {
2886
+ thresholdNetworkUrl,
2887
+ body
2888
+ }
2889
+ });
2890
+ }
2891
+ if (!response.ok) {
2892
+ let errorMessage = `HTTP ${response.status}`;
2893
+ try {
2894
+ const errorBody = await response.json();
2895
+ errorMessage = errorBody.error_message || errorBody.message || errorMessage;
2896
+ } catch {
2897
+ errorMessage = response.statusText || errorMessage;
2898
+ }
2899
+ throw new CofheError({
2900
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2901
+ message: `sealOutput request failed: ${errorMessage}`,
2902
+ hint: "Check the threshold network URL and request parameters.",
2903
+ context: {
2904
+ thresholdNetworkUrl,
2905
+ status: response.status,
2906
+ statusText: response.statusText,
2907
+ body
2908
+ }
2909
+ });
2910
+ }
2911
+ let submitResponse;
2912
+ try {
2913
+ submitResponse = await response.json();
2914
+ } catch (e) {
2915
+ throw new CofheError({
2916
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2917
+ message: `Failed to parse sealOutput submit response`,
2918
+ cause: e instanceof Error ? e : void 0,
2919
+ context: {
2920
+ thresholdNetworkUrl,
2921
+ body
2922
+ }
2923
+ });
2924
+ }
2925
+ if (!submitResponse.request_id) {
2926
+ throw new CofheError({
2927
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2928
+ message: `sealOutput submit response missing request_id`,
2929
+ context: {
2930
+ thresholdNetworkUrl,
2931
+ body,
2932
+ submitResponse
2933
+ }
2934
+ });
2935
+ }
2936
+ return submitResponse.request_id;
2937
+ }
2938
+ async function pollSealOutputStatus(thresholdNetworkUrl, requestId, onPoll) {
2939
+ const startTime = Date.now();
2940
+ let attemptIndex = 0;
2941
+ let completed = false;
2942
+ while (!completed) {
2943
+ const elapsedMs = Date.now() - startTime;
2944
+ const intervalMs = computeMinuteRampPollIntervalMs(elapsedMs, {
2945
+ minIntervalMs: POLL_INTERVAL_MS,
2946
+ maxIntervalMs: POLL_MAX_INTERVAL_MS
2947
+ });
2948
+ onPoll?.({
2949
+ operation: "sealoutput",
2950
+ requestId,
2951
+ attemptIndex,
2952
+ elapsedMs,
2953
+ intervalMs,
2954
+ timeoutMs: POLL_TIMEOUT_MS
2955
+ });
2956
+ if (elapsedMs > POLL_TIMEOUT_MS) {
2957
+ throw new CofheError({
2958
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2959
+ message: `sealOutput polling timed out after ${POLL_TIMEOUT_MS}ms`,
2960
+ hint: "The request may still be processing. Try again later.",
2961
+ context: {
2962
+ thresholdNetworkUrl,
2963
+ requestId,
2964
+ timeoutMs: POLL_TIMEOUT_MS
2965
+ }
2966
+ });
2967
+ }
2968
+ let response;
2969
+ try {
2970
+ response = await fetch(`${thresholdNetworkUrl}/v2/sealoutput/${requestId}`, {
2971
+ method: "GET",
2972
+ headers: {
2973
+ "Content-Type": "application/json"
2974
+ }
2975
+ });
2976
+ } catch (e) {
2977
+ throw new CofheError({
2978
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2979
+ message: `sealOutput status poll failed`,
2980
+ hint: "Ensure the threshold network URL is valid and reachable.",
2981
+ cause: e instanceof Error ? e : void 0,
2982
+ context: {
2983
+ thresholdNetworkUrl,
2984
+ requestId
2985
+ }
2986
+ });
2987
+ }
2988
+ if (response.status === 404) {
2989
+ throw new CofheError({
2990
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2991
+ message: `sealOutput request not found: ${requestId}`,
2992
+ hint: "The request may have expired or been invalid.",
2993
+ context: {
2994
+ thresholdNetworkUrl,
2995
+ requestId
2996
+ }
2997
+ });
2998
+ }
2999
+ if (!response.ok) {
3000
+ let errorMessage = `HTTP ${response.status}`;
3001
+ try {
3002
+ const errorBody = await response.json();
3003
+ errorMessage = errorBody.error_message || errorBody.message || errorMessage;
3004
+ } catch {
3005
+ errorMessage = response.statusText || errorMessage;
3006
+ }
3007
+ throw new CofheError({
3008
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
3009
+ message: `sealOutput status poll failed: ${errorMessage}`,
3010
+ context: {
3011
+ thresholdNetworkUrl,
3012
+ requestId,
3013
+ status: response.status,
3014
+ statusText: response.statusText
3015
+ }
3016
+ });
3017
+ }
3018
+ let statusResponse;
3019
+ try {
3020
+ statusResponse = await response.json();
3021
+ } catch (e) {
3022
+ throw new CofheError({
3023
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
3024
+ message: `Failed to parse sealOutput status response`,
3025
+ cause: e instanceof Error ? e : void 0,
3026
+ context: {
3027
+ thresholdNetworkUrl,
3028
+ requestId
3029
+ }
3030
+ });
3031
+ }
3032
+ if (statusResponse.status === "COMPLETED") {
3033
+ if (statusResponse.is_succeed === false) {
3034
+ const errorMessage = statusResponse.error_message || "Unknown error";
3035
+ throw new CofheError({
3036
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
3037
+ message: `sealOutput request failed: ${errorMessage}`,
3038
+ context: {
3039
+ thresholdNetworkUrl,
3040
+ requestId,
3041
+ statusResponse
3042
+ }
3043
+ });
3044
+ }
3045
+ if (!statusResponse.sealed) {
3046
+ throw new CofheError({
3047
+ code: "SEAL_OUTPUT_RETURNED_NULL" /* SealOutputReturnedNull */,
3048
+ message: `sealOutput request completed but returned no sealed data`,
3049
+ context: {
3050
+ thresholdNetworkUrl,
3051
+ requestId,
3052
+ statusResponse
3053
+ }
3054
+ });
3055
+ }
3056
+ return convertSealedData(statusResponse.sealed);
3057
+ }
3058
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
3059
+ attemptIndex += 1;
3060
+ }
3061
+ throw new CofheError({
3062
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
3063
+ message: "Polling loop exited unexpectedly",
3064
+ context: {
3065
+ thresholdNetworkUrl,
3066
+ requestId
3067
+ }
3068
+ });
3069
+ }
3070
+ async function tnSealOutputV2(params) {
3071
+ const { thresholdNetworkUrl, ctHash, chainId, permission, onPoll } = params;
3072
+ const requestId = await submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, permission);
3073
+ return await pollSealOutputStatus(thresholdNetworkUrl, requestId, onPoll);
3074
+ }
3075
+
3076
+ // core/decrypt/decryptForViewBuilder.ts
3077
+ var DecryptForViewBuilder = class extends BaseBuilder {
3078
+ ctHash;
3079
+ utype;
3080
+ permitHash;
3081
+ permit;
3082
+ pollCallback;
3083
+ constructor(params) {
3084
+ super({
3085
+ config: params.config,
3086
+ publicClient: params.publicClient,
3087
+ walletClient: params.walletClient,
3088
+ chainId: params.chainId,
3089
+ account: params.account,
3090
+ requireConnected: params.requireConnected
3091
+ });
3092
+ this.ctHash = params.ctHash;
3093
+ this.utype = params.utype;
3094
+ this.permitHash = params.permitHash;
3095
+ this.permit = params.permit;
3096
+ }
3097
+ /**
3098
+ * @param chainId - Chain to decrypt values from. Used to fetch the threshold network URL and use the correct permit.
3099
+ *
3100
+ * If not provided, the chainId will be fetched from the connected publicClient.
3101
+ *
3102
+ * Example:
3103
+ * ```typescript
3104
+ * const unsealed = await client.decryptForView(ctHash, utype)
3105
+ * .setChainId(11155111)
3106
+ * .execute();
3107
+ * ```
3108
+ *
3109
+ * @returns The chainable DecryptForViewBuilder instance.
3110
+ */
3111
+ setChainId(chainId) {
3112
+ this.chainId = chainId;
3113
+ return this;
3114
+ }
3115
+ getChainId() {
3116
+ return this.chainId;
3117
+ }
3118
+ /**
3119
+ * @param account - Account to decrypt values from. Used to fetch the correct permit.
3120
+ *
3121
+ * If not provided, the account will be fetched from the connected walletClient.
3122
+ *
3123
+ * Example:
3124
+ * ```typescript
3125
+ * const unsealed = await client.decryptForView(ctHash, utype)
3126
+ * .setAccount('0x1234567890123456789012345678901234567890')
3127
+ * .execute();
3128
+ * ```
3129
+ *
3130
+ * @returns The chainable DecryptForViewBuilder instance.
3131
+ */
3132
+ setAccount(account) {
3133
+ this.account = account;
3134
+ return this;
3135
+ }
3136
+ getAccount() {
3137
+ return this.account;
3138
+ }
3139
+ onPoll(callback) {
3140
+ this.pollCallback = callback;
3141
+ return this;
3142
+ }
3143
+ withPermit(permitOrPermitHash) {
3144
+ if (typeof permitOrPermitHash === "string") {
3145
+ this.permitHash = permitOrPermitHash;
3146
+ this.permit = void 0;
3147
+ } else if (permitOrPermitHash === void 0) {
3148
+ this.permitHash = void 0;
3149
+ this.permit = void 0;
3150
+ } else {
3151
+ this.permit = permitOrPermitHash;
3152
+ this.permitHash = void 0;
3153
+ }
3154
+ return this;
3155
+ }
3156
+ /**
3157
+ * @param permitHash - Permit hash to decrypt values from. Used to fetch the correct permit.
3158
+ *
3159
+ * If not provided, the active permit for the chainId and account will be used.
3160
+ * If `setPermit()` is called, it will be used regardless of chainId, account, or permitHash.
3161
+ *
3162
+ * Example:
3163
+ * ```typescript
3164
+ * const unsealed = await client.decryptForView(ctHash, utype)
3165
+ * .setPermitHash('0x1234567890123456789012345678901234567890')
3166
+ * .execute();
3167
+ * ```
3168
+ *
3169
+ * @returns The chainable DecryptForViewBuilder instance.
3170
+ */
3171
+ /** @deprecated Use `withPermit(permitHash)` instead. */
3172
+ setPermitHash(permitHash) {
3173
+ return this.withPermit(permitHash);
3174
+ }
3175
+ getPermitHash() {
3176
+ return this.permitHash;
3177
+ }
3178
+ /**
3179
+ * @param permit - Permit to decrypt values with. If provided, it will be used regardless of chainId, account, or permitHash.
3180
+ *
3181
+ * If not provided, the permit will be determined by chainId, account, and permitHash.
3182
+ *
3183
+ * Example:
3184
+ * ```typescript
3185
+ * const unsealed = await client.decryptForView(ctHash, utype)
3186
+ * .setPermit(permit)
3187
+ * .execute();
3188
+ * ```
3189
+ *
3190
+ * @returns The chainable DecryptForViewBuilder instance.
3191
+ */
3192
+ /** @deprecated Use `withPermit(permit)` instead. */
3193
+ setPermit(permit) {
3194
+ return this.withPermit(permit);
3195
+ }
3196
+ getPermit() {
3197
+ return this.permit;
3198
+ }
3199
+ async getThresholdNetworkUrl() {
3200
+ this.assertChainId();
3201
+ return getThresholdNetworkUrlOrThrow(this.config, this.chainId);
3202
+ }
3203
+ validateUtypeOrThrow() {
3204
+ if (!isValidUtype(this.utype))
3205
+ throw new CofheError({
3206
+ code: "INVALID_UTYPE" /* InvalidUtype */,
3207
+ message: `Invalid utype to decrypt to`,
3208
+ context: {
3209
+ utype: this.utype
3210
+ }
3211
+ });
3212
+ }
3213
+ async getResolvedPermit() {
3214
+ if (this.permit)
3215
+ return this.permit;
3216
+ this.assertChainId();
3217
+ this.assertAccount();
3218
+ if (this.permitHash) {
3219
+ const permit2 = await permits.getPermit(this.chainId, this.account, this.permitHash);
3220
+ if (!permit2) {
3221
+ throw new CofheError({
3222
+ code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
3223
+ message: `Permit with hash <${this.permitHash}> not found for account <${this.account}> and chainId <${this.chainId}>`,
3224
+ hint: "Ensure the permit exists and is valid.",
3225
+ context: {
3226
+ chainId: this.chainId,
3227
+ account: this.account,
3228
+ permitHash: this.permitHash
3229
+ }
3230
+ });
3231
+ }
3232
+ return permit2;
3233
+ }
3234
+ const permit = await permits.getActivePermit(this.chainId, this.account);
3235
+ if (!permit) {
3236
+ throw new CofheError({
3237
+ code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
3238
+ message: `Active permit not found for chainId <${this.chainId}> and account <${this.account}>`,
3239
+ hint: "Ensure a permit exists for this account on this chain.",
3240
+ context: {
3241
+ chainId: this.chainId,
3242
+ account: this.account
3243
+ }
3244
+ });
3245
+ }
3246
+ return permit;
3247
+ }
3248
+ /**
3249
+ * On hardhat, interact with MockZkVerifier contract instead of CoFHE
3250
+ */
3251
+ async mocksSealOutput(permit) {
3252
+ this.assertPublicClient();
3253
+ const mocksDecryptDelay = this.config.mocks.decryptDelay;
3254
+ if (mocksDecryptDelay > 0)
3255
+ await sleep(mocksDecryptDelay);
3256
+ return cofheMocksDecryptForView(this.ctHash, this.utype, permit, this.publicClient);
3257
+ }
3258
+ /**
3259
+ * In the production context, perform a true decryption with the CoFHE coprocessor.
3260
+ */
3261
+ async productionSealOutput(permit) {
3262
+ this.assertChainId();
3263
+ this.assertPublicClient();
3264
+ const thresholdNetworkUrl = await this.getThresholdNetworkUrl();
3265
+ const permission = PermitUtils.getPermission(permit, true);
3266
+ const sealed = await tnSealOutputV2({
3267
+ ctHash: this.ctHash,
3268
+ chainId: this.chainId,
3269
+ permission,
3270
+ thresholdNetworkUrl,
3271
+ onPoll: this.pollCallback
3272
+ });
3273
+ return PermitUtils.unseal(permit, sealed);
3274
+ }
3275
+ /**
3276
+ * Final step of the decryption process. MUST BE CALLED LAST IN THE CHAIN.
3277
+ *
3278
+ * This will:
3279
+ * - Use a permit based on provided permit OR chainId + account + permitHash
3280
+ * - Check permit validity
3281
+ * - Call CoFHE `/sealoutput` with the permit, which returns a sealed (encrypted) item
3282
+ * - Unseal the sealed item with the permit
3283
+ * - Return the unsealed item
3284
+ *
3285
+ * Example:
3286
+ * ```typescript
3287
+ * const unsealed = await client.decryptForView(ctHash, utype)
3288
+ * .setChainId(11155111) // optional
3289
+ * .setAccount('0x123...890') // optional
3290
+ * .withPermit() // optional
3291
+ * .execute(); // execute
3292
+ * ```
3293
+ *
3294
+ * @returns The unsealed item.
3295
+ */
3296
+ async execute() {
3297
+ this.validateUtypeOrThrow();
3298
+ const permit = await this.getResolvedPermit();
3299
+ PermitUtils.validate(permit);
3300
+ const chainId = permit._signedDomain.chainId;
3301
+ let unsealed;
3302
+ if (chainId === hardhat2.id) {
3303
+ unsealed = await this.mocksSealOutput(permit);
3304
+ } else {
3305
+ unsealed = await this.productionSealOutput(permit);
3306
+ }
3307
+ return convertViaUtype(this.utype, unsealed);
3308
+ }
3309
+ };
3310
+ async function cofheMocksDecryptForTx(ctHash, utype, permit, publicClient) {
3311
+ let allowed;
3312
+ let error;
3313
+ let decryptedValue;
3314
+ if (permit !== null) {
3315
+ let permission = PermitUtils.getPermission(permit, true);
3316
+ const permissionWithBigInts = {
3317
+ ...permission,
3318
+ expiration: BigInt(permission.expiration),
3319
+ validatorId: BigInt(permission.validatorId)
3320
+ };
3321
+ [allowed, error, decryptedValue] = await publicClient.readContract({
3322
+ address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
3323
+ abi: MockThresholdNetworkAbi,
3324
+ functionName: "decryptForTxWithPermit",
3325
+ args: [BigInt(ctHash), permissionWithBigInts]
3326
+ });
3327
+ } else {
3328
+ [allowed, error, decryptedValue] = await publicClient.readContract({
3329
+ address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
3330
+ abi: MockThresholdNetworkAbi,
3331
+ functionName: "decryptForTxWithoutPermit",
3332
+ args: [BigInt(ctHash)]
3333
+ });
3334
+ }
3335
+ if (error != "") {
3336
+ throw new CofheError({
3337
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3338
+ message: `mocks decryptForTx call failed: ${error}`
3339
+ });
3340
+ }
3341
+ if (allowed == false) {
3342
+ throw new CofheError({
3343
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3344
+ message: `mocks decryptForTx call failed: ACL Access Denied (NotAllowed)`
3345
+ });
3346
+ }
3347
+ const packed = viem.encodePacked(["uint256", "uint256"], [BigInt(ctHash), decryptedValue]);
3348
+ const messageHash = viem.keccak256(packed);
3349
+ const signature = await accounts.sign({
3350
+ hash: messageHash,
3351
+ privateKey: MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY,
3352
+ to: "hex"
3353
+ });
3354
+ return {
3355
+ ctHash,
3356
+ decryptedValue,
3357
+ signature
3358
+ };
3359
+ }
3360
+ function normalizeTnSignature(signature) {
3361
+ if (typeof signature !== "string") {
3362
+ throw new CofheError({
3363
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3364
+ message: "decrypt response missing signature",
3365
+ context: {
3366
+ signature
3367
+ }
3368
+ });
3369
+ }
3370
+ const trimmed = signature.trim();
3371
+ if (trimmed.length === 0) {
3372
+ throw new CofheError({
3373
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3374
+ message: "decrypt response returned empty signature"
3375
+ });
3376
+ }
3377
+ const prefixed = trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
3378
+ const parsed = viem.parseSignature(prefixed);
3379
+ return viem.serializeSignature(parsed);
3380
+ }
3381
+ function parseDecryptedBytesToBigInt(decrypted) {
3382
+ if (!Array.isArray(decrypted)) {
3383
+ throw new CofheError({
3384
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3385
+ message: "decrypt response field <decrypted> must be a byte array",
3386
+ context: {
3387
+ decrypted
3388
+ }
3389
+ });
3390
+ }
3391
+ if (decrypted.length === 0) {
3392
+ throw new CofheError({
3393
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3394
+ message: "decrypt response field <decrypted> was an empty byte array",
3395
+ context: {
3396
+ decrypted
3397
+ }
3398
+ });
3399
+ }
3400
+ let hex = "";
3401
+ for (const b of decrypted) {
3402
+ if (typeof b !== "number" || !Number.isInteger(b) || b < 0 || b > 255) {
3403
+ throw new CofheError({
3404
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3405
+ message: "decrypt response field <decrypted> contained a non-byte value",
3406
+ context: {
3407
+ badElement: b,
3408
+ decrypted
3409
+ }
3410
+ });
3411
+ }
3412
+ hex += b.toString(16).padStart(2, "0");
3413
+ }
3414
+ return BigInt(`0x${hex}`);
3415
+ }
3416
+
3417
+ // core/decrypt/tnDecryptV2.ts
3418
+ var POLL_INTERVAL_MS2 = 1e3;
3419
+ var POLL_MAX_INTERVAL_MS2 = 1e4;
3420
+ var POLL_TIMEOUT_MS2 = 5 * 60 * 1e3;
3421
+ function assertDecryptSubmitResponseV2(value) {
3422
+ if (value == null || typeof value !== "object") {
3423
+ throw new CofheError({
3424
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3425
+ message: "decrypt submit response must be a JSON object",
3426
+ context: {
3427
+ value
3428
+ }
3429
+ });
3430
+ }
3431
+ const v = value;
3432
+ if (typeof v.request_id !== "string" || v.request_id.trim().length === 0) {
3433
+ throw new CofheError({
3434
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3435
+ message: "decrypt submit response missing request_id",
3436
+ context: {
3437
+ value
3438
+ }
3439
+ });
3440
+ }
3441
+ return { request_id: v.request_id };
3442
+ }
3443
+ function assertDecryptStatusResponseV2(value) {
3444
+ if (value == null || typeof value !== "object") {
3445
+ throw new CofheError({
3446
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3447
+ message: "decrypt status response must be a JSON object",
3448
+ context: {
3449
+ value
3450
+ }
3451
+ });
3452
+ }
3453
+ const v = value;
3454
+ const requestId = v.request_id;
3455
+ const status = v.status;
3456
+ const submittedAt = v.submitted_at;
3457
+ if (typeof requestId !== "string" || requestId.trim().length === 0) {
3458
+ throw new CofheError({
3459
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3460
+ message: "decrypt status response missing request_id",
3461
+ context: {
3462
+ value
3463
+ }
3464
+ });
3465
+ }
3466
+ if (status !== "PROCESSING" && status !== "COMPLETED") {
3467
+ throw new CofheError({
3468
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3469
+ message: "decrypt status response has invalid status",
3470
+ context: {
3471
+ value,
3472
+ status
3473
+ }
3474
+ });
3475
+ }
3476
+ if (typeof submittedAt !== "string" || submittedAt.trim().length === 0) {
3477
+ throw new CofheError({
3478
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3479
+ message: "decrypt status response missing submitted_at",
3480
+ context: {
3481
+ value
3482
+ }
3483
+ });
3484
+ }
3485
+ return value;
3486
+ }
3487
+ async function submitDecryptRequestV2(thresholdNetworkUrl, ctHash, chainId, permission) {
3488
+ const body = {
3489
+ ct_tempkey: BigInt(ctHash).toString(16).padStart(64, "0"),
3490
+ host_chain_id: chainId
3491
+ };
3492
+ if (permission) {
3493
+ body.permit = permission;
3494
+ }
3495
+ let response;
3496
+ try {
3497
+ response = await fetch(`${thresholdNetworkUrl}/v2/decrypt`, {
3498
+ method: "POST",
3499
+ headers: {
3500
+ "Content-Type": "application/json"
3501
+ },
3502
+ body: JSON.stringify(body)
3503
+ });
3504
+ } catch (e) {
3505
+ throw new CofheError({
3506
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3507
+ message: `decrypt request failed`,
3508
+ hint: "Ensure the threshold network URL is valid and reachable.",
3509
+ cause: e instanceof Error ? e : void 0,
3510
+ context: {
3511
+ thresholdNetworkUrl,
3512
+ body
3513
+ }
3514
+ });
3515
+ }
3516
+ if (!response.ok) {
3517
+ let errorMessage = `HTTP ${response.status}`;
3518
+ try {
3519
+ const errorBody = await response.json();
3520
+ const maybeMessage = errorBody.error_message || errorBody.message;
3521
+ if (typeof maybeMessage === "string" && maybeMessage.length > 0)
3522
+ errorMessage = maybeMessage;
3523
+ } catch {
3524
+ errorMessage = response.statusText || errorMessage;
3525
+ }
3526
+ throw new CofheError({
3527
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3528
+ message: `decrypt request failed: ${errorMessage}`,
3529
+ hint: "Check the threshold network URL and request parameters.",
3530
+ context: {
3531
+ thresholdNetworkUrl,
3532
+ status: response.status,
3533
+ statusText: response.statusText,
3534
+ body
3535
+ }
3536
+ });
3537
+ }
3538
+ let rawJson;
3539
+ try {
3540
+ rawJson = await response.json();
3541
+ } catch (e) {
3542
+ throw new CofheError({
3543
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3544
+ message: `Failed to parse decrypt submit response`,
3545
+ cause: e instanceof Error ? e : void 0,
3546
+ context: {
3547
+ thresholdNetworkUrl,
3548
+ body
3549
+ }
3550
+ });
3551
+ }
3552
+ const submitResponse = assertDecryptSubmitResponseV2(rawJson);
3553
+ return submitResponse.request_id;
3554
+ }
3555
+ async function pollDecryptStatusV2(thresholdNetworkUrl, requestId, onPoll) {
3556
+ const startTime = Date.now();
3557
+ let attemptIndex = 0;
3558
+ let completed = false;
3559
+ while (!completed) {
3560
+ const elapsedMs = Date.now() - startTime;
3561
+ const intervalMs = computeMinuteRampPollIntervalMs(elapsedMs, {
3562
+ minIntervalMs: POLL_INTERVAL_MS2,
3563
+ maxIntervalMs: POLL_MAX_INTERVAL_MS2
3564
+ });
3565
+ onPoll?.({
3566
+ operation: "decrypt",
3567
+ requestId,
3568
+ attemptIndex,
3569
+ elapsedMs,
3570
+ intervalMs,
3571
+ timeoutMs: POLL_TIMEOUT_MS2
3572
+ });
3573
+ if (elapsedMs > POLL_TIMEOUT_MS2) {
3574
+ throw new CofheError({
3575
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3576
+ message: `decrypt polling timed out after ${POLL_TIMEOUT_MS2}ms`,
3577
+ hint: "The request may still be processing. Try again later.",
3578
+ context: {
3579
+ thresholdNetworkUrl,
3580
+ requestId,
3581
+ timeoutMs: POLL_TIMEOUT_MS2
3582
+ }
3583
+ });
3584
+ }
3585
+ let response;
3586
+ try {
3587
+ response = await fetch(`${thresholdNetworkUrl}/v2/decrypt/${requestId}`, {
3588
+ method: "GET",
3589
+ headers: {
3590
+ "Content-Type": "application/json"
3591
+ }
3592
+ });
3593
+ } catch (e) {
3594
+ throw new CofheError({
3595
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3596
+ message: `decrypt status poll failed`,
3597
+ hint: "Ensure the threshold network URL is valid and reachable.",
3598
+ cause: e instanceof Error ? e : void 0,
3599
+ context: {
3600
+ thresholdNetworkUrl,
3601
+ requestId
3602
+ }
3603
+ });
3604
+ }
3605
+ if (response.status === 404) {
3606
+ throw new CofheError({
3607
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3608
+ message: `decrypt request not found: ${requestId}`,
3609
+ hint: "The request may have expired or been invalid.",
3610
+ context: {
3611
+ thresholdNetworkUrl,
3612
+ requestId
3613
+ }
3614
+ });
3615
+ }
3616
+ if (!response.ok) {
3617
+ let errorMessage = `HTTP ${response.status}`;
3618
+ try {
3619
+ const errorBody = await response.json();
3620
+ const maybeMessage = errorBody.error_message || errorBody.message;
3621
+ if (typeof maybeMessage === "string" && maybeMessage.length > 0)
3622
+ errorMessage = maybeMessage;
3623
+ } catch {
3624
+ errorMessage = response.statusText || errorMessage;
3625
+ }
3626
+ throw new CofheError({
3627
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3628
+ message: `decrypt status poll failed: ${errorMessage}`,
3629
+ context: {
3630
+ thresholdNetworkUrl,
3631
+ requestId,
3632
+ status: response.status,
3633
+ statusText: response.statusText
3634
+ }
3635
+ });
3636
+ }
3637
+ let rawJson;
3638
+ try {
3639
+ rawJson = await response.json();
3640
+ } catch (e) {
3641
+ throw new CofheError({
3642
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3643
+ message: `Failed to parse decrypt status response`,
3644
+ cause: e instanceof Error ? e : void 0,
3645
+ context: {
3646
+ thresholdNetworkUrl,
3647
+ requestId
3648
+ }
3649
+ });
3650
+ }
3651
+ const statusResponse = assertDecryptStatusResponseV2(rawJson);
3652
+ if (statusResponse.status === "COMPLETED") {
3653
+ if (statusResponse.is_succeed === false) {
3654
+ const errorMessage = statusResponse.error_message || "Unknown error";
3655
+ throw new CofheError({
3656
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3657
+ message: `decrypt request failed: ${errorMessage}`,
3658
+ context: {
3659
+ thresholdNetworkUrl,
3660
+ requestId,
3661
+ statusResponse
3662
+ }
3663
+ });
3664
+ }
3665
+ if (statusResponse.error_message) {
3666
+ throw new CofheError({
3667
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3668
+ message: `decrypt request failed: ${statusResponse.error_message}`,
3669
+ context: {
3670
+ thresholdNetworkUrl,
3671
+ requestId,
3672
+ statusResponse
3673
+ }
3674
+ });
3675
+ }
3676
+ if (!Array.isArray(statusResponse.decrypted)) {
3677
+ throw new CofheError({
3678
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3679
+ message: "decrypt completed but response missing <decrypted> byte array",
3680
+ context: {
3681
+ thresholdNetworkUrl,
3682
+ requestId,
3683
+ statusResponse
3684
+ }
3685
+ });
3686
+ }
3687
+ const decryptedValue = parseDecryptedBytesToBigInt(statusResponse.decrypted);
3688
+ const signature = normalizeTnSignature(statusResponse.signature);
3689
+ return { decryptedValue, signature };
3690
+ }
3691
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
3692
+ attemptIndex += 1;
3693
+ }
3694
+ throw new CofheError({
3695
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3696
+ message: "Polling loop exited unexpectedly",
3697
+ context: {
3698
+ thresholdNetworkUrl,
3699
+ requestId
3700
+ }
3701
+ });
3702
+ }
3703
+ async function tnDecryptV2(params) {
3704
+ const { thresholdNetworkUrl, ctHash, chainId, permission, onPoll } = params;
3705
+ const requestId = await submitDecryptRequestV2(thresholdNetworkUrl, ctHash, chainId, permission);
3706
+ return await pollDecryptStatusV2(thresholdNetworkUrl, requestId, onPoll);
3707
+ }
3708
+
3709
+ // core/decrypt/decryptForTxBuilder.ts
3710
+ var DecryptForTxBuilder = class extends BaseBuilder {
3711
+ ctHash;
3712
+ permitHash;
3713
+ permit;
3714
+ permitSelection = "unset";
3715
+ pollCallback;
3716
+ constructor(params) {
3717
+ super({
3718
+ config: params.config,
3719
+ publicClient: params.publicClient,
3720
+ walletClient: params.walletClient,
3721
+ chainId: params.chainId,
3722
+ account: params.account,
3723
+ requireConnected: params.requireConnected
3724
+ });
3725
+ this.ctHash = params.ctHash;
3726
+ }
3727
+ setChainId(chainId) {
3728
+ this.chainId = chainId;
3729
+ return this;
3730
+ }
3731
+ getChainId() {
3732
+ return this.chainId;
3733
+ }
3734
+ setAccount(account) {
3735
+ this.account = account;
3736
+ return this;
3737
+ }
3738
+ getAccount() {
3739
+ return this.account;
3740
+ }
3741
+ onPoll(callback) {
3742
+ this.pollCallback = callback;
3743
+ return this;
3744
+ }
3745
+ withPermit(permitOrPermitHash) {
3746
+ if (this.permitSelection === "with-permit") {
3747
+ throw new CofheError({
3748
+ code: "INTERNAL_ERROR" /* InternalError */,
3749
+ message: "decryptForTx: withPermit() can only be selected once.",
3750
+ hint: "Choose the permit mode once. If you need a different permit, start a new decryptForTx() builder chain."
3751
+ });
3752
+ }
3753
+ if (this.permitSelection === "without-permit") {
3754
+ throw new CofheError({
3755
+ code: "INTERNAL_ERROR" /* InternalError */,
3756
+ message: "decryptForTx: cannot call withPermit() after withoutPermit() has been selected.",
3757
+ hint: "Choose exactly one permit mode: either call .withPermit(...) or .withoutPermit(), but not both."
3758
+ });
3759
+ }
3760
+ this.permitSelection = "with-permit";
3761
+ if (typeof permitOrPermitHash === "string") {
3762
+ this.permitHash = permitOrPermitHash;
3763
+ this.permit = void 0;
3764
+ } else if (permitOrPermitHash === void 0) {
3765
+ this.permitHash = void 0;
3766
+ this.permit = void 0;
3767
+ } else {
3768
+ this.permit = permitOrPermitHash;
3769
+ this.permitHash = void 0;
3770
+ }
3771
+ return this;
3772
+ }
3773
+ /**
3774
+ * Select "no permit" mode.
3775
+ *
3776
+ * This uses global allowance (no permit required) and sends an empty permission payload to `/decrypt`.
3777
+ */
3778
+ withoutPermit() {
3779
+ if (this.permitSelection === "without-permit") {
3780
+ throw new CofheError({
3781
+ code: "INTERNAL_ERROR" /* InternalError */,
3782
+ message: "decryptForTx: withoutPermit() can only be selected once.",
3783
+ hint: "Choose the permit mode once. If you need a different mode, start a new decryptForTx() builder chain."
3784
+ });
3785
+ }
3786
+ if (this.permitSelection === "with-permit") {
3787
+ throw new CofheError({
3788
+ code: "INTERNAL_ERROR" /* InternalError */,
3789
+ message: "decryptForTx: cannot call withoutPermit() after withPermit() has been selected.",
3790
+ hint: "Choose exactly one permit mode: either call .withPermit(...) or .withoutPermit(), but not both."
3791
+ });
3792
+ }
3793
+ this.permitSelection = "without-permit";
3794
+ this.permitHash = void 0;
3795
+ this.permit = void 0;
3796
+ return this;
3797
+ }
3798
+ getPermit() {
3799
+ return this.permit;
3800
+ }
3801
+ getPermitHash() {
3802
+ return this.permitHash;
3803
+ }
3804
+ async getThresholdNetworkUrl() {
3805
+ this.assertChainId();
3806
+ return getThresholdNetworkUrlOrThrow(this.config, this.chainId);
3807
+ }
3808
+ async getResolvedPermit() {
3809
+ if (this.permitSelection === "unset") {
3810
+ throw new CofheError({
3811
+ code: "INTERNAL_ERROR" /* InternalError */,
3812
+ message: "decryptForTx: missing permit selection; call withPermit(...) or withoutPermit() before execute().",
3813
+ hint: "Call .withPermit() to use the active permit, or .withoutPermit() for global allowance."
3814
+ });
3815
+ }
3816
+ if (this.permitSelection === "without-permit") {
3817
+ return null;
3818
+ }
3819
+ if (this.permit)
3820
+ return this.permit;
3821
+ this.assertChainId();
3822
+ this.assertAccount();
3823
+ if (this.permitHash) {
3824
+ const permit2 = await permits.getPermit(this.chainId, this.account, this.permitHash);
3825
+ if (!permit2) {
3826
+ throw new CofheError({
3827
+ code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
3828
+ message: `Permit with hash <${this.permitHash}> not found for account <${this.account}> and chainId <${this.chainId}>`,
3829
+ hint: "Ensure the permit exists and is valid.",
3830
+ context: {
3831
+ chainId: this.chainId,
3832
+ account: this.account,
3833
+ permitHash: this.permitHash
3834
+ }
3835
+ });
3836
+ }
3837
+ return permit2;
3838
+ }
3839
+ const permit = await permits.getActivePermit(this.chainId, this.account);
3840
+ if (!permit) {
3841
+ throw new CofheError({
3842
+ code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
3843
+ message: `Active permit not found for chainId <${this.chainId}> and account <${this.account}>`,
3844
+ hint: "Create a permit (e.g. client.permits.createSelf(...)) and/or set it active (client.permits.selectActivePermit(hash)).",
3845
+ context: {
3846
+ chainId: this.chainId,
3847
+ account: this.account
3848
+ }
3849
+ });
3850
+ }
3851
+ return permit;
3852
+ }
3853
+ /**
3854
+ * On hardhat, interact with MockThresholdNetwork contract
3855
+ */
3856
+ async mocksDecryptForTx(permit) {
3857
+ this.assertPublicClient();
3858
+ const delay = this.config.mocks.decryptDelay;
3859
+ if (delay > 0)
3860
+ await sleep(delay);
3861
+ const result = await cofheMocksDecryptForTx(this.ctHash, 0, permit, this.publicClient);
3862
+ return result;
3863
+ }
3864
+ /**
3865
+ * In the production context, perform a true decryption with the CoFHE coprocessor.
3866
+ */
3867
+ async productionDecryptForTx(permit) {
3868
+ this.assertChainId();
3869
+ this.assertPublicClient();
3870
+ const thresholdNetworkUrl = await this.getThresholdNetworkUrl();
3871
+ const permission = permit ? PermitUtils.getPermission(permit, true) : null;
3872
+ const { decryptedValue, signature } = await tnDecryptV2({
3873
+ ctHash: this.ctHash,
3874
+ chainId: this.chainId,
3875
+ permission,
3876
+ thresholdNetworkUrl,
3877
+ onPoll: this.pollCallback
3878
+ });
3879
+ return {
3880
+ ctHash: this.ctHash,
3881
+ decryptedValue,
3882
+ signature
3883
+ };
3884
+ }
3885
+ /**
3886
+ * Final step of the decryptForTx process. MUST BE CALLED LAST IN THE CHAIN.
3887
+ *
3888
+ * You must explicitly choose one permit mode before calling `execute()`:
3889
+ * - `withPermit(permit)` / `withPermit(permitHash)` / `withPermit()` (active permit)
3890
+ * - `withoutPermit()` (global allowance)
3891
+ */
3892
+ async execute() {
3893
+ const permit = await this.getResolvedPermit();
3894
+ if (permit !== null) {
3895
+ PermitUtils.validate(permit);
3896
+ const chainId = permit._signedDomain.chainId;
3897
+ if (chainId === hardhat2.id) {
3898
+ return await this.mocksDecryptForTx(permit);
3899
+ } else {
3900
+ return await this.productionDecryptForTx(permit);
3901
+ }
3902
+ } else {
3903
+ if (!this.chainId) {
3904
+ this.assertPublicClient();
3905
+ this.chainId = await getPublicClientChainID(this.publicClient);
3906
+ }
3907
+ this.assertChainId();
3908
+ if (this.chainId === hardhat2.id) {
3909
+ return await this.mocksDecryptForTx(null);
3910
+ } else {
3911
+ return await this.productionDecryptForTx(null);
3912
+ }
3913
+ }
3914
+ }
3915
+ };
3916
+ var decryptResultSignerAbi = viem.parseAbi(["function decryptResultSigner() view returns (address)"]);
3917
+ async function verifyDecryptResult(handle, cleartext, signature, publicClient) {
3918
+ const expectedSigner = await publicClient.readContract({
3919
+ address: TASK_MANAGER_ADDRESS,
3920
+ abi: decryptResultSignerAbi,
3921
+ functionName: "decryptResultSigner",
3922
+ args: []
3923
+ });
3924
+ if (viem.isAddressEqual(expectedSigner, viem.zeroAddress))
3925
+ return true;
3926
+ const ctHash = BigInt(handle);
3927
+ const messageHash = viem.keccak256(viem.encodePacked(["uint256", "uint256"], [ctHash, cleartext]));
3928
+ try {
3929
+ const recovered = await viem.recoverAddress({ hash: messageHash, signature });
3930
+ return viem.isAddressEqual(recovered, expectedSigner);
3931
+ } catch {
3932
+ return false;
3933
+ }
3934
+ }
3935
+
3936
+ // core/client.ts
3937
+ var InitialConnectStore = {
3938
+ connected: false,
3939
+ connecting: false,
3940
+ connectError: void 0,
3941
+ chainId: void 0,
3942
+ account: void 0,
3943
+ publicClient: void 0,
3944
+ walletClient: void 0
3945
+ };
3946
+ function createCofheClientBase(opts) {
3947
+ const keysStorage = createKeysStore(opts.config.fheKeyStorage);
3948
+ const connectStore = vanilla.createStore(() => InitialConnectStore);
3949
+ let connectAttemptId = 0;
3950
+ const updateConnectState = (partial) => {
3951
+ connectStore.setState((state) => ({ ...state, ...partial }));
3952
+ };
3953
+ const _requireConnected = () => {
3954
+ const state = connectStore.getState();
3955
+ const notConnected = !state.connected || !state.account || !state.chainId || !state.publicClient || !state.walletClient;
3956
+ if (notConnected) {
3957
+ throw new CofheError({
3958
+ code: "NOT_CONNECTED" /* NotConnected */,
3959
+ message: "Client must be connected, account and chainId must be initialized",
3960
+ hint: "Ensure client.connect() has been called and awaited.",
3961
+ context: {
3962
+ connected: state.connected,
3963
+ account: state.account,
3964
+ chainId: state.chainId,
3965
+ publicClient: state.publicClient,
3966
+ walletClient: state.walletClient
3967
+ }
3968
+ });
3969
+ }
3970
+ };
3971
+ async function connect(publicClient, walletClient) {
3972
+ const state = connectStore.getState();
3973
+ if (state.connected && state.publicClient === publicClient && state.walletClient === walletClient)
3974
+ return;
3975
+ connectAttemptId += 1;
3976
+ const localAttemptId = connectAttemptId;
3977
+ updateConnectState({
3978
+ ...InitialConnectStore,
3979
+ connecting: true
3980
+ });
3981
+ try {
3982
+ const chainId = await getPublicClientChainID(publicClient);
3983
+ const account = await getWalletClientAccount(walletClient);
3984
+ if (localAttemptId !== connectAttemptId)
3985
+ return;
3986
+ updateConnectState({
3987
+ connected: true,
3988
+ connecting: false,
3989
+ connectError: void 0,
3990
+ chainId,
3991
+ account,
3992
+ publicClient,
3993
+ walletClient
3994
+ });
3995
+ } catch (e) {
3996
+ if (localAttemptId !== connectAttemptId)
3997
+ return;
3998
+ updateConnectState({
3999
+ ...InitialConnectStore,
4000
+ connectError: e
4001
+ });
4002
+ throw e;
4003
+ }
4004
+ }
4005
+ function disconnect() {
4006
+ connectAttemptId += 1;
4007
+ updateConnectState({ ...InitialConnectStore });
4008
+ }
4009
+ function encryptInputs(inputs) {
4010
+ const state = connectStore.getState();
4011
+ return new EncryptInputsBuilder({
4012
+ inputs,
4013
+ account: state.account ?? void 0,
4014
+ chainId: state.chainId ?? void 0,
4015
+ config: opts.config,
4016
+ publicClient: state.publicClient ?? void 0,
4017
+ walletClient: state.walletClient ?? void 0,
4018
+ zkvWalletClient: opts.config._internal?.zkvWalletClient,
4019
+ tfhePublicKeyDeserializer: opts.tfhePublicKeyDeserializer,
4020
+ compactPkeCrsDeserializer: opts.compactPkeCrsDeserializer,
4021
+ zkBuilderAndCrsGenerator: opts.zkBuilderAndCrsGenerator,
4022
+ initTfhe: opts.initTfhe,
4023
+ zkProveWorkerFn: opts.zkProveWorkerFn,
4024
+ keysStorage,
4025
+ requireConnected: _requireConnected
4026
+ });
4027
+ }
4028
+ function decryptForView(ctHash, utype) {
4029
+ const state = connectStore.getState();
4030
+ return new DecryptForViewBuilder({
4031
+ ctHash,
4032
+ utype,
4033
+ chainId: state.chainId,
4034
+ account: state.account,
4035
+ config: opts.config,
4036
+ publicClient: state.publicClient,
4037
+ walletClient: state.walletClient,
4038
+ requireConnected: _requireConnected
4039
+ });
4040
+ }
4041
+ function decryptForTx(ctHash) {
4042
+ const state = connectStore.getState();
4043
+ return new DecryptForTxBuilder({
4044
+ ctHash,
4045
+ chainId: state.chainId,
4046
+ account: state.account,
4047
+ config: opts.config,
4048
+ publicClient: state.publicClient,
4049
+ walletClient: state.walletClient,
4050
+ requireConnected: _requireConnected
4051
+ });
4052
+ }
4053
+ function verifyDecryptResult2(handle, cleartext, signature) {
4054
+ _requireConnected();
4055
+ const { publicClient } = connectStore.getState();
4056
+ return verifyDecryptResult(handle, cleartext, signature, publicClient);
4057
+ }
4058
+ const _getChainIdAndAccount = (chainId, account) => {
4059
+ const state = connectStore.getState();
4060
+ const _chainId = chainId ?? state.chainId;
4061
+ const _account = account ?? state.account;
4062
+ if (_chainId == null || _account == null) {
4063
+ throw new CofheError({
4064
+ code: "NOT_CONNECTED" /* NotConnected */,
4065
+ message: "ChainId or account not available.",
4066
+ hint: "Ensure client.connect() has been called, or provide chainId and account explicitly.",
4067
+ context: {
4068
+ chainId: _chainId,
4069
+ account: _account
4070
+ }
4071
+ });
4072
+ }
4073
+ return { chainId: _chainId, account: _account };
4074
+ };
4075
+ const clientPermits = {
4076
+ // Pass through store access
4077
+ getSnapshot: permits.getSnapshot,
4078
+ subscribe: permits.subscribe,
4079
+ // Creation methods (require connection)
4080
+ createSelf: async (options, clients) => {
4081
+ _requireConnected();
4082
+ const { publicClient, walletClient } = clients ?? connectStore.getState();
4083
+ return permits.createSelf(options, publicClient, walletClient);
4084
+ },
4085
+ createSharing: async (options, clients) => {
4086
+ _requireConnected();
4087
+ const { publicClient, walletClient } = clients ?? connectStore.getState();
4088
+ return permits.createSharing(options, publicClient, walletClient);
4089
+ },
4090
+ importShared: async (options, clients) => {
4091
+ _requireConnected();
4092
+ const { publicClient, walletClient } = clients ?? connectStore.getState();
4093
+ return permits.importShared(options, publicClient, walletClient);
4094
+ },
4095
+ // Get or create methods (require connection)
4096
+ getOrCreateSelfPermit: async (chainId, account, options) => {
4097
+ _requireConnected();
4098
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4099
+ const { publicClient, walletClient } = connectStore.getState();
4100
+ return permits.getOrCreateSelfPermit(publicClient, walletClient, _chainId, _account, options);
4101
+ },
4102
+ getOrCreateSharingPermit: async (options, chainId, account) => {
4103
+ _requireConnected();
4104
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4105
+ const { publicClient, walletClient } = connectStore.getState();
4106
+ return permits.getOrCreateSharingPermit(publicClient, walletClient, options, _chainId, _account);
4107
+ },
4108
+ // Retrieval methods (auto-fill chainId/account)
4109
+ getPermit: (hash, chainId, account) => {
4110
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4111
+ return permits.getPermit(_chainId, _account, hash);
4112
+ },
4113
+ getPermits: (chainId, account) => {
4114
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4115
+ return permits.getPermits(_chainId, _account);
4116
+ },
4117
+ getActivePermit: (chainId, account) => {
4118
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4119
+ return permits.getActivePermit(_chainId, _account);
4120
+ },
4121
+ getActivePermitHash: (chainId, account) => {
4122
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4123
+ return permits.getActivePermitHash(_chainId, _account);
4124
+ },
4125
+ // Mutation methods (auto-fill chainId/account)
4126
+ selectActivePermit: (hash, chainId, account) => {
4127
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4128
+ return permits.selectActivePermit(_chainId, _account, hash);
4129
+ },
4130
+ removePermit: async (hash, chainId, account) => {
4131
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4132
+ return permits.removePermit(_chainId, _account, hash);
4133
+ },
4134
+ removeActivePermit: async (chainId, account) => {
4135
+ const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4136
+ return permits.removeActivePermit(_chainId, _account);
4137
+ },
4138
+ // Utils (no context needed)
4139
+ getHash: permits.getHash,
4140
+ serialize: permits.serialize,
4141
+ deserialize: permits.deserialize
4142
+ };
4143
+ return {
4144
+ // Zustand reactive accessors (don't export store directly to prevent mutation)
4145
+ getSnapshot: connectStore.getState,
4146
+ subscribe: connectStore.subscribe,
4147
+ // flags (read-only: reflect snapshot)
4148
+ get connection() {
4149
+ return connectStore.getState();
4150
+ },
4151
+ get connected() {
4152
+ return connectStore.getState().connected;
4153
+ },
4154
+ get connecting() {
4155
+ return connectStore.getState().connecting;
4156
+ },
4157
+ // config & platform-specific (read-only)
4158
+ config: opts.config,
4159
+ connect,
4160
+ disconnect,
4161
+ encryptInputs,
4162
+ decryptForView,
4163
+ /**
4164
+ * @deprecated Use `decryptForView` instead. Kept for backward compatibility.
4165
+ */
4166
+ decryptHandle: decryptForView,
4167
+ decryptForTx,
4168
+ verifyDecryptResult: verifyDecryptResult2,
4169
+ permits: clientPermits
4170
+ // Add SDK-specific methods below that require connection
4171
+ // Example:
4172
+ // async encryptData(data: unknown) {
4173
+ // requireConnected();
4174
+ // // Use state.publicClient and state.walletClient for implementation
4175
+ // },
4176
+ };
4177
+ }
4178
+
4179
+ // web/const.ts
4180
+ var hasDOM = typeof globalThis?.document !== "undefined" && typeof globalThis?.window !== "undefined";
4181
+
4182
+ // web/storage.ts
4183
+ var createWebStorage = (opts = { enableLog: false }) => {
4184
+ if (!hasDOM)
4185
+ throw new Error("createWebStorage can only be used in a browser environment");
4186
+ const client = iframeSharedStorage.constructClient({
4187
+ iframe: {
4188
+ src: "https://iframe-shared-storage.vercel.app/hub.html",
4189
+ messagingOptions: {
4190
+ enableLog: opts.enableLog ? "both" : void 0
4191
+ },
4192
+ iframeReadyTimeoutMs: 3e4,
4193
+ // if the iframe is not initied during this interval AND a reuqest is made, such request will throw an error
4194
+ methodCallTimeoutMs: 1e4,
4195
+ // if a method call is not answered during this interval, the call will throw an error
4196
+ methodCallRetries: 3
4197
+ // number of retries for a method call if it times out
4198
+ }
4199
+ });
4200
+ const indexedDBKeyval = client.indexedDBKeyval;
4201
+ return {
4202
+ getItem: async (name) => {
4203
+ return await indexedDBKeyval.get(name) ?? null;
4204
+ },
4205
+ setItem: async (name, value) => {
4206
+ await indexedDBKeyval.set(name, value);
4207
+ },
4208
+ removeItem: async (name) => {
4209
+ await indexedDBKeyval.del(name);
4210
+ }
4211
+ };
4212
+ };
4213
+ function createSsrStorage() {
4214
+ console.warn("using no-op server-side SSR storage");
4215
+ return {
4216
+ getItem: async () => null,
4217
+ setItem: async () => {
4218
+ },
4219
+ removeItem: async () => {
4220
+ }
4221
+ };
4222
+ }
4223
+
4224
+ // web/workerManager.ts
4225
+ var ZkProveWorkerManager = class {
4226
+ worker = null;
4227
+ pendingRequests = /* @__PURE__ */ new Map();
4228
+ requestCounter = 0;
4229
+ workerReady = false;
4230
+ initializationPromise = null;
4231
+ /**
4232
+ * Initialize the worker
4233
+ */
4234
+ async initializeWorker() {
4235
+ if (this.worker && this.workerReady) {
4236
+ return;
4237
+ }
4238
+ if (this.initializationPromise) {
4239
+ return this.initializationPromise;
4240
+ }
4241
+ this.initializationPromise = new Promise((resolve, reject) => {
4242
+ try {
4243
+ if (typeof Worker === "undefined") {
4244
+ reject(new Error("Web Workers not supported"));
4245
+ return;
4246
+ }
4247
+ try {
4248
+ 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" });
4249
+ } catch (error) {
4250
+ reject(new Error(`Failed to create worker: ${error}`));
4251
+ return;
4252
+ }
4253
+ this.worker.onmessage = (event) => {
4254
+ const { id, type, result, error } = event.data;
4255
+ if (type === "ready") {
4256
+ this.workerReady = true;
4257
+ resolve();
4258
+ return;
4259
+ }
4260
+ const pending = this.pendingRequests.get(id);
4261
+ if (!pending) {
4262
+ console.warn("[Worker Manager] Received response for unknown request:", id);
4263
+ return;
4264
+ }
4265
+ clearTimeout(pending.timeoutId);
4266
+ this.pendingRequests.delete(id);
4267
+ if (type === "success" && result) {
4268
+ pending.resolve(new Uint8Array(result));
4269
+ } else if (type === "error") {
4270
+ pending.reject(new Error(error || "Worker error"));
4271
+ } else {
4272
+ pending.reject(new Error("Invalid response from worker"));
4273
+ }
4274
+ };
4275
+ this.worker.onerror = (error) => {
4276
+ console.error("[Worker Manager] Worker error event:", error);
4277
+ console.error("[Worker Manager] Error message:", error.message);
4278
+ console.error("[Worker Manager] Error filename:", error.filename);
4279
+ console.error("[Worker Manager] Error lineno:", error.lineno);
4280
+ if (!this.workerReady) {
4281
+ reject(new Error(`Worker failed to initialize: ${error.message || "Unknown error"}`));
4282
+ }
4283
+ this.pendingRequests.forEach(({ reject: reject2, timeoutId }) => {
4284
+ clearTimeout(timeoutId);
4285
+ reject2(new Error("Worker encountered an error"));
4286
+ });
4287
+ this.pendingRequests.clear();
4288
+ };
4289
+ setTimeout(() => {
4290
+ if (!this.workerReady) {
4291
+ reject(new Error("Worker initialization timeout"));
4292
+ }
4293
+ }, 5e3);
4294
+ } catch (error) {
4295
+ reject(error);
4296
+ }
4297
+ });
4298
+ return this.initializationPromise;
4299
+ }
4300
+ /**
4301
+ * Submit a proof generation request to the worker
4302
+ */
4303
+ async submitProof(fheKeyHex, crsHex, items, metadata) {
4304
+ await this.initializeWorker();
4305
+ const id = `zkprove-${Date.now()}-${this.requestCounter++}`;
4306
+ return new Promise((resolve, reject) => {
4307
+ const timeoutId = setTimeout(() => {
4308
+ this.pendingRequests.delete(id);
4309
+ reject(new Error("Worker request timeout (30s)"));
4310
+ }, 3e4);
4311
+ this.pendingRequests.set(id, { resolve, reject, timeoutId });
4312
+ const message = {
4313
+ id,
4314
+ type: "zkProve",
4315
+ fheKeyHex,
4316
+ crsHex,
4317
+ items,
4318
+ metadata: Array.from(metadata)
4319
+ };
4320
+ this.worker.postMessage(message);
4321
+ });
4322
+ }
4323
+ /**
4324
+ * Terminate the worker and clean up
4325
+ */
4326
+ terminate() {
4327
+ if (this.worker) {
4328
+ this.worker.terminate();
4329
+ this.worker = null;
4330
+ this.workerReady = false;
4331
+ this.initializationPromise = null;
4332
+ }
4333
+ this.pendingRequests.forEach(({ reject, timeoutId }) => {
4334
+ clearTimeout(timeoutId);
4335
+ reject(new Error("Worker terminated"));
4336
+ });
4337
+ this.pendingRequests.clear();
4338
+ }
4339
+ /**
4340
+ * Check if worker is available
4341
+ */
4342
+ isAvailable() {
4343
+ return typeof Worker !== "undefined";
4344
+ }
4345
+ };
4346
+ var workerManager = null;
4347
+ function getWorkerManager() {
4348
+ if (!workerManager) {
4349
+ workerManager = new ZkProveWorkerManager();
4350
+ }
4351
+ return workerManager;
4352
+ }
4353
+ function terminateWorker() {
4354
+ if (workerManager) {
4355
+ workerManager.terminate();
4356
+ workerManager = null;
4357
+ }
4358
+ }
4359
+ function areWorkersAvailable() {
4360
+ return typeof Worker !== "undefined";
4361
+ }
4362
+ var tfheInitialized = false;
4363
+ async function initTfhe() {
4364
+ if (tfheInitialized)
4365
+ return false;
4366
+ await init__default.default();
4367
+ await init.init_panic_hook();
4368
+ tfheInitialized = true;
4369
+ return true;
4370
+ }
4371
+ var fromHexString2 = (hexString) => {
4372
+ const cleanString = hexString.length % 2 === 1 ? `0${hexString}` : hexString;
4373
+ const arr = cleanString.replace(/^0x/, "").match(/.{1,2}/g);
4374
+ if (!arr)
4375
+ return new Uint8Array();
4376
+ return new Uint8Array(arr.map((byte) => parseInt(byte, 16)));
4377
+ };
4378
+ var tfhePublicKeyDeserializer = (buff) => {
4379
+ init.TfheCompactPublicKey.deserialize(fromHexString2(buff));
4380
+ };
4381
+ var compactPkeCrsDeserializer = (buff) => {
4382
+ init.CompactPkeCrs.deserialize(fromHexString2(buff));
4383
+ };
4384
+ var zkBuilderAndCrsGenerator = (fhe, crs) => {
4385
+ const fhePublicKey = init.TfheCompactPublicKey.deserialize(fromHexString2(fhe));
4386
+ const zkBuilder = init.ProvenCompactCiphertextList.builder(fhePublicKey);
4387
+ const zkCrs = init.CompactPkeCrs.deserialize(fromHexString2(crs));
4388
+ return { zkBuilder, zkCrs };
4389
+ };
4390
+ async function zkProveWithWorker2(fheKeyHex, crsHex, items, metadata) {
4391
+ const serializedItems = items.map((item) => ({
4392
+ utype: fheTypeToString(item.utype),
4393
+ data: typeof item.data === "bigint" ? item.data.toString() : item.data
4394
+ }));
4395
+ const workerManager2 = getWorkerManager();
4396
+ return await workerManager2.submitProof(fheKeyHex, crsHex, serializedItems, metadata);
4397
+ }
4398
+ function createCofheConfig(config) {
4399
+ return createCofheConfigBase({
4400
+ environment: "web",
4401
+ ...config,
4402
+ fheKeyStorage: config.fheKeyStorage === null ? null : config.fheKeyStorage ?? (hasDOM ? createWebStorage() : createSsrStorage())
4403
+ });
4404
+ }
4405
+ function createCofheClient(config) {
4406
+ return createCofheClientBase({
4407
+ config,
4408
+ zkBuilderAndCrsGenerator,
4409
+ tfhePublicKeyDeserializer,
4410
+ compactPkeCrsDeserializer,
4411
+ initTfhe,
4412
+ // Always provide the worker function if available - config.useWorkers controls usage
4413
+ // areWorkersAvailable will return true if the Worker API is available and false in Node.js
4414
+ zkProveWorkerFn: areWorkersAvailable() ? zkProveWithWorker2 : void 0
4415
+ });
4416
+ }
4417
+ function createCofheClientWithCustomWorker(config, customZkProveWorkerFn) {
4418
+ return createCofheClientBase({
4419
+ config,
4420
+ zkBuilderAndCrsGenerator,
4421
+ tfhePublicKeyDeserializer,
4422
+ compactPkeCrsDeserializer,
4423
+ initTfhe,
4424
+ zkProveWorkerFn: customZkProveWorkerFn
4425
+ });
4426
+ }
4427
+
4428
+ exports.areWorkersAvailable = areWorkersAvailable;
4429
+ exports.createCofheClient = createCofheClient;
4430
+ exports.createCofheClientWithCustomWorker = createCofheClientWithCustomWorker;
4431
+ exports.createCofheConfig = createCofheConfig;
4432
+ exports.createSsrStorage = createSsrStorage;
4433
+ exports.hasDOM = hasDOM;
4434
+ exports.terminateWorker = terminateWorker;