@cofhe/sdk 0.5.1 → 0.6.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 (47) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/adapters/test/ethers5.test.ts +1 -1
  3. package/adapters/test/ethers6.test.ts +1 -1
  4. package/adapters/test/wagmi.test.ts +1 -1
  5. package/chains/chains/hardhat.ts +3 -3
  6. package/core/consts.ts +0 -3
  7. package/core/decrypt/decryptForTxBuilder.ts +21 -0
  8. package/core/decrypt/decryptForViewBuilder.ts +19 -0
  9. package/core/decrypt/submitRetry.ts +126 -0
  10. package/core/decrypt/tnDecryptV2.ts +48 -53
  11. package/core/decrypt/tnSealOutputV2.ts +48 -54
  12. package/core/encrypt/cofheMocksZkVerifySign.ts +2 -2
  13. package/core/encrypt/encryptInputsBuilder.ts +46 -11
  14. package/core/encrypt/zkPackProveVerify.ts +3 -3
  15. package/core/index.ts +13 -1
  16. package/core/test/decryptBuilders.test.ts +28 -0
  17. package/core/test/encryptInputsBuilder.test.ts +35 -0
  18. package/core/test/pollCallbacks.test.ts +226 -0
  19. package/core/types.ts +65 -5
  20. package/dist/chains.cjs +3 -3
  21. package/dist/chains.js +1 -1
  22. package/dist/{chunk-4FP4V35O.js → chunk-ESMZCFJY.js} +1 -2
  23. package/dist/{chunk-TBLR7NNE.js → chunk-MTRAXQXC.js} +3 -3
  24. package/dist/{chunk-S7OKGLFD.js → chunk-PE5V5CCV.js} +288 -153
  25. package/dist/{chunk-MRCKUMOS.js → chunk-VB62WYPL.js} +1 -1
  26. package/dist/{clientTypes-BSbwairE.d.cts → clientTypes-BDy1qIBu.d.cts} +78 -11
  27. package/dist/{clientTypes-DDmcgZ0a.d.ts → clientTypes-CyUvRRzA.d.ts} +78 -11
  28. package/dist/core.cjs +288 -155
  29. package/dist/core.d.cts +3 -5
  30. package/dist/core.d.ts +3 -5
  31. package/dist/core.js +4 -4
  32. package/dist/node.cjs +243 -108
  33. package/dist/node.d.cts +1 -1
  34. package/dist/node.d.ts +1 -1
  35. package/dist/node.js +4 -4
  36. package/dist/permits.d.cts +10 -6
  37. package/dist/permits.d.ts +10 -6
  38. package/dist/permits.js +2 -2
  39. package/dist/web.cjs +243 -108
  40. package/dist/web.d.cts +1 -1
  41. package/dist/web.d.ts +1 -1
  42. package/dist/web.js +4 -4
  43. package/dist/zkProve.worker.js +1 -1
  44. package/package.json +2 -2
  45. package/permits/store.ts +1 -0
  46. package/web/test/ssr.test.ts +23 -0
  47. package/web/test/tfheinit.web.test.ts +81 -5
package/dist/core.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as CofheConfig, c as CofheClientParams, b as CofheClient, d as CofheClientConnectionState, F as FheTypes } from './clientTypes-BSbwairE.cjs';
2
- export { h as CofheClientPermits, C as CofheInputConfig, f as CofheInternalConfig, G as DecryptEndpoint, $ as DecryptForTxBuilder, a0 as DecryptForTxResult, _ as DecryptForViewBuilder, B as DecryptPollCallbackContext, D as DecryptPollCallbackFunction, Z as EncryptInputsBuilder, H as EncryptSetStateFn, Q as EncryptStep, J as EncryptStepCallbackContext, N as Encryptable, o as EncryptableAddress, i as EncryptableBool, E as EncryptableItem, z as EncryptableToEncryptedItemInputMap, n as EncryptableUint128, k as EncryptableUint16, l as EncryptableUint32, m as EncryptableUint64, j as EncryptableUint8, x as EncryptedAddressInput, r as EncryptedBoolInput, q as EncryptedItemInput, y as EncryptedItemInputs, p as EncryptedNumber, w as EncryptedUint128Input, t as EncryptedUint16Input, u as EncryptedUint32Input, v as EncryptedUint64Input, s as EncryptedUint8Input, M as FheAllUTypes, V as FheKeyDeserializer, A as FheTypeValue, K as FheUintUTypes, I as IStorage, X as KeysStorage, Y as KeysStore, L as LiteralToPrimitive, P as Primitive, U as UnsealedItem, a1 as ZkBuilderAndCrsGenerator, a2 as ZkProveWorkerFunction, a3 as ZkProveWorkerRequest, a4 as ZkProveWorkerResponse, S as assertCorrectEncryptedItemInput, e as createCofheConfigBase, W as createKeysStore, T as fetchKeys, g as getCofheConfigItem, O as isEncryptableItem, R as isLastEncryptionStep, a5 as zkProveWithWorker } from './clientTypes-BSbwairE.cjs';
1
+ import { a as CofheConfig, c as CofheClientParams, b as CofheClient, d as CofheClientConnectionState, F as FheTypes } from './clientTypes-BDy1qIBu.cjs';
2
+ export { O as AnyExternalHash, h as CofheClientPermits, C as CofheInputConfig, f as CofheInternalConfig, W as DecryptEndpoint, ab as DecryptForTxBuilder, ac as DecryptForTxResult, aa as DecryptForViewBuilder, V as DecryptPollCallbackContext, T as DecryptPollCallbackFunction, a9 as EncryptInputsBuilder, X as EncryptSetStateFn, a1 as EncryptStep, Y as EncryptStepCallbackContext, $ as Encryptable, o as EncryptableAddress, i as EncryptableBool, E as EncryptableItem, z as EncryptableToEncryptedItemInputMap, Q as EncryptableToExternalHashMap, n as EncryptableUint128, k as EncryptableUint16, l as EncryptableUint32, m as EncryptableUint64, j as EncryptableUint8, x as EncryptedAddressInput, r as EncryptedBoolInput, q as EncryptedItemInput, y as EncryptedItemInputs, p as EncryptedNumber, w as EncryptedUint128Input, t as EncryptedUint16Input, u as EncryptedUint32Input, v as EncryptedUint64Input, s as EncryptedUint8Input, M as ExternalAddressHash, B as ExternalBoolHash, N as ExternalHashProof, R as ExternalItemHashes, K as ExternalUint128Hash, G as ExternalUint16Hash, H as ExternalUint32Hash, J as ExternalUint64Hash, D as ExternalUint8Hash, _ as FheAllUTypes, a5 as FheKeyDeserializer, A as FheTypeValue, Z as FheUintUTypes, S as HashPlusProofResult, I as IStorage, a7 as KeysStorage, a8 as KeysStore, L as LiteralToPrimitive, P as Primitive, U as UnsealedItem, ad as ZkBuilderAndCrsGenerator, ae as ZkProveWorkerFunction, af as ZkProveWorkerRequest, ag as ZkProveWorkerResponse, a3 as assertCorrectEncryptedItemInput, e as createCofheConfigBase, a6 as createKeysStore, a4 as fetchKeys, g as getCofheConfigItem, a0 as isEncryptableItem, a2 as isLastEncryptionStep, ah as zkProveWithWorker } from './clientTypes-BDy1qIBu.cjs';
3
3
  import { Hex, PublicClient } from 'viem';
