@cofhe/sdk 1.0.0-alpha.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/acps/onchain-utils.ts +15 -10
  3. package/acps/sealing.ts +22 -2
  4. package/acps/test/aclServedAddresses.test.ts +65 -0
  5. package/acps/test/sealing.test.ts +51 -0
  6. package/core/encrypt/encryptInputsBuilder.ts +31 -13
  7. package/core/encrypt/zkPackProveVerify.ts +16 -4
  8. package/core/error.ts +1 -0
  9. package/core/test/encryptInputsBuilder.test.ts +56 -4
  10. package/core/test/zkPoKMetadata.test.ts +27 -0
  11. package/dist/acps.cjs +122 -99
  12. package/dist/acps.d.cts +2 -2
  13. package/dist/acps.d.ts +2 -2
  14. package/dist/acps.js +2 -2
  15. package/dist/{chunk-6ZW76ZKB.js → chunk-3SD2UCRE.js} +1 -1
  16. package/dist/{chunk-OL3DZN7A.js → chunk-GKEJHZ52.js} +35 -19
  17. package/dist/{chunk-XQ32JG3T.js → chunk-OC5TGQGG.js} +14 -13
  18. package/dist/{chunk-BQWHPIYU.js → chunk-WAA2U7CT.js} +29 -6
  19. package/dist/{clientTypes-C0A9ji5O.d.cts → clientTypes-C2b_qub5.d.cts} +6 -3
  20. package/dist/{clientTypes-CcU5WvdV.d.ts → clientTypes-DEKYh0cw.d.ts} +6 -3
  21. package/dist/core.cjs +220 -180
  22. package/dist/core.d.cts +4 -3
  23. package/dist/core.d.ts +4 -3
  24. package/dist/core.js +4 -4
  25. package/dist/node.cjs +153 -114
  26. package/dist/node.d.cts +2 -2
  27. package/dist/node.d.ts +2 -2
  28. package/dist/node.js +4 -4
  29. package/dist/{onchain-utils-D9Z33IP7.d.cts → onchain-utils-CgOslubH.d.cts} +3 -3
  30. package/dist/{onchain-utils-D9Z33IP7.d.ts → onchain-utils-CgOslubH.d.ts} +3 -3
  31. package/dist/web.cjs +153 -114
  32. package/dist/web.d.cts +2 -2
  33. package/dist/web.d.ts +2 -2
  34. package/dist/web.js +4 -4
  35. package/dist/zkProve.worker.js +2 -2
  36. package/package.json +1 -1
package/dist/core.cjs CHANGED
@@ -41,6 +41,167 @@ function toBigInt(value) {
41
41
  }
42
42
  }
43
43
 
