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