@cofhe/sdk 0.1.0 → 0.1.1

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