@zama-fhe/sdk 3.3.0 → 3.3.1-alpha.2

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 (119) hide show
  1. package/README.md +0 -2
  2. package/dist/cjs/base-signer.cjs +1 -1
  3. package/dist/cjs/base-signer.cjs.map +1 -1
  4. package/dist/cjs/chains.cjs +1 -1
  5. package/dist/cjs/chains.cjs.map +1 -1
  6. package/dist/cjs/cleartext/index.cjs +1 -1
  7. package/dist/cjs/cleartext.cjs +2 -0
  8. package/dist/cjs/cleartext.cjs.map +1 -0
  9. package/dist/cjs/ethers/index.cjs.map +1 -1
  10. package/dist/cjs/fhevm-relayer.cjs +2 -0
  11. package/dist/cjs/fhevm-relayer.cjs.map +1 -0
  12. package/dist/cjs/index.cjs +1 -1
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/node/index.cjs +2 -0
  15. package/dist/cjs/node/index.cjs.map +1 -0
  16. package/dist/cjs/query/index.cjs +1 -1
  17. package/dist/cjs/query/index.cjs.map +1 -1
  18. package/dist/cjs/relayer.cjs +1 -1
  19. package/dist/cjs/relayer.cjs.map +1 -1
  20. package/dist/cjs/token.cjs +1 -1
  21. package/dist/cjs/token.cjs.map +1 -1
  22. package/dist/cjs/viem/index.cjs +1 -1
  23. package/dist/cjs/viem/index.cjs.map +1 -1
  24. package/dist/cjs/web/index.cjs +1 -590
  25. package/dist/cjs/web/index.cjs.map +1 -1
  26. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  27. package/dist/esm/base-signer-CI-FYai2.js +2 -0
  28. package/dist/esm/base-signer-CI-FYai2.js.map +1 -0
  29. package/dist/esm/{base-signer-C3Wc5oi9.d.ts → base-signer-Q2EJECrc.d.ts} +2 -2
  30. package/dist/esm/chains/index.d.ts +2 -3
  31. package/dist/esm/chains/index.js +1 -1
  32. package/dist/esm/chains-CLv9HEJ_.js +2 -0
  33. package/dist/esm/chains-CLv9HEJ_.js.map +1 -0
  34. package/dist/esm/cleartext/index.d.ts +3 -2
  35. package/dist/esm/cleartext/index.js +1 -1
  36. package/dist/esm/cleartext-BfXTVQu-.js +2 -0
  37. package/dist/esm/cleartext-BfXTVQu-.js.map +1 -0
  38. package/dist/esm/cleartext-U6sPs_Kd.d.ts +19 -0
  39. package/dist/esm/ethers/index.d.ts +4 -5
  40. package/dist/esm/ethers/index.js +1 -1
  41. package/dist/esm/ethers/index.js.map +1 -1
  42. package/dist/esm/fhevm-relayer-B-lEKfPQ.js +2 -0
  43. package/dist/esm/fhevm-relayer-B-lEKfPQ.js.map +1 -0
  44. package/dist/esm/index-BnIp_-Ak.d.ts +328 -0
  45. package/dist/esm/{index-CYBH0nyo.d.ts → index-D66eC3G7.d.ts} +60 -13
  46. package/dist/esm/index.d.ts +8 -11
  47. package/dist/esm/index.js +1 -1
  48. package/dist/esm/index.js.map +1 -1
  49. package/dist/esm/node/index.d.ts +5 -194
  50. package/dist/esm/node/index.js +1 -1
  51. package/dist/esm/node/index.js.map +1 -1
  52. package/dist/esm/query/index.d.ts +3 -380
  53. package/dist/esm/query/index.js +1 -1
  54. package/dist/esm/query/index.js.map +1 -1
  55. package/dist/esm/relayer-BYq9bLh8.js +2 -0
  56. package/dist/esm/relayer-BYq9bLh8.js.map +1 -0
  57. package/dist/esm/token-CmHTAAWW.js +2 -0
  58. package/dist/esm/token-CmHTAAWW.js.map +1 -0
  59. package/dist/esm/{types-piBsdTIP.d.ts → types-Bov8XY36.d.ts} +3 -3
  60. package/dist/esm/{types-OHIaPwCy.d.ts → types-BpvL50qX.d.ts} +3 -3
  61. package/dist/esm/types-C-WTLcHZ.d.ts +988 -0
  62. package/dist/esm/viem/index.d.ts +4 -5
  63. package/dist/esm/viem/index.js +1 -1
  64. package/dist/esm/viem/index.js.map +1 -1
  65. package/dist/esm/web/index.d.ts +6 -9
  66. package/dist/esm/web/index.js +1 -590
  67. package/dist/esm/web/index.js.map +1 -1
  68. package/dist/esm/{wrappers-registry-C1oK8Bi6.js → wrappers-registry-xZWzyAi4.js} +2 -2
  69. package/dist/esm/wrappers-registry-xZWzyAi4.js.map +1 -0
  70. package/dist/esm/{index-C1Mtc8Rw.d.ts → zama-sdk-q4_qt64Q.d.ts} +1471 -1102
  71. package/package.json +6 -2
  72. package/dist/cjs/assertions.cjs +0 -2
  73. package/dist/cjs/assertions.cjs.map +0 -1
  74. package/dist/cjs/encryption.cjs +0 -2
  75. package/dist/cjs/encryption.cjs.map +0 -1
  76. package/dist/cjs/relayer-cleartext.cjs +0 -2
  77. package/dist/cjs/relayer-cleartext.cjs.map +0 -1
  78. package/dist/cjs/relayer-sdk.worker.js +0 -589
  79. package/dist/cjs/timeout.cjs +0 -2
  80. package/dist/cjs/timeout.cjs.map +0 -1
  81. package/dist/cjs/validation.cjs +0 -2
  82. package/dist/cjs/validation.cjs.map +0 -1
  83. package/dist/esm/assertions-zYseN5Xz.js +0 -2
  84. package/dist/esm/assertions-zYseN5Xz.js.map +0 -1
  85. package/dist/esm/base-signer-DjytqPkd.js +0 -2
  86. package/dist/esm/base-signer-DjytqPkd.js.map +0 -1
  87. package/dist/esm/chains-CXcO1DBP.js +0 -2
  88. package/dist/esm/chains-CXcO1DBP.js.map +0 -1
  89. package/dist/esm/cleartext-DAkOTlrE.d.ts +0 -19
  90. package/dist/esm/cleartext-rTWFctyd.js +0 -2
  91. package/dist/esm/cleartext-rTWFctyd.js.map +0 -1
  92. package/dist/esm/encryption-x4Z_Icqk.js +0 -2
  93. package/dist/esm/encryption-x4Z_Icqk.js.map +0 -1
  94. package/dist/esm/hex-A72GrTf9.js +0 -2
  95. package/dist/esm/hex-A72GrTf9.js.map +0 -1
  96. package/dist/esm/indexeddb-storage-Mi-fCWN3.js +0 -2
  97. package/dist/esm/indexeddb-storage-Mi-fCWN3.js.map +0 -1
  98. package/dist/esm/memory-storage-fp9RY5BQ.js +0 -2
  99. package/dist/esm/memory-storage-fp9RY5BQ.js.map +0 -1
  100. package/dist/esm/node/relayer-sdk.node-worker.d.ts +0 -1
  101. package/dist/esm/node/relayer-sdk.node-worker.js +0 -2
  102. package/dist/esm/node/relayer-sdk.node-worker.js.map +0 -1
  103. package/dist/esm/relayer-cleartext-Bp6jtxDd.js +0 -2
  104. package/dist/esm/relayer-cleartext-Bp6jtxDd.js.map +0 -1
  105. package/dist/esm/relayer-cleartext-CSeMlmGO.d.ts +0 -844
  106. package/dist/esm/relayer-eavK5bfZ.js +0 -2
  107. package/dist/esm/relayer-eavK5bfZ.js.map +0 -1
  108. package/dist/esm/relayer-sdk.worker.js +0 -589
  109. package/dist/esm/timeout-CNVfiaJD.js +0 -2
  110. package/dist/esm/timeout-CNVfiaJD.js.map +0 -1
  111. package/dist/esm/token-Bt33g0zQ.js +0 -2
  112. package/dist/esm/token-Bt33g0zQ.js.map +0 -1
  113. package/dist/esm/types-BgczXqW2.d.ts +0 -49
  114. package/dist/esm/types-Gn5MeDsr.d.ts +0 -669
  115. package/dist/esm/validation-DLszOweh.js +0 -2
  116. package/dist/esm/validation-DLszOweh.js.map +0 -1
  117. package/dist/esm/worker.base-client-BVnT4yJa.js +0 -2
  118. package/dist/esm/worker.base-client-BVnT4yJa.js.map +0 -1
  119. package/dist/esm/wrappers-registry-C1oK8Bi6.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zama-fhe/sdk",
3
- "version": "3.3.0",
3
+ "version": "3.3.1-alpha.2",
4
4
  "description": "TypeScript SDK for Zama fhEVM confidential smart contracts",
5
5
  "keywords": [
6
6
  "blockchain",
@@ -134,6 +134,10 @@
134
134
  "types": "./dist/esm/node/index.d.ts",
135
135
  "default": "./dist/esm/node/index.js"
136
136
  },
137
+ "require": {
138
+ "types": "./dist/esm/node/index.d.ts",
139
+ "default": "./dist/cjs/node/index.cjs"
140
+ },
137
141
  "default": "./dist/esm/node/index.js"
138
142
  },
139
143
  "./chains": {
@@ -162,7 +166,7 @@
162
166
  "api-report:check": "api-extractor run -c api-extractor.json && api-extractor run -c api-extractor.web.json && api-extractor run -c api-extractor.viem.json && api-extractor run -c api-extractor.ethers.json && api-extractor run -c api-extractor.node.json && api-extractor run -c api-extractor.query.json"
163
167
  },
164
168
  "dependencies": {
165
- "@zama-fhe/relayer-sdk": "~0.4.4",
169
+ "@fhevm/sdk": "1.1.0-alpha.8",
166
170
  "viem": ">=2",
167
171
  "zod": ">=4"
168
172
  },
@@ -1,2 +0,0 @@
1
- function e(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function t(e){if(!(e instanceof Error))return!1;if(e.name===`ContractFunctionExecutionError`||e.name===`ContractFunctionRevertedError`||`code`in e&&e.code===`CALL_EXCEPTION`)return!0;let t=e.message.toLowerCase();return t.includes(`execution reverted`)||t.includes(`call revert exception`)}const n=[`cause`,`error`,`info`];function r(e,t,i=6){if(i<0||typeof e!=`object`||!e)return;let a=e;if(t(a))return a;for(let e of n){let n=a[e];if(typeof n==`object`&&n){let e=r(n,t,i-1);if(e)return e}}}const i=[`code`,`status`,`statusCode`,`retryAfter`];function a(e){let t=Error(e.message);e.name&&(t.name=e.name);for(let n of i){let r=e[n];r!==void 0&&(t[n]=r)}return e.responseStatus!==void 0&&(t.info={responseStatus:e.responseStatus}),e.cause&&(t.cause=a(e.cause)),t}function o(e){if(e.code===-32005||e.status===429||e.code===429)return!0;if(e.code===`SERVER_ERROR`&&typeof e.info==`object`&&e.info!==null){let t=e.info.responseStatus;if(typeof t==`string`&&/^\s*429\b/.test(t))return!0}return!1}function s(e){if(o(e))return!0;if(typeof e.message==`string`){let t=e.message.toLowerCase();return t.includes(`too many requests`)||t.includes(`rate limit`)||t.includes(`rate-limit`)}return!1}function c(e){return r(e,e=>e.code===`RELAYER_FETCH_ERROR`)!==void 0}function l(e){return c(e)?!1:r(e,s)!==void 0}function u(e){return c(e)?!1:r(e,o)!==void 0}function d(e){let t=e.code;if(t===`NETWORK_ERROR`||t===`SERVER_ERROR`||t===`TIMEOUT`)return!0;let n=e.name;return n===`HttpRequestError`||n===`RpcRequestError`||n===`TimeoutError`||n===`WebSocketRequestError`}function f(e){return c(e)?!1:u(e)?!0:r(e,d)!==void 0}function p(e){if(!(e instanceof Error)||f(e))return!1;if(r(e,e=>e.code===`RELAYER_FETCH_ERROR`&&(e.status===502||e.status===503||e.status===504)))return!0;let t=e.message.toLowerCase();return t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`socket hang up`)||t.includes(`fetch failed`)||t.includes(`network`)}function m(e){let t=e.toLowerCase();return t.includes(`user address`)&&t.includes(`is not authorized to user decrypt`)}function h(e){return/handle (0x[0-9a-fA-F]{64})/.exec(e)?.[1]}function g(e){if(e==null)return;let t=e.trim();if(t!==``){if(/^\d+$/.test(t))return Number(t);if(/[a-zA-Z]/.test(t)){let e=Date.parse(t);if(!Number.isNaN(e))return Math.max(0,Math.round((e-Date.now())/1e3))}}}function _(e){if(typeof e!=`object`||!e)return;let t=e.get;if(typeof t==`function`)return g(t.call(e,`Retry-After`))}function v(e){let t=e.response;if(typeof t==`object`&&t)return _(t.headers)}function y(e){return typeof e.retryAfter==`number`&&Number.isFinite(e.retryAfter)&&e.retryAfter>0?e.retryAfter:v(e)}function b(e){let t=r(e,e=>y(e)!==void 0);return t?y(t):void 0}function x(e){let t=r(e,e=>typeof e.statusCode==`number`||typeof e.status==`number`);if(t)return typeof t.statusCode==`number`?t.statusCode:t.status}function S(e,t){if(e==null)throw TypeError(`${t} must not be null or undefined`)}function C(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${t} must be an object, got ${typeof e}`)}function w(e,t){if(typeof e!=`string`)throw TypeError(`${t} must be a string, got ${typeof e}`)}function T(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function, got ${typeof e}`)}function E(e,t){if(typeof e!=`bigint`)throw TypeError(`${t} must be a bigint, got ${typeof e}`)}function D(e,t,n){w(e[t],n)}function O(e,t,n){T(e[t],n)}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return t}});
2
- //# sourceMappingURL=assertions.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"assertions.cjs","names":[],"sources":["../../src/utils/error.ts","../../src/utils/assertions.ts"],"sourcesContent":["/** Coerce an unknown caught value to an Error instance. */\nexport function toError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n return new Error(String(error.message));\n }\n return new Error(String(error));\n}\n\n/**\n * Returns true if the error is a contract call revert (as opposed to a network/transport error).\n * Detects viem's ContractFunctionExecutionError / ContractFunctionRevertedError\n * and ethers' CALL_EXCEPTION.\n */\nexport function isContractCallError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n // viem: ContractFunctionExecutionError, ContractFunctionRevertedError\n if (\n error.name === \"ContractFunctionExecutionError\" ||\n error.name === \"ContractFunctionRevertedError\"\n ) {\n return true;\n }\n // ethers: error.code === \"CALL_EXCEPTION\"\n if (\"code\" in error && error.code === \"CALL_EXCEPTION\") {\n return true;\n }\n // Fallback: common revert message patterns from various providers\n const msg = error.message.toLowerCase();\n return msg.includes(\"execution reverted\") || msg.includes(\"call revert exception\");\n}\n\n/** JSON-RPC error code providers use for rate limiting (\"limit exceeded\"). */\nconst JSON_RPC_LIMIT_EXCEEDED = -32005;\n\n/** Properties that may nest a lower-level cause across viem / ethers / fetch. */\nconst NESTED_ERROR_KEYS = [\"cause\", \"error\", \"info\"] as const;\n\n/**\n * Walk an error and its nested causes (`cause` / `error` / `info`, as used by\n * viem, ethers, and fetch wrappers), applying `predicate` to each object node.\n * Returns the first node for which `predicate` returns true, or `undefined`.\n * Depth-bounded to avoid pathological / cyclic structures.\n */\nfunction findInErrorChain(\n error: unknown,\n predicate: (node: Record<string, unknown>) => boolean,\n depth = 6,\n): Record<string, unknown> | undefined {\n if (depth < 0 || error === null || error === undefined || typeof error !== \"object\") {\n return undefined;\n }\n const node = error as Record<string, unknown>;\n if (predicate(node)) {\n return node;\n }\n for (const key of NESTED_ERROR_KEYS) {\n const next = node[key];\n if (next !== undefined && next !== null && typeof next === \"object\") {\n const found = findInErrorChain(next, predicate, depth - 1);\n if (found) {\n return found;\n }\n }\n }\n return undefined;\n}\n\n// ============================================================================\n// Cross-thread serialization\n// ============================================================================\n\n/**\n * A plain, structured-clone-safe snapshot of an error and its cause chain.\n *\n * The worker boundary (`postMessage`) strips prototypes, `code`/`status`, and —\n * critically — the `cause` chain, leaving only the message. Decryption errors\n * are classified on the **main thread** ({@link wrapDecryptError}), so the worker\n * only needs to faithfully hand the error across the boundary, not understand it.\n * `serializeError` is that mechanical, taxonomy-agnostic envelope: it copies the\n * scalar signal fields the classifier keys on and flattens the nested cause chain\n * into a single `cause` link. {@link deserializeError} rebuilds an `Error` whose\n * `.cause` chain mirrors the original, so the existing chain-walking detectors\n * work on it unchanged.\n */\nexport interface SerializedError {\n name: string;\n message: string;\n /** e.g. JSON-RPC -32005, \"RELAYER_FETCH_ERROR\", ethers \"CALL_EXCEPTION\". */\n code?: string | number;\n /** viem-style HTTP status. */\n status?: number;\n /** relayer / node-fetch-style HTTP status. */\n statusCode?: number;\n /** Server-driven retry delay in **seconds** (numeric prop or parsed `Retry-After`). */\n retryAfter?: number;\n /**\n * ethers surfaces an HTTP status only as a string on `info.responseStatus`\n * (e.g. `\"429 Too Many Requests\"`), not as a numeric `status`. It lives on a\n * nested `info` object the flattening would otherwise skip, so it is lifted\n * onto the envelope and rebuilt onto `error.info.responseStatus`, letting the\n * ethers rate-limit detector classify a worker-origin 429 exactly as it would\n * the same error on the main thread.\n */\n responseStatus?: string;\n cause?: SerializedError;\n}\n\n/** Scalar signal fields carried verbatim across the boundary, in both directions. */\nconst SERIALIZED_SCALAR_KEYS = [\"code\", \"status\", \"statusCode\", \"retryAfter\"] as const;\n\n/**\n * ethers reports its HTTP status only as a string on `info.responseStatus`\n * (e.g. `\"429 Too Many Requests\"`). Read it directly off the node — not via the\n * cause-chain flattening, which descends a single branch — so it survives even\n * when the error also carries an `error` link that would be walked first.\n */\nfunction responseStatusFromNode(node: Record<string, unknown>): string | undefined {\n const info = node.info;\n if (info !== null && typeof info === \"object\") {\n const responseStatus = (info as Record<string, unknown>).responseStatus;\n if (typeof responseStatus === \"string\") {\n return responseStatus;\n }\n }\n return undefined;\n}\n\n/**\n * Copy the scalar signal fields the classifier keys on from a raw error node\n * onto the envelope, only where not already set — so a shallower node keeps\n * priority. Also lifts ethers' string `info.responseStatus` and the relayer's\n * `Retry-After` header (both destroyed by structured clone: the header lives on\n * a non-cloneable `Headers`, the status on a nested `info` the flattening skips).\n */\nfunction captureNodeSignals(node: Record<string, unknown>, into: SerializedError): void {\n if (into.code === undefined && (typeof node.code === \"string\" || typeof node.code === \"number\")) {\n into.code = node.code;\n }\n if (into.status === undefined && typeof node.status === \"number\") {\n into.status = node.status;\n }\n if (into.statusCode === undefined && typeof node.statusCode === \"number\") {\n into.statusCode = node.statusCode;\n }\n if (into.responseStatus === undefined) {\n const responseStatus = responseStatusFromNode(node);\n if (responseStatus !== undefined) {\n into.responseStatus = responseStatus;\n }\n }\n if (into.retryAfter === undefined) {\n if (typeof node.retryAfter === \"number\") {\n into.retryAfter = node.retryAfter;\n } else {\n const fromHeader = retryAfterFromHeader(node);\n if (fromHeader !== undefined) {\n into.retryAfter = fromHeader;\n }\n }\n }\n}\n\n/** Lift any still-missing scalar signal from an already-serialized child up. */\nfunction hoistMissingSignals(from: SerializedError, into: SerializedError): void {\n if (into.code === undefined && from.code !== undefined) {\n into.code = from.code;\n }\n if (into.status === undefined && from.status !== undefined) {\n into.status = from.status;\n }\n if (into.statusCode === undefined && from.statusCode !== undefined) {\n into.statusCode = from.statusCode;\n }\n if (into.responseStatus === undefined && from.responseStatus !== undefined) {\n into.responseStatus = from.responseStatus;\n }\n if (into.retryAfter === undefined && from.retryAfter !== undefined) {\n into.retryAfter = from.retryAfter;\n }\n}\n\n/**\n * Flatten an error (and its `cause` / `error` / `info` chain) into a\n * structured-clone-safe {@link SerializedError}. Depth-bounded to mirror\n * {@link findInErrorChain} and guard against cyclic structures.\n */\nexport function serializeError(error: unknown, depth = 6): SerializedError {\n const coerced = toError(error);\n const node =\n typeof error === \"object\" && error !== null\n ? (error as Record<string, unknown>)\n : (coerced as unknown as Record<string, unknown>);\n\n const serialized: SerializedError = { name: coerced.name, message: coerced.message };\n captureNodeSignals(node, serialized);\n\n if (depth > 0) {\n // Walk *every* nested link (`cause` / `error` / `info`), not just the first\n // present one: an error commonly carries several (ethers puts the underlying\n // fault on `error` and the HTTP status on `info`), and the signal-bearing\n // branch is not always the first. Keep the first as the representative\n // `.cause` for message/chain fidelity, and lift any still-missing scalar\n // signal off the others so none is dropped.\n for (const key of NESTED_ERROR_KEYS) {\n const next = node[key];\n if (next !== undefined && next !== null && typeof next === \"object\") {\n const child = serializeError(next, depth - 1);\n if (serialized.cause === undefined) {\n serialized.cause = child;\n }\n hoistMissingSignals(child, serialized);\n }\n }\n }\n\n return serialized;\n}\n\n/**\n * Rebuild a real {@link Error} from a {@link SerializedError}, re-attaching the\n * scalar signal fields and reconstructing the `.cause` chain so chain-walking\n * detectors ({@link findInErrorChain}, {@link extractHttpStatus},\n * {@link isRpcRateLimitError}) operate on it exactly as on the original.\n */\nexport function deserializeError(serialized: SerializedError): Error {\n const error = new Error(serialized.message) as Error & Record<string, unknown>;\n if (serialized.name) {\n error.name = serialized.name;\n }\n for (const key of SERIALIZED_SCALAR_KEYS) {\n const value = serialized[key];\n if (value !== undefined) {\n error[key] = value;\n }\n }\n // Rebuild ethers' `info.responseStatus` on the same node as its `code`, so the\n // ethers rate-limit detector (`code: \"SERVER_ERROR\"` + `info.responseStatus`)\n // matches the round-tripped error exactly as it would the original.\n if (serialized.responseStatus !== undefined) {\n error.info = { responseStatus: serialized.responseStatus };\n }\n if (serialized.cause) {\n error.cause = deserializeError(serialized.cause);\n }\n return error;\n}\n\n// ============================================================================\n// Classification detectors (main-thread)\n// ============================================================================\n\n/**\n * Structured (unambiguous) consumer rate-limit signal across the RPC providers\n * the SDK reads through:\n * - JSON-RPC `-32005` (\"limit exceeded\");\n * - viem-style numeric `status: 429`, and viem's own `shouldRetry` shape where\n * the JSON-RPC error `code` is `429`;\n * - ethers' 429, which surfaces as `code: \"SERVER_ERROR\"` with the status only\n * in `info.responseStatus` (a string like `\"429 Too Many Requests\"`) and no\n * numeric top-level status — the leading code is parsed out of it.\n *\n * Deliberately NOT `statusCode: 429` — that is the relayer / node-fetch HTTP\n * shape, which stays {@link RelayerRequestFailedError} (SDK-236), so a relayer\n * 429 is never mistaken for a consumer-RPC throttle.\n */\nfunction nodeHasStructuredRateLimit(node: Record<string, unknown>): boolean {\n if (node.code === JSON_RPC_LIMIT_EXCEEDED || node.status === 429 || node.code === 429) {\n return true;\n }\n // ethers: `code: \"SERVER_ERROR\"`, status lives in `info.responseStatus`.\n if (node.code === \"SERVER_ERROR\" && typeof node.info === \"object\" && node.info !== null) {\n const responseStatus = (node.info as Record<string, unknown>).responseStatus;\n if (typeof responseStatus === \"string\" && /^\\s*429\\b/.test(responseStatus)) {\n return true;\n }\n }\n return false;\n}\n\nfunction nodeIsRpcRateLimit(node: Record<string, unknown>): boolean {\n if (nodeHasStructuredRateLimit(node)) {\n return true;\n }\n // Message fallback for providers without a structured code. Deliberately\n // narrow (specific throttling phrases, no bare \"429\") to avoid false positives\n // that would turn a terminal error into a retryable one.\n if (typeof node.message === \"string\") {\n const msg = node.message.toLowerCase();\n return (\n msg.includes(\"too many requests\") || msg.includes(\"rate limit\") || msg.includes(\"rate-limit\")\n );\n }\n return false;\n}\n\n/**\n * The relayer SDK tags its HTTP errors with `code: \"RELAYER_FETCH_ERROR\"`. These\n * stay the relayer's domain ({@link RelayerRequestFailedError} / SDK-236), never\n * {@link RpcRateLimitError}, even on a 429.\n */\nfunction isRelayerFetchError(error: unknown): boolean {\n return findInErrorChain(error, (node) => node.code === \"RELAYER_FETCH_ERROR\") !== undefined;\n}\n\n/**\n * True if the error is the consumer's RPC provider throttling an on-chain read\n * (HTTP 429 / JSON-RPC -32005). Relayer-originated 429s are excluded.\n */\nexport function isRpcRateLimitError(error: unknown): boolean {\n if (isRelayerFetchError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeIsRpcRateLimit) !== undefined;\n}\n\n/**\n * Like {@link isRpcRateLimitError} but only matches an unambiguous **structured**\n * signal (`-32005` or a viem `status: 429`), ignoring message text. The classifier\n * promotes this ahead of any HTTP status, while a message-only throttle is only\n * trusted when no status is present — so a relayer HTTP error whose body happens\n * to say \"rate limit\" still maps to {@link RelayerRequestFailedError}.\n */\nexport function hasStructuredRpcRateLimitSignal(error: unknown): boolean {\n if (isRelayerFetchError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeHasStructuredRateLimit) !== undefined;\n}\n\n/**\n * Transport-error signatures of the consumer's own RPC client (viem / ethers).\n * The worker's on-chain reads (the ACL `persistAllowed` pre-check) go through\n * that client, which already retries transport faults internally — so a failure\n * carrying one of these shapes must NOT be retried again by the SDK on top.\n */\nfunction nodeHasConsumerRpcSignature(node: Record<string, unknown>): boolean {\n // ethers transient transport codes.\n const code = node.code;\n if (code === \"NETWORK_ERROR\" || code === \"SERVER_ERROR\" || code === \"TIMEOUT\") {\n return true;\n }\n // viem transport error classes (the `name` survives the worker boundary).\n const name = node.name;\n return (\n name === \"HttpRequestError\" ||\n name === \"RpcRequestError\" ||\n name === \"TimeoutError\" ||\n name === \"WebSocketRequestError\"\n );\n}\n\n/**\n * True when a failure originates from the **consumer's RPC provider** (viem /\n * ethers) rather than the relayer. Keeps the SDK's relayer retry from\n * double-retrying transport faults the integrator's client already retried.\n * A relayer HTTP error (`RELAYER_FETCH_ERROR`) is never consumer-RPC.\n */\nexport function isConsumerRpcError(error: unknown): boolean {\n if (isRelayerFetchError(error)) {\n return false;\n }\n if (hasStructuredRpcRateLimitSignal(error)) {\n return true;\n }\n return findInErrorChain(error, nodeHasConsumerRpcSignature) !== undefined;\n}\n\n/**\n * True only for transient faults attributable to the **relayer transport** — the\n * one network actor the SDK owns retries for, since viem/ethers don't model the\n * relayer. This is the single gate for {@link withRetry}.\n *\n * Two-tier retry model:\n * - **Relayer transport** (here): a relayer HTTP 502/503/504 — tagged\n * `RELAYER_FETCH_ERROR` with a gateway status — or a relayer-boundary network\n * failure (the relayer SDK uses bare `fetch`, so a transport error with no\n * viem/ethers signature is the relayer connection itself). Retried.\n * - **Consumer RPC** ({@link isConsumerRpcError}): deferred to viem/ethers, never\n * retried here. Timeouts are owned by viem/ethers and the worker-level\n * operation timeout (SDK-237), so they are not auto-retried at this layer.\n *\n * Relayer back-pressure (HTTP 429) is deliberately excluded: it is surfaced to\n * the caller as a retryable {@link RelayerRequestFailedError} with `retryAfter`,\n * not silently retried.\n */\nexport function isRetryableRelayerError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n if (isConsumerRpcError(error)) {\n return false;\n }\n // Relayer HTTP gateway transients (502/503/504), tagged by the relayer SDK.\n const relayerGatewayError = findInErrorChain(\n error,\n (n) =>\n n.code === \"RELAYER_FETCH_ERROR\" &&\n (n.status === 502 || n.status === 503 || n.status === 504),\n );\n if (relayerGatewayError) {\n return true;\n }\n // Relayer-boundary transport failure (no consumer-RPC signature above).\n const msg = error.message.toLowerCase();\n return (\n msg.includes(\"econnreset\") ||\n msg.includes(\"econnrefused\") ||\n msg.includes(\"socket hang up\") ||\n msg.includes(\"fetch failed\") ||\n msg.includes(\"network\")\n );\n}\n\n/**\n * The relayer SDK's ACL gate (`validateAclPermissions`) throws a message-only\n * Error when the actor isn't allowed: `User address <a> is not authorized to\n * user decrypt handle <h>!`. Matching it here, once, against the pinned\n * `@zama-fhe/relayer-sdk`, is what lets {@link wrapDecryptError} surface a typed\n * NotEntitledError (the \"dapp contract … is not authorized\" variant is a dapp\n * misconfig and is intentionally left to DecryptionFailedError).\n *\n * This is a deliberate bridge, not a destination: `@zama-fhe/relayer-sdk` ships\n * a typed `ACLUserDecryptionError`, but its active `userDecrypt` path still\n * throws a plain Error. TODO(SDK-239 follow-up): once the relayer surfaces the\n * typed/coded ACL error from that path, key off the code instead of the message\n * and drop this matcher. The `error.test.ts` guard reads the installed relayer\n * source and fails loudly if the message drifts before then.\n */\nexport function isNotEntitledMessage(message: string): boolean {\n const m = message.toLowerCase();\n return m.includes(\"user address\") && m.includes(\"is not authorized to user decrypt\");\n}\n\n/** Parse the on-chain handle out of the relayer's not-entitled message. */\nexport function parseHandleFromMessage(message: string): string | undefined {\n return /handle (0x[0-9a-fA-F]{64})/.exec(message)?.[1];\n}\n\n/**\n * Parse an HTTP `Retry-After` header value into **seconds** (the SDK's duration\n * unit and the header's own unit), or `undefined` when absent/unparseable. Per\n * RFC 9110 the value is either a non-negative number of seconds (`\"120\"`) or an\n * HTTP-date; a past date floors to `0`.\n */\nexport function parseRetryAfterHeader(value: string | null | undefined): number | undefined {\n if (value === null || value === undefined) {\n return undefined;\n }\n const trimmed = value.trim();\n if (trimmed === \"\") {\n return undefined;\n }\n // delta-seconds: a non-negative integer (already the unit we want).\n if (/^\\d+$/.test(trimmed)) {\n return Number(trimmed);\n }\n // HTTP-date — an IMF-fixdate always carries alphabetic day/month names, so\n // require a letter before deferring to the lenient Date.parse.\n if (/[a-zA-Z]/.test(trimmed)) {\n const dateMs = Date.parse(trimmed);\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, Math.round((dateMs - Date.now()) / 1000));\n }\n }\n return undefined;\n}\n\n/** Read a `Retry-After` header (→ seconds) off a `Headers`-like object, if present. */\nfunction readRetryAfterHeader(headers: unknown): number | undefined {\n if (headers === null || typeof headers !== \"object\") {\n return undefined;\n }\n const get = (headers as { get?: unknown }).get;\n if (typeof get !== \"function\") {\n return undefined;\n }\n return parseRetryAfterHeader(\n (get as (name: string) => string | null).call(headers, \"Retry-After\"),\n );\n}\n\n/**\n * A node's **relayer** `Retry-After` header (seconds), read from a wrapped fetch\n * `Response` (the relayer SDK's `cause.response.headers`). The SDK owns the\n * relayer fetch, so parsing the header there is legitimate.\n *\n * The viem/chain side (`HttpRequestError.headers`) is deliberately **not** read:\n * for consumer RPC the integrator's viem/ethers transport already honors\n * `Retry-After` in its own retry loop (and retries) before the error ever\n * surfaces, so re-reading it here would re-implement a transport concern.\n * Chain-RPC backoff is configured on the consumer's transport (`chain.network`).\n */\nfunction retryAfterFromHeader(node: Record<string, unknown>): number | undefined {\n const response = node.response;\n if (response !== null && typeof response === \"object\") {\n return readRetryAfterHeader((response as Record<string, unknown>).headers);\n }\n return undefined;\n}\n\n/**\n * A single node's server-driven retry delay (seconds): a numeric `retryAfter`\n * (a non-positive synthetic value is ignored), else a `Retry-After` header.\n */\nfunction retryAfterFromNode(node: Record<string, unknown>): number | undefined {\n if (\n typeof node.retryAfter === \"number\" &&\n Number.isFinite(node.retryAfter) &&\n node.retryAfter > 0\n ) {\n return node.retryAfter;\n }\n return retryAfterFromHeader(node);\n}\n\n/**\n * Best-effort extraction of a server-driven retry delay, in **seconds**, from\n * anywhere in an error's cause chain. Reads a numeric `retryAfter` property and\n * the **relayer's** `Retry-After` header (`cause.response.headers`). The\n * consumer-RPC/chain side is intentionally not read — viem/ethers own that\n * backoff (see {@link retryAfterFromHeader}). `undefined` when absent.\n */\nexport function extractRetryAfter(error: unknown): number | undefined {\n const node = findInErrorChain(error, (n) => retryAfterFromNode(n) !== undefined);\n return node ? retryAfterFromNode(node) : undefined;\n}\n\n/**\n * Extract an HTTP status code from an error or anywhere in its cause chain.\n * Relayer SDK errors may carry a `status` or `statusCode` property; walking the\n * full chain (rather than just depth-1) keeps this in step with the other\n * chain-walking detectors and avoids a depth asymmetry between them.\n */\nexport function extractHttpStatus(error: unknown): number | undefined {\n const node = findInErrorChain(\n error,\n (n) => typeof n.statusCode === \"number\" || typeof n.status === \"number\",\n );\n if (!node) {\n return undefined;\n }\n return (typeof node.statusCode === \"number\" ? node.statusCode : node.status) as number;\n}\n","export function assertNonNullable<T>(value: T, context: string): asserts value is NonNullable<T> {\n if (value === null || value === undefined) {\n throw new TypeError(`${context} must not be null or undefined`);\n }\n}\n\nexport function assertObject(\n value: unknown,\n context: string,\n): asserts value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${context} must be an object, got ${typeof value}`);\n }\n}\n\nexport function assertString(value: unknown, context: string): asserts value is string {\n if (typeof value !== \"string\") {\n throw new TypeError(`${context} must be a string, got ${typeof value}`);\n }\n}\n\nexport function assertArray(value: unknown, context: string): asserts value is unknown[] {\n if (!Array.isArray(value)) {\n throw new TypeError(`${context} must be an array, got ${typeof value}`);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport function assertFunction(value: unknown, context: string): asserts value is Function {\n if (typeof value !== \"function\") {\n throw new TypeError(`${context} must be a function, got ${typeof value}`);\n }\n}\n\nexport function assertBigint(value: unknown, context: string): asserts value is bigint {\n if (typeof value !== \"bigint\") {\n throw new TypeError(`${context} must be a bigint, got ${typeof value}`);\n }\n}\n\n/** Assert that `obj[key]` is a string. Narrows `obj` to include `{ [key]: string }`. */\nexport function assertStringProp<\n K extends string,\n O extends Record<string, unknown> = Record<string, unknown>,\n>(obj: O, key: K, context: string): asserts obj is O & Record<K, string> {\n assertString(obj[key], context);\n}\n\n/** Assert that `obj[key]` is a function. Narrows `obj` to include `{ [key]: F }`. */\nexport function assertFunctionProp<\n K extends string,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n F extends Function,\n O extends Record<string, unknown> = Record<string, unknown>,\n>(obj: O, key: K, context: string): asserts obj is O & Record<K, F> {\n assertFunction(obj[key], context);\n}\n\nexport function assertCondition(condition: boolean, message: string): asserts condition {\n if (!condition) {\n throw new TypeError(message);\n }\n}\n"],"mappings":"AACA,SAAgB,EAAQ,EAAuB,CAO7C,OANI,aAAiB,MACZ,EAEL,OAAO,GAAU,UAAY,GAAkB,YAAa,EACnD,MAAM,OAAO,EAAM,OAAO,CAAC,EAE7B,MAAM,OAAO,CAAK,CAAC,CAChC,CAOA,SAAgB,EAAoB,EAAyB,CAC3D,GAAI,EAAE,aAAiB,OACrB,MAAO,GAUT,GANE,EAAM,OAAS,kCACf,EAAM,OAAS,iCAKb,SAAU,GAAS,EAAM,OAAS,iBACpC,MAAO,GAGT,IAAM,EAAM,EAAM,QAAQ,YAAY,EACtC,OAAO,EAAI,SAAS,oBAAoB,GAAK,EAAI,SAAS,uBAAuB,CACnF,CAGA,MAGM,EAAoB,CAAC,QAAS,QAAS,MAAM,EAQnD,SAAS,EACP,EACA,EACA,EAAQ,EAC6B,CACrC,GAAI,EAAQ,GAA8C,OAAO,GAAU,WAA1D,EACf,OAEF,IAAM,EAAO,EACb,GAAI,EAAU,CAAI,EAChB,OAAO,EAET,IAAK,IAAM,KAAO,EAAmB,CACnC,IAAM,EAAO,EAAK,GAClB,GAA2C,OAAO,GAAS,UAAvD,EAAiE,CACnE,IAAM,EAAQ,EAAiB,EAAM,EAAW,EAAQ,CAAC,EACzD,GAAI,EACF,OAAO,CAEX,CACF,CAEF,CA2CA,MAAM,EAAyB,CAAC,OAAQ,SAAU,aAAc,YAAY,EAoH5E,SAAgB,EAAiB,EAAoC,CACnE,IA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AU,SACnB,MAAU,UAAU,GAAG,EAAQ,yBAAyB,OAAO,GAAO,CAE1E,CAGA,SAAgB,EAGd,EAAQ,EAAQ,EAAuD,CACvE,EAAa,EAAI,GAAM,CAAO,CAChC,CAGA,SAAgB,EAKd,EAAQ,EAAQ,EAAkD,CAClE,EAAe,EAAI,GAAM,CAAO,CAClC"}
@@ -1,2 +0,0 @@
1
- const e=require("./relayer.cjs");var t=class extends e.r{constructor(t,n){super(e.i.EncryptionFailed,t,n),this.name=`EncryptionFailedError`}},n=class extends e.r{constructor(t,n){super(e.i.DecryptionFailed,t,n),this.name=`DecryptionFailedError`}};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
2
- //# sourceMappingURL=encryption.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"encryption.cjs","names":["ZamaError","ZamaErrorCode"],"sources":["../../src/errors/encryption.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** FHE encryption failed. */\nexport class EncryptionFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.EncryptionFailed, message, options);\n this.name = \"EncryptionFailedError\";\n }\n}\n\n/** FHE decryption failed. */\nexport class DecryptionFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.DecryptionFailed, message, options);\n this.name = \"DecryptionFailedError\";\n }\n}\n"],"mappings":"iCAGA,IAAa,EAAb,cAA2CA,EAAAA,CAAU,CACnD,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAAAA,EAAc,iBAAkB,EAAS,CAAO,EACtD,KAAK,KAAO,uBACd,CACF,EAGa,EAAb,cAA2CD,EAAAA,CAAU,CACnD,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAAAA,EAAc,iBAAkB,EAAS,CAAO,EACtD,KAAK,KAAO,uBACd,CACF"}
@@ -1,2 +0,0 @@
1
- const e=require("./relayer.cjs"),t=require("./encryption.cjs");let n=require("viem/accounts"),r=require("viem"),i=require("viem/chains");var a=class extends e.r{encryptedValue;contractAddress;account;constructor(t,n){super(e.i.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}};const o=(e,t)=>({name:`InputVerification`,version:`1`,chainId:BigInt(e),verifyingContract:t}),s=(e,t)=>({name:`Decryption`,version:`1`,chainId:BigInt(e),verifyingContract:t}),c={domain:o,types:{CiphertextVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`userAddress`,type:`address`},{name:`contractAddress`,type:`address`},{name:`contractChainId`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},l={domain:s,types:{PublicDecryptVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`decryptedResult`,type:`bytes`},{name:`extraData`,type:`bytes`}]}},u={domain:s,types:{UserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},d={domain:s,types:{DelegatedUserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`delegatorAddress`,type:`address`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},f={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},p={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},m={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(f),Object.freeze(p),Object.freeze(m),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function h(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function g(e){return typeof e==`string`?e in f:!1}function _(e){if(!g(e))throw Error(`Invalid FheType name '${e}'`);return f[e]}function v(e){if(!h(e))throw Error(`Invalid FheType id '${e}'`);let t=m[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const y=(0,r.toBytes)(`ZK-w_rct`),b=(0,r.toBytes)(`ZK-w_hdl`);function x(e,t){let n=Math.ceil(v(t)/8);return(0,r.toBytes)((0,r.pad)((0,r.toHex)(e),{size:n}))}function S(e,n,i){if(i.length!==32)throw new t.n(`random32 must be exactly 32 bytes`);let a=x(n,e),o=(0,r.keccak256)((0,r.concat)([(0,r.toHex)(new Uint8Array([e])),(0,r.toHex)(a),(0,r.toHex)(i)]));return(0,r.keccak256)((0,r.concat)([(0,r.toHex)(y),o]))}function C(e,n,i,a,o){if(!Number.isInteger(n)||n<0||n>255)throw new t.n(`index must be an integer between 0 and 255`);let s=(0,r.keccak256)((0,r.concat)([(0,r.toHex)(y),e])),c=(0,r.keccak256)((0,r.encodePacked)([`bytes`,`bytes32`,`uint8`,`address`,`uint256`],[(0,r.toHex)(b),s,n,a,o])),l=o&18446744073709551615n;return(0,r.toHex)(BigInt(c)&115792089237316195423570985008687907853269984665640254554447762662844404858880n|BigInt(n)<<80n|l<<16n|BigInt(i)<<8n|BigInt(0),{size:32})}const w=(0,r.parseAbi)([`function persistAllowed(bytes32 handle, address account) view returns (bool)`,`function isAllowedForDecryption(bytes32 handle) view returns (bool)`,`function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)`]),T=(0,r.parseAbi)([`function plaintexts(bytes32 handle) view returns (uint256)`]),E=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`}],D={EIP712Domain:E,UserDecryptRequestVerification:u.types.UserDecryptRequestVerification},O={EIP712Domain:E,DelegatedUserDecryptRequestVerification:d.types.DelegatedUserDecryptRequestVerification},k={EIP712Domain:E,PublicDecryptVerification:l.types.PublicDecryptVerification},A=new Set([i.mainnet.id,i.sepolia.id]);function j(e,t){let n=Number(BigInt(e)>>8n&255n);return n===0?t!==0n:n===7?(0,r.toHex)(t,{size:20}):t}function M(e){if(!g(e.type))throw new t.n(`Unsupported FHE type`);let n=_(e.type),i;if(e.type===`ebool`){if(typeof e.value==`boolean`)i=e.value?1n:0n;else if(i=e.value,i!==0n&&i!==1n)throw new t.n(`Bool value must be 0, 1, true, or false`)}else i=e.type===`eaddress`?BigInt((0,r.getAddress)(e.value)):e.value;if(i<0n)throw new t.n(`Only non-negative cleartext values are supported`);let a=v(n),o=(1n<<BigInt(a))-1n;if(i>o)throw new t.n(`Value ${i} exceeds max ${o} for FheType ${n}`);return{fheType:n,value:i}}var N=class{#e;#t;kmsSigner;inputSigner;constructor(t){if(A.has(t.id))throw new e.t(`Cleartext mode is not allowed on chain ${t.id}. It is intended for local development and testing only.`);if(!t.executorAddress)throw new e.t(`Cleartext transport requires an executorAddress for chain ${t.id}.`);this.#e=(0,r.createPublicClient)({transport:typeof t.network==`string`?(0,r.http)(t.network):(0,r.custom)(t.network)}),this.#t=t,this.kmsSigner=(0,n.privateKeyToAccount)(t.kmsSignerPrivateKey??`0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91`),this.inputSigner=(0,n.privateKeyToAccount)(t.inputSignerPrivateKey??`0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901`)}async generateTransportKeyPair(){let e=(0,r.toHex)(crypto.getRandomValues(new Uint8Array(32))),t=(0,r.toHex)(crypto.getRandomValues(new Uint8Array(32)));for(;t===e;)t=(0,r.toHex)(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:e,privateKey:t}}async createEIP712(e,t,n,r=7){return{domain:u.domain(this.#t.id,this.#t.verifyingContractAddressDecryption),types:D,primaryType:`UserDecryptRequestVerification`,message:{publicKey:e,contractAddresses:t,startTimestamp:String(n),durationDays:String(r),extraData:`0x00`}}}async encrypt(e){let t=e.values.map(M),n=(0,r.getAddress)(e.contractAddress),i=(0,r.getAddress)(e.userAddress),a=t.map(({fheType:e,value:t})=>S(e,t,crypto.getRandomValues(new Uint8Array(32)))),o=(0,r.keccak256)(a.length>0?(0,r.concat)(a):`0x`),s=t.map(({fheType:e},t)=>C(o,t,e,this.#t.aclContractAddress,BigInt(this.#t.id))),l=t.map(({value:e})=>(0,r.pad)((0,r.toHex)(e),{size:32})),u=l.length>0?(0,r.concat)(l):`0x`,d=await this.inputSigner.signTypedData({domain:c.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressInputVerification),types:{CiphertextVerification:c.types.CiphertextVerification},primaryType:`CiphertextVerification`,message:{ctHandles:s,userAddress:i,contractAddress:n,contractChainId:BigInt(this.#t.id),extraData:u}});return{encryptedValues:s,inputProof:(0,r.concat)([(0,r.toHex)(new Uint8Array([s.length])),(0,r.toHex)(new Uint8Array([1])),...s,d,u])}}async userDecrypt(e){return await this.#r(e.encryptedValues,(0,r.getAddress)(e.signerAddress),(0,r.getAddress)(e.contractAddress),`User`,`user decrypt`),this.#n(e.encryptedValues)}async publicDecrypt(e){let n=e,i=(await Promise.all(n.map(e=>this.#o(e)))).findIndex(e=>!e);if(i!==-1)throw new t.t(`Encrypted value ${n[i]} is not allowed for public decryption`);let a=await Promise.all(n.map(e=>this.#s(e))),o=Object.fromEntries(n.map((e,t)=>[e,j(e,a[t])])),s=(0,r.concat)(a.map(e=>(0,r.pad)((0,r.toHex)(e),{size:32}))),c=await this.kmsSigner.signTypedData({domain:l.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressDecryption),types:k,primaryType:`PublicDecryptVerification`,message:{ctHandles:n,decryptedResult:s,extraData:`0x`}});return{clearValues:o,abiEncodedClearValues:s,decryptionProof:(0,r.concat)([(0,r.toHex)(new Uint8Array([1])),c])}}async createDelegatedUserDecryptEIP712(e,t,n,i,a=7){let o={publicKey:e,contractAddresses:t,delegatorAddress:(0,r.getAddress)(n),startTimestamp:String(i),durationDays:String(a),extraData:`0x00`};return{domain:d.domain(this.#t.id,this.#t.verifyingContractAddressDecryption),types:O,primaryType:`DelegatedUserDecryptRequestVerification`,message:o}}async delegatedUserDecrypt(e){return await this.#i(e.encryptedValues,(0,r.getAddress)(e.delegatorAddress),(0,r.getAddress)(e.delegateAddress),(0,r.getAddress)(e.contractAddress)),this.#n(e.encryptedValues)}async requestZKProofVerification(t){throw new e.t(`Not implemented in cleartext mode`)}async fetchFheEncryptionKeyBytes(){return{publicKeyId:`mock-public-key-id`,publicKey:new Uint8Array([32])}}async getPublicParams(e){return{publicParams:new Uint8Array([32]),publicParamsId:`mock-public-params-id`}}async getAclAddress(){return this.#t.aclContractAddress}terminate(){}[Symbol.dispose](){this.terminate()}async#n(e){let t=await Promise.all(e.map(e=>this.#s(e)));return Object.fromEntries(e.map((e,n)=>[e,j(e,t[n])]))}async#r(e,n,r,i,o){if(n===r)throw new t.t(`${i} address ${n} must not equal contract address for ${o}`);let s=await Promise.all(e.flatMap(e=>[this.#a(e,n),this.#a(e,r)]));for(let i=0;i<e.length;i++){let c=s[i*2],l=s[i*2+1];if(!c)throw new a({encryptedValue:e[i],contractAddress:r,account:n});if(!l)throw new t.t(`Contract ${r} is not authorized for ${o} of encrypted value ${e[i]}`)}}async#i(e,n,r,i){let o=await Promise.all(e.map(e=>this.#e.readContract({address:this.#t.aclContractAddress,abi:w,functionName:`isHandleDelegatedForUserDecryption`,args:[n,r,i,e]})));for(let n=0;n<e.length;n++)if(!o[n])throw new t.t(`Encrypted value ${e[n]} is not delegated for user decryption`);let s=await Promise.all(e.map(e=>this.#a(e,n)));for(let t=0;t<e.length;t++)if(!s[t])throw new a({encryptedValue:e[t],contractAddress:i,account:n})}async#a(e,t){return this.#e.readContract({address:this.#t.aclContractAddress,abi:w,functionName:`persistAllowed`,args:[e,t]})}async#o(e){return this.#e.readContract({address:this.#t.aclContractAddress,abi:w,functionName:`isAllowedForDecryption`,args:[e]})}async#s(e){return this.#e.readContract({address:this.#t.executorAddress,abi:T,functionName:`plaintexts`,args:[e]})}};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return N}});
2
- //# sourceMappingURL=relayer-cleartext.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"relayer-cleartext.cjs","names":["ZamaError","ZamaErrorCode","EncryptionFailedError","mainnet","sepolia","EncryptionFailedError","#client","#config","ConfigurationError","#assertDecryptAuthorization","#decryptHandles","#isAllowedForDecryption","DecryptionFailedError","#readPlaintext","#assertDelegation","#persistAllowed"],"sources":["../../src/errors/entitlement.ts","../../src/relayer/cleartext/eip712.ts","../../src/relayer/cleartext/constants.ts","../../src/relayer/cleartext/fhe-type.ts","../../src/relayer/cleartext/handle.ts","../../src/relayer/cleartext/relayer-cleartext.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * The signer (or delegator) lacks ACL permission to decrypt the encrypted value —\n * `persistAllowed` returned `false`. Terminal and **non-retryable**: the fix is\n * an on-chain grant (`FHE.allow`), or for indexers, to wait for a backfill once\n * the grant lands. Distinct from transient failures like {@link RpcRateLimitError}.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof NotEntitledError) {\n * // don't retry — wait for an ACL grant / backfill\n * }\n * }\n * ```\n */\nexport class NotEntitledError extends ZamaError {\n /** The encrypted value the actor is not entitled to decrypt. */\n readonly encryptedValue: string;\n /** The contract the encrypted value belongs to. */\n readonly contractAddress: string;\n /** The actor (signer or delegator) that lacks ACL permission. */\n readonly account: string;\n\n constructor(\n args: { encryptedValue: string; contractAddress: string; account: string },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.NotEntitled,\n `Account ${args.account} is not entitled to decrypt encrypted value ${args.encryptedValue} ` +\n `on contract ${args.contractAddress}. This is not a transient failure — ` +\n `the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,\n options,\n );\n this.name = \"NotEntitledError\";\n this.encryptedValue = args.encryptedValue;\n this.contractAddress = args.contractAddress;\n this.account = args.account;\n }\n}\n","import type { Address } from \"viem\";\nimport type {\n CoprocessorEIP712DomainType,\n CoprocessorEIP712TypesType,\n KmsDelegatedUserDecryptEIP712TypesType,\n KmsEIP712DomainType,\n KmsPublicDecryptEIP712TypesType,\n KmsUserDecryptEIP712TypesType,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nconst inputDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): CoprocessorEIP712DomainType => ({\n name: \"InputVerification\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nconst decryptionDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): KmsEIP712DomainType => ({\n name: \"Decryption\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nexport const INPUT_VERIFICATION_EIP712 = {\n domain: inputDomain,\n types: {\n CiphertextVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"userAddress\", type: \"address\" },\n { name: \"contractAddress\", type: \"address\" },\n { name: \"contractChainId\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const KMS_DECRYPTION_EIP712 = {\n domain: decryptionDomain,\n types: {\n PublicDecryptVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"decryptedResult\", type: \"bytes\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n UserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const DELEGATED_USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n DelegatedUserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"delegatorAddress\", type: \"address\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\n// ── Compile-time structural checks against relayer-sdk types ──────────\n// These assertions ensure our local EIP-712 type arrays stay in sync with\n// the relayer-sdk's canonical definitions. A mismatch will cause a build error.\ntype AssertFieldsMatch<\n Local extends readonly { readonly name: string; readonly type: string }[],\n Canonical extends readonly { readonly name: string; readonly type: string }[],\n> = [Local[\"length\"]] extends [Canonical[\"length\"]]\n ? {\n [K in keyof Local]: Local[K] extends { readonly name: infer N; readonly type: infer T }\n ? Canonical[K & keyof Canonical] extends { readonly name: N; readonly type: T }\n ? true\n : { error: `Field mismatch at index ${K & string}` }\n : never;\n }\n : { error: \"Field count mismatch\" };\n\n// Wrapping in readonly true[] ensures a mismatch produces a compile error\n// (not just an inert type alias that TypeScript silently accepts).\ntype AssertAllTrue<T extends readonly true[]> = T;\n\ntype _CheckInput = AssertAllTrue<\n AssertFieldsMatch<\n typeof INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n CoprocessorEIP712TypesType[\"CiphertextVerification\"]\n >\n>;\ntype _CheckPublicDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n KmsPublicDecryptEIP712TypesType[\"PublicDecryptVerification\"]\n >\n>;\ntype _CheckUserDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n KmsUserDecryptEIP712TypesType[\"UserDecryptRequestVerification\"]\n >\n>;\ntype _CheckDelegatedDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n KmsDelegatedUserDecryptEIP712TypesType[\"DelegatedUserDecryptRequestVerification\"]\n >\n>;\n","export const HANDLE_VERSION = 0;\n\nexport const PREHANDLE_MASK = 0xffffffffffffffffffffffffffffffffffffffffff0000000000000000000000n;\n\n// Constants used for instanciation of the cleartext FHEVM instance.\nexport const MOCK_INPUT_SIGNER_PK =\n \"0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901\";\nexport const MOCK_KMS_SIGNER_PK =\n \"0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91\";\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import { concat, encodePacked, keccak256, pad, toBytes, toHex, type Address, type Hex } from \"viem\";\nimport { HANDLE_VERSION, PREHANDLE_MASK } from \"./constants\";\nimport { encryptionBitsFromFheTypeId, type FheTypeId } from \"./fhe-type\";\nimport { EncryptionFailedError } from \"../../errors\";\n\nconst RAW_CT_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_rct\");\nconst HANDLE_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_hdl\");\n\nfunction cleartextToBytes(cleartext: bigint, fheType: FheTypeId): Uint8Array {\n const byteLength = Math.ceil(encryptionBitsFromFheTypeId(fheType) / 8);\n return toBytes(pad(toHex(cleartext), { size: byteLength }));\n}\n\nexport function computeMockCiphertext(\n fheType: FheTypeId,\n cleartext: bigint,\n random32: Uint8Array,\n): Hex {\n if (random32.length !== 32) {\n throw new EncryptionFailedError(\"random32 must be exactly 32 bytes\");\n }\n\n const clearBytes = cleartextToBytes(cleartext, fheType);\n const inner = keccak256(\n concat([toHex(new Uint8Array([fheType])), toHex(clearBytes), toHex(random32)]),\n );\n\n return keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), inner]));\n}\n\nexport function computeInputHandle(\n mockCiphertext: Hex,\n index: number,\n fheType: FheTypeId,\n aclAddress: Address,\n chainId: bigint,\n): Hex {\n if (!Number.isInteger(index) || index < 0 || index > 255) {\n throw new EncryptionFailedError(\"index must be an integer between 0 and 255\");\n }\n\n const blobHash = keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), mockCiphertext]));\n const handleHash = keccak256(\n encodePacked(\n [\"bytes\", \"bytes32\", \"uint8\", \"address\", \"uint256\"],\n [toHex(HANDLE_HASH_DOMAIN_SEPARATOR), blobHash, index, aclAddress, chainId],\n ),\n );\n\n const chainId64 = chainId & 0xffff_ffff_ffff_ffffn;\n const handle =\n (BigInt(handleHash) & PREHANDLE_MASK) |\n (BigInt(index) << 80n) |\n (chainId64 << 16n) |\n (BigInt(fheType) << 8n) |\n BigInt(HANDLE_VERSION);\n\n return toHex(handle, { size: 32 });\n}\n","import type { PrivateKeyAccount } from \"viem/accounts\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport {\n concat,\n createPublicClient,\n custom,\n getAddress,\n http,\n keccak256,\n pad,\n parseAbi,\n toHex,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { mainnet, sepolia } from \"viem/chains\";\nimport type {\n InputProofBytesType,\n KmsDelegatedUserDecryptEIP712Type,\n KmsPublicDecryptEIP712Type,\n KmsUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nimport type { TransportKeyPair } from \"../../credentials/types\";\nimport type { RelayerSDK } from \"../relayer-sdk\";\nimport type {\n ClearValue,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n EncryptedValue,\n FheEncryptionKey,\n PublicDecryptResult,\n PublicParamsData,\n UserDecryptParams,\n} from \"../relayer-sdk.types\";\nimport {\n DELEGATED_USER_DECRYPT_EIP712,\n INPUT_VERIFICATION_EIP712,\n KMS_DECRYPTION_EIP712,\n USER_DECRYPT_EIP712,\n} from \"./eip712\";\nimport { MOCK_INPUT_SIGNER_PK, MOCK_KMS_SIGNER_PK } from \"./constants\";\nimport {\n encryptionBitsFromFheTypeId,\n fheTypeIdFromName,\n isFheTypeName,\n type FheTypeId,\n} from \"./fhe-type\";\nimport { computeInputHandle, computeMockCiphertext } from \"./handle\";\nimport type { FheChain } from \"../../chains/types\";\nimport {\n ConfigurationError,\n DecryptionFailedError,\n EncryptionFailedError,\n NotEntitledError,\n} from \"../../errors\";\n\nconst ACL_ABI = parseAbi([\n \"function persistAllowed(bytes32 handle, address account) view returns (bool)\",\n \"function isAllowedForDecryption(bytes32 handle) view returns (bool)\",\n \"function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)\",\n]);\n\nconst EXECUTOR_ABI = parseAbi([\"function plaintexts(bytes32 handle) view returns (uint256)\"]);\n\nconst STANDARD_EIP712_DOMAIN = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nconst USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n UserDecryptRequestVerification: USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n} satisfies KmsUserDecryptEIP712Type[\"types\"];\nconst DELEGATED_USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n DelegatedUserDecryptRequestVerification:\n DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n} satisfies KmsDelegatedUserDecryptEIP712Type[\"types\"];\nconst KMS_DECRYPTION_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n PublicDecryptVerification: KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n} satisfies KmsPublicDecryptEIP712Type[\"types\"];\n\nconst FORBIDDEN_CHAIN_IDS = new Set<number>([mainnet.id, sepolia.id]);\n\n// FheTypeId constants for hot-path comparisons\nconst EBOOL_ID: FheTypeId = 0;\nconst EADDRESS_ID: FheTypeId = 7;\n\nfunction decodeClearValue(encryptedValue: EncryptedValue, rawValue: bigint): ClearValue {\n const typeByte = Number((BigInt(encryptedValue) >> 8n) & 0xffn);\n if (typeByte === EBOOL_ID) {\n return rawValue !== 0n;\n }\n if (typeByte === EADDRESS_ID) {\n return toHex(rawValue, { size: 20 });\n }\n return rawValue;\n}\n\nfunction normalizeEncryptValue(entry: EncryptParams[\"values\"][number]): {\n fheType: FheTypeId;\n value: bigint;\n} {\n if (!isFheTypeName(entry.type)) {\n throw new EncryptionFailedError(\"Unsupported FHE type\");\n }\n\n const fheType = fheTypeIdFromName(entry.type);\n\n let value: bigint;\n if (entry.type === \"ebool\") {\n if (typeof entry.value === \"boolean\") {\n value = entry.value ? 1n : 0n;\n } else {\n value = entry.value;\n if (value !== 0n && value !== 1n) {\n throw new EncryptionFailedError(\"Bool value must be 0, 1, true, or false\");\n }\n }\n } else if (entry.type === \"eaddress\") {\n value = BigInt(getAddress(entry.value));\n } else {\n value = entry.value;\n }\n\n if (value < 0n) {\n throw new EncryptionFailedError(\"Only non-negative cleartext values are supported\");\n }\n\n const bits = encryptionBitsFromFheTypeId(fheType);\n const maxValue = (1n << BigInt(bits)) - 1n;\n if (value > maxValue) {\n throw new EncryptionFailedError(\n `Value ${value} exceeds max ${maxValue} for FheType ${fheType}`,\n );\n }\n\n return { fheType, value };\n}\n\nexport class RelayerCleartext implements RelayerSDK, Disposable {\n readonly #client: PublicClient;\n readonly #config: FheChain;\n readonly kmsSigner: PrivateKeyAccount;\n readonly inputSigner: PrivateKeyAccount;\n\n constructor(config: FheChain) {\n if (FORBIDDEN_CHAIN_IDS.has(config.id)) {\n throw new ConfigurationError(\n `Cleartext mode is not allowed on chain ${config.id}. ` +\n `It is intended for local development and testing only.`,\n );\n }\n if (!config.executorAddress) {\n throw new ConfigurationError(\n `Cleartext transport requires an executorAddress for chain ${config.id}.`,\n );\n }\n this.#client = createPublicClient({\n transport: typeof config.network === \"string\" ? http(config.network) : custom(config.network),\n });\n this.#config = config;\n this.kmsSigner = privateKeyToAccount(config.kmsSignerPrivateKey ?? MOCK_KMS_SIGNER_PK);\n this.inputSigner = privateKeyToAccount(config.inputSignerPrivateKey ?? MOCK_INPUT_SIGNER_PK);\n }\n\n async generateTransportKeyPair(): Promise<TransportKeyPair> {\n const publicKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n let privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n\n while (privateKey === publicKey) {\n privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n }\n\n return { publicKey, privateKey };\n }\n\n async createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays = 7,\n ): Promise<EIP712TypedData> {\n return {\n domain: USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: USER_DECRYPT_TYPES,\n primaryType: \"UserDecryptRequestVerification\",\n message: {\n publicKey,\n contractAddresses,\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n },\n };\n }\n\n async encrypt(params: EncryptParams): Promise<EncryptResult> {\n const entries = params.values.map(normalizeEncryptValue);\n const contractAddress = getAddress(params.contractAddress);\n const userAddress = getAddress(params.userAddress);\n\n const mockCiphertexts = entries.map(({ fheType, value }) =>\n computeMockCiphertext(fheType, value, crypto.getRandomValues(new Uint8Array(32))),\n );\n\n const ciphertextBlob = keccak256(mockCiphertexts.length > 0 ? concat(mockCiphertexts) : \"0x\");\n\n const handles = entries.map(({ fheType }, index) =>\n computeInputHandle(\n ciphertextBlob,\n index,\n fheType,\n this.#config.aclContractAddress as Address,\n BigInt(this.#config.id),\n ),\n );\n\n const cleartextParts = entries.map(({ value }) => pad(toHex(value), { size: 32 }));\n const cleartextBytes: Hex = cleartextParts.length > 0 ? concat(cleartextParts) : \"0x\";\n\n const signature = await this.inputSigner.signTypedData({\n domain: INPUT_VERIFICATION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressInputVerification as Address,\n ),\n types: { CiphertextVerification: INPUT_VERIFICATION_EIP712.types.CiphertextVerification },\n primaryType: \"CiphertextVerification\",\n message: {\n ctHandles: handles,\n userAddress,\n contractAddress,\n contractChainId: BigInt(this.#config.id),\n extraData: cleartextBytes,\n },\n });\n\n const inputProof = concat([\n toHex(new Uint8Array([handles.length])),\n toHex(new Uint8Array([1])),\n ...handles,\n signature,\n cleartextBytes,\n ]);\n\n return { encryptedValues: handles, inputProof };\n }\n\n async userDecrypt(\n params: UserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDecryptAuthorization(\n params.encryptedValues,\n getAddress(params.signerAddress),\n getAddress(params.contractAddress),\n \"User\",\n \"user decrypt\",\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async publicDecrypt(encryptedValues: EncryptedValue[]): Promise<PublicDecryptResult> {\n const normalizedHandles = encryptedValues;\n\n const allowedResults = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#isAllowedForDecryption(encryptedValue)),\n );\n const unauthorizedIndex = allowedResults.findIndex((isAllowed) => !isAllowed);\n if (unauthorizedIndex !== -1) {\n throw new DecryptionFailedError(\n `Encrypted value ${normalizedHandles[unauthorizedIndex]!} is not allowed for public decryption`,\n );\n }\n\n const orderedValues = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n const clearValues: PublicDecryptResult[\"clearValues\"] = Object.fromEntries(\n normalizedHandles.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, orderedValues[index]!),\n ]),\n );\n\n const abiEncodedClearValues = concat(orderedValues.map((v) => pad(toHex(v), { size: 32 })));\n\n const signature = await this.kmsSigner.signTypedData({\n domain: KMS_DECRYPTION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: KMS_DECRYPTION_TYPES,\n primaryType: \"PublicDecryptVerification\",\n message: {\n ctHandles: normalizedHandles,\n decryptedResult: abiEncodedClearValues,\n extraData: \"0x\",\n },\n });\n\n const decryptionProof = concat([toHex(new Uint8Array([1])), signature]);\n\n return { clearValues, abiEncodedClearValues, decryptionProof };\n }\n\n async createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays = 7,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n const message: KmsDelegatedUserDecryptEIP712Type[\"message\"] = {\n publicKey,\n contractAddresses,\n delegatorAddress: getAddress(delegatorAddress),\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n };\n\n return {\n domain: DELEGATED_USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: DELEGATED_USER_DECRYPT_TYPES,\n primaryType: \"DelegatedUserDecryptRequestVerification\",\n message,\n };\n }\n\n async delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDelegation(\n params.encryptedValues,\n getAddress(params.delegatorAddress),\n getAddress(params.delegateAddress),\n getAddress(params.contractAddress),\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async requestZKProofVerification(_zkProof: ZKProofLike): Promise<InputProofBytesType> {\n throw new ConfigurationError(\"Not implemented in cleartext mode\");\n }\n\n async fetchFheEncryptionKeyBytes(): Promise<FheEncryptionKey | null> {\n return { publicKeyId: \"mock-public-key-id\", publicKey: new Uint8Array([32]) };\n }\n\n async getPublicParams(_bits: number): Promise<PublicParamsData | null> {\n return { publicParams: new Uint8Array([32]), publicParamsId: \"mock-public-params-id\" };\n }\n\n async getAclAddress(): Promise<Address> {\n return this.#config.aclContractAddress as Address;\n }\n\n terminate(): void {\n // No resources to release in cleartext mode.\n }\n\n /** Calls {@link terminate} (no-op in cleartext mode). */\n [Symbol.dispose](): void {\n this.terminate();\n }\n\n async #decryptHandles(\n normalizedEncryptedValues: EncryptedValue[],\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n const values = await Promise.all(\n normalizedEncryptedValues.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n\n return Object.fromEntries(\n normalizedEncryptedValues.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, values[index]!),\n ]),\n );\n }\n\n async #assertDecryptAuthorization(\n normalizedEncryptedValues: EncryptedValue[],\n actorAddress: Address,\n contractAddress: Address,\n actorLabel: \"User\" | \"Delegator\",\n operationLabel: \"user decrypt\" | \"delegated decrypt\",\n ): Promise<void> {\n if (actorAddress === contractAddress) {\n throw new DecryptionFailedError(\n `${actorLabel} address ${actorAddress} must not equal contract address for ${operationLabel}`,\n );\n }\n\n const results = await Promise.all(\n normalizedEncryptedValues.flatMap((encryptedValue) => [\n this.#persistAllowed(encryptedValue, actorAddress),\n this.#persistAllowed(encryptedValue, contractAddress),\n ]),\n );\n\n for (let i = 0; i < normalizedEncryptedValues.length; i++) {\n const actorAllowed = results[i * 2];\n const contractAllowed = results[i * 2 + 1];\n if (!actorAllowed) {\n throw new NotEntitledError({\n encryptedValue: normalizedEncryptedValues[i]!,\n contractAddress,\n account: actorAddress,\n });\n }\n if (!contractAllowed) {\n throw new DecryptionFailedError(\n `Contract ${contractAddress} is not authorized for ${operationLabel} of encrypted value ${normalizedEncryptedValues[i]!}`,\n );\n }\n }\n }\n\n async #assertDelegation(\n encryptedValues: EncryptedValue[],\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n ): Promise<void> {\n const results = await Promise.all(\n encryptedValues.map((encryptedValue) =>\n this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, encryptedValue],\n }),\n ),\n );\n\n for (let i = 0; i < encryptedValues.length; i++) {\n if (!results[i]) {\n throw new DecryptionFailedError(\n `Encrypted value ${encryptedValues[i]!} is not delegated for user decryption`,\n );\n }\n }\n\n // Parity with the relayer/worker path: a delegated handle still requires the\n // *delegator* to hold the ACL grant (`persistAllowed`). Without this check,\n // the same condition surfaces differently in local cleartext dev than in\n // production — exactly where integrators wire up their error handling.\n // Cleartext is host-chain-only: `#persistAllowed` reads the ACL directly on\n // the local chain, with no gateway and no cross-chain sync. A failed check\n // here can never be a propagation lag — it is authoritative and permanent —\n // so it maps to the terminal NotEntitledError, not the retryable\n // DelegationNotPropagatedError (which would make the delegated-decrypt retry\n // loop spin its full budget on a local misconfig before failing).\n const delegatorAllowed = await Promise.all(\n encryptedValues.map((encryptedValue) =>\n this.#persistAllowed(encryptedValue, delegatorAddress),\n ),\n );\n\n for (let i = 0; i < encryptedValues.length; i++) {\n if (!delegatorAllowed[i]) {\n throw new NotEntitledError({\n encryptedValue: encryptedValues[i]!,\n contractAddress,\n account: delegatorAddress,\n });\n }\n }\n }\n\n async #persistAllowed(encryptedValue: EncryptedValue, account: Address): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"persistAllowed\",\n args: [encryptedValue, account],\n });\n }\n\n async #isAllowedForDecryption(encryptedValue: EncryptedValue): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isAllowedForDecryption\",\n args: [encryptedValue],\n });\n }\n\n async #readPlaintext(encryptedValue: EncryptedValue): Promise<bigint> {\n return this.#client.readContract({\n address: this.#config.executorAddress as Address,\n abi: EXECUTOR_ABI,\n functionName: \"plaintexts\",\n args: [encryptedValue],\n });\n }\n}\n"],"mappings":"yIAmBA,IAAa,EAAb,cAAsCA,EAAAA,CAAU,CAE9C,eAEA,gBAEA,QAEA,YACE,EACA,EACA,CACA,MACEC,EAAAA,EAAc,YACd,WAAW,EAAK,QAAQ,8CAA8C,EAAK,eAAe,eACzE,EAAK,gBAAgB,yHAEtC,CACF,EACA,KAAK,KAAO,mBACZ,KAAK,eAAiB,EAAK,eAC3B,KAAK,gBAAkB,EAAK,gBAC5B,KAAK,QAAU,EAAK,OACtB,CACF,ECjCA,MAAM,GACJ,EACA,KACiC,CACjC,KAAM,oBACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEM,GACJ,EACA,KACyB,CACzB,KAAM,aACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEa,EAA4B,CACvC,OAAQ,EACR,MAAO,CACL,uBAAwB,CACtB,CAAE,KAAM,YAAa,KAAM,WAAY,EACvC,CAAE,KAAM,cAAe,KAAM,SAAU,EACvC,CAAE,KAAM,kBAAmB,KAAM,SAAU,EAC3C,CAAE,KAAM,kBAAmB,KAAM,SAAU,EAC3C,CAAE,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