@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/acps.cjs CHANGED
@@ -66,6 +66,100 @@ function isBigIntOrNumber(value) {
66
66
  }
67
67
  }
68
68
 
69
+ // core/error.ts
70
+ var CofheError = class _CofheError extends Error {
71
+ code;
72
+ cause;
73
+ hint;
74
+ context;
75
+ apiErrorCode;
76
+ constructor({ code, message, cause, hint, context, apiErrorCode }) {
77
+ const fullMessage = cause ? `${message} | Caused by: ${cause.message}` : message;
78
+ super(fullMessage);
79
+ this.name = "CofheError";
80
+ this.code = code;
81
+ this.cause = cause;
82
+ this.hint = hint;
83
+ this.context = context;
84
+ this.apiErrorCode = apiErrorCode;
85
+ if (Error.captureStackTrace) {
86
+ Error.captureStackTrace(this, _CofheError);
87
+ }
88
+ }
89
+ /**
90
+ * Creates a CofheError from an unknown error
91
+ * If the error is a CofheError, it is returned unchanged, else a new CofheError is created
92
+ * If a wrapperError is provided, it is used to create the new CofheError, else a default is used
93
+ */
94
+ static fromError(error, wrapperError) {
95
+ if (isCofheError(error))
96
+ return error;
97
+ const cause = error instanceof Error ? error : new Error(`${error}`);
98
+ return new _CofheError({
99
+ code: wrapperError?.code ?? "INTERNAL_ERROR" /* InternalError */,
100
+ message: wrapperError?.message ?? "An internal error occurred",
101
+ hint: wrapperError?.hint,
102
+ context: wrapperError?.context,
103
+ apiErrorCode: wrapperError?.apiErrorCode,
104
+ cause
105
+ });
106
+ }
107
+ /**
108
+ * Serializes the error to JSON string with proper handling of Error objects
109
+ */
110
+ serialize() {
111
+ return bigintSafeJsonStringify({
112
+ name: this.name,
113
+ code: this.code,
114
+ message: this.message,
115
+ hint: this.hint,
116
+ context: this.context,
117
+ apiErrorCode: this.apiErrorCode,
118
+ cause: this.cause ? {
119
+ name: this.cause.name,
120
+ message: this.cause.message,
121
+ stack: this.cause.stack
122
+ } : void 0,
123
+ stack: this.stack
124
+ });
125
+ }
126
+ /**
127
+ * Returns a human-readable string representation of the error
128
+ */
129
+ toString() {
130
+ const codeSuffix = this.apiErrorCode ? ` (api: ${this.apiErrorCode})` : "";
131
+ const parts = [`${this.name} [${this.code}]${codeSuffix}: ${this.message}`];
132
+ if (this.hint) {
133
+ parts.push(`Hint: ${this.hint}`);
134
+ }
135
+ if (this.context && Object.keys(this.context).length > 0) {
136
+ parts.push(`Context: ${bigintSafeJsonStringify(this.context)}`);
137
+ }
138
+ if (this.stack) {
139
+ parts.push(`
140
+ Stack trace:`);
141
+ parts.push(this.stack);
142
+ }
143
+ if (this.cause) {
144
+ parts.push(`
145
+ Caused by: ${this.cause.name}: ${this.cause.message}`);
146
+ if (this.cause.stack) {
147
+ parts.push(this.cause.stack);
148
+ }
149
+ }
150
+ return parts.join("\n");
151
+ }
152
+ };
153
+ var bigintSafeJsonStringify = (value) => {
154
+ return JSON.stringify(value, (key, value2) => {
155
+ if (typeof value2 === "bigint") {
156
+ return `${value2}n`;
157
+ }
158
+ return value2;
159
+ });
160
+ };
161
+ var isCofheError = (error) => error instanceof CofheError;
162
+
69
163
  // acps/sealing.ts
70
164
  var KEY_HEX_LENGTH = 64;
