@cofhe/sdk 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/core/baseBuilder.ts +18 -18
  3. package/core/client.test.ts +58 -55
  4. package/core/client.ts +50 -30
  5. package/core/clientTypes.ts +21 -17
  6. package/core/config.test.ts +32 -33
  7. package/core/config.ts +47 -48
  8. package/core/consts.ts +6 -2
  9. package/core/decrypt/{MockQueryDecrypterAbi.ts → MockThresholdNetworkAbi.ts} +71 -21
  10. package/core/decrypt/cofheMocksDecryptForTx.ts +142 -0
  11. package/core/decrypt/{cofheMocksSealOutput.ts → cofheMocksDecryptForView.ts} +12 -12
  12. package/core/decrypt/decryptForTxBuilder.ts +340 -0
  13. package/core/decrypt/{decryptHandleBuilder.ts → decryptForViewBuilder.ts} +75 -42
  14. package/core/decrypt/tnDecrypt.ts +232 -0
  15. package/core/decrypt/tnSealOutputV1.ts +5 -5
  16. package/core/decrypt/tnSealOutputV2.ts +27 -27
  17. package/core/encrypt/cofheMocksZkVerifySign.ts +15 -15
  18. package/core/encrypt/encryptInputsBuilder.test.ts +57 -61
  19. package/core/encrypt/encryptInputsBuilder.ts +65 -42
  20. package/core/encrypt/zkPackProveVerify.ts +11 -11
  21. package/core/error.ts +18 -18
  22. package/core/fetchKeys.test.ts +3 -3
  23. package/core/fetchKeys.ts +3 -3
  24. package/core/index.ts +14 -11
  25. package/core/utils.ts +10 -10
  26. package/dist/{chunk-I5WFEYXX.js → chunk-2TPSCOW3.js} +791 -209
  27. package/dist/{chunk-R3B5TMVX.js → chunk-NWDKXBIP.js} +3 -2
  28. package/dist/{clientTypes-RqkgkV2i.d.ts → clientTypes-6aTZPQ_4.d.ts} +204 -85
  29. package/dist/{clientTypes-e4filDzK.d.cts → clientTypes-Bhq7pCSA.d.cts} +204 -85
  30. package/dist/core.cjs +799 -214
  31. package/dist/core.d.cts +25 -23
  32. package/dist/core.d.ts +25 -23
  33. package/dist/core.js +2 -2
  34. package/dist/node.cjs +748 -165
  35. package/dist/node.d.cts +10 -10
  36. package/dist/node.d.ts +10 -10
  37. package/dist/node.js +7 -7
  38. package/dist/permits.js +1 -1
  39. package/dist/web.cjs +751 -168
  40. package/dist/web.d.cts +11 -11
  41. package/dist/web.d.ts +11 -11
  42. package/dist/web.js +9 -9
  43. package/node/client.test.ts +34 -34
  44. package/node/config.test.ts +11 -11
  45. package/node/encryptInputs.test.ts +29 -29
  46. package/node/index.ts +15 -15
  47. package/package.json +1 -1
  48. package/web/client.web.test.ts +34 -34
  49. package/web/config.web.test.ts +11 -11
  50. package/web/encryptInputs.web.test.ts +29 -29
  51. package/web/index.ts +19 -19
  52. package/web/worker.builder.web.test.ts +28 -28
  53. package/web/worker.config.web.test.ts +47 -47
  54. package/web/worker.output.web.test.ts +10 -10
package/dist/node.cjs CHANGED
@@ -35,7 +35,7 @@ var nacl__namespace = /*#__PURE__*/_interopNamespace(nacl);
35
35
  // core/client.ts
36
36
 
37
37
  // core/error.ts