4
4
  import './types-C07FK-cL.cjs';
5
5
  import 'zod';
@@ -106,8 +106,6 @@ declare const TASK_MANAGER_ADDRESS: "0xeA30c4B8b44078Bbf8a6ef5b9f1eC1626C7848D9"
106
106
  declare const MOCKS_ZK_VERIFIER_ADDRESS: "0x0000000000000000000000000000000000005001";
107
107
  /** Mock Threshold Network contract address (used for testing) */
108
108
  declare const MOCKS_THRESHOLD_NETWORK_ADDRESS: "0x0000000000000000000000000000000000005002";
109
- /** Test Bed contract address (used for testing) */
110
- declare const TEST_BED_ADDRESS: "0x0000000000000000000000000000000000005003";
111
109
  /** Private key for the Mock ZK Verifier signer account */
112
110
  declare const MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY: "0x6C8D7F768A6BB4AAFE85E8A2F5A9680355239C7E14646ED62B044E39DE154512";
113
111
  /** Address for the Mock ZK Verifier signer account */
@@ -139,4 +137,4 @@ declare function verifyDecryptResult(handle: bigint | string, cleartext: bigint,
139
137
  */
140
138
  declare function fheTypeToString(utype: FheTypes): string;
141
139
 
142
- export { InitialConnectStore as CONNECT_STORE_DEFAULTS, CofheClient, CofheClientConnectionState, CofheClientParams, CofheConfig, CofheError, CofheErrorCode, type CofheErrorParams, FheTypes, MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_ZK_VERIFIER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, TASK_MANAGER_ADDRESS, TEST_BED_ADDRESS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, TFHE_RS_ZK_MAX_BITS, createCofheClientBase, fheTypeToString, isCofheError, verifyDecryptResult };
140
+ export { InitialConnectStore as CONNECT_STORE_DEFAULTS, CofheClient, CofheClientConnectionState, CofheClientParams, CofheConfig, CofheError, CofheErrorCode, type CofheErrorParams, FheTypes, MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_ZK_VERIFIER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, TASK_MANAGER_ADDRESS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, TFHE_RS_ZK_MAX_BITS, createCofheClientBase, fheTypeToString, isCofheError, verifyDecryptResult };
package/dist/core.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as CofheConfig, c as CofheClientParams, b as CofheClient, d as CofheClientConnectionState, F as FheTypes } from './clientTypes-DDmcgZ0a.js';
2
- export { h as CofheClientPermits, C as CofheInputConfig, f as CofheInternalConfig, G as DecryptEndpoint, $ as DecryptForTxBuilder, a0 as DecryptForTxResult, _ as DecryptForViewBuilder, B as DecryptPollCallbackContext, D as DecryptPollCallbackFunction, Z as EncryptInputsBuilder, H as EncryptSetStateFn, Q as EncryptStep, J as EncryptStepCallbackContext, N as Encryptable, o as EncryptableAddress, i as EncryptableBool, E as EncryptableItem, z as EncryptableToEncryptedItemInputMap, n as EncryptableUint128, k as EncryptableUint16, l as EncryptableUint32, m as EncryptableUint64, j as EncryptableUint8, x as EncryptedAddressInput, r as EncryptedBoolInput, q as EncryptedItemInput, y as EncryptedItemInputs, p as EncryptedNumber, w as EncryptedUint128Input, t as EncryptedUint16Input, u as EncryptedUint32Input, v as EncryptedUint64Input, s as EncryptedUint8Input, M as FheAllUTypes, V as FheKeyDeserializer, A as FheTypeValue, K as FheUintUTypes, I as IStorage, X as KeysStorage, Y as KeysStore, L as LiteralToPrimitive, P as Primitive, U as UnsealedItem, a1 as ZkBuilderAndCrsGenerator, a2 as ZkProveWorkerFunction, a3 as ZkProveWorkerRequest, a4 as ZkProveWorkerResponse, S as assertCorrectEncryptedItemInput, e as createCofheConfigBase, W as createKeysStore, T as fetchKeys, g as getCofheConfigItem, O as isEncryptableItem, R as isLastEncryptionStep, a5 as zkProveWithWorker } from './clientTypes-DDmcgZ0a.js';
1
+ import { a as CofheConfig, c as CofheClientParams, b as CofheClient, d as CofheClientConnectionState, F as FheTypes } from './clientTypes-CyUvRRzA.js';
2
+ export { O as AnyExternalHash, h as CofheClientPermits, C as CofheInputConfig, f as CofheInternalConfig, W as DecryptEndpoint, ab as DecryptForTxBuilder, ac as DecryptForTxResult, aa as DecryptForViewBuilder, V as DecryptPollCallbackContext, T as DecryptPollCallbackFunction, a9 as EncryptInputsBuilder, X as EncryptSetStateFn, a1 as EncryptStep, Y as EncryptStepCallbackContext, $ as Encryptable, o as EncryptableAddress, i as EncryptableBool, E as EncryptableItem, z as EncryptableToEncryptedItemInputMap, Q as EncryptableToExternalHashMap, n as EncryptableUint128, k as EncryptableUint16, l as EncryptableUint32, m as EncryptableUint64, j as EncryptableUint8, x as EncryptedAddressInput, r as EncryptedBoolInput, q as EncryptedItemInput, y as EncryptedItemInputs, p as EncryptedNumber, w as EncryptedUint128Input, t as EncryptedUint16Input, u as EncryptedUint32Input, v as EncryptedUint64Input, s as EncryptedUint8Input, M as ExternalAddressHash, B as ExternalBoolHash, N as ExternalHashProof, R as ExternalItemHashes, K as ExternalUint128Hash, G as ExternalUint16Hash, H as ExternalUint32Hash, J as ExternalUint64Hash, D as ExternalUint8Hash, _ as FheAllUTypes, a5 as FheKeyDeserializer, A as FheTypeValue, Z as FheUintUTypes, S as HashPlusProofResult, I as IStorage, a7 as KeysStorage, a8 as KeysStore, L as LiteralToPrimitive, P as Primitive, U as UnsealedItem, ad as ZkBuilderAndCrsGenerator, ae as ZkProveWorkerFunction, af as ZkProveWorkerRequest, ag as ZkProveWorkerResponse, a3 as assertCorrectEncryptedItemInput, e as createCofheConfigBase, a6 as createKeysStore, a4 as fetchKeys, g as getCofheConfigItem, a0 as isEncryptableItem, a2 as isLastEncryptionStep, ah as zkProveWithWorker } from './clientTypes-CyUvRRzA.js';
3
3
  import { Hex, PublicClient } from 'viem';
