@cofhe/sdk 0.7.1 → 1.0.0-alpha.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 (123) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/acps/acp.ts +35 -7
  3. package/acps/index.ts +28 -12
  4. package/acps/onchain-utils.ts +188 -49
  5. package/acps/registry.ts +231 -0
  6. package/acps/sealing.ts +9 -3
  7. package/acps/share-metadata/appKey.ts +8 -0
  8. package/acps/share-metadata/decode.ts +120 -0
  9. package/acps/share-metadata/describe.ts +198 -0
  10. package/acps/share-metadata/encode.ts +147 -0
  11. package/acps/share-metadata/erc7984.ts +26 -0
  12. package/acps/share-metadata/index.ts +9 -0
  13. package/acps/share-metadata/layout.ts +69 -0
  14. package/acps/share-metadata/presets.ts +116 -0
  15. package/acps/share-metadata/schema.ts +47 -0
  16. package/acps/share-metadata/test/codec.test.ts +140 -0
  17. package/acps/share-metadata/test/describe.test.ts +112 -0
  18. package/acps/share-metadata/test/fixtures.ts +157 -0
  19. package/acps/share-metadata/test/live.test.ts +56 -0
  20. package/acps/share-metadata/test/presets.test.ts +119 -0
  21. package/acps/share-metadata/test/verify.test.ts +144 -0
  22. package/acps/share-metadata/verify.ts +155 -0
  23. package/acps/store.ts +48 -18
  24. package/acps/test/acp.test.ts +102 -7
  25. package/acps/test/localstorage.test.ts +28 -1
  26. package/acps/test/onchainAccessStatus.test.ts +116 -0
  27. package/acps/test/registry.test.ts +144 -0
  28. package/acps/test/sealing.test.ts +23 -0
  29. package/acps/test/store.test.ts +71 -0
  30. package/acps/test/utils.test.ts +63 -0
  31. package/acps/test/validation.test.ts +0 -4
  32. package/acps/types.ts +59 -6
  33. package/acps/utils.ts +15 -2
  34. package/acps/validation.ts +3 -1
  35. package/chains/chains/arbitrum.ts +14 -0
  36. package/chains/chains/ethereum.ts +14 -0
  37. package/chains/index.ts +5 -1
  38. package/chains/test/chains.test.ts +24 -3
  39. package/core/acps.ts +164 -207
  40. package/core/client.ts +44 -13
  41. package/core/clientTypes.ts +50 -7
  42. package/core/config.ts +33 -1
  43. package/core/consts.ts +14 -2
  44. package/core/decrypt/apiError.ts +4 -1
  45. package/core/decrypt/verifyDecryptResult.ts +8 -4
  46. package/core/encrypt/cofheMocksZkVerifySign.ts +19 -2
  47. package/core/encrypt/encryptInputsBuilder.ts +6 -0
  48. package/core/encrypt/zkPackProveVerify.ts +7 -1
  49. package/core/error.ts +1 -0
  50. package/core/fetchKeys.ts +2 -2
  51. package/core/index.ts +9 -1
  52. package/core/keyStore.ts +23 -10
  53. package/core/taskManager.ts +48 -0
  54. package/core/test/acpDefaults.test.ts +108 -19
  55. package/core/test/acpStoreAccountCase.test.ts +80 -0
  56. package/core/test/acps.test.ts +128 -3
  57. package/core/test/apiError.test.ts +8 -0
  58. package/core/test/appKeyConfig.test.ts +94 -0
  59. package/core/test/client.test.ts +41 -0
  60. package/core/test/config.test.ts +24 -0
  61. package/core/test/decrypt.test.ts +11 -4
  62. package/core/test/decryptBuilders.test.ts +110 -2
  63. package/core/test/encryptInputsBuilder.test.ts +1 -1
  64. package/core/test/fetchKeys.test.ts +23 -2
  65. package/core/test/incomingShares.test.ts +84 -0
  66. package/core/test/keyStore.test.ts +18 -6
  67. package/core/test/mocksEncryptRange.test.ts +90 -0
  68. package/core/test/taskManager.test.ts +57 -0
  69. package/core/test/utils.test.ts +128 -0
  70. package/core/test/verifyDecryptResult.test.ts +51 -0
  71. package/core/types.ts +8 -0
  72. package/core/utils.ts +16 -9
  73. package/dist/acps.cjs +984 -64
  74. package/dist/acps.d.cts +589 -10
  75. package/dist/acps.d.ts +589 -10
  76. package/dist/acps.js +2 -2
  77. package/dist/chains.cjs +26 -0
  78. package/dist/chains.d.cts +45 -1
  79. package/dist/chains.d.ts +45 -1
  80. package/dist/chains.js +1 -1
  81. package/dist/chunk-6ZW76ZKB.js +228 -0
  82. package/dist/chunk-BQWHPIYU.js +1828 -0
  83. package/dist/chunk-KSOV5B4B.js +50 -0
  84. package/dist/{chunk-43USWPEH.js → chunk-OL3DZN7A.js} +159 -523
  85. package/dist/{chunk-N6IDQRRU.js → chunk-UKQAJK4N.js} +25 -1
  86. package/dist/chunk-XQ32JG3T.js +174 -0
  87. package/dist/{clientTypes-CYZjFznO.d.cts → clientTypes-C0A9ji5O.d.cts} +132 -29
  88. package/dist/{clientTypes-BN3nbzYM.d.ts → clientTypes-CcU5WvdV.d.ts} +132 -29
  89. package/dist/core.cjs +3269 -2626
  90. package/dist/core.d.cts +32 -8
  91. package/dist/core.d.ts +32 -8
  92. package/dist/core.js +5 -4
  93. package/dist/node.cjs +3074 -2436
  94. package/dist/node.d.cts +2 -2
  95. package/dist/node.d.ts +2 -2
  96. package/dist/node.js +20 -19
  97. package/dist/{acp-Wi6isVQI.d.cts → onchain-utils-D9Z33IP7.d.cts} +166 -12
  98. package/dist/{acp-Wi6isVQI.d.ts → onchain-utils-D9Z33IP7.d.ts} +166 -12
  99. package/dist/web.cjs +3204 -2493
  100. package/dist/web.d.cts +49 -3
  101. package/dist/web.d.ts +49 -3
  102. package/dist/web.js +52 -27
  103. package/dist/zkProve.worker.cjs +79 -18
  104. package/dist/zkProve.worker.js +24 -24
  105. package/node/index.ts +1 -10
  106. package/node/storage.ts +20 -9
  107. package/node/test/inherited.test.ts +5 -1
  108. package/node/test/storage-memory-fallback.test.ts +47 -0
  109. package/node/test/storage-permissions.test.ts +40 -0
  110. package/package.json +3 -1
  111. package/web/index.ts +101 -36
  112. package/web/test/countingZkProveWorker.ts +31 -0
  113. package/web/test/inherited.web.test.ts +5 -1
  114. package/web/test/mainThreadPool.web.test.ts +174 -0
  115. package/web/test/threadPoolBenchHelper.ts +134 -0
  116. package/web/test/threadPoolOff.web.test.ts +17 -0
  117. package/web/test/threadPoolOn.web.test.ts +80 -0
  118. package/web/test/workerInitRace.web.test.ts +79 -0
  119. package/web/tfheThreadPool.ts +140 -0
  120. package/web/workerManager.ts +4 -2
  121. package/web/zkProve.worker.ts +42 -26
  122. package/dist/chunk-ESMZCFJY.js +0 -12
  123. package/dist/chunk-Q7CBWGQX.js +0 -1029