71
165
  var GenerateSealingKey = () => {
@@ -93,9 +187,25 @@ var unsealWithPrivateKey = (privateKey, parsedData) => {
93
187
  const nonce = parsedData.nonce instanceof Uint8Array ? parsedData.nonce : new Uint8Array(parsedData.nonce);
94
188
  const ephemPublicKey = parsedData.public_key instanceof Uint8Array ? parsedData.public_key : new Uint8Array(parsedData.public_key);
95
189
  const dataToDecrypt = parsedData.data instanceof Uint8Array ? parsedData.data : new Uint8Array(parsedData.data);
96
- const decryptedMessage = nacl__default.default.box.open(dataToDecrypt, nonce, ephemPublicKey, fromHexString(privateKey));
190
+ let decryptedMessage;
191
+ let cause;
192
+ try {
193
+ decryptedMessage = nacl__default.default.box.open(dataToDecrypt, nonce, ephemPublicKey, fromHexString(privateKey));
194
+ } catch (e) {
195
+ decryptedMessage = null;
196
+ cause = e instanceof Error ? e : void 0;
197
+ }
97
198
  if (!decryptedMessage) {
98
- throw new Error("Failed to decrypt message");
199
+ throw new CofheError({
200
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
201
+ message: "Failed to unseal decrypt response",
202
+ cause,
203
+ context: {
204
+ dataLength: dataToDecrypt.length,
205
+ nonceLength: nonce.length,
206
+ publicKeyLength: ephemPublicKey.length
207
+ }
208
+ });
99
209
  }
100
210
  return toBigInt(decryptedMessage);
101
211
  };
@@ -412,100 +522,6 @@ var COFHE_ADDRESS_BOOK_ADDRESS = "0xC0F4e00E531a2B086492Ae3DCC1515038307196b";
412
522
  var TASK_MANAGER_ID = 1n;
413
523
  BigInt(1 << 30);
414
524
 
415
- // core/error.ts
416
- var CofheError = class _CofheError extends Error {
417
- code;
418
- cause;
419
- hint;
420
- context;
421
- apiErrorCode;
422
- constructor({ code, message, cause, hint, context, apiErrorCode }) {
423
- const fullMessage = cause ? `${message} | Caused by: ${cause.message}` : message;
424
- super(fullMessage);
425
- this.name = "CofheError";
426
- this.code = code;
427
- this.cause = cause;
428
- this.hint = hint;
429
- this.context = context;
430
- this.apiErrorCode = apiErrorCode;
431
- if (Error.captureStackTrace) {
432
- Error.captureStackTrace(this, _CofheError);
433
- }
434
- }
435
- /**
436
- * Creates a CofheError from an unknown error
437
- * If the error is a CofheError, it is returned unchanged, else a new CofheError is created
438
- * If a wrapperError is provided, it is used to create the new CofheError, else a default is used
439
- */
440
- static fromError(error, wrapperError) {
441
- if (isCofheError(error))
442
- return error;
443
- const cause = error instanceof Error ? error : new Error(`${error}`);
444
- return new _CofheError({
445
- code: wrapperError?.code ?? "INTERNAL_ERROR" /* InternalError */,
446
- message: wrapperError?.message ?? "An internal error occurred",
447
- hint: wrapperError?.hint,
448
- context: wrapperError?.context,
449
- apiErrorCode: wrapperError?.apiErrorCode,
450
- cause
451
- });
452
- }
453
- /**
454
- * Serializes the error to JSON string with proper handling of Error objects
455
- */
456
- serialize() {
457
- return bigintSafeJsonStringify({
458
- name: this.name,
459
- code: this.code,
460
- message: this.message,
461
- hint: this.hint,
462
- context: this.context,
463
- apiErrorCode: this.apiErrorCode,
464
- cause: this.cause ? {
465
- name: this.cause.name,
466
- message: this.cause.message,
467
- stack: this.cause.stack
468
- } : void 0,
469
- stack: this.stack
470
- });
471
- }
472
- /**
473
- * Returns a human-readable string representation of the error
474
- */
475
- toString() {
476
- const codeSuffix = this.apiErrorCode ? ` (api: ${this.apiErrorCode})` : "";
477
- const parts = [`${this.name} [${this.code}]${codeSuffix}: ${this.message}`];
478
- if (this.hint) {
479
- parts.push(`Hint: ${this.hint}`);
480
- }
481
- if (this.context && Object.keys(this.context).length > 0) {
482
- parts.push(`Context: ${bigintSafeJsonStringify(this.context)}`);
483
- }
484
- if (this.stack) {
485
- parts.push(`
486
- Stack trace:`);
487
- parts.push(this.stack);
488
- }
489
- if (this.cause) {
490
- parts.push(`
491
- Caused by: ${this.cause.name}: ${this.cause.message}`);
492
- if (this.cause.stack) {
493
- parts.push(this.cause.stack);
494
- }
495
- }
496
- return parts.join("\n");
497
- }
498
- };
499
- var bigintSafeJsonStringify = (value) => {
500
- return JSON.stringify(value, (key, value2) => {
501
- if (typeof value2 === "bigint") {
502
- return `${value2}n`;
503
- }
504
- return value2;
505
- });
506
- };
507
- var isCofheError = (error) => error instanceof CofheError;
508
-
509
525
  // core/taskManager.ts
510
526
  var ADDRESS_BOOK_ABI = viem.parseAbi([
511
527
  "function getTm(uint256 id) view returns (address)",
@@ -813,15 +829,22 @@ var getAclServedAddresses = async (publicClient, chainId) => {
813
829
  } catch {
814
830
  return {};
815
831
  }
832
+ let transient = false;
833
+ const readServedAddress = (functionName) => publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName }).catch((err) => {
834
+ if (revertErrorName(err, ACL_SERVED_ADDRESSES_ABI) === void 0)
835
+ transient = true;
836
+ return void 0;
837
+ });
816
838
  const [defaultRevoker, shareRegistry] = await Promise.all([
817
- publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: "defaultRevokerContract" }).catch(() => void 0),
818
- publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: "shareRegistry" }).catch(() => void 0)
839
+ readServedAddress("defaultRevokerContract"),
840
+ readServedAddress("shareRegistry")
819
841
  ]);