44
+ // core/error.ts
45
+ var CofheErrorCode = /* @__PURE__ */ ((CofheErrorCode2) => {
46
+ CofheErrorCode2["InternalError"] = "INTERNAL_ERROR";
47
+ CofheErrorCode2["UnknownEnvironment"] = "UNKNOWN_ENVIRONMENT";
48
+ CofheErrorCode2["InitTfheFailed"] = "INIT_TFHE_FAILED";
49
+ CofheErrorCode2["InitViemFailed"] = "INIT_VIEM_FAILED";
50
+ CofheErrorCode2["InitEthersFailed"] = "INIT_ETHERS_FAILED";
51
+ CofheErrorCode2["NotConnected"] = "NOT_CONNECTED";
52
+ CofheErrorCode2["MissingPublicClient"] = "MISSING_PUBLIC_CLIENT";
53
+ CofheErrorCode2["MissingWalletClient"] = "MISSING_WALLET_CLIENT";
54
+ CofheErrorCode2["MissingProviderParam"] = "MISSING_PROVIDER_PARAM";
55
+ CofheErrorCode2["EmptySecurityZonesParam"] = "EMPTY_SECURITY_ZONES_PARAM";
56
+ CofheErrorCode2["InvalidACPData"] = "INVALID_ACP_DATA";
57
+ CofheErrorCode2["InvalidACPDomain"] = "INVALID_ACP_DOMAIN";
58
+ CofheErrorCode2["ACPNotFound"] = "ACP_NOT_FOUND";
59
+ CofheErrorCode2["CannotRemoveLastACP"] = "CANNOT_REMOVE_LAST_ACP";
60
+ CofheErrorCode2["AccountUninitialized"] = "ACCOUNT_UNINITIALIZED";
61
+ CofheErrorCode2["ChainIdUninitialized"] = "CHAIN_ID_UNINITIALIZED";
62
+ CofheErrorCode2["ConsumingContractUninitialized"] = "CONSUMING_CONTRACT_UNINITIALIZED";
63
+ CofheErrorCode2["ConsumingContractInvalid"] = "CONSUMING_CONTRACT_INVALID";
64
+ CofheErrorCode2["SealOutputFailed"] = "SEAL_OUTPUT_FAILED";
65
+ CofheErrorCode2["SealOutputReturnedNull"] = "SEAL_OUTPUT_RETURNED_NULL";
66
+ CofheErrorCode2["InvalidUtype"] = "INVALID_UTYPE";
67
+ CofheErrorCode2["DecryptFailed"] = "DECRYPT_FAILED";
68
+ CofheErrorCode2["DecryptReturnedNull"] = "DECRYPT_RETURNED_NULL";
69
+ CofheErrorCode2["ZkMocksInsertCtHashesFailed"] = "ZK_MOCKS_INSERT_CT_HASHES_FAILED";
70
+ CofheErrorCode2["ZkMocksCalcCtHashesFailed"] = "ZK_MOCKS_CALC_CT_HASHES_FAILED";
71
+ CofheErrorCode2["ZkMocksVerifySignFailed"] = "ZK_MOCKS_VERIFY_SIGN_FAILED";
72
+ CofheErrorCode2["ZkMocksCreateProofSignatureFailed"] = "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED";
73
+ CofheErrorCode2["ZkVerifyFailed"] = "ZK_VERIFY_FAILED";
74
+ CofheErrorCode2["ZkPackFailed"] = "ZK_PACK_FAILED";
75
+ CofheErrorCode2["ZkProveFailed"] = "ZK_PROVE_FAILED";
76
+ CofheErrorCode2["EncryptRemainingInItems"] = "ENCRYPT_REMAINING_IN_ITEMS";
77
+ CofheErrorCode2["ZkUninitialized"] = "ZK_UNINITIALIZED";
78
+ CofheErrorCode2["ZkVerifierUrlUninitialized"] = "ZK_VERIFIER_URL_UNINITIALIZED";
79
+ CofheErrorCode2["ThresholdNetworkUrlUninitialized"] = "THRESHOLD_NETWORK_URL_UNINITIALIZED";
80
+ CofheErrorCode2["MissingConfig"] = "MISSING_CONFIG";
81
+ CofheErrorCode2["UnsupportedChain"] = "UNSUPPORTED_CHAIN";
82
+ CofheErrorCode2["MissingZkBuilderAndCrsGenerator"] = "MISSING_ZK_BUILDER_AND_CRS_GENERATOR";
83
+ CofheErrorCode2["MissingTfhePublicKeyDeserializer"] = "MISSING_TFHE_PUBLIC_KEY_DESERIALIZER";
84
+ CofheErrorCode2["MissingCompactPkeCrsDeserializer"] = "MISSING_COMPACT_PKE_CRS_DESERIALIZER";
85
+ CofheErrorCode2["MissingFheKey"] = "MISSING_FHE_KEY";
86
+ CofheErrorCode2["MissingCrs"] = "MISSING_CRS";
87
+ CofheErrorCode2["FetchKeysFailed"] = "FETCH_KEYS_FAILED";
88
+ CofheErrorCode2["PublicWalletGetChainIdFailed"] = "PUBLIC_WALLET_GET_CHAIN_ID_FAILED";
89
+ CofheErrorCode2["PublicWalletGetAddressesFailed"] = "PUBLIC_WALLET_GET_ADDRESSES_FAILED";
90
+ CofheErrorCode2["RehydrateKeysStoreFailed"] = "REHYDRATE_KEYS_STORE_FAILED";
91
+ CofheErrorCode2["TaskManagerUnresolved"] = "TASK_MANAGER_UNRESOLVED";
92
+ CofheErrorCode2["BadRequest"] = "BAD_REQUEST";
93
+ CofheErrorCode2["UnknownChain"] = "UNKNOWN_CHAIN";
94
+ CofheErrorCode2["ACPMalformed"] = "ACP_MALFORMED";
95
+ CofheErrorCode2["ACPDenied"] = "ACP_DENIED";
96
+ CofheErrorCode2["ACPExpired"] = "ACP_EXPIRED";
97
+ CofheErrorCode2["ACPInvalid"] = "ACP_INVALID";
98
+ CofheErrorCode2["ACPRevoked"] = "ACP_REVOKED";
99
+ CofheErrorCode2["NotPubliclyAllowed"] = "NOT_PUBLICLY_ALLOWED";
100
+ CofheErrorCode2["CtNotFound"] = "CT_NOT_FOUND";
101
+ CofheErrorCode2["UnsupportedSecurityZone"] = "UNSUPPORTED_SECURITY_ZONE";
102
+ CofheErrorCode2["UnsupportedType"] = "UNSUPPORTED_TYPE";
103
+ CofheErrorCode2["SigningFailed"] = "SIGNING_FAILED";
104
+ CofheErrorCode2["CtSourceError"] = "CT_SOURCE_ERROR";
105
+ CofheErrorCode2["ACPVerifierError"] = "ACP_VERIFIER_ERROR";
106
+ CofheErrorCode2["CtSourceTimeout"] = "CT_SOURCE_TIMEOUT";
107
+ CofheErrorCode2["ACPVerifierTimeout"] = "ACP_VERIFIER_TIMEOUT";
108
+ CofheErrorCode2["ACPRequired"] = "ACP_REQUIRED";
109
+ CofheErrorCode2["SealFailed"] = "SEAL_FAILED";
110
+ return CofheErrorCode2;
111
+ })(CofheErrorCode || {});
112
+ var CofheError = class _CofheError extends Error {
113
+ code;
114
+ cause;
115
+ hint;
116
+ context;
117
+ apiErrorCode;
118
+ constructor({ code, message, cause, hint, context, apiErrorCode }) {
119
+ const fullMessage = cause ? `${message} | Caused by: ${cause.message}` : message;
120
+ super(fullMessage);
121
+ this.name = "CofheError";
122
+ this.code = code;
123
+ this.cause = cause;
124
+ this.hint = hint;
125
+ this.context = context;
126
+ this.apiErrorCode = apiErrorCode;
127
+ if (Error.captureStackTrace) {
128
+ Error.captureStackTrace(this, _CofheError);
129
+ }
130
+ }
131
+ /**
132
+ * Creates a CofheError from an unknown error
133
+ * If the error is a CofheError, it is returned unchanged, else a new CofheError is created
134
+ * If a wrapperError is provided, it is used to create the new CofheError, else a default is used
135
+ */
136
+ static fromError(error, wrapperError) {
137
+ if (isCofheError(error))
138
+ return error;
139
+ const cause = error instanceof Error ? error : new Error(`${error}`);
140
+ return new _CofheError({
141
+ code: wrapperError?.code ?? "INTERNAL_ERROR" /* InternalError */,
142
+ message: wrapperError?.message ?? "An internal error occurred",
143
+ hint: wrapperError?.hint,
144
+ context: wrapperError?.context,
145
+ apiErrorCode: wrapperError?.apiErrorCode,
146
+ cause
147
+ });
148
+ }
149
+ /**
150
+ * Serializes the error to JSON string with proper handling of Error objects
151
+ */
152
+ serialize() {
153
+ return bigintSafeJsonStringify({
154
+ name: this.name,
155
+ code: this.code,
156
+ message: this.message,
157
+ hint: this.hint,
158
+ context: this.context,
159
+ apiErrorCode: this.apiErrorCode,
160
+ cause: this.cause ? {
161
+ name: this.cause.name,
162
+ message: this.cause.message,
163
+ stack: this.cause.stack
164
+ } : void 0,
165
+ stack: this.stack
166
+ });
167
+ }
168
+ /**
169
+ * Returns a human-readable string representation of the error
170
+ */
171
+ toString() {
172
+ const codeSuffix = this.apiErrorCode ? ` (api: ${this.apiErrorCode})` : "";
173
+ const parts = [`${this.name} [${this.code}]${codeSuffix}: ${this.message}`];
174
+ if (this.hint) {
175
+ parts.push(`Hint: ${this.hint}`);
176
+ }
177
+ if (this.context && Object.keys(this.context).length > 0) {
178
+ parts.push(`Context: ${bigintSafeJsonStringify(this.context)}`);
179
+ }
180
+ if (this.stack) {
181
+ parts.push(`
182
+ Stack trace:`);
183
+ parts.push(this.stack);
184
+ }
185
+ if (this.cause) {
186
+ parts.push(`
187
+ Caused by: ${this.cause.name}: ${this.cause.message}`);
188
+ if (this.cause.stack) {
189
+ parts.push(this.cause.stack);
190
+ }
191
+ }
192
+ return parts.join("\n");
193
+ }
194
+ };
195
+ var bigintSafeJsonStringify = (value) => {
196
+ return JSON.stringify(value, (key, value2) => {
197
+ if (typeof value2 === "bigint") {
198
+ return `${value2}n`;
199
+ }
200
+ return value2;
201
+ });
202
+ };
203
+ var isCofheError = (error) => error instanceof CofheError;
204
+
44
205
  // acps/sealing.ts