38
- var CofhesdkError = class _CofhesdkError extends Error {
38
+ var CofheError = class _CofheError extends Error {
39
39
  code;
40
40
  cause;
41
41
  hint;
@@ -43,25 +43,25 @@ var CofhesdkError = class _CofhesdkError extends Error {
43
43
  constructor({ code, message, cause, hint, context }) {
44
44
  const fullMessage = cause ? `${message} | Caused by: ${cause.message}` : message;
45
45
  super(fullMessage);
46
- this.name = "CofhesdkError";
46
+ this.name = "CofheError";
47
47
  this.code = code;
48
48
  this.cause = cause;
49
49
  this.hint = hint;
50
50
  this.context = context;
51
51
  if (Error.captureStackTrace) {
52
- Error.captureStackTrace(this, _CofhesdkError);
52
+ Error.captureStackTrace(this, _CofheError);
53
53
  }
54
54
  }
55
55
  /**
56
- * Creates a CofhesdkError from an unknown error
57
- * If the error is a CofhesdkError, it is returned unchanged, else a new CofhesdkError is created
58
- * If a wrapperError is provided, it is used to create the new CofhesdkError, else a default is used
56
+ * Creates a CofheError from an unknown error
57
+ * If the error is a CofheError, it is returned unchanged, else a new CofheError is created
58
+ * If a wrapperError is provided, it is used to create the new CofheError, else a default is used
59
59
  */
60
60
  static fromError(error, wrapperError) {
61
- if (isCofhesdkError(error))
61
+ if (isCofheError(error))
62
62
  return error;
63
63
  const cause = error instanceof Error ? error : new Error(`${error}`);
64
- return new _CofhesdkError({
64
+ return new _CofheError({
65
65
  code: wrapperError?.code ?? "INTERNAL_ERROR" /* InternalError */,
66
66
  message: wrapperError?.message ?? "An internal error occurred",
67
67
  hint: wrapperError?.hint,
@@ -121,7 +121,7 @@ var bigintSafeJsonStringify = (value) => {
121
121
  return value2;
122
122
  });
123
123
  };
124
- var isCofhesdkError = (error) => error instanceof CofhesdkError;
124
+ var isCofheError = (error) => error instanceof CofheError;
125
125
 
126
126
  // core/types.ts
127
127
  var FheUintUTypes = [
@@ -165,14 +165,14 @@ async function getPublicClientChainID(publicClient) {
165
165
  try {
166
166
  chainId = publicClient.chain?.id ?? await publicClient.getChainId();
167
167
  } catch (e) {
168
- throw new CofhesdkError({
168
+ throw new CofheError({
169
169
  code: "PUBLIC_WALLET_GET_CHAIN_ID_FAILED" /* PublicWalletGetChainIdFailed */,
170
170
  message: "getting chain ID from public client failed",
171
171
  cause: e instanceof Error ? e : void 0
172
172
  });
173
173
  }
174
174
  if (chainId === null) {
175
- throw new CofhesdkError({
175
+ throw new CofheError({
176
176
  code: "PUBLIC_WALLET_GET_CHAIN_ID_FAILED" /* PublicWalletGetChainIdFailed */,
177
177
  message: "chain ID from public client is null"
178
178
  });
@@ -187,14 +187,14 @@ async function getWalletClientAccount(walletClient) {
187
187
  address = (await walletClient.getAddresses())?.[0];
188
188
  }
189
189
  } catch (e) {
190
- throw new CofhesdkError({
190
+ throw new CofheError({
191
191
  code: "PUBLIC_WALLET_GET_ADDRESSES_FAILED" /* PublicWalletGetAddressesFailed */,
192
192
  message: "getting address from wallet client failed",
193
193
  cause: e instanceof Error ? e : void 0
194
194
  });
195
195
  }
196
196
  if (!address) {
197
- throw new CofhesdkError({
197
+ throw new CofheError({
198
198
  code: "PUBLIC_WALLET_GET_ADDRESSES_FAILED" /* PublicWalletGetAddressesFailed */,
199
199
  message: "address from wallet client is null"
200
200
  });
@@ -262,7 +262,7 @@ var zkPack = (items, builder) => {
262
262
  break;
263
263
  }
264
264
  default: {
265
- throw new CofhesdkError({
265
+ throw new CofheError({
266
266
  code: "ZK_PACK_FAILED" /* ZkPackFailed */,
267
267
  message: `Invalid utype: ${item.utype}`,
268
268
  hint: `Ensure that the utype is valid, using the Encryptable type, for example: Encryptable.uint128(100n)`,
@@ -274,7 +274,7 @@ var zkPack = (items, builder) => {
274
274
  }
275
275
  }
276
276
  if (totalBits > MAX_ENCRYPTABLE_BITS) {
277
- throw new CofhesdkError({
277
+ throw new CofheError({
278
278
  code: "ZK_PACK_FAILED" /* ZkPackFailed */,
279
279
  message: `Total bits ${totalBits} exceeds ${MAX_ENCRYPTABLE_BITS}`,
280
280
  hint: `Ensure that the total bits of the items to encrypt does not exceed ${MAX_ENCRYPTABLE_BITS}`,
@@ -338,14 +338,14 @@ var zkVerify = async (verifierUrl, serializedBytes, address, securityZone, chain
338
338
  });
339
339
  if (!response.ok) {
340
340
  const errorBody = await response.text();
341
- throw new CofhesdkError({
341
+ throw new CofheError({
342
342
  code: "ZK_VERIFY_FAILED" /* ZkVerifyFailed */,
343
343
  message: `HTTP error! ZK proof verification failed - ${errorBody}`
344
344
  });
345
345
  }
346
346
  const json = await response.json();
347
347
  if (json.status !== "success") {
348
- throw new CofhesdkError({
348
+ throw new CofheError({
349
349
  code: "ZK_VERIFY_FAILED" /* ZkVerifyFailed */,
350
350
  message: `ZK proof verification response malformed - ${json.error}`
351
351
  });
@@ -357,7 +357,7 @@ var zkVerify = async (verifierUrl, serializedBytes, address, securityZone, chain
357
357
  };
358
358
  });
359
359
  } catch (e) {
360
- throw new CofhesdkError({
360
+ throw new CofheError({
361
361
  code: "ZK_VERIFY_FAILED" /* ZkVerifyFailed */,
362
362
  message: `ZK proof verification failed`,
363
363
  cause: e instanceof Error ? e : void 0
@@ -479,8 +479,9 @@ var MockZkVerifierAbi = [
479
479
  // core/consts.ts
480
480
  var TASK_MANAGER_ADDRESS = "0xeA30c4B8b44078Bbf8a6ef5b9f1eC1626C7848D9";
481
481
  var MOCKS_ZK_VERIFIER_ADDRESS = "0x0000000000000000000000000000000000005001";
482
- var MOCKS_QUERY_DECRYPTER_ADDRESS = "0x0000000000000000000000000000000000005002";
482
+ var MOCKS_THRESHOLD_NETWORK_ADDRESS = "0x0000000000000000000000000000000000005002";
483
483
  var MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY = "0x6C8D7F768A6BB4AAFE85E8A2F5A9680355239C7E14646ED62B044E39DE154512";
484
+ var MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY = "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d";
484
485
 
485
486
  // core/encrypt/cofheMocksZkVerifySign.ts
486
487
  function createMockZkVerifierSigner() {
@@ -525,7 +526,7 @@ async function cofheMocksCheckEncryptableBits(items) {
525
526
  }
526
527
  }
527
528
  if (totalBits > MAX_ENCRYPTABLE_BITS) {
528
- throw new CofhesdkError({
529
+ throw new CofheError({
529
530
  code: "ZK_PACK_FAILED" /* ZkPackFailed */,
530
531
  message: `Total bits ${totalBits} exceeds ${MAX_ENCRYPTABLE_BITS}`,
531
532
  hint: `Ensure that the total bits of the items to encrypt does not exceed ${MAX_ENCRYPTABLE_BITS}`,
@@ -554,7 +555,7 @@ async function calcCtHashes(items, account, securityZone, publicClient) {
554
555
  args: calcCtHashesArgs
555
556
  });
556
557
  } catch (err) {
557
- throw new CofhesdkError({
558
+ throw new CofheError({
558
559
  code: "ZK_MOCKS_CALC_CT_HASHES_FAILED" /* ZkMocksCalcCtHashesFailed */,
559
560
  message: `mockZkVerifySign calcCtHashes failed while calling zkVerifyCalcCtHashesPacked`,
560
561
  cause: err instanceof Error ? err : void 0,
@@ -569,7 +570,7 @@ async function calcCtHashes(items, account, securityZone, publicClient) {
569
570
  });
570
571
  }
571
572
  if (ctHashes.length !== items.length) {
572
- throw new CofhesdkError({
573
+ throw new CofheError({
573
574
  code: "ZK_MOCKS_CALC_CT_HASHES_FAILED" /* ZkMocksCalcCtHashesFailed */,
574
575
  message: `mockZkVerifySign calcCtHashes returned incorrect number of ctHashes`,
575
576
  context: {
@@ -600,7 +601,7 @@ async function insertCtHashes(items, walletClient) {
600
601
  account
601
602
  });
602
603
  } catch (err) {
603
- throw new CofhesdkError({
604
+ throw new CofheError({
604
605
  code: "ZK_MOCKS_INSERT_CT_HASHES_FAILED" /* ZkMocksInsertCtHashesFailed */,
605
606
  message: `mockZkVerifySign insertPackedCtHashes failed while calling insertPackedCtHashes`,
606
607
  cause: err instanceof Error ? err : void 0,
@@ -618,7 +619,7 @@ async function createProofSignatures(items, securityZone) {
618
619
  try {
619
620
  encInputSignerClient = createMockZkVerifierSigner();
620
621
  } catch (err) {
621
- throw new CofhesdkError({
622
+ throw new CofheError({
622
623
  code: "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED" /* ZkMocksCreateProofSignatureFailed */,
623
624
  message: `mockZkVerifySign createProofSignatures failed while creating wallet client`,
624
625
  cause: err instanceof Error ? err : void 0,
@@ -639,7 +640,7 @@ async function createProofSignatures(items, securityZone) {
639
640
  signatures.push(signature);
640
641
  }
641
642
  } catch (err) {
642
- throw new CofhesdkError({
643
+ throw new CofheError({
643
644
  code: "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED" /* ZkMocksCreateProofSignatureFailed */,
644
645
  message: `mockZkVerifySign createProofSignatures failed while calling signMessage`,
645
646
  cause: err instanceof Error ? err : void 0,
@@ -650,7 +651,7 @@ async function createProofSignatures(items, securityZone) {
650
651
  });
651
652
  }
652
653
  if (signatures.length !== items.length) {
653
- throw new CofhesdkError({
654
+ throw new CofheError({
654
655
  code: "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED" /* ZkMocksCreateProofSignatureFailed */,
655
656
  message: `mockZkVerifySign createProofSignatures returned incorrect number of signatures`,
656
657
  context: {
@@ -707,13 +708,11 @@ var hardhat2 = defineChain({
707
708
  thresholdNetworkUrl: "http://127.0.0.1:3000",
708
709
  environment: "MOCK"
709
710
  });
710
- var CofhesdkConfigSchema = zod.z.object({
711
+ var CofheConfigSchema = zod.z.object({
711
712
  /** Environment that the SDK is running in */
712
713
  environment: zod.z.enum(["node", "hardhat", "web", "react"]).optional().default("node"),
713
714
  /** List of supported chain configurations */
714
715
  supportedChains: zod.z.array(zod.z.custom()),
715
- /** How permits are generated */
716
- permitGeneration: zod.z.enum(["ON_CONNECT", "ON_DECRYPT_HANDLES", "MANUAL"]).optional().default("ON_CONNECT"),
717
716
  /** Default permit expiration in seconds, default is 30 days */
718
717
  defaultPermitExpiration: zod.z.number().optional().default(60 * 60 * 24 * 30),
719
718
  /** Storage method for fhe keys (defaults to indexedDB on web, filesystem on node) */
@@ -732,24 +731,25 @@ var CofhesdkConfigSchema = zod.z.object({
732
731
  useWorkers: zod.z.boolean().optional().default(true),
733
732
  /** Mocks configs */
734
733
  mocks: zod.z.object({
735
- sealOutputDelay: zod.z.number().optional().default(0)
736
- }).optional().default({ sealOutputDelay: 0 }),
734
+ decryptDelay: zod.z.number().optional().default(0),
735
+ encryptDelay: zod.z.union([zod.z.number(), zod.z.tuple([zod.z.number(), zod.z.number(), zod.z.number(), zod.z.number(), zod.z.number()])]).optional().default([100, 100, 100, 500, 500])
736
+ }).optional().default({ decryptDelay: 0, encryptDelay: [100, 100, 100, 500, 500] }),
737
737
  /** Internal configuration */
738
738
  _internal: zod.z.object({
739
739
  zkvWalletClient: zod.z.any().optional()
740
740
  }).optional()
741
741
  });
742
- function createCofhesdkConfigBase(config) {
743
- const result = CofhesdkConfigSchema.safeParse(config);
742
+ function createCofheConfigBase(config) {
743
+ const result = CofheConfigSchema.safeParse(config);
744
744
  if (!result.success) {
745
- throw new Error(`Invalid cofhesdk configuration: ${zod.z.prettifyError(result.error)}`, { cause: result.error });
745
+ throw new Error(`Invalid cofhe configuration: ${zod.z.prettifyError(result.error)}`, { cause: result.error });
746
746
  }
747
747
  return result.data;
748
748
  }
749
749
  function getSupportedChainOrThrow(config, chainId) {
750
750
  const supportedChain = config.supportedChains.find((chain) => chain.id === chainId);
751
751
  if (!supportedChain) {
752
- throw new CofhesdkError({
752
+ throw new CofheError({
753
753
  code: "UNSUPPORTED_CHAIN" /* UnsupportedChain */,
754
754
  message: `Config does not support chain <${chainId}>`,
755
755
  hint: "Ensure config passed to client has been created with this chain in the config.supportedChains array.",
@@ -765,7 +765,7 @@ function getCoFheUrlOrThrow(config, chainId) {
765
765
  const supportedChain = getSupportedChainOrThrow(config, chainId);
766
766
  const url = supportedChain.coFheUrl;
767
767
  if (!url) {
768
- throw new CofhesdkError({
768
+ throw new CofheError({
769
769
  code: "MISSING_CONFIG" /* MissingConfig */,
770
770
  message: `CoFHE URL is not configured for chain <${chainId}>`,
771
771
  hint: "Ensure this chain config includes a coFheUrl property.",
@@ -778,7 +778,7 @@ function getZkVerifierUrlOrThrow(config, chainId) {
778
778
  const supportedChain = getSupportedChainOrThrow(config, chainId);
779
779
  const url = supportedChain.verifierUrl;
780
780
  if (!url) {
781
- throw new CofhesdkError({
781
+ throw new CofheError({
782
782
  code: "ZK_VERIFIER_URL_UNINITIALIZED" /* ZkVerifierUrlUninitialized */,
783
783
  message: `ZK verifier URL is not configured for chain <${chainId}>`,
784
784
  hint: "Ensure this chain config includes a verifierUrl property.",
@@ -791,7 +791,7 @@ function getThresholdNetworkUrlOrThrow(config, chainId) {
791
791
  const supportedChain = getSupportedChainOrThrow(config, chainId);
792
792
  const url = supportedChain.thresholdNetworkUrl;
793
793
  if (!url) {
794
- throw new CofhesdkError({
794
+ throw new CofheError({
795
795
  code: "THRESHOLD_NETWORK_URL_UNINITIALIZED" /* ThresholdNetworkUrlUninitialized */,
796
796
  message: `Threshold network URL is not configured for chain <${chainId}>`,
797
797
  hint: "Ensure this chain config includes a thresholdNetworkUrl property.",
@@ -1003,7 +1003,7 @@ var BaseBuilder = class {
1003
1003
  account;
1004
1004
  constructor(params) {
1005
1005
  if (!params.config) {
1006
- throw new CofhesdkError({
1006
+ throw new CofheError({
1007
1007
  code: "MISSING_CONFIG" /* MissingConfig */,
1008
1008
  message: "Builder config is undefined",
1009
1009
  hint: "Ensure client has been created with a config.",
@@ -1021,12 +1021,12 @@ var BaseBuilder = class {
1021
1021
  }
1022
1022
  /**
1023
1023
  * Asserts that this.chainId is populated
1024
- * @throws {CofhesdkError} If chainId is not set
1024
+ * @throws {CofheError} If chainId is not set
1025
1025
  */
1026
1026
  assertChainId() {
1027
1027
  if (this.chainId)
1028
1028
  return;
1029
- throw new CofhesdkError({
1029
+ throw new CofheError({
1030
1030
  code: "CHAIN_ID_UNINITIALIZED" /* ChainIdUninitialized */,
1031
1031
  message: "Chain ID is not set",
1032
1032
  hint: "Ensure client.connect() has been called and awaited, or use setChainId(...) to set the chainId explicitly.",
@@ -1037,12 +1037,12 @@ var BaseBuilder = class {
1037
1037
  }
1038
1038
  /**
1039
1039
  * Asserts that this.account is populated
1040
- * @throws {CofhesdkError} If account is not set
1040
+ * @throws {CofheError} If account is not set
1041
1041
  */
1042
1042
  assertAccount() {
1043
1043
  if (this.account)
1044
1044
  return;
1045
- throw new CofhesdkError({
1045
+ throw new CofheError({
1046
1046
  code: "ACCOUNT_UNINITIALIZED" /* AccountUninitialized */,
1047
1047
  message: "Account is not set",
1048
1048
  hint: "Ensure client.connect() has been called and awaited, or use setAccount(...) to set the account explicitly.",
@@ -1053,12 +1053,12 @@ var BaseBuilder = class {
1053
1053
  }
1054
1054
  /**
1055
1055
  * Asserts that this.publicClient is populated
1056
- * @throws {CofhesdkError} If publicClient is not set
1056
+ * @throws {CofheError} If publicClient is not set
1057
1057
  */
1058
1058
  assertPublicClient() {
1059
1059
  if (this.publicClient)
1060
1060
  return;
1061
- throw new CofhesdkError({
1061
+ throw new CofheError({
1062
1062
  code: "MISSING_PUBLIC_CLIENT" /* MissingPublicClient */,
1063
1063
  message: "Public client not found",
1064
1064
  hint: "Ensure client.connect() has been called with a publicClient.",
@@ -1069,12 +1069,12 @@ var BaseBuilder = class {
1069
1069
  }
1070
1070
  /**
1071
1071
  * Asserts that this.walletClient is populated
1072
- * @throws {CofhesdkError} If walletClient is not set
1072
+ * @throws {CofheError} If walletClient is not set
1073
1073
  */
1074
1074
  assertWalletClient() {
1075
1075
  if (this.walletClient)
1076
1076
  return;
1077
- throw new CofhesdkError({
1077
+ throw new CofheError({
1078
1078
  code: "MISSING_WALLET_CLIENT" /* MissingWalletClient */,
1079
1079
  message: "Wallet client not found",
1080
1080
  hint: "Ensure client.connect() has been called with a walletClient.",
@@ -1119,7 +1119,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1119
1119
  this.securityZone = params.securityZone ?? 0;
1120
1120
  this.zkvWalletClient = params.zkvWalletClient;
1121
1121
  if (!params.tfhePublicKeyDeserializer) {
1122
- throw new CofhesdkError({
1122
+ throw new CofheError({
1123
1123
  code: "MISSING_TFHE_PUBLIC_KEY_DESERIALIZER" /* MissingTfhePublicKeyDeserializer */,
1124
1124
  message: "EncryptInputsBuilder tfhePublicKeyDeserializer is undefined",
1125
1125
  hint: "Ensure client has been created with a tfhePublicKeyDeserializer.",
@@ -1130,7 +1130,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1130
1130
  }
1131
1131
  this.tfhePublicKeyDeserializer = params.tfhePublicKeyDeserializer;
1132
1132
  if (!params.compactPkeCrsDeserializer) {
1133
- throw new CofhesdkError({
1133
+ throw new CofheError({
1134
1134
  code: "MISSING_COMPACT_PKE_CRS_DESERIALIZER" /* MissingCompactPkeCrsDeserializer */,
1135
1135
  message: "EncryptInputsBuilder compactPkeCrsDeserializer is undefined",
1136
1136
  hint: "Ensure client has been created with a compactPkeCrsDeserializer.",
@@ -1141,7 +1141,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1141
1141
  }
1142
1142
  this.compactPkeCrsDeserializer = params.compactPkeCrsDeserializer;
1143
1143
  if (!params.zkBuilderAndCrsGenerator) {
1144
- throw new CofhesdkError({
1144
+ throw new CofheError({
1145
1145
  code: "MISSING_ZK_BUILDER_AND_CRS_GENERATOR" /* MissingZkBuilderAndCrsGenerator */,
1146
1146
  message: "EncryptInputsBuilder zkBuilderAndCrsGenerator is undefined",
1147
1147
  hint: "Ensure client has been created with a zkBuilderAndCrsGenerator.",
@@ -1165,7 +1165,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1165
1165
  * ```typescript
1166
1166
  * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1167
1167
  * .setAccount("0x123")
1168
- * .encrypt();
1168
+ * .execute();
1169
1169
  * ```
1170
1170
  *
1171
1171
  * @returns The chainable EncryptInputsBuilder instance.
@@ -1186,7 +1186,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1186
1186
  * ```typescript
1187
1187
  * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1188
1188
  * .setChainId(11155111)
1189
- * .encrypt();
1189
+ * .execute();
1190
1190
  * ```
1191
1191
  *
1192
1192
  * @returns The chainable EncryptInputsBuilder instance.
@@ -1207,7 +1207,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1207
1207
  * ```typescript
1208
1208
  * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1209
1209
  * .setSecurityZone(1)
1210
- * .encrypt();
1210
+ * .execute();
1211
1211
  * ```
1212
1212
  *
1213
1213
  * @returns The chainable EncryptInputsBuilder instance.
@@ -1228,7 +1228,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1228
1228
  * ```typescript
1229
1229
  * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1230
1230
  * .setUseWorker(false)
1231
- * .encrypt();
1231
+ * .execute();
1232
1232
  * ```
1233
1233
  *
1234
1234
  * @returns The chainable EncryptInputsBuilder instance.
@@ -1262,13 +1262,13 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1262
1262
  * Example:
1263
1263
  * ```typescript
1264
1264
  * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1265
- * .setStepCallback((step: EncryptStep) => console.log(step))
1266
- * .encrypt();
1265
+ * .onStep((step: EncryptStep) => console.log(step))
1266
+ * .execute();
1267
1267
  * ```
1268
1268
  *
1269
1269
  * @returns The EncryptInputsBuilder instance.
1270
1270
  */
1271
- setStepCallback(callback) {
1271
+ onStep(callback) {
1272
1272
  this.stepCallback = callback;
1273
1273
  return this;
1274
1274
  }
@@ -1291,7 +1291,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1291
1291
  this.stepCallback(step, { ...context, isStart: false, isEnd: true, duration });
1292
1292
  }
1293
1293
  /**
1294
- * zkVerifierUrl is included in the chains exported from cofhesdk/chains for use in CofhesdkConfig.supportedChains
1294
+ * zkVerifierUrl is included in the chains exported from @cofhe/sdk/chains for use in CofheConfig.supportedChains
1295
1295
  * Users should generally not set this manually.
1296
1296
  */
1297
1297
  async getZkVerifierUrl() {
@@ -1299,7 +1299,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1299
1299
  return getZkVerifierUrlOrThrow(this.config, this.chainId);
1300
1300
  }
1301
1301
  /**
1302
- * initTfhe is a platform-specific dependency injected into core/createCofhesdkClientBase by web/createCofhesdkClient and node/createCofhesdkClient
1302
+ * initTfhe is a platform-specific dependency injected into core/createCofheClientBase by web/createCofheClient and node/createCofheClient
1303
1303
  * web/ uses zama "tfhe"
1304
1304
  * node/ uses zama "node-tfhe"
1305
1305
  * Users should not set this manually.
@@ -1310,7 +1310,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1310
1310
  try {
1311
1311
  return await this.initTfhe();
1312
1312
  } catch (error) {
1313
- throw CofhesdkError.fromError(error, {
1313
+ throw CofheError.fromError(error, {
1314
1314
  code: "INIT_TFHE_FAILED" /* InitTfheFailed */,
1315
1315
  message: `Failed to initialize TFHE`,
1316
1316
  context: {
@@ -1329,7 +1329,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1329
1329
  try {
1330
1330
  await this.keysStorage?.rehydrateKeysStore();
1331
1331
  } catch (error) {
1332
- throw CofhesdkError.fromError(error, {
1332
+ throw CofheError.fromError(error, {
1333
1333
  code: "REHYDRATE_KEYS_STORE_FAILED" /* RehydrateKeysStoreFailed */,
1334
1334
  message: `Failed to rehydrate keys store`,
1335
1335
  context: {
@@ -1351,7 +1351,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1351
1351
  this.keysStorage
1352
1352
  );
1353
1353
  } catch (error) {
1354
- throw CofhesdkError.fromError(error, {
1354
+ throw CofheError.fromError(error, {
1355
1355
  code: "FETCH_KEYS_FAILED" /* FetchKeysFailed */,
1356
1356
  message: `Failed to fetch FHE key and CRS`,
1357
1357
  context: {
@@ -1364,7 +1364,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1364
1364
  });
1365
1365
  }
1366
1366
  if (!fheKey) {
1367
- throw new CofhesdkError({
1367
+ throw new CofheError({
1368
1368
  code: "MISSING_FHE_KEY" /* MissingFheKey */,
1369
1369
  message: `FHE key not found`,
1370
1370
  context: {
@@ -1374,7 +1374,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1374
1374
  });
1375
1375
  }
1376
1376
  if (!crs) {
1377
- throw new CofhesdkError({
1377
+ throw new CofheError({
1378
1378
  code: "MISSING_CRS" /* MissingCrs */,
1379
1379
  message: `CRS not found for chainId <${this.chainId}>`,
1380
1380
  context: {
@@ -1384,6 +1384,17 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1384
1384
  }
1385
1385
  return { fheKey, fheKeyFetchedFromCoFHE, crs, crsFetchedFromCoFHE };
1386
1386
  }
1387
+ /**
1388
+ * Resolves the encryptDelay config into an array of 5 per-step delays.
1389
+ * A single number is broadcast to all steps; a tuple is used as-is.
1390
+ */
1391
+ resolveEncryptDelays() {
1392
+ const encryptDelay = this.config?.mocks?.encryptDelay ?? [100, 100, 100, 500, 500];
1393
+ if (typeof encryptDelay === "number") {
1394
+ return [encryptDelay, encryptDelay, encryptDelay, encryptDelay, encryptDelay];
1395
+ }
1396
+ return encryptDelay;
1397
+ }
1387
1398
  /**
1388
1399
  * @dev Encrypt against the cofheMocks instead of CoFHE
1389
1400
  *
@@ -1391,25 +1402,35 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1391
1402
  * cofheMocksInsertPackedHashes - stores the ctHashes and their plaintext values for on-chain mocking of FHE operations.
1392
1403
  * cofheMocksZkCreateProofSignatures - creates signatures to be included in the encrypted inputs. The signers address is known and verified in the mock contracts.
1393
1404
  */
1394
- async mocksEncrypt() {
1405
+ async mocksExecute() {
1395
1406
  this.assertAccount();
1396
1407
  this.assertPublicClient();
1397
1408
  this.assertWalletClient();
1409
+ const [initTfheDelay, fetchKeysDelay, packDelay, proveDelay, verifyDelay] = this.resolveEncryptDelays();
1398
1410
  this.fireStepStart("initTfhe" /* InitTfhe */);
1399
- await sleep(100);
1400
- this.fireStepEnd("initTfhe" /* InitTfhe */, { tfheInitializationExecuted: false });
1411
+ await sleep(initTfheDelay);
1412
+ this.fireStepEnd("initTfhe" /* InitTfhe */, {
1413
+ tfheInitializationExecuted: false,
1414
+ isMocks: true,
1415
+ mockSleep: initTfheDelay
1416
+ });
1401
1417
  this.fireStepStart("fetchKeys" /* FetchKeys */);
1402
- await sleep(100);
1403
- this.fireStepEnd("fetchKeys" /* FetchKeys */, { fheKeyFetchedFromCoFHE: false, crsFetchedFromCoFHE: false });
1418
+ await sleep(fetchKeysDelay);
1419
+ this.fireStepEnd("fetchKeys" /* FetchKeys */, {
1420
+ fheKeyFetchedFromCoFHE: false,
1421
+ crsFetchedFromCoFHE: false,
1422
+ isMocks: true,
1423
+ mockSleep: fetchKeysDelay
1424
+ });
1404
1425
  this.fireStepStart("pack" /* Pack */);
1405
1426
  await cofheMocksCheckEncryptableBits(this.inputItems);
1406
- await sleep(100);
1407
- this.fireStepEnd("pack" /* Pack */);
1427
+ await sleep(packDelay);
1428
+ this.fireStepEnd("pack" /* Pack */, { isMocks: true, mockSleep: packDelay });
1408
1429
  this.fireStepStart("prove" /* Prove */);
1409
- await sleep(500);
1410
- this.fireStepEnd("prove" /* Prove */);
1430
+ await sleep(proveDelay);
1431
+ this.fireStepEnd("prove" /* Prove */, { isMocks: true, mockSleep: proveDelay });
1411
1432
  this.fireStepStart("verify" /* Verify */);
1412
- await sleep(500);
1433
+ await sleep(verifyDelay);
1413
1434
  const signedResults = await cofheMocksZkVerifySign(
1414
1435
  this.inputItems,
1415
1436
  this.account,
@@ -1424,13 +1445,13 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1424
1445
  utype: this.inputItems[index].utype,
1425
1446
  signature
1426
1447
  }));
1427
- this.fireStepEnd("verify" /* Verify */);
1448
+ this.fireStepEnd("verify" /* Verify */, { isMocks: true, mockSleep: verifyDelay });
1428
1449
  return encryptedInputs;
1429
1450
  }
1430
1451
  /**
1431
1452
  * In the production context, perform a true encryption with the CoFHE coprocessor.
1432
1453
  */
1433
- async productionEncrypt() {
1454
+ async productionExecute() {
1434
1455
  this.assertAccount();
1435
1456
  this.assertChainId();
1436
1457
  this.fireStepStart("initTfhe" /* InitTfhe */);
@@ -1493,15 +1514,15 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1493
1514
  * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1494
1515
  * .setAccount('0x123...890') // optional
1495
1516
  * .setChainId(11155111) // optional
1496
- * .encrypt(); // execute
1517
+ * .execute(); // execute
1497
1518
  * ```
1498
1519
  *
1499
1520
  * @returns The encrypted inputs.
1500
1521
  */
1501
- async encrypt() {
1522
+ async execute() {
1502
1523
  if (this.chainId === chains.hardhat.id)
1503
- return this.mocksEncrypt();
1504
- return this.productionEncrypt();
1524
+ return this.mocksExecute();
1525
+ return this.productionExecute();
1505
1526
  }
1506
1527
  };
1507
1528
 
@@ -2523,8 +2544,8 @@ var convertViaUtype = (utype, value) => {
2523
2544
  }
2524
2545
  };
2525
2546
 
2526
- // core/decrypt/MockQueryDecrypterAbi.ts
2527
- var MockQueryDecrypterAbi = [
2547
+ // core/decrypt/MockThresholdNetworkAbi.ts
2548
+ var MockThresholdNetworkAbi = [
2528
2549
  {
2529
2550
  type: "function",
2530
2551
  name: "acl",
@@ -2571,11 +2592,7 @@ var MockQueryDecrypterAbi = [
2571
2592
  { name: "expiration", type: "uint64", internalType: "uint64" },
2572
2593
  { name: "recipient", type: "address", internalType: "address" },
2573
2594
  { name: "validatorId", type: "uint256", internalType: "uint256" },
2574
- {
2575
- name: "validatorContract",
2576
- type: "address",
2577
- internalType: "address"
2578
- },
2595
+ { name: "validatorContract", type: "address", internalType: "address" },
2579
2596
  { name: "sealingKey", type: "bytes32", internalType: "bytes32" },
2580
2597
  { name: "issuerSignature", type: "bytes", internalType: "bytes" },
2581
2598
  { name: "recipientSignature", type: "bytes", internalType: "bytes" }
@@ -2604,11 +2621,7 @@ var MockQueryDecrypterAbi = [
2604
2621
  { name: "expiration", type: "uint64", internalType: "uint64" },
2605
2622
  { name: "recipient", type: "address", internalType: "address" },
2606
2623
  { name: "validatorId", type: "uint256", internalType: "uint256" },
2607
- {
2608
- name: "validatorContract",
2609
- type: "address",
2610
- internalType: "address"
2611
- },
2624
+ { name: "validatorContract", type: "address", internalType: "address" },
2612
2625
  { name: "sealingKey", type: "bytes32", internalType: "bytes32" },
2613
2626
  { name: "issuerSignature", type: "bytes", internalType: "bytes" },
2614
2627
  { name: "recipientSignature", type: "bytes", internalType: "bytes" }
@@ -2632,13 +2645,6 @@ var MockQueryDecrypterAbi = [
2632
2645
  outputs: [{ name: "", type: "bytes32", internalType: "bytes32" }],
2633
2646
  stateMutability: "pure"
2634
2647
  },
2635
- {
2636
- type: "function",
2637
- name: "taskManager",
2638
- inputs: [],
2639
- outputs: [{ name: "", type: "address", internalType: "contract TaskManager" }],
2640
- stateMutability: "view"
2641
- },
2642
2648
  {
2643
2649
  type: "function",
2644
2650
  name: "unseal",
@@ -2649,15 +2655,80 @@ var MockQueryDecrypterAbi = [
2649
2655
  outputs: [{ name: "", type: "uint256", internalType: "uint256" }],
2650
2656
  stateMutability: "pure"
2651
2657
  },
2652
- { type: "error", name: "NotAllowed", inputs: [] },
2653
- { type: "error", name: "SealingKeyInvalid", inputs: [] },
2654
- { type: "error", name: "SealingKeyMissing", inputs: [] }
2658
+ {
2659
+ type: "function",
2660
+ name: "mockAcl",
2661
+ inputs: [],
2662
+ outputs: [{ name: "", type: "address", internalType: "contract MockACL" }],
2663
+ stateMutability: "view"
2664
+ },
2665
+ {
2666
+ type: "function",
2667
+ name: "mockTaskManager",
2668
+ inputs: [],
2669
+ outputs: [{ name: "", type: "address", internalType: "contract MockTaskManager" }],
2670
+ stateMutability: "view"
2671
+ },
2672
+ {
2673
+ type: "function",
2674
+ name: "mockQueryDecrypt",
2675
+ inputs: [
2676
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
2677
+ { name: "", type: "uint256", internalType: "uint256" },
2678
+ { name: "issuer", type: "address", internalType: "address" }
2679
+ ],
2680
+ outputs: [
2681
+ { name: "allowed", type: "bool", internalType: "bool" },
2682
+ { name: "error", type: "string", internalType: "string" },
2683
+ { name: "", type: "uint256", internalType: "uint256" }
2684
+ ],
2685
+ stateMutability: "view"
2686
+ },
2687
+ {
2688
+ type: "function",
2689
+ name: "decryptForTxWithPermit",
2690
+ inputs: [
2691
+ { name: "ctHash", type: "uint256", internalType: "uint256" },
2692
+ {
2693
+ name: "permission",
2694
+ type: "tuple",
2695
+ internalType: "struct Permission",
2696
+ components: [
2697
+ { name: "issuer", type: "address", internalType: "address" },
2698
+ { name: "expiration", type: "uint64", internalType: "uint64" },
2699
+ { name: "recipient", type: "address", internalType: "address" },
2700
+ { name: "validatorId", type: "uint256", internalType: "uint256" },
2701
+ { name: "validatorContract", type: "address", internalType: "address" },
2702
+ { name: "sealingKey", type: "bytes32", internalType: "bytes32" },
2703
+ { name: "issuerSignature", type: "bytes", internalType: "bytes" },
2704
+ { name: "recipientSignature", type: "bytes", internalType: "bytes" }
2705
+ ]
2706
+ }
2707
+ ],
2708
+ outputs: [
2709
+ { name: "allowed", type: "bool", internalType: "bool" },
2710
+ { name: "error", type: "string", internalType: "string" },
2711
+ { name: "decryptedValue", type: "uint256", internalType: "uint256" }
2712
+ ],
2713
+ stateMutability: "view"
2714
+ },
2715
+ {
2716
+ type: "function",
2717
+ name: "decryptForTxWithoutPermit",
2718
+ inputs: [{ name: "ctHash", type: "uint256", internalType: "uint256" }],
2719
+ outputs: [
2720
+ { name: "allowed", type: "bool", internalType: "bool" },
2721
+ { name: "error", type: "string", internalType: "string" },
2722
+ { name: "decryptedValue", type: "uint256", internalType: "uint256" }
2723
+ ],
2724
+ stateMutability: "view"
2725
+ }
2655
2726
  ];
2656
2727
 
2657
- // core/decrypt/cofheMocksSealOutput.ts
2658
- async function cofheMocksSealOutput(ctHash, utype, permit, publicClient, mocksSealOutputDelay) {
2659
- if (mocksSealOutputDelay > 0)
2660
- await sleep(mocksSealOutputDelay);
2728
+ // core/decrypt/cofheMocksDecryptForView.ts
2729
+ async function cofheMocksDecryptForView(ctHash, utype, permit, publicClient, mocksDecryptDelay) {
2730
+ if (mocksDecryptDelay > 0)
2731
+ await sleep(mocksDecryptDelay);
2661
2732
  const permission = PermitUtils.getPermission(permit, true);
2662
2733
  const permissionWithBigInts = {
2663
2734
  ...permission,
@@ -2665,19 +2736,19 @@ async function cofheMocksSealOutput(ctHash, utype, permit, publicClient, mocksSe
2665
2736
  validatorId: BigInt(permission.validatorId)
2666
2737
  };
2667
2738
  const [allowed, error, result] = await publicClient.readContract({
2668
- address: MOCKS_QUERY_DECRYPTER_ADDRESS,
2669
- abi: MockQueryDecrypterAbi,
2739
+ address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
2740
+ abi: MockThresholdNetworkAbi,
2670
2741
  functionName: "querySealOutput",
2671
2742
  args: [ctHash, BigInt(utype), permissionWithBigInts]
2672
2743
  });
2673
2744
  if (error != "") {
2674
- throw new CofhesdkError({
2745
+ throw new CofheError({
2675
2746
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2676
2747
  message: `mocks querySealOutput call failed: ${error}`
2677
2748
  });
2678
2749
  }
2679
2750
  if (allowed == false) {
2680
- throw new CofhesdkError({
2751
+ throw new CofheError({
2681
2752
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2682
2753
  message: `mocks querySealOutput call failed: ACL Access Denied (NotAllowed)`
2683
2754
  });
@@ -2696,7 +2767,7 @@ function numberArrayToUint8Array(arr) {
2696
2767
  }
2697
2768
  function convertSealedData(sealed) {
2698
2769
  if (!sealed) {
2699
- throw new CofhesdkError({
2770
+ throw new CofheError({
2700
2771
  code: "SEAL_OUTPUT_RETURNED_NULL" /* SealOutputReturnedNull */,
2701
2772
  message: "Sealed data is missing from completed response"
2702
2773
  });
@@ -2723,7 +2794,7 @@ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, per
2723
2794
  body: JSON.stringify(body)
2724
2795
  });
2725
2796
  } catch (e) {
2726
- throw new CofhesdkError({
2797
+ throw new CofheError({
2727
2798
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2728
2799
  message: `sealOutput request failed`,
2729
2800
  hint: "Ensure the threshold network URL is valid and reachable.",
@@ -2742,7 +2813,7 @@ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, per
2742
2813
  } catch {
2743
2814
  errorMessage = response.statusText || errorMessage;
2744
2815
  }
2745
- throw new CofhesdkError({
2816
+ throw new CofheError({
2746
2817
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2747
2818
  message: `sealOutput request failed: ${errorMessage}`,
2748
2819
  hint: "Check the threshold network URL and request parameters.",
@@ -2758,7 +2829,7 @@ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, per
2758
2829
  try {
2759
2830
  submitResponse = await response.json();
2760
2831
  } catch (e) {
2761
- throw new CofhesdkError({
2832
+ throw new CofheError({
2762
2833
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2763
2834
  message: `Failed to parse sealOutput submit response`,
2764
2835
  cause: e instanceof Error ? e : void 0,
@@ -2769,7 +2840,7 @@ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, per
2769
2840
  });
2770
2841
  }
2771
2842
  if (!submitResponse.request_id) {
2772
- throw new CofhesdkError({
2843
+ throw new CofheError({
2773
2844
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2774
2845
  message: `sealOutput submit response missing request_id`,
2775
2846
  context: {
@@ -2786,7 +2857,7 @@ async function pollSealOutputStatus(thresholdNetworkUrl, requestId) {
2786
2857
  let completed = false;
2787
2858
  while (!completed) {
2788
2859
  if (Date.now() - startTime > POLL_TIMEOUT_MS) {
2789
- throw new CofhesdkError({
2860
+ throw new CofheError({
2790
2861
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2791
2862
  message: `sealOutput polling timed out after ${POLL_TIMEOUT_MS}ms`,
2792
2863
  hint: "The request may still be processing. Try again later.",
@@ -2806,7 +2877,7 @@ async function pollSealOutputStatus(thresholdNetworkUrl, requestId) {
2806
2877
  }
2807
2878
  });
2808
2879
  } catch (e) {
2809
- throw new CofhesdkError({
2880
+ throw new CofheError({
2810
2881
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2811
2882
  message: `sealOutput status poll failed`,
2812
2883
  hint: "Ensure the threshold network URL is valid and reachable.",
@@ -2818,7 +2889,7 @@ async function pollSealOutputStatus(thresholdNetworkUrl, requestId) {
2818
2889
  });
2819
2890
  }
2820
2891
  if (response.status === 404) {
2821
- throw new CofhesdkError({
2892
+ throw new CofheError({
2822
2893
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2823
2894
  message: `sealOutput request not found: ${requestId}`,
2824
2895
  hint: "The request may have expired or been invalid.",
@@ -2836,7 +2907,7 @@ async function pollSealOutputStatus(thresholdNetworkUrl, requestId) {
2836
2907
  } catch {
2837
2908
  errorMessage = response.statusText || errorMessage;
2838
2909
  }
2839
- throw new CofhesdkError({
2910
+ throw new CofheError({
2840
2911
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2841
2912
  message: `sealOutput status poll failed: ${errorMessage}`,
2842
2913
  context: {
@@ -2851,7 +2922,7 @@ async function pollSealOutputStatus(thresholdNetworkUrl, requestId) {
2851
2922
  try {
2852
2923
  statusResponse = await response.json();
2853
2924
  } catch (e) {
2854
- throw new CofhesdkError({
2925
+ throw new CofheError({
2855
2926
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2856
2927
  message: `Failed to parse sealOutput status response`,
2857
2928
  cause: e instanceof Error ? e : void 0,
@@ -2864,7 +2935,7 @@ async function pollSealOutputStatus(thresholdNetworkUrl, requestId) {
2864
2935
  if (statusResponse.status === "COMPLETED") {
2865
2936
  if (statusResponse.is_succeed === false) {
2866
2937
  const errorMessage = statusResponse.error_message || "Unknown error";
2867
- throw new CofhesdkError({
2938
+ throw new CofheError({
2868
2939
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2869
2940
  message: `sealOutput request failed: ${errorMessage}`,
2870
2941
  context: {
@@ -2875,7 +2946,7 @@ async function pollSealOutputStatus(thresholdNetworkUrl, requestId) {
2875
2946
  });
2876
2947
  }
2877
2948
  if (!statusResponse.sealed) {
2878
- throw new CofhesdkError({
2949
+ throw new CofheError({
2879
2950
  code: "SEAL_OUTPUT_RETURNED_NULL" /* SealOutputReturnedNull */,
2880
2951
  message: `sealOutput request completed but returned no sealed data`,
2881
2952
  context: {
@@ -2889,7 +2960,7 @@ async function pollSealOutputStatus(thresholdNetworkUrl, requestId) {
2889
2960
  }
2890
2961
  await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
2891
2962
  }
2892
- throw new CofhesdkError({
2963
+ throw new CofheError({
2893
2964
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2894
2965
  message: "Polling loop exited unexpectedly",
2895
2966
  context: {
@@ -2902,9 +2973,99 @@ async function tnSealOutputV2(ctHash, chainId, permission, thresholdNetworkUrl)
2902
2973
  const requestId = await submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, permission);
2903
2974
  return await pollSealOutputStatus(thresholdNetworkUrl, requestId);
2904
2975
  }
2976
+ async function cofheMocksDecryptForTx(ctHash, utype, permit, publicClient, mocksDecryptForTxDelay) {
2977
+ if (mocksDecryptForTxDelay > 0)
2978
+ await sleep(mocksDecryptForTxDelay);
2979
+ if (permit !== null) {
2980
+ let permission = PermitUtils.getPermission(permit, true);
2981
+ const permissionWithBigInts = {
2982
+ ...permission,
2983
+ expiration: BigInt(permission.expiration),
2984
+ validatorId: BigInt(permission.validatorId)
2985
+ };
2986
+ const [allowed2, error2, result2] = await publicClient.readContract({
2987
+ address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
2988
+ abi: MockThresholdNetworkAbi,
2989
+ functionName: "decryptForTxWithPermit",
2990
+ args: [ctHash, permissionWithBigInts]
2991
+ });
2992
+ if (error2 != "") {
2993
+ throw new CofheError({
2994
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
2995
+ message: `mocks decryptForTx call failed: ${error2}`
2996
+ });
2997
+ }
2998
+ if (allowed2 == false) {
2999
+ throw new CofheError({
3000
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3001
+ message: `mocks decryptForTx call failed: ACL Access Denied (NotAllowed)`
3002
+ });
3003
+ }
3004
+ const chainId2 = await publicClient.getChainId();
3005
+ const ctHashBigInt2 = BigInt(ctHash);
3006
+ const resultBigInt2 = BigInt(result2);
3007
+ const encryptionType2 = Number((ctHashBigInt2 & 0x7fn << 8n) >> 8n);
3008
+ const ctHashBytes322 = viem.pad(viem.toHex(ctHashBigInt2), { size: 32 });
3009
+ const packed2 = viem.encodePacked(
3010
+ ["uint256", "uint32", "uint64", "bytes32"],
3011
+ [resultBigInt2, encryptionType2, BigInt(chainId2), ctHashBytes322]
3012
+ );
3013
+ const messageHash2 = viem.keccak256(packed2);
3014
+ const signatureHex2 = await accounts.sign({
3015
+ hash: messageHash2,
3016
+ privateKey: MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY,
3017
+ to: "hex"
3018
+ });
3019
+ const signature2 = signatureHex2.slice(2);
3020
+ return {
3021
+ ctHash,
3022
+ decryptedValue: BigInt(result2),
3023
+ signature: signature2
3024
+ };
3025
+ }
3026
+ const [allowed, error, result] = await publicClient.readContract({
3027
+ address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
3028
+ abi: MockThresholdNetworkAbi,
3029
+ functionName: "decryptForTxWithoutPermit",
3030
+ args: [ctHash]
3031
+ });
3032
+ if (error != "") {
3033
+ throw new CofheError({
3034
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3035
+ message: `mocks decryptForTx call failed: ${error}`
3036
+ });
3037
+ }
3038
+ if (allowed == false) {
3039
+ throw new CofheError({
3040
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3041
+ message: `mocks decryptForTx call failed: ACL Access Denied (NotAllowed)`
3042
+ });
3043
+ }
3044
+ const chainId = await publicClient.getChainId();
3045
+ const ctHashBigInt = BigInt(ctHash);
3046
+ const resultBigInt = BigInt(result);
3047
+ const encryptionType = Number((ctHashBigInt & 0x7fn << 8n) >> 8n);
3048
+ const ctHashBytes32 = viem.pad(viem.toHex(ctHashBigInt), { size: 32 });
3049
+ const packed = viem.encodePacked(
3050
+ ["uint256", "uint32", "uint64", "bytes32"],
3051
+ [resultBigInt, encryptionType, BigInt(chainId), ctHashBytes32]
3052
+ );
3053
+ const messageHash = viem.keccak256(packed);
3054
+ const signatureHex = await accounts.sign({
3055
+ hash: messageHash,
3056
+ privateKey: MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY,
3057
+ to: "hex"
3058
+ });
3059
+ const signature = signatureHex.slice(2);
3060
+ return {
3061
+ ctHash,
3062
+ decryptedValue: BigInt(result),
3063
+ signature
3064
+ };
3065
+ }
2905
3066
 
2906
- // core/decrypt/decryptHandleBuilder.ts
2907
- var DecryptHandlesBuilder = class extends BaseBuilder {
3067
+ // core/decrypt/decryptForViewBuilder.ts
3068
+ var DecryptForViewBuilder = class extends BaseBuilder {
2908
3069
  ctHash;
2909
3070
  utype;
2910
3071
  permitHash;
@@ -2930,12 +3091,12 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
2930
3091
  *
2931
3092
  * Example:
2932
3093
  * ```typescript
2933
- * const unsealed = await decryptHandle(ctHash, utype)
3094
+ * const unsealed = await client.decryptForView(ctHash, utype)
2934
3095
  * .setChainId(11155111)
2935
- * .decrypt();
3096
+ * .execute();
2936
3097
  * ```
2937
3098
  *
2938
- * @returns The chainable DecryptHandlesBuilder instance.
3099
+ * @returns The chainable DecryptForViewBuilder instance.
2939
3100
  */
2940
3101
  setChainId(chainId) {
2941
3102
  this.chainId = chainId;
@@ -2951,12 +3112,12 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
2951
3112
  *
2952
3113
  * Example:
2953
3114
  * ```typescript
2954
- * const unsealed = await decryptHandle(ctHash, utype)
3115
+ * const unsealed = await client.decryptForView(ctHash, utype)
2955
3116
  * .setAccount('0x1234567890123456789012345678901234567890')
2956
- * .decrypt();
3117
+ * .execute();
2957
3118
  * ```
2958
3119
  *
2959
- * @returns The chainable DecryptHandlesBuilder instance.
3120
+ * @returns The chainable DecryptForViewBuilder instance.
2960
3121
  */
2961
3122
  setAccount(account) {
2962
3123
  this.account = account;
@@ -2965,6 +3126,19 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
2965
3126
  getAccount() {
2966
3127
  return this.account;
2967
3128
  }
3129
+ withPermit(permitOrPermitHash) {
3130
+ if (typeof permitOrPermitHash === "string") {
3131
+ this.permitHash = permitOrPermitHash;
3132
+ this.permit = void 0;
3133
+ } else if (permitOrPermitHash === void 0) {
3134
+ this.permitHash = void 0;
3135
+ this.permit = void 0;
3136
+ } else {
3137
+ this.permit = permitOrPermitHash;
3138
+ this.permitHash = void 0;
3139
+ }
3140
+ return this;
3141
+ }
2968
3142
  /**
2969
3143
  * @param permitHash - Permit hash to decrypt values from. Used to fetch the correct permit.
2970
3144
  *
@@ -2973,16 +3147,16 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
2973
3147
  *
2974
3148
  * Example:
2975
3149
  * ```typescript
2976
- * const unsealed = await decryptHandle(ctHash, utype)
3150
+ * const unsealed = await client.decryptForView(ctHash, utype)
2977
3151
  * .setPermitHash('0x1234567890123456789012345678901234567890')
2978
- * .decrypt();
3152
+ * .execute();
2979
3153
  * ```
2980
3154
  *
2981
- * @returns The chainable DecryptHandlesBuilder instance.
3155
+ * @returns The chainable DecryptForViewBuilder instance.
2982
3156
  */
3157
+ /** @deprecated Use `withPermit(permitHash)` instead. */
2983
3158
  setPermitHash(permitHash) {
2984
- this.permitHash = permitHash;
2985
- return this;
3159
+ return this.withPermit(permitHash);
2986
3160
  }
2987
3161
  getPermitHash() {
2988
3162
  return this.permitHash;
@@ -2994,16 +3168,16 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
2994
3168
  *
2995
3169
  * Example:
2996
3170
  * ```typescript
2997
- * const unsealed = await decryptHandle(ctHash, utype)
3171
+ * const unsealed = await client.decryptForView(ctHash, utype)
2998
3172
  * .setPermit(permit)
2999
- * .decrypt();
3173
+ * .execute();
3000
3174
  * ```
3001
3175
  *
3002
- * @returns The chainable DecryptHandlesBuilder instance.
3176
+ * @returns The chainable DecryptForViewBuilder instance.
3003
3177
  */
3178
+ /** @deprecated Use `withPermit(permit)` instead. */
3004
3179
  setPermit(permit) {
3005
- this.permit = permit;
3006
- return this;
3180
+ return this.withPermit(permit);
3007
3181
  }
3008
3182
  getPermit() {
3009
3183
  return this.permit;
@@ -3014,7 +3188,7 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
3014
3188
  }
3015
3189
  validateUtypeOrThrow() {
3016
3190
  if (!isValidUtype(this.utype))
3017
- throw new CofhesdkError({
3191
+ throw new CofheError({
3018
3192
  code: "INVALID_UTYPE" /* InvalidUtype */,
3019
3193
  message: `Invalid utype to decrypt to`,
3020
3194
  context: {
@@ -3030,7 +3204,7 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
3030
3204
  if (this.permitHash) {
3031
3205
  const permit2 = await permits.getPermit(this.chainId, this.account, this.permitHash);
3032
3206
  if (!permit2) {
3033
- throw new CofhesdkError({
3207
+ throw new CofheError({
3034
3208
  code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
3035
3209
  message: `Permit with hash <${this.permitHash}> not found for account <${this.account}> and chainId <${this.chainId}>`,
3036
3210
  hint: "Ensure the permit exists and is valid.",
@@ -3045,7 +3219,7 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
3045
3219
  }
3046
3220
  const permit = await permits.getActivePermit(this.chainId, this.account);
3047
3221
  if (!permit) {
3048
- throw new CofhesdkError({
3222
+ throw new CofheError({
3049
3223
  code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
3050
3224
  message: `Active permit not found for chainId <${this.chainId}> and account <${this.account}>`,
3051
3225
  hint: "Ensure a permit exists for this account on this chain.",
@@ -3062,8 +3236,8 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
3062
3236
  */
3063
3237
  async mocksSealOutput(permit) {
3064
3238
  this.assertPublicClient();
3065
- const mocksSealOutputDelay = this.config.mocks.sealOutputDelay;
3066
- return cofheMocksSealOutput(this.ctHash, this.utype, permit, this.publicClient, mocksSealOutputDelay);
3239
+ const mocksDecryptDelay = this.config.mocks.decryptDelay;
3240
+ return cofheMocksDecryptForView(this.ctHash, this.utype, permit, this.publicClient, mocksDecryptDelay);
3067
3241
  }
3068
3242
  /**
3069
3243
  * In the production context, perform a true decryption with the CoFHE coprocessor.
@@ -3088,15 +3262,16 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
3088
3262
  *
3089
3263
  * Example:
3090
3264
  * ```typescript
3091
- * const unsealed = await decryptHandle(ctHash, utype)
3265
+ * const unsealed = await client.decryptForView(ctHash, utype)
3092
3266
  * .setChainId(11155111) // optional
3093
3267
  * .setAccount('0x123...890') // optional
3094
- * .decrypt(); // execute
3268
+ * .withPermit() // optional
3269
+ * .execute(); // execute
3095
3270
  * ```
3096
3271
  *
3097
3272
  * @returns The unsealed item.
3098
3273
  */
3099
- async decrypt() {
3274
+ async execute() {
3100
3275
  this.validateUtypeOrThrow();
3101
3276
  const permit = await this.getResolvedPermit();
3102
3277
  PermitUtils.validate(permit);
@@ -3112,6 +3287,394 @@ var DecryptHandlesBuilder = class extends BaseBuilder {
3112
3287
  }
3113
3288
  };
3114
3289
 
3290
+ // core/decrypt/tnDecrypt.ts
3291
+ function normalizeSignature(signature) {
3292
+ if (typeof signature !== "string") {
3293
+ throw new CofheError({
3294
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3295
+ message: "decrypt response missing signature",
3296
+ context: {
3297
+ signature
3298
+ }
3299
+ });
3300
+ }
3301
+ const trimmed = signature.trim();
3302
+ if (trimmed.length === 0) {
3303
+ throw new CofheError({
3304
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3305
+ message: "decrypt response returned empty signature"
3306
+ });
3307
+ }
3308
+ return trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
3309
+ }
3310
+ function parseDecryptedBytesToBigInt(decrypted) {
3311
+ if (!Array.isArray(decrypted)) {
3312
+ throw new CofheError({
3313
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3314
+ message: "decrypt response field <decrypted> must be a byte array",
3315
+ context: {
3316
+ decrypted
3317
+ }
3318
+ });
3319
+ }
3320
+ if (decrypted.length === 0) {
3321
+ throw new CofheError({
3322
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3323
+ message: "decrypt response field <decrypted> was an empty byte array",
3324
+ context: {
3325
+ decrypted
3326
+ }
3327
+ });
3328
+ }
3329
+ let hex = "";
3330
+ for (const b of decrypted) {
3331
+ if (typeof b !== "number" || !Number.isInteger(b) || b < 0 || b > 255) {
3332
+ throw new CofheError({
3333
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3334
+ message: "decrypt response field <decrypted> contained a non-byte value",
3335
+ context: {
3336
+ badElement: b,
3337
+ decrypted
3338
+ }
3339
+ });
3340
+ }
3341
+ hex += b.toString(16).padStart(2, "0");
3342
+ }
3343
+ return BigInt(`0x${hex}`);
3344
+ }
3345
+ function assertTnDecryptResponse(value) {
3346
+ if (value == null || typeof value !== "object") {
3347
+ throw new CofheError({
3348
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3349
+ message: "decrypt response must be a JSON object",
3350
+ context: {
3351
+ value
3352
+ }
3353
+ });
3354
+ }
3355
+ const v = value;
3356
+ const decrypted = v.decrypted;
3357
+ const signature = v.signature;
3358
+ const encryptionType = v.encryption_type;
3359
+ const errorMessage = v.error_message;
3360
+ if (!Array.isArray(decrypted)) {
3361
+ throw new CofheError({
3362
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3363
+ message: "decrypt response missing <decrypted> byte array",
3364
+ context: { decryptResponse: value }
3365
+ });
3366
+ }
3367
+ if (typeof signature !== "string") {
3368
+ throw new CofheError({
3369
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3370
+ message: "decrypt response missing <signature> string",
3371
+ context: { decryptResponse: value }
3372
+ });
3373
+ }
3374
+ if (typeof encryptionType !== "number") {
3375
+ throw new CofheError({
3376
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3377
+ message: "decrypt response missing <encryption_type> number",
3378
+ context: { decryptResponse: value }
3379
+ });
3380
+ }
3381
+ if (!(typeof errorMessage === "string" || errorMessage === null)) {
3382
+ throw new CofheError({
3383
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3384
+ message: "decrypt response field <error_message> must be string or null",
3385
+ context: { decryptResponse: value }
3386
+ });
3387
+ }
3388
+ return {
3389
+ decrypted,
3390
+ signature,
3391
+ encryption_type: encryptionType,
3392
+ error_message: errorMessage
3393
+ };
3394
+ }
3395
+ async function tnDecrypt(ctHash, chainId, permission, thresholdNetworkUrl) {
3396
+ const body = {
3397
+ ct_tempkey: ctHash.toString(16).padStart(64, "0"),
3398
+ host_chain_id: chainId
3399
+ };
3400
+ if (permission) {
3401
+ body.permit = permission;
3402
+ }
3403
+ let response;
3404
+ try {
3405
+ response = await fetch(`${thresholdNetworkUrl}/decrypt`, {
3406
+ method: "POST",
3407
+ headers: {
3408
+ "Content-Type": "application/json"
3409
+ },
3410
+ body: JSON.stringify(body)
3411
+ });
3412
+ } catch (e) {
3413
+ throw new CofheError({
3414
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3415
+ message: `decrypt request failed`,
3416
+ hint: "Ensure the threshold network URL is valid and reachable.",
3417
+ cause: e instanceof Error ? e : void 0,
3418
+ context: {
3419
+ thresholdNetworkUrl,
3420
+ body
3421
+ }
3422
+ });
3423
+ }
3424
+ const responseText = await response.text();
3425
+ if (!response.ok) {
3426
+ let errorMessage = response.statusText || `HTTP ${response.status}`;
3427
+ try {
3428
+ const errorBody = JSON.parse(responseText);
3429
+ const maybeMessage = errorBody.error_message || errorBody.message;
3430
+ if (typeof maybeMessage === "string" && maybeMessage.length > 0)
3431
+ errorMessage = maybeMessage;
3432
+ } catch {
3433
+ const trimmed = responseText.trim();
3434
+ if (trimmed.length > 0)
3435
+ errorMessage = trimmed;
3436
+ }
3437
+ throw new CofheError({
3438
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3439
+ message: `decrypt request failed: ${errorMessage}`,
3440
+ hint: "Check the threshold network URL and request parameters.",
3441
+ context: {
3442
+ thresholdNetworkUrl,
3443
+ status: response.status,
3444
+ statusText: response.statusText,
3445
+ body,
3446
+ responseText
3447
+ }
3448
+ });
3449
+ }
3450
+ let rawJson;
3451
+ try {
3452
+ rawJson = JSON.parse(responseText);
3453
+ } catch (e) {
3454
+ throw new CofheError({
3455
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3456
+ message: `Failed to parse decrypt response`,
3457
+ cause: e instanceof Error ? e : void 0,
3458
+ context: {
3459
+ thresholdNetworkUrl,
3460
+ body,
3461
+ responseText
3462
+ }
3463
+ });
3464
+ }
3465
+ const decryptResponse = assertTnDecryptResponse(rawJson);
3466
+ if (decryptResponse.error_message) {
3467
+ throw new CofheError({
3468
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3469
+ message: `decrypt request failed: ${decryptResponse.error_message}`,
3470
+ context: {
3471
+ thresholdNetworkUrl,
3472
+ body,
3473
+ decryptResponse
3474
+ }
3475
+ });
3476
+ }
3477
+ const decryptedValue = parseDecryptedBytesToBigInt(decryptResponse.decrypted);
3478
+ const signature = normalizeSignature(decryptResponse.signature);
3479
+ return { decryptedValue, signature };
3480
+ }
3481
+
3482
+ // core/decrypt/decryptForTxBuilder.ts
3483
+ var DecryptForTxBuilder = class extends BaseBuilder {
3484
+ ctHash;
3485
+ permitHash;
3486
+ permit;
3487
+ permitSelection = "unset";
3488
+ constructor(params) {
3489
+ super({
3490
+ config: params.config,
3491
+ publicClient: params.publicClient,
3492
+ walletClient: params.walletClient,
3493
+ chainId: params.chainId,
3494
+ account: params.account,
3495
+ requireConnected: params.requireConnected
3496
+ });
3497
+ this.ctHash = params.ctHash;
3498
+ }
3499
+ setChainId(chainId) {
3500
+ this.chainId = chainId;
3501
+ return this;
3502
+ }
3503
+ getChainId() {
3504
+ return this.chainId;
3505
+ }
3506
+ setAccount(account) {
3507
+ this.account = account;
3508
+ return this;
3509
+ }
3510
+ getAccount() {
3511
+ return this.account;
3512
+ }
3513
+ withPermit(permitOrPermitHash) {
3514
+ if (this.permitSelection === "with-permit") {
3515
+ throw new CofheError({
3516
+ code: "INTERNAL_ERROR" /* InternalError */,
3517
+ message: "decryptForTx: withPermit() can only be selected once.",
3518
+ hint: "Choose the permit mode once. If you need a different permit, start a new decryptForTx() builder chain."
3519
+ });
3520
+ }
3521
+ if (this.permitSelection === "without-permit") {
3522
+ throw new CofheError({
3523
+ code: "INTERNAL_ERROR" /* InternalError */,
3524
+ message: "decryptForTx: cannot call withPermit() after withoutPermit() has been selected.",
3525
+ hint: "Choose exactly one permit mode: either call .withPermit(...) or .withoutPermit(), but not both."
3526
+ });
3527
+ }
3528
+ this.permitSelection = "with-permit";
3529
+ if (typeof permitOrPermitHash === "string") {
3530
+ this.permitHash = permitOrPermitHash;
3531
+ this.permit = void 0;
3532
+ } else if (permitOrPermitHash === void 0) {
3533
+ this.permitHash = void 0;
3534
+ this.permit = void 0;
3535
+ } else {
3536
+ this.permit = permitOrPermitHash;
3537
+ this.permitHash = void 0;
3538
+ }
3539
+ return this;
3540
+ }
3541
+ /**
3542
+ * Select "no permit" mode.
3543
+ *
3544
+ * This uses global allowance (no permit required) and sends an empty permission payload to `/decrypt`.
3545
+ */
3546
+ withoutPermit() {
3547
+ if (this.permitSelection === "without-permit") {
3548
+ throw new CofheError({
3549
+ code: "INTERNAL_ERROR" /* InternalError */,
3550
+ message: "decryptForTx: withoutPermit() can only be selected once.",
3551
+ hint: "Choose the permit mode once. If you need a different mode, start a new decryptForTx() builder chain."
3552
+ });
3553
+ }
3554
+ if (this.permitSelection === "with-permit") {
3555
+ throw new CofheError({
3556
+ code: "INTERNAL_ERROR" /* InternalError */,
3557
+ message: "decryptForTx: cannot call withoutPermit() after withPermit() has been selected.",
3558
+ hint: "Choose exactly one permit mode: either call .withPermit(...) or .withoutPermit(), but not both."
3559
+ });
3560
+ }
3561
+ this.permitSelection = "without-permit";
3562
+ this.permitHash = void 0;
3563
+ this.permit = void 0;
3564
+ return this;
3565
+ }
3566
+ getPermit() {
3567
+ return this.permit;
3568
+ }
3569
+ getPermitHash() {
3570
+ return this.permitHash;
3571
+ }
3572
+ async getThresholdNetworkUrl() {
3573
+ this.assertChainId();
3574
+ return getThresholdNetworkUrlOrThrow(this.config, this.chainId);
3575
+ }
3576
+ async getResolvedPermit() {
3577
+ if (this.permitSelection === "unset") {
3578
+ throw new CofheError({
3579
+ code: "INTERNAL_ERROR" /* InternalError */,
3580
+ message: "decryptForTx: missing permit selection; call withPermit(...) or withoutPermit() before execute().",
3581
+ hint: "Call .withPermit() to use the active permit, or .withoutPermit() for global allowance."
3582
+ });
3583
+ }
3584
+ if (this.permitSelection === "without-permit") {
3585
+ return null;
3586
+ }
3587
+ if (this.permit)
3588
+ return this.permit;
3589
+ this.assertChainId();
3590
+ this.assertAccount();
3591
+ if (this.permitHash) {
3592
+ const permit2 = await permits.getPermit(this.chainId, this.account, this.permitHash);
3593
+ if (!permit2) {
3594
+ throw new CofheError({
3595
+ code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
3596
+ message: `Permit with hash <${this.permitHash}> not found for account <${this.account}> and chainId <${this.chainId}>`,
3597
+ hint: "Ensure the permit exists and is valid.",
3598
+ context: {
3599
+ chainId: this.chainId,
3600
+ account: this.account,
3601
+ permitHash: this.permitHash
3602
+ }
3603
+ });
3604
+ }
3605
+ return permit2;
3606
+ }
3607
+ const permit = await permits.getActivePermit(this.chainId, this.account);
3608
+ if (!permit) {
3609
+ throw new CofheError({
3610
+ code: "PERMIT_NOT_FOUND" /* PermitNotFound */,
3611
+ message: `Active permit not found for chainId <${this.chainId}> and account <${this.account}>`,
3612
+ hint: "Create a permit (e.g. client.permits.createSelf(...)) and/or set it active (client.permits.selectActivePermit(hash)).",
3613
+ context: {
3614
+ chainId: this.chainId,
3615
+ account: this.account
3616
+ }
3617
+ });
3618
+ }
3619
+ return permit;
3620
+ }
3621
+ /**
3622
+ * On hardhat, interact with MockThresholdNetwork contract
3623
+ */
3624
+ async mocksDecryptForTx(permit) {
3625
+ this.assertPublicClient();
3626
+ const delay = this.config.mocks.decryptDelay;
3627
+ const result = await cofheMocksDecryptForTx(this.ctHash, 0, permit, this.publicClient, delay);
3628
+ return result;
3629
+ }
3630
+ /**
3631
+ * In the production context, perform a true decryption with the CoFHE coprocessor.
3632
+ */
3633
+ async productionDecryptForTx(permit) {
3634
+ this.assertChainId();
3635
+ this.assertPublicClient();
3636
+ const thresholdNetworkUrl = await this.getThresholdNetworkUrl();
3637
+ const permission = permit ? PermitUtils.getPermission(permit, true) : null;
3638
+ const { decryptedValue, signature } = await tnDecrypt(this.ctHash, this.chainId, permission, thresholdNetworkUrl);
3639
+ return {
3640
+ ctHash: this.ctHash,
3641
+ decryptedValue,
3642
+ signature
3643
+ };
3644
+ }
3645
+ /**
3646
+ * Final step of the decryptForTx process. MUST BE CALLED LAST IN THE CHAIN.
3647
+ *
3648
+ * You must explicitly choose one permit mode before calling `execute()`:
3649
+ * - `withPermit(permit)` / `withPermit(permitHash)` / `withPermit()` (active permit)
3650
+ * - `withoutPermit()` (global allowance)
3651
+ */
3652
+ async execute() {
3653
+ const permit = await this.getResolvedPermit();
3654
+ if (permit !== null) {
3655
+ PermitUtils.validate(permit);
3656
+ PermitUtils.isValid(permit);
3657
+ const chainId = permit._signedDomain.chainId;
3658
+ if (chainId === hardhat2.id) {
3659
+ return await this.mocksDecryptForTx(permit);
3660
+ } else {
3661
+ return await this.productionDecryptForTx(permit);
3662
+ }
3663
+ } else {
3664
+ if (!this.chainId) {
3665
+ this.assertPublicClient();
3666
+ this.chainId = await getPublicClientChainID(this.publicClient);
3667
+ }
3668
+ this.assertChainId();
3669
+ if (this.chainId === hardhat2.id) {
3670
+ return await this.mocksDecryptForTx(null);
3671
+ } else {
3672
+ return await this.productionDecryptForTx(null);
3673
+ }
3674
+ }
3675
+ }
3676
+ };
3677
+
3115
3678
  // core/client.ts
3116
3679
  var InitialConnectStore = {
3117
3680
  connected: false,
@@ -3122,7 +3685,7 @@ var InitialConnectStore = {
3122
3685
  publicClient: void 0,
3123
3686
  walletClient: void 0
3124
3687
  };
3125
- function createCofhesdkClientBase(opts) {
3688
+ function createCofheClientBase(opts) {
3126
3689
  const keysStorage = createKeysStore(opts.config.fheKeyStorage);
3127
3690
  const connectStore = vanilla.createStore(() => InitialConnectStore);
3128
3691
  let connectAttemptId = 0;
@@ -3133,7 +3696,7 @@ function createCofhesdkClientBase(opts) {
3133
3696
  const state = connectStore.getState();
3134
3697
  const notConnected = !state.connected || !state.account || !state.chainId || !state.publicClient || !state.walletClient;
3135
3698
  if (notConnected) {
3136
- throw new CofhesdkError({
3699
+ throw new CofheError({
3137
3700
  code: "NOT_CONNECTED" /* NotConnected */,
3138
3701
  message: "Client must be connected, account and chainId must be initialized",
3139
3702
  hint: "Ensure client.connect() has been called and awaited.",
@@ -3204,16 +3767,28 @@ function createCofhesdkClientBase(opts) {
3204
3767
  requireConnected: _requireConnected
3205
3768
  });
3206
3769
  }
3207
- function decryptHandle(ctHash, utype) {
3770
+ function decryptForView(ctHash, utype) {
3208
3771
  const state = connectStore.getState();
3209
- return new DecryptHandlesBuilder({
3772
+ return new DecryptForViewBuilder({
3210
3773
  ctHash,
3211
3774
  utype,
3212
- chainId: state.chainId ?? void 0,
3213
- account: state.account ?? void 0,
3775
+ chainId: state.chainId,
3776
+ account: state.account,
3214
3777
  config: opts.config,
3215
- publicClient: state.publicClient ?? void 0,
3216
- walletClient: state.walletClient ?? void 0,
3778
+ publicClient: state.publicClient,
3779
+ walletClient: state.walletClient,
3780
+ requireConnected: _requireConnected
3781
+ });
3782
+ }
3783
+ function decryptForTx(ctHash) {
3784
+ const state = connectStore.getState();
3785
+ return new DecryptForTxBuilder({
3786
+ ctHash,
3787
+ chainId: state.chainId,
3788
+ account: state.account,
3789
+ config: opts.config,
3790
+ publicClient: state.publicClient,
3791
+ walletClient: state.walletClient,
3217
3792
  requireConnected: _requireConnected
3218
3793
  });
3219
3794
  }
@@ -3222,7 +3797,7 @@ function createCofhesdkClientBase(opts) {
3222
3797
  const _chainId = chainId ?? state.chainId;
3223
3798
  const _account = account ?? state.account;
3224
3799
  if (_chainId == null || _account == null) {
3225
- throw new CofhesdkError({
3800
+ throw new CofheError({
3226
3801
  code: "NOT_CONNECTED" /* NotConnected */,
3227
3802
  message: "ChainId or account not available.",
3228
3803
  hint: "Ensure client.connect() has been called, or provide chainId and account explicitly.",
@@ -3307,6 +3882,9 @@ function createCofhesdkClientBase(opts) {
3307
3882
  getSnapshot: connectStore.getState,
3308
3883
  subscribe: connectStore.subscribe,
3309
3884
  // flags (read-only: reflect snapshot)
3885
+ get connection() {
3886
+ return connectStore.getState();
3887
+ },
3310
3888
  get connected() {
3311
3889
  return connectStore.getState().connected;
3312
3890
  },
@@ -3318,7 +3896,12 @@ function createCofhesdkClientBase(opts) {
3318
3896
  connect,
3319
3897
  disconnect,
3320
3898
  encryptInputs,
3321
- decryptHandle,
3899
+ decryptForView,
3900
+ /**
3901
+ * @deprecated Use `decryptForView` instead. Kept for backward compatibility.
3902
+ */
3903
+ decryptHandle: decryptForView,
3904
+ decryptForTx,
3322
3905
  permits: clientPermits
3323
3906
  // Add SDK-specific methods below that require connection
3324
3907
  // Example:
@@ -3394,15 +3977,15 @@ var zkBuilderAndCrsGenerator = (fhe, crs) => {
3394
3977
  const zkCrs = nodeTfhe.CompactPkeCrs.deserialize(fromHexString2(crs));
3395
3978
  return { zkBuilder, zkCrs };
3396
3979
  };
3397
- function createCofhesdkConfig(config) {
3398
- return createCofhesdkConfigBase({
3980
+ function createCofheConfig(config) {
3981
+ return createCofheConfigBase({
3399
3982
  environment: "node",
3400
3983
  ...config,
3401
3984
  fheKeyStorage: config.fheKeyStorage === null ? null : config.fheKeyStorage ?? createNodeStorage()
3402
3985
  });
3403
3986
  }
3404
- function createCofhesdkClient(config) {
3405
- return createCofhesdkClientBase({
3987
+ function createCofheClient(config) {
3988
+ return createCofheClientBase({
3406
3989
  config,
3407
3990
  zkBuilderAndCrsGenerator,
3408
3991
  tfhePublicKeyDeserializer,
@@ -3411,5 +3994,5 @@ function createCofhesdkClient(config) {
3411
3994
  });
3412
3995
  }
3413
3996
 
3414
- exports.createCofhesdkClient = createCofhesdkClient;
3415
- exports.createCofhesdkConfig = createCofhesdkConfig;
3997
+ exports.createCofheClient = createCofheClient;
3998
+ exports.createCofheConfig = createCofheConfig;