820
842
  const resolved = {
821
843
  defaultRevoker: defaultRevoker != null && defaultRevoker !== viem.zeroAddress ? defaultRevoker : void 0,
822
844
  shareRegistry: shareRegistry != null && shareRegistry !== viem.zeroAddress ? shareRegistry : void 0
823
845
  };
824
- aclServedAddressesCache.set(chainId, resolved);
846
+ if (!transient)
847
+ aclServedAddressesCache.set(chainId, resolved);
825
848
  return resolved;
826
849
  };
827
850
 
package/dist/acps.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as ACP, S as ShareLabel, a as StoredValueLabel, E as EventValueLabel, L as LabelledShare, V as ValidationResult, b as ACPPublic, c as ACPSignaturePrimaryType, d as EIP712Types, e as EIP712Message, f as SerializedACP } from './onchain-utils-D9Z33IP7.cjs';
2
- export { O as ACPAccessStatus, P as ACPHashFields, h as ACPMetadata, H as ACPOf, D as ACPPrivate, M as ACPScope, N as ACPScopeOptions, F as ACPType, l as ACPUtils, p as AclServedAddresses, C as CreateSelfACPOptions, g as CreateSharingACPOptions, k as EIP712Domain, B as EIP712Type, r as EthEncryptedData, Q as Expand, G as GenerateSealingKey, I as ImportACPOptions, I as ImportSharedACPOptions, j as IncomingShare, v as LabelVerification, R as RecipientACP, q as SealingKeyPair, J as SelfACP, C as SelfACPOptions, x as ShareLabelCheck, t as ShareLabelReadArg, w as ShareLabelVerifyMode, i as SharedACP, K as SharingACP, g as SharingACPOptions, U as UnlabelledLabel, o as clearAclServedAddresses, m as getAclAddress, n as getAclServedAddresses, s as seal, u as unsealWithPrivateKey, y as verifyShareLabel, z as verifyShareLabels } from './onchain-utils-D9Z33IP7.cjs';
1
+ import { A as ACP, S as ShareLabel, a as StoredValueLabel, E as EventValueLabel, L as LabelledShare, V as ValidationResult, b as ACPPublic, c as ACPSignaturePrimaryType, d as EIP712Types, e as EIP712Message, f as SerializedACP } from './onchain-utils-CgOslubH.cjs';
2
+ export { O as ACPAccessStatus, P as ACPHashFields, h as ACPMetadata, H as ACPOf, D as ACPPrivate, M as ACPScope, N as ACPScopeOptions, F as ACPType, l as ACPUtils, p as AclServedAddresses, C as CreateSelfACPOptions, g as CreateSharingACPOptions, k as EIP712Domain, B as EIP712Type, r as EthEncryptedData, Q as Expand, G as GenerateSealingKey, I as ImportACPOptions, I as ImportSharedACPOptions, j as IncomingShare, v as LabelVerification, R as RecipientACP, q as SealingKeyPair, J as SelfACP, C as SelfACPOptions, x as ShareLabelCheck, t as ShareLabelReadArg, w as ShareLabelVerifyMode, i as SharedACP, K as SharingACP, g as SharingACPOptions, U as UnlabelledLabel, o as clearAclServedAddresses, m as getAclAddress, n as getAclServedAddresses, s as seal, u as unsealWithPrivateKey, y as verifyShareLabel, z as verifyShareLabels } from './onchain-utils-CgOslubH.cjs';
3
3
  import { Hex, AbiParameterToPrimitiveType, Address, PublicClient, Abi, ContractFunctionName, ContractFunctionArgs, Log } from 'viem';
4
4
  import { z } from 'zod';
5
5
  import * as zustand_middleware from 'zustand/middleware';