@@ -1,391 +1,15 @@
1
- import { hardhat as hardhat$1 } from './chunk-N6IDQRRU.js';
2
- import { acpStore, ACPUtils } from './chunk-Q7CBWGQX.js';
3
- import { TFHE_RS_KEY_VERSION, TASK_MANAGER_ADDRESS, 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-ESMZCFJY.js';
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';
4
5
  import { createStore } from 'zustand/vanilla';
5
- import { parseAbi, isAddressEqual, zeroAddress, recoverAddress, keccak256, encodeAbiParameters, encodePacked, createWalletClient, http, getAddress, parseSignature, serializeSignature } from 'viem';
6
+ import { parseAbi, isAddressEqual, zeroAddress, recoverAddress, encodePacked, keccak256, createWalletClient, http, getAddress, parseSignature, serializeSignature } from 'viem';
6
7
  import { hardhat } from 'viem/chains';
7
8
  import { sign, privateKeyToAccount } from 'viem/accounts';
8
9
  import { z } from 'zod';
9
10
  import { persist, createJSONStorage } from 'zustand/middleware';
10
11
  import { produce } from 'immer';
11
12
 
12
- // core/error.ts
13
- var CofheErrorCode = /* @__PURE__ */ ((CofheErrorCode2) => {
14
- CofheErrorCode2["InternalError"] = "INTERNAL_ERROR";
15
- CofheErrorCode2["UnknownEnvironment"] = "UNKNOWN_ENVIRONMENT";
16
- CofheErrorCode2["InitTfheFailed"] = "INIT_TFHE_FAILED";
17
- CofheErrorCode2["InitViemFailed"] = "INIT_VIEM_FAILED";
18
- CofheErrorCode2["InitEthersFailed"] = "INIT_ETHERS_FAILED";
19
- CofheErrorCode2["NotConnected"] = "NOT_CONNECTED";
20
- CofheErrorCode2["MissingPublicClient"] = "MISSING_PUBLIC_CLIENT";
21
- CofheErrorCode2["MissingWalletClient"] = "MISSING_WALLET_CLIENT";
22
- CofheErrorCode2["MissingProviderParam"] = "MISSING_PROVIDER_PARAM";
23
- CofheErrorCode2["EmptySecurityZonesParam"] = "EMPTY_SECURITY_ZONES_PARAM";
24
- CofheErrorCode2["InvalidACPData"] = "INVALID_ACP_DATA";
25
- CofheErrorCode2["InvalidACPDomain"] = "INVALID_ACP_DOMAIN";
26
- CofheErrorCode2["ACPNotFound"] = "ACP_NOT_FOUND";
27
- CofheErrorCode2["CannotRemoveLastACP"] = "CANNOT_REMOVE_LAST_ACP";
28
- CofheErrorCode2["AccountUninitialized"] = "ACCOUNT_UNINITIALIZED";
29
- CofheErrorCode2["ChainIdUninitialized"] = "CHAIN_ID_UNINITIALIZED";
30
- CofheErrorCode2["ConsumingContractUninitialized"] = "CONSUMING_CONTRACT_UNINITIALIZED";
31
- CofheErrorCode2["SealOutputFailed"] = "SEAL_OUTPUT_FAILED";
32
- CofheErrorCode2["SealOutputReturnedNull"] = "SEAL_OUTPUT_RETURNED_NULL";
33
- CofheErrorCode2["InvalidUtype"] = "INVALID_UTYPE";
34
- CofheErrorCode2["DecryptFailed"] = "DECRYPT_FAILED";
35
- CofheErrorCode2["DecryptReturnedNull"] = "DECRYPT_RETURNED_NULL";
36
- CofheErrorCode2["ZkMocksInsertCtHashesFailed"] = "ZK_MOCKS_INSERT_CT_HASHES_FAILED";
37
- CofheErrorCode2["ZkMocksCalcCtHashesFailed"] = "ZK_MOCKS_CALC_CT_HASHES_FAILED";
38
- CofheErrorCode2["ZkMocksVerifySignFailed"] = "ZK_MOCKS_VERIFY_SIGN_FAILED";
39
- CofheErrorCode2["ZkMocksCreateProofSignatureFailed"] = "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED";
40
- CofheErrorCode2["ZkVerifyFailed"] = "ZK_VERIFY_FAILED";
41
- CofheErrorCode2["ZkPackFailed"] = "ZK_PACK_FAILED";
42
- CofheErrorCode2["ZkProveFailed"] = "ZK_PROVE_FAILED";
43
- CofheErrorCode2["EncryptRemainingInItems"] = "ENCRYPT_REMAINING_IN_ITEMS";
44
- CofheErrorCode2["ZkUninitialized"] = "ZK_UNINITIALIZED";
45
- CofheErrorCode2["ZkVerifierUrlUninitialized"] = "ZK_VERIFIER_URL_UNINITIALIZED";
46
- CofheErrorCode2["ThresholdNetworkUrlUninitialized"] = "THRESHOLD_NETWORK_URL_UNINITIALIZED";
47
- CofheErrorCode2["MissingConfig"] = "MISSING_CONFIG";
48
- CofheErrorCode2["UnsupportedChain"] = "UNSUPPORTED_CHAIN";
49
- CofheErrorCode2["MissingZkBuilderAndCrsGenerator"] = "MISSING_ZK_BUILDER_AND_CRS_GENERATOR";
50
- CofheErrorCode2["MissingTfhePublicKeyDeserializer"] = "MISSING_TFHE_PUBLIC_KEY_DESERIALIZER";
51
- CofheErrorCode2["MissingCompactPkeCrsDeserializer"] = "MISSING_COMPACT_PKE_CRS_DESERIALIZER";
52
- CofheErrorCode2["MissingFheKey"] = "MISSING_FHE_KEY";
53
- CofheErrorCode2["MissingCrs"] = "MISSING_CRS";
54
- CofheErrorCode2["FetchKeysFailed"] = "FETCH_KEYS_FAILED";
55
- CofheErrorCode2["PublicWalletGetChainIdFailed"] = "PUBLIC_WALLET_GET_CHAIN_ID_FAILED";
56
- CofheErrorCode2["PublicWalletGetAddressesFailed"] = "PUBLIC_WALLET_GET_ADDRESSES_FAILED";
57
- CofheErrorCode2["RehydrateKeysStoreFailed"] = "REHYDRATE_KEYS_STORE_FAILED";
58
- CofheErrorCode2["BadRequest"] = "BAD_REQUEST";
59
- CofheErrorCode2["UnknownChain"] = "UNKNOWN_CHAIN";
60
- CofheErrorCode2["ACPMalformed"] = "ACP_MALFORMED";
61
- CofheErrorCode2["ACPDenied"] = "ACP_DENIED";
62
- CofheErrorCode2["ACPExpired"] = "ACP_EXPIRED";
63
- CofheErrorCode2["ACPInvalid"] = "ACP_INVALID";
64
- CofheErrorCode2["ACPRevoked"] = "ACP_REVOKED";
65
- CofheErrorCode2["NotPubliclyAllowed"] = "NOT_PUBLICLY_ALLOWED";
66
- CofheErrorCode2["CtNotFound"] = "CT_NOT_FOUND";
67
- CofheErrorCode2["UnsupportedSecurityZone"] = "UNSUPPORTED_SECURITY_ZONE";
68
- CofheErrorCode2["UnsupportedType"] = "UNSUPPORTED_TYPE";
69
- CofheErrorCode2["SigningFailed"] = "SIGNING_FAILED";
70
- CofheErrorCode2["CtSourceError"] = "CT_SOURCE_ERROR";
71
- CofheErrorCode2["ACPVerifierError"] = "ACP_VERIFIER_ERROR";
72
- CofheErrorCode2["CtSourceTimeout"] = "CT_SOURCE_TIMEOUT";
73
- CofheErrorCode2["ACPVerifierTimeout"] = "ACP_VERIFIER_TIMEOUT";
74
- CofheErrorCode2["ACPRequired"] = "ACP_REQUIRED";
75
- CofheErrorCode2["SealFailed"] = "SEAL_FAILED";
76
- return CofheErrorCode2;
77
- })(CofheErrorCode || {});
78
- var CofheError = class _CofheError extends Error {
79
- code;
80
- cause;
81
- hint;
82
- context;
83
- apiErrorCode;
84
- constructor({ code, message, cause, hint, context, apiErrorCode }) {
85
- const fullMessage = cause ? `${message} | Caused by: ${cause.message}` : message;
86
- super(fullMessage);
87
- this.name = "CofheError";
88
- this.code = code;
89
- this.cause = cause;
90
- this.hint = hint;
91
- this.context = context;
92
- this.apiErrorCode = apiErrorCode;
93
- if (Error.captureStackTrace) {
94
- Error.captureStackTrace(this, _CofheError);
95
- }
96
- }
97
- /**
98
- * Creates a CofheError from an unknown error
99
- * If the error is a CofheError, it is returned unchanged, else a new CofheError is created
100
- * If a wrapperError is provided, it is used to create the new CofheError, else a default is used
101
- */
102
- static fromError(error, wrapperError) {
103
- if (isCofheError(error))
104
- return error;
105
- const cause = error instanceof Error ? error : new Error(`${error}`);
106
- return new _CofheError({
107
- code: wrapperError?.code ?? "INTERNAL_ERROR" /* InternalError */,
108
- message: wrapperError?.message ?? "An internal error occurred",
109
- hint: wrapperError?.hint,
110
- context: wrapperError?.context,
111
- apiErrorCode: wrapperError?.apiErrorCode,
112
- cause
113
- });
114
- }
115
- /**
116
- * Serializes the error to JSON string with proper handling of Error objects
117
- */
118
- serialize() {
119
- return bigintSafeJsonStringify({
120
- name: this.name,
121
- code: this.code,
122
- message: this.message,
123
- hint: this.hint,
124
- context: this.context,
125
- apiErrorCode: this.apiErrorCode,
126
- cause: this.cause ? {
127
- name: this.cause.name,
128
- message: this.cause.message,
129
- stack: this.cause.stack
130
- } : void 0,
131
- stack: this.stack
132
- });
133
- }
134
- /**
135
- * Returns a human-readable string representation of the error
136
- */
137
- toString() {
138
- const codeSuffix = this.apiErrorCode ? ` (api: ${this.apiErrorCode})` : "";
139
- const parts = [`${this.name} [${this.code}]${codeSuffix}: ${this.message}`];
140
- if (this.hint) {
141
- parts.push(`Hint: ${this.hint}`);
142
- }
143
- if (this.context && Object.keys(this.context).length > 0) {
144
- parts.push(`Context: ${bigintSafeJsonStringify(this.context)}`);
145
- }
146
- if (this.stack) {
147
- parts.push(`
148
- Stack trace:`);
149
- parts.push(this.stack);
150
- }
151
- if (this.cause) {
152
- parts.push(`
153
- Caused by: ${this.cause.name}: ${this.cause.message}`);
154
- if (this.cause.stack) {
155
- parts.push(this.cause.stack);
156
- }
157
- }
158
- return parts.join("\n");
159
- }
160
- };
161
- var bigintSafeJsonStringify = (value) => {
162
- return JSON.stringify(value, (key, value2) => {
163
- if (typeof value2 === "bigint") {
164
- return `${value2}n`;
165
- }
166
- return value2;
167
- });
168
- };
169
- var isCofheError = (error) => error instanceof CofheError;
170
-
171
- // core/types.ts
172
- var FheTypes = /* @__PURE__ */ ((FheTypes2) => {
173
- FheTypes2[FheTypes2["Bool"] = 0] = "Bool";
174
- FheTypes2[FheTypes2["Uint4"] = 1] = "Uint4";
175
- FheTypes2[FheTypes2["Uint8"] = 2] = "Uint8";
176
- FheTypes2[FheTypes2["Uint16"] = 3] = "Uint16";
177
- FheTypes2[FheTypes2["Uint32"] = 4] = "Uint32";
178
- FheTypes2[FheTypes2["Uint64"] = 5] = "Uint64";
179
- FheTypes2[FheTypes2["Uint128"] = 6] = "Uint128";
180
- FheTypes2[FheTypes2["Uint160"] = 7] = "Uint160";
181
- FheTypes2[FheTypes2["Uint256"] = 8] = "Uint256";
182
- FheTypes2[FheTypes2["Uint512"] = 9] = "Uint512";
183
- FheTypes2[FheTypes2["Uint1024"] = 10] = "Uint1024";
184
- FheTypes2[FheTypes2["Uint2048"] = 11] = "Uint2048";
185
- FheTypes2[FheTypes2["Uint2"] = 12] = "Uint2";
186
- FheTypes2[FheTypes2["Uint6"] = 13] = "Uint6";
187
- FheTypes2[FheTypes2["Uint10"] = 14] = "Uint10";
188
- FheTypes2[FheTypes2["Uint12"] = 15] = "Uint12";
189
- FheTypes2[FheTypes2["Uint14"] = 16] = "Uint14";
190
- FheTypes2[FheTypes2["Int2"] = 17] = "Int2";
191
- FheTypes2[FheTypes2["Int4"] = 18] = "Int4";
192
- FheTypes2[FheTypes2["Int6"] = 19] = "Int6";
193
- FheTypes2[FheTypes2["Int8"] = 20] = "Int8";
194
- FheTypes2[FheTypes2["Int10"] = 21] = "Int10";
195
- FheTypes2[FheTypes2["Int12"] = 22] = "Int12";
196
- FheTypes2[FheTypes2["Int14"] = 23] = "Int14";
197
- FheTypes2[FheTypes2["Int16"] = 24] = "Int16";
198
- FheTypes2[FheTypes2["Int32"] = 25] = "Int32";
199
- FheTypes2[FheTypes2["Int64"] = 26] = "Int64";
200
- FheTypes2[FheTypes2["Int128"] = 27] = "Int128";
201
- FheTypes2[FheTypes2["Int160"] = 28] = "Int160";
202
- FheTypes2[FheTypes2["Int256"] = 29] = "Int256";
203
- return FheTypes2;
204
- })(FheTypes || {});
205
- var FheUintUTypes = [
206
- 2 /* Uint8 */,
207
- 3 /* Uint16 */,
208
- 4 /* Uint32 */,
209
- 5 /* Uint64 */,
210
- 6 /* Uint128 */
211
- // [U256-DISABLED]
212
- // FheTypes.Uint256,
213
- ];
214
- var FheAllUTypes = [
215
- 0 /* Bool */,
216
- 2 /* Uint8 */,
217
- 3 /* Uint16 */,
218
- 4 /* Uint32 */,
219
- 5 /* Uint64 */,
220
- 6 /* Uint128 */,
221
- // [U256-DISABLED]
222
- // FheTypes.Uint256,
223
- 7 /* Uint160 */
224
- ];
225
- var EncryptableFactoriesImpl = {
226
- bool: (data, securityZone = 0) => ({ data, securityZone, utype: 0 /* Bool */ }),
227
- address: (data, securityZone = 0) => ({ data, securityZone, utype: 7 /* Uint160 */ }),
228
- uint8: (data, securityZone = 0) => ({ data, securityZone, utype: 2 /* Uint8 */ }),
229
- uint16: (data, securityZone = 0) => ({ data, securityZone, utype: 3 /* Uint16 */ }),
230
- uint32: (data, securityZone = 0) => ({ data, securityZone, utype: 4 /* Uint32 */ }),
231
- uint64: (data, securityZone = 0) => ({ data, securityZone, utype: 5 /* Uint64 */ }),
232
- uint128: (data, securityZone = 0) => ({ data, securityZone, utype: 6 /* Uint128 */ })
233
- // [U256-DISABLED]
234
- // uint256: (data: EncryptableUint256['data'], securityZone = 0) =>
235
- // ({ data, securityZone, utype: FheTypes.Uint256 }) as EncryptableUint256,
236
- };
237
- function createEncryptableByLiteral(type, data, securityZone = 0) {
238
- switch (type) {
239
- case "bool": {
240
- if (typeof data !== "boolean")
241
- throw new Error("Bool encryptable data must be boolean");
242
- return EncryptableFactoriesImpl.bool(data, securityZone);
243
- }
244
- case "address":
245
- case "uint8":
246
- case "uint16":
247
- case "uint32":
248
- case "uint64":
249
- case "uint128": {
250
- if (typeof data === "boolean")
251
- throw new Error("Uint encryptable data must be string or bigint");
252
- return EncryptableFactoriesImpl[type](data, securityZone);
253
- }
254
- default: {
255
- const _exhaustive = type;
256
- throw new Error(`Unsupported encryptable type: ${_exhaustive}`);
257
- }
258
- }
259
- }
260
- var Encryptable = {
261
- ...EncryptableFactoriesImpl,
262
- create: createEncryptableByLiteral
263
- };
264
- function isEncryptableItem(value) {
265
- return (
266
- // Is object and exists
267
- typeof value === "object" && value !== null && // Has securityZone
268
- "securityZone" in value && typeof value.securityZone === "number" && // Has utype
269
- "utype" in value && FheAllUTypes.includes(value.utype) && // Has data
270
- "data" in value && ["string", "number", "bigint", "boolean"].includes(typeof value.data)
271
- );
272
- }
273
- var EncryptStep = /* @__PURE__ */ ((EncryptStep2) => {
274
- EncryptStep2["InitTfhe"] = "initTfhe";
275
- EncryptStep2["FetchKeys"] = "fetchKeys";
276
- EncryptStep2["Pack"] = "pack";
277
- EncryptStep2["Prove"] = "prove";
278
- EncryptStep2["Verify"] = "verify";
279
- return EncryptStep2;
280
- })(EncryptStep || {});
281
- function isLastEncryptionStep(step) {
282
- return step === "verify" /* Verify */;
283
- }
284
- var toHexString = (bytes) => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
285
- var toBigIntOrThrow = (value) => {
286
- if (typeof value === "bigint") {
287
- return value;
288
- }
289
- try {
290
- return BigInt(value);
291
- } catch (error) {
292
- throw new Error("Invalid input: Unable to convert to bigint");
293
- }
294
- };
295
- var validateBigIntInRange = (value, max, min = 0n) => {
296
- if (typeof value !== "bigint") {
297
- throw new Error("Value must be of type bigint");
298
- }
299
- if (value > max || value < min) {
300
- throw new Error(`Value out of range: ${max} - ${min}, try a different uint type`);
301
- }
302
- };
303
- var hexToBytes = (hex) => {
304
- const bytes = new Uint8Array(hex.length / 2);
305
- for (let i = 0; i < hex.length; i += 2) {
306
- bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
307
- }
308
- return bytes;
309
- };
310
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
311
- async function getPublicClientChainID(publicClient) {
312
- let chainId = null;
313
- try {
314
- chainId = publicClient.chain?.id ?? await publicClient.getChainId();
315
- } catch (e) {
316
- throw new CofheError({
317
- code: "PUBLIC_WALLET_GET_CHAIN_ID_FAILED" /* PublicWalletGetChainIdFailed */,
318
- message: "getting chain ID from public client failed",
319
- cause: e instanceof Error ? e : void 0
320
- });
321
- }
322
- if (chainId === null) {
323
- throw new CofheError({
324
- code: "PUBLIC_WALLET_GET_CHAIN_ID_FAILED" /* PublicWalletGetChainIdFailed */,
325
- message: "chain ID from public client is null"
326
- });
327
- }
328
- return chainId;
329
- }
330
- async function getWalletClientAccount(walletClient) {
331
- let address;
332
- try {
333
- address = walletClient.account?.address;
334
- if (!address) {
335
- address = (await walletClient.getAddresses())?.[0];
336
- }
337
- } catch (e) {
338
- throw new CofheError({
339
- code: "PUBLIC_WALLET_GET_ADDRESSES_FAILED" /* PublicWalletGetAddressesFailed */,
340
- message: "getting address from wallet client failed",
341
- cause: e instanceof Error ? e : void 0
342
- });
343
- }
344
- if (!address) {
345
- throw new CofheError({
346
- code: "PUBLIC_WALLET_GET_ADDRESSES_FAILED" /* PublicWalletGetAddressesFailed */,
347
- message: "address from wallet client is null"
348
- });
349
- }
350
- return address;
351
- }
352
- function fheTypeToString(utype) {
353
- switch (utype) {
354
- case 0 /* Bool */:
355
- return "bool";
356
- case 1 /* Uint4 */:
357
- return "uint4";
358
- case 2 /* Uint8 */:
359
- return "uint8";
360
- case 3 /* Uint16 */:
361
- return "uint16";
362
- case 4 /* Uint32 */:
363
- return "uint32";
364
- case 5 /* Uint64 */:
365
- return "uint64";
366
- case 6 /* Uint128 */:
367
- return "uint128";
368
- case 7 /* Uint160 */:
369
- return "uint160";
370
- case 8 /* Uint256 */:
371
- return "uint256";
372
- case 9 /* Uint512 */:
373
- return "uint512";
374
- case 10 /* Uint1024 */:
375
- return "uint1024";
376
- case 11 /* Uint2048 */:
377
- return "uint2048";
378
- case 12 /* Uint2 */:
379
- return "uint2";
380
- case 13 /* Uint6 */:
381
- return "uint6";
382
- case 14 /* Uint10 */:
383
- return "uint10";
384
- default:
385
- throw new Error(`Unknown FheType: ${utype}`);
386
- }
387
- }
388
-
389
13
  // core/encrypt/zkPackProveVerify.ts
390
14
  var MAX_UINT8 = 255n;
391
15
  var MAX_UINT16 = 65535n;
@@ -674,26 +298,32 @@ async function cofheMocksCheckEncryptableBits(items) {
674
298
  break;
675
299
  }
676
300
  case 2 /* Uint8 */: {
301
+ validateBigIntInRange(toBigIntOrThrow(item.data), MAX_UINT8);
677
302
  totalBits += 8;
678
303
  break;
679
304
  }
680
305
  case 3 /* Uint16 */: {
306
+ validateBigIntInRange(toBigIntOrThrow(item.data), MAX_UINT16);
681
307
  totalBits += 16;
682
308
  break;
683
309
  }
684
310
  case 4 /* Uint32 */: {
311
+ validateBigIntInRange(toBigIntOrThrow(item.data), MAX_UINT32);
685
312
  totalBits += 32;
686
313
  break;
687
314
  }
688
315
  case 5 /* Uint64 */: {
316
+ validateBigIntInRange(toBigIntOrThrow(item.data), MAX_UINT64);
689
317
  totalBits += 64;
690
318
  break;
691
319
  }
692
320
  case 6 /* Uint128 */: {
321
+ validateBigIntInRange(toBigIntOrThrow(item.data), MAX_UINT128);
693
322
  totalBits += 128;
694
323
  break;
695
324
  }
696
325
  case 7 /* Uint160 */: {
326
+ validateBigIntInRange(toBigIntOrThrow(item.data), MAX_UINT160);
697
327
  totalBits += 160;
698
328
  break;
699
329
  }
@@ -862,11 +492,14 @@ var CofheConfigSchema = z.object({
862
492
  }).or(z.null()).default(null),
863
493
  /** Whether to use Web Workers for ZK proof generation (web platform only) */
864
494
  useWorkers: z.boolean().optional().default(true),
495
+ /** How many threads tfhe's rayon pool may use for ZK proof generation (web platform only) */
496
+ tfheThreads: z.union([z.number().int().positive(), z.literal("auto"), z.literal(false)]).optional().default("auto"),
865
497
  /** ACP acp defaults */
866
498
  acp: z.object({
867
499
  defaultRevoker: z.custom().optional(),
868
500
  defaultContractScopes: z.custom().optional(),
869
- sharingRegistry: z.custom().optional()
501
+ sharingRegistry: z.custom().optional(),
502
+ app: z.string().min(1).optional()
870
503
  }).optional().default({}),
871
504
  /** Mocks configs */
872
505
  mocks: z.object({
@@ -970,6 +603,9 @@ var DEFAULT_KEYS_STORE = {
970
603
  fhe: {},
971
604
  crs: {}
972
605
  };
606
+ function isSecurityZoneRecord(value) {
607
+ return value != null && typeof value === "object";
608
+ }
973
609
  function isStoreWithPersist(store) {
974
610
  return "persist" in store;
975
611
  }
@@ -984,10 +620,10 @@ function createKeysStore(storage) {
984
620
  const stored = keysStore.getState().fhe[chainId]?.[securityZone];
985
621
  return stored;
986
622
  };
987
- const getCrs = (chainId) => {
988
- if (chainId == null)
623
+ const getCrs = (chainId, securityZone = 0) => {
624
+ if (chainId == null || securityZone == null)
989
625
  return void 0;
990
- const stored = keysStore.getState().crs[chainId];
626
+ const stored = keysStore.getState().crs[chainId]?.[securityZone];
991
627
  return stored;
992
628
  };
993
629
  const setFheKey = (chainId, securityZone, key) => {
@@ -999,10 +635,12 @@ function createKeysStore(storage) {
999
635
  })
1000
636
  );
1001
637
  };
1002
- const setCrs = (chainId, crs) => {
638
+ const setCrs = (chainId, securityZone, crs) => {
1003
639
  keysStore.setState(
1004
640
  produce((state) => {
1005
- state.crs[chainId] = crs;
641
+ if (state.crs[chainId] == null)
642
+ state.crs[chainId] = {};
643
+ state.crs[chainId][securityZone] = crs;
1006
644
  })
1007
645
  );
1008
646
  };
@@ -1050,7 +688,13 @@ function createStoreWithPersit(storage) {
1050
688
  const currentZones = current.fhe[chainId] || {};
1051
689
  mergedFhe[chainId] = { ...persistedZones, ...currentZones };
1052
690
  }
1053
- const mergedCrs = { ...persisted.crs, ...current.crs };
691
+ const mergedCrs = {};
692
+ const allCrsChainIds = /* @__PURE__ */ new Set([...Object.keys(current.crs), ...Object.keys(persisted.crs)]);
693
+ for (const chainId of allCrsChainIds) {
694
+ const persistedZones = isSecurityZoneRecord(persisted.crs[chainId]) ? persisted.crs[chainId] : {};
695
+ const currentZones = isSecurityZoneRecord(current.crs[chainId]) ? current.crs[chainId] : {};
696
+ mergedCrs[chainId] = { ...persistedZones, ...currentZones };
697
+ }
1054
698
  return {
1055
699
  fhe: mergedFhe,
1056
700
  crs: mergedCrs
@@ -1112,7 +756,7 @@ var fetchFhePublicKey = async (coFheUrl, chainId, securityZone, tfhePublicKeyDes
1112
756
  return [pk_data, true];
1113
757
  };
1114
758
  var fetchCrs = async (coFheUrl, chainId, securityZone, compactPkeCrsDeserializer, keysStorage) => {
1115
- const storedKey = keysStorage?.getCrs(chainId);
759
+ const storedKey = keysStorage?.getCrs(chainId, securityZone);
1116
760
  const [storedKeyValid] = checkKeyValidity(storedKey, compactPkeCrsDeserializer);
1117
761
  if (storedKeyValid)
1118
762
  return [storedKey, false];
@@ -1139,7 +783,7 @@ var fetchCrs = async (coFheUrl, chainId, securityZone, compactPkeCrsDeserializer
1139
783
  console.error(`Error serializing CRS ${err}`);
1140
784
  throw new Error(`Error serializing CRS; ${err}`);
1141
785
  }
1142
- keysStorage?.setCrs(chainId, crs_data);
786
+ keysStorage?.setCrs(chainId, securityZone, crs_data);
1143
787
  return [crs_data, true];
1144
788
  };
1145
789
  var fetchKeys = async (config, chainId, securityZone = 0, tfhePublicKeyDeserializer, compactPkeCrsDeserializer, keysStorage) => {
@@ -1251,6 +895,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1251
895
  zkBuilderAndCrsGenerator;
1252
896
  initTfhe;
1253
897
  zkProveWorkerFn;
898
+ beforeMainThreadProve;
1254
899
  keysStorage;
1255
900
  // Worker configuration (from config, overrideable)
1256
901
  useWorker;
@@ -1308,6 +953,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1308
953
  this.zkBuilderAndCrsGenerator = params.zkBuilderAndCrsGenerator;
1309
954
  this.initTfhe = params.initTfhe;
1310
955
  this.zkProveWorkerFn = params.zkProveWorkerFn;
956
+ this.beforeMainThreadProve = params.beforeMainThreadProve;
1311
957
  this.keysStorage = params.keysStorage;
1312
958
  this.useWorker = params.config?.useWorkers ?? true;
1313
959
  }
@@ -1598,6 +1244,7 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1598
1244
  }
1599
1245
  }
1600
1246
  if (proof == null) {
1247
+ await this.beforeMainThreadProve?.();
1601
1248
  proof = await zkProve(zkBuilder, zkCrs, metadata);
1602
1249
  usedWorker = false;
1603
1250
  }
@@ -1655,11 +1302,6 @@ var EncryptInputsBuilder = class extends BaseBuilder {
1655
1302
  return this.buildBatchResult(result);
1656
1303
  }
1657
1304
  };
1658
- var ACP_VALIDATOR_ABI = parseAbi([
1659
- "function revokeSingle(uint256 id)",
1660
- "function revokeAllExisting()",
1661
- "function disabled(address issuer, uint256 id) view returns (bool)"
1662
- ]);
1663
1305
  var storeACP = async (acp, publicClient, walletClient) => {
1664
1306
  const chainId = await publicClient.getChainId();
1665
1307
  const account = walletClient.account.address;
@@ -1686,8 +1328,14 @@ var createSelf = async (options, publicClient, walletClient) => {
1686
1328
  var createSharing = async (options, publicClient, walletClient) => {
1687
1329
  return createACPWithSign(options, publicClient, walletClient, ACPUtils.createSharingAndSign, false);
1688
1330
  };
1689
- var importShared = async (options, publicClient, walletClient) => {
1690
- return createACPWithSign(options, publicClient, walletClient, ACPUtils.importSharedAndSign);
1331
+ var importShared = async (options, publicClient, walletClient, { activate = true, name } = {}) => {
1332
+ return createACPWithSign(
1333
+ options,
1334
+ publicClient,
1335
+ walletClient,
1336
+ (o, pc, wc) => ACPUtils.importSharedAndSign(o, pc, wc, { name }),
1337
+ activate
1338
+ );
1691
1339
  };
1692
1340
  var getHash = (acp) => {
1693
1341
  return ACPUtils.getHash(acp);
@@ -1734,13 +1382,15 @@ var getOrCreateSharingACP = async (publicClient, walletClient, options, chainId,
1734
1382
  }
1735
1383
  return createSharing(options, publicClient, walletClient);
1736
1384
  };
1737
- var applyACPDefaults = (options, acpConfig, chainId) => {
1385
+ var applyACPDefaultsFromChain = async (options, acpConfig, publicClient, chainId) => {
1738
1386
  const result = { ...options };
1739
- const defaultRevoker = acpConfig?.defaultRevoker?.[chainId];
1740
- const hasValidatorOptions = options.revokerData != null || options.revokerContract != null;
1741
- if (defaultRevoker != null && !hasValidatorOptions) {
1742
- result.revokerContract = defaultRevoker;
1743
- result.revokerData = Math.round(Date.now() / 1e3) - 60;
1387
+ const hasRevokerOptions = options.revokerData != null || options.revokerContract != null;
1388
+ if (!hasRevokerOptions) {
1389
+ const defaultRevoker = acpConfig?.defaultRevoker?.[chainId] ?? (await getAclServedAddresses(publicClient, chainId)).defaultRevoker;
1390
+ if (defaultRevoker != null) {
1391
+ result.revokerContract = defaultRevoker;
1392
+ result.revokerData = await getBlockRevokerData(publicClient);
1393
+ }
1744
1394
  }
1745
1395
  const defaultContracts = acpConfig?.defaultContractScopes?.[chainId];
1746
1396
  const hasScopeOptions = options.scope != null || options.contracts != null || options.handles != null;
@@ -1749,45 +1399,15 @@ var applyACPDefaults = (options, acpConfig, chainId) => {
1749
1399
  }
1750
1400
  return result;
1751
1401
  };
1752
- var ACL_SERVED_ADDRESSES_ABI = parseAbi([
1753
- "function acl() view returns (address)",
1754
- "function defaultRevokerContract() view returns (address)",
1755
- "function shareRegistry() view returns (address)"
1756
- ]);
1757
- var aclServedAddressesCache = /* @__PURE__ */ new Map();
1758
- var clearAclServedAddresses = () => aclServedAddressesCache.clear();
1759
- var getAclServedAddresses = async (publicClient, chainId) => {
1760
- const cached = aclServedAddressesCache.get(chainId);
1761
- if (cached != null)
1762
- return cached;
1763
- let aclAddress;
1764
- try {
1765
- aclAddress = await publicClient.readContract({
1766
- address: TASK_MANAGER_ADDRESS,
1767
- abi: ACL_SERVED_ADDRESSES_ABI,
1768
- functionName: "acl"
1769
- });
1770
- } catch {
1771
- return {};
1402
+ var getBlockRevokerData = async (publicClient) => {
1403
+ const block = await publicClient.getBlock();
1404
+ const revokerData = Number(block.timestamp);
1405
+ if (!Number.isSafeInteger(revokerData)) {
1406
+ throw new Error(
1407
+ `ACP revokerData cannot represent the chain block timestamp ${block.timestamp.toString()} as a safe integer`
1408
+ );
1772
1409
  }
1773
- const [defaultRevoker, shareRegistry] = await Promise.all([
1774
- publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: "defaultRevokerContract" }).catch(() => void 0),
1775
- publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: "shareRegistry" }).catch(() => void 0)
1776
- ]);
1777
- const resolved = {
1778
- defaultRevoker: defaultRevoker != null && defaultRevoker !== zeroAddress ? defaultRevoker : void 0,
1779
- shareRegistry: shareRegistry != null && shareRegistry !== zeroAddress ? shareRegistry : void 0
1780
- };
1781
- aclServedAddressesCache.set(chainId, resolved);
1782
- return resolved;
1783
- };
1784
- var applyACPDefaultsFromChain = async (options, acpConfig, publicClient, chainId) => {
1785
- const hasExplicitRevoker = acpConfig?.defaultRevoker?.[chainId] != null || options.revokerData != null || options.revokerContract != null;
1786
- if (hasExplicitRevoker)
1787
- return applyACPDefaults(options, acpConfig, chainId);
1788
- const served = await getAclServedAddresses(publicClient, chainId);
1789
- const effectiveConfig = served.defaultRevoker != null ? { ...acpConfig, defaultRevoker: { ...acpConfig?.defaultRevoker, [chainId]: served.defaultRevoker } } : acpConfig;
1790
- return applyACPDefaults(options, effectiveConfig, chainId);
1410
+ return revokerData;
1791
1411
  };
1792
1412
  var revokeACP = async (acp, walletClient) => {
1793
1413
  if (acp.revokerContract === zeroAddress || acp.revokerData === 0) {
@@ -1800,7 +1420,7 @@ var revokeACP = async (acp, walletClient) => {
1800
1420
  }
1801
1421
  return walletClient.writeContract({
1802
1422
  address: acp.revokerContract,
1803
- abi: ACP_VALIDATOR_ABI,
1423
+ abi: ACP_REVOKER_ABI,
1804
1424
  functionName: "revokeSingle",
1805
1425
  args: [BigInt(acp.revokerData)],
1806
1426
  account: walletClient.account,
@@ -1821,65 +1441,42 @@ var revokeAllACPs = async (walletClient, publicClient, revokerContract) => {
1821
1441
  }
1822
1442
  return walletClient.writeContract({
1823
1443
  address: revoker,
1824
- abi: ACP_VALIDATOR_ABI,
1444
+ abi: ACP_REVOKER_ABI,
1825
1445
  functionName: "revokeAllExisting",
1826
1446
  args: [],
1827
1447
  account: walletClient.account,
1828
1448
  chain: walletClient.chain
1829
1449
  });
1830
1450
  };
1451
+ var checkAccess = async (acp, publicClient, handle) => {
1452
+ if (acp.type === "sharing" && handle === void 0) {
1453
+ if (ACPUtils.isExpired(acp))
1454
+ return "expired";
1455
+ return await isACPRevoked(acp, publicClient) ? "revoked" : "valid";
1456
+ }
1457
+ return ACPUtils.checkAccessOnChain(acp, publicClient, handle);
1458
+ };
1831
1459
  var isACPRevoked = async (acp, publicClient) => {
1832
1460
  if (acp.revokerContract === zeroAddress || acp.revokerData === 0)
1833
1461
  return false;
1834
1462
  return publicClient.readContract({
1835
1463
  address: acp.revokerContract,
1836
- abi: ACP_VALIDATOR_ABI,
1464
+ abi: ACP_REVOKER_ABI,
1837
1465
  functionName: "disabled",
1838
1466
  args: [acp.issuer, BigInt(acp.revokerData)]
1839
1467
  });
1840
1468
  };
1841
- var ACP_SHARE_REGISTRY_ABI = parseAbi([
1842
- "struct ACP { address issuer; uint64 expiration; address recipient; uint256 revokerData; address revokerContract; uint8 scope; address[] contracts; bytes32[] handles; bytes32 sealingKey; bytes issuerSignature; bytes recipientSignature; }",
1843
- "function share(ACP calldata acp) external returns (bytes32)",
1844
- "function removeShare(bytes32 shareId) external",
1845
- "function sharesFor(address recipient) external view returns (ACP[] memory)",
1846
- "function getShare(bytes32 shareId) external view returns (ACP memory)",
1847
- "function isShareValid(bytes32 shareId) external view returns (bool)"
1848
- ]);
1849
- var ACP_TUPLE = [
1850
- {
1851
- type: "tuple",
1852
- components: [
1853
- { name: "issuer", type: "address" },
1854
- { name: "expiration", type: "uint64" },
1855
- { name: "recipient", type: "address" },
1856
- { name: "revokerData", type: "uint256" },
1857
- { name: "revokerContract", type: "address" },
1858
- { name: "scope", type: "uint8" },
1859
- { name: "contracts", type: "address[]" },
1860
- { name: "handles", type: "bytes32[]" },
1861
- { name: "sealingKey", type: "bytes32" },
1862
- { name: "issuerSignature", type: "bytes" },
1863
- { name: "recipientSignature", type: "bytes" }
1864
- ]
1865
- }
1866
- ];
1867
- var ZERO_BYTES32 = `0x${"0".repeat(64)}`;
1868
- var toChainShare = (acp) => {
1869
- const pub = ACPUtils.getPublic(acp, true);
1870
- return {
1871
- ...pub,
1872
- expiration: BigInt(pub.expiration),
1873
- revokerData: BigInt(pub.revokerData),
1874
- sealingKey: ZERO_BYTES32,
1875
- recipientSignature: "0x"
1876
- };
1877
- };
1878
- var computeShareId = (acp) => {
1879
- const p = toChainShare(acp);
1880
- return keccak256(encodeAbiParameters(ACP_TUPLE, [p]));
1469
+ var metadataOf = (acp, { labels, metadata, appKey }) => {
1470
+ if (labels != null && metadata != null)
1471
+ throw new Error("Pass either labels or metadata, not both");
1472
+ if (labels == null)
1473
+ return metadata ?? acp.metadata ?? "0x";
1474
+ if (labels.length !== acp.handles.length) {
1475
+ throw new Error(`Cannot label a share of ${acp.handles.length} handles with ${labels.length} labels`);
1476
+ }
1477
+ return encodeShareMetadata(labels, { issuer: acp.issuer, appKey });
1881
1478
  };
1882
- var shareOnChain = async (acp, walletClient, registry) => {
1479
+ var shareOnChain = async (acp, walletClient, registry, options = {}) => {
1883
1480
  if (acp.type !== "sharing") {
1884
1481
  throw new Error(`Cannot share a '${acp.type}' ACP on-chain \u2014 only 'sharing' ACPs are shareable.`);
1885
1482
  }
@@ -1891,39 +1488,49 @@ var shareOnChain = async (acp, walletClient, registry) => {
1891
1488
  if (walletClient.account.address.toLowerCase() !== acp.issuer.toLowerCase()) {
1892
1489
  throw new Error("Only the ACP issuer can share it on-chain");
1893
1490
  }
1491
+ const metadata = metadataOf(acp, options);
1894
1492
  const txHash = await walletClient.writeContract({
1895
1493
  address: registry,
1896
1494
  abi: ACP_SHARE_REGISTRY_ABI,
1897
1495
  functionName: "share",
1898
- args: [toChainShare(acp)],
1496
+ args: [toChainShare(acp), metadata],
1899
1497
  account: walletClient.account,
1900
1498
  chain: walletClient.chain ?? null
1901
1499
  });
1902
1500
  return { txHash, shareId: computeShareId(acp) };
1903
1501
  };
1904
- var getIncomingShares = async (publicClient, registry, recipient) => {
1905
- const raw = await publicClient.readContract({
1906
- address: registry,
1907
- abi: ACP_SHARE_REGISTRY_ABI,
1908
- functionName: "sharesFor",
1909
- args: [recipient]
1910
- });
1911
- return raw.map((s) => ({
1912
- shareId: keccak256(encodeAbiParameters(ACP_TUPLE, [s])),
1913
- issuer: s.issuer,
1914
- expiration: Number(s.expiration),
1915
- recipient: s.recipient,
1916
- revokerData: Number(s.revokerData),
1917
- revokerContract: s.revokerContract,
1918
- scope: Number(s.scope),
1919
- contracts: [...s.contracts],
1920
- handles: [...s.handles],
1921
- issuerSignature: s.issuerSignature
1922
- }));
1502
+ var toIncomingShare = ({ shareId, share: s, metadata }) => ({
1503
+ shareId,
1504
+ issuer: s.issuer,
1505
+ expiration: Number(s.expiration),
1506
+ recipient: s.recipient,
1507
+ revokerData: Number(s.revokerData),
1508
+ revokerContract: s.revokerContract,
1509
+ scope: Number(s.scope),
1510
+ contracts: [...s.contracts],
1511
+ handles: [...s.handles],
1512
+ issuerSignature: s.issuerSignature,
1513
+ metadata,
1514
+ ...appKeyOf(metadata, s.handles) && { appKey: appKeyOf(metadata, s.handles) }
1515
+ });
1516
+ var appKeyOf = (metadata, handles) => {
1517
+ try {
1518
+ return decodeShareAppKey(metadata, handles);
1519
+ } catch {
1520
+ return void 0;
1521
+ }
1522
+ };
1523
+ var getIncomingShares = async (publicClient, registry, recipient, { appKey } = {}) => {
1524
+ const shares = (await readSharesFor(publicClient, registry, recipient)).posted.map(toIncomingShare);
1525
+ return appKey == null ? shares : shares.filter((share) => share.appKey === appKey);
1923
1526
  };
1924
- var importFromChain = async (share, publicClient, walletClient) => {
1925
- const { shareId: _shareId, ...options } = share;
1926
- return importShared({ ...options, type: "sharing" }, publicClient, walletClient);
1527
+ var getShareFromChain = async (publicClient, registry, shareId) => {
1528
+ const posted = await readShare(publicClient, registry, shareId);
1529
+ return posted && toIncomingShare(posted);
1530
+ };
1531
+ var importFromChain = async (share, publicClient, walletClient, importOptions = {}) => {
1532
+ const { shareId: _shareId, appKey: _appKey, ...options } = share;
1533
+ return importShared({ ...options, type: "sharing" }, publicClient, walletClient, importOptions);
1927
1534
  };
1928
1535
  var removeShareOnChain = async (shareId, walletClient, registry) => {
1929
1536
  if (walletClient.account == null)
@@ -1961,12 +1568,13 @@ var acps = {
1961
1568
  revokeACP,
1962
1569
  revokeAllACPs,
1963
1570
  isACPRevoked,
1571
+ checkAccess,
1964
1572
  shareOnChain,
1965
1573
  getIncomingShares,
1574
+ getShareFromChain,
1966
1575
  importFromChain,
1967
1576
  removeShareOnChain,
1968
1577
  computeShareId,
1969
- applyACPDefaults,
1970
1578
  applyACPDefaultsFromChain,
1971
1579
  getAclServedAddresses,
1972
1580
  clearAclServedAddresses
@@ -2273,7 +1881,7 @@ var BACKEND_ERROR_CODE_TO_COFHE_ERROR_CODE = {
2273
1881
  seal_failed: "SEAL_FAILED" /* SealFailed */
2274
1882
  };
2275
1883
  function isBackendApiErrorCode(value) {
2276
- return value in BACKEND_ERROR_CODE_TO_COFHE_ERROR_CODE;
1884
+ return Object.prototype.hasOwnProperty.call(BACKEND_ERROR_CODE_TO_COFHE_ERROR_CODE, value);
2277
1885
  }
2278
1886
  async function parseApiErrorResponseBody(response) {
2279
1887
  let errorMessage = `HTTP ${response.status}`;
@@ -3680,13 +3288,13 @@ var buildDecryptResultHash = (ctHash, cleartext, chainId) => {
3680
3288
  async function verifyDecryptResult(handle, cleartext, signature, publicClient) {
3681
3289
  const chainId = publicClient.chain?.id ?? await publicClient.getChainId();
3682
3290
  const expectedSigner = await publicClient.readContract({
3683
- address: TASK_MANAGER_ADDRESS,
3291
+ address: await getTaskManagerAddress(publicClient, chainId),
3684
3292
  abi: decryptResultSignerAbi,
3685
3293
  functionName: "decryptResultSigner",
3686
3294
  args: []
3687
3295
  });
3688
3296
  if (isAddressEqual(expectedSigner, zeroAddress))
3689
- return true;
3297
+ return false;
3690
3298
  const ctHash = BigInt(handle);
3691
3299
  const messageHash = buildDecryptResultHash(ctHash, cleartext, chainId);
3692
3300
  try {
@@ -3714,6 +3322,7 @@ function createCofheClientBase(opts) {
3714
3322
  const updateConnectState = (partial) => {
3715
3323
  connectStore.setState((state) => ({ ...state, ...partial }));
3716
3324
  };
3325
+ const withAppKey = () => opts.config.acp?.app == null ? {} : { appKey: shareAppKey(opts.config.acp.app) };
3717
3326
  const _resolveSharingRegistry = async (publicClient, chainId) => {
3718
3327
  const configured = opts.config.acp?.sharingRegistry?.[chainId];
3719
3328
  if (configured != null)
@@ -3800,6 +3409,7 @@ function createCofheClientBase(opts) {
3800
3409
  zkBuilderAndCrsGenerator: opts.zkBuilderAndCrsGenerator,
3801
3410
  initTfhe: opts.initTfhe,
3802
3411
  zkProveWorkerFn: opts.zkProveWorkerFn,
3412
+ beforeMainThreadProve: opts.beforeMainThreadProve,
3803
3413
  keysStorage,
3804
3414
  requireConnected: _requireConnected
3805
3415
  });
@@ -3871,15 +3481,16 @@ function createCofheClientBase(opts) {
3871
3481
  const { publicClient, walletClient } = clients ?? connectStore.getState();
3872
3482
  const chainId = await publicClient.getChainId();
3873
3483
  return acps.createSharing(
3874
- await acps.applyACPDefaultsFromChain(options, opts.config.acp, publicClient, chainId),
3484
+ await acps.applyACPDefaultsFromChain({ ...withAppKey(), ...options }, opts.config.acp, publicClient, chainId),
3875
3485
  publicClient,
3876
3486
  walletClient
3877
3487
  );
3878
3488
  },
3879
- importShared: async (options, clients) => {
3489
+ importShared: async (options, importOptions = {}) => {
3880
3490
  _requireConnected();
3881
- const { publicClient, walletClient } = clients ?? connectStore.getState();
3882
- return acps.importShared(options, publicClient, walletClient);
3491
+ const { activate, name, ...clients } = importOptions;
3492
+ const { publicClient, walletClient } = clients.publicClient ? clients : connectStore.getState();
3493
+ return acps.importShared(options, publicClient, walletClient, { activate, name });
3883
3494
  },
3884
3495
  // Get or create methods (require connection)
3885
3496
  getOrCreateSelfACP: async (chainId, account, options) => {
@@ -3901,7 +3512,7 @@ function createCofheClientBase(opts) {
3901
3512
  return acps.getOrCreateSharingACP(
3902
3513
  publicClient,
3903
3514
  walletClient,
3904
- await acps.applyACPDefaultsFromChain(options, opts.config.acp, publicClient, _chainId),
3515
+ await acps.applyACPDefaultsFromChain({ ...withAppKey(), ...options }, opts.config.acp, publicClient, _chainId),
3905
3516
  _chainId,
3906
3517
  _account
3907
3518
  );
@@ -3922,13 +3533,18 @@ function createCofheClientBase(opts) {
3922
3533
  const { publicClient } = connectStore.getState();
3923
3534
  return acps.isACPRevoked(acp, publicClient);
3924
3535
  },
3536
+ checkAccess: async (acp, handle) => {
3537
+ _requireConnected();
3538
+ const { publicClient } = connectStore.getState();
3539
+ return acps.checkAccess(acp, publicClient, handle);
3540
+ },
3925
3541
  // On-chain sharing (require connection + config.acp.sharingRegistry)
3926
- shareOnChain: async (acp) => {
3542
+ shareOnChain: async (acp, options) => {
3927
3543
  _requireConnected();
3928
3544
  const { publicClient, walletClient } = connectStore.getState();
3929
3545
  const chainId = await publicClient.getChainId();
3930
3546
  const sharingRegistry = await _resolveSharingRegistry(publicClient, chainId);
3931
- return acps.shareOnChain(acp, walletClient, sharingRegistry);
3547
+ return acps.shareOnChain(acp, walletClient, sharingRegistry, { ...withAppKey(), ...options });
3932
3548
  },
3933
3549
  getIncomingShares: async () => {
3934
3550
  _requireConnected();
@@ -3936,12 +3552,32 @@ function createCofheClientBase(opts) {
3936
3552
  const chainId = await publicClient.getChainId();
3937
3553
  const account = walletClient.account.address;
3938
3554
  const sharingRegistry = await _resolveSharingRegistry(publicClient, chainId);
3939
- return acps.getIncomingShares(publicClient, sharingRegistry, account);
3555
+ return acps.getIncomingShares(publicClient, sharingRegistry, account, withAppKey());
3556
+ },
3557
+ getShareFromChain: async (shareId) => {
3558
+ _requireConnected();
3559
+ const { publicClient } = connectStore.getState();
3560
+ const chainId = await publicClient.getChainId();
3561
+ const sharingRegistry = await _resolveSharingRegistry(publicClient, chainId);
3562
+ return acps.getShareFromChain(publicClient, sharingRegistry, shareId);
3563
+ },
3564
+ verifyShareLabels: async (share, options) => {
3565
+ _requireConnected();
3566
+ const { publicClient } = connectStore.getState();
3567
+ if (share.metadata == null || share.metadata === "0x")
3568
+ return null;
3569
+ return verifyShareLabels({
3570
+ labels: decodeShareMetadata(share.metadata, share.handles),
3571
+ handles: share.handles,
3572
+ issuer: share.issuer,
3573
+ publicClient,
3574
+ verify: options?.verify
3575
+ });
3940
3576
  },
3941
- importFromChain: async (share) => {
3577
+ importFromChain: async (share, options) => {
3942
3578
  _requireConnected();
3943
3579
  const { publicClient, walletClient } = connectStore.getState();
3944
- return acps.importFromChain(share, publicClient, walletClient);
3580
+ return acps.importFromChain(share, publicClient, walletClient, options);
3945
3581
  },
3946
3582
  dismissShare: async (shareId) => {
3947
3583
  _requireConnected();
@@ -4029,4 +3665,4 @@ function createCofheClientBase(opts) {
4029
3665
  };
4030
3666
  }
4031
3667
 
4032
- export { CofheError, CofheErrorCode, DecryptForTxBuilder, DecryptForViewBuilder, EncryptInputsBuilder, EncryptStep, Encryptable, FheAllUTypes, FheTypes, FheUintUTypes, InitialConnectStore, assertNoRenamedConfigKeys, cofheFetch, createCofheClientBase, createCofheConfigBase, createKeysStore, fetchKeys, fheTypeToString, getCofheConfigItem, getCofheDebugInterceptors, isCofheError, isEncryptableItem, isLastEncryptionStep, setCofheDebugInterceptors, verifyDecryptResult, zkProveWithWorker };
3668
+ export { DecryptForTxBuilder, DecryptForViewBuilder, EncryptInputsBuilder, InitialConnectStore, assertNoRenamedConfigKeys, cofheFetch, createCofheClientBase, createCofheConfigBase, createKeysStore, fetchKeys, getCofheConfigItem, getCofheDebugInterceptors, setCofheDebugInterceptors, verifyDecryptResult, zkProveWithWorker };