@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
@@ -59,6 +59,28 @@ var baseSepolia = defineChain({
59
59
  environment: "TESTNET"
60
60
  });
61
61
 
62
+ // chains/chains/ethereum.ts
63
+ var ethereum = defineChain({
64
+ id: 1,
65
+ name: "Ethereum",
66
+ network: "ethereum",
67
+ coFheUrl: "https://cofhe.mainnet.fhenix.zone",
68
+ verifierUrl: "https://cofhe-vrf.mainnet.fhenix.zone",
69
+ thresholdNetworkUrl: "https://cofhe-tn.mainnet.fhenix.zone",
70
+ environment: "MAINNET"
71
+ });
72
+
73
+ // chains/chains/arbitrum.ts
74
+ var arbitrum = defineChain({
75
+ id: 42161,
76
+ name: "Arbitrum One",
77
+ network: "arbitrum",
78
+ coFheUrl: "https://cofhe.mainnet.fhenix.zone",
79
+ verifierUrl: "https://cofhe-vrf.mainnet.fhenix.zone",
80
+ thresholdNetworkUrl: "https://cofhe-tn.mainnet.fhenix.zone",
81
+ environment: "MAINNET"
82
+ });
83
+
62
84
  // chains/chains/hardhat.ts
63
85
  var hardhat = defineChain({
64
86
  id: 31337,
@@ -98,6 +120,8 @@ var chains = {
98
120
  sepolia,
99
121
  arbSepolia,
100
122
  baseSepolia,
123
+ ethereum,
124
+ arbitrum,
101
125
  hardhat,
102
126
  localcofhe,
103
127
  stagingCofhe
@@ -111,4 +135,4 @@ var getChainByName = (name) => {
111
135
  );
112
136
  };
113
137
 
114
- export { arbSepolia, baseSepolia, chains, getChainById, getChainByName, hardhat, localcofhe, sepolia, stagingCofhe };
138
+ export { arbSepolia, arbitrum, baseSepolia, chains, ethereum, getChainById, getChainByName, hardhat, localcofhe, sepolia, stagingCofhe };
@@ -0,0 +1,174 @@
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
+ // core/error.ts
15
+ var CofheErrorCode = /* @__PURE__ */ ((CofheErrorCode2) => {
16
+ CofheErrorCode2["InternalError"] = "INTERNAL_ERROR";
17
+ CofheErrorCode2["UnknownEnvironment"] = "UNKNOWN_ENVIRONMENT";
18
+ CofheErrorCode2["InitTfheFailed"] = "INIT_TFHE_FAILED";
19
+ CofheErrorCode2["InitViemFailed"] = "INIT_VIEM_FAILED";
20
+ CofheErrorCode2["InitEthersFailed"] = "INIT_ETHERS_FAILED";
21
+ CofheErrorCode2["NotConnected"] = "NOT_CONNECTED";
22
+ CofheErrorCode2["MissingPublicClient"] = "MISSING_PUBLIC_CLIENT";
23
+ CofheErrorCode2["MissingWalletClient"] = "MISSING_WALLET_CLIENT";
24
+ CofheErrorCode2["MissingProviderParam"] = "MISSING_PROVIDER_PARAM";
25
+ CofheErrorCode2["EmptySecurityZonesParam"] = "EMPTY_SECURITY_ZONES_PARAM";
26
+ CofheErrorCode2["InvalidACPData"] = "INVALID_ACP_DATA";
27
+ CofheErrorCode2["InvalidACPDomain"] = "INVALID_ACP_DOMAIN";
28
+ CofheErrorCode2["ACPNotFound"] = "ACP_NOT_FOUND";
29
+ CofheErrorCode2["CannotRemoveLastACP"] = "CANNOT_REMOVE_LAST_ACP";
30
+ CofheErrorCode2["AccountUninitialized"] = "ACCOUNT_UNINITIALIZED";
31
+ CofheErrorCode2["ChainIdUninitialized"] = "CHAIN_ID_UNINITIALIZED";
32
+ CofheErrorCode2["ConsumingContractUninitialized"] = "CONSUMING_CONTRACT_UNINITIALIZED";
33
+ CofheErrorCode2["SealOutputFailed"] = "SEAL_OUTPUT_FAILED";
34
+ CofheErrorCode2["SealOutputReturnedNull"] = "SEAL_OUTPUT_RETURNED_NULL";
35
+ CofheErrorCode2["InvalidUtype"] = "INVALID_UTYPE";
36
+ CofheErrorCode2["DecryptFailed"] = "DECRYPT_FAILED";
37
+ CofheErrorCode2["DecryptReturnedNull"] = "DECRYPT_RETURNED_NULL";
38
+ CofheErrorCode2["ZkMocksInsertCtHashesFailed"] = "ZK_MOCKS_INSERT_CT_HASHES_FAILED";
39
+ CofheErrorCode2["ZkMocksCalcCtHashesFailed"] = "ZK_MOCKS_CALC_CT_HASHES_FAILED";
40
+ CofheErrorCode2["ZkMocksVerifySignFailed"] = "ZK_MOCKS_VERIFY_SIGN_FAILED";
41
+ CofheErrorCode2["ZkMocksCreateProofSignatureFailed"] = "ZK_MOCKS_CREATE_PROOF_SIGNATURE_FAILED";
42
+ CofheErrorCode2["ZkVerifyFailed"] = "ZK_VERIFY_FAILED";
43
+ CofheErrorCode2["ZkPackFailed"] = "ZK_PACK_FAILED";
44
+ CofheErrorCode2["ZkProveFailed"] = "ZK_PROVE_FAILED";
45
+ CofheErrorCode2["EncryptRemainingInItems"] = "ENCRYPT_REMAINING_IN_ITEMS";
46
+ CofheErrorCode2["ZkUninitialized"] = "ZK_UNINITIALIZED";
47
+ CofheErrorCode2["ZkVerifierUrlUninitialized"] = "ZK_VERIFIER_URL_UNINITIALIZED";
48
+ CofheErrorCode2["ThresholdNetworkUrlUninitialized"] = "THRESHOLD_NETWORK_URL_UNINITIALIZED";
49
+ CofheErrorCode2["MissingConfig"] = "MISSING_CONFIG";
50
+ CofheErrorCode2["UnsupportedChain"] = "UNSUPPORTED_CHAIN";
51
+ CofheErrorCode2["MissingZkBuilderAndCrsGenerator"] = "MISSING_ZK_BUILDER_AND_CRS_GENERATOR";
52
+ CofheErrorCode2["MissingTfhePublicKeyDeserializer"] = "MISSING_TFHE_PUBLIC_KEY_DESERIALIZER";
53
+ CofheErrorCode2["MissingCompactPkeCrsDeserializer"] = "MISSING_COMPACT_PKE_CRS_DESERIALIZER";
54
+ CofheErrorCode2["MissingFheKey"] = "MISSING_FHE_KEY";
55
+ CofheErrorCode2["MissingCrs"] = "MISSING_CRS";
56
+ CofheErrorCode2["FetchKeysFailed"] = "FETCH_KEYS_FAILED";
57
+ CofheErrorCode2["PublicWalletGetChainIdFailed"] = "PUBLIC_WALLET_GET_CHAIN_ID_FAILED";
58
+ CofheErrorCode2["PublicWalletGetAddressesFailed"] = "PUBLIC_WALLET_GET_ADDRESSES_FAILED";
59
+ CofheErrorCode2["RehydrateKeysStoreFailed"] = "REHYDRATE_KEYS_STORE_FAILED";
60
+ CofheErrorCode2["TaskManagerUnresolved"] = "TASK_MANAGER_UNRESOLVED";
61
+ CofheErrorCode2["BadRequest"] = "BAD_REQUEST";
62
+ CofheErrorCode2["UnknownChain"] = "UNKNOWN_CHAIN";
63
+ CofheErrorCode2["ACPMalformed"] = "ACP_MALFORMED";
64
+ CofheErrorCode2["ACPDenied"] = "ACP_DENIED";
65
+ CofheErrorCode2["ACPExpired"] = "ACP_EXPIRED";
66
+ CofheErrorCode2["ACPInvalid"] = "ACP_INVALID";
67
+ CofheErrorCode2["ACPRevoked"] = "ACP_REVOKED";
68
+ CofheErrorCode2["NotPubliclyAllowed"] = "NOT_PUBLICLY_ALLOWED";
69
+ CofheErrorCode2["CtNotFound"] = "CT_NOT_FOUND";
70
+ CofheErrorCode2["UnsupportedSecurityZone"] = "UNSUPPORTED_SECURITY_ZONE";
71
+ CofheErrorCode2["UnsupportedType"] = "UNSUPPORTED_TYPE";
72
+ CofheErrorCode2["SigningFailed"] = "SIGNING_FAILED";
73
+ CofheErrorCode2["CtSourceError"] = "CT_SOURCE_ERROR";
74
+ CofheErrorCode2["ACPVerifierError"] = "ACP_VERIFIER_ERROR";
75
+ CofheErrorCode2["CtSourceTimeout"] = "CT_SOURCE_TIMEOUT";
76
+ CofheErrorCode2["ACPVerifierTimeout"] = "ACP_VERIFIER_TIMEOUT";
77
+ CofheErrorCode2["ACPRequired"] = "ACP_REQUIRED";
78
+ CofheErrorCode2["SealFailed"] = "SEAL_FAILED";
79
+ return CofheErrorCode2;
80
+ })(CofheErrorCode || {});
81
+ var CofheError = class _CofheError extends Error {
82
+ code;
83
+ cause;
84
+ hint;
85
+ context;
86
+ apiErrorCode;
87
+ constructor({ code, message, cause, hint, context, apiErrorCode }) {
88
+ const fullMessage = cause ? `${message} | Caused by: ${cause.message}` : message;
89
+ super(fullMessage);
90
+ this.name = "CofheError";
91
+ this.code = code;
92
+ this.cause = cause;
93
+ this.hint = hint;
94
+ this.context = context;
95
+ this.apiErrorCode = apiErrorCode;
96
+ if (Error.captureStackTrace) {
97
+ Error.captureStackTrace(this, _CofheError);
98
+ }
99
+ }
100
+ /**
101
+ * Creates a CofheError from an unknown error
102
+ * If the error is a CofheError, it is returned unchanged, else a new CofheError is created
103
+ * If a wrapperError is provided, it is used to create the new CofheError, else a default is used
104
+ */
105
+ static fromError(error, wrapperError) {
106
+ if (isCofheError(error))
107
+ return error;
108
+ const cause = error instanceof Error ? error : new Error(`${error}`);
109
+ return new _CofheError({
110
+ code: wrapperError?.code ?? "INTERNAL_ERROR" /* InternalError */,
111
+ message: wrapperError?.message ?? "An internal error occurred",
112
+ hint: wrapperError?.hint,
113
+ context: wrapperError?.context,
114
+ apiErrorCode: wrapperError?.apiErrorCode,
115
+ cause
116
+ });
117
+ }
118
+ /**
119
+ * Serializes the error to JSON string with proper handling of Error objects
120
+ */
121
+ serialize() {
122
+ return bigintSafeJsonStringify({
123
+ name: this.name,
124
+ code: this.code,
125
+ message: this.message,
126
+ hint: this.hint,
127
+ context: this.context,
128
+ apiErrorCode: this.apiErrorCode,
129
+ cause: this.cause ? {
130
+ name: this.cause.name,
131
+ message: this.cause.message,
132
+ stack: this.cause.stack
133
+ } : void 0,
134
+ stack: this.stack
135
+ });
136
+ }
137
+ /**
138
+ * Returns a human-readable string representation of the error
139
+ */
140
+ toString() {
141
+ const codeSuffix = this.apiErrorCode ? ` (api: ${this.apiErrorCode})` : "";
142
+ const parts = [`${this.name} [${this.code}]${codeSuffix}: ${this.message}`];
143
+ if (this.hint) {
144
+ parts.push(`Hint: ${this.hint}`);
145
+ }
146
+ if (this.context && Object.keys(this.context).length > 0) {
147
+ parts.push(`Context: ${bigintSafeJsonStringify(this.context)}`);
148
+ }
149
+ if (this.stack) {
150
+ parts.push(`
151
+ Stack trace:`);
152
+ parts.push(this.stack);
153
+ }
154
+ if (this.cause) {
155
+ parts.push(`
156
+ Caused by: ${this.cause.name}: ${this.cause.message}`);
157
+ if (this.cause.stack) {
158
+ parts.push(this.cause.stack);
159
+ }
160
+ }
161
+ return parts.join("\n");
162
+ }
163
+ };
164
+ var bigintSafeJsonStringify = (value) => {
165
+ return JSON.stringify(value, (key, value2) => {
166
+ if (typeof value2 === "bigint") {
167
+ return `${value2}n`;
168
+ }
169
+ return value2;
170
+ });
171
+ };
172
+ var isCofheError = (error) => error instanceof CofheError;
173
+
174
+ 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,10 +1,17 @@
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, h as EIP712Domain, C as CreateSelfACPOptions, p as SelfACP, d as CreateSharingACPOptions, q as SharingACP, I as ImportSharedACPOptions, R as RecipientACP, v as ACPHashFields, S as SerializedACP, g as IncomingShare, i as ACPUtils } from './acp-Wi6isVQI.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-D9Z33IP7.cjs';
5
5
  import { StoreApi } from 'zustand/vanilla';
6
6
 
7
7
  type TfheInitializer = () => Promise<boolean>;
8
+ /**
9
+ * How many threads tfhe's rayon pool may use for ZK proof generation (web only).
10
+ * - `'auto'` (default): derive from `navigator.hardwareConcurrency`, capped
11
+ * - a positive number: request exactly that many
12
+ * - `false`: stay single-threaded
13
+ */
14
+ type TfheThreadsSetting = number | 'auto' | false;
8
15
  interface IStorage {
9
16
  getItem: (name: string) => Promise<any>;
10
17
  setItem: (name: string, value: any) => Promise<void>;
@@ -229,6 +236,25 @@ type CofheConfig = {
229
236
  * Default: true
230
237
  */
231
238
  useWorkers: boolean;
239
+ /**
240
+ * How many threads tfhe's rayon pool may use for ZK proof generation
241
+ * (web platform only; ignored on node/hardhat).
242
+ *
243
+ * Proving dominates the cost of `encryptInputs`, and tfhe's wasm is built with
244
+ * rayon, so spreading it across threads is a large win — roughly 5x on an
245
+ * 8-thread pool.
246
+ *
247
+ * Requires a cross-origin-isolated page (`Cross-Origin-Opener-Policy: same-origin`
248
+ * plus `Cross-Origin-Embedder-Policy: require-corp` or `credentialless`). When the
249
+ * page isn't isolated the pool is skipped and proving stays single-threaded, so
250
+ * this is safe to leave on.
251
+ *
252
+ * `'auto'` derives the count from `navigator.hardwareConcurrency` (capped, since
253
+ * the speedup flattens out); a number requests exactly that many; `false` keeps
254
+ * tfhe single-threaded.
255
+ * Default: 'auto'
256
+ */
257
+ tfheThreads: TfheThreadsSetting;
232
258
  /** ACP acp defaults, applied when creating acps (user options always win) */
233
259
  acp: {
234
260
  /**
@@ -254,6 +280,13 @@ type CofheConfig = {
254
280
  * names a registry.
255
281
  */
256
282
  sharingRegistry?: Record<number, `0x${string}`>;
283
+ /**
284
+ * The name of this app, e.g. 'explorer.fhenix.io'. Set, every share the client creates
285
+ * carries the app's key (`shareAppKey(app)`, kept in the share metadata), and
286
+ * `getIncomingShares` lists only the shares posted for this app. Unset, shares carry no
287
+ * key and every importable share is listed.
288
+ */
289
+ app?: string;
257
290
  };
258
291
  /** Mocks configs */
259
292
  mocks: {
@@ -310,10 +343,12 @@ declare const CofheConfigSchema: z.ZodObject<{
310
343
  removeItem: z.ZodCustom<(name: string) => Promise<void>, (name: string) => Promise<void>>;
311
344
  }, z.core.$strip>, z.ZodNull]>>;
312
345
  useWorkers: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
346
+ tfheThreads: z.ZodDefault<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodLiteral<"auto">, z.ZodLiteral<false>]>>>;
313
347
  acp: z.ZodDefault<z.ZodOptional<z.ZodObject<{
314
348
  defaultRevoker: z.ZodOptional<z.ZodCustom<Record<number, `0x${string}`>, Record<number, `0x${string}`>>>;
315
349
  defaultContractScopes: z.ZodOptional<z.ZodCustom<Record<number, `0x${string}`[]>, Record<number, `0x${string}`[]>>>;
316
350
  sharingRegistry: z.ZodOptional<z.ZodCustom<Record<number, `0x${string}`>, Record<number, `0x${string}`>>>;
351
+ app: z.ZodOptional<z.ZodString>;
317
352
  }, z.core.$strip>>>;
318
353
  mocks: z.ZodDefault<z.ZodOptional<z.ZodObject<{
319
354
  decryptDelay: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
@@ -665,6 +700,12 @@ interface ZkProveWorkerRequest {
665
700
  data: any;
666
701
  }>;
667
702
  metadata: number[];
703
+ /**
704
+ * Forwarded from `config.tfheThreads`. The worker applies it the first time it
705
+ * initialises tfhe — `initThreadPool` can only run once per wasm instance, so
706
+ * later requests carrying a different value have no effect.
707
+ */
708
+ tfheThreads?: TfheThreadsSetting;
668
709
  }
669
710
  /**
670
711
  * Message sent from worker back to main thread with proof result
@@ -712,14 +753,14 @@ type ChainRecord<T> = Record<string, T>;
712
753
  type SecurityZoneRecord<T> = Record<number, T>;
713
754
  type KeysStore = {
714
755
  fhe: ChainRecord<SecurityZoneRecord<string | undefined>>;
715
- crs: ChainRecord<string | undefined>;
756
+ crs: ChainRecord<SecurityZoneRecord<string | undefined>>;
716
757
  };
717
758
  type KeysStorage = {
718
759
  store: StoreApi<KeysStore>;
719
760
  getFheKey: (chainId: number | undefined, securityZone?: number) => string | undefined;
720
- getCrs: (chainId: number | undefined) => string | undefined;
761
+ getCrs: (chainId: number | undefined, securityZone?: number) => string | undefined;
721
762
  setFheKey: (chainId: number, securityZone: number, key: string) => void;
722
- setCrs: (chainId: number, crs: string) => void;
763
+ setCrs: (chainId: number, securityZone: number, crs: string) => void;
723
764
  clearKeysStorage: () => Promise<void>;
724
765
  rehydrateKeysStore: () => Promise<void>;
725
766
  };
@@ -753,6 +794,7 @@ type EncryptInputsBuilderParams<T extends EncryptableItem[]> = BaseBuilderParams
753
794
  zkBuilderAndCrsGenerator: ZkBuilderAndCrsGenerator | undefined;
754
795
  initTfhe: TfheInitializer | undefined;
755
796
  zkProveWorkerFn: ZkProveWorkerFunction | undefined;
797
+ beforeMainThreadProve?: (() => Promise<void>) | undefined;
756
798
  keysStorage: KeysStorage | undefined;
757
799
  };
758
800
  /**
@@ -779,6 +821,7 @@ declare class EncryptInputsBuilder<T extends EncryptableItem[]> extends BaseBuil
779
821
  private zkBuilderAndCrsGenerator;
780
822
  private initTfhe;
781
823
  private zkProveWorkerFn;
824
+ private beforeMainThreadProve;
782
825
  private keysStorage;
783
826
  private useWorker;
784
827
  private stepTimestamps;
@@ -971,10 +1014,34 @@ declare class EncryptInputsBuilder<T extends EncryptableItem[]> extends BaseBuil
971
1014
  execute(): Promise<HashPlusProofResult<T>>;
972
1015
  }
973
1016
 
974
- interface AclServedAddresses {
975
- defaultRevoker?: Hex;
976
- shareRegistry?: Hex;
977
- }
1017
+ /** Options for importing a shared acp. */
1018
+ type ImportActivationOptions = {
1019
+ /**
1020
+ * Make the imported acp the active one. Defaults to `true`.
1021
+ * With `false` the acp is only stored: decrypts that use the active acp keep using the current one,
1022
+ * and the imported acp is used only where it is passed explicitly (e.g. `.withACP(acp)`).
1023
+ */
1024
+ activate?: boolean;
1025
+ };
1026
+ /** Options for importing a shared acp: activation, and the recipient's own name for it. */
1027
+ type ImportSharedOptions = ImportActivationOptions & {
1028
+ /**
1029
+ * The name of the imported acp. Defaults to "Shared by 0x1234…abcd" (its issuer); the issuer's
1030
+ * own name for the share is not exported and is ignored if present.
1031
+ */
1032
+ name?: string;
1033
+ };
1034
+ /**
1035
+ * What `shareOnChain` posts with a share: the labels of its handles (one per handle, in order;
1036
+ * encoded with `encodeShareMetadata`), or an already encoded metadata blob. Written once, with the
1037
+ * share. Omitted, the labels the acp was created with are posted (`createSharing({ labels })`),
1038
+ * or none. `appKey` goes with given labels; a client configured with `acp: { app }` fills it in.
1039
+ */
1040
+ type ShareOnChainOptions = {
1041
+ labels?: readonly ShareLabel[];
1042
+ metadata?: Hex;
1043
+ appKey?: Hex;
1044
+ };
978
1045
  declare const acps: {
979
1046
  getSnapshot: () => {
980
1047
  acps: {
@@ -985,6 +1052,7 @@ declare const acps: {
985
1052
  name: string;
986
1053
  type: "self" | "sharing" | "recipient";
987
1054
  sealingPrivateKey: Hex;
1055
+ metadata?: Hex | undefined;
988
1056
  _signedDomain?: EIP712Domain | undefined;
989
1057
  issuer: Hex;
990
1058
  expiration: number;
@@ -1016,6 +1084,7 @@ declare const acps: {
1016
1084
  name: string;
1017
1085
  type: "self" | "sharing" | "recipient";
1018
1086
  sealingPrivateKey: Hex;
1087
+ metadata?: Hex | undefined;
1019
1088
  _signedDomain?: EIP712Domain | undefined;
1020
1089
  issuer: Hex;
1021
1090
  expiration: number;
@@ -1046,6 +1115,7 @@ declare const acps: {
1046
1115
  name: string;
1047
1116
  type: "self" | "sharing" | "recipient";
1048
1117
  sealingPrivateKey: Hex;
1118
+ metadata?: Hex | undefined;
1049
1119
  _signedDomain?: EIP712Domain | undefined;
1050
1120
  issuer: Hex;
1051
1121
  expiration: number;
@@ -1070,7 +1140,7 @@ declare const acps: {
1070
1140
  }) => void) => () => void;
1071
1141
  createSelf: (options: CreateSelfACPOptions, publicClient: PublicClient, walletClient: WalletClient) => Promise<SelfACP>;
1072
1142
  createSharing: (options: CreateSharingACPOptions, publicClient: PublicClient, walletClient: WalletClient) => Promise<SharingACP>;
1073
- importShared: (options: ImportSharedACPOptions | string, publicClient: PublicClient, walletClient: WalletClient) => Promise<RecipientACP>;
1143
+ importShared: (options: ImportSharedACPOptions | string, publicClient: PublicClient, walletClient: WalletClient, { activate, name }?: ImportSharedOptions) => Promise<RecipientACP>;
1074
1144
  getOrCreateSelfACP: (publicClient: PublicClient, walletClient: WalletClient, chainId?: number, account?: string, options?: CreateSelfACPOptions) => Promise<ACP>;
1075
1145
  getOrCreateSharingACP: (publicClient: PublicClient, walletClient: WalletClient, options: CreateSharingACPOptions, chainId?: number, account?: string) => Promise<ACP>;
1076
1146
  getHash: (acp: ACPHashFields) => string;
@@ -1080,6 +1150,7 @@ declare const acps: {
1080
1150
  name: string;
1081
1151
  type: "self" | "sharing" | "recipient";
1082
1152
  sealingPrivateKey: Hex;
1153
+ metadata?: Hex | undefined;
1083
1154
  _signedDomain?: EIP712Domain | undefined;
1084
1155
  issuer: Hex;
1085
1156
  expiration: number;
@@ -1098,6 +1169,7 @@ declare const acps: {
1098
1169
  name: string;
1099
1170
  type: "self" | "sharing" | "recipient";
1100
1171
  sealingPrivateKey: Hex;
1172
+ metadata?: Hex | undefined;
1101
1173
  _signedDomain?: EIP712Domain | undefined;
1102
1174
  issuer: Hex;
1103
1175
  expiration: number;
@@ -1121,24 +1193,18 @@ declare const acps: {
1121
1193
  revokeACP: (acp: ACP, walletClient: WalletClient) => Promise<Hex>;
1122
1194
  revokeAllACPs: (walletClient: WalletClient, publicClient: PublicClient, revokerContract?: Hex) => Promise<Hex>;
1123
1195
  isACPRevoked: (acp: ACP, publicClient: PublicClient) => Promise<boolean>;
1124
- shareOnChain: (acp: ACP, walletClient: WalletClient, registry: Hex) => Promise<{
1196
+ checkAccess: (acp: ACP, publicClient: PublicClient, handle?: bigint | Hex) => Promise<ACPAccessStatus>;
1197
+ shareOnChain: (acp: ACP, walletClient: WalletClient, registry: Hex, options?: ShareOnChainOptions) => Promise<{
1125
1198
  txHash: Hex;
1126
1199
  shareId: Hex;
1127
1200
  }>;
1128
- getIncomingShares: (publicClient: PublicClient, registry: Hex, recipient: Hex) => Promise<IncomingShare[]>;
1129
- importFromChain: (share: IncomingShare, publicClient: PublicClient, walletClient: WalletClient) => Promise<RecipientACP>;
1201
+ getIncomingShares: (publicClient: PublicClient, registry: Hex, recipient: Hex, { appKey }?: {
1202
+ appKey?: Hex;
1203
+ }) => Promise<IncomingShare[]>;
1204
+ getShareFromChain: (publicClient: PublicClient, registry: Hex, shareId: Hex) => Promise<IncomingShare | null>;
1205
+ importFromChain: (share: IncomingShare, publicClient: PublicClient, walletClient: WalletClient, importOptions?: ImportSharedOptions) => Promise<RecipientACP>;
1130
1206
  removeShareOnChain: (shareId: Hex, walletClient: WalletClient, registry: Hex) => Promise<Hex>;
1131
1207
  computeShareId: (acp: ACP) => Hex;
1132
- applyACPDefaults: <T extends {
1133
- revokerData?: number;
1134
- revokerContract?: string;
1135
- scope?: number;
1136
- contracts?: string[];
1137
- handles?: (bigint | number | string)[];
1138
- }>(options: T, acpConfig: {
1139
- defaultRevoker?: Record<number, Hex>;
1140
- defaultContractScopes?: Record<number, Hex[]>;
1141
- } | undefined, chainId: number) => T;
1142
1208
  applyACPDefaultsFromChain: <T extends {
1143
1209
  revokerData?: number;
1144
1210
  revokerContract?: string;
@@ -1195,12 +1261,21 @@ type CofheClientACPsClients = {
1195
1261
  publicClient: PublicClient;
1196
1262
  walletClient: WalletClient;
1197
1263
  };
1264
+ /**
1265
+ * Options for `importShared`. `activate: false` stores the imported acp without making it the active
1266
+ * one (default `true`). `name` names it (default "Shared by 0x1234…abcd"). Clients default to the
1267
+ * connected ones; pass both to override.
1268
+ */
1269
+ type CofheClientImportSharedOptions = ImportSharedOptions & (CofheClientACPsClients | {
1270
+ publicClient?: undefined;
1271
+ walletClient?: undefined;
1272
+ });
1198
1273
  type CofheClientACPs = {
1199
1274
  getSnapshot: typeof acps.getSnapshot;
1200
1275
  subscribe: typeof acps.subscribe;
1201
1276
  createSelf: (options: CreateSelfACPOptions, clients?: CofheClientACPsClients) => Promise<SelfACP>;
1202
1277
  createSharing: (options: CreateSharingACPOptions, clients?: CofheClientACPsClients) => Promise<SharingACP>;
1203
- importShared: (options: ImportSharedACPOptions | string, clients?: CofheClientACPsClients) => Promise<RecipientACP>;
1278
+ importShared: (options: ImportSharedACPOptions | string, importOptions?: CofheClientImportSharedOptions) => Promise<RecipientACP>;
1204
1279
  getACP: (hash: string, chainId?: number, account?: string) => ACP | undefined;
1205
1280
  getACPs: (chainId?: number, account?: string) => Record<string, ACP>;
1206
1281
  getActiveACP: (chainId?: number, account?: string) => ACP | undefined;
@@ -1213,15 +1288,36 @@ type CofheClientACPs = {
1213
1288
  revokeACP: (acp: ACP) => Promise<`0x${string}`>;
1214
1289
  revokeAllACPs: (revokerContract?: `0x${string}`) => Promise<`0x${string}`>;
1215
1290
  isACPRevoked: (acp: ACP) => Promise<boolean>;
1216
- /** Post a signed sharing ACP to the on-chain share registry (ACL-served, or config `acp.sharingRegistry`). */
1217
- shareOnChain: (acp: ACP) => Promise<{
1291
+ /**
1292
+ * The ACP on-chain status as a value instead of a revert. Without a handle: 'valid', or
1293
+ * 'expired' / 'revoked' / an invalid signature. With a handle, a valid ACP reports
1294
+ * 'allowed', 'out-of-scope' or 'issuer-not-allowed'. For the issuer copy of a share (type
1295
+ * 'sharing', no recipient signature yet) the handle-less check covers expiry and revocation only.
1296
+ */
1297
+ checkAccess: (acp: ACP, handle?: bigint | `0x${string}`) => Promise<ACPAccessStatus>;
1298
+ /**
1299
+ * Post a signed sharing ACP to the on-chain share registry (ACL-served, or config `acp.sharingRegistry`),
1300
+ * optionally with the labels of its handles (`options.labels`, one per handle) or an encoded blob.
1301
+ */
1302
+ shareOnChain: (acp: ACP, options?: ShareOnChainOptions) => Promise<{
1218
1303
  txHash: `0x${string}`;
1219
1304
  shareId: `0x${string}`;
1220
1305
  }>;
1221
- /** Importable shares addressed to the connected account (unexpired, not revoked). */
1306
+ /** Importable shares addressed to the connected account (unexpired, not revoked), with their metadata. */
1222
1307
  getIncomingShares: () => Promise<IncomingShare[]>;
1223
- /** Import a share read from the registry: sign as recipient, store and activate. */
1224
- importFromChain: (share: IncomingShare) => Promise<RecipientACP>;
1308
+ /** One share by id, as posted; null when unknown or removed. */
1309
+ getShareFromChain: (shareId: `0x${string}`) => Promise<IncomingShare | null>;
1310
+ /**
1311
+ * Check a share's labels against the chain, index for index with its handles, as far as
1312
+ * `verify` says (default 'all'). Takes a share read from the registry or an acp imported from
1313
+ * exported JSON (or the issuer's sharing acp). Null for a share without metadata. Throws on a
1314
+ * malformed blob.
1315
+ */
1316
+ verifyShareLabels: (share: LabelledShare, options?: {
1317
+ verify?: ShareLabelVerifyMode;
1318
+ }) => Promise<ShareLabelCheck[] | null>;
1319
+ /** Import a share read from the registry: sign as recipient, store and (unless `activate: false`) activate. */
1320
+ importFromChain: (share: IncomingShare, options?: ImportSharedOptions) => Promise<RecipientACP>;
1225
1321
  /** Recipient-side: remove a share from the registry (after import, or to decline). */
1226
1322
  dismissShare: (shareId: `0x${string}`) => Promise<`0x${string}`>;
1227
1323
  /** Issuer-side: retract a pending share from the registry. */
@@ -1238,6 +1334,13 @@ type CofheClientParams<TConfig extends CofheConfig> = {
1238
1334
  compactPkeCrsDeserializer: FheKeyDeserializer;
1239
1335
  initTfhe: TfheInitializer;
1240
1336
  zkProveWorkerFn?: ZkProveWorkerFunction;
1337
+ /**
1338
+ * Runs right before a ZK proof is generated on the calling thread, i.e. only
1339
+ * when the worker path is disabled, unavailable or has failed. Platforms use
1340
+ * it for setup that only pays off when that thread does the proving (web
1341
+ * starts tfhe's rayon thread pool here).
1342
+ */
1343
+ beforeMainThreadProve?: () => Promise<void>;
1241
1344
  };
1242
1345
 
1243
- export { EncryptInputsBuilder as $, type AnyExternalHash as A, type EncryptableToExternalHashMap as B, type CofheInputConfig as C, type ExternalItemHashes as D, type EncryptableItem as E, FheTypes as F, type DecryptPollCallbackFunction as G, type HashPlusProofResult as H, type IStorage as I, type DecryptPollCallbackContext as J, type DecryptEndpoint as K, type LiteralToPrimitive as L, type EncryptStepCallbackFunction as M, type EncryptStepCallbackContext as N, FheUintUTypes as O, type Primitive as P, FheAllUTypes as Q, Encryptable as R, isEncryptableItem as S, EncryptStep as T, type UnsealedItem as U, isLastEncryptionStep as V, fetchKeys as W, type FheKeyDeserializer as X, createKeysStore as Y, type KeysStorage as Z, type KeysStore as _, type CofheConfig as a, type EncryptInputsBuilderUnset as a0, DecryptForViewBuilder as a1, DecryptForTxBuilder as a2, type DecryptForTxResult as a3, type ZkBuilderAndCrsGenerator as a4, type ZkProveWorkerFunction as a5, type ZkProveWorkerRequest as a6, type ZkProveWorkerResponse as a7, zkProveWithWorker as a8, type CofheClient as b, type CofheClientParams as c, type CofheClientConnectionState as d, createCofheConfigBase as e, assertNoRenamedConfigKeys as f, getCofheConfigItem as g, type CofheInternalConfig as h, type CofheClientACPs as i, type EncryptableBool as j, type EncryptableUint8 as k, type EncryptableUint16 as l, type EncryptableUint32 as m, type EncryptableUint64 as n, type EncryptableUint128 as o, type EncryptableAddress as p, type EncryptedNumber as q, type FheTypeValue as r, type ExternalBoolHash as s, type ExternalUint8Hash as t, type ExternalUint16Hash as u, type ExternalUint32Hash as v, type ExternalUint64Hash as w, type ExternalUint128Hash as x, type ExternalAddressHash as y, type ExternalHashProof as z };
1346
+ export { type KeysStorage as $, type AnyExternalHash as A, type EncryptableToExternalHashMap as B, type CofheInputConfig as C, type ExternalItemHashes as D, type EncryptableItem as E, FheTypes as F, type DecryptPollCallbackFunction as G, type HashPlusProofResult as H, type IStorage as I, type DecryptPollCallbackContext as J, type DecryptEndpoint as K, type LiteralToPrimitive as L, type EncryptStepCallbackFunction as M, type EncryptStepCallbackContext as N, type TfheThreadsSetting as O, type Primitive as P, FheUintUTypes as Q, FheAllUTypes as R, Encryptable as S, type TfheInitializer as T, type UnsealedItem as U, isEncryptableItem as V, EncryptStep as W, isLastEncryptionStep as X, fetchKeys as Y, type FheKeyDeserializer as Z, createKeysStore as _, type CofheConfig as a, type KeysStore as a0, EncryptInputsBuilder as a1, type EncryptInputsBuilderUnset as a2, DecryptForViewBuilder as a3, DecryptForTxBuilder as a4, type DecryptForTxResult as a5, type ZkBuilderAndCrsGenerator as a6, type ZkProveWorkerFunction as a7, type ZkProveWorkerRequest as a8, type ZkProveWorkerResponse as a9, zkProveWithWorker as aa, type CofheClient as b, type CofheClientParams as c, type CofheClientConnectionState as d, createCofheConfigBase as e, assertNoRenamedConfigKeys as f, getCofheConfigItem as g, type CofheInternalConfig as h, type CofheClientACPs as i, type EncryptableBool as j, type EncryptableUint8 as k, type EncryptableUint16 as l, type EncryptableUint32 as m, type EncryptableUint64 as n, type EncryptableUint128 as o, type EncryptableAddress as p, type EncryptedNumber as q, type FheTypeValue as r, type ExternalBoolHash as s, type ExternalUint8Hash as t, type ExternalUint16Hash as u, type ExternalUint32Hash as v, type ExternalUint64Hash as w, type ExternalUint128Hash as x, type ExternalAddressHash as y, type ExternalHashProof as z };