package/dist/acps.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as ACP, S as ShareLabel, a as StoredValueLabel, E as EventValueLabel, L as LabelledShare, V as ValidationResult, b as ACPPublic, c as ACPSignaturePrimaryType, d as EIP712Types, e as EIP712Message, f as SerializedACP } from './onchain-utils-D9Z33IP7.js';
2
- export { O as ACPAccessStatus, P as ACPHashFields, h as ACPMetadata, H as ACPOf, D as ACPPrivate, M as ACPScope, N as ACPScopeOptions, F as ACPType, l as ACPUtils, p as AclServedAddresses, C as CreateSelfACPOptions, g as CreateSharingACPOptions, k as EIP712Domain, B as EIP712Type, r as EthEncryptedData, Q as Expand, G as GenerateSealingKey, I as ImportACPOptions, I as ImportSharedACPOptions, j as IncomingShare, v as LabelVerification, R as RecipientACP, q as SealingKeyPair, J as SelfACP, C as SelfACPOptions, x as ShareLabelCheck, t as ShareLabelReadArg, w as ShareLabelVerifyMode, i as SharedACP, K as SharingACP, g as SharingACPOptions, U as UnlabelledLabel, o as clearAclServedAddresses, m as getAclAddress, n as getAclServedAddresses, s as seal, u as unsealWithPrivateKey, y as verifyShareLabel, z as verifyShareLabels } from './onchain-utils-D9Z33IP7.js';
1
+ import { A as ACP, S as ShareLabel, a as StoredValueLabel, E as EventValueLabel, L as LabelledShare, V as ValidationResult, b as ACPPublic, c as ACPSignaturePrimaryType, d as EIP712Types, e as EIP712Message, f as SerializedACP } from './onchain-utils-CgOslubH.js';
2
+ export { O as ACPAccessStatus, P as ACPHashFields, h as ACPMetadata, H as ACPOf, D as ACPPrivate, M as ACPScope, N as ACPScopeOptions, F as ACPType, l as ACPUtils, p as AclServedAddresses, C as CreateSelfACPOptions, g as CreateSharingACPOptions, k as EIP712Domain, B as EIP712Type, r as EthEncryptedData, Q as Expand, G as GenerateSealingKey, I as ImportACPOptions, I as ImportSharedACPOptions, j as IncomingShare, v as LabelVerification, R as RecipientACP, q as SealingKeyPair, J as SelfACP, C as SelfACPOptions, x as ShareLabelCheck, t as ShareLabelReadArg, w as ShareLabelVerifyMode, i as SharedACP, K as SharingACP, g as SharingACPOptions, U as UnlabelledLabel, o as clearAclServedAddresses, m as getAclAddress, n as getAclServedAddresses, s as seal, u as unsealWithPrivateKey, y as verifyShareLabel, z as verifyShareLabels } from './onchain-utils-CgOslubH.js';
3
3
  import { Hex, AbiParameterToPrimitiveType, Address, PublicClient, Abi, ContractFunctionName, ContractFunctionArgs, Log } from 'viem';
4
4
  import { z } from 'zod';
5
5
  import * as zustand_middleware from 'zustand/middleware';
package/dist/acps.js CHANGED
@@ -1,2 +1,2 @@
1
- export { ACPScope, ACPUtils, ACP_REVOKER_ABI, ACP_SHARE_REGISTRY_ABI, ACP_SHARE_TUPLE_ABI, ACP_STORE_DEFAULTS, ERC7984_ABI, GenerateSealingKey, ImportACPOptionsValidator, ImportACPValidator, LAYOUT_VERSION as SHARE_METADATA_VERSION, SelfACPOptionsValidator, SelfACPValidator, SharingACPOptionsValidator, SharingACPValidator, SignatureTypes, SignatureUtils, UNLABELLED, ValidationUtils, _acpStore, acpStore, addressNotZeroSchema, addressSchema, bytesNotEmptySchema, bytesSchema, clearAclServedAddresses, clearStaleStore, computeShareId, contractsSchema, decodeShareAppKey, decodeShareMetadata, decodeShareMetadataFull, describeShareLabels, describeShareMetadata, encodeShareMetadata, eventLogLabel, getACP, getACPs, getAclAddress, getAclServedAddresses, getActiveACP, getActiveACPHash, getSignatureTypesAndMessage, handlesSchema, readPostedShares, readShare, readSharesFor, removeACP, removeActiveACPHash, resetStore, seal, setACP, setActiveACPHash, shareAppKey, shareIdOfChainShare, toChainShare, unsealWithPrivateKey, validateImportACP, validateImportACPOptions, validateSelfACP, validateSelfACPOptions, validateSharingACP, validateSharingACPOptions, verifyShareLabel, verifyShareLabels, viewFunctionLabel } from './chunk-BQWHPIYU.js';
2
- import './chunk-XQ32JG3T.js';
1
+ export { ACPScope, ACPUtils, ACP_REVOKER_ABI, ACP_SHARE_REGISTRY_ABI, ACP_SHARE_TUPLE_ABI, ACP_STORE_DEFAULTS, ERC7984_ABI, GenerateSealingKey, ImportACPOptionsValidator, ImportACPValidator, LAYOUT_VERSION as SHARE_METADATA_VERSION, SelfACPOptionsValidator, SelfACPValidator, SharingACPOptionsValidator, SharingACPValidator, SignatureTypes, SignatureUtils, UNLABELLED, ValidationUtils, _acpStore, acpStore, addressNotZeroSchema, addressSchema, bytesNotEmptySchema, bytesSchema, clearAclServedAddresses, clearStaleStore, computeShareId, contractsSchema, decodeShareAppKey, decodeShareMetadata, decodeShareMetadataFull, describeShareLabels, describeShareMetadata, encodeShareMetadata, eventLogLabel, getACP, getACPs, getAclAddress, getAclServedAddresses, getActiveACP, getActiveACPHash, getSignatureTypesAndMessage, handlesSchema, readPostedShares, readShare, readSharesFor, removeACP, removeActiveACPHash, resetStore, seal, setACP, setActiveACPHash, shareAppKey, shareIdOfChainShare, toChainShare, unsealWithPrivateKey, validateImportACP, validateImportACPOptions, validateSelfACP, validateSelfACPOptions, validateSharingACP, validateSharingACPOptions, verifyShareLabel, verifyShareLabels, viewFunctionLabel } from './chunk-WAA2U7CT.js';
2
+ import './chunk-OC5TGQGG.js';
@@ -1,4 +1,4 @@
1
- import { CofheError } from './chunk-XQ32JG3T.js';
1
+ import { CofheError } from './chunk-OC5TGQGG.js';
2
2
  import 'viem';
