@cofhe/sdk 1.0.0-alpha.0 → 1.0.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,56 @@
1
1
  # @cofhe/sdk Changelog
2
2
 
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - d711ce2: 1.0.0, the first stable release. Breaking changes since 0.8, detailed in their own entries below:
8
+
9
+ - The on-chain share registry has a new layout (`share(acp, metadata)`, header-only `sharesFor` / `getShare`), and shared ACPs no longer carry a `name`.
10
+ - The mocks need Solidity 0.8.25 or later and `@openzeppelin/contracts-upgradeable`.
11
+ - `CofheProvider` takes either `config` or `cofheClient`, not both.
12
+
13
+ ### Minor Changes
14
+
15
+ - 6dcfb7d: ACPs sharing SNAPSHOTs (ctHashes rather than live data) can use the new on-chain ACP Sharing Registry `metadata` field to cite the origin of the snapshotted data (contract address + view-function / event), and the recipient can verify it on-chain. [Docs](https://cofhesdk.fhenix.io/sdk/acp#labelling-a-snapshot-share)
16
+
17
+ **@cofhe/sdk**
18
+
19
+ - `createSharing({ labels })`, `shareOnChain(acp, { labels | metadata })`; labels travel in `export()` / `importShared` as `SharedACP.metadata`.
20
+ - New `client.acp.verifyShareLabels`, `client.acp.getShareFromChain`, and `describeShareMetadata`. `IncomingShare` gains `metadata` and `appKey`.
21
+ - New `acp.app` config option: shares are tagged with the app's key and `getIncomingShares` lists only that app's shares ([docs](https://cofhesdk.fhenix.io/sdk/acp#mark-shares-for-your-app)).
22
+ - `@cofhe/sdk/acps` exports the metadata codec, label builders (`viewFunctionLabel`, `eventLogLabel`, `UNLABELLED`), verifiers, registry readers, `shareAppKey` and `ERC7984_ABI`.
23
+
24
+ **@cofhe/react**
25
+
26
+ - New `useCofheShareLabels`. `useCofheShareOnChain` accepts `{ acp, labels | metadata }`.
27
+ - The inbox shows each share's labels and their verification. [Docs](https://cofhesdk.fhenix.io/react/acp#share-labels)
28
+
29
+ **Mocks and plugins**
30
+
31
+ - `ACPShareRegistry`, `ACPTimestampRevoker` and `Permissioned` are copied verbatim from a pinned cofhe-contracts commit (`pnpm update:cofhe-contracts <commit>`). The share registry is deployed behind `MockERC1967Proxy`.
32
+ - Mocks now need Solidity ≥0.8.25 and `@openzeppelin/contracts-upgradeable` (new Hardhat plugin peer dependency; Foundry users add its remapping).
33
+
34
+ ### Patch Changes
35
+
36
+ - d711ce2: The mocks now behave like the real TaskManager and TFHE-rs in more places. Tests that relied on the old mock behaviour may start failing, as they would on a real network.
37
+
38
+ - `FHE.asE*` (trivial encrypt) reverts with `InvalidInputForFunction` when the value does not fit the type (e.g. `FHE.asEuint8(256)`), and with `InvalidSecurityZone` for an out of range zone, instead of storing the value masked.
39
+ - `encryptInputs` against the mocks rejects out-of-range values with the same error as the production path, instead of passing them on to be masked (e.g. `Encryptable.uint8(256n)` became `0`).
40
+ - `FHE.not` on encrypted integers is a bitwise NOT (`not(euint8(2))` is 253, not 0), and `FHE.rol` / `FHE.ror` rotate within the type's width, with the amount taken modulo the width, instead of shifting.
41
+ - `FHE.rem(x, 0)` returns `x` instead of reverting.
42
+ - `FHE.random*` handles carry their type and security zone and can be allowed and computed on.
43
+ - `MockTaskManager.isPubliclyAllowed` returns whether a handle was made public with `FHE.allowGlobal` / `FHE.allowPublic`, instead of reverting with `NotImplemented`.
44
+ - Handles in a negative security zone go through the ACL like any other handle. Previously any contract could use them and `FHE.allow*` did nothing.
45
+ - `publishDecryptResultBatch` emits `DecryptionResult` with the caller as `requestor`, and the batch decrypt result functions revert with `LengthMismatch` when the arrays differ in length.
46
+ - `setSecurityZones` rejects an inverted range (`min > max`) with `InvalidSecurityZone`.
47
+
48
+ - 5a192ee: Node storage now creates ~/.cofhesdk with mode 0700 and files with 0600, and tightens permissions on existing ones.
49
+ - 757e448: Use the latest chain block timestamp for injected ACP revoker data while preserving explicit revoker configuration precedence.
50
+ - 73d5297: `seal` and `unsealWithPrivateKey` now throw when the sealing key contains non-hex characters. Previously a 64-character key with invalid characters passed the length check and those characters decoded to zero bytes, so `seal` silently encrypted to the wrong key (an entirely invalid key became the all-zero key, which offers no confidentiality), and `unsealWithPrivateKey` failed later with `Failed to decrypt message`.
51
+ - 8fad647: `unsealWithPrivateKey` throws a `CofheError` with code `SealOutputFailed` when a decrypt response can't be unsealed, instead of a plain `Error`. `useCofheDecrypt` no longer retries these failures.
52
+ - a4fcea7: `verifyDecryptResult` now returns `false` when the chain's TaskManager has no `decryptResultSigner` set (zero address). It used to return `true` for any signature in that case. The on-chain `verifyDecryptResult` still skips the check when no signer is set.
53
+
3
54
  ## 0.8.0
4
55
 
5
56
  ### Minor Changes
@@ -345,9 +345,9 @@ export const clearAclServedAddresses = () => aclServedAddressesCache.clear();
345
345
  * TaskManager -> acl() -> getters). Zero addresses and pre-upgrade ACLs (getters absent -> revert)
346
346
  * resolve to `undefined` — callers fall back to `acp.*` config.
347
347
  *
348
- * Resolutions are cached per chainId. A failure to reach the TaskManager (network
349
- * error, no CoFHE deployment) is NOT cached, so a transient outage does not pin
350
- * an empty result for the whole session.
348
+ * Resolutions are cached per chainId. A failure to reach the TaskManager or the ACL
349
+ * getters (network error, no CoFHE deployment) is NOT cached, so a transient outage
350
+ * does not pin an empty result for the whole session.
351
351
  */
352
352
  export const getAclServedAddresses = async (
353
353
  publicClient: PublicClient,
@@ -367,19 +367,24 @@ export const getAclServedAddresses = async (
367
367
  return {};
368
368
  }
369
369
 
370
+ // A revert means the getter is missing (pre-upgrade ACL) and is safe to cache. Any other
371
+ // error (rate limit, timeout) is transient: return what we have but don't cache it.
372
+ let transient = false;
373
+ const readServedAddress = (functionName: 'defaultRevokerContract' | 'shareRegistry') =>
374
+ publicClient.readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName }).catch((err) => {
375
+ if (revertErrorName(err, ACL_SERVED_ADDRESSES_ABI) === undefined) transient = true;
376
+ return undefined;
377
+ });
378
+
370
379
  const [defaultRevoker, shareRegistry] = await Promise.all([
371
- publicClient
372
- .readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: 'defaultRevokerContract' })
373
- .catch(() => undefined),
374
- publicClient
375
- .readContract({ address: aclAddress, abi: ACL_SERVED_ADDRESSES_ABI, functionName: 'shareRegistry' })
376
- .catch(() => undefined),
380
+ readServedAddress('defaultRevokerContract'),
381
+ readServedAddress('shareRegistry'),
377
382
  ]);
378
383
 
379
384
  const resolved: AclServedAddresses = {
380
385
  defaultRevoker: defaultRevoker != null && defaultRevoker !== zeroAddress ? defaultRevoker : undefined,
381
386
  shareRegistry: shareRegistry != null && shareRegistry !== zeroAddress ? shareRegistry : undefined,
382
387
  };
383
- aclServedAddressesCache.set(chainId, resolved);
388
+ if (!transient) aclServedAddressesCache.set(chainId, resolved);
384
389
  return resolved;
385
390
  };
package/acps/sealing.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import nacl from 'tweetnacl';
2
2
  import { type Hex } from 'viem';
3
3
  import { fromHexString, toBeArray, toBigInt, toHexString, isBigIntOrNumber, isString } from './utils.js';
4
+ import { CofheError, CofheErrorCode } from '../core/error.js';
4
5
 
5
6
  /** 32-byte X25519 keys as bare hex (no 0x prefix) */
6
7
  const KEY_HEX_LENGTH = 64;
@@ -74,9 +75,28 @@ export const unsealWithPrivateKey = (privateKey: string, parsedData: EthEncrypte
74
75
  parsedData.public_key instanceof Uint8Array ? parsedData.public_key : new Uint8Array(parsedData.public_key);
75
76
  const dataToDecrypt = parsedData.data instanceof Uint8Array ? parsedData.data : new Uint8Array(parsedData.data);
76
77
 
77
- const decryptedMessage = nacl.box.open(dataToDecrypt, nonce, ephemPublicKey, fromHexString(privateKey));
78
+ // nacl returns null for a wrong key or tampered payload and throws on malformed inputs. Either way it
79
+ // is a CofheError, so callers that stop retrying on those (e.g. `useCofheDecrypt`) do not re-request.
80
+ let decryptedMessage: Uint8Array | null;
81
+ let cause: Error | undefined;
82
+ try {
83
+ decryptedMessage = nacl.box.open(dataToDecrypt, nonce, ephemPublicKey, fromHexString(privateKey));
84
+ } catch (e) {
85
+ decryptedMessage = null;
86
+ cause = e instanceof Error ? e : undefined;
87
+ }
78
88
  if (!decryptedMessage) {
79
- throw new Error('Failed to decrypt message');
89
+ // Lengths only: the context must not carry the private key or any sealing material.
90
+ throw new CofheError({
91
+ code: CofheErrorCode.SealOutputFailed,
92
+ message: 'Failed to unseal decrypt response',
93
+ cause,
94
+ context: {
95
+ dataLength: dataToDecrypt.length,
96
+ nonceLength: nonce.length,
97
+ publicKeyLength: ephemPublicKey.length,
98
+ },
99
+ });
80
100
  }
81
101
 
82
102
  return toBigInt(decryptedMessage);
@@ -0,0 +1,65 @@
1
+ import { ContractFunctionRevertedError, HttpRequestError, parseAbi } from 'viem';
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ import { clearTaskManagerAddressCache } from '../../core/taskManager.js';
5
+ import { clearAclServedAddresses, getAclServedAddresses } from '../onchain-utils.js';
6
+
7
+ const CHAIN_ID = 421614;
8
+ const TASK_MANAGER = '0x0000000000000000000000000000000000005000';
9
+ const ACL = '0x00000000000000000000000000000000000000dd';
10
+ const REVOKER = '0x00000000000000000000000000000000000000cc';
11
+ const REGISTRY = '0x00000000000000000000000000000000000000ee';
12
+
13
+ const GETTERS_ABI = parseAbi([
14
+ 'function defaultRevokerContract() view returns (address)',
15
+ 'function shareRegistry() view returns (address)',
16
+ ]);
17
+
18
+ function clientWithGetters(getter: (functionName: string) => Promise<unknown>) {
19
+ return {
20
+ readContract: vi.fn(async ({ functionName }: { functionName: string }) => {
21
+ if (functionName === 'getTm') return TASK_MANAGER;
22
+ if (functionName === 'acl') return ACL;
23
+ return getter(functionName);
24
+ }),
25
+ } as any;
26
+ }
27
+
28
+ describe('getAclServedAddresses', () => {
29
+ beforeEach(() => {
30
+ clearAclServedAddresses();
31
+ clearTaskManagerAddressCache();
32
+ });
33
+
34
+ it('does not cache a transient failure of the ACL getters', async () => {
35
+ let down = true;
36
+ const publicClient = clientWithGetters(async (functionName) => {
37
+ if (down) throw new HttpRequestError({ url: 'http://rpc', status: 429 });
38
+ return functionName === 'defaultRevokerContract' ? REVOKER : REGISTRY;
39
+ });
40
+
41
+ expect(await getAclServedAddresses(publicClient, CHAIN_ID)).toEqual({
42
+ defaultRevoker: undefined,
43
+ shareRegistry: undefined,
44
+ });
45
+
46
+ down = false;
47
+ expect(await getAclServedAddresses(publicClient, CHAIN_ID)).toEqual({
48
+ defaultRevoker: REVOKER,
49
+ shareRegistry: REGISTRY,
50
+ });
51
+ });
52
+
53
+ it('caches a pre-upgrade ACL whose getters revert', async () => {
54
+ const publicClient = clientWithGetters(async (functionName) => {
55
+ throw new ContractFunctionRevertedError({ abi: GETTERS_ABI, functionName, data: '0x' });
56
+ });
57
+
58
+ const expected = { defaultRevoker: undefined, shareRegistry: undefined };
59
+ expect(await getAclServedAddresses(publicClient, CHAIN_ID)).toEqual(expected);
60
+ const calls = publicClient.readContract.mock.calls.length;
61
+
62
+ expect(await getAclServedAddresses(publicClient, CHAIN_ID)).toEqual(expected);
63
+ expect(publicClient.readContract.mock.calls.length).toBe(calls);
64
+ });
65
+ });
@@ -1,5 +1,6 @@
1
1
  import { describe, it, expect } from 'vitest';
2
2
  import { GenerateSealingKey, seal, unsealWithPrivateKey } from '../index.js';
3
+ import { CofheError, CofheErrorCode } from '../../core/error.js';
3
4
 
4
5
  describe('seal / unsealWithPrivateKey', () => {
5
6
  it('should seal data into EthEncryptedData shape', () => {
@@ -80,6 +81,56 @@ describe('seal / unsealWithPrivateKey', () => {
80
81
  seal('not a number', publicKey);
81
82
  }).toThrow('Value not a number is not a number or bigint: string');
82
83
  });
84
+
85
+ describe('unseal failures are CofheErrors', () => {
86
+ const expectUnsealFailed = (fn: () => unknown, secrets: string[] = []) => {
87
+ let thrown: unknown;
88
+ try {
89
+ fn();
90
+ } catch (e) {
91
+ thrown = e;
92
+ }
93
+ expect(thrown).toBeInstanceOf(CofheError);
94
+ expect((thrown as CofheError).code).toBe(CofheErrorCode.SealOutputFailed);
95
+ const serialized = (thrown as CofheError).serialize();
96
+ for (const secret of secrets) expect(serialized).not.toContain(secret.replace(/^0x/, ''));
97
+ };
98
+
99
+ it('throws SealOutputFailed when unsealing with the wrong private key', () => {
100
+ const pair = GenerateSealingKey();
101
+ const other = GenerateSealingKey();
102
+ const sealed = seal(BigInt(42), pair.publicKey);
103
+
104
+ expectUnsealFailed(() => unsealWithPrivateKey(other.privateKey, sealed), [other.privateKey, pair.privateKey]);
105
+ });
106
+
107
+ it('throws SealOutputFailed when the sealed payload is corrupted', () => {
108
+ const pair = GenerateSealingKey();
109
+ const sealed = seal(BigInt(42), pair.publicKey);
110
+ const corrupted = { ...sealed, data: Uint8Array.from(sealed.data) };
111
+ corrupted.data[0] ^= 0xff;
112
+
113
+ expectUnsealFailed(() => unsealWithPrivateKey(pair.privateKey, corrupted), [pair.privateKey]);
114
+ });
115
+
116
+ it('throws SealOutputFailed, keeping the cause, when nacl rejects malformed inputs', () => {
117
+ const pair = GenerateSealingKey();
118
+ const sealed = seal(BigInt(42), pair.publicKey);
119
+ const shortNonce = { ...sealed, nonce: sealed.nonce.slice(0, 4) };
120
+
121
+ expectUnsealFailed(() => unsealWithPrivateKey(pair.privateKey, shortNonce), [pair.privateKey]);
122
+ try {
123
+ unsealWithPrivateKey(pair.privateKey, shortNonce);
124
+ } catch (e) {
125
+ expect((e as CofheError).cause).toBeInstanceOf(Error);
126
+ }
127
+ });
128
+
129
+ it('still reports a malformed sealing key as a plain key error, not a seal failure', () => {
130
+ const sealed = seal(BigInt(1), GenerateSealingKey().publicKey);
131
+ expect(() => unsealWithPrivateKey('deadbeef', sealed)).toThrow('Private key must be of length 64');
132
+ });
133
+ });
83
134
  });
84
135
 
85
136
  describe('GenerateSealingKey', () => {
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-3L2IVPMI.js';
2
+ import './chunk-J23FYAI2.js';
@@ -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-J23FYAI2.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 { 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-3L2IVPMI.js';
3
+ import { sleep, getPublicClientChainID, getWalletClientAccount, validateBigIntInRange, toBigIntOrThrow, hexToBytes, toHexString, FheUintUTypes } from './chunk-WJGTPW7K.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-J23FYAI2.js';
5
5
  import { createStore } from 'zustand/vanilla';
6
6
  import { parseAbi, isAddressEqual, zeroAddress, recoverAddress, encodePacked, keccak256, createWalletClient, http, getAddress, parseSignature, serializeSignature } from 'viem';
7
7
  import { hardhat } from 'viem/chains';
@@ -1,4 +1,4 @@
1
- import { CofheError } from './chunk-XQ32JG3T.js';
1
+ import { CofheError } from './chunk-J23FYAI2.js';
2
2
  import 'viem';
3
3
 
4
4
  // core/types.ts
@@ -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>;