45
206
  var KEY_HEX_LENGTH = 64;
46
207
  var GenerateSealingKey = () => {
@@ -55,9 +216,25 @@ var unsealWithPrivateKey = (privateKey, parsedData) => {
55
216
  const nonce = parsedData.nonce instanceof Uint8Array ? parsedData.nonce : new Uint8Array(parsedData.nonce);
56
217
  const ephemPublicKey = parsedData.public_key instanceof Uint8Array ? parsedData.public_key : new Uint8Array(parsedData.public_key);
57
218
  const dataToDecrypt = parsedData.data instanceof Uint8Array ? parsedData.data : new Uint8Array(parsedData.data);
58
- const decryptedMessage = nacl__default.default.box.open(dataToDecrypt, nonce, ephemPublicKey, fromHexString(privateKey));
219
+ let decryptedMessage;
220
+ let cause;
221
+ try {
222
+ decryptedMessage = nacl__default.default.box.open(dataToDecrypt, nonce, ephemPublicKey, fromHexString(privateKey));
223
+ } catch (e) {
224
+ decryptedMessage = null;
225
+ cause = e instanceof Error ? e : void 0;
226
+ }
59
227
  if (!decryptedMessage) {
60
- throw new Error("Failed to decrypt message");
228
+ throw new CofheError({
229
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
230
+ message: "Failed to unseal decrypt response",
231
+ cause,
232
+ context: {
233
+ dataLength: dataToDecrypt.length,
234
+ nonceLength: nonce.length,
235
+ publicKeyLength: ephemPublicKey.length
236
+ }
237
+ });
61
238
  }
62
239
  return toBigInt(decryptedMessage);
63
240
  };
@@ -377,166 +554,6 @@ var TFHE_RS_ZK_MAX_BITS = 2048;
377
554
  var TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT = BigInt(1 << 30);
378
555
  var TFHE_RS_KEY_VERSION = 2;
379
556
 
380
- // core/error.ts
381
- var CofheErrorCode = /* @__PURE__ */ ((CofheErrorCode2) => {
382
- CofheErrorCode2["InternalError"] = "INTERNAL_ERROR";
383
- CofheErrorCode2["UnknownEnvironment"] = "UNKNOWN_ENVIRONMENT";
384
- CofheErrorCode2["InitTfheFailed"] = "INIT_TFHE_FAILED";
385
- CofheErrorCode2["InitViemFailed"] = "INIT_VIEM_FAILED";
386
- CofheErrorCode2["InitEthersFailed"] = "INIT_ETHERS_FAILED";
387
- CofheErrorCode2["NotConnected"] = "NOT_CONNECTED";
388
- CofheErrorCode2["MissingPublicClient"] = "MISSING_PUBLIC_CLIENT";
389
- CofheErrorCode2["MissingWalletClient"] = "MISSING_WALLET_CLIENT";
390
- CofheErrorCode2["MissingProviderParam"] = "MISSING_PROVIDER_PARAM";
391
- CofheErrorCode2["EmptySecurityZonesParam"] = "EMPTY_SECURITY_ZONES_PARAM";
392
- CofheErrorCode2["InvalidACPData"] = "INVALID_ACP_DATA";
393
- CofheErrorCode2["InvalidACPDomain"] = "INVALID_ACP_DOMAIN";
394
- CofheErrorCode2["ACPNotFound"] = "ACP_NOT_FOUND";
395
- CofheErrorCode2["CannotRemoveLastACP"] = "CANNOT_REMOVE_LAST_ACP";
396
- CofheErrorCode2["AccountUninitialized"] = "ACCOUNT_UNINITIALIZED";
397
- CofheErrorCode2["ChainIdUninitialized"] = "CHAIN_ID_UNINITIALIZED";
398
- CofheErrorCode2["ConsumingContractUninitialized"] = "CONSUMING_CONTRACT_UNINITIALIZED";
399
- CofheErrorCode2["SealOutputFailed"] = "SEAL_OUTPUT_FAILED";
400
- CofheErrorCode2["SealOutputReturnedNull"] = "SEAL_OUTPUT_RETURNED_NULL";
401
- CofheErrorCode2["InvalidUtype"] = "INVALID_UTYPE";
402
- CofheErrorCode2["DecryptFailed"] = "DECRYPT_FAILED";
403
- CofheErrorCode2["DecryptReturnedNull"] = "DECRYPT_RETURNED_NULL";
404
- CofheErrorCode2["ZkMocksInsertCtHashesFailed"] = "ZK_MOCKS_INSERT_CT_HASHES_FAILED";
405
- CofheErrorCode2["ZkMocksCalcCtHashesFailed"] = "ZK_MOCKS_CALC_CT_HASHES_FAILED";
406
- CofheErrorCode2["ZkMocksVerifySignFailed"] = "ZK_MOCKS_VERIFY_SIGN_FAILED";
407
- CofheErrorCode2["ZkMocksCreateProofSignatureFailed"] = "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED";
408
- CofheErrorCode2["ZkVerifyFailed"] = "ZK_VERIFY_FAILED";
409
- CofheErrorCode2["ZkPackFailed"] = "ZK_PACK_FAILED";
410
- CofheErrorCode2["ZkProveFailed"] = "ZK_PROVE_FAILED";
411
- CofheErrorCode2["EncryptRemainingInItems"] = "ENCRYPT_REMAINING_IN_ITEMS";
412
- CofheErrorCode2["ZkUninitialized"] = "ZK_UNINITIALIZED";
413
- CofheErrorCode2["ZkVerifierUrlUninitialized"] = "ZK_VERIFIER_URL_UNINITIALIZED";
414
- CofheErrorCode2["ThresholdNetworkUrlUninitialized"] = "THRESHOLD_NETWORK_URL_UNINITIALIZED";
415
- CofheErrorCode2["MissingConfig"] = "MISSING_CONFIG";
416
- CofheErrorCode2["UnsupportedChain"] = "UNSUPPORTED_CHAIN";
417
- CofheErrorCode2["MissingZkBuilderAndCrsGenerator"] = "MISSING_ZK_BUILDER_AND_CRS_GENERATOR";
418
- CofheErrorCode2["MissingTfhePublicKeyDeserializer"] = "MISSING_TFHE_PUBLIC_KEY_DESERIALIZER";
419
- CofheErrorCode2["MissingCompactPkeCrsDeserializer"] = "MISSING_COMPACT_PKE_CRS_DESERIALIZER";
420
- CofheErrorCode2["MissingFheKey"] = "MISSING_FHE_KEY";
421
- CofheErrorCode2["MissingCrs"] = "MISSING_CRS";
422
- CofheErrorCode2["FetchKeysFailed"] = "FETCH_KEYS_FAILED";
423
- CofheErrorCode2["PublicWalletGetChainIdFailed"] = "PUBLIC_WALLET_GET_CHAIN_ID_FAILED";
424
- CofheErrorCode2["PublicWalletGetAddressesFailed"] = "PUBLIC_WALLET_GET_ADDRESSES_FAILED";
425
- CofheErrorCode2["RehydrateKeysStoreFailed"] = "REHYDRATE_KEYS_STORE_FAILED";
426
- CofheErrorCode2["TaskManagerUnresolved"] = "TASK_MANAGER_UNRESOLVED";
427
- CofheErrorCode2["BadRequest"] = "BAD_REQUEST";
428
- CofheErrorCode2["UnknownChain"] = "UNKNOWN_CHAIN";
429
- CofheErrorCode2["ACPMalformed"] = "ACP_MALFORMED";
430
- CofheErrorCode2["ACPDenied"] = "ACP_DENIED";
431
- CofheErrorCode2["ACPExpired"] = "ACP_EXPIRED";
432
- CofheErrorCode2["ACPInvalid"] = "ACP_INVALID";
433
- CofheErrorCode2["ACPRevoked"] = "ACP_REVOKED";
434
- CofheErrorCode2["NotPubliclyAllowed"] = "NOT_PUBLICLY_ALLOWED";
435
- CofheErrorCode2["CtNotFound"] = "CT_NOT_FOUND";
436
- CofheErrorCode2["UnsupportedSecurityZone"] = "UNSUPPORTED_SECURITY_ZONE";
437
- CofheErrorCode2["UnsupportedType"] = "UNSUPPORTED_TYPE";
438
- CofheErrorCode2["SigningFailed"] = "SIGNING_FAILED";
439
- CofheErrorCode2["CtSourceError"] = "CT_SOURCE_ERROR";
440
- CofheErrorCode2["ACPVerifierError"] = "ACP_VERIFIER_ERROR";
441
- CofheErrorCode2["CtSourceTimeout"] = "CT_SOURCE_TIMEOUT";
442
- CofheErrorCode2["ACPVerifierTimeout"] = "ACP_VERIFIER_TIMEOUT";
443
- CofheErrorCode2["ACPRequired"] = "ACP_REQUIRED";
444
- CofheErrorCode2["SealFailed"] = "SEAL_FAILED";
445
- return CofheErrorCode2;
446
- })(CofheErrorCode || {});
447
- var CofheError = class _CofheError extends Error {
448
- code;
449
- cause;
450
- hint;
451
- context;
452
- apiErrorCode;
453
- constructor({ code, message, cause, hint, context, apiErrorCode }) {
454
- const fullMessage = cause ? `${message} | Caused by: ${cause.message}` : message;
455
- super(fullMessage);
456
- this.name = "CofheError";
457
- this.code = code;
458
- this.cause = cause;
459
- this.hint = hint;
460
- this.context = context;
461
- this.apiErrorCode = apiErrorCode;
462
- if (Error.captureStackTrace) {
463
- Error.captureStackTrace(this, _CofheError);
464
- }
465
- }
466
- /**
467
- * Creates a CofheError from an unknown error
468
- * If the error is a CofheError, it is returned unchanged, else a new CofheError is created
469
- * If a wrapperError is provided, it is used to create the new CofheError, else a default is used
470
- */
471
- static fromError(error, wrapperError) {
472
- if (isCofheError(error))
473
- return error;
474
- const cause = error instanceof Error ? error : new Error(`${error}`);
475
- return new _CofheError({
476
- code: wrapperError?.code ?? "INTERNAL_ERROR" /* InternalError */,
477
- message: wrapperError?.message ?? "An internal error occurred",
478
- hint: wrapperError?.hint,
479
- context: wrapperError?.context,
480
- apiErrorCode: wrapperError?.apiErrorCode,
481
- cause
482
- });
483
- }
484
- /**
485
- * Serializes the error to JSON string with proper handling of Error objects
486
- */
487
- serialize() {
488
- return bigintSafeJsonStringify({
489
- name: this.name,
490
- code: this.code,
491
- message: this.message,
492
- hint: this.hint,
493
- context: this.context,
494
- apiErrorCode: this.apiErrorCode,
495
- cause: this.cause ? {
496
- name: this.cause.name,
497
- message: this.cause.message,
498
- stack: this.cause.stack
499
- } : void 0,
500
- stack: this.stack
501
- });
502
- }
503
- /**
504
- * Returns a human-readable string representation of the error
505
- */
506
- toString() {
507
- const codeSuffix = this.apiErrorCode ? ` (api: ${this.apiErrorCode})` : "";
508
- const parts = [`${this.name} [${this.code}]${codeSuffix}: ${this.message}`];
509
- if (this.hint) {
510
- parts.push(`Hint: ${this.hint}`);
511
- }
512
- if (this.context && Object.keys(this.context).length > 0) {
513
- parts.push(`Context: ${bigintSafeJsonStringify(this.context)}`);
514
- }
515
- if (this.stack) {
516
- parts.push(`
517
- Stack trace:`);
518
- parts.push(this.stack);
519
- }
520
- if (this.cause) {
521
- parts.push(`
522
- Caused by: ${this.cause.name}: ${this.cause.message}`);
523
- if (this.cause.stack) {
524
- parts.push(this.cause.stack);
525
- }
526
- }
527
- return parts.join("\n");
528
- }
529
- };
530
- var bigintSafeJsonStringify = (value) => {
531
- return JSON.stringify(value, (key, value2) => {
532
- if (typeof value2 === "bigint") {
533
- return `${value2}n`;
534
- }
535
- return value2;
536
- });
537
- };
538
- var isCofheError = (error) => error instanceof CofheError;
539
-
540
557
  // core/taskManager.ts
541
558
  var ADDRESS_BOOK_ABI = viem.parseAbi([
542
559
  "function getTm(uint256 id) view returns (address)",
@@ -844,15 +861,22 @@ var getAclServedAddresses = async (publicClient, chainId) => {
844
861
  } catch {
845
862
  return {};
846
863
  }
864
+ let transient = false;
865
+ const readServedAddress = (functionName) => publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName }).catch((err) => {
866
+ if (revertErrorName(err, ACL_SERVED_ADDRESSES_ABI) === void 0)
867
+ transient = true;
868
+ return void 0;
869
+ });
847
870
  const [defaultRevoker, shareRegistry] = await Promise.all([
848
- publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: "defaultRevokerContract" }).catch(() => void 0),
849
- publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: "shareRegistry" }).catch(() => void 0)
871
+ readServedAddress("defaultRevokerContract"),
872
+ readServedAddress("shareRegistry")
850
873
  ]);