3
3
 
4
4
  // core/types.ts
@@ -1,9 +1,9 @@
1
1
  import { hardhat as hardhat$1 } from './chunk-UKQAJK4N.js';
2
- import { acpStore, clearAclServedAddresses, getAclServedAddresses, computeShareId, ACPUtils, getTaskManagerAddress, verifyShareLabels, decodeShareMetadata, shareAppKey, ACP_SHARE_REGISTRY_ABI, readShare, readSharesFor, toChainShare, ACP_REVOKER_ABI, decodeShareAppKey, encodeShareMetadata } from './chunk-BQWHPIYU.js';
3
- import { sleep, getPublicClientChainID, getWalletClientAccount, validateBigIntInRange, toBigIntOrThrow, hexToBytes, toHexString, FheUintUTypes } from './chunk-6ZW76ZKB.js';
4
- import { TFHE_RS_KEY_VERSION, CofheError, TFHE_RS_ZK_MAX_BITS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, MOCKS_ZK_VERIFIER_ADDRESS } from './chunk-XQ32JG3T.js';
2
+ import { acpStore, clearAclServedAddresses, getAclServedAddresses, computeShareId, ACPUtils, getTaskManagerAddress, verifyShareLabels, decodeShareMetadata, shareAppKey, ACP_SHARE_REGISTRY_ABI, readShare, readSharesFor, toChainShare, ACP_REVOKER_ABI, decodeShareAppKey, encodeShareMetadata } from './chunk-WAA2U7CT.js';
3
+ import { sleep, getPublicClientChainID, getWalletClientAccount, validateBigIntInRange, toBigIntOrThrow, hexToBytes, toHexString, FheUintUTypes } from './chunk-3SD2UCRE.js';
4
+ import { TFHE_RS_KEY_VERSION, CofheError, TFHE_RS_ZK_MAX_BITS, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, MOCKS_ZK_VERIFIER_ADDRESS } from './chunk-OC5TGQGG.js';
5
5
  import { createStore } from 'zustand/vanilla';
6
- import { parseAbi, isAddressEqual, zeroAddress, recoverAddress, encodePacked, keccak256, createWalletClient, http, getAddress, parseSignature, serializeSignature } from 'viem';
6
+ import { parseAbi, isAddress, isAddressEqual, zeroAddress, recoverAddress, encodePacked, keccak256, createWalletClient, http, getAddress, parseSignature, serializeSignature } from 'viem';
7
7
  import { hardhat } from 'viem/chains';
8
8
  import { sign, privateKeyToAccount } from 'viem/accounts';
9
9
  import { z } from 'zod';
@@ -110,19 +110,22 @@ var zkProve = async (builder, crs, metadata) => {
110
110
  }, 0);
111
111
  });
112
112
  };
