@cofhe/sdk 0.0.0-beta-20251027110729

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