4
4
  import './types-C07FK-cL.js';
5
5
  import 'zod';
@@ -106,8 +106,6 @@ declare const TASK_MANAGER_ADDRESS: "0xeA30c4B8b44078Bbf8a6ef5b9f1eC1626C7848D9"
106
106
  declare const MOCKS_ZK_VERIFIER_ADDRESS: "0x0000000000000000000000000000000000005001";
107
107
  /** Mock Threshold Network contract address (used for testing) */
108
108
  declare const MOCKS_THRESHOLD_NETWORK_ADDRESS: "0x0000000000000000000000000000000000005002";
109
- /** Test Bed contract address (used for testing) */
110
- declare const TEST_BED_ADDRESS: "0x0000000000000000000000000000000000005003";
111
109
  /** Private key for the Mock ZK Verifier signer account */
112
110
  declare const MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY: "0x6C8D7F768A6BB4AAFE85E8A2F5A9680355239C7E14646ED62B044E39DE154512";
113
111
  /** Address for the Mock ZK Verifier signer account */
@@ -139,4 +137,4 @@ declare function verifyDecryptResult(handle: bigint | string, cleartext: bigint,
139
137
  */
140
138
  declare function fheTypeToString(utype: FheTypes): string;
141
139
 
142
- export { InitialConnectStore as CONNECT_STORE_DEFAULTS, CofheClient, CofheClientConnectionState, CofheClientParams, CofheConfig, CofheError, CofheErrorCode, type CofheErrorParams, FheTypes, MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_ZK_VERIFIER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, TASK_MANAGER_ADDRESS, TEST_BED_ADDRESS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, TFHE_RS_ZK_MAX_BITS, createCofheClientBase, fheTypeToString, isCofheError, verifyDecryptResult };
140
+ export { InitialConnectStore as CONNECT_STORE_DEFAULTS, CofheClient, CofheClientConnectionState, CofheClientParams, CofheConfig, CofheError, CofheErrorCode, type CofheErrorParams, FheTypes, MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_ZK_VERIFIER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, TASK_MANAGER_ADDRESS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, TFHE_RS_ZK_MAX_BITS, createCofheClientBase, fheTypeToString, isCofheError, verifyDecryptResult };
package/dist/core.js CHANGED
@@ -1,4 +1,4 @@
1
- export { InitialConnectStore as CONNECT_STORE_DEFAULTS, CofheError, CofheErrorCode, DecryptForTxBuilder, DecryptForViewBuilder, EncryptInputsBuilder, EncryptStep, Encryptable, FheAllUTypes, FheTypes, FheUintUTypes, assertCorrectEncryptedItemInput, createCofheClientBase, createCofheConfigBase, createKeysStore, fetchKeys, fheTypeToString, getCofheConfigItem, isCofheError, isEncryptableItem, isLastEncryptionStep, verifyDecryptResult, zkProveWithWorker } from './chunk-S7OKGLFD.js';
2
- import './chunk-TBLR7NNE.js';
3
- import './chunk-MRCKUMOS.js';
4
- export { MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_ZK_VERIFIER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, TASK_MANAGER_ADDRESS, TEST_BED_ADDRESS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, TFHE_RS_ZK_MAX_BITS } from './chunk-4FP4V35O.js';
1
+ export { InitialConnectStore as CONNECT_STORE_DEFAULTS, CofheError, CofheErrorCode, DecryptForTxBuilder, DecryptForViewBuilder, EncryptInputsBuilder, EncryptStep, Encryptable, FheAllUTypes, FheTypes, FheUintUTypes, assertCorrectEncryptedItemInput, createCofheClientBase, createCofheConfigBase, createKeysStore, fetchKeys, fheTypeToString, getCofheConfigItem, isCofheError, isEncryptableItem, isLastEncryptionStep, verifyDecryptResult, zkProveWithWorker } from './chunk-PE5V5CCV.js';
2
+ import './chunk-MTRAXQXC.js';
3
+ import './chunk-VB62WYPL.js';
4
+ export { MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_ZK_VERIFIER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, TASK_MANAGER_ADDRESS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, TFHE_RS_ZK_MAX_BITS } from './chunk-ESMZCFJY.js';
package/dist/node.cjs CHANGED
@@ -358,7 +358,7 @@ var zkVerify = async (verifierUrl, serializedBytes, address, securityZone, chain
358
358
  }
359
359
  };