113
- var constructZkPoKMetadata = (accountAddr, securityZone, chainId) => {
113
+ var constructZkPoKMetadata = (accountAddr, securityZone, chainId, consumingContract) => {
114
114
  const accountAddrNoPrefix = accountAddr.startsWith("0x") ? accountAddr.slice(2) : accountAddr;
115
115
  const accountBytes = hexToBytes(accountAddrNoPrefix);
116
+ const contractNoPrefix = consumingContract.startsWith("0x") ? consumingContract.slice(2) : consumingContract;
117
+ const contractBytes = hexToBytes(contractNoPrefix);
116
118
  const chainIdBytes = new Uint8Array(32);
117
119
  let value = chainId;
118
120
  for (let i = 31; i >= 0 && value > 0; i--) {
119
121
  chainIdBytes[i] = value & 255;
120
122
  value = value >>> 8;
121
123
  }
122
- const metadata = new Uint8Array(1 + accountBytes.length + 32);
124
+ const metadata = new Uint8Array(1 + accountBytes.length + 32 + contractBytes.length);
123
125
  metadata[0] = securityZone;
124
126
  metadata.set(accountBytes, 1);
125
127
  metadata.set(chainIdBytes, 1 + accountBytes.length);
128
+ metadata.set(contractBytes, 1 + accountBytes.length + 32);
126
129
  return metadata;
127
130
  };
128
131
  var zkVerifyBatch = async (verifierUrl, serializedBytes, address, securityZone, chainId, consumingContract) => {
@@ -1002,20 +1005,33 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1002
1005
  return this.consumingContract;
1003
1006
  }
1004
1007
  /**
1005
- * Asserts that this.consumingContract is populated
1006
- * @throws {CofheError} If consumingContract is not set
1008
+ * Asserts that this.consumingContract is populated and is an address.
1009
+ * Runs before TFHE init, key fetching and proving, so a bad address costs
1010
+ * nothing: the contract is bound into the proof, and a proof built for a
1011
+ * non-address could only fail at the verifier, after the expensive step.
1012
+ * @throws {CofheError} If consumingContract is not set or is not an address
1007
1013
  */
1008
1014
  assertConsumingContract() {
1009
- if (this.consumingContract)
1010
- return;
1011
- throw new CofheError({
1012
- code: "CONSUMING_CONTRACT_UNINITIALIZED" /* ConsumingContractUninitialized */,
1013
- message: "Consuming contract is not set",
1014
- hint: "Use setConsumingContract(...) to set the contract that will consume the encrypted inputs.",
1015
- context: {
1016
- consumingContract: this.consumingContract
1017
- }
1018
- });
1015
+ if (!this.consumingContract) {
1016
+ throw new CofheError({
1017
+ code: "CONSUMING_CONTRACT_UNINITIALIZED" /* ConsumingContractUninitialized */,
1018
+ message: "Consuming contract is not set",
1019
+ hint: "Use setConsumingContract(...) to set the contract that will consume the encrypted inputs.",
1020
+ context: {
1021
+ consumingContract: this.consumingContract
1022
+ }
1023
+ });
1024
+ }
1025
+ if (!isAddress(this.consumingContract, { strict: false })) {
1026
+ throw new CofheError({
1027
+ code: "CONSUMING_CONTRACT_INVALID" /* ConsumingContractInvalid */,
1028
+ message: "Consuming contract is not an address",
1029
+ hint: "setConsumingContract(...) takes the 20-byte address of the contract that will consume the encrypted inputs.",
1030
+ context: {
1031
+ consumingContract: this.consumingContract
1032
+ }
1033
+ });
1034
+ }
1019
1035
  }
1020
1036
  setUseWorker(useWorker) {
1021
1037
  this.useWorker = useWorker;
@@ -1231,7 +1247,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1231
1247
  zkBuilder = zkPack(this.inputItems, zkBuilder);
1232
1248
  this.fireStepEnd("pack" /* Pack */);
1233
1249
  this.fireStepStart("prove" /* Prove */);
1234
- const metadata = constructZkPoKMetadata(this.account, this.securityZone, this.chainId);
1250
+ const metadata = constructZkPoKMetadata(this.account, this.securityZone, this.chainId, this.consumingContract);
1235
1251
  let proof = null;
1236
1252
  let usedWorker = false;
1237
1253
  let workerFailedError;
@@ -1,16 +1,3 @@
1
- // core/consts.ts
2
- var COFHE_ADDRESS_BOOK_ADDRESS = "0xC0F4e00E531a2B086492Ae3DCC1515038307196b";
3
- var TASK_MANAGER_ID = 1n;
4
- var MOCKS_TASK_MANAGER_ADDRESS = "0x0000000000000000000000000000000000005000";
5
- var MOCKS_ZK_VERIFIER_ADDRESS = "0x0000000000000000000000000000000000005001";
6
- var MOCKS_THRESHOLD_NETWORK_ADDRESS = "0x0000000000000000000000000000000000005002";
7
- var MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY = "0x6C8D7F768A6BB4AAFE85E8A2F5A9680355239C7E14646ED62B044E39DE154512";
8
- var MOCKS_ZK_VERIFIER_SIGNER_ADDRESS = "0x6E12D8C87503D4287c294f2Fdef96ACd9DFf6bd2";
9
- var MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY = "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d";
10
- var TFHE_RS_ZK_MAX_BITS = 2048;
11
- var TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT = BigInt(1 << 30);
12
- var TFHE_RS_KEY_VERSION = 2;
13
-
14
1
  // core/error.ts
15
2
  var CofheErrorCode = /* @__PURE__ */ ((CofheErrorCode2) => {
16
3
  CofheErrorCode2["InternalError"] = "INTERNAL_ERROR";
@@ -30,6 +17,7 @@ var CofheErrorCode = /* @__PURE__ */ ((CofheErrorCode2) => {
30
17
  CofheErrorCode2["AccountUninitialized"] = "ACCOUNT_UNINITIALIZED";
31
18
  CofheErrorCode2["ChainIdUninitialized"] = "CHAIN_ID_UNINITIALIZED";
32
19
  CofheErrorCode2["ConsumingContractUninitialized"] = "CONSUMING_CONTRACT_UNINITIALIZED";
20
+ CofheErrorCode2["ConsumingContractInvalid"] = "CONSUMING_CONTRACT_INVALID";
33
21
  CofheErrorCode2["SealOutputFailed"] = "SEAL_OUTPUT_FAILED";
34
22
  CofheErrorCode2["SealOutputReturnedNull"] = "SEAL_OUTPUT_RETURNED_NULL";
35
23
  CofheErrorCode2["InvalidUtype"] = "INVALID_UTYPE";
@@ -171,4 +159,17 @@ var bigintSafeJsonStringify = (value) => {
171
159
  };
172
160
  var isCofheError = (error) => error instanceof CofheError;
173
161
 
162
+ // core/consts.ts
163
+ var COFHE_ADDRESS_BOOK_ADDRESS = "0xC0F4e00E531a2B086492Ae3DCC1515038307196b";
164
+ var TASK_MANAGER_ID = 1n;
165
+ var MOCKS_TASK_MANAGER_ADDRESS = "0x0000000000000000000000000000000000005000";
166
+ var MOCKS_ZK_VERIFIER_ADDRESS = "0x0000000000000000000000000000000000005001";
167
+ var MOCKS_THRESHOLD_NETWORK_ADDRESS = "0x0000000000000000000000000000000000005002";
168
+ var MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY = "0x6C8D7F768A6BB4AAFE85E8A2F5A9680355239C7E14646ED62B044E39DE154512";
169
+ var MOCKS_ZK_VERIFIER_SIGNER_ADDRESS = "0x6E12D8C87503D4287c294f2Fdef96ACd9DFf6bd2";
170
+ var MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY = "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d";
171
+ var TFHE_RS_ZK_MAX_BITS = 2048;
172
+ var TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT = BigInt(1 << 30);
173
+ var TFHE_RS_KEY_VERSION = 2;
174
+
174
175
  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_KEY_VERSION, TFHE_RS_SAFE_SERIALIZATION_SIZE_LIMIT, TFHE_RS_ZK_MAX_BITS, isCofheError };
@@ -1,4 +1,4 @@
1
- import { TASK_MANAGER_ID, COFHE_ADDRESS_BOOK_ADDRESS, CofheError } from './chunk-XQ32JG3T.js';
1
+ import { CofheError, TASK_MANAGER_ID, COFHE_ADDRESS_BOOK_ADDRESS } from './chunk-OC5TGQGG.js';
2
2
  import { isAddress, getAddress, zeroAddress, isHex, parseAbi, keccak256, padHex, numberToHex, concatHex, toFunctionSelector, size, sliceHex, toHex, encodeAbiParameters, hexToBigInt, stringToHex, hexToNumber, toEventSignature, toFunctionSignature, decodeErrorResult, toEventSelector, decodeAbiParameters } from 'viem';
3
3
  import nacl from 'tweetnacl';
4
4
  import { z } from 'zod';
@@ -86,9 +86,25 @@ var unsealWithPrivateKey = (privateKey, parsedData) => {
86
86
  const nonce = parsedData.nonce instanceof Uint8Array ? parsedData.nonce : new Uint8Array(parsedData.nonce);
87
87
  const ephemPublicKey = parsedData.public_key instanceof Uint8Array ? parsedData.public_key : new Uint8Array(parsedData.public_key);
88
88
  const dataToDecrypt = parsedData.data instanceof Uint8Array ? parsedData.data : new Uint8Array(parsedData.data);
89
- const decryptedMessage = nacl.box.open(dataToDecrypt, nonce, ephemPublicKey, fromHexString(privateKey));
89
+ let decryptedMessage;
90
+ let cause;
91
+ try {
92
+ decryptedMessage = nacl.box.open(dataToDecrypt, nonce, ephemPublicKey, fromHexString(privateKey));
93
+ } catch (e) {
94
+ decryptedMessage = null;
95
+ cause = e instanceof Error ? e : void 0;
96
+ }
90
97
  if (!decryptedMessage) {
91
- throw new Error("Failed to decrypt message");
98
+ throw new CofheError({
99
+ code: "SEAL_OUTPUT_FAILED" /* SealOutputFailed */,
100
+ message: "Failed to unseal decrypt response",
101
+ cause,
102
+ context: {
103
+ dataLength: dataToDecrypt.length,
104
+ nonceLength: nonce.length,
105
+ publicKeyLength: ephemPublicKey.length
106
+ }
107
+ });
92
108
  }
93
109
  return toBigInt(decryptedMessage);
94
110
  };
@@ -705,15 +721,22 @@ var getAclServedAddresses = async (publicClient, chainId) => {
705
721
  } catch {
706
722
  return {};
707
723
  }
724
+ let transient = false;
725
+ const readServedAddress = (functionName) => publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName }).catch((err) => {
726
+ if (revertErrorName(err, ACL_SERVED_ADDRESSES_ABI) === void 0)
727
+ transient = true;
728
+ return void 0;
729
+ });
708
730
  const [defaultRevoker, shareRegistry] = await Promise.all([
709
- publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: "defaultRevokerContract" }).catch(() => void 0),
710
- publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: "shareRegistry" }).catch(() => void 0)
731
+ readServedAddress("defaultRevokerContract"),
732
+ readServedAddress("shareRegistry")
711
733
  ]);