851
874
  const resolved = {
852
875
  defaultRevoker: defaultRevoker != null && defaultRevoker !== viem.zeroAddress ? defaultRevoker : void 0,
853
876
  shareRegistry: shareRegistry != null && shareRegistry !== viem.zeroAddress ? shareRegistry : void 0
854
877
  };
855
- aclServedAddressesCache.set(chainId, resolved);
878
+ if (!transient)
879
+ aclServedAddressesCache.set(chainId, resolved);
856
880
  return resolved;
857
881
  };
858
882
 
@@ -2106,19 +2130,22 @@ var zkProve = async (builder, crs, metadata) => {
2106
2130
  }, 0);
2107
2131
  });
2108
2132
  };
2109
- var constructZkPoKMetadata = (accountAddr, securityZone, chainId) => {
2133
+ var constructZkPoKMetadata = (accountAddr, securityZone, chainId, consumingContract) => {
2110
2134
  const accountAddrNoPrefix = accountAddr.startsWith("0x") ? accountAddr.slice(2) : accountAddr;
2111
2135
  const accountBytes = hexToBytes(accountAddrNoPrefix);
2136
+ const contractNoPrefix = consumingContract.startsWith("0x") ? consumingContract.slice(2) : consumingContract;
2137
+ const contractBytes = hexToBytes(contractNoPrefix);
2112
2138
  const chainIdBytes = new Uint8Array(32);
2113
2139
  let value = chainId;
2114
2140
  for (let i = 31; i >= 0 && value > 0; i--) {
2115
2141
  chainIdBytes[i] = value & 255;
2116
2142
  value = value >>> 8;
2117
2143
  }
2118
- const metadata = new Uint8Array(1 + accountBytes.length + 32);
2144
+ const metadata = new Uint8Array(1 + accountBytes.length + 32 + contractBytes.length);
2119
2145
  metadata[0] = securityZone;
2120
2146
  metadata.set(accountBytes, 1);
2121
2147
  metadata.set(chainIdBytes, 1 + accountBytes.length);
2148
+ metadata.set(contractBytes, 1 + accountBytes.length + 32);
2122
2149
  return metadata;
2123
2150
  };
2124
2151
  var zkVerifyBatch = async (verifierUrl, serializedBytes, address, securityZone, chainId, consumingContract) => {
@@ -3034,20 +3061,33 @@ var EncryptInputsBuilder = class extends BaseBuilder {
3034
3061
  return this.consumingContract;
3035
3062
  }
3036
3063
  /**
3037
- * Asserts that this.consumingContract is populated
3038
- * @throws {CofheError} If consumingContract is not set
3064
+ * Asserts that this.consumingContract is populated and is an address.
3065
+ * Runs before TFHE init, key fetching and proving, so a bad address costs
3066
+ * nothing: the contract is bound into the proof, and a proof built for a
3067
+ * non-address could only fail at the verifier, after the expensive step.
3068
+ * @throws {CofheError} If consumingContract is not set or is not an address
3039
3069
  */
3040
3070
  assertConsumingContract() {
3041
- if (this.consumingContract)
3042
- return;
3043
- throw new CofheError({
3044
- code: "CONSUMING_CONTRACT_UNINITIALIZED" /* ConsumingContractUninitialized */,
3045
- message: "Consuming contract is not set",
3046
- hint: "Use setConsumingContract(...) to set the contract that will consume the encrypted inputs.",
3047
- context: {
3048
- consumingContract: this.consumingContract
3049
- }
3050
- });
3071
+ if (!this.consumingContract) {
3072
+ throw new CofheError({
3073
+ code: "CONSUMING_CONTRACT_UNINITIALIZED" /* ConsumingContractUninitialized */,
3074
+ message: "Consuming contract is not set",
3075
+ hint: "Use setConsumingContract(...) to set the contract that will consume the encrypted inputs.",
3076
+ context: {
3077
+ consumingContract: this.consumingContract
3078
+ }
3079
+ });
3080
+ }
3081
+ if (!viem.isAddress(this.consumingContract, { strict: false })) {
3082
+ throw new CofheError({
3083
+ code: "CONSUMING_CONTRACT_INVALID" /* ConsumingContractInvalid */,
3084
+ message: "Consuming contract is not an address",
3085
+ hint: "setConsumingContract(...) takes the 20-byte address of the contract that will consume the encrypted inputs.",
3086
+ context: {
3087
+ consumingContract: this.consumingContract
3088
+ }
3089
+ });
3090
+ }
3051
3091
  }
3052
3092
  setUseWorker(useWorker) {
3053
3093
  this.useWorker = useWorker;
@@ -3263,7 +3303,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
3263
3303
  zkBuilder = zkPack(this.inputItems, zkBuilder);
3264
3304
  this.fireStepEnd("pack" /* Pack */);
3265
3305
  this.fireStepStart("prove" /* Prove */);
3266
- const metadata = constructZkPoKMetadata(this.account, this.securityZone, this.chainId);
3306
+ const metadata = constructZkPoKMetadata(this.account, this.securityZone, this.chainId, this.consumingContract);
3267
3307
  let proof = null;
3268
3308
  let usedWorker = false;
3269
3309
  let workerFailedError;
package/dist/core.d.cts CHANGED
@@ -1,9 +1,9 @@
1
- import { a as CofheConfig, c as CofheClientParams, b as CofheClient, d as CofheClientConnectionState, F as FheTypes } from './clientTypes-C0A9ji5O.cjs';
2
- export { A as AnyExternalHash, i as CofheClientACPs, C as CofheInputConfig, h as CofheInternalConfig, K as DecryptEndpoint, a4 as DecryptForTxBuilder, a5 as DecryptForTxResult, a3 as DecryptForViewBuilder, J as DecryptPollCallbackContext, G as DecryptPollCallbackFunction, a1 as EncryptInputsBuilder, a2 as EncryptInputsBuilderUnset, M as EncryptSetStateFn, W as EncryptStep, N as EncryptStepCallbackContext, S as Encryptable, p as EncryptableAddress, j as EncryptableBool, E as EncryptableItem, B as EncryptableToExternalHashMap, o as EncryptableUint128, l as EncryptableUint16, m as EncryptableUint32, n as EncryptableUint64, k as EncryptableUint8, q as EncryptedNumber, y as ExternalAddressHash, s as ExternalBoolHash, z as ExternalHashProof, D as ExternalItemHashes, x as ExternalUint128Hash, u as ExternalUint16Hash, v as ExternalUint32Hash, w as ExternalUint64Hash, t as ExternalUint8Hash, R as FheAllUTypes, Z as FheKeyDeserializer, r as FheTypeValue, Q as FheUintUTypes, H as HashPlusProofResult, I as IStorage, $ as KeysStorage, a0 as KeysStore, L as LiteralToPrimitive, P as Primitive, T as TfheInitializer, O as TfheThreadsSetting, U as UnsealedItem, a6 as ZkBuilderAndCrsGenerator, a7 as ZkProveWorkerFunction, a8 as ZkProveWorkerRequest, a9 as ZkProveWorkerResponse, f as assertNoRenamedConfigKeys, e as createCofheConfigBase, _ as createKeysStore, Y as fetchKeys, g as getCofheConfigItem, V as isEncryptableItem, X as isLastEncryptionStep, aa as zkProveWithWorker } from './clientTypes-C0A9ji5O.cjs';
1
+ import { a as CofheConfig, c as CofheClientParams, b as CofheClient, d as CofheClientConnectionState, F as FheTypes } from './clientTypes-C2b_qub5.cjs';
2
+ export { A as AnyExternalHash, i as CofheClientACPs, C as CofheInputConfig, h as CofheInternalConfig, K as DecryptEndpoint, a4 as DecryptForTxBuilder, a5 as DecryptForTxResult, a3 as DecryptForViewBuilder, J as DecryptPollCallbackContext, G as DecryptPollCallbackFunction, a1 as EncryptInputsBuilder, a2 as EncryptInputsBuilderUnset, M as EncryptSetStateFn, W as EncryptStep, N as EncryptStepCallbackContext, S as Encryptable, p as EncryptableAddress, j as EncryptableBool, E as EncryptableItem, B as EncryptableToExternalHashMap, o as EncryptableUint128, l as EncryptableUint16, m as EncryptableUint32, n as EncryptableUint64, k as EncryptableUint8, q as EncryptedNumber, y as ExternalAddressHash, s as ExternalBoolHash, z as ExternalHashProof, D as ExternalItemHashes, x as ExternalUint128Hash, u as ExternalUint16Hash, v as ExternalUint32Hash, w as ExternalUint64Hash, t as ExternalUint8Hash, R as FheAllUTypes, Z as FheKeyDeserializer, r as FheTypeValue, Q as FheUintUTypes, H as HashPlusProofResult, I as IStorage, $ as KeysStorage, a0 as KeysStore, L as LiteralToPrimitive, P as Primitive, T as TfheInitializer, O as TfheThreadsSetting, U as UnsealedItem, a6 as ZkBuilderAndCrsGenerator, a7 as ZkProveWorkerFunction, a8 as ZkProveWorkerRequest, a9 as ZkProveWorkerResponse, f as assertNoRenamedConfigKeys, e as createCofheConfigBase, _ as createKeysStore, Y as fetchKeys, g as getCofheConfigItem, V as isEncryptableItem, X as isLastEncryptionStep, aa as zkProveWithWorker } from './clientTypes-C2b_qub5.cjs';
3
3
  import { PublicClient, Address, Hex } from 'viem';
4
4
  import './types-C07FK-cL.cjs';
5
5
  import 'zod';
6
- import './onchain-utils-D9Z33IP7.cjs';
6
+ import './onchain-utils-CgOslubH.cjs';
7
7
  import 'zustand/vanilla';
8
8
 
9
9
  declare const InitialConnectStore: CofheClientConnectionState;
@@ -55,6 +55,7 @@ declare enum CofheErrorCode {
55
55
  AccountUninitialized = "ACCOUNT_UNINITIALIZED",
56
56
  ChainIdUninitialized = "CHAIN_ID_UNINITIALIZED",
57
57
  ConsumingContractUninitialized = "CONSUMING_CONTRACT_UNINITIALIZED",
58
+ ConsumingContractInvalid = "CONSUMING_CONTRACT_INVALID",
58
59
  SealOutputFailed = "SEAL_OUTPUT_FAILED",
59
60
  SealOutputReturnedNull = "SEAL_OUTPUT_RETURNED_NULL",
60
61
  InvalidUtype = "INVALID_UTYPE",
package/dist/core.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { a as CofheConfig, c as CofheClientParams, b as CofheClient, d as CofheClientConnectionState, F as FheTypes } from './clientTypes-CcU5WvdV.js';
2
- export { A as AnyExternalHash, i as CofheClientACPs, C as CofheInputConfig, h as CofheInternalConfig, K as DecryptEndpoint, a4 as DecryptForTxBuilder, a5 as DecryptForTxResult, a3 as DecryptForViewBuilder, J as DecryptPollCallbackContext, G as DecryptPollCallbackFunction, a1 as EncryptInputsBuilder, a2 as EncryptInputsBuilderUnset, M as EncryptSetStateFn, W as EncryptStep, N as EncryptStepCallbackContext, S as Encryptable, p as EncryptableAddress, j as EncryptableBool, E as EncryptableItem, B as EncryptableToExternalHashMap, o as EncryptableUint128, l as EncryptableUint16, m as EncryptableUint32, n as EncryptableUint64, k as EncryptableUint8, q as EncryptedNumber, y as ExternalAddressHash, s as ExternalBoolHash, z as ExternalHashProof, D as ExternalItemHashes, x as ExternalUint128Hash, u as ExternalUint16Hash, v as ExternalUint32Hash, w as ExternalUint64Hash, t as ExternalUint8Hash, R as FheAllUTypes, Z as FheKeyDeserializer, r as FheTypeValue, Q as FheUintUTypes, H as HashPlusProofResult, I as IStorage, $ as KeysStorage, a0 as KeysStore, L as LiteralToPrimitive, P as Primitive, T as TfheInitializer, O as TfheThreadsSetting, U as UnsealedItem, a6 as ZkBuilderAndCrsGenerator, a7 as ZkProveWorkerFunction, a8 as ZkProveWorkerRequest, a9 as ZkProveWorkerResponse, f as assertNoRenamedConfigKeys, e as createCofheConfigBase, _ as createKeysStore, Y as fetchKeys, g as getCofheConfigItem, V as isEncryptableItem, X as isLastEncryptionStep, aa as zkProveWithWorker } from './clientTypes-CcU5WvdV.js';
1
+ import { a as CofheConfig, c as CofheClientParams, b as CofheClient, d as CofheClientConnectionState, F as FheTypes } from './clientTypes-DEKYh0cw.js';
2
+ export { A as AnyExternalHash, i as CofheClientACPs, C as CofheInputConfig, h as CofheInternalConfig, K as DecryptEndpoint, a4 as DecryptForTxBuilder, a5 as DecryptForTxResult, a3 as DecryptForViewBuilder, J as DecryptPollCallbackContext, G as DecryptPollCallbackFunction, a1 as EncryptInputsBuilder, a2 as EncryptInputsBuilderUnset, M as EncryptSetStateFn, W as EncryptStep, N as EncryptStepCallbackContext, S as Encryptable, p as EncryptableAddress, j as EncryptableBool, E as EncryptableItem, B as EncryptableToExternalHashMap, o as EncryptableUint128, l as EncryptableUint16, m as EncryptableUint32, n as EncryptableUint64, k as EncryptableUint8, q as EncryptedNumber, y as ExternalAddressHash, s as ExternalBoolHash, z as ExternalHashProof, D as ExternalItemHashes, x as ExternalUint128Hash, u as ExternalUint16Hash, v as ExternalUint32Hash, w as ExternalUint64Hash, t as ExternalUint8Hash, R as FheAllUTypes, Z as FheKeyDeserializer, r as FheTypeValue, Q as FheUintUTypes, H as HashPlusProofResult, I as IStorage, $ as KeysStorage, a0 as KeysStore, L as LiteralToPrimitive, P as Primitive, T as TfheInitializer, O as TfheThreadsSetting, U as UnsealedItem, a6 as ZkBuilderAndCrsGenerator, a7 as ZkProveWorkerFunction, a8 as ZkProveWorkerRequest, a9 as ZkProveWorkerResponse, f as assertNoRenamedConfigKeys, e as createCofheConfigBase, _ as createKeysStore, Y as fetchKeys, g as getCofheConfigItem, V as isEncryptableItem, X as isLastEncryptionStep, aa as zkProveWithWorker } from './clientTypes-DEKYh0cw.js';
3
3
  import { PublicClient, Address, Hex } from 'viem';
4
4
  import './types-C07FK-cL.js';
5
5
  import 'zod';
6
- import './onchain-utils-D9Z33IP7.js';
6
+ import './onchain-utils-CgOslubH.js';
7
7
  import 'zustand/vanilla';
8
8
 
9
9
  declare const InitialConnectStore: CofheClientConnectionState;
@@ -55,6 +55,7 @@ declare enum CofheErrorCode {
55
55
  AccountUninitialized = "ACCOUNT_UNINITIALIZED",
56
56
  ChainIdUninitialized = "CHAIN_ID_UNINITIALIZED",
57
57
  ConsumingContractUninitialized = "CONSUMING_CONTRACT_UNINITIALIZED",
58
+ ConsumingContractInvalid = "CONSUMING_CONTRACT_INVALID",
58
59
  SealOutputFailed = "SEAL_OUTPUT_FAILED",
59
60
  SealOutputReturnedNull = "SEAL_OUTPUT_RETURNED_NULL",
60
61
  InvalidUtype = "INVALID_UTYPE",
package/dist/core.js CHANGED
@@ -1,5 +1,5 @@
1
- export { InitialConnectStore as CONNECT_STORE_DEFAULTS, DecryptForTxBuilder, DecryptForViewBuilder, EncryptInputsBuilder, assertNoRenamedConfigKeys, cofheFetch, createCofheClientBase, createCofheConfigBase, createKeysStore, fetchKeys, getCofheConfigItem, getCofheDebugInterceptors, setCofheDebugInterceptors, verifyDecryptResult, zkProveWithWorker } from './chunk-OL3DZN7A.js';
1
+ export { InitialConnectStore as CONNECT_STORE_DEFAULTS, DecryptForTxBuilder, DecryptForViewBuilder, EncryptInputsBuilder, assertNoRenamedConfigKeys, cofheFetch, createCofheClientBase, createCofheConfigBase, createKeysStore, fetchKeys, getCofheConfigItem, getCofheDebugInterceptors, setCofheDebugInterceptors, verifyDecryptResult, zkProveWithWorker } from './chunk-GKEJHZ52.js';
2
2
  import './chunk-UKQAJK4N.js';
3
- export { getTaskManagerAddress } from './chunk-BQWHPIYU.js';
4
- export { EncryptStep, Encryptable, FheAllUTypes, FheTypes, FheUintUTypes, fheTypeToString, isEncryptableItem, isLastEncryptionStep } from './chunk-6ZW76ZKB.js';
5
- export { COFHE_ADDRESS_BOOK_ADDRESS, CofheError, CofheErrorCode, MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_TASK_MANAGER_ADDRESS, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_ZK_VERIFIER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, TASK_MANAGER_ID, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, TFHE_RS_ZK_MAX_BITS, isCofheError } from './chunk-XQ32JG3T.js';
3
+ export { getTaskManagerAddress } from './chunk-WAA2U7CT.js';
4
+ export { EncryptStep, Encryptable, FheAllUTypes, FheTypes, FheUintUTypes, fheTypeToString, isEncryptableItem, isLastEncryptionStep } from './chunk-3SD2UCRE.js';
5
+ export { COFHE_ADDRESS_BOOK_ADDRESS, CofheError, CofheErrorCode, MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_TASK_MANAGER_ADDRESS, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_ZK_VERIFIER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, TASK_MANAGER_ID, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, TFHE_RS_ZK_MAX_BITS, isCofheError } from './chunk-OC5TGQGG.js';