360
360
  var concatSigRecid = (signature, recid) => {
361
- return signature + (recid + 27).toString(16).padStart(2, "0");
361
+ return `${signature}${(recid + 27).toString(16).padStart(2, "0")}`;
362
362
  };
363
363
 
364
364
  // core/encrypt/MockZkVerifierAbi.ts
@@ -690,9 +690,9 @@ var hardhat2 = defineChain({
690
690
  name: "Hardhat",
691
691
  network: "localhost",
692
692
  // These are unused in the mock environment
693
- coFheUrl: "http://127.0.0.1:8448",
694
- verifierUrl: "http://127.0.0.1:3001",
695
- thresholdNetworkUrl: "http://127.0.0.1:3000",
693
+ coFheUrl: "http://ignored-in-mock-environment",
694
+ verifierUrl: "http://ignored-in-mock-environment",
695
+ thresholdNetworkUrl: "http://ignored-in-mock-environment",
696
696
  environment: "MOCK"
697
697
  });
698
698
  var CofheConfigSchema = zod.z.object({
@@ -1078,6 +1078,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1078
1078
  securityZone;
1079
1079
  stepCallback;
1080
1080
  inputItems;
1081
+ hpp = false;
1081
1082
  zkvWalletClient;
1082
1083
  tfhePublicKeyDeserializer;
1083
1084
  compactPkeCrsDeserializer;
@@ -1207,6 +1208,20 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1207
1208
  getSecurityZone() {
1208
1209
  return this.securityZone;
1209
1210
  }
1211
+ /**
1212
+ * Example:
1213
+ * ```typescript
1214
+ * const encrypted = await encryptInputs([Encryptable.uint128(10n)])
1215
+ * .asHashPlusProof()
1216
+ * .execute();
1217
+ * ```
1218
+ *
1219
+ * @returns Chainable EncryptInputsBuilder instance that will return a HashPlusProofResult instead of an array of EncryptedItemInputs.
1220
+ */
1221
+ asHashPlusProof() {
1222
+ this.hpp = true;
1223
+ return this;
1224
+ }
1210
1225
  /**
1211
1226
  * @param useWorker - Whether to use Web Workers for ZK proof generation.
1212
1227
  *
@@ -1488,6 +1503,15 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1488
1503
  this.fireStepEnd("verify" /* Verify */);
1489
1504
  return encryptedInputs;
1490
1505
  }
1506
+ structsToHashPlusProof(inItems) {
1507
+ let hashes = [];
1508
+ let proof = "";
1509
+ for (const item of inItems) {
1510
+ hashes.push("0x" + item.ctHash.toString(16).padStart(64, "0"));
1511
+ proof += item.signature;
1512
+ }
1513
+ return [...hashes, proof];
1514
+ }
1491
1515
  /**
1492
1516
  * Final step of the encryption process. MUST BE CALLED LAST IN THE CHAIN.
1493
1517
  *
@@ -1508,9 +1532,14 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1508
1532
  * @returns The encrypted inputs.
1509
1533
  */
1510
1534
  async execute() {
1535
+ let items;
1511
1536
  if (this.chainId === chains.hardhat.id)
1512
- return this.mocksExecute();
1513
- return this.productionExecute();
1537
+ items = await this.mocksExecute();
1538
+ else
1539
+ items = await this.productionExecute();
1540
+ if (this.hpp)
1541
+ return this.structsToHashPlusProof(items);
1542
+ return items;
1514
1543
  }
1515
1544
  };
1516
1545
 
@@ -2809,6 +2838,96 @@ function computeMinuteRampPollIntervalMs(elapsedMs, params) {
2809
2838
  return Math.min(params.maxIntervalMs, Math.max(params.minIntervalMs, intervalMs));
2810
2839
  }
2811
2840
 
2841
+ // core/decrypt/submitRetry.ts
2842
+ var DEFAULT_404_RETRY_TIMEOUT_MS = 1e4;
2843
+ function isRetryableSubmitStatus(status) {
2844
+ return status === 204 || status === 404;
2845
+ }
2846
+ function normalize404RetryTimeoutMs(params) {
2847
+ const { timeoutMs, operationLabel, errorCode } = params;
2848
+ if (timeoutMs === void 0)
2849
+ return DEFAULT_404_RETRY_TIMEOUT_MS;
2850
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
2851
+ throw new CofheError({
2852
+ code: errorCode,
2853
+ message: `${operationLabel} submit 404 retry timeout must be a finite number greater than or equal to 0`,
2854
+ context: {
2855
+ timeoutMs
2856
+ }
2857
+ });
2858
+ }
2859
+ return timeoutMs;
2860
+ }
2861
+ async function classifySubmitResponse(params) {
2862
+ const { response, extractErrorMessage } = params;
2863
+ if (isRetryableSubmitStatus(response.status)) {
2864
+ return { kind: "retryable", status: response.status };
2865
+ }
2866
+ if (response.ok) {
2867
+ return { kind: "parse-json" };
2868
+ }
2869
+ let errorMessage = `HTTP ${response.status}`;
2870
+ try {
2871
+ const errorBody = await response.json();
2872
+ const maybeErrorMessage = extractErrorMessage?.(errorBody);
2873
+ if (typeof maybeErrorMessage === "string" && maybeErrorMessage.length > 0) {
2874
+ errorMessage = maybeErrorMessage;
2875
+ } else if (errorBody && typeof errorBody === "object") {
2876
+ const defaultMessage = errorBody.error_message;
2877
+ const fallbackMessage = errorBody.message;
2878
+ if (typeof defaultMessage === "string" && defaultMessage.length > 0) {
2879
+ errorMessage = defaultMessage;
2880
+ } else if (typeof fallbackMessage === "string" && fallbackMessage.length > 0) {
2881
+ errorMessage = fallbackMessage;
2882
+ }
2883
+ }
2884
+ } catch {
2885
+ errorMessage = response.statusText || errorMessage;
2886
+ }
2887
+ return { kind: "fatal-http", errorMessage };
2888
+ }
2889
+ function throwIfSubmitRetryTimedOut(params) {
2890
+ const {
2891
+ operationLabel,
2892
+ errorCode,
2893
+ status,
2894
+ elapsedMs,
2895
+ retry404TimeoutMs,
2896
+ overallTimeoutMs,
2897
+ thresholdNetworkUrl,
2898
+ body,
2899
+ attemptIndex
2900
+ } = params;
2901
+ if (status === 404 && elapsedMs > retry404TimeoutMs) {
2902
+ throw new CofheError({
2903
+ code: errorCode,
2904
+ message: `${operationLabel} submit retried 404 responses without receiving request_id for ${retry404TimeoutMs}ms`,
2905
+ hint: "The ciphertext may not be indexed yet. Increase set404RetryTimeout(...) if the backend is slow to index ciphertexts.",
2906
+ context: {
2907
+ thresholdNetworkUrl,
2908
+ body,
2909
+ attemptIndex,
2910
+ timeoutMs: retry404TimeoutMs,
2911
+ status
2912
+ }
2913
+ });
2914
+ }
2915
+ if (elapsedMs > overallTimeoutMs) {
2916
+ throw new CofheError({
2917
+ code: errorCode,
2918
+ message: `${operationLabel} submit retried without receiving request_id for ${overallTimeoutMs}ms`,
2919
+ hint: "The ciphertext may still be propagating. Try again later.",
2920
+ context: {
2921
+ thresholdNetworkUrl,
2922
+ body,
2923
+ attemptIndex,
2924
+ timeoutMs: overallTimeoutMs,
2925
+ status
2926
+ }
2927
+ });
2928
+ }
2929
+ }
2930
+
2812
2931
  // core/decrypt/tnSealOutputV2.ts
2813
2932
  var POLL_INTERVAL_MS = 1e3;
2814
2933
  var POLL_MAX_INTERVAL_MS = 1e4;
@@ -2870,7 +2989,7 @@ function parseCompletedSealOutputResponse(params) {
2870
2989
  }
2871
2990
  return convertSealedData(sealed);
2872
2991
  }
2873
- async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, permission, overallStartTime, onPoll) {
2992
+ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, permission, overallStartTime, retry404TimeoutMs, onPoll) {
2874
2993
  const body = {
2875
2994
  ct_tempkey: BigInt(ctHash).toString(16).padStart(64, "0"),
2876
2995
  host_chain_id: chainId,
@@ -2900,17 +3019,11 @@ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, per
2900
3019
  }
2901
3020
  });
2902
3021
  }
2903
- if (!response.ok) {
2904
- let errorMessage = `HTTP ${response.status}`;
2905
- try {
2906
- const errorBody = await response.json();
2907
- errorMessage = errorBody.error_message || errorBody.message || errorMessage;
2908
- } catch {
2909
- errorMessage = response.statusText || errorMessage;
2910
- }
3022
+ const responseClassification = await classifySubmitResponse({ response });
3023
+ if (responseClassification.kind === "fatal-http") {
2911
3024
  throw new CofheError({
2912
3025
  code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2913
- message: `sealOutput request failed: ${errorMessage}`,
3026
+ message: `sealOutput request failed: ${responseClassification.errorMessage}`,
2914
3027
  hint: "Check the threshold network URL and request parameters.",
2915
3028
  context: {
2916
3029
  thresholdNetworkUrl,
@@ -2921,8 +3034,8 @@ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, per
2921
3034
  }
2922
3035
  });
2923
3036
  }
2924
- let submitResponse;
2925
- if (response.status !== 204) {
3037
+ if (responseClassification.kind === "parse-json") {
3038
+ let submitResponse;
2926
3039
  try {
2927
3040
  submitResponse = await response.json();
2928
3041
  } catch (e) {
@@ -2950,46 +3063,39 @@ async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, per
2950
3063
  if (submitResponse.request_id) {
2951
3064
  return { kind: "request_id", requestId: submitResponse.request_id };
2952
3065
  }
2953
- }
2954
- if (response.status === 204) {
2955
- const elapsedMs = Date.now() - overallStartTime;
2956
- if (elapsedMs > SEAL_OUTPUT_TIMEOUT_MS) {
2957
- throw new CofheError({
2958
- code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2959
- message: `sealOutput submit retried without receiving request_id for ${SEAL_OUTPUT_TIMEOUT_MS}ms`,
2960
- hint: "The ciphertext may still be propagating. Try again later.",
2961
- context: {
2962
- thresholdNetworkUrl,
2963
- body,
2964
- attemptIndex,
2965
- timeoutMs: SEAL_OUTPUT_TIMEOUT_MS,
2966
- submitResponse,
2967
- status: response.status
2968
- }
2969
- });
2970
- }
2971
- onPoll?.({
2972
- operation: "sealoutput",
2973
- requestId: "",
2974
- attemptIndex,
2975
- elapsedMs,
2976
- intervalMs: SUBMIT_RETRY_INTERVAL_MS,
2977
- timeoutMs: SEAL_OUTPUT_TIMEOUT_MS
3066
+ throw new CofheError({
3067
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
3068
+ message: `sealOutput submit response missing request_id`,
3069
+ context: {
3070
+ thresholdNetworkUrl,
3071
+ body,
3072
+ submitResponse,
3073
+ attemptIndex
3074
+ }
2978
3075
  });
2979
- await new Promise((resolve) => setTimeout(resolve, SUBMIT_RETRY_INTERVAL_MS));
2980
- attemptIndex += 1;
2981
- continue;
2982
3076
  }
2983
- throw new CofheError({
2984
- code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
2985
- message: `sealOutput submit response missing request_id`,
2986
- context: {
2987
- thresholdNetworkUrl,
2988
- body,
2989
- submitResponse,
2990
- attemptIndex
2991
- }
3077
+ const elapsedMs = Date.now() - overallStartTime;
3078
+ throwIfSubmitRetryTimedOut({
3079
+ operationLabel: "sealOutput",
3080
+ errorCode: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
3081
+ status: responseClassification.status,
3082
+ elapsedMs,
3083
+ retry404TimeoutMs,
3084
+ overallTimeoutMs: SEAL_OUTPUT_TIMEOUT_MS,
3085
+ thresholdNetworkUrl,
3086
+ body,
3087
+ attemptIndex
2992
3088
  });
3089
+ onPoll?.({
3090
+ operation: "sealoutput",
3091
+ requestId: "",
3092
+ attemptIndex,
3093
+ elapsedMs,
3094
+ intervalMs: SUBMIT_RETRY_INTERVAL_MS,
3095
+ timeoutMs: SEAL_OUTPUT_TIMEOUT_MS
3096
+ });
3097
+ await new Promise((resolve) => setTimeout(resolve, SUBMIT_RETRY_INTERVAL_MS));
3098
+ attemptIndex += 1;
2993
3099
  }
2994
3100
  }
2995
3101
  async function pollSealOutputStatus(thresholdNetworkUrl, requestId, overallStartTime, onPoll) {
@@ -3104,7 +3210,12 @@ async function pollSealOutputStatus(thresholdNetworkUrl, requestId, overallStart
3104
3210
  });
3105
3211
  }
3106
3212
  async function tnSealOutputV2(params) {
3107
- const { thresholdNetworkUrl, ctHash, chainId, permission, onPoll } = params;
3213
+ const { thresholdNetworkUrl, ctHash, chainId, permission, retry404TimeoutMs, onPoll } = params;
3214
+ const normalized404RetryTimeoutMs = normalize404RetryTimeoutMs({
3215
+ timeoutMs: retry404TimeoutMs,
3216
+ operationLabel: "sealOutput",
3217
+ errorCode: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */
3218
+ });
3108
3219
  const overallStartTime = Date.now();
3109
3220
  const submitResult = await submitSealOutputRequest(
3110
3221
  thresholdNetworkUrl,
@@ -3112,6 +3223,7 @@ async function tnSealOutputV2(params) {
3112
3223
  chainId,
3113
3224
  permission,
3114
3225
  overallStartTime,
3226
+ normalized404RetryTimeoutMs,
3115
3227
  onPoll
3116
3228
  );
3117
3229
  if (submitResult.kind === "completed") {
@@ -3121,12 +3233,14 @@ async function tnSealOutputV2(params) {
3121
3233
  }
3122
3234
 
3123
3235
  // core/decrypt/decryptForViewBuilder.ts
3236
+ var DEFAULT_404_RETRY_TIMEOUT_MS2 = 1e4;
3124
3237
  var DecryptForViewBuilder = class extends BaseBuilder {
3125
3238
  ctHash;
3126
3239
  utype;
3127
3240
  permitHash;
3128
3241
  permit;
3129
3242
  pollCallback;
3243
+ retry404TimeoutMs = DEFAULT_404_RETRY_TIMEOUT_MS2;
3130
3244
  constructor(params) {
3131
3245
  super({
3132
3246
  config: params.config,
@@ -3187,6 +3301,19 @@ var DecryptForViewBuilder = class extends BaseBuilder {
3187
3301
  this.pollCallback = callback;
3188
3302
  return this;
3189
3303
  }
3304
+ set404RetryTimeout(timeoutMs) {
3305
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
3306
+ throw new CofheError({
3307
+ code: "INTERNAL_ERROR" /* InternalError */,
3308
+ message: "decryptForView: set404RetryTimeout(timeoutMs) expects a finite number greater than or equal to 0.",
3309
+ context: {
3310
+ timeoutMs
3311
+ }
3312
+ });
3313
+ }
3314
+ this.retry404TimeoutMs = timeoutMs;
3315
+ return this;
3316
+ }
3190
3317
  withPermit(permitOrPermitHash) {
3191
3318
  if (typeof permitOrPermitHash === "string") {
3192
3319
  this.permitHash = permitOrPermitHash;
@@ -3315,6 +3442,7 @@ var DecryptForViewBuilder = class extends BaseBuilder {
3315
3442
  chainId: this.chainId,
3316
3443
  permission,
3317
3444
  thresholdNetworkUrl,
3445
+ retry404TimeoutMs: this.retry404TimeoutMs,
3318
3446
  onPoll: this.pollCallback
3319
3447
  });
3320
3448
  return PermitUtils.unseal(permit, sealed);
@@ -3590,7 +3718,7 @@ function assertDecryptStatusResponseV2(value) {
3590
3718
  }
3591
3719
  return value;
3592
3720
  }
3593
- async function submitDecryptRequestV2(thresholdNetworkUrl, ctHash, chainId, permission, overallStartTime, onPoll) {
3721
+ async function submitDecryptRequestV2(thresholdNetworkUrl, ctHash, chainId, permission, overallStartTime, retry404TimeoutMs, onPoll) {
3594
3722
  const body = {
3595
3723
  ct_tempkey: BigInt(ctHash).toString(16).padStart(64, "0"),
3596
3724
  host_chain_id: chainId
@@ -3622,19 +3750,11 @@ async function submitDecryptRequestV2(thresholdNetworkUrl, ctHash, chainId, perm
3622
3750
  }
3623
3751
  });
3624
3752
  }
3625
- if (!response.ok) {
3626
- let errorMessage = `HTTP ${response.status}`;
3627
- try {
3628
- const errorBody = await response.json();
3629
- const maybeMessage = errorBody.error_message || errorBody.message;
3630
- if (typeof maybeMessage === "string" && maybeMessage.length > 0)
3631
- errorMessage = maybeMessage;
3632
- } catch {
3633
- errorMessage = response.statusText || errorMessage;
3634
- }
3753
+ const responseClassification = await classifySubmitResponse({ response });
3754
+ if (responseClassification.kind === "fatal-http") {
3635
3755
  throw new CofheError({
3636
3756
  code: "DECRYPT_FAILED" /* DecryptFailed */,
3637
- message: `decrypt request failed: ${errorMessage}`,
3757
+ message: `decrypt request failed: ${responseClassification.errorMessage}`,
3638
3758
  hint: "Check the threshold network URL and request parameters.",
3639
3759
  context: {
3640
3760
  thresholdNetworkUrl,
@@ -3645,8 +3765,8 @@ async function submitDecryptRequestV2(thresholdNetworkUrl, ctHash, chainId, perm
3645
3765
  }
3646
3766
  });
3647
3767
  }
3648
- let submitResponse;
3649
- if (response.status !== 204) {
3768
+ if (responseClassification.kind === "parse-json") {
3769
+ let submitResponse;
3650
3770
  let rawJson;
3651
3771
  try {
3652
3772
  rawJson = await response.json();
@@ -3676,46 +3796,39 @@ async function submitDecryptRequestV2(thresholdNetworkUrl, ctHash, chainId, perm
3676
3796
  if (submitResponse.request_id) {
3677
3797
  return { kind: "request_id", requestId: submitResponse.request_id };
3678
3798
  }
3679
- }
3680
- if (response.status === 204) {
3681
- const elapsedMs = Date.now() - overallStartTime;
3682
- if (elapsedMs > DECRYPT_TIMEOUT_MS) {
3683
- throw new CofheError({
3684
- code: "DECRYPT_FAILED" /* DecryptFailed */,
3685
- message: `decrypt submit retried without receiving request_id for ${DECRYPT_TIMEOUT_MS}ms`,
3686
- hint: "The ciphertext may still be propagating. Try again later.",
3687
- context: {
3688
- thresholdNetworkUrl,
3689
- body,
3690
- attemptIndex,
3691
- timeoutMs: DECRYPT_TIMEOUT_MS,
3692
- submitResponse,
3693
- status: response.status
3694
- }
3695
- });
3696
- }
3697
- onPoll?.({
3698
- operation: "decrypt",
3699
- requestId: "",
3700
- attemptIndex,
3701
- elapsedMs,
3702
- intervalMs: SUBMIT_RETRY_INTERVAL_MS2,
3703
- timeoutMs: DECRYPT_TIMEOUT_MS
3799
+ throw new CofheError({
3800
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3801
+ message: `decrypt submit response missing request_id`,
3802
+ context: {
3803
+ thresholdNetworkUrl,
3804
+ body,
3805
+ submitResponse,
3806
+ attemptIndex
3807
+ }
3704
3808
  });
3705
- await new Promise((resolve) => setTimeout(resolve, SUBMIT_RETRY_INTERVAL_MS2));
3706
- attemptIndex += 1;
3707
- continue;
3708
3809
  }
3709
- throw new CofheError({
3710
- code: "DECRYPT_FAILED" /* DecryptFailed */,
3711
- message: `decrypt submit response missing request_id`,
3712
- context: {
3713
- thresholdNetworkUrl,
3714
- body,
3715
- submitResponse,
3716
- attemptIndex
3717
- }
3810
+ const elapsedMs = Date.now() - overallStartTime;
3811
+ throwIfSubmitRetryTimedOut({
3812
+ operationLabel: "decrypt",
3813
+ errorCode: "DECRYPT_FAILED" /* DecryptFailed */,
3814
+ status: responseClassification.status,
3815
+ elapsedMs,
3816
+ retry404TimeoutMs,
3817
+ overallTimeoutMs: DECRYPT_TIMEOUT_MS,
3818
+ thresholdNetworkUrl,
3819
+ body,
3820
+ attemptIndex
3718
3821
  });
3822
+ onPoll?.({
3823
+ operation: "decrypt",
3824
+ requestId: "",
3825
+ attemptIndex,
3826
+ elapsedMs,
3827
+ intervalMs: SUBMIT_RETRY_INTERVAL_MS2,
3828
+ timeoutMs: DECRYPT_TIMEOUT_MS
3829
+ });
3830
+ await new Promise((resolve) => setTimeout(resolve, SUBMIT_RETRY_INTERVAL_MS2));
3831
+ attemptIndex += 1;
3719
3832
  }
3720
3833
  }
3721
3834
  async function pollDecryptStatusV2(thresholdNetworkUrl, requestId, overallStartTime, onPoll) {
@@ -3833,7 +3946,12 @@ async function pollDecryptStatusV2(thresholdNetworkUrl, requestId, overallStartT
3833
3946
  });
3834
3947
  }
3835
3948
  async function tnDecryptV2(params) {
3836
- const { thresholdNetworkUrl, ctHash, chainId, permission, onPoll } = params;
3949
+ const { thresholdNetworkUrl, ctHash, chainId, permission, retry404TimeoutMs, onPoll } = params;
3950
+ const normalized404RetryTimeoutMs = normalize404RetryTimeoutMs({
3951
+ timeoutMs: retry404TimeoutMs,
3952
+ operationLabel: "decrypt",
3953
+ errorCode: "DECRYPT_FAILED" /* DecryptFailed */
3954
+ });
3837
3955
  const overallStartTime = Date.now();
3838
3956
  const submitResult = await submitDecryptRequestV2(
3839
3957
  thresholdNetworkUrl,
@@ -3841,6 +3959,7 @@ async function tnDecryptV2(params) {
3841
3959
  chainId,
3842
3960
  permission,
3843
3961
  overallStartTime,
3962
+ normalized404RetryTimeoutMs,
3844
3963
  onPoll
3845
3964
  );
3846
3965
  if (submitResult.kind === "completed") {
@@ -3850,12 +3969,14 @@ async function tnDecryptV2(params) {
3850
3969
  }
3851
3970
 
3852
3971
  // core/decrypt/decryptForTxBuilder.ts
3972
+ var DEFAULT_404_RETRY_TIMEOUT_MS3 = 1e4;
3853
3973
  var DecryptForTxBuilder = class extends BaseBuilder {
3854
3974
  ctHash;
3855
3975
  permitHash;
3856
3976
  permit;
3857
3977
  permitSelection = "unset";
3858
3978
  pollCallback;
3979
+ retry404TimeoutMs = DEFAULT_404_RETRY_TIMEOUT_MS3;
3859
3980
  constructor(params) {
3860
3981
  super({
3861
3982
  config: params.config,
@@ -3885,6 +4006,19 @@ var DecryptForTxBuilder = class extends BaseBuilder {
3885
4006
  this.pollCallback = callback;
3886
4007
  return this;
3887
4008
  }
4009
+ set404RetryTimeout(timeoutMs) {
4010
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
4011
+ throw new CofheError({
4012
+ code: "INTERNAL_ERROR" /* InternalError */,
4013
+ message: "decryptForTx: set404RetryTimeout(timeoutMs) expects a finite number greater than or equal to 0.",
4014
+ context: {
4015
+ timeoutMs
4016
+ }
4017
+ });
4018
+ }
4019
+ this.retry404TimeoutMs = timeoutMs;
4020
+ return this;
4021
+ }
3888
4022
  withPermit(permitOrPermitHash) {
3889
4023
  if (this.permitSelection === "with-permit") {
3890
4024
  throw new CofheError({
@@ -4017,6 +4151,7 @@ var DecryptForTxBuilder = class extends BaseBuilder {
4017
4151
  chainId: this.chainId,
4018
4152
  permission,
4019
4153
  thresholdNetworkUrl,
4154
+ retry404TimeoutMs: this.retry404TimeoutMs,
4020
4155
  onPoll: this.pollCallback
4021
4156
  });
4022
4157
  return {
package/dist/node.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as CofheInputConfig, a as CofheConfig, b as CofheClient } from './clientTypes-BSbwairE.cjs';
1
+ import { C as CofheInputConfig, a as CofheConfig, b as CofheClient } from './clientTypes-BDy1qIBu.cjs';
2
2
  import 'viem';
3
3
  import './types-C07FK-cL.cjs';
4
4
  import 'zod';
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as CofheInputConfig, a as CofheConfig, b as CofheClient } from './clientTypes-DDmcgZ0a.js';
1
+ import { C as CofheInputConfig, a as CofheConfig, b as CofheClient } from './clientTypes-CyUvRRzA.js';
2
2
  import 'viem';
3
3
  import './types-C07FK-cL.js';
4
4
  import 'zod';
package/dist/node.js CHANGED
@@ -1,7 +1,7 @@
1
- import { createCofheConfigBase, createCofheClientBase } from './chunk-S7OKGLFD.js';
2
- import './chunk-TBLR7NNE.js';
3
- import './chunk-MRCKUMOS.js';
4
- import { TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT } from './chunk-4FP4V35O.js';
1
+ import { createCofheConfigBase, createCofheClientBase } from './chunk-PE5V5CCV.js';
2
+ import './chunk-MTRAXQXC.js';
3
+ import './chunk-VB62WYPL.js';
4
+ import { TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT } from './chunk-ESMZCFJY.js';
5
5
  import { promises } from 'fs';
6
6
  import { join } from 'path';
7
7
  import { init_panic_hook, ProvenCompactCiphertextList, CompactPkeCrs, TfheCompactPublicKey } from 'node-tfhe';