712
734
  const resolved = {
713
735
  defaultRevoker: defaultRevoker != null && defaultRevoker !== zeroAddress ? defaultRevoker : void 0,
714
736
  shareRegistry: shareRegistry != null && shareRegistry !== zeroAddress ? shareRegistry : void 0
715
737
  };
716
- aclServedAddressesCache.set(chainId, resolved);
738
+ if (!transient)
739
+ aclServedAddressesCache.set(chainId, resolved);
717
740
  return resolved;
718
741
  };
719
742
 
@@ -1,7 +1,7 @@
1
1
  import { WalletClient, PublicClient, Hex } from 'viem';
2
2
  import { C as CofheChain } from './types-C07FK-cL.cjs';
3
3
  import { z } from 'zod';
4
- import { A as ACP, k as EIP712Domain, C as CreateSelfACPOptions, J as SelfACP, g as CreateSharingACPOptions, K as SharingACP, I as ImportSharedACPOptions, R as RecipientACP, P as ACPHashFields, f as SerializedACP, O as ACPAccessStatus, S as ShareLabel, j as IncomingShare, p as AclServedAddresses, L as LabelledShare, w as ShareLabelVerifyMode, x as ShareLabelCheck, l as ACPUtils } from './onchain-utils-D9Z33IP7.cjs';
4
+ import { A as ACP, k as EIP712Domain, C as CreateSelfACPOptions, J as SelfACP, g as CreateSharingACPOptions, K as SharingACP, I as ImportSharedACPOptions, R as RecipientACP, P as ACPHashFields, f as SerializedACP, O as ACPAccessStatus, S as ShareLabel, j as IncomingShare, p as AclServedAddresses, L as LabelledShare, w as ShareLabelVerifyMode, x as ShareLabelCheck, l as ACPUtils } from './onchain-utils-CgOslubH.cjs';
5
5
  import { StoreApi } from 'zustand/vanilla';
6
6
 
7
7
  type TfheInitializer = () => Promise<boolean>;
@@ -896,8 +896,11 @@ declare class EncryptInputsBuilder<T extends EncryptableItem[]> extends BaseBuil
896
896
  setConsumingContract(address: string): EncryptInputsBuilder<T>;
897
897
  getConsumingContract(): string | undefined;
898
898
  /**
899
- * Asserts that this.consumingContract is populated
900
- * @throws {CofheError} If consumingContract is not set
899
+ * Asserts that this.consumingContract is populated and is an address.
900
+ * Runs before TFHE init, key fetching and proving, so a bad address costs
901
+ * nothing: the contract is bound into the proof, and a proof built for a
902
+ * non-address could only fail at the verifier, after the expensive step.
903
+ * @throws {CofheError} If consumingContract is not set or is not an address
901
904
  */
902
905
  private assertConsumingContract;
903
906
  /**
@@ -1,7 +1,7 @@
1
1
  import { WalletClient, PublicClient, Hex } from 'viem';
2
2
  import { C as CofheChain } from './types-C07FK-cL.js';
3
3
  import { z } from 'zod';
4
- import { A as ACP, k as EIP712Domain, C as CreateSelfACPOptions, J as SelfACP, g as CreateSharingACPOptions, K as SharingACP, I as ImportSharedACPOptions, R as RecipientACP, P as ACPHashFields, f as SerializedACP, O as ACPAccessStatus, S as ShareLabel, j as IncomingShare, p as AclServedAddresses, L as LabelledShare, w as ShareLabelVerifyMode, x as ShareLabelCheck, l as ACPUtils } from './onchain-utils-D9Z33IP7.js';
4
+ import { A as ACP, k as EIP712Domain, C as CreateSelfACPOptions, J as SelfACP, g as CreateSharingACPOptions, K as SharingACP, I as ImportSharedACPOptions, R as RecipientACP, P as ACPHashFields, f as SerializedACP, O as ACPAccessStatus, S as ShareLabel, j as IncomingShare, p as AclServedAddresses, L as LabelledShare, w as ShareLabelVerifyMode, x as ShareLabelCheck, l as ACPUtils } from './onchain-utils-CgOslubH.js';
5
5
  import { StoreApi } from 'zustand/vanilla';
6
6
 
7
7
  type TfheInitializer = () => Promise<boolean>;
@@ -896,8 +896,11 @@ declare class EncryptInputsBuilder<T extends EncryptableItem[]> extends BaseBuil
896
896
  setConsumingContract(address: string): EncryptInputsBuilder<T>;
897
897
  getConsumingContract(): string | undefined;
898
898
  /**
899
- * Asserts that this.consumingContract is populated
900
- * @throws {CofheError} If consumingContract is not set
899
+ * Asserts that this.consumingContract is populated and is an address.
900
+ * Runs before TFHE init, key fetching and proving, so a bad address costs
901
+ * nothing: the contract is bound into the proof, and a proof built for a
902
+ * non-address could only fail at the verifier, after the expensive step.
903
+ * @throws {CofheError} If consumingContract is not set or is not an address
901
904
  */
902
905
  private assertConsumingContract;
903
906
  /**