@zama-fhe/sdk 3.2.0 → 3.3.0-alpha.10
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/dist/cjs/assertions.cjs +1 -1
- package/dist/cjs/assertions.cjs.map +1 -1
- package/dist/cjs/base-signer.cjs +1 -1
- package/dist/cjs/base-signer.cjs.map +1 -1
- package/dist/cjs/ethers/index.cjs +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/relayer-cleartext.cjs +1 -1
- package/dist/cjs/relayer-cleartext.cjs.map +1 -1
- package/dist/cjs/relayer-sdk.worker.js +134 -34
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/timeout.cjs +2 -0
- package/dist/cjs/timeout.cjs.map +1 -0
- package/dist/cjs/token.cjs +1 -1
- package/dist/cjs/token.cjs.map +1 -1
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/cjs/web/index.cjs +136 -36
- package/dist/cjs/web/index.cjs.map +1 -1
- package/dist/cjs/wrappers-registry.cjs +1 -1
- package/dist/cjs/wrappers-registry.cjs.map +1 -1
- package/dist/esm/assertions-zYseN5Xz.js +2 -0
- package/dist/esm/assertions-zYseN5Xz.js.map +1 -0
- package/dist/esm/{base-signer-ByGw5ReU.d.ts → base-signer-C3Wc5oi9.d.ts} +2 -2
- package/dist/esm/base-signer-DjytqPkd.js +2 -0
- package/dist/esm/base-signer-DjytqPkd.js.map +1 -0
- package/dist/esm/cleartext/index.d.ts +1 -1
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-DMW5nK1M.d.ts → cleartext-DAkOTlrE.d.ts} +2 -2
- package/dist/esm/{cleartext-CTla3A3O.js → cleartext-rTWFctyd.js} +2 -2
- package/dist/esm/{cleartext-CTla3A3O.js.map → cleartext-rTWFctyd.js.map} +1 -1
- package/dist/esm/{encryption-BGmINekJ.js → encryption-x4Z_Icqk.js} +2 -2
- package/dist/esm/{encryption-BGmINekJ.js.map → encryption-x4Z_Icqk.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +4 -4
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/{hex-CxtyupeQ.js → hex-A72GrTf9.js} +2 -2
- package/dist/esm/{hex-CxtyupeQ.js.map → hex-A72GrTf9.js.map} +1 -1
- package/dist/esm/{index-DoVo9J1n.d.ts → index-C1Mtc8Rw.d.ts} +450 -163
- package/dist/esm/index.d.ts +17 -13
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node/index.d.ts +25 -7
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/node/index.js.map +1 -1
- package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
- package/dist/esm/node/relayer-sdk.node-worker.js.map +1 -1
- package/dist/esm/query/index.d.ts +42 -4
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/relayer-cleartext-Bp6jtxDd.js +2 -0
- package/dist/esm/relayer-cleartext-Bp6jtxDd.js.map +1 -0
- package/dist/esm/{relayer-cleartext-DkKKjfI6.d.ts → relayer-cleartext-CSeMlmGO.d.ts} +102 -13
- package/dist/esm/relayer-eavK5bfZ.js +2 -0
- package/dist/esm/relayer-eavK5bfZ.js.map +1 -0
- package/dist/esm/relayer-sdk.worker.js +134 -34
- package/dist/esm/timeout-CNVfiaJD.js +2 -0
- package/dist/esm/timeout-CNVfiaJD.js.map +1 -0
- package/dist/esm/token-Bt33g0zQ.js +2 -0
- package/dist/esm/token-Bt33g0zQ.js.map +1 -0
- package/dist/esm/{types-BjDu-RZg.d.ts → types-Gn5MeDsr.d.ts} +14 -2
- package/dist/esm/{types-Xg_On_yY.d.ts → types-OHIaPwCy.d.ts} +2 -2
- package/dist/esm/{types-DiZhtG8i.d.ts → types-piBsdTIP.d.ts} +2 -2
- package/dist/esm/{validation-DHZ3JPOn.js → validation-DLszOweh.js} +2 -2
- package/dist/esm/{validation-DHZ3JPOn.js.map → validation-DLszOweh.js.map} +1 -1
- package/dist/esm/viem/index.d.ts +4 -4
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/web/index.d.ts +2 -2
- package/dist/esm/web/index.js +135 -35
- package/dist/esm/web/index.js.map +1 -1
- package/dist/esm/worker.base-client-BVnT4yJa.js +2 -0
- package/dist/esm/worker.base-client-BVnT4yJa.js.map +1 -0
- package/dist/esm/{wrappers-registry-BWWG0aze.js → wrappers-registry-C1oK8Bi6.js} +2 -2
- package/dist/esm/wrappers-registry-C1oK8Bi6.js.map +1 -0
- package/package.json +51 -51
- package/dist/esm/assertions-CnPIS0VN.js +0 -2
- package/dist/esm/assertions-CnPIS0VN.js.map +0 -1
- package/dist/esm/base-signer-BVqcM5jt.js +0 -2
- package/dist/esm/base-signer-BVqcM5jt.js.map +0 -1
- package/dist/esm/error-W1N-FGwV.js +0 -2
- package/dist/esm/error-W1N-FGwV.js.map +0 -1
- package/dist/esm/relayer-D-nicEYJ.js +0 -2
- package/dist/esm/relayer-D-nicEYJ.js.map +0 -1
- package/dist/esm/relayer-cleartext-DGcb5qtE.js +0 -2
- package/dist/esm/relayer-cleartext-DGcb5qtE.js.map +0 -1
- package/dist/esm/token-TQ-VFHS4.js +0 -2
- package/dist/esm/token-TQ-VFHS4.js.map +0 -1
- package/dist/esm/worker.base-client-x522sMBy.js +0 -2
- package/dist/esm/worker.base-client-x522sMBy.js.map +0 -1
- package/dist/esm/wrappers-registry-BWWG0aze.js.map +0 -1
package/dist/cjs/assertions.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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`)}function
|
|
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
2
|
//# sourceMappingURL=assertions.cjs.map
|
|
@@ -1 +1 @@
|
|
|
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/**\n * Extract an HTTP status code from an error, if present.\n * Relayer SDK errors may carry a `status` or `statusCode` property.\n */\nexport function extractHttpStatus(error: unknown): number | undefined {\n if (error === null || error === undefined || typeof error !== \"object\") {\n return undefined;\n }\n const e = error as Record<string, unknown>;\n if (typeof e.statusCode === \"number\") {\n return e.statusCode;\n }\n if (typeof e.status === \"number\") {\n return e.status;\n }\n // Check nested cause\n if (e.cause !== null && e.cause !== undefined && typeof e.cause === \"object\") {\n const cause = e.cause as Record<string, unknown>;\n if (typeof cause.statusCode === \"number\") {\n return cause.statusCode;\n }\n if (typeof cause.status === \"number\") {\n return cause.status;\n }\n }\n return undefined;\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,CAMA,SAAgB,EAAkB,EAAoC,CACpE,GAA6C,OAAO,GAAU,WAA1D,EACF,OAEF,IAAM,EAAI,EACV,GAAI,OAAO,EAAE,YAAe,SAC1B,OAAO,EAAE,WAEX,GAAI,OAAO,EAAE,QAAW,SACtB,OAAO,EAAE,OAGX,GAAI,EAAE,QAAU,MAAQ,EAAE,QAAU,IAAA,IAAa,OAAO,EAAE,OAAU,SAAU,CAC5E,IAAM,EAAQ,EAAE,MAChB,GAAI,OAAO,EAAM,YAAe,SAC9B,OAAO,EAAM,WAEf,GAAI,OAAO,EAAM,QAAW,SAC1B,OAAO,EAAM,MAEjB,CAEF,CC9DA,SAAgB,EAAqB,EAAU,EAAkD,CAC/F,GAAI,GAAU,KACZ,MAAU,UAAU,GAAG,EAAQ,+BAA+B,CAElE,CAEA,SAAgB,EACd,EACA,EAC0C,CAC1C,GAAI,OAAO,GAAU,WAAY,GAAkB,MAAM,QAAQ,CAAK,EACpE,MAAU,UAAU,GAAG,EAAQ,0BAA0B,OAAO,GAAO,CAE3E,CAEA,SAAgB,EAAa,EAAgB,EAA0C,CACrF,GAAI,OAAO,GAAU,SACnB,MAAU,UAAU,GAAG,EAAQ,yBAAyB,OAAO,GAAO,CAE1E,CASA,SAAgB,EAAe,EAAgB,EAA4C,CACzF,GAAI,OAAO,GAAU,WACnB,MAAU,UAAU,GAAG,EAAQ,2BAA2B,OAAO,GAAO,CAE5E,CAEA,SAAgB,EAAa,EAAgB,EAA0C,CACrF,GAAI,OAAO,GAAU,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
|
+
{"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":"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"}
|
package/dist/cjs/base-signer.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./relayer.cjs"),t=require("./wrappers-registry.cjs"),n=require("./assertions.cjs"),r=require("./validation.cjs"),i=require("./chains.cjs");let a=require("viem"),o=require("zod/mini");function s(e){return`keypair:${e}`}function c(e){return`permits:${e.signerAddress}:${e.chainId}:${e.delegatorAddress}`}function l(e){return`permits-index:${e}`}function u(e){return(0,a.getAddress)(e)}const d=o.z.custom(e=>typeof e==`string`&&(0,a.isHex)(e,{strict:!0}),`expected 0x-prefixed hex string`),f=o.z.custom(e=>typeof e==`string`&&(0,a.isAddress)(e,{strict:!1}),`expected EVM address`),p=o.z.pipe(f,o.z.transform(u)),m=o.z.int().check(o.z.nonnegative()),h=o.z.int().check(o.z.positive()),g=o.z.int().check(o.z.nonnegative()),_=o.z.int().check(o.z.positive()),v=o.z.int().check(o.z.positive());function y(){return Math.floor(Date.now()/1e3)}function b(e){return[...new Set(e.map(u))].toSorted()}const x=`transportKeyPairTTL must be a positive integer number of seconds`,S=`permitTTL must be a positive integer number of days`,C=365*86400,w=o.z.int({error:x}).check(o.z.positive({error:x}),o.z.maximum(C,`transportKeyPairTTL must not exceed the fhevm ACL maximum of ${C}s (365 days)`)),T=o.z.int({error:S}).check(o.z.positive({error:S})),E=o.z.object({publicKey:d,privateKey:d,createdAt:m,expiresAt:h}),D=o.z.object({keypairPublicKey:d,signerAddress:p,delegatorAddress:p,chainId:v,signedContractAddresses:o.z.array(p).check(o.z.maxLength(10)),signature:d,startTimestamp:m,durationDays:_}),O=o.z.array(D),k=o.z.array(o.z.string());var A=class{#e;#t;#n;#r;#i=new Map;constructor(e){this.#e=e.generator,this.#t=e.storage,this.#n=e.ttl,this.#r=e.logger}async readStored(e){let n=s(e),r=await this.#t.get(n);if(r==null)return null;let i=E.safeParse(r);if(!i.success)return await t.F(`delete transport key pair entry`,()=>this.#t.delete(n),this.#r),null;let a=i.data;return y()>=a.expiresAt?(await t.F(`delete transport key pair entry`,()=>this.#t.delete(n),this.#r),null):a}async getOrCreate(e){let n=this.#i.get(e);if(n)return n;let r=(async()=>{let n=await this.readStored(e);if(n!==null)return n;let r=await this.#e(),i=y(),a={publicKey:r.publicKey,privateKey:r.privateKey,createdAt:i,expiresAt:i+this.#n},o=s(e);return await t.F(`persist transport key pair`,()=>this.#t.set(o,a),this.#r),a})().finally(()=>{this.#i.delete(e)});return this.#i.set(e,r),r}async clear(e){let n=s(e);await t.F(`delete transport key pair entry`,()=>this.#t.delete(n),this.#r)}};function j(e,t){let n=new Set(e.flatMap(e=>e.signedContractAddresses));return t.filter(e=>!n.has(e))}function M(e){let t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));return t}function N(e,t,n){return e.filter(e=>e.keypairPublicKey===t&&n<e.startTimestamp+e.durationDays*86400)}function P(e,t){let n=new Set(t);return e.filter(e=>!e.signedContractAddresses.some(e=>n.has(e)))}function F(e,t){return[...new Set([...e,...t])].toSorted()}function I(e,t,n){let r=new Set(n),i=e.filter(e=>new Set([...e.signedContractAddresses,...t]).size<=10);if(i.length===0)return null;function a(e){return e.signedContractAddresses.reduce((e,t)=>e+ +!!r.has(t),0)}let o=Math.max(...i.map(a));return i.filter(e=>a(e)===o).reduce((e,t)=>t.startTimestamp>e.startTimestamp?t:e)}var L=class{#e;#t;constructor(e){this.#e=e.storage,this.#t=e.logger}async list(e){let t=c(e),n=await this.#e.get(t);if(n==null)return[];let r=O.safeParse(n);return r.success?r.data:(await this.#a(t),await this.#i(e),[])}async listUsableAndPrune(e,n){let r=await this.list(e),i=N(r,n,Math.floor(Date.now()/1e3));if(i.length!==r.length){let n=c(e);i.length===0?(await this.#a(n),await this.#i(e)):await t.F(`update permit entry`,()=>this.#e.set(n,i),this.#t)}return i}async append(e,t){if(t.length===0)return;let n=t.map(e=>D.parse(e)),r=await this.list(e);await this.#e.set(c(e),[...r,...n]),await this.#r(e)}async replace(e,t,n){let r=D.parse(n),i=(await this.list(e)).filter(e=>e.signature!==t);await this.#e.set(c(e),[...i,r]),await this.#r(e)}async deletePermitsTouching(e,t){let n=await this.list(e);if(n.length===0)return;let r=c(e),i=P(n,t);i.length===0?(await this.#a(r),await this.#i(e)):await this.#e.set(r,i)}async clearAllForSigner(e){let n=l(e),r=await this.#n(n);await Promise.all(r.map(e=>this.#a(e))),await t.F(`delete permit index`,()=>this.#e.delete(n),this.#t)}async#n(e){let n=await this.#e.get(e);if(n==null)return[];let r=k.safeParse(n);return r.success?r.data:(await t.F(`delete permit index`,()=>this.#e.delete(e),this.#t),[])}async#r(e){let t=l(e.signerAddress),n=c(e),r=await this.#n(t);r.includes(n)||await this.#e.set(t,[...r,n])}async#i(e){let n=l(e.signerAddress),r=c(e),i=await this.#n(n),a=i.filter(e=>e!==r);a.length!==i.length&&(a.length===0?await t.F(`delete permit index`,()=>this.#e.delete(n),this.#t):await t.F(`update permit index`,()=>this.#e.set(n,a),this.#t))}async#a(e){await t.F(`delete permit entry`,()=>this.#e.delete(e),this.#t)}},R=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=new A({generator:()=>e.relayer.generateTransportKeyPair(),storage:e.storage,ttl:e.transportKeyPairTTL,logger:e.logger}),this.#t=new L({storage:e.permitStorage??e.storage,logger:e.logger}),this.#n=e.relayer,this.#r=e.signer,this.#i=e.permitTTL,this.#a=e.logger}async grantPermit(e,n){let r=this.#r.requireWalletAccount(`grantPermit`),i=u(r.address),a=b(e),o=await this.#e.getOrCreate(i);if(a.length===0)return{keypair:o,permits:[]};let s={signerAddress:i,chainId:r.chainId,delegatorAddress:n?u(n):i},c=await this.#t.listUsableAndPrune(s,o.publicKey),l=j(c,a);if(l.length>0){let e=I(c,l,a);if(e!==null){let n=F(e.signedContractAddresses,l),r=await this.#o({chunk:n,keypair:o,scope:s});await t.F(`replace permit`,()=>this.#t.replace(s,e.signature,r),this.#a),c[c.indexOf(e)]=r}else for(let e of M(l)){let n=await this.#o({chunk:e,keypair:o,scope:s});c.push(n),await t.F(`persist permit`,()=>this.#t.append(s,[n]),this.#a)}}let d=new Set(a);return{keypair:o,permits:c.filter(e=>e.signedContractAddresses.some(e=>d.has(e)))}}async hasPermit(e,t){if(e.length===0)return!0;let n=this.#r.walletAccount.getSnapshot();if(!n)return!1;let r=u(n.address),i=await this.#e.readStored(r);if(i===null)return!1;let a={signerAddress:r,chainId:n.chainId,delegatorAddress:t?u(t):r};return j(await this.#t.listUsableAndPrune(a,i.publicKey),b(e)).length===0}async revokePermits(e){let t=this.#r.requireWalletAccount(`revokePermits`),n=u(t.address);if(e===void 0){await this.#t.clearAllForSigner(n);return}let r=b(e);if(r.length===0)return;let i=t.chainId;await this.#t.deletePermitsTouching({signerAddress:n,chainId:i,delegatorAddress:n},r)}async clearCredentials(){let e=u(this.#r.requireWalletAccount(`clearCredentials`).address);await this.#e.clear(e),await this.#t.clearAllForSigner(e)}async warmTransportKeyPair(e){await this.#e.getOrCreate(u(e))}async handleWalletAccountChange(e,t){let n=e?u(e.address):void 0;n!==(t?u(t.address):void 0)&&n&&(await this.#e.clear(n),await this.#t.clearAllForSigner(n))}async#o(n){let{chunk:r,keypair:i,scope:a}=n,o=y(),s=a.delegatorAddress!==a.signerAddress;try{let e=s?await this.#n.createDelegatedUserDecryptEIP712(i.publicKey,r,a.delegatorAddress,o,this.#i):await this.#n.createEIP712(i.publicKey,r,o,this.#i),t=await this.#r.signTypedData(e);return{keypairPublicKey:i.publicKey,signerAddress:a.signerAddress,delegatorAddress:a.delegatorAddress,chainId:a.chainId,signedContractAddresses:r,signature:t,startTimestamp:o,durationDays:this.#i}}catch(n){throw n instanceof e.r?n:t.U(n,`Credential signing failed`)}}},z=class{#e;#t=`[zama-sdk]`;constructor(e){this.#e=e}error(e,t){this.#e?.error(`${this.#t} ${e}`,t)}warn(e,t){this.#e?.warn(`${this.#t} ${e}`,t)}info(e,t){this.#e?.info(`${this.#t} ${e}`,t)}debug(e,t){this.#e?.debug(`${this.#t} ${e}`,t)}},B=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const V=new B;function H(){return typeof window<`u`?new r.n(`CredentialStore`):new B}function U(e=H(),t=e){return{storage:e,permitStorage:t}}function W(t,n){let r=new Map(t.map(e=>[e.id,e]));if(r.size!==t.length){let n=t.map(e=>e.id);throw new e.t(`Duplicate chain id(s) [${[...new Set(n.filter((e,t)=>n.indexOf(e)!==t))].join(`, `)}] in the chains array. Each chain id must appear only once. Note: hardhat and anvil are aliases (both use 31337).`)}let i=new Map(Object.entries(n)),a=new Map;for(let t of r.keys()){let n=r.get(t),o=i.get(String(t));if(!o)throw new e.t(`Chain ${t} has no relayer configured. Add a relayer entry: relayers: { [${t}]: web() }`);if(!n)throw new e.t(`Chain ${t} has a relayer configured but no entry in the chains array. Add the chain config to the chains array.`);a.set(t,{chain:n,relayer:o})}let o=new Set(Object.keys(n).map(Number)),s=new Set([...o].filter(e=>!r.has(e)));if(s.size>0)throw new e.t(`Relayer entries for chain(s) [${[...s].join(`, `)}] have no matching entry in the chains array. Remove them or add the corresponding chain config.`);return a}var G=class{#e;#t;#n;#r;constructor(t,n,r){if(t.length===0)throw new e.t(`At least one chain is required.`);this.#e=new Map(t.map(e=>[e.id,e])),this.#r=t[0].id;let i=W(t,n),a=new Map;for(let[e,t]of i){let n=t.relayer,r=a.get(n);r||(r=[],a.set(n,r)),r.push([e,t.chain])}let o=new Map,s=[];try{for(let[e,t]of a){let n=t.map(([,e])=>e),i=e.createWorker?.(n,r);i&&s.push(i);for(let[n,a]of t)o.set(n,e.createRelayer(a,i,r))}}catch(e){for(let e of s)try{e.terminate()}catch{}throw e}this.#t=o,this.#n=s}get chains(){return[...this.#e.values()]}get chain(){let e=this.#e.get(this.#r);return n.r(e,`RelayerDispatcher: chain`),e}switchChain(t){if(!this.#e.has(t))throw new e.t(`No relayer configured for chain ${t}. Add it to the chains array.`);this.#r=t}get#i(){let e=this.#t.get(this.#r);return n.r(e,`RelayerDispatcher: relayer`),e}generateTransportKeyPair(){return this.#i.generateTransportKeyPair()}createEIP712(e,t,n,r){return this.#i.createEIP712(e,t,n,r)}encrypt(e){return this.#i.encrypt(e)}userDecrypt(e){return this.#i.userDecrypt(e)}publicDecrypt(e){return this.#i.publicDecrypt(e)}createDelegatedUserDecryptEIP712(e,t,n,r,i){return this.#i.createDelegatedUserDecryptEIP712(e,t,n,r,i)}delegatedUserDecrypt(e){return this.#i.delegatedUserDecrypt(e)}requestZKProofVerification(e){return this.#i.requestZKProofVerification(e)}fetchFheEncryptionKeyBytes(){return this.#i.fetchFheEncryptionKeyBytes()}getPublicParams(e){return this.#i.getPublicParams(e)}getAclAddress(){return this.#i.getAclAddress()}terminate(){let e=[];for(let t of new Set(this.#t.values()))try{t.terminate()}catch(t){e.push(n.c(t))}for(let t of new Set(this.#n))try{t.terminate()}catch(t){e.push(n.c(t))}if(e.length>0)throw AggregateError(e,`Failed to terminate relayer resources`)}[Symbol.dispose](){this.terminate()}};const K={[i.s.id]:i.s.registryAddress,[i.c.id]:i.c.registryAddress,[i.a.id]:i.a.registryAddress,[i.o.id]:i.o.registryAddress,[i.n.id]:i.n.registryAddress},q=o.z.record(o.z.string().check(o.z.regex(/^\d+$/,`expected numeric chain id key`)),p),J=g,Y=300*1e3;var X=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},K,r.t(o.z.optional(q),e.registryAddresses)),this.#t=r.t(J,e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.provider.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,a.getAddress)(n)}async listPairs(n={}){let r=n.page??1,i=n.pageSize??100,a=n.metadata??!1;if(r<1)throw new e.t(`page must be >= 1, got ${r}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.provider.readContract(t.a(o));c=this.#i(s,Number(e))}let l=BigInt((r-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:r,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(t.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:r,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Y:void 0)}return{items:m,total:c,page:r,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(t.b(e.tokenAddress)),this.provider.readContract(t.x(e.tokenAddress)),this.provider.readContract(t.v(e.tokenAddress)),this.provider.readContract(t.y(e.tokenAddress)),this.provider.readContract(t.b(e.confidentialTokenAddress)),this.provider.readContract(t.x(e.confidentialTokenAddress)),this.provider.readContract(t.v(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let n=await this.getRegistryAddress(),r=(0,a.getAddress)(e),i=`ct:${n}:${r}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.provider.readContract(t.t(n,r));return c===a.zeroAddress?this.#i(i,null,Y):this.#i(i,{confidentialTokenAddress:c,isValid:s})}async getUnderlyingToken(e){let n=await this.getRegistryAddress(),r=(0,a.getAddress)(e),i=`ut:${n}:${r}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.provider.readContract(t.n(n,r));return c===a.zeroAddress?this.#i(i,null,Y):this.#i(i,{tokenAddress:c,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(t.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(t.a(e))}async getTokenPairsSlice(e,n){let r=await this.getRegistryAddress();return this.provider.readContract(t.o(r,e,n))}async getTokenPair(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.r(n,e))}async getConfidentialTokenAddress(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.t(n,(0,a.getAddress)(e)))}async getTokenAddress(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.n(n,(0,a.getAddress)(e)))}async isConfidentialTokenValid(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.s(n,(0,a.getAddress)(e)))}};function Z(e,t,n){let{storage:i,permitStorage:a}=U(n.storage,n.permitStorage),o=new z(n.logger),s=new G(n.chains,n.relayers,o);return{chains:n.chains,relayer:s,provider:t,signer:e,storage:i,permitStorage:a,transportKeyPairTTL:r.t(w,n.transportKeyPairTTL??2592e3),permitTTL:r.t(T,n.permitTTL??30),registryTTL:r.t(J,n.registryTTL??86400),logger:o,onEvent:n.onEvent}}function Q(e,t){return e?.address===t?.address&&e?.chainId===t?.chainId}var $=class{#e=new Set;#t;#n;constructor(e){this.#t=e,this.#n=e!==void 0}getSnapshot(){return this.#t}isReady(){return this.#n}setSnapshot(e){this.#n=!0;let t=this.#t;Q(t,e)||(this.#t=e,this.#r({previous:t,next:e}))}subscribe(e){this.#e.add(e);let t=this.#t;return t&&e({previous:void 0,next:t}),()=>{this.#e.delete(e)}}#r(e){for(let t of this.#e)t(e)}};function ee(e){return new $(e)}var te=class{walletAccount;#e=!1;constructor(e){this.walletAccount=new $(e)}requireWalletAccount(e){let n=this.walletAccount.getSnapshot();if(!n)throw new t.z(e);return n}dispose(){this.#e||(this.#e=!0,this.onDispose())}[Symbol.dispose](){this.dispose()}onDispose(){}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return V}});
|
|
1
|
+
const e=require("./relayer.cjs"),t=require("./wrappers-registry.cjs"),n=require("./assertions.cjs"),r=require("./validation.cjs"),i=require("./chains.cjs");let a=require("viem"),o=require("zod/mini");function s(e){return`keypair:${e}`}function c(e){return`permits:${e.signerAddress}:${e.chainId}:${e.delegatorAddress}`}function l(e){return`permits-index:${e}`}function u(e){return(0,a.getAddress)(e)}const d=o.z.custom(e=>typeof e==`string`&&(0,a.isHex)(e,{strict:!0}),`expected 0x-prefixed hex string`),f=o.z.custom(e=>typeof e==`string`&&(0,a.isAddress)(e,{strict:!1}),`expected EVM address`),p=o.z.pipe(f,o.z.transform(u)),m=o.z.int().check(o.z.nonnegative()),h=o.z.int().check(o.z.positive()),g=o.z.int().check(o.z.nonnegative()),_=o.z.int().check(o.z.positive()),v=o.z.int().check(o.z.positive());function y(){return Math.floor(Date.now()/1e3)}function b(e){return[...new Set(e.map(u))].toSorted()}const x=`transportKeyPairTTL must be a positive integer number of seconds`,S=`permitTTL must be a positive integer number of days`,C=365*86400,w=o.z.int({error:x}).check(o.z.positive({error:x}),o.z.maximum(C,`transportKeyPairTTL must not exceed the fhevm ACL maximum of ${C}s (365 days)`)),T=o.z.int({error:S}).check(o.z.positive({error:S})),E=o.z.object({publicKey:d,privateKey:d,createdAt:m,expiresAt:h}),D=o.z.object({keypairPublicKey:d,signerAddress:p,delegatorAddress:p,chainId:v,signedContractAddresses:o.z.array(p).check(o.z.maxLength(10)),signature:d,startTimestamp:m,durationDays:_}),O=o.z.array(D),k=o.z.array(o.z.string());var A=class{#e;#t;#n;#r;#i=new Map;constructor(e){this.#e=e.generator,this.#t=e.storage,this.#n=e.ttl,this.#r=e.logger}async readStored(e){let n=s(e),r=await this.#t.get(n);if(r==null)return null;let i=E.safeParse(r);if(!i.success)return await t.L(`delete transport key pair entry`,()=>this.#t.delete(n),this.#r),null;let a=i.data;return y()>=a.expiresAt?(await t.L(`delete transport key pair entry`,()=>this.#t.delete(n),this.#r),null):a}async getOrCreate(e){let n=this.#i.get(e);if(n)return n;let r=(async()=>{let n=await this.readStored(e);if(n!==null)return n;let r=await this.#e(),i=y(),a={publicKey:r.publicKey,privateKey:r.privateKey,createdAt:i,expiresAt:i+this.#n},o=s(e);return await t.L(`persist transport key pair`,()=>this.#t.set(o,a),this.#r),a})().finally(()=>{this.#i.delete(e)});return this.#i.set(e,r),r}async clear(e){let n=s(e);await t.L(`delete transport key pair entry`,()=>this.#t.delete(n),this.#r)}};function j(e,t){let n=new Set(e.flatMap(e=>e.signedContractAddresses));return t.filter(e=>!n.has(e))}function M(e){let t=[];for(let n=0;n<e.length;n+=10)t.push(e.slice(n,n+10));return t}function N(e,t,n){return e.filter(e=>e.keypairPublicKey===t&&n<e.startTimestamp+e.durationDays*86400)}function P(e,t){let n=new Set(t);return e.filter(e=>!e.signedContractAddresses.some(e=>n.has(e)))}function F(e,t){return[...new Set([...e,...t])].toSorted()}function I(e,t,n){let r=new Set(n),i=e.filter(e=>new Set([...e.signedContractAddresses,...t]).size<=10);if(i.length===0)return null;function a(e){return e.signedContractAddresses.reduce((e,t)=>e+ +!!r.has(t),0)}let o=Math.max(...i.map(a));return i.filter(e=>a(e)===o).reduce((e,t)=>t.startTimestamp>e.startTimestamp?t:e)}var L=class{#e;#t;constructor(e){this.#e=e.storage,this.#t=e.logger}async list(e){let t=c(e),n=await this.#e.get(t);if(n==null)return[];let r=O.safeParse(n);return r.success?r.data:(await this.#a(t),await this.#i(e),[])}async listUsableAndPrune(e,n){let r=await this.list(e),i=N(r,n,Math.floor(Date.now()/1e3));if(i.length!==r.length){let n=c(e);i.length===0?(await this.#a(n),await this.#i(e)):await t.L(`update permit entry`,()=>this.#e.set(n,i),this.#t)}return i}async append(e,t){if(t.length===0)return;let n=t.map(e=>D.parse(e)),r=await this.list(e);await this.#e.set(c(e),[...r,...n]),await this.#r(e)}async replace(e,t,n){let r=D.parse(n),i=(await this.list(e)).filter(e=>e.signature!==t);await this.#e.set(c(e),[...i,r]),await this.#r(e)}async deletePermitsTouching(e,t){let n=await this.list(e);if(n.length===0)return;let r=c(e),i=P(n,t);i.length===0?(await this.#a(r),await this.#i(e)):await this.#e.set(r,i)}async clearAllForSigner(e){let n=l(e),r=await this.#n(n);await Promise.all(r.map(e=>this.#a(e))),await t.L(`delete permit index`,()=>this.#e.delete(n),this.#t)}async#n(e){let n=await this.#e.get(e);if(n==null)return[];let r=k.safeParse(n);return r.success?r.data:(await t.L(`delete permit index`,()=>this.#e.delete(e),this.#t),[])}async#r(e){let t=l(e.signerAddress),n=c(e),r=await this.#n(t);r.includes(n)||await this.#e.set(t,[...r,n])}async#i(e){let n=l(e.signerAddress),r=c(e),i=await this.#n(n),a=i.filter(e=>e!==r);a.length!==i.length&&(a.length===0?await t.L(`delete permit index`,()=>this.#e.delete(n),this.#t):await t.L(`update permit index`,()=>this.#e.set(n,a),this.#t))}async#a(e){await t.L(`delete permit entry`,()=>this.#e.delete(e),this.#t)}},R=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=new A({generator:()=>e.relayer.generateTransportKeyPair(),storage:e.storage,ttl:e.transportKeyPairTTL,logger:e.logger}),this.#t=new L({storage:e.permitStorage??e.storage,logger:e.logger}),this.#n=e.relayer,this.#r=e.signer,this.#i=e.permitTTL,this.#a=e.logger}async grantPermit(e,n){let r=this.#r.requireWalletAccount(`grantPermit`),i=u(r.address),a=b(e),o=await this.#e.getOrCreate(i);if(a.length===0)return{keypair:o,permits:[]};let s={signerAddress:i,chainId:r.chainId,delegatorAddress:n?u(n):i},c=await this.#t.listUsableAndPrune(s,o.publicKey),l=j(c,a);if(l.length>0){let e=I(c,l,a);if(e!==null){let n=F(e.signedContractAddresses,l),r=await this.#o({chunk:n,keypair:o,scope:s});await t.L(`replace permit`,()=>this.#t.replace(s,e.signature,r),this.#a),c[c.indexOf(e)]=r}else for(let e of M(l)){let n=await this.#o({chunk:e,keypair:o,scope:s});c.push(n),await t.L(`persist permit`,()=>this.#t.append(s,[n]),this.#a)}}let d=new Set(a);return{keypair:o,permits:c.filter(e=>e.signedContractAddresses.some(e=>d.has(e)))}}async hasPermit(e,t){if(e.length===0)return!0;let n=this.#r.walletAccount.getSnapshot();if(!n)return!1;let r=u(n.address),i=await this.#e.readStored(r);if(i===null)return!1;let a={signerAddress:r,chainId:n.chainId,delegatorAddress:t?u(t):r};return j(await this.#t.listUsableAndPrune(a,i.publicKey),b(e)).length===0}async revokePermits(e){let t=this.#r.requireWalletAccount(`revokePermits`),n=u(t.address);if(e===void 0){await this.#t.clearAllForSigner(n);return}let r=b(e);if(r.length===0)return;let i=t.chainId;await this.#t.deletePermitsTouching({signerAddress:n,chainId:i,delegatorAddress:n},r)}async clearCredentials(){let e=u(this.#r.requireWalletAccount(`clearCredentials`).address);await this.#e.clear(e),await this.#t.clearAllForSigner(e)}async warmTransportKeyPair(e){await this.#e.getOrCreate(u(e))}async handleWalletAccountChange(e,t){let n=e?u(e.address):void 0;n!==(t?u(t.address):void 0)&&n&&(await this.#e.clear(n),await this.#t.clearAllForSigner(n))}async#o(n){let{chunk:r,keypair:i,scope:a}=n,o=y(),s=a.delegatorAddress!==a.signerAddress;try{let e=s?await this.#n.createDelegatedUserDecryptEIP712(i.publicKey,r,a.delegatorAddress,o,this.#i):await this.#n.createEIP712(i.publicKey,r,o,this.#i),t=await this.#r.signTypedData(e);return{keypairPublicKey:i.publicKey,signerAddress:a.signerAddress,delegatorAddress:a.delegatorAddress,chainId:a.chainId,signedContractAddresses:r,signature:t,startTimestamp:o,durationDays:this.#i}}catch(n){throw n instanceof e.r?n:t.G(n,`Credential signing failed`)}}},z=class{#e;#t=`[zama-sdk]`;constructor(e){this.#e=e}error(e,t){this.#e?.error(`${this.#t} ${e}`,t)}warn(e,t){this.#e?.warn(`${this.#t} ${e}`,t)}info(e,t){this.#e?.info(`${this.#t} ${e}`,t)}debug(e,t){this.#e?.debug(`${this.#t} ${e}`,t)}},B=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const V=new B;function H(){return typeof window<`u`?new r.n(`CredentialStore`):new B}function U(e=H(),t=e){return{storage:e,permitStorage:t}}function W(t,n){let r=new Map(t.map(e=>[e.id,e]));if(r.size!==t.length){let n=t.map(e=>e.id);throw new e.t(`Duplicate chain id(s) [${[...new Set(n.filter((e,t)=>n.indexOf(e)!==t))].join(`, `)}] in the chains array. Each chain id must appear only once. Note: hardhat and anvil are aliases (both use 31337).`)}let i=new Map(Object.entries(n)),a=new Map;for(let t of r.keys()){let n=r.get(t),o=i.get(String(t));if(!o)throw new e.t(`Chain ${t} has no relayer configured. Add a relayer entry: relayers: { [${t}]: web() }`);if(!n)throw new e.t(`Chain ${t} has a relayer configured but no entry in the chains array. Add the chain config to the chains array.`);a.set(t,{chain:n,relayer:o})}let o=new Set(Object.keys(n).map(Number)),s=new Set([...o].filter(e=>!r.has(e)));if(s.size>0)throw new e.t(`Relayer entries for chain(s) [${[...s].join(`, `)}] have no matching entry in the chains array. Remove them or add the corresponding chain config.`);return a}var G=class{#e;#t;#n;#r;constructor(t,n,r){if(t.length===0)throw new e.t(`At least one chain is required.`);this.#e=new Map(t.map(e=>[e.id,e])),this.#r=t[0].id;let i=W(t,n),a=new Map;for(let[e,t]of i){let n=t.relayer,r=a.get(n);r||(r=[],a.set(n,r)),r.push([e,t.chain])}let o=new Map,s=[];try{for(let[e,t]of a){let n=t.map(([,e])=>e),i=e.createWorker?.(n,r);i&&s.push(i);for(let[n,a]of t)o.set(n,e.createRelayer(a,i,r))}}catch(e){for(let e of s)try{e.terminate()}catch{}throw e}this.#t=o,this.#n=s}get chains(){return[...this.#e.values()]}get chain(){let e=this.#e.get(this.#r);return n.r(e,`RelayerDispatcher: chain`),e}switchChain(t){if(!this.#e.has(t))throw new e.t(`No relayer configured for chain ${t}. Add it to the chains array.`);this.#r=t}get#i(){let e=this.#t.get(this.#r);return n.r(e,`RelayerDispatcher: relayer`),e}generateTransportKeyPair(){return this.#i.generateTransportKeyPair()}createEIP712(e,t,n,r){return this.#i.createEIP712(e,t,n,r)}encrypt(e){return this.#i.encrypt(e)}userDecrypt(e){return this.#i.userDecrypt(e)}publicDecrypt(e){return this.#i.publicDecrypt(e)}createDelegatedUserDecryptEIP712(e,t,n,r,i){return this.#i.createDelegatedUserDecryptEIP712(e,t,n,r,i)}delegatedUserDecrypt(e){return this.#i.delegatedUserDecrypt(e)}requestZKProofVerification(e){return this.#i.requestZKProofVerification(e)}fetchFheEncryptionKeyBytes(){return this.#i.fetchFheEncryptionKeyBytes()}getPublicParams(e){return this.#i.getPublicParams(e)}getAclAddress(){return this.#i.getAclAddress()}terminate(){let e=[];for(let t of new Set(this.#t.values()))try{t.terminate()}catch(t){e.push(n.h(t))}for(let t of new Set(this.#n))try{t.terminate()}catch(t){e.push(n.h(t))}if(e.length>0)throw AggregateError(e,`Failed to terminate relayer resources`)}[Symbol.dispose](){this.terminate()}};const K={[i.s.id]:i.s.registryAddress,[i.c.id]:i.c.registryAddress,[i.a.id]:i.a.registryAddress,[i.o.id]:i.o.registryAddress,[i.n.id]:i.n.registryAddress},q=o.z.record(o.z.string().check(o.z.regex(/^\d+$/,`expected numeric chain id key`)),p),J=g,Y=300*1e3;var X=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},K,r.t(o.z.optional(q),e.registryAddresses)),this.#t=r.t(J,e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.provider.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,a.getAddress)(n)}async listPairs(n={}){let r=n.page??1,i=n.pageSize??100,a=n.metadata??!1;if(r<1)throw new e.t(`page must be >= 1, got ${r}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.provider.readContract(t.a(o));c=this.#i(s,Number(e))}let l=BigInt((r-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:r,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(t.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:r,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Y:void 0)}return{items:m,total:c,page:r,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(t.b(e.tokenAddress)),this.provider.readContract(t.x(e.tokenAddress)),this.provider.readContract(t.v(e.tokenAddress)),this.provider.readContract(t.y(e.tokenAddress)),this.provider.readContract(t.b(e.confidentialTokenAddress)),this.provider.readContract(t.x(e.confidentialTokenAddress)),this.provider.readContract(t.v(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let n=await this.getRegistryAddress(),r=(0,a.getAddress)(e),i=`ct:${n}:${r}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.provider.readContract(t.t(n,r));return c===a.zeroAddress?this.#i(i,null,Y):this.#i(i,{confidentialTokenAddress:c,isValid:s})}async getUnderlyingToken(e){let n=await this.getRegistryAddress(),r=(0,a.getAddress)(e),i=`ut:${n}:${r}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.provider.readContract(t.n(n,r));return c===a.zeroAddress?this.#i(i,null,Y):this.#i(i,{tokenAddress:c,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(t.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(t.a(e))}async getTokenPairsSlice(e,n){let r=await this.getRegistryAddress();return this.provider.readContract(t.o(r,e,n))}async getTokenPair(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.r(n,e))}async getConfidentialTokenAddress(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.t(n,(0,a.getAddress)(e)))}async getTokenAddress(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.n(n,(0,a.getAddress)(e)))}async isConfidentialTokenValid(e){let n=await this.getRegistryAddress();return this.provider.readContract(t.s(n,(0,a.getAddress)(e)))}};function Z(e,t,n){let{storage:i,permitStorage:a}=U(n.storage,n.permitStorage),o=new z(n.logger),s=new G(n.chains,n.relayers,o);return{chains:n.chains,relayer:s,provider:t,signer:e,storage:i,permitStorage:a,transportKeyPairTTL:r.t(w,n.transportKeyPairTTL??2592e3),permitTTL:r.t(T,n.permitTTL??30),registryTTL:r.t(J,n.registryTTL??86400),logger:o,onEvent:n.onEvent}}function Q(e,t){return e?.address===t?.address&&e?.chainId===t?.chainId}var $=class{#e=new Set;#t;#n;constructor(e){this.#t=e,this.#n=e!==void 0}getSnapshot(){return this.#t}isReady(){return this.#n}setSnapshot(e){this.#n=!0;let t=this.#t;Q(t,e)||(this.#t=e,this.#r({previous:t,next:e}))}subscribe(e){this.#e.add(e);let t=this.#t;return t&&e({previous:void 0,next:t}),()=>{this.#e.delete(e)}}#r(e){for(let t of this.#e)t(e)}};function ee(e){return new $(e)}var te=class{walletAccount;#e=!1;constructor(e){this.walletAccount=new $(e)}requireWalletAccount(e){let n=this.walletAccount.getSnapshot();if(!n)throw new t.V(e);return n}dispose(){this.#e||(this.#e=!0,this.onDispose())}[Symbol.dispose](){this.dispose()}onDispose(){}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return te}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return V}});
|
|
2
2
|
//# sourceMappingURL=base-signer.cjs.map
|