@zama-fhe/sdk 3.7.0-beta.8 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/cjs/base-signer.cjs +1 -1
  2. package/dist/cjs/base-signer.cjs.map +1 -1
  3. package/dist/cjs/erc165.cjs +1 -1
  4. package/dist/cjs/erc165.cjs.map +1 -1
  5. package/dist/cjs/fhevm-relayer.cjs +1 -1
  6. package/dist/cjs/fhevm-relayer.cjs.map +1 -1
  7. package/dist/cjs/index.cjs +1 -1
  8. package/dist/cjs/index.cjs.map +1 -1
  9. package/dist/cjs/telemetry.cjs +1 -1
  10. package/dist/cjs/telemetry.cjs.map +1 -1
  11. package/dist/cjs/token.cjs +1 -1
  12. package/dist/cjs/token.cjs.map +1 -1
  13. package/dist/cjs/vaults/index.cjs +1 -1
  14. package/dist/cjs/web/index.cjs +1 -1
  15. package/dist/cjs/wrapped-token.cjs +1 -1
  16. package/dist/esm/base-signer-b1ff2VPI.js +2 -0
  17. package/dist/esm/base-signer-b1ff2VPI.js.map +1 -0
  18. package/dist/esm/cleartext/index.js +1 -1
  19. package/dist/esm/{cleartext-C0ba9z6Z.js → cleartext-CiE1gO7Y.js} +2 -2
  20. package/dist/esm/{cleartext-C0ba9z6Z.js.map → cleartext-CiE1gO7Y.js.map} +1 -1
  21. package/dist/esm/erc165-BAd2z3ay.js +2 -0
  22. package/dist/esm/erc165-BAd2z3ay.js.map +1 -0
  23. package/dist/esm/ethers/index.js +1 -1
  24. package/dist/esm/fhevm-relayer-DXLb4mIw.js +8 -0
  25. package/dist/esm/{fhevm-relayer-BWhXU1WB.js.map → fhevm-relayer-DXLb4mIw.js.map} +1 -1
  26. package/dist/esm/{index-DHMs4ZRb.d.ts → index-BKMce5ya.d.ts} +2 -2
  27. package/dist/esm/{decryption-q0ODuDDS.d.ts → index-CpQK8U4F.d.ts} +2 -6
  28. package/dist/esm/index.d.ts +3 -4
  29. package/dist/esm/index.js +1 -1
  30. package/dist/esm/index.js.map +1 -1
  31. package/dist/esm/node/index.js +1 -1
  32. package/dist/esm/query/index.d.ts +2 -3
  33. package/dist/esm/query/index.js +1 -1
  34. package/dist/esm/telemetry-Dll0Swdj.js +2 -0
  35. package/dist/esm/{telemetry-DvJV3oBk.js.map → telemetry-Dll0Swdj.js.map} +1 -1
  36. package/dist/esm/token-CTvEGQmH.js +2 -0
  37. package/dist/esm/token-CTvEGQmH.js.map +1 -0
  38. package/dist/esm/vaults/index.d.ts +1 -2
  39. package/dist/esm/vaults/index.js +1 -1
  40. package/dist/esm/viem/index.js +1 -1
  41. package/dist/esm/web/index.d.ts +16 -1
  42. package/dist/esm/web/index.js +1 -1
  43. package/dist/esm/wrapped-token-IDUEFpZx.js +2 -0
  44. package/dist/esm/{wrapped-token-3usJd0oi.js.map → wrapped-token-IDUEFpZx.js.map} +1 -1
  45. package/package.json +1 -15
  46. package/dist/cjs/fatal-batch.cjs +0 -2
  47. package/dist/cjs/fatal-batch.cjs.map +0 -1
  48. package/dist/cjs/internal/index.cjs +0 -2
  49. package/dist/cjs/internal/index.cjs.map +0 -1
  50. package/dist/cjs/signing.cjs +0 -2
  51. package/dist/cjs/signing.cjs.map +0 -1
  52. package/dist/esm/base-signer-CNHZZnr2.js +0 -2
  53. package/dist/esm/base-signer-CNHZZnr2.js.map +0 -1
  54. package/dist/esm/encrypt-worker-client-CKTlhAGI.d.ts +0 -19
  55. package/dist/esm/erc165-B8gx2luK.js +0 -2
  56. package/dist/esm/erc165-B8gx2luK.js.map +0 -1
  57. package/dist/esm/fatal-batch-BiiS7KdS.js +0 -2
  58. package/dist/esm/fatal-batch-BiiS7KdS.js.map +0 -1
  59. package/dist/esm/fhevm-relayer-BWhXU1WB.js +0 -8
  60. package/dist/esm/index-B09m_e9L.d.ts +0 -1
  61. package/dist/esm/internal/index.d.ts +0 -26
  62. package/dist/esm/internal/index.js +0 -2
  63. package/dist/esm/internal/index.js.map +0 -1
  64. package/dist/esm/signing-C6nbPCyd.js +0 -2
  65. package/dist/esm/signing-C6nbPCyd.js.map +0 -1
  66. package/dist/esm/telemetry-DvJV3oBk.js +0 -2
  67. package/dist/esm/token-g6sinwTx.js +0 -2
  68. package/dist/esm/token-g6sinwTx.js.map +0 -1
  69. package/dist/esm/wrapped-token-3usJd0oi.js +0 -2
@@ -4,5 +4,5 @@ var e=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);const t=r
4
4
  * Copyright 2019 Google LLC
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- var u=e(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n.Comlink={}))})(e,(function(e){"use strict";let t=Symbol(`Comlink.proxy`),n=Symbol(`Comlink.endpoint`),r=Symbol(`Comlink.releaseProxy`),i=Symbol(`Comlink.finalizer`),a=Symbol(`Comlink.thrown`),o=e=>typeof e==`object`&&!!e||typeof e==`function`,s=new Map([[`proxy`,{canHandle:e=>o(e)&&e[t],serialize(e){let{port1:t,port2:n}=new MessageChannel;return l(e,t),[n,[n]]},deserialize(e){return e.start(),f(e)}}],[`throw`,{canHandle:e=>o(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(Error(e.value.message),e.value):e.value}}]]);function c(e,t){for(let n of e)if(t===n||n===`*`||n instanceof RegExp&&n.test(t))return!0;return!1}function l(e,t=globalThis,n=[`*`]){t.addEventListener(`message`,function r(o){if(!o||!o.data)return;if(!c(n,o.origin)){console.warn(`Invalid origin '${o.origin}' for comlink proxy`);return}let{id:s,type:u,path:f}=Object.assign({path:[]},o.data),p=(o.data.argumentList||[]).map(D),m;try{let t=f.slice(0,-1).reduce((e,t)=>e[t],e),n=f.reduce((e,t)=>e[t],e);switch(u){case`GET`:m=n;break;case`SET`:t[f.slice(-1)[0]]=D(o.data.value),m=!0;break;case`APPLY`:m=n.apply(t,p);break;case`CONSTRUCT`:m=w(new n(...p));break;case`ENDPOINT`:{let{port1:t,port2:n}=new MessageChannel;l(e,n),m=C(t,[t])}break;case`RELEASE`:m=void 0;break;default:return}}catch(e){m={value:e,[a]:0}}Promise.resolve(m).catch(e=>({value:e,[a]:0})).then(n=>{let[a,o]=E(n);t.postMessage(Object.assign(Object.assign({},a),{id:s}),o),u===`RELEASE`&&(t.removeEventListener(`message`,r),d(t),i in e&&typeof e[i]==`function`&&e[i]())}).catch(e=>{let[n,r]=E({value:TypeError(`Unserializable return value`),[a]:0});t.postMessage(Object.assign(Object.assign({},n),{id:s}),r)})}),t.start&&t.start()}function u(e){return e.constructor.name===`MessagePort`}function d(e){u(e)&&e.close()}function f(e,t){let n=new Map;return e.addEventListener(`message`,function(e){let{data:t}=e;if(!t||!t.id)return;let r=n.get(t.id);if(r)try{r(t)}finally{n.delete(t.id)}}),y(e,n,[],t)}function p(e){if(e)throw Error(`Proxy has been released and is not useable`)}function m(e){return O(e,new Map,{type:`RELEASE`}).then(()=>{d(e)})}let h=new WeakMap,g=`FinalizationRegistry`in globalThis&&new FinalizationRegistry(e=>{let t=(h.get(e)||0)-1;h.set(e,t),t===0&&m(e)});function _(e,t){let n=(h.get(t)||0)+1;h.set(t,n),g&&g.register(e,t,e)}function v(e){g&&g.unregister(e)}function y(e,t,i=[],a=function(){}){let o=!1,s=new Proxy(a,{get(n,a){if(p(o),a===r)return()=>{v(s),m(e),t.clear(),o=!0};if(a===`then`){if(i.length===0)return{then:()=>s};let n=O(e,t,{type:`GET`,path:i.map(e=>e.toString())}).then(D);return n.then.bind(n)}return y(e,t,[...i,a])},set(n,r,a){p(o);let[s,c]=E(a);return O(e,t,{type:`SET`,path:[...i,r].map(e=>e.toString()),value:s},c).then(D)},apply(r,a,s){p(o);let c=i[i.length-1];if(c===n)return O(e,t,{type:`ENDPOINT`}).then(D);if(c===`bind`)return y(e,t,i.slice(0,-1));let[l,u]=x(s);return O(e,t,{type:`APPLY`,path:i.map(e=>e.toString()),argumentList:l},u).then(D)},construct(n,r){p(o);let[a,s]=x(r);return O(e,t,{type:`CONSTRUCT`,path:i.map(e=>e.toString()),argumentList:a},s).then(D)}});return _(s,e),s}function b(e){return Array.prototype.concat.apply([],e)}function x(e){let t=e.map(E);return[t.map(e=>e[0]),b(t.map(e=>e[1]))]}let S=new WeakMap;function C(e,t){return S.set(e,t),e}function w(e){return Object.assign(e,{[t]:!0})}function T(e,t=globalThis,n=`*`){return{postMessage:(t,r)=>e.postMessage(t,n,r),addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}}function E(e){for(let[t,n]of s)if(n.canHandle(e)){let[r,i]=n.serialize(e);return[{type:`HANDLER`,name:t,value:r},i]}return[{type:`RAW`,value:e},S.get(e)||[]]}function D(e){switch(e.type){case`HANDLER`:return s.get(e.name).deserialize(e.value);case`RAW`:return e.value}}function O(e,t,n,r){return new Promise(i=>{let a=k();t.set(a,i),e.start&&e.start(),e.postMessage(Object.assign({id:a},n),r)})}function k(){return[,,,,].fill(0).map(()=>Math.floor(Math.random()*(2**53-1)).toString(16)).join(`-`)}e.createEndpoint=n,e.expose=l,e.finalizer=i,e.proxy=w,e.proxyMarker=t,e.releaseProxy=r,e.transfer=C,e.transferHandlers=s,e.windowEndpoint=T,e.wrap=f}))}))();function d(e){return typeof e==`object`&&!!e&&e.wireError===!0}const f=[`statusCode`,`status`,`retryAfter`,`timeoutMs`,`relayerApiError`,`code`,`data`,`shortMessage`,`details`,`error`,`info`];function p(e){try{return structuredClone(e),!0}catch{return!1}}function m(e){let n=e.response;return t.x(n?.headers)}function h(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function g(e){let n={};for(let t of f){let r=e[t];r!==void 0&&p(r)&&(n[t]=r)}if(!t.y(n.retryAfter)){let t=m(e);t!==void 0&&(n.retryAfter=t)}return n}function _(e,t=6){if(d(e))return e;let n=e=>t>0&&e!==void 0?_(e,t-1):void 0;if(e instanceof Error)return{wireError:!0,name:e.name,message:e.message,stack:e.stack,props:g(e),cause:n(e.cause)};if(typeof e==`object`&&e){let{message:t,cause:r}=e;return{wireError:!0,name:`Error`,message:typeof t==`string`?t:h(e),stack:void 0,props:g(e),cause:n(r)}}return{wireError:!0,name:`Error`,message:typeof e==`string`?e:h(e),stack:void 0,props:{},cause:void 0}}function v(e){let t=Error(e.message,e.cause?{cause:v(e.cause)}:{});return t.name=e.name,e.stack!==void 0&&(t.stack=e.stack),Object.assign(t,e.props),t}function y(){throw Error(`The encrypt worker is only available in the ESM build.`)}const b={spawn:1e4,init:3e5},x=new WeakSet;var S=class extends Error{crashed;constructor(e,t){super(e,t),this.name=`WorkerUnavailableError`,this.crashed=t?.crashed??!1}};function C(e){if(typeof e!=`object`||!e)return!1;let{name:t,message:n}=e;return t===`DataCloneError`||t===`TypeError`&&typeof n==`string`&&n.includes(`Unserializable return value`)}function w(e){if(e?.aborted)throw e.reason??new DOMException(`The operation was aborted.`,`AbortError`)}const T={count:0,last:void 0,warnedFor:-1};function E(e){if(e===void 0)return{key:e,transfers:[]};let t=e.publicKeyBytes.bytes,n=e.crsBytes.bytes;if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array))return{key:e,transfers:[]};let r=t.slice(),i=n.slice();return{key:{...e,publicKeyBytes:{...e.publicKeyBytes,bytes:r},crsBytes:{...e.crsBytes,bytes:i}},transfers:[r.buffer,i.buffer]}}function D(){let e,t=new Promise((t,n)=>{e=n});return t.catch(()=>{}),{initPromise:void 0,worker:void 0,api:void 0,doomed:t,doom:e}}var O=class{#e;#t;#n=!1;#r=T;#i=0;#a=new Map;#o;#s=0;#c=!1;constructor(e){this.#e=e}init=()=>{let e=this.#t??=D();if(e.initPromise===void 0){let t=this.#f(()=>this.#u(e)).catch(n=>{throw e.initPromise===t&&(e.initPromise=void 0),n});e.initPromise=t}return e.initPromise};encryptValue=e=>this.#f(()=>this.#l(t=>t.encryptValue(e),(t,n,r)=>t.encryptValue(n,{...e,options:r}),e.options));encryptValues=e=>this.#f(()=>this.#l(t=>t.encryptValues(e),(t,n,r)=>t.encryptValues(n,{...e,options:r}),e.options));dispose(){this.#c=!0,this.#p()}async#l(e,t,n){let{signal:r,onProgress:i,...a}=n??{};w(r),await this.init(),w(r);let o=this.#t,s=o?.api;if(this.#o!==void 0&&(this.#n||s===void 0))return e(await this.#o);if(o===void 0||s===void 0)return e(await this.#b(o,this.#r.last??new S(`Encrypt worker not running.`)));let c=this.#i++,l=()=>void s.abort(c).catch(()=>{});r?.addEventListener(`abort`,l,{once:!0}),i&&this.#a.set(c,i);try{let e=await this.#v(o,t(s,c,a));return this.#r=T,e}catch(t){if(t instanceof S)return e(await this.#b(o,t));throw t}finally{this.#a.delete(c),r?.removeEventListener(`abort`,l)}}async#u(e){if(this.#n)return;let t=this.#e.blockedReason;if(t!==void 0){await this.#b(e,new S(t));return}let n=await this.#e.prefetchKey();try{let t=await this.#h(e),r=this.#e.network,i=typeof r==`string`?null:(0,u.proxy)(async e=>{try{return await r.request(e)}catch(e){throw _(e)}}),a=(0,u.proxy)((e,t)=>{try{this.#e.logger[e](t)}catch(e){this.#d(`logger`,e)}}),o=(0,u.proxy)((e,t)=>{try{this.#a.get(e)?.(t)}catch(e){this.#d(`onProgress`,e)}}),s=E(n);await this.#v(e,t.init((0,u.transfer)({...this.#e.initPayload,clientOptions:{...this.#e.initPayload.clientOptions,fheEncryptionKey:s.key},rpcUrl:typeof r==`string`?r:void 0},s.transfers),i,a,o),{ms:this.#e.timeouts.init,operation:`init`}),e.api=t,this.#r={...this.#r,last:void 0}}catch(t){if(!(t instanceof S))throw this.#y(e,new S(`Encrypt worker init failed.`)),t;await this.#b(e,t)}}#d(e,t){let n=t instanceof Error?t.message:String(t);try{this.#e.logger.warn(`Encrypt offload ${e} callback threw: ${n}`)}catch{}}async#f(e){this.#s++;try{return await e()}finally{this.#s--,this.#p()}}#p(){!this.#c||this.#s>0||(this.#c=!1,this.#t?.worker?.terminate(),this.#t=void 0,this.#o=void 0,this.#n=!1,this.#r=T)}#m(){let e=this.#e.workerSource;if(e===void 0)return y();if(typeof e==`function`){let t=e();return x.has(t)&&this.#e.logger.warnAlways(`The offloadWorker factory returned a worker it already handed out; each call must construct a fresh Worker.`),x.add(t),t}return new Worker(e,{type:`module`,name:`zama-fhe-encrypt`})}async#h(e){let t;try{t=this.#m()}catch(e){throw new S(e instanceof Error?e.message:String(e),{cause:e})}e.worker=t;let n=await this.#g(e,t);return this.#_(e,t),n}#g(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(a),t.removeEventListener(`message`,o),t.removeEventListener(`error`,s)},a=setTimeout(()=>{i(),r(new S(`Encrypt worker did not start within ${this.#e.timeouts.spawn}ms.`))},this.#e.timeouts.spawn),o=e=>{e.data===`zama-encrypt-worker-ready`&&(i(),n((0,u.wrap)(t)))},s=t=>{i();let n=t.message||`Encrypt worker error.`;r(new S(n)),this.#y(e,new S(n))};t.addEventListener(`message`,o),t.addEventListener(`error`,s)})}#_(e,t){t.addEventListener(`error`,t=>{if(this.#t!==e)return;let n=new S(t.message||`Encrypt worker error.`,{crashed:!0});this.#r={...this.#r,count:this.#r.count+1,last:n},this.#y(e,n)})}async#v(e,t,n){let r=n===void 0?void 0:setTimeout(()=>{this.#y(e,new S(`Encrypt worker ${n.operation} timed out after ${n.ms}ms.`))},n.ms);try{return await Promise.race([t.catch(e=>{let t=d(e)?v(e):e;throw C(t)?new S(t.message,{cause:t}):t}),e.doomed])}finally{r!==void 0&&clearTimeout(r)}}#y(e,t){e!==void 0&&(this.#t===e&&(this.#t=void 0),e.worker?.terminate(),e.worker=void 0,e.api=void 0,e.initPromise=void 0,e.doom(t))}async#b(e,t){let r=t instanceof Error?t.message:String(t);if(this.#e.strict)throw this.#y(e,new S(`Encrypt worker unavailable.`)),new n.n(`Encrypt offload required (offloadEncrypt: true) but unavailable: ${r}`,{cause:t});let{transient:i,pinning:a}=this.#x(t);if(this.#n||=!i,this.#y(e,new S(`Encrypt worker degraded to inline.`)),this.#S(r,i,a),this.#o===void 0){let e=(async()=>{let e=this.#e.createInlineClient();return await e.init(),e})().catch(t=>{throw this.#o===e&&(this.#o=void 0),this.#e.logger.warnAlways(`Encrypt inline fallback failed to initialize: ${t instanceof Error?t.message:String(t)}`),t});this.#o=e}return this.#o}#x(e){let t=e instanceof S&&e.crashed&&this.#r.count<2;return{transient:t,pinning:!t&&!this.#n}}#S(e,t,n){if(!n&&this.#r.warnedFor===this.#r.count)return;this.#r={...this.#r,warnedFor:this.#r.count};let r=t?`in-flight encryption falls back`:`encryption falls back`;this.#e.logger.warnAlways(`Encrypt offload unavailable, ${r} to the calling thread: ${e}`)}},k=class{#e;#t;#n;#r;#i;#a;#o;constructor(e){this.#e=e.chain;let{timeout:t,debug:n,batchRpcCalls:r,moduleVersions:i,fheEncryptionKey:o}=e.options??{},u=this.#e.auth?M(this.#e.auth):void 0,d={publicClient:(0,a.createPublicClient)({transport:typeof this.#e.network==`string`?(0,a.http)(this.#e.network):(0,a.custom)(this.#e.network)}),chain:l(this.#e),options:{batchRpcCalls:r,moduleVersions:i,fheEncryptionKey:o}};this.#i={...u!==void 0&&{auth:u},...t!==void 0&&{timeout:t},...n!==void 0&&{debug:n}},this.#a=e.telemetry;let f=()=>this.#t.fetchFheEncryptionKeyBytes({options:this.#c(void 0)}),p=e=>({init:async()=>{await f(),await e.init()},encryptValue:t=>e.encryptValue(t),encryptValues:t=>e.encryptValues(t),fetchFheEncryptionKeyBytes:t=>e.fetchFheEncryptionKeyBytes(t)});e.cleartext?(this.#t=(0,c.createFhevmCleartextBaseClient)(d),this.#n=(0,c.createFhevmCleartextDecryptClient)(d),this.#r=p((0,c.createFhevmCleartextEncryptClient)(d))):(this.#t=(0,s.createFhevmBaseClient)(d),this.#n=(0,s.createFhevmDecryptClient)(d),this.#r=this.#s(e,d,{prefetchKey:f,createInlineClient:()=>p((0,s.createFhevmEncryptClient)(d))}))}#s(e,t,n){let i=e.offloadEncrypt??!1,a=i===!0,o=typeof Worker==`function`&&(e.offloadWorker!==void 0||!1);if(i===!1||!(a||o))return n.createInlineClient();let s=r.t(),c=j(s);if(c!==void 0&&!a)return e.logger.warnAlways(`Encryption runs on the calling thread: ${c}.`),n.createInlineClient();let l=new O({initPayload:{chain:t.chain,clientOptions:t.options,runtime:s??{}},network:this.#e.network,prefetchKey:n.prefetchKey,createInlineClient:n.createInlineClient,logger:e.logger,timeouts:e.offloadTimeouts??b,workerSource:e.offloadWorker,blockedReason:c,strict:a});return{init:()=>l.init(),encryptValue:e=>l.encryptValue(e),encryptValues:e=>l.encryptValues(e),fetchFheEncryptionKeyBytes:e=>this.#t.fetchFheEncryptionKeyBytes(e),dispose:()=>l.dispose()}}get chain(){return this.#e}#c(e){let{operation:t,...n}={...this.#i,...e};return this.#a===void 0?n:{...n,headers:{...n.headers,...i.n(this.#a,t)}}}#l=()=>(this.#o??=this.#r.init().catch(e=>{throw this.#o=void 0,e}),this.#o);dispose=()=>{this.#o=void 0,this.#r.dispose?.()};decryptPublicValue=async e=>(await this.#t.init(),this.#t.decryptPublicValue({...e,options:this.#c(e.options)}));decryptPublicValues=async e=>(await this.#t.init(),this.#t.decryptPublicValues({...e,options:this.#c(e.options)}));decryptPublicValuesWithSignatures=async e=>(await this.#t.init(),this.#t.decryptPublicValuesWithSignatures({...e,options:this.#c(e.options)}));encryptValue=async e=>(await this.#l(),this.#r.encryptValue({...e,options:this.#c(e.options)}));encryptValues=async e=>(await this.#l(),this.#r.encryptValues({...e,options:this.#c(e.options)}));decryptValue=async e=>(await this.#n.init(),this.#n.decryptValue({...e,options:this.#c(e.options)}));decryptValues=async e=>(await this.#n.init(),this.#n.decryptValues({...e,options:this.#c(e.options)}));decryptValuesFromPairs=async e=>(await this.#n.init(),this.#n.decryptValuesFromPairs({...e,options:this.#c(e.options)}));fetchFheEncryptionKeyBytes=async e=>(await this.#t.init(),this.#t.fetchFheEncryptionKeyBytes({...e,options:this.#c(e?.options)}));signDecryptionPermit=async e=>(await this.#t.init(),this.#t.signDecryptionPermit(e));createUnsignedLegacyDecryptionPermitEip712=e=>(0,o.createUnsignedLegacyDecryptionPermitEip712)(this.#t,e);serializeTransportKeyPair=e=>this.#n.serializeTransportKeyPair(e);serializeSignedDecryptionPermit=e=>this.#t.serializeSignedDecryptionPermit(e);parseTransportKeyPair=async e=>(await this.#n.init(),this.#n.parseTransportKeyPair(e));parseSignedDecryptionPermit=async e=>{await this.#t.init();let{serializedPermit:t}=e;return this.#t.parseSignedDecryptionPermit({...e,serializedPermit:{...t,signature:A(t.signature)}})};generateTransportKeyPair=async()=>(await this.#n.init(),this.#n.generateTransportKeyPair())};function A(e){if(e.length!==132)return e;let t=parseInt(e.slice(130),16);return t!==0&&t!==1?e:`${e.slice(0,130)}${t===0?`1b`:`1c`}`}function j(e){if(r.n())return`a runtime locateFile cannot cross the encrypt worker boundary`;if(e===void 0&&(0,s.hasFhevmRuntimeConfig)())return`a runtime config set outside createConfig cannot be replicated in the encrypt worker realm`}function M(e){let n=e.__type;switch(n){case`ApiKeyHeader`:return{type:n,value:e.value,header:e.header};case`ApiKeyCookie`:return{type:n,value:e.value,cookie:e.cookie};case`BearerToken`:return{type:n,token:e.token};default:throw new t.t(`Unknown auth type: ${String(n)}`)}}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return k}});
7
+ var u=e(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?r(e):typeof define==`function`&&define.amd?define([`exports`],r):(n=typeof globalThis<`u`?globalThis:n||self,r(n.Comlink={}))})(e,(function(e){"use strict";let t=Symbol(`Comlink.proxy`),n=Symbol(`Comlink.endpoint`),r=Symbol(`Comlink.releaseProxy`),i=Symbol(`Comlink.finalizer`),a=Symbol(`Comlink.thrown`),o=e=>typeof e==`object`&&!!e||typeof e==`function`,s=new Map([[`proxy`,{canHandle:e=>o(e)&&e[t],serialize(e){let{port1:t,port2:n}=new MessageChannel;return l(e,t),[n,[n]]},deserialize(e){return e.start(),f(e)}}],[`throw`,{canHandle:e=>o(e)&&a in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(Error(e.value.message),e.value):e.value}}]]);function c(e,t){for(let n of e)if(t===n||n===`*`||n instanceof RegExp&&n.test(t))return!0;return!1}function l(e,t=globalThis,n=[`*`]){t.addEventListener(`message`,function r(o){if(!o||!o.data)return;if(!c(n,o.origin)){console.warn(`Invalid origin '${o.origin}' for comlink proxy`);return}let{id:s,type:u,path:f}=Object.assign({path:[]},o.data),p=(o.data.argumentList||[]).map(D),m;try{let t=f.slice(0,-1).reduce((e,t)=>e[t],e),n=f.reduce((e,t)=>e[t],e);switch(u){case`GET`:m=n;break;case`SET`:t[f.slice(-1)[0]]=D(o.data.value),m=!0;break;case`APPLY`:m=n.apply(t,p);break;case`CONSTRUCT`:m=w(new n(...p));break;case`ENDPOINT`:{let{port1:t,port2:n}=new MessageChannel;l(e,n),m=C(t,[t])}break;case`RELEASE`:m=void 0;break;default:return}}catch(e){m={value:e,[a]:0}}Promise.resolve(m).catch(e=>({value:e,[a]:0})).then(n=>{let[a,o]=E(n);t.postMessage(Object.assign(Object.assign({},a),{id:s}),o),u===`RELEASE`&&(t.removeEventListener(`message`,r),d(t),i in e&&typeof e[i]==`function`&&e[i]())}).catch(e=>{let[n,r]=E({value:TypeError(`Unserializable return value`),[a]:0});t.postMessage(Object.assign(Object.assign({},n),{id:s}),r)})}),t.start&&t.start()}function u(e){return e.constructor.name===`MessagePort`}function d(e){u(e)&&e.close()}function f(e,t){let n=new Map;return e.addEventListener(`message`,function(e){let{data:t}=e;if(!t||!t.id)return;let r=n.get(t.id);if(r)try{r(t)}finally{n.delete(t.id)}}),y(e,n,[],t)}function p(e){if(e)throw Error(`Proxy has been released and is not useable`)}function m(e){return O(e,new Map,{type:`RELEASE`}).then(()=>{d(e)})}let h=new WeakMap,g=`FinalizationRegistry`in globalThis&&new FinalizationRegistry(e=>{let t=(h.get(e)||0)-1;h.set(e,t),t===0&&m(e)});function _(e,t){let n=(h.get(t)||0)+1;h.set(t,n),g&&g.register(e,t,e)}function v(e){g&&g.unregister(e)}function y(e,t,i=[],a=function(){}){let o=!1,s=new Proxy(a,{get(n,a){if(p(o),a===r)return()=>{v(s),m(e),t.clear(),o=!0};if(a===`then`){if(i.length===0)return{then:()=>s};let n=O(e,t,{type:`GET`,path:i.map(e=>e.toString())}).then(D);return n.then.bind(n)}return y(e,t,[...i,a])},set(n,r,a){p(o);let[s,c]=E(a);return O(e,t,{type:`SET`,path:[...i,r].map(e=>e.toString()),value:s},c).then(D)},apply(r,a,s){p(o);let c=i[i.length-1];if(c===n)return O(e,t,{type:`ENDPOINT`}).then(D);if(c===`bind`)return y(e,t,i.slice(0,-1));let[l,u]=x(s);return O(e,t,{type:`APPLY`,path:i.map(e=>e.toString()),argumentList:l},u).then(D)},construct(n,r){p(o);let[a,s]=x(r);return O(e,t,{type:`CONSTRUCT`,path:i.map(e=>e.toString()),argumentList:a},s).then(D)}});return _(s,e),s}function b(e){return Array.prototype.concat.apply([],e)}function x(e){let t=e.map(E);return[t.map(e=>e[0]),b(t.map(e=>e[1]))]}let S=new WeakMap;function C(e,t){return S.set(e,t),e}function w(e){return Object.assign(e,{[t]:!0})}function T(e,t=globalThis,n=`*`){return{postMessage:(t,r)=>e.postMessage(t,n,r),addEventListener:t.addEventListener.bind(t),removeEventListener:t.removeEventListener.bind(t)}}function E(e){for(let[t,n]of s)if(n.canHandle(e)){let[r,i]=n.serialize(e);return[{type:`HANDLER`,name:t,value:r},i]}return[{type:`RAW`,value:e},S.get(e)||[]]}function D(e){switch(e.type){case`HANDLER`:return s.get(e.name).deserialize(e.value);case`RAW`:return e.value}}function O(e,t,n,r){return new Promise(i=>{let a=k();t.set(a,i),e.start&&e.start(),e.postMessage(Object.assign({id:a},n),r)})}function k(){return[,,,,].fill(0).map(()=>Math.floor(Math.random()*(2**53-1)).toString(16)).join(`-`)}e.createEndpoint=n,e.expose=l,e.finalizer=i,e.proxy=w,e.proxyMarker=t,e.releaseProxy=r,e.transfer=C,e.transferHandlers=s,e.windowEndpoint=T,e.wrap=f}))}))();function d(e){return typeof e==`object`&&!!e&&e.wireError===!0}const f=[`statusCode`,`status`,`retryAfter`,`timeoutMs`,`relayerApiError`,`code`,`data`,`shortMessage`,`details`,`error`,`info`];function p(e){try{return structuredClone(e),!0}catch{return!1}}function m(e){let n=e.response;return t.x(n?.headers)}function h(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function g(e){let n={};for(let t of f){let r=e[t];r!==void 0&&p(r)&&(n[t]=r)}if(!t.y(n.retryAfter)){let t=m(e);t!==void 0&&(n.retryAfter=t)}return n}function _(e,t=6){if(d(e))return e;let n=e=>t>0&&e!==void 0?_(e,t-1):void 0;if(e instanceof Error)return{wireError:!0,name:e.name,message:e.message,stack:e.stack,props:g(e),cause:n(e.cause)};if(typeof e==`object`&&e){let{message:t,cause:r}=e;return{wireError:!0,name:`Error`,message:typeof t==`string`?t:h(e),stack:void 0,props:g(e),cause:n(r)}}return{wireError:!0,name:`Error`,message:typeof e==`string`?e:h(e),stack:void 0,props:{},cause:void 0}}function v(e){let t=Error(e.message,e.cause?{cause:v(e.cause)}:{});return t.name=e.name,e.stack!==void 0&&(t.stack=e.stack),Object.assign(t,e.props),t}function y(){throw Error(`The encrypt worker is only available in the ESM build.`)}const b={spawn:1e4,init:3e5},x=new WeakSet;var S=class extends Error{crashed;constructor(e,t){super(e,t),this.name=`WorkerUnavailableError`,this.crashed=t?.crashed??!1}};function C(e){if(typeof e!=`object`||!e)return!1;let{name:t,message:n}=e;return t===`DataCloneError`||t===`TypeError`&&typeof n==`string`&&n.includes(`Unserializable return value`)}function w(e){if(e?.aborted)throw e.reason??new DOMException(`The operation was aborted.`,`AbortError`)}const T={count:0,last:void 0,warnedFor:-1};function E(e){if(e===void 0)return{key:e,transfers:[]};let t=e.publicKeyBytes.bytes,n=e.crsBytes.bytes;if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array))return{key:e,transfers:[]};let r=t.slice(),i=n.slice();return{key:{...e,publicKeyBytes:{...e.publicKeyBytes,bytes:r},crsBytes:{...e.crsBytes,bytes:i}},transfers:[r.buffer,i.buffer]}}function D(){let e,t=new Promise((t,n)=>{e=n});return t.catch(()=>{}),{initPromise:void 0,worker:void 0,api:void 0,doomed:t,doom:e}}var O=class{#e;#t;#n=!1;#r=T;#i=0;#a=new Map;#o;#s=0;#c=!1;constructor(e){this.#e=e}init=()=>{let e=this.#t??=D();if(e.initPromise===void 0){let t=this.#f(()=>this.#u(e)).catch(n=>{throw e.initPromise===t&&(e.initPromise=void 0),n});e.initPromise=t}return e.initPromise};encryptValue=e=>this.#f(()=>this.#l(t=>t.encryptValue(e),(t,n,r)=>t.encryptValue(n,{...e,options:r}),e.options));encryptValues=e=>this.#f(()=>this.#l(t=>t.encryptValues(e),(t,n,r)=>t.encryptValues(n,{...e,options:r}),e.options));dispose(){this.#c=!0,this.#p()}async#l(e,t,n){let{signal:r,onProgress:i,...a}=n??{};w(r),await this.init(),w(r);let o=this.#t,s=o?.api;if(this.#o!==void 0&&(this.#n||s===void 0))return e(await this.#o);if(o===void 0||s===void 0)return e(await this.#b(o,this.#r.last??new S(`Encrypt worker not running.`)));let c=this.#i++,l=()=>void s.abort(c).catch(()=>{});r?.addEventListener(`abort`,l,{once:!0}),i&&this.#a.set(c,i);try{let e=await this.#v(o,t(s,c,a));return this.#r=T,e}catch(t){if(t instanceof S)return e(await this.#b(o,t));throw t}finally{this.#a.delete(c),r?.removeEventListener(`abort`,l)}}async#u(e){if(this.#n)return;let t=this.#e.blockedReason;if(t!==void 0){await this.#b(e,new S(t));return}let n=await this.#e.prefetchKey();try{let t=await this.#h(e),r=this.#e.network,i=typeof r==`string`?null:(0,u.proxy)(async e=>{try{return await r.request(e)}catch(e){throw _(e)}}),a=(0,u.proxy)((e,t)=>{try{this.#e.logger[e](t)}catch(e){this.#d(`logger`,e)}}),o=(0,u.proxy)((e,t)=>{try{this.#a.get(e)?.(t)}catch(e){this.#d(`onProgress`,e)}}),s=E(n);await this.#v(e,t.init((0,u.transfer)({...this.#e.initPayload,clientOptions:{...this.#e.initPayload.clientOptions,fheEncryptionKey:s.key},rpcUrl:typeof r==`string`?r:void 0},s.transfers),i,a,o),{ms:this.#e.timeouts.init,operation:`init`}),e.api=t,this.#r={...this.#r,last:void 0}}catch(t){if(!(t instanceof S))throw this.#y(e,new S(`Encrypt worker init failed.`)),t;await this.#b(e,t)}}#d(e,t){let n=t instanceof Error?t.message:String(t);try{this.#e.logger.warn(`Encrypt offload ${e} callback threw: ${n}`)}catch{}}async#f(e){this.#s++;try{return await e()}finally{this.#s--,this.#p()}}#p(){!this.#c||this.#s>0||(this.#c=!1,this.#t?.worker?.terminate(),this.#t=void 0,this.#o=void 0,this.#n=!1,this.#r=T)}#m(){let e=this.#e.workerSource;if(e===void 0)return y();if(typeof e==`function`){let t=e();return x.has(t)&&this.#e.logger.warnAlways(`The offloadWorker factory returned a worker it already handed out; each call must construct a fresh Worker.`),x.add(t),t}return new Worker(e,{type:`module`,name:`zama-fhe-encrypt`})}async#h(e){let t;try{t=this.#m()}catch(e){throw new S(e instanceof Error?e.message:String(e),{cause:e})}e.worker=t;let n=await this.#g(e,t);return this.#_(e,t),n}#g(e,t){return new Promise((n,r)=>{let i=()=>{clearTimeout(a),t.removeEventListener(`message`,o),t.removeEventListener(`error`,s)},a=setTimeout(()=>{i(),r(new S(`Encrypt worker did not start within ${this.#e.timeouts.spawn}ms.`))},this.#e.timeouts.spawn),o=e=>{e.data===`zama-encrypt-worker-ready`&&(i(),n((0,u.wrap)(t)))},s=t=>{i();let n=t.message||`Encrypt worker error.`;r(new S(n)),this.#y(e,new S(n))};t.addEventListener(`message`,o),t.addEventListener(`error`,s)})}#_(e,t){t.addEventListener(`error`,t=>{if(this.#t!==e)return;let n=new S(t.message||`Encrypt worker error.`,{crashed:!0});this.#r={...this.#r,count:this.#r.count+1,last:n},this.#y(e,n)})}async#v(e,t,n){let r=n===void 0?void 0:setTimeout(()=>{this.#y(e,new S(`Encrypt worker ${n.operation} timed out after ${n.ms}ms.`))},n.ms);try{return await Promise.race([t.catch(e=>{let t=d(e)?v(e):e;throw C(t)?new S(t.message,{cause:t}):t}),e.doomed])}finally{r!==void 0&&clearTimeout(r)}}#y(e,t){e!==void 0&&(this.#t===e&&(this.#t=void 0),e.worker?.terminate(),e.worker=void 0,e.api=void 0,e.initPromise=void 0,e.doom(t))}async#b(e,t){let r=t instanceof Error?t.message:String(t);if(this.#e.strict)throw this.#y(e,new S(`Encrypt worker unavailable.`)),new n.n(`Encrypt offload required (offloadEncrypt: true) but unavailable: ${r}`,{cause:t});let{transient:i,pinning:a}=this.#x(t);if(this.#n||=!i,this.#y(e,new S(`Encrypt worker degraded to inline.`)),this.#S(r,i,a),this.#o===void 0){let e=(async()=>{let e=this.#e.createInlineClient();return await e.init(),e})().catch(t=>{throw this.#o===e&&(this.#o=void 0),this.#e.logger.warnAlways(`Encrypt inline fallback failed to initialize: ${t instanceof Error?t.message:String(t)}`),t});this.#o=e}return this.#o}#x(e){let t=e instanceof S&&e.crashed&&this.#r.count<2;return{transient:t,pinning:!t&&!this.#n}}#S(e,t,n){if(!n&&this.#r.warnedFor===this.#r.count)return;this.#r={...this.#r,warnedFor:this.#r.count};let r=t?`in-flight encryption falls back`:`encryption falls back`;this.#e.logger.warnAlways(`Encrypt offload unavailable, ${r} to the calling thread: ${e}`)}},k=class{#e;#t;#n;#r;#i;#a;#o;constructor(e){this.#e=e.chain;let{timeout:t,debug:n,batchRpcCalls:r,moduleVersions:i,fheEncryptionKey:o}=e.options??{},u=this.#e.auth?M(this.#e.auth):void 0,d={publicClient:(0,a.createPublicClient)({transport:typeof this.#e.network==`string`?(0,a.http)(this.#e.network):(0,a.custom)(this.#e.network)}),chain:l(this.#e),options:{batchRpcCalls:r,moduleVersions:i,fheEncryptionKey:o}};this.#i={...u!==void 0&&{auth:u},...t!==void 0&&{timeout:t},...n!==void 0&&{debug:n}},this.#a=e.telemetry;let f=()=>this.#t.fetchFheEncryptionKeyBytes({options:this.#c(void 0)}),p=e=>({init:async()=>{await f(),await e.init()},encryptValue:t=>e.encryptValue(t),encryptValues:t=>e.encryptValues(t),fetchFheEncryptionKeyBytes:t=>e.fetchFheEncryptionKeyBytes(t)});e.cleartext?(this.#t=(0,c.createFhevmCleartextBaseClient)(d),this.#n=(0,c.createFhevmCleartextDecryptClient)(d),this.#r=p((0,c.createFhevmCleartextEncryptClient)(d))):(this.#t=(0,s.createFhevmBaseClient)(d),this.#n=(0,s.createFhevmDecryptClient)(d),this.#r=this.#s(e,d,{prefetchKey:f,createInlineClient:()=>p((0,s.createFhevmEncryptClient)(d))}))}#s(e,t,n){let i=e.offloadEncrypt??!1,a=i===!0,o=typeof Worker==`function`&&(e.offloadWorker!==void 0||!1);if(i===!1||!(a||o))return n.createInlineClient();let s=r.t(),c=j(s);if(c!==void 0&&!a)return e.logger.warnAlways(`Encryption runs on the calling thread: ${c}.`),n.createInlineClient();let l=new O({initPayload:{chain:t.chain,clientOptions:t.options,runtime:s??{}},network:this.#e.network,prefetchKey:n.prefetchKey,createInlineClient:n.createInlineClient,logger:e.logger,timeouts:e.offloadTimeouts??b,workerSource:e.offloadWorker,blockedReason:c,strict:a});return{init:()=>l.init(),encryptValue:e=>l.encryptValue(e),encryptValues:e=>l.encryptValues(e),fetchFheEncryptionKeyBytes:e=>this.#t.fetchFheEncryptionKeyBytes(e),dispose:()=>l.dispose()}}get chain(){return this.#e}#c(e){let{operation:t,...n}={...this.#i,...e};return this.#a===void 0?n:{...n,headers:{...n.headers,...i.n(this.#a,t)}}}#l=()=>(this.#o??=this.#r.init().catch(e=>{throw this.#o=void 0,e}),this.#o);dispose=()=>{this.#o=void 0,this.#r.dispose?.()};decryptPublicValue=async e=>(await this.#t.init(),this.#t.decryptPublicValue({...e,options:this.#c(e.options)}));decryptPublicValues=async e=>(await this.#t.init(),this.#t.decryptPublicValues({...e,options:this.#c(e.options)}));decryptPublicValuesWithSignatures=async e=>(await this.#t.init(),this.#t.decryptPublicValuesWithSignatures({...e,options:this.#c(e.options)}));encryptValue=async e=>(await this.#l(),this.#r.encryptValue({...e,options:this.#c(e.options)}));encryptValues=async e=>(await this.#l(),this.#r.encryptValues({...e,options:this.#c(e.options)}));decryptValue=async e=>(await this.#n.init(),this.#n.decryptValue({...e,options:this.#c(e.options)}));decryptValues=async e=>(await this.#n.init(),this.#n.decryptValues({...e,options:this.#c(e.options)}));decryptValuesFromPairs=async e=>(await this.#n.init(),this.#n.decryptValuesFromPairs({...e,options:this.#c(e.options)}));fetchFheEncryptionKeyBytes=async e=>(await this.#t.init(),this.#t.fetchFheEncryptionKeyBytes({...e,options:this.#c(e?.options)}));signDecryptionPermit=async e=>(await this.#t.init(),this.#t.signDecryptionPermit(e));createUnsignedLegacyDecryptionPermitEip712=e=>(0,o.createUnsignedLegacyDecryptionPermitEip712)(this.#t,e);serializeTransportKeyPair=e=>this.#n.serializeTransportKeyPair(e);serializeSignedDecryptionPermit=e=>this.#t.serializeSignedDecryptionPermit(e);parseTransportKeyPair=async e=>(await this.#n.init(),this.#n.parseTransportKeyPair(e));parseSignedDecryptionPermit=async e=>{await this.#t.init();let{serializedPermit:t}=e;return this.#t.parseSignedDecryptionPermit({...e,serializedPermit:{...t,signature:A(t.signature)}})};generateTransportKeyPair=async()=>(await this.#n.init(),this.#n.generateTransportKeyPair())};function A(e){if(e.length!==132)return e;let t=parseInt(e.slice(130),16);return t!==0&&t!==1?e:`${e.slice(0,130)}${t===0?`1b`:`1c`}`}function j(e){if(r.n())return`a runtime locateFile cannot cross the encrypt worker boundary`;if(e===void 0&&(0,s.hasFhevmRuntimeConfig)())return`a runtime config set outside createConfig cannot be replicated in the encrypt worker realm`}function M(e){let n=e.__type;switch(n){case`ApiKeyHeader`:return{type:n,value:e.value,header:e.header};case`ApiKeyCookie`:return{type:n,value:e.value,cookie:e.cookie};case`BearerToken`:return{type:n,token:e.token};default:throw new t.t(`Unknown auth type: ${String(n)}`)}}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return k}});
8
8
  //# sourceMappingURL=fhevm-relayer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fhevm-relayer.cjs","names":["readRetryAfterHeader","isValidRetryAfterSeconds","#config","#progressListeners","#generation","#withActive","#initOnce","#dispatch","#releaseRequested","#releaseIfIdle","#degradePromise","#pinnedInline","#degrade","#crashes","#sequence","#overBoundary","#spawn","#warnCallbackThrew","#teardown","#active","#createWorker","#raceReady","#armCrashHandler","EncryptOffloadUnavailableError","#classifyDegrade","#warnDegraded","#chain","#base","#decrypt","#encrypt","#defaultOptions","#telemetry","#requestOptions","#buildEncryptBackend","getAppliedWireRuntime","telemetryHeaders","#encryptInitPromise","#initEncrypt","hasAppliedLocateFile","ConfigurationError"],"sources":["../../src/chains/to-fhevm-chain.ts","../../../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/umd/comlink.js","../../src/worker/protocol.ts","../../src/worker/spawn.ts","../../src/worker/encrypt-worker-client.ts","../../src/relayer/fhevm-relayer.ts"],"sourcesContent":["import type { FhevmChain } from \"@fhevm/sdk/chains\";\nimport type { FheChain } from \"./types\";\n\n/**\n * Derive an `@fhevm/sdk` {@link FhevmChain} from zama-sdk's richer\n * {@link FheChain}.\n *\n * `FheChain` carries fields `@fhevm/sdk` does not model (RPC `network`,\n * `registryAddress`, `executorAddress`, cleartext signer keys); those stay on\n * `FheChain` for the token layer. This adapter projects only the subset the\n * FHE runtime needs: contract addresses, relayer URL, and gateway.\n */\nexport function toFhevmChain(chain: FheChain): FhevmChain {\n return {\n id: chain.id,\n fhevm: {\n contracts: {\n acl: { address: chain.aclContractAddress },\n inputVerifier: { address: chain.inputVerifierContractAddress },\n kmsVerifier: { address: chain.kmsContractAddress },\n protocolConfig: undefined,\n },\n relayerUrl: chain.relayerUrl,\n gateway: {\n id: chain.gatewayChainId,\n contracts: {\n decryption: { address: chain.verifyingContractAddressDecryption },\n inputVerification: { address: chain.verifyingContractAddressInputVerification },\n },\n },\n },\n } satisfies FhevmChain;\n}\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Comlink = {}));\n})(this, (function (exports) { 'use strict';\n\n /**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n const proxyMarker = Symbol(\"Comlink.proxy\");\n const createEndpoint = Symbol(\"Comlink.endpoint\");\n const releaseProxy = Symbol(\"Comlink.releaseProxy\");\n const finalizer = Symbol(\"Comlink.finalizer\");\n const throwMarker = Symbol(\"Comlink.thrown\");\n const isObject = (val) => (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n /**\n * Internal transfer handle to handle objects marked to proxy.\n */\n const proxyTransferHandler = {\n canHandle: (val) => isObject(val) && val[proxyMarker],\n serialize(obj) {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port1);\n return [port2, [port2]];\n },\n deserialize(port) {\n port.start();\n return wrap(port);\n },\n };\n /**\n * Internal transfer handler to handle thrown exceptions.\n */\n const throwTransferHandler = {\n canHandle: (value) => isObject(value) && throwMarker in value,\n serialize({ value }) {\n let serialized;\n if (value instanceof Error) {\n serialized = {\n isError: true,\n value: {\n message: value.message,\n name: value.name,\n stack: value.stack,\n },\n };\n }\n else {\n serialized = { isError: false, value };\n }\n return [serialized, []];\n },\n deserialize(serialized) {\n if (serialized.isError) {\n throw Object.assign(new Error(serialized.value.message), serialized.value);\n }\n throw serialized.value;\n },\n };\n /**\n * Allows customizing the serialization of certain values.\n */\n const transferHandlers = new Map([\n [\"proxy\", proxyTransferHandler],\n [\"throw\", throwTransferHandler],\n ]);\n function isAllowedOrigin(allowedOrigins, origin) {\n for (const allowedOrigin of allowedOrigins) {\n if (origin === allowedOrigin || allowedOrigin === \"*\") {\n return true;\n }\n if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n return true;\n }\n }\n return false;\n }\n function expose(obj, ep = globalThis, allowedOrigins = [\"*\"]) {\n ep.addEventListener(\"message\", function callback(ev) {\n if (!ev || !ev.data) {\n return;\n }\n if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n return;\n }\n const { id, type, path } = Object.assign({ path: [] }, ev.data);\n const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n let returnValue;\n try {\n const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n switch (type) {\n case \"GET\" /* MessageType.GET */:\n {\n returnValue = rawValue;\n }\n break;\n case \"SET\" /* MessageType.SET */:\n {\n parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n returnValue = true;\n }\n break;\n case \"APPLY\" /* MessageType.APPLY */:\n {\n returnValue = rawValue.apply(parent, argumentList);\n }\n break;\n case \"CONSTRUCT\" /* MessageType.CONSTRUCT */:\n {\n const value = new rawValue(...argumentList);\n returnValue = proxy(value);\n }\n break;\n case \"ENDPOINT\" /* MessageType.ENDPOINT */:\n {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port2);\n returnValue = transfer(port1, [port1]);\n }\n break;\n case \"RELEASE\" /* MessageType.RELEASE */:\n {\n returnValue = undefined;\n }\n break;\n default:\n return;\n }\n }\n catch (value) {\n returnValue = { value, [throwMarker]: 0 };\n }\n Promise.resolve(returnValue)\n .catch((value) => {\n return { value, [throwMarker]: 0 };\n })\n .then((returnValue) => {\n const [wireValue, transferables] = toWireValue(returnValue);\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n if (type === \"RELEASE\" /* MessageType.RELEASE */) {\n // detach and deactive after sending release response above.\n ep.removeEventListener(\"message\", callback);\n closeEndPoint(ep);\n if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n obj[finalizer]();\n }\n }\n })\n .catch((error) => {\n // Send Serialization Error To Caller\n const [wireValue, transferables] = toWireValue({\n value: new TypeError(\"Unserializable return value\"),\n [throwMarker]: 0,\n });\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n });\n });\n if (ep.start) {\n ep.start();\n }\n }\n function isMessagePort(endpoint) {\n return endpoint.constructor.name === \"MessagePort\";\n }\n function closeEndPoint(endpoint) {\n if (isMessagePort(endpoint))\n endpoint.close();\n }\n function wrap(ep, target) {\n const pendingListeners = new Map();\n ep.addEventListener(\"message\", function handleMessage(ev) {\n const { data } = ev;\n if (!data || !data.id) {\n return;\n }\n const resolver = pendingListeners.get(data.id);\n if (!resolver) {\n return;\n }\n try {\n resolver(data);\n }\n finally {\n pendingListeners.delete(data.id);\n }\n });\n return createProxy(ep, pendingListeners, [], target);\n }\n function throwIfProxyReleased(isReleased) {\n if (isReleased) {\n throw new Error(\"Proxy has been released and is not useable\");\n }\n }\n function releaseEndpoint(ep) {\n return requestResponseMessage(ep, new Map(), {\n type: \"RELEASE\" /* MessageType.RELEASE */,\n }).then(() => {\n closeEndPoint(ep);\n });\n }\n const proxyCounter = new WeakMap();\n const proxyFinalizers = \"FinalizationRegistry\" in globalThis &&\n new FinalizationRegistry((ep) => {\n const newCount = (proxyCounter.get(ep) || 0) - 1;\n proxyCounter.set(ep, newCount);\n if (newCount === 0) {\n releaseEndpoint(ep);\n }\n });\n function registerProxy(proxy, ep) {\n const newCount = (proxyCounter.get(ep) || 0) + 1;\n proxyCounter.set(ep, newCount);\n if (proxyFinalizers) {\n proxyFinalizers.register(proxy, ep, proxy);\n }\n }\n function unregisterProxy(proxy) {\n if (proxyFinalizers) {\n proxyFinalizers.unregister(proxy);\n }\n }\n function createProxy(ep, pendingListeners, path = [], target = function () { }) {\n let isProxyReleased = false;\n const proxy = new Proxy(target, {\n get(_target, prop) {\n throwIfProxyReleased(isProxyReleased);\n if (prop === releaseProxy) {\n return () => {\n unregisterProxy(proxy);\n releaseEndpoint(ep);\n pendingListeners.clear();\n isProxyReleased = true;\n };\n }\n if (prop === \"then\") {\n if (path.length === 0) {\n return { then: () => proxy };\n }\n const r = requestResponseMessage(ep, pendingListeners, {\n type: \"GET\" /* MessageType.GET */,\n path: path.map((p) => p.toString()),\n }).then(fromWireValue);\n return r.then.bind(r);\n }\n return createProxy(ep, pendingListeners, [...path, prop]);\n },\n set(_target, prop, rawValue) {\n throwIfProxyReleased(isProxyReleased);\n // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n const [value, transferables] = toWireValue(rawValue);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"SET\" /* MessageType.SET */,\n path: [...path, prop].map((p) => p.toString()),\n value,\n }, transferables).then(fromWireValue);\n },\n apply(_target, _thisArg, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const last = path[path.length - 1];\n if (last === createEndpoint) {\n return requestResponseMessage(ep, pendingListeners, {\n type: \"ENDPOINT\" /* MessageType.ENDPOINT */,\n }).then(fromWireValue);\n }\n // We just pretend that `bind()` didn’t happen.\n if (last === \"bind\") {\n return createProxy(ep, pendingListeners, path.slice(0, -1));\n }\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"APPLY\" /* MessageType.APPLY */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n construct(_target, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"CONSTRUCT\" /* MessageType.CONSTRUCT */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n });\n registerProxy(proxy, ep);\n return proxy;\n }\n function myFlat(arr) {\n return Array.prototype.concat.apply([], arr);\n }\n function processArguments(argumentList) {\n const processed = argumentList.map(toWireValue);\n return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n }\n const transferCache = new WeakMap();\n function transfer(obj, transfers) {\n transferCache.set(obj, transfers);\n return obj;\n }\n function proxy(obj) {\n return Object.assign(obj, { [proxyMarker]: true });\n }\n function windowEndpoint(w, context = globalThis, targetOrigin = \"*\") {\n return {\n postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),\n addEventListener: context.addEventListener.bind(context),\n removeEventListener: context.removeEventListener.bind(context),\n };\n }\n function toWireValue(value) {\n for (const [name, handler] of transferHandlers) {\n if (handler.canHandle(value)) {\n const [serializedValue, transferables] = handler.serialize(value);\n return [\n {\n type: \"HANDLER\" /* WireValueType.HANDLER */,\n name,\n value: serializedValue,\n },\n transferables,\n ];\n }\n }\n return [\n {\n type: \"RAW\" /* WireValueType.RAW */,\n value,\n },\n transferCache.get(value) || [],\n ];\n }\n function fromWireValue(value) {\n switch (value.type) {\n case \"HANDLER\" /* WireValueType.HANDLER */:\n return transferHandlers.get(value.name).deserialize(value.value);\n case \"RAW\" /* WireValueType.RAW */:\n return value.value;\n }\n }\n function requestResponseMessage(ep, pendingListeners, msg, transfers) {\n return new Promise((resolve) => {\n const id = generateUUID();\n pendingListeners.set(id, resolve);\n if (ep.start) {\n ep.start();\n }\n ep.postMessage(Object.assign({ id }, msg), transfers);\n });\n }\n function generateUUID() {\n return new Array(4)\n .fill(0)\n .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n .join(\"-\");\n }\n\n exports.createEndpoint = createEndpoint;\n exports.expose = expose;\n exports.finalizer = finalizer;\n exports.proxy = proxy;\n exports.proxyMarker = proxyMarker;\n exports.releaseProxy = releaseProxy;\n exports.transfer = transfer;\n exports.transferHandlers = transferHandlers;\n exports.windowEndpoint = windowEndpoint;\n exports.wrap = wrap;\n\n}));\n//# sourceMappingURL=comlink.js.map\n","/**\n * Shared contract between the main-thread encrypt client and the encrypt\n * worker, spoken over Comlink. Every payload must survive `structuredClone`:\n * no `AbortSignal`, no class instances; callbacks cross as Comlink proxies.\n */\n\nimport type { FhevmChain } from \"@fhevm/sdk/chains\";\nimport type {\n FhevmClientOptions,\n FhevmEncryptBackend,\n FhevmRelayerOptions,\n WireRuntimeConfig,\n} from \"../relayer/types\";\nimport { isValidRetryAfterSeconds, readRetryAfterHeader } from \"../utils/error\";\n\ntype EncryptParameters = Parameters<FhevmEncryptBackend[\"encryptValue\"]>[0];\ntype EncryptsParameters = Parameters<FhevmEncryptBackend[\"encryptValues\"]>[0];\n\n/**\n * What the worker offloads, and all the encrypt client's surface the worker\n * client implements. Key fetches stay on the calling thread, where the chain's\n * auth applies and the key never crosses back out.\n */\nexport type EncryptOffloadBackend = Pick<\n FhevmEncryptBackend,\n \"init\" | \"encryptValue\" | \"encryptValues\"\n>;\n\n/** Per-request options minus `signal`, the one non-cloneable member of the set. */\nexport type WireRequestOptions = Omit<FhevmRelayerOptions, \"signal\">;\n\nexport type WireProgressEvent = Parameters<\n NonNullable<NonNullable<EncryptParameters[\"options\"]>[\"onProgress\"]>\n>[0];\n\nexport type WireInitPayload = {\n readonly chain: FhevmChain;\n /** RPC URL for host-chain reads; absent when reads proxy through `rpcRequest`. */\n readonly rpcUrl: string | undefined;\n /** Carries `fheEncryptionKey`, prefetched on the main thread so the worker skips the download. */\n readonly clientOptions: FhevmClientOptions;\n readonly runtime: WireRuntimeConfig;\n};\n\n/** Main-thread callback the worker uses for host-chain reads when the chain's network is an injected provider. */\nexport type WireRpcRequest = (args: { method: string; params?: unknown }) => Promise<unknown>;\n\n/**\n * Main-thread callback receiving every operation's progress events, routed on\n * `id`. One channel per worker avoids minting a `MessageChannel` per call, whose\n * local port and listener would linger until garbage collection after terminate.\n * Returns `unknown`: a Comlink proxy call answers with a promise.\n */\nexport type WireProgressCallback = (id: number, event: WireProgressEvent) => unknown;\n\nexport type WireLogCallback = (level: \"debug\" | \"warn\" | \"error\", message: string) => unknown;\n\n/**\n * The API the worker exposes over Comlink. `id` correlates an in-flight\n * operation with `abort` and with its progress events, since neither an\n * `AbortSignal` nor a per-call callback can cross the boundary cheaply. The\n * `init` callback parameters must be passed as Comlink proxies (or `null`).\n */\nexport type EncryptWorkerApi = {\n init(\n payload: WireInitPayload,\n rpcRequest: WireRpcRequest | null,\n log: WireLogCallback,\n onProgress: WireProgressCallback,\n ): Promise<void>;\n encryptValue(\n id: number,\n parameters: {\n readonly value: EncryptParameters[\"value\"];\n readonly contractAddress: string;\n readonly userAddress: string;\n readonly options: WireRequestOptions | undefined;\n },\n ): ReturnType<FhevmEncryptBackend[\"encryptValue\"]>;\n encryptValues(\n id: number,\n parameters: {\n readonly values: EncryptsParameters[\"values\"];\n readonly contractAddress: string;\n readonly userAddress: string;\n readonly options: WireRequestOptions | undefined;\n },\n ): ReturnType<FhevmEncryptBackend[\"encryptValues\"]>;\n abort(id: number): void;\n};\n\n/** Raw message the worker posts once its module graph has loaded, before Comlink traffic. */\nexport const WORKER_READY_MESSAGE = \"zama-encrypt-worker-ready\";\n\n/**\n * An `Error` flattened for the boundary crossing, thrown by the worker as a\n * plain object so it survives structured clone intact. `props` carries the\n * fields the SDK's duck-typed classifiers read (`statusCode`, `retryAfter`,\n * `code`, …); a cloned `Error` instance would drop them with the prototype.\n * Reading them through the prototype chain is deliberate: upstream's `status`\n * and `relayerApiError` are prototype getters, not own fields.\n */\nexport type WireError = {\n readonly wireError: true;\n readonly name: string;\n readonly message: string;\n readonly stack: string | undefined;\n readonly props: Record<string, unknown>;\n readonly cause: WireError | undefined;\n};\n\nexport function isWireError(value: unknown): value is WireError {\n // Exact `true`, not presence: an `Error` subclass carrying the key must not be\n // rehydrated as a flattened one.\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { wireError?: unknown }).wireError === true\n );\n}\n\n/**\n * Fields preserved across the boundary: what the error classifiers read off\n * `@fhevm/sdk`, relayer, and JSON-RPC errors, plus the `error`/`info` nesting\n * keys those classifiers walk alongside `cause`.\n */\nconst WIRE_ERROR_PROPS = [\n \"statusCode\",\n \"status\",\n \"retryAfter\",\n \"timeoutMs\",\n \"relayerApiError\",\n \"code\",\n \"data\",\n \"shortMessage\",\n \"details\",\n \"error\",\n \"info\",\n] as const;\n\nconst MAX_CAUSE_DEPTH = 6;\n\n/** A probe is exact where a structural walk only approximates. */\nfunction isCloneSafe(value: unknown): boolean {\n try {\n structuredClone(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * The `Retry-After` header survives as a plain number of seconds; the\n * `Response` object it lives on cannot cross the boundary.\n */\nfunction retryAfterFromResponse(error: object): number | undefined {\n const response = (error as { response?: { headers?: unknown } }).response;\n return readRetryAfterHeader(response?.headers);\n}\n\n/**\n * `JSON.stringify` throws instead of returning `undefined` on a bigint or a\n * circular value; a non-Error thrown value must never fail error handling itself.\n */\nfunction stringifyNonError(error: unknown): string {\n try {\n return JSON.stringify(error) ?? String(error);\n } catch {\n return String(error);\n }\n}\n\n/** The classifier fields readable off one thrown value, `Error` or plain object alike. */\nfunction extractWireProps(source: object): Record<string, unknown> {\n const props: Record<string, unknown> = {};\n for (const key of WIRE_ERROR_PROPS) {\n const value = (source as Record<string, unknown>)[key];\n if (value !== undefined && isCloneSafe(value)) {\n props[key] = value;\n }\n }\n // The header wins over a malformed own delay (`0`, negative, `NaN`), as the\n // inline extractor in `utils/error.ts` decides it.\n if (!isValidRetryAfterSeconds(props[\"retryAfter\"])) {\n const fromHeader = retryAfterFromResponse(source);\n if (fromHeader !== undefined) {\n props[\"retryAfter\"] = fromHeader;\n }\n }\n return props;\n}\n\nexport function toWireError(error: unknown, depth: number = MAX_CAUSE_DEPTH): WireError {\n if (isWireError(error)) {\n return error;\n }\n const nest = (cause: unknown): WireError | undefined =>\n depth > 0 && cause !== undefined ? toWireError(cause, depth - 1) : undefined;\n if (error instanceof Error) {\n return {\n wireError: true,\n name: error.name,\n message: error.message,\n stack: error.stack,\n props: extractWireProps(error),\n cause: nest(error.cause),\n };\n }\n if (typeof error === \"object\" && error !== null) {\n // Wallets reject with a plain `{ code, message, data }`; dropping `code`\n // would break viem's classification inside the worker.\n const { message, cause } = error as { message?: unknown; cause?: unknown };\n return {\n wireError: true,\n name: \"Error\",\n message: typeof message === \"string\" ? message : stringifyNonError(error),\n stack: undefined,\n props: extractWireProps(error),\n cause: nest(cause),\n };\n }\n return {\n wireError: true,\n name: \"Error\",\n message: typeof error === \"string\" ? error : stringifyNonError(error),\n stack: undefined,\n props: {},\n cause: undefined,\n };\n}\n\n/**\n * Rebuilds a plain `Error` carrying the original `name`, own fields, and cause\n * chain, so name-based classification and status/retry-after extraction behave\n * as if the error had been thrown on this thread.\n */\nexport function fromWireError(wire: WireError): Error {\n const error = new Error(wire.message, wire.cause ? { cause: fromWireError(wire.cause) } : {});\n error.name = wire.name;\n if (wire.stack !== undefined) {\n error.stack = wire.stack;\n }\n Object.assign(error, wire.props);\n return error;\n}\n","export const BUNDLED_ENCRYPT_WORKER = false;\nexport function createEncryptWorker() {\n throw new Error(\"The encrypt worker is only available in the ESM build.\");\n}\n","import { proxy, transfer, wrap, type Remote } from \"comlink\";\nimport type { EIP1193Provider } from \"viem\";\nimport { EncryptOffloadUnavailableError } from \"../errors/encryption\";\nimport type { FhevmClientOptions } from \"../relayer/types\";\nimport type { LoggerService } from \"../services/logger-service\";\nimport type {\n EncryptOffloadBackend,\n EncryptWorkerApi,\n WireInitPayload,\n WireProgressEvent,\n WireRequestOptions,\n} from \"./protocol\";\nimport { WORKER_READY_MESSAGE, fromWireError, isWireError, toWireError } from \"./protocol\";\nimport { createEncryptWorker } from \"./spawn\";\n\n/**\n * Watchdog deadlines, in milliseconds, for worker lifecycle steps: each is a\n * ceiling on \"the worker never answered\", not on legitimate slow work. Encrypt\n * operations themselves are not watched: nothing bounds local WASM compute, so\n * a proof may run for as long as it needs.\n */\nexport type EncryptWorkerTimeouts = {\n /** Worker startup + module-graph load; a bundler that mishandled the worker URL fails here. */\n readonly spawn: number;\n /** Client init inside the worker realm: chain reads and WASM compilation. */\n readonly init: number;\n};\n\nexport const DEFAULT_ENCRYPT_WORKER_TIMEOUTS: EncryptWorkerTimeouts = {\n spawn: 10_000,\n init: 300_000,\n};\n\n/** Second crash pins the client to the calling thread. */\nconst CRASH_PIN_THRESHOLD = 2;\n\n/** Stable prefix of every degrade warning. */\nexport const ENCRYPT_OFFLOAD_WARN_PREFIX = \"Encrypt offload unavailable\";\n\n/** Workers already returned by an `offloadWorker` factory, to catch a factory that hands out one worker forever. */\nconst handedOutWorkers = new WeakSet<Worker>();\n\n/** Internal signal: the worker infrastructure failed; the operation itself was not rejected. */\nclass WorkerUnavailableError extends Error {\n /** True when a worker that had already signalled ready died under us, so a respawn is worth trying. */\n readonly crashed: boolean;\n\n constructor(message: string, options?: ErrorOptions & { readonly crashed?: boolean }) {\n super(message, options);\n this.name = \"WorkerUnavailableError\";\n this.crashed = options?.crashed ?? false;\n }\n}\n\n/**\n * A payload Comlink could not clone into the worker (`DataCloneError`) or could\n * not return out of it (its own `TypeError`): a boundary failure, so it degrades\n * rather than reaching the caller as an application error.\n */\nfunction isCloneFailure(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) {\n return false;\n }\n const { name, message } = error as { name?: unknown; message?: unknown };\n return (\n name === \"DataCloneError\" ||\n (name === \"TypeError\" &&\n typeof message === \"string\" &&\n message.includes(\"Unserializable return value\"))\n );\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException(\"The operation was aborted.\", \"AbortError\");\n }\n}\n\n/** What the client remembers about worker crashes, dropped whole by a worker answer and by a release. */\ntype CrashHistory = {\n readonly count: number;\n /** The crash that killed the current worker, so a call landing after it degrades as a crash too. */\n readonly last: WorkerUnavailableError | undefined;\n /** Crash count the degrade warning was last emitted for, so one failure warns once. */\n readonly warnedFor: number;\n};\n\nconst NO_CRASHES: CrashHistory = { count: 0, last: undefined, warnedFor: -1 };\n\n/**\n * The key copied for the crossing plus the buffers to transfer, so the wire copy\n * is moved instead of cloned. Anything but the known binary shape crosses\n * unchanged.\n */\nfunction keyForTransfer(key: FhevmClientOptions[\"fheEncryptionKey\"]): {\n readonly key: FhevmClientOptions[\"fheEncryptionKey\"];\n readonly transfers: Transferable[];\n} {\n if (key === undefined) {\n return { key, transfers: [] };\n }\n const publicKeyBytes = key.publicKeyBytes.bytes;\n const crsBytes = key.crsBytes.bytes;\n if (!(publicKeyBytes instanceof Uint8Array) || !(crsBytes instanceof Uint8Array)) {\n return { key, transfers: [] };\n }\n // `slice` yields a fresh exactly-sized buffer, so transferring it leaves this\n // thread's cached key intact.\n const publicKeyCopy = publicKeyBytes.slice();\n const crsCopy = crsBytes.slice();\n return {\n key: {\n ...key,\n publicKeyBytes: { ...key.publicKeyBytes, bytes: publicKeyCopy },\n crsBytes: { ...key.crsBytes, bytes: crsCopy },\n },\n transfers: [publicKeyCopy.buffer as ArrayBuffer, crsCopy.buffer as ArrayBuffer],\n };\n}\n\n/**\n * Per-call options: `signal` is forwarded as an `abort` call, `onProgress` is\n * served from the worker's shared progress channel, and `never` keeps the\n * callback contravariantly compatible with each operation's own event type.\n */\ntype CallOptions = WireRequestOptions & {\n readonly signal?: AbortSignal;\n readonly onProgress?: (args: never) => void;\n};\n\n/**\n * Everything scoped to one spawned worker, created by the init that spawns it\n * and dropped whole by a teardown. A late event carrying its own generation can\n * therefore only settle that generation, never the worker running in its place.\n */\ntype WorkerGeneration = {\n /** Memoized bring-up for this worker; it dies with the generation, so the next call re-runs it. */\n initPromise: Promise<void> | undefined;\n worker: Worker | undefined;\n api: Remote<EncryptWorkerApi> | undefined;\n /** Never resolves; teardown rejects it, and every boundary crossing races it so all of them settle together. */\n readonly doomed: Promise<never>;\n /** Rejects `doomed` with the teardown's `WorkerUnavailableError`. */\n readonly doom: (error: WorkerUnavailableError) => void;\n};\n\nfunction createWorkerGeneration(): WorkerGeneration {\n let doom!: (error: WorkerUnavailableError) => void;\n const doomed = new Promise<never>((_resolve, reject) => {\n doom = reject;\n });\n // An idle teardown dooms a generation with no crossing racing it; this\n // handler keeps that from surfacing as an unhandled rejection.\n doomed.catch(() => {});\n return { initPromise: undefined, worker: undefined, api: undefined, doomed, doom };\n}\n\nexport type EncryptWorkerClientConfig = {\n readonly initPayload: Omit<WireInitPayload, \"rpcUrl\">;\n /** The chain's RPC endpoint: a URL crosses into the worker; a provider is proxied per request. */\n readonly network: EIP1193Provider | string;\n /** Fetches the FHE key on the calling thread, where the chain's auth applies; the worker realm never downloads it itself. */\n readonly prefetchKey: () => Promise<FhevmClientOptions[\"fheEncryptionKey\"]>;\n readonly createInlineClient: () => EncryptOffloadBackend;\n readonly logger: LoggerService;\n readonly timeouts: EncryptWorkerTimeouts;\n /** A string or `URL` is spawned with the SDK's worker options; a factory is called for the worker itself. */\n readonly workerSource?: string | URL | (() => Worker);\n /**\n * A pre-known reason offload cannot work in this session: init degrades with\n * it immediately, so strict rejects at call time rather than at config time.\n */\n readonly blockedReason?: string;\n /**\n * Strict offload (`offloadEncrypt: true`): never run encryption on the\n * calling thread. Every path that would degrade rejects with\n * {@link EncryptOffloadUnavailableError} instead.\n */\n readonly strict: boolean;\n};\n\n/**\n * Encrypt backend that runs `@fhevm/sdk` in a dedicated module worker so proof\n * generation never blocks the main thread. Only infrastructure failure degrades\n * to inline (or rejects under `strict`); worker-reported errors are rethrown,\n * since inline would fail the same way.\n */\nexport class EncryptWorkerClient implements EncryptOffloadBackend {\n readonly #config: EncryptWorkerClientConfig;\n /** Resources of the worker currently being brought up or served; undefined while none runs. */\n #generation: WorkerGeneration | undefined;\n /** True once the client runs inline for the rest of its life, with no further spawn attempts. */\n #pinnedInline = false;\n #crashes: CrashHistory = NO_CRASHES;\n /** Wire ids, allocated across generations so a late reply can never be read as a live operation. */\n #sequence = 0;\n /** Per-operation `onProgress`, keyed by wire id and routed over one channel registered at init: one channel per worker avoids minting a `MessageChannel` per call, whose local port and listener would linger until garbage collection after terminate. */\n readonly #progressListeners = new Map<number, (event: WireProgressEvent) => void>();\n /** Memoized inline backend. Kept, with its key copy, across a worker recovery so a later degrade skips the refetch. */\n #degradePromise: Promise<EncryptOffloadBackend> | undefined;\n /** Operations that must drain before a requested release terminates the worker. */\n #active = 0;\n #releaseRequested = false;\n\n constructor(config: EncryptWorkerClientConfig) {\n this.#config = config;\n }\n\n init = (): Promise<void> => {\n // A call landing mid-drain rides the worker being released rather than\n // canceling the release: the drain still completes, and the call after it\n // spawns a fresh worker.\n const generation = (this.#generation ??= createWorkerGeneration());\n if (generation.initPromise === undefined) {\n // Only a successful cycle is memoized: a failure a retry could clear must\n // not be replayed to every later call.\n const attempt: Promise<void> = this.#withActive(() => this.#initOnce(generation)).catch(\n (error: unknown) => {\n if (generation.initPromise === attempt) {\n generation.initPromise = undefined;\n }\n throw error;\n },\n );\n generation.initPromise = attempt;\n }\n return generation.initPromise;\n };\n\n encryptValue: EncryptOffloadBackend[\"encryptValue\"] = (parameters) =>\n this.#withActive(() =>\n this.#dispatch(\n (backend) => backend.encryptValue(parameters),\n // Spread, so a field upstream adds to the parameters still crosses; the\n // stripped `options` replaces the caller's, which carries `signal`.\n (api, id, options) => api.encryptValue(id, { ...parameters, options }),\n parameters.options,\n ),\n );\n\n encryptValues: EncryptOffloadBackend[\"encryptValues\"] = (parameters) =>\n this.#withActive(() =>\n this.#dispatch(\n (backend) => backend.encryptValues(parameters),\n (api, id, options) => api.encryptValues(id, { ...parameters, options }),\n parameters.options,\n ),\n );\n\n /**\n * Releases the worker without changing what callers observe: in-flight\n * operations (an init included) run to completion over the worker, and the\n * worker is terminated as soon as the last one settles, immediately if the\n * client is idle. The client is not spent: the release resets it whole, so a\n * later call re-fetches the key and spawns a fresh worker exactly like the\n * first one, even if the client had degraded to the calling thread. The drain\n * is not bounded: a worker wedged inside an operation is only terminated once\n * that operation settles.\n */\n dispose(): void {\n this.#releaseRequested = true;\n this.#releaseIfIdle();\n }\n\n /**\n * The one place that decides between the worker and the calling thread:\n * inline once pinned or while no worker is running; otherwise the worker,\n * falling back to inline on infrastructure failure while application errors\n * pass through.\n */\n async #dispatch<T>(\n invoke: (backend: EncryptOffloadBackend) => Promise<T>,\n overWorker: (\n api: Remote<EncryptWorkerApi>,\n id: number,\n options: WireRequestOptions,\n ) => Promise<T>,\n callOptions: CallOptions | undefined,\n ): Promise<T> {\n const { signal, onProgress, ...options } = callOptions ?? {};\n // The worker dequeues an abort only after the proof, so a dispatched call always runs whole.\n throwIfAborted(signal);\n await this.init();\n // A listener added after the abort never fires, so an abort during init needs this recheck.\n throwIfAborted(signal);\n const generation = this.#generation;\n const api = generation?.api;\n // An existing degrade attempt already carries the decision that created it,\n // and its inline backend caches the key, so reuse it rather than degrading again.\n if (this.#degradePromise !== undefined && (this.#pinnedInline || api === undefined)) {\n return invoke(await this.#degradePromise);\n }\n if (generation === undefined || api === undefined) {\n return invoke(\n await this.#degrade(\n generation,\n this.#crashes.last ?? new WorkerUnavailableError(\"Encrypt worker not running.\"),\n ),\n );\n }\n const id = this.#sequence++;\n const onAbort = () => void api.abort(id).catch(() => {});\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (onProgress) {\n this.#progressListeners.set(id, onProgress as (event: WireProgressEvent) => void);\n }\n try {\n const result = await this.#overBoundary(generation, overWorker(api, id, options));\n // A worker operation that answered clears the crash history: two unrelated\n // crashes far apart must not add up to a permanent degrade.\n this.#crashes = NO_CRASHES;\n return result;\n } catch (error) {\n if (error instanceof WorkerUnavailableError) {\n return invoke(await this.#degrade(generation, error));\n }\n throw error;\n } finally {\n this.#progressListeners.delete(id);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n }\n\n async #initOnce(generation: WorkerGeneration): Promise<void> {\n if (this.#pinnedInline) {\n // The degrade that pinned the client already initialized the backend every call now runs on.\n return;\n }\n const blockedReason = this.#config.blockedReason;\n if (blockedReason !== undefined) {\n // Handled before any resource is spent: non-strict callers never get here\n // (the relayer inlines directly), and strict throws out of the degrade.\n await this.#degrade(generation, new WorkerUnavailableError(blockedReason));\n return;\n }\n // Outside the degrade guard: a failed key fetch is an application/network\n // error, and the inline backend would refetch the same key from the same\n // relayer. It rejects out of init exactly as the inline arm's would.\n const fheEncryptionKey = await this.#config.prefetchKey();\n try {\n const api = await this.#spawn(generation);\n const network = this.#config.network;\n const rpcRequest =\n typeof network === \"string\"\n ? null\n : proxy(async (args: { method: string; params?: unknown }) => {\n try {\n return await network.request(args as Parameters<EIP1193Provider[\"request\"]>[0]);\n } catch (error) {\n // Comlink keeps only name/message/stack on a thrown error, which\n // would strip the provider's `code` (4001, -32005) the worker's\n // classifiers read; flatten it so those fields cross.\n throw toWireError(error);\n }\n });\n // A callback that throws would reject the Comlink proxy call back in the\n // worker realm, where nothing can report it, so it is contained here.\n const log = proxy((level: \"debug\" | \"warn\" | \"error\", message: string) => {\n try {\n this.#config.logger[level](message);\n } catch (error) {\n this.#warnCallbackThrew(\"logger\", error);\n }\n });\n const onProgress = proxy((id: number, event: WireProgressEvent) => {\n try {\n this.#progressListeners.get(id)?.(event);\n } catch (error) {\n this.#warnCallbackThrew(\"onProgress\", error);\n }\n });\n // The copy stays on this thread so a later degrade to inline reuses the\n // key instead of refetching; transferring the wire copy avoids a third\n // in-transit copy of it.\n const wireKey = keyForTransfer(fheEncryptionKey);\n await this.#overBoundary(\n generation,\n api.init(\n transfer(\n {\n ...this.#config.initPayload,\n clientOptions: {\n ...this.#config.initPayload.clientOptions,\n fheEncryptionKey: wireKey.key,\n },\n rpcUrl: typeof network === \"string\" ? network : undefined,\n },\n wireKey.transfers,\n ),\n rpcRequest,\n log,\n onProgress,\n ),\n { ms: this.#config.timeouts.init, operation: \"init\" },\n );\n generation.api = api;\n this.#crashes = { ...this.#crashes, last: undefined };\n } catch (error) {\n // Only \"the worker never answered or crashed\" is infrastructure. An error\n // the worker itself reported (a chain read, bad key material) would fail\n // the same way inline, so it reaches the caller unchanged.\n if (!(error instanceof WorkerUnavailableError)) {\n this.#teardown(generation, new WorkerUnavailableError(\"Encrypt worker init failed.\"));\n throw error;\n }\n await this.#degrade(generation, error);\n }\n }\n\n /** Reports a caller callback that threw; the reporting itself must not throw back into the worker. */\n #warnCallbackThrew(callback: string, error: unknown): void {\n const reason = error instanceof Error ? error.message : String(error);\n try {\n this.#config.logger.warn(`Encrypt offload ${callback} callback threw: ${reason}`);\n } catch {\n // A logger that throws on its own warning leaves nowhere left to report.\n }\n }\n\n /**\n * The count spans a whole public entry, its init included, so a release\n * requested mid-call cannot terminate the worker between the init and the\n * operation.\n */\n async #withActive<T>(work: () => Promise<T>): Promise<T> {\n this.#active++;\n try {\n return await work();\n } finally {\n this.#active--;\n this.#releaseIfIdle();\n }\n }\n\n #releaseIfIdle(): void {\n if (!this.#releaseRequested || this.#active > 0) {\n return;\n }\n this.#releaseRequested = false;\n this.#generation?.worker?.terminate();\n // A full reset, so a release is the recovery lever for a degraded client:\n // the next call re-fetches the key and spawns a fresh worker either way.\n this.#generation = undefined;\n this.#degradePromise = undefined;\n this.#pinnedInline = false;\n this.#crashes = NO_CRASHES;\n }\n\n #createWorker(): Worker {\n const source = this.#config.workerSource;\n if (source === undefined) {\n return createEncryptWorker();\n }\n if (typeof source === \"function\") {\n const worker = source();\n // A memoized factory would hand the client a worker it already terminated,\n // so the contract is one fresh Worker per call.\n if (handedOutWorkers.has(worker)) {\n this.#config.logger.warnAlways(\n \"The offloadWorker factory returned a worker it already handed out; each call must construct a fresh Worker.\",\n );\n }\n handedOutWorkers.add(worker);\n return worker;\n }\n return new Worker(source, { type: \"module\", name: \"zama-fhe-encrypt\" });\n }\n\n /** Resolves once the worker's module graph has loaded. */\n async #spawn(generation: WorkerGeneration): Promise<Remote<EncryptWorkerApi>> {\n let worker: Worker;\n try {\n worker = this.#createWorker();\n } catch (error) {\n // A blocked construction is infrastructure, so it must reach the\n // degrade path as such rather than as the raw thrown error.\n throw new WorkerUnavailableError(error instanceof Error ? error.message : String(error), {\n cause: error,\n });\n }\n generation.worker = worker;\n const api = await this.#raceReady(generation, worker);\n this.#armCrashHandler(generation, worker);\n return api;\n }\n\n /** Resolves with the Comlink API on the worker's ready message; rejects on the spawn deadline or a pre-ready error. */\n #raceReady(generation: WorkerGeneration, worker: Worker): Promise<Remote<EncryptWorkerApi>> {\n return new Promise<Remote<EncryptWorkerApi>>((resolve, reject) => {\n const settle = () => {\n clearTimeout(timer);\n worker.removeEventListener(\"message\", onReady);\n worker.removeEventListener(\"error\", onError);\n };\n const timer = setTimeout(() => {\n settle();\n reject(\n new WorkerUnavailableError(\n `Encrypt worker did not start within ${this.#config.timeouts.spawn}ms.`,\n ),\n );\n }, this.#config.timeouts.spawn);\n const onReady = (event: MessageEvent) => {\n if (event.data === WORKER_READY_MESSAGE) {\n settle();\n resolve(wrap<EncryptWorkerApi>(worker));\n }\n };\n const onError = (event: ErrorEvent) => {\n settle();\n const message = event.message || \"Encrypt worker error.\";\n // A worker that never came up is not worth respawning per call, so\n // this failure is not flagged as a crash.\n reject(new WorkerUnavailableError(message));\n this.#teardown(generation, new WorkerUnavailableError(message));\n };\n worker.addEventListener(\"message\", onReady);\n worker.addEventListener(\"error\", onError);\n });\n }\n\n /** Permanent crash detector, armed only after ready so a pre-ready failure never counts as a crash. */\n #armCrashHandler(generation: WorkerGeneration, worker: Worker): void {\n worker.addEventListener(\"error\", (event: ErrorEvent) => {\n // A generation already torn down cannot crash the client again: nothing\n // is waiting on it, and the worker running in its place is unaffected.\n if (this.#generation !== generation) {\n return;\n }\n // A ready worker died under us: the teardown drops the memoized init so\n // the next call spawns a fresh one, and the operations it took down\n // finish inline.\n const crash = new WorkerUnavailableError(event.message || \"Encrypt worker error.\", {\n crashed: true,\n });\n this.#crashes = { ...this.#crashes, count: this.#crashes.count + 1, last: crash };\n this.#teardown(generation, crash);\n });\n }\n\n /**\n * Awaits one promise crossing the worker boundary, racing the generation's\n * `doomed` promise so a teardown settles it with the teardown's\n * `WorkerUnavailableError`, which degrades it inline. Without a `deadline` it\n * settles whenever the worker answers; a `deadline` bounds a lifecycle step,\n * and missing it means the worker is presumed stuck, so the generation is\n * torn down whole.\n */\n async #overBoundary<T>(\n generation: WorkerGeneration,\n work: Promise<T>,\n deadline?: { readonly ms: number; readonly operation: string },\n ): Promise<T> {\n const timer =\n deadline === undefined\n ? undefined\n : setTimeout(() => {\n this.#teardown(\n generation,\n new WorkerUnavailableError(\n `Encrypt worker ${deadline.operation} timed out after ${deadline.ms}ms.`,\n ),\n );\n }, deadline.ms);\n try {\n return await Promise.race([\n work.catch((error: unknown) => {\n const failure = isWireError(error) ? fromWireError(error) : (error as Error);\n // A payload Comlink could not carry is infrastructure, so it degrades\n // instead of reaching the caller as the operation's own failure.\n throw isCloneFailure(failure)\n ? new WorkerUnavailableError(failure.message, { cause: failure })\n : failure;\n }),\n generation.doomed,\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n }\n\n /**\n * Rejects and drops one generation whole: its worker, its memoized init, and\n * every crossing racing its `doomed` promise. The next call therefore re-runs\n * the cycle on a fresh generation, so a spurious teardown costs a respawn\n * rather than a permanent degrade.\n */\n #teardown(generation: WorkerGeneration | undefined, error: WorkerUnavailableError): void {\n if (generation === undefined) {\n return;\n }\n if (this.#generation === generation) {\n this.#generation = undefined;\n }\n generation.worker?.terminate();\n generation.worker = undefined;\n generation.api = undefined;\n generation.initPromise = undefined;\n generation.doom(error);\n }\n\n async #degrade(\n generation: WorkerGeneration | undefined,\n cause: unknown,\n ): Promise<EncryptOffloadBackend> {\n const reason = cause instanceof Error ? cause.message : String(cause);\n if (this.#config.strict) {\n this.#teardown(generation, new WorkerUnavailableError(\"Encrypt worker unavailable.\"));\n throw new EncryptOffloadUnavailableError(\n `Encrypt offload required (offloadEncrypt: true) but unavailable: ${reason}`,\n { cause },\n );\n }\n const { transient, pinning } = this.#classifyDegrade(cause);\n this.#pinnedInline ||= !transient;\n this.#teardown(generation, new WorkerUnavailableError(\"Encrypt worker degraded to inline.\"));\n this.#warnDegraded(reason, transient, pinning);\n if (this.#degradePromise === undefined) {\n // Only a live backend is memoized: an inline init is a key refetch, and a\n // transient failure there must not close the degrade path for the session.\n const attempt: Promise<EncryptOffloadBackend> = (async () => {\n const inline = this.#config.createInlineClient();\n await inline.init();\n return inline;\n })().catch((error: unknown) => {\n if (this.#degradePromise === attempt) {\n this.#degradePromise = undefined;\n }\n this.#config.logger.warnAlways(\n `Encrypt inline fallback failed to initialize: ${error instanceof Error ? error.message : String(error)}`,\n );\n throw error;\n });\n this.#degradePromise = attempt;\n }\n return this.#degradePromise;\n }\n\n /**\n * How one failure degrades, read off the state before the degrade mutates it:\n * `transient` diverts only this call, `pinning` settles the client inline now.\n * One crash is treated as transient; a repeat crash, or a worker that never\n * came up, settles the client inline rather than spawning a replacement per call.\n */\n #classifyDegrade(cause: unknown): { readonly transient: boolean; readonly pinning: boolean } {\n const transient =\n cause instanceof WorkerUnavailableError &&\n cause.crashed &&\n this.#crashes.count < CRASH_PIN_THRESHOLD;\n return { transient, pinning: !transient && !this.#pinnedInline };\n }\n\n /** One warning per failure, whether it pins the client inline or only diverts this call. */\n #warnDegraded(reason: string, transient: boolean, pinning: boolean): void {\n if (!pinning && this.#crashes.warnedFor === this.#crashes.count) {\n return;\n }\n this.#crashes = { ...this.#crashes, warnedFor: this.#crashes.count };\n const scope = transient ? \"in-flight encryption falls back\" : \"encryption falls back\";\n // Always on the console: a silent return to main-thread encryption is the\n // freeze this offload prevents.\n this.#config.logger.warnAlways(\n `${ENCRYPT_OFFLOAD_WARN_PREFIX}, ${scope} to the calling thread: ${reason}`,\n );\n }\n}\n","import { createUnsignedLegacyDecryptionPermitEip712 as createUnsignedLegacyDecryptionPermitEip712Action } from \"@fhevm/sdk/actions/base\";\nimport {\n createFhevmBaseClient,\n createFhevmDecryptClient,\n createFhevmEncryptClient,\n hasFhevmRuntimeConfig,\n} from \"@fhevm/sdk/viem\";\nimport {\n createFhevmCleartextBaseClient,\n createFhevmCleartextDecryptClient,\n createFhevmCleartextEncryptClient,\n} from \"@fhevm/sdk/viem/cleartext\";\nimport { createPublicClient, custom, http } from \"viem\";\nimport { toFhevmChain } from \"../chains/to-fhevm-chain\";\nimport type { FheChain } from \"../chains/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { getAppliedWireRuntime, hasAppliedLocateFile } from \"./applied-runtime\";\nimport type { LoggerService } from \"../services/logger-service\";\nimport { type RelayerTelemetry, telemetryHeaders } from \"../telemetry\";\nimport {\n DEFAULT_ENCRYPT_WORKER_TIMEOUTS,\n EncryptWorkerClient,\n type EncryptWorkerClientConfig,\n type EncryptWorkerTimeouts,\n} from \"../worker/encrypt-worker-client\";\nimport { BUNDLED_ENCRYPT_WORKER } from \"../worker/spawn\";\nimport type {\n FhevmBaseClient,\n FhevmClient,\n FhevmDecryptClient,\n FhevmEncryptBackend,\n FhevmRelayerOptions,\n RelayerRequestOptions,\n RelayerSDK,\n RelayerOptions,\n WireRuntimeConfig,\n} from \"./types\";\n\n/** The `@fhevm/sdk` client inputs the worker realm rebuilds its own client from. */\ntype EncryptInitPayload = EncryptWorkerClientConfig[\"initPayload\"];\n\n/** Construction config for {@link FhevmRelayer}. */\nexport interface FhevmRelayerConfig {\n /** FHE chain configuration. */\n chain: FheChain;\n /**\n * Cleartext mode for local dev/test chains without FHE infrastructure — reads\n * mock cleartexts from the on-chain executor (discovered automatically)\n * instead of calling the relayer.\n */\n cleartext?: boolean;\n /**\n * Per-transport {@link RelayerOptions}: `@fhevm/sdk` client options plus a\n * default request `timeout` applied to every relayer round-trip on the chain.\n */\n options?: RelayerOptions;\n /** Encrypt-worker offload mode; see `web()`'s `offloadEncrypt` option. */\n offloadEncrypt?: \"auto\" | boolean;\n /** Watchdog deadlines for the encrypt worker; `web()` defaults every field before it gets here. */\n offloadTimeouts?: EncryptWorkerTimeouts;\n /** Custom source for the encrypt worker; see `web()`'s `offloadWorker` option. */\n offloadWorker?: string | URL | (() => Worker);\n /** Receives worker log lines and offload-fallback warnings. */\n logger: LoggerService;\n telemetry?: RelayerTelemetry;\n}\n\n/**\n * Single-chain FHE backend that drives `@fhevm/sdk` on the calling thread with\n * capability-scoped lazy initialization.\n * EIP-712 signing is done by the signer layer; this backend builds the typed\n * data and, on decrypt, reassembles the new SDK's signed permit from the\n * interface's params + the previously returned signature.\n *\n * @remarks\n * Each method delegates to the narrowest base, decrypt, or encrypt client,\n * adding two cross-cutting behaviors that the delegated signatures don't\n * express:\n *\n * - **Lazy init.** Each operation initializes only the capability it requires.\n * Public decrypt avoids WASM, private decrypt loads TKMS only, and encryption\n * alone loads TFHE and the FHE encryption key.\n * - **Option merging.** The chain's default options (`auth`, `timeout`, `debug`)\n * are spread in first, then the per-call `options`, so a per-call value always\n * wins over the chain default. Serialization helpers make no relayer\n * round-trip, so they inject no options.\n *\n * @internal\n */\nexport class FhevmRelayer implements RelayerSDK {\n readonly #chain: FheChain;\n readonly #base: FhevmBaseClient;\n readonly #decrypt: FhevmDecryptClient;\n readonly #encrypt: FhevmEncryptBackend;\n readonly #defaultOptions: Partial<FhevmRelayerOptions>;\n readonly #telemetry: RelayerTelemetry | undefined;\n #encryptInitPromise: Promise<void> | undefined;\n\n /**\n * Builds capability-scoped `@fhevm/sdk` clients for the chain and captures\n * the chain's `auth`/`timeout`/`debug` as request defaults. Construction is\n * cheap; each client's one-time init is deferred to its first operation.\n */\n constructor(config: FhevmRelayerConfig) {\n this.#chain = config.chain;\n const { timeout, debug, batchRpcCalls, moduleVersions, fheEncryptionKey } =\n config.options ?? {};\n const auth = this.#chain.auth ? toFhevmAuth(this.#chain.auth) : undefined;\n const transport =\n typeof this.#chain.network === \"string\"\n ? http(this.#chain.network)\n : custom(this.#chain.network);\n const params = {\n publicClient: createPublicClient({ transport }),\n chain: toFhevmChain(this.#chain),\n options: { batchRpcCalls, moduleVersions, fheEncryptionKey },\n };\n this.#defaultOptions = {\n ...(auth !== undefined && { auth }),\n ...(timeout !== undefined && { timeout }),\n ...(debug !== undefined && { debug }),\n };\n this.#telemetry = config.telemetry;\n // The FHE key is always fetched here, on the calling thread, so the chain's\n // default request options (auth in particular) apply; a worker realm has no\n // access to them.\n const prefetchKey = () =>\n this.#base.fetchFheEncryptionKeyBytes({ options: this.#requestOptions(undefined) });\n // Re-listed rather than spread: the upstream client exposes an enumerable\n // `ready` getter, and a spread would call it, starting init at construction.\n const withInlineInit = (client: FhevmEncryptBackend): FhevmEncryptBackend => ({\n init: async () => {\n await prefetchKey();\n await client.init();\n },\n encryptValue: (parameters) => client.encryptValue(parameters),\n encryptValues: (parameters) => client.encryptValues(parameters),\n fetchFheEncryptionKeyBytes: (parameters) => client.fetchFheEncryptionKeyBytes(parameters),\n });\n if (config.cleartext) {\n this.#base = createFhevmCleartextBaseClient(params);\n this.#decrypt = createFhevmCleartextDecryptClient(params);\n this.#encrypt = withInlineInit(createFhevmCleartextEncryptClient(params));\n } else {\n this.#base = createFhevmBaseClient(params);\n this.#decrypt = createFhevmDecryptClient(params);\n this.#encrypt = this.#buildEncryptBackend(config, params, {\n prefetchKey,\n createInlineClient: () => withInlineInit(createFhevmEncryptClient(params)),\n });\n }\n }\n\n /**\n * Picks the encrypt backend for a non-cleartext chain: the worker client when\n * offload is on and reachable, the inline calling-thread client otherwise.\n */\n #buildEncryptBackend(\n config: FhevmRelayerConfig,\n params: { chain: EncryptInitPayload[\"chain\"]; options: EncryptInitPayload[\"clientOptions\"] },\n inline: {\n prefetchKey: EncryptWorkerClientConfig[\"prefetchKey\"];\n createInlineClient: () => FhevmEncryptBackend;\n },\n ): FhevmEncryptBackend {\n const offload = config.offloadEncrypt ?? false;\n const strict = offload === true;\n const workerAvailable =\n typeof Worker === \"function\" &&\n (config.offloadWorker !== undefined || BUNDLED_ENCRYPT_WORKER);\n // Silent both ways: offload off is what the caller asked for, and a realm\n // with no Worker is an environment fact that would warn on every SSR\n // render. Strict skips the capability check, since construction runs during\n // that render and the failure must surface at call time instead.\n if (offload === false || !(strict || workerAvailable)) {\n return inline.createInlineClient();\n }\n const runtime = getAppliedWireRuntime();\n const blocker = encryptOffloadBlocker(runtime);\n if (blocker !== undefined && !strict) {\n // Always on the console: the alternative is an opaque rejection at\n // encrypt time, or WASM assets silently resolved from the default URLs.\n config.logger.warnAlways(`Encryption runs on the calling thread: ${blocker}.`);\n return inline.createInlineClient();\n }\n const workerClient = new EncryptWorkerClient({\n initPayload: { chain: params.chain, clientOptions: params.options, runtime: runtime ?? {} },\n network: this.#chain.network,\n prefetchKey: inline.prefetchKey,\n createInlineClient: inline.createInlineClient,\n logger: config.logger,\n timeouts: config.offloadTimeouts ?? DEFAULT_ENCRYPT_WORKER_TIMEOUTS,\n workerSource: config.offloadWorker,\n // Strict with a blocker: the client degrades at init, which rejects at\n // call time rather than at config time.\n blockedReason: blocker,\n strict,\n });\n return {\n init: () => workerClient.init(),\n encryptValue: (parameters) => workerClient.encryptValue(parameters),\n encryptValues: (parameters) => workerClient.encryptValues(parameters),\n // Served from the calling thread: routing it through the worker would\n // structured-clone the ~50 MB key back out on every call. `ignoreCache`\n // therefore refreshes this thread's cache, not the worker's seeded key.\n fetchFheEncryptionKeyBytes: (parameters) => this.#base.fetchFheEncryptionKeyBytes(parameters),\n dispose: () => workerClient.dispose(),\n };\n }\n\n /** The FHE chain this backend is bound to. */\n get chain() {\n return this.#chain;\n }\n\n // `operation` becomes a header here and must never reach `@fhevm/sdk`.\n #requestOptions<T extends Partial<FhevmRelayerOptions> | undefined>(\n options: T,\n ): Omit<Partial<FhevmRelayerOptions> & NonNullable<T>, \"operation\"> {\n const { operation, ...merged } = {\n ...this.#defaultOptions,\n ...options,\n } as Partial<FhevmRelayerOptions> & NonNullable<T> & RelayerRequestOptions;\n if (this.#telemetry === undefined) {\n return merged;\n }\n return {\n ...merged,\n headers: { ...merged.headers, ...telemetryHeaders(this.#telemetry, operation) },\n };\n }\n\n // Only a fulfilled init is memoized: a rejection clears the memo so the next\n // encryption retries instead of inheriting a transient key-fetch failure.\n #initEncrypt = (): Promise<void> => {\n this.#encryptInitPromise ??= this.#encrypt.init().catch((error: unknown) => {\n this.#encryptInitPromise = undefined;\n throw error;\n });\n return this.#encryptInitPromise;\n };\n\n /**\n * Releases the encrypt worker once in-flight encryptions settle and drops the\n * memoized init; the next encryption spawns a fresh worker and re-initializes.\n */\n dispose = (): void => {\n this.#encryptInitPromise = undefined;\n this.#encrypt.dispose?.();\n };\n\n /**\n * Decrypts a single publicly-decryptable value — one whose contract granted\n * public access, so no permit or key pair is needed — into its typed clear\n * value.\n *\n * @example\n * ```ts\n * const { type, value } = await relayer.decryptPublicValue({\n * encryptedValue: handle, // a bytes32 ciphertext reference\n * });\n * ```\n */\n decryptPublicValue: FhevmClient[\"decryptPublicValue\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.decryptPublicValue({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Batch form of {@link decryptPublicValue}: decrypts many publicly-decryptable\n * values in one relayer round-trip, returning their typed clear values in\n * order.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptPublicValues({\n * encryptedValues: [handleA, handleB],\n * });\n * ```\n */\n decryptPublicValues: FhevmClient[\"decryptPublicValues\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.decryptPublicValues({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Like {@link decryptPublicValues}, but also returns the KMS signature bundle —\n * the handles list, ABI-encoded cleartexts, and decryption proof — needed to\n * verify or replay the result on-chain.\n *\n * @example\n * ```ts\n * const { clearValues, checkSignaturesArgs } =\n * await relayer.decryptPublicValuesWithSignatures({ encryptedValues: [handle] });\n * // checkSignaturesArgs: { handlesList, abiEncodedCleartexts, decryptionProof }\n * ```\n */\n decryptPublicValuesWithSignatures: FhevmClient[\"decryptPublicValuesWithSignatures\"] = async (\n parameters,\n ) => {\n await this.#base.init();\n return this.#base.decryptPublicValuesWithSignatures({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Encrypts one typed input under the chain's FHE key, bound to the contract it\n * targets and the user submitting it, and returns the ciphertext handle plus\n * the input proof the contract verifies on-chain. `type` is the FHE type\n * with the `e` prefix (`\"euint64\"`, `\"ebool\"`, `\"eaddress\"`).\n *\n * @example\n * ```ts\n * const { encryptedValue, inputProof } = await relayer.encryptValue({\n * value: { type: \"euint64\", value: 1000n },\n * contractAddress: \"0xToken…\",\n * userAddress: \"0xUser…\",\n * });\n * ```\n */\n encryptValue: FhevmClient[\"encryptValue\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.encryptValue({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Batch form of {@link encryptValue}: encrypts several inputs for the same\n * contract and user in one call, returning all ciphertext handles under a\n * single shared input proof.\n *\n * @example\n * ```ts\n * const { encryptedValues, inputProof } = await relayer.encryptValues({\n * values: [\n * { type: \"euint64\", value: 1000n },\n * { type: \"ebool\", value: true },\n * ],\n * contractAddress: \"0xToken…\",\n * userAddress: \"0xUser…\",\n * });\n * ```\n */\n encryptValues: FhevmClient[\"encryptValues\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.encryptValues({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * User-decrypts a single access-controlled value: the relayer re-encrypts it\n * to the ephemeral transport key pair, gated by the signed permit, and this\n * returns the typed clear value. Build the key pair with\n * {@link generateTransportKeyPair} and the permit with\n * {@link signDecryptionPermit}.\n *\n * @example\n * ```ts\n * const { type, value } = await relayer.decryptValue({\n * encryptedValue: handle,\n * contractAddress: \"0xToken…\",\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValue: FhevmClient[\"decryptValue\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValue({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Batch form of {@link decryptValue} for values that all belong to the same\n * contract; returns the typed clear values positionally. For values spanning\n * multiple contracts, use {@link decryptValuesFromPairs}.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptValues({\n * encryptedValues: [handleA, handleB],\n * contractAddress: \"0xToken…\",\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValues: FhevmClient[\"decryptValues\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValues({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * User-decrypts values that span multiple contracts: each pair carries its own\n * `contractAddress`, so one permit covering those contracts decrypts them all\n * in a single round-trip. Returns the typed clear values positionally.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptValuesFromPairs({\n * pairs: [\n * { encryptedValue: handleA, contractAddress: \"0xTokenA…\" },\n * { encryptedValue: handleB, contractAddress: \"0xTokenB…\" },\n * ],\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValuesFromPairs: FhevmClient[\"decryptValuesFromPairs\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValuesFromPairs({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Fetches the chain's raw FHE public-key bytes — the key encryption uses —\n * served from cache unless `ignoreCache` forces a refetch. Rarely called\n * directly: {@link encryptValue}/{@link encryptValues} fetch the key for you.\n *\n * @example\n * ```ts\n * const keyBytes = await relayer.fetchFheEncryptionKeyBytes();\n * const fresh = await relayer.fetchFheEncryptionKeyBytes({ ignoreCache: true });\n * ```\n */\n fetchFheEncryptionKeyBytes: FhevmClient[\"fetchFheEncryptionKeyBytes\"] = async (parameters) => {\n // Served from the base client, which shares the key cache with the encrypt\n // client: initializing encryption here would spawn the encrypt worker and\n // wait out its bring-up for a key this thread fetches itself.\n await this.#base.init();\n return this.#base.fetchFheEncryptionKeyBytes({\n ...parameters,\n options: this.#requestOptions(parameters?.options),\n });\n };\n\n /**\n * Builds the EIP-712 user-decrypt permit and signs it with the given signer,\n * authorizing the transport key pair to decrypt the listed contracts' values\n * for `durationSeconds` starting at `startTimestamp`. Pass `delegatorAddress`\n * to sign a delegated permit — decrypting values owned by that account instead\n * of the signer's own. Persist the result via\n * {@link serializeSignedDecryptionPermit}.\n *\n * @example\n * ```ts\n * const signedPermit = await relayer.signDecryptionPermit({\n * transportKeyPair,\n * contractAddresses: [\"0xToken…\"],\n * startTimestamp: Math.floor(Date.now() / 1000),\n * durationSeconds: 60 * 60 * 24,\n * signerAddress: \"0xUser…\",\n * signer,\n * // delegatorAddress: \"0xOwner…\", // omit for a self permit\n * });\n * ```\n */\n signDecryptionPermit: FhevmClient[\"signDecryptionPermit\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.signDecryptionPermit(parameters);\n };\n\n /**\n * Builds the unsigned EIP-712 typed data for a V1 decryption permit, without\n * signing it — the signer-less counterpart to {@link signDecryptionPermit}.\n * Hand the result to an out-of-process signer for `eth_signTypedData_v4`,\n * then verify the returned signature via {@link parseSignedDecryptionPermit}.\n *\n * Not on `@fhevm/sdk`'s client decorator, so it's called directly against\n * the base client rather than through a decorated method.\n *\n * @example\n * ```ts\n * const eip712 = await relayer.createUnsignedLegacyDecryptionPermitEip712({\n * transportKeyPair,\n * contractAddresses: [\"0xToken…\"],\n * startTimestamp: Math.floor(Date.now() / 1000),\n * durationSeconds: 60 * 60 * 24,\n * // delegatorAddress: \"0xOwner…\", // omit for a self permit\n * });\n * ```\n */\n createUnsignedLegacyDecryptionPermitEip712: RelayerSDK[\"createUnsignedLegacyDecryptionPermitEip712\"] =\n (parameters) => createUnsignedLegacyDecryptionPermitEip712Action(this.#base, parameters);\n\n // Permit/key-pair helpers carry no request options. Parsing explicitly\n // initializes the capability that validates the restored value; serialization\n // resolves the frozen context internally (via initPublicAction), which reads\n // on-chain state.\n\n /**\n * Serializes a transport key pair to a hex `{ publicKey, privateKey }` pair for\n * storage or transport, so a decryption session can resume without regenerating\n * keys. Reverse of {@link parseTransportKeyPair}.\n *\n * @example\n * ```ts\n * const stored = await relayer.serializeTransportKeyPair({ transportKeyPair });\n * // { publicKey: \"0x…\", privateKey: \"0x…\" }\n * ```\n */\n serializeTransportKeyPair: FhevmClient[\"serializeTransportKeyPair\"] = (parameters) =>\n this.#decrypt.serializeTransportKeyPair(parameters);\n\n /**\n * Serializes a signed permit to a plain, JSON-stringifiable object (version,\n * EIP-712 payload, signature, signer) for caching or transport. Reverse of\n * {@link parseSignedDecryptionPermit}.\n *\n * @example\n * ```ts\n * const serialized = await relayer.serializeSignedDecryptionPermit({ signedPermit });\n * localStorage.setItem(\"permit\", JSON.stringify(serialized));\n * ```\n */\n serializeSignedDecryptionPermit: FhevmClient[\"serializeSignedDecryptionPermit\"] = (parameters) =>\n this.#base.serializeSignedDecryptionPermit(parameters);\n\n /**\n * Rebuilds a transport key pair from its serialized hex\n * `{ publicKey, privateKey }` form. Reverse of {@link serializeTransportKeyPair}.\n *\n * @example\n * ```ts\n * const transportKeyPair = await relayer.parseTransportKeyPair({\n * publicKey: stored.publicKey,\n * privateKey: stored.privateKey,\n * });\n * ```\n */\n parseTransportKeyPair: FhevmClient[\"parseTransportKeyPair\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.parseTransportKeyPair(parameters);\n };\n\n /**\n * Rebuilds a signed permit from its serialized form and validates it: checks\n * the EIP-712 structure, verifies the signature against the on-chain verifier,\n * and confirms the permit's public key matches `transportKeyPair`. Reverse of\n * {@link serializeSignedDecryptionPermit}.\n *\n * @throws if the permit is malformed, expired, or its signature is invalid.\n *\n * @example\n * ```ts\n * const signedPermit = await relayer.parseSignedDecryptionPermit({\n * serializedPermit,\n * transportKeyPair,\n * });\n * ```\n */\n parseSignedDecryptionPermit: FhevmClient[\"parseSignedDecryptionPermit\"] = async (parameters) => {\n await this.#base.init();\n const { serializedPermit } = parameters;\n return this.#base.parseSignedDecryptionPermit({\n ...parameters,\n serializedPermit: {\n ...serializedPermit,\n signature: normalizeSignatureV(serializedPermit.signature),\n },\n });\n };\n\n /**\n * Generates a fresh ephemeral transport key pair for a user-decrypt session.\n * The relayer re-encrypts decrypted values to this pair's public key, so only\n * the holder of the private key can read them; bind it to a permit via\n * {@link signDecryptionPermit}.\n *\n * @example\n * ```ts\n * const transportKeyPair = await relayer.generateTransportKeyPair();\n * ```\n */\n generateTransportKeyPair: FhevmClient[\"generateTransportKeyPair\"] = async () => {\n await this.#decrypt.init();\n return this.#decrypt.generateTransportKeyPair();\n };\n}\n\n/**\n * Rewrites a 65-byte signature's recovery byte from 0/1 to 27/28. The gateway\n * verifies V1 permits on-chain with OpenZeppelin `ECDSA.recover`, which rejects\n * 0/1. Longer signatures (ERC-1271, concatenated) pass through untouched.\n */\nfunction normalizeSignatureV(signature: string): string {\n if (signature.length !== 132) {\n return signature;\n }\n const v = parseInt(signature.slice(130), 16);\n if (v !== 0 && v !== 1) {\n return signature;\n }\n return `${signature.slice(0, 130)}${v === 0 ? \"1b\" : \"1c\"}`;\n}\n\n/**\n * The one reason, if any, this thread's configuration cannot be reproduced in\n * the worker realm, so offload is worse than inline there.\n */\nfunction encryptOffloadBlocker(runtime: WireRuntimeConfig | undefined): string | undefined {\n // A runtime `locateFile` is a function: it cannot be cloned into the worker\n // realm, which would silently resolve WASM assets from the default URLs.\n if (hasAppliedLocateFile()) {\n return \"a runtime locateFile cannot cross the encrypt worker boundary\";\n }\n // Unreadable here, so the worker would run on fhevm defaults: an auth it\n // carries would 401 inside the worker as an application error, which never degrades.\n if (runtime === undefined && hasFhevmRuntimeConfig()) {\n return \"a runtime config set outside createConfig cannot be replicated in the encrypt worker realm\";\n }\n return undefined;\n}\n\n/**\n * Translates the SDK's public {@link FheChain.auth} shape (discriminated by\n * `__type`) into the `type`-discriminated `auth` that `@fhevm/sdk` expects.\n *\n * @throws if the auth discriminator is not one of the supported kinds.\n */\nexport function toFhevmAuth(\n auth: NonNullable<FheChain[\"auth\"]>,\n): NonNullable<FhevmRelayerOptions[\"auth\"]> {\n const type = auth[\"__type\"];\n switch (type) {\n case \"ApiKeyHeader\":\n return { type, value: auth.value, header: auth.header };\n case \"ApiKeyCookie\":\n return { type, value: auth.value, cookie: auth.cookie };\n case \"BearerToken\":\n return { type, token: auth.token };\n default:\n throw new ConfigurationError(`Unknown auth type: ${String(type)}`);\n }\n}\n"],"x_google_ignoreList":[1],"mappings":"qUAYA,SAAgB,EAAa,EAA6B,CACxD,MAAO,CACL,GAAI,EAAM,GACV,MAAO,CACL,UAAW,CACT,IAAK,CAAE,QAAS,EAAM,kBAAmB,EACzC,cAAe,CAAE,QAAS,EAAM,4BAA6B,EAC7D,YAAa,CAAE,QAAS,EAAM,kBAAmB,EACjD,eAAgB,IAAA,EAClB,EACA,WAAY,EAAM,WAClB,QAAS,CACP,GAAI,EAAM,eACV,UAAW,CACT,WAAY,CAAE,QAAS,EAAM,kCAAmC,EAChE,kBAAmB,CAAE,QAAS,EAAM,yCAA0C,CAChF,CACF,CACF,CACF,CACF;;;;;;kBChCC,SAAU,EAAQ,EAAS,CACxB,OAAO,GAAY,UAAmB,IAAW,OAAc,EAAQ,CAAO,EAC9E,OAAO,QAAW,YAAc,OAAO,IAAM,OAAO,CAAC,SAAS,EAAG,CAAO,GACvE,EAAS,OAAO,WAAe,IAAc,WAAa,GAAU,KAAM,EAAQ,EAAO,QAAU,CAAC,CAAC,EAC1G,EAAA,CAAC,GAAS,SAAU,EAAS,CAAE,aAO3B,IAAM,EAAc,OAAO,eAAe,EACpC,EAAiB,OAAO,kBAAkB,EAC1C,EAAe,OAAO,sBAAsB,EAC5C,EAAY,OAAO,mBAAmB,EACtC,EAAc,OAAO,gBAAgB,EACrC,EAAY,GAAS,OAAO,GAAQ,YAAY,GAAiB,OAAO,GAAQ,WAgDhF,EAAmB,IAAI,IAAI,CAC7B,CAAC,QAAS,CA5CV,UAAY,GAAQ,EAAS,CAAG,GAAK,EAAI,GACzC,UAAU,EAAK,CACX,GAAM,CAAE,QAAO,SAAU,IAAI,eAE7B,OADA,EAAO,EAAK,CAAK,EACV,CAAC,EAAO,CAAC,CAAK,CAAC,CAC1B,EACA,YAAY,EAAM,CAEd,OADA,EAAK,MAAM,EACJ,EAAK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C1C,IAAM,EAAO,EAAK,OAClB,OAAQ,EAAR,CACE,IAAK,eACH,MAAO,CAAE,OAAM,MAAO,EAAK,MAAO,OAAQ,EAAK,MAAO,EACxD,IAAK,eACH,MAAO,CAAE,OAAM,MAAO,EAAK,MAAO,OAAQ,EAAK,MAAO,EACxD,IAAK,cACH,MAAO,CAAE,OAAM,MAAO,EAAK,KAAM,EACnC,QACE,MAAM,IAAIC,EAAAA,EAAmB,sBAAsB,OAAO,CAAI,GAAG,CACrE,CACF"}
1
+ {"version":3,"file":"fhevm-relayer.cjs","names":["readRetryAfterHeader","isValidRetryAfterSeconds","#config","#progressListeners","#generation","#withActive","#initOnce","#dispatch","#releaseRequested","#releaseIfIdle","#degradePromise","#pinnedInline","#degrade","#crashes","#sequence","#overBoundary","#spawn","#warnCallbackThrew","#teardown","#active","#createWorker","#raceReady","#armCrashHandler","EncryptOffloadUnavailableError","#classifyDegrade","#warnDegraded","#chain","#base","#decrypt","#encrypt","#defaultOptions","#telemetry","#requestOptions","#buildEncryptBackend","getAppliedWireRuntime","telemetryHeaders","#encryptInitPromise","#initEncrypt","hasAppliedLocateFile","ConfigurationError"],"sources":["../../src/chains/to-fhevm-chain.ts","../../../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/umd/comlink.js","../../src/worker/protocol.ts","../../src/worker/spawn.ts","../../src/worker/encrypt-worker-client.ts","../../src/relayer/fhevm-relayer.ts"],"sourcesContent":["import type { FhevmChain } from \"@fhevm/sdk/chains\";\nimport type { FheChain } from \"./types\";\n\n/**\n * Derive an `@fhevm/sdk` {@link FhevmChain} from zama-sdk's richer\n * {@link FheChain}.\n *\n * `FheChain` carries fields `@fhevm/sdk` does not model (RPC `network`,\n * `registryAddress`, `executorAddress`, cleartext signer keys); those stay on\n * `FheChain` for the token layer. This adapter projects only the subset the\n * FHE runtime needs: contract addresses, relayer URL, and gateway.\n */\nexport function toFhevmChain(chain: FheChain): FhevmChain {\n return {\n id: chain.id,\n fhevm: {\n contracts: {\n acl: { address: chain.aclContractAddress },\n inputVerifier: { address: chain.inputVerifierContractAddress },\n kmsVerifier: { address: chain.kmsContractAddress },\n protocolConfig: undefined,\n },\n relayerUrl: chain.relayerUrl,\n gateway: {\n id: chain.gatewayChainId,\n contracts: {\n decryption: { address: chain.verifyingContractAddressDecryption },\n inputVerification: { address: chain.verifyingContractAddressInputVerification },\n },\n },\n },\n } satisfies FhevmChain;\n}\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Comlink = {}));\n})(this, (function (exports) { 'use strict';\n\n /**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n const proxyMarker = Symbol(\"Comlink.proxy\");\n const createEndpoint = Symbol(\"Comlink.endpoint\");\n const releaseProxy = Symbol(\"Comlink.releaseProxy\");\n const finalizer = Symbol(\"Comlink.finalizer\");\n const throwMarker = Symbol(\"Comlink.thrown\");\n const isObject = (val) => (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n /**\n * Internal transfer handle to handle objects marked to proxy.\n */\n const proxyTransferHandler = {\n canHandle: (val) => isObject(val) && val[proxyMarker],\n serialize(obj) {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port1);\n return [port2, [port2]];\n },\n deserialize(port) {\n port.start();\n return wrap(port);\n },\n };\n /**\n * Internal transfer handler to handle thrown exceptions.\n */\n const throwTransferHandler = {\n canHandle: (value) => isObject(value) && throwMarker in value,\n serialize({ value }) {\n let serialized;\n if (value instanceof Error) {\n serialized = {\n isError: true,\n value: {\n message: value.message,\n name: value.name,\n stack: value.stack,\n },\n };\n }\n else {\n serialized = { isError: false, value };\n }\n return [serialized, []];\n },\n deserialize(serialized) {\n if (serialized.isError) {\n throw Object.assign(new Error(serialized.value.message), serialized.value);\n }\n throw serialized.value;\n },\n };\n /**\n * Allows customizing the serialization of certain values.\n */\n const transferHandlers = new Map([\n [\"proxy\", proxyTransferHandler],\n [\"throw\", throwTransferHandler],\n ]);\n function isAllowedOrigin(allowedOrigins, origin) {\n for (const allowedOrigin of allowedOrigins) {\n if (origin === allowedOrigin || allowedOrigin === \"*\") {\n return true;\n }\n if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n return true;\n }\n }\n return false;\n }\n function expose(obj, ep = globalThis, allowedOrigins = [\"*\"]) {\n ep.addEventListener(\"message\", function callback(ev) {\n if (!ev || !ev.data) {\n return;\n }\n if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n return;\n }\n const { id, type, path } = Object.assign({ path: [] }, ev.data);\n const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n let returnValue;\n try {\n const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n switch (type) {\n case \"GET\" /* MessageType.GET */:\n {\n returnValue = rawValue;\n }\n break;\n case \"SET\" /* MessageType.SET */:\n {\n parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n returnValue = true;\n }\n break;\n case \"APPLY\" /* MessageType.APPLY */:\n {\n returnValue = rawValue.apply(parent, argumentList);\n }\n break;\n case \"CONSTRUCT\" /* MessageType.CONSTRUCT */:\n {\n const value = new rawValue(...argumentList);\n returnValue = proxy(value);\n }\n break;\n case \"ENDPOINT\" /* MessageType.ENDPOINT */:\n {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port2);\n returnValue = transfer(port1, [port1]);\n }\n break;\n case \"RELEASE\" /* MessageType.RELEASE */:\n {\n returnValue = undefined;\n }\n break;\n default:\n return;\n }\n }\n catch (value) {\n returnValue = { value, [throwMarker]: 0 };\n }\n Promise.resolve(returnValue)\n .catch((value) => {\n return { value, [throwMarker]: 0 };\n })\n .then((returnValue) => {\n const [wireValue, transferables] = toWireValue(returnValue);\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n if (type === \"RELEASE\" /* MessageType.RELEASE */) {\n // detach and deactive after sending release response above.\n ep.removeEventListener(\"message\", callback);\n closeEndPoint(ep);\n if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n obj[finalizer]();\n }\n }\n })\n .catch((error) => {\n // Send Serialization Error To Caller\n const [wireValue, transferables] = toWireValue({\n value: new TypeError(\"Unserializable return value\"),\n [throwMarker]: 0,\n });\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n });\n });\n if (ep.start) {\n ep.start();\n }\n }\n function isMessagePort(endpoint) {\n return endpoint.constructor.name === \"MessagePort\";\n }\n function closeEndPoint(endpoint) {\n if (isMessagePort(endpoint))\n endpoint.close();\n }\n function wrap(ep, target) {\n const pendingListeners = new Map();\n ep.addEventListener(\"message\", function handleMessage(ev) {\n const { data } = ev;\n if (!data || !data.id) {\n return;\n }\n const resolver = pendingListeners.get(data.id);\n if (!resolver) {\n return;\n }\n try {\n resolver(data);\n }\n finally {\n pendingListeners.delete(data.id);\n }\n });\n return createProxy(ep, pendingListeners, [], target);\n }\n function throwIfProxyReleased(isReleased) {\n if (isReleased) {\n throw new Error(\"Proxy has been released and is not useable\");\n }\n }\n function releaseEndpoint(ep) {\n return requestResponseMessage(ep, new Map(), {\n type: \"RELEASE\" /* MessageType.RELEASE */,\n }).then(() => {\n closeEndPoint(ep);\n });\n }\n const proxyCounter = new WeakMap();\n const proxyFinalizers = \"FinalizationRegistry\" in globalThis &&\n new FinalizationRegistry((ep) => {\n const newCount = (proxyCounter.get(ep) || 0) - 1;\n proxyCounter.set(ep, newCount);\n if (newCount === 0) {\n releaseEndpoint(ep);\n }\n });\n function registerProxy(proxy, ep) {\n const newCount = (proxyCounter.get(ep) || 0) + 1;\n proxyCounter.set(ep, newCount);\n if (proxyFinalizers) {\n proxyFinalizers.register(proxy, ep, proxy);\n }\n }\n function unregisterProxy(proxy) {\n if (proxyFinalizers) {\n proxyFinalizers.unregister(proxy);\n }\n }\n function createProxy(ep, pendingListeners, path = [], target = function () { }) {\n let isProxyReleased = false;\n const proxy = new Proxy(target, {\n get(_target, prop) {\n throwIfProxyReleased(isProxyReleased);\n if (prop === releaseProxy) {\n return () => {\n unregisterProxy(proxy);\n releaseEndpoint(ep);\n pendingListeners.clear();\n isProxyReleased = true;\n };\n }\n if (prop === \"then\") {\n if (path.length === 0) {\n return { then: () => proxy };\n }\n const r = requestResponseMessage(ep, pendingListeners, {\n type: \"GET\" /* MessageType.GET */,\n path: path.map((p) => p.toString()),\n }).then(fromWireValue);\n return r.then.bind(r);\n }\n return createProxy(ep, pendingListeners, [...path, prop]);\n },\n set(_target, prop, rawValue) {\n throwIfProxyReleased(isProxyReleased);\n // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n const [value, transferables] = toWireValue(rawValue);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"SET\" /* MessageType.SET */,\n path: [...path, prop].map((p) => p.toString()),\n value,\n }, transferables).then(fromWireValue);\n },\n apply(_target, _thisArg, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const last = path[path.length - 1];\n if (last === createEndpoint) {\n return requestResponseMessage(ep, pendingListeners, {\n type: \"ENDPOINT\" /* MessageType.ENDPOINT */,\n }).then(fromWireValue);\n }\n // We just pretend that `bind()` didn’t happen.\n if (last === \"bind\") {\n return createProxy(ep, pendingListeners, path.slice(0, -1));\n }\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"APPLY\" /* MessageType.APPLY */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n construct(_target, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"CONSTRUCT\" /* MessageType.CONSTRUCT */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n });\n registerProxy(proxy, ep);\n return proxy;\n }\n function myFlat(arr) {\n return Array.prototype.concat.apply([], arr);\n }\n function processArguments(argumentList) {\n const processed = argumentList.map(toWireValue);\n return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n }\n const transferCache = new WeakMap();\n function transfer(obj, transfers) {\n transferCache.set(obj, transfers);\n return obj;\n }\n function proxy(obj) {\n return Object.assign(obj, { [proxyMarker]: true });\n }\n function windowEndpoint(w, context = globalThis, targetOrigin = \"*\") {\n return {\n postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),\n addEventListener: context.addEventListener.bind(context),\n removeEventListener: context.removeEventListener.bind(context),\n };\n }\n function toWireValue(value) {\n for (const [name, handler] of transferHandlers) {\n if (handler.canHandle(value)) {\n const [serializedValue, transferables] = handler.serialize(value);\n return [\n {\n type: \"HANDLER\" /* WireValueType.HANDLER */,\n name,\n value: serializedValue,\n },\n transferables,\n ];\n }\n }\n return [\n {\n type: \"RAW\" /* WireValueType.RAW */,\n value,\n },\n transferCache.get(value) || [],\n ];\n }\n function fromWireValue(value) {\n switch (value.type) {\n case \"HANDLER\" /* WireValueType.HANDLER */:\n return transferHandlers.get(value.name).deserialize(value.value);\n case \"RAW\" /* WireValueType.RAW */:\n return value.value;\n }\n }\n function requestResponseMessage(ep, pendingListeners, msg, transfers) {\n return new Promise((resolve) => {\n const id = generateUUID();\n pendingListeners.set(id, resolve);\n if (ep.start) {\n ep.start();\n }\n ep.postMessage(Object.assign({ id }, msg), transfers);\n });\n }\n function generateUUID() {\n return new Array(4)\n .fill(0)\n .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n .join(\"-\");\n }\n\n exports.createEndpoint = createEndpoint;\n exports.expose = expose;\n exports.finalizer = finalizer;\n exports.proxy = proxy;\n exports.proxyMarker = proxyMarker;\n exports.releaseProxy = releaseProxy;\n exports.transfer = transfer;\n exports.transferHandlers = transferHandlers;\n exports.windowEndpoint = windowEndpoint;\n exports.wrap = wrap;\n\n}));\n//# sourceMappingURL=comlink.js.map\n","/**\n * Shared contract between the main-thread encrypt client and the encrypt\n * worker, spoken over Comlink. Every payload must survive `structuredClone`:\n * no `AbortSignal`, no class instances; callbacks cross as Comlink proxies.\n */\n\nimport type { FhevmChain } from \"@fhevm/sdk/chains\";\nimport type {\n FhevmClientOptions,\n FhevmEncryptBackend,\n FhevmRelayerOptions,\n WireRuntimeConfig,\n} from \"../relayer/types\";\nimport { isValidRetryAfterSeconds, readRetryAfterHeader } from \"../utils/error\";\n\ntype EncryptParameters = Parameters<FhevmEncryptBackend[\"encryptValue\"]>[0];\ntype EncryptsParameters = Parameters<FhevmEncryptBackend[\"encryptValues\"]>[0];\n\n/**\n * What the worker offloads, and all the encrypt client's surface the worker\n * client implements. Key fetches stay on the calling thread, where the chain's\n * auth applies and the key never crosses back out.\n */\nexport type EncryptOffloadBackend = Pick<\n FhevmEncryptBackend,\n \"init\" | \"encryptValue\" | \"encryptValues\"\n>;\n\n/** Per-request options minus `signal`, the one non-cloneable member of the set. */\nexport type WireRequestOptions = Omit<FhevmRelayerOptions, \"signal\">;\n\nexport type WireProgressEvent = Parameters<\n NonNullable<NonNullable<EncryptParameters[\"options\"]>[\"onProgress\"]>\n>[0];\n\nexport type WireInitPayload = {\n readonly chain: FhevmChain;\n /** RPC URL for host-chain reads; absent when reads proxy through `rpcRequest`. */\n readonly rpcUrl: string | undefined;\n /** Carries `fheEncryptionKey`, prefetched on the main thread so the worker skips the download. */\n readonly clientOptions: FhevmClientOptions;\n readonly runtime: WireRuntimeConfig;\n};\n\n/** Main-thread callback the worker uses for host-chain reads when the chain's network is an injected provider. */\nexport type WireRpcRequest = (args: { method: string; params?: unknown }) => Promise<unknown>;\n\n/**\n * Main-thread callback receiving every operation's progress events, routed on\n * `id`. One channel per worker avoids minting a `MessageChannel` per call, whose\n * local port and listener would linger until garbage collection after terminate.\n * Returns `unknown`: a Comlink proxy call answers with a promise.\n */\nexport type WireProgressCallback = (id: number, event: WireProgressEvent) => unknown;\n\nexport type WireLogCallback = (level: \"debug\" | \"warn\" | \"error\", message: string) => unknown;\n\n/**\n * The API the worker exposes over Comlink. `id` correlates an in-flight\n * operation with `abort` and with its progress events, since neither an\n * `AbortSignal` nor a per-call callback can cross the boundary cheaply. The\n * `init` callback parameters must be passed as Comlink proxies (or `null`).\n */\nexport type EncryptWorkerApi = {\n init(\n payload: WireInitPayload,\n rpcRequest: WireRpcRequest | null,\n log: WireLogCallback,\n onProgress: WireProgressCallback,\n ): Promise<void>;\n encryptValue(\n id: number,\n parameters: {\n readonly value: EncryptParameters[\"value\"];\n readonly contractAddress: string;\n readonly userAddress: string;\n readonly options: WireRequestOptions | undefined;\n },\n ): ReturnType<FhevmEncryptBackend[\"encryptValue\"]>;\n encryptValues(\n id: number,\n parameters: {\n readonly values: EncryptsParameters[\"values\"];\n readonly contractAddress: string;\n readonly userAddress: string;\n readonly options: WireRequestOptions | undefined;\n },\n ): ReturnType<FhevmEncryptBackend[\"encryptValues\"]>;\n abort(id: number): void;\n};\n\n/** Raw message the worker posts once its module graph has loaded, before Comlink traffic. */\nexport const WORKER_READY_MESSAGE = \"zama-encrypt-worker-ready\";\n\n/**\n * An `Error` flattened for the boundary crossing, thrown by the worker as a\n * plain object so it survives structured clone intact. `props` carries the\n * fields the SDK's duck-typed classifiers read (`statusCode`, `retryAfter`,\n * `code`, …); a cloned `Error` instance would drop them with the prototype.\n * Reading them through the prototype chain is deliberate: upstream's `status`\n * and `relayerApiError` are prototype getters, not own fields.\n */\nexport type WireError = {\n readonly wireError: true;\n readonly name: string;\n readonly message: string;\n readonly stack: string | undefined;\n readonly props: Record<string, unknown>;\n readonly cause: WireError | undefined;\n};\n\nexport function isWireError(value: unknown): value is WireError {\n // Exact `true`, not presence: an `Error` subclass carrying the key must not be\n // rehydrated as a flattened one.\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { wireError?: unknown }).wireError === true\n );\n}\n\n/**\n * Fields preserved across the boundary: what the error classifiers read off\n * `@fhevm/sdk`, relayer, and JSON-RPC errors, plus the `error`/`info` nesting\n * keys those classifiers walk alongside `cause`.\n */\nconst WIRE_ERROR_PROPS = [\n \"statusCode\",\n \"status\",\n \"retryAfter\",\n \"timeoutMs\",\n \"relayerApiError\",\n \"code\",\n \"data\",\n \"shortMessage\",\n \"details\",\n \"error\",\n \"info\",\n] as const;\n\nconst MAX_CAUSE_DEPTH = 6;\n\n/** A probe is exact where a structural walk only approximates. */\nfunction isCloneSafe(value: unknown): boolean {\n try {\n structuredClone(value);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * The `Retry-After` header survives as a plain number of seconds; the\n * `Response` object it lives on cannot cross the boundary.\n */\nfunction retryAfterFromResponse(error: object): number | undefined {\n const response = (error as { response?: { headers?: unknown } }).response;\n return readRetryAfterHeader(response?.headers);\n}\n\n/**\n * `JSON.stringify` throws instead of returning `undefined` on a bigint or a\n * circular value; a non-Error thrown value must never fail error handling itself.\n */\nfunction stringifyNonError(error: unknown): string {\n try {\n return JSON.stringify(error) ?? String(error);\n } catch {\n return String(error);\n }\n}\n\n/** The classifier fields readable off one thrown value, `Error` or plain object alike. */\nfunction extractWireProps(source: object): Record<string, unknown> {\n const props: Record<string, unknown> = {};\n for (const key of WIRE_ERROR_PROPS) {\n const value = (source as Record<string, unknown>)[key];\n if (value !== undefined && isCloneSafe(value)) {\n props[key] = value;\n }\n }\n // The header wins over a malformed own delay (`0`, negative, `NaN`), as the\n // inline extractor in `utils/error.ts` decides it.\n if (!isValidRetryAfterSeconds(props[\"retryAfter\"])) {\n const fromHeader = retryAfterFromResponse(source);\n if (fromHeader !== undefined) {\n props[\"retryAfter\"] = fromHeader;\n }\n }\n return props;\n}\n\nexport function toWireError(error: unknown, depth: number = MAX_CAUSE_DEPTH): WireError {\n if (isWireError(error)) {\n return error;\n }\n const nest = (cause: unknown): WireError | undefined =>\n depth > 0 && cause !== undefined ? toWireError(cause, depth - 1) : undefined;\n if (error instanceof Error) {\n return {\n wireError: true,\n name: error.name,\n message: error.message,\n stack: error.stack,\n props: extractWireProps(error),\n cause: nest(error.cause),\n };\n }\n if (typeof error === \"object\" && error !== null) {\n // Wallets reject with a plain `{ code, message, data }`; dropping `code`\n // would break viem's classification inside the worker.\n const { message, cause } = error as { message?: unknown; cause?: unknown };\n return {\n wireError: true,\n name: \"Error\",\n message: typeof message === \"string\" ? message : stringifyNonError(error),\n stack: undefined,\n props: extractWireProps(error),\n cause: nest(cause),\n };\n }\n return {\n wireError: true,\n name: \"Error\",\n message: typeof error === \"string\" ? error : stringifyNonError(error),\n stack: undefined,\n props: {},\n cause: undefined,\n };\n}\n\n/**\n * Rebuilds a plain `Error` carrying the original `name`, own fields, and cause\n * chain, so name-based classification and status/retry-after extraction behave\n * as if the error had been thrown on this thread.\n */\nexport function fromWireError(wire: WireError): Error {\n const error = new Error(wire.message, wire.cause ? { cause: fromWireError(wire.cause) } : {});\n error.name = wire.name;\n if (wire.stack !== undefined) {\n error.stack = wire.stack;\n }\n Object.assign(error, wire.props);\n return error;\n}\n","export const BUNDLED_ENCRYPT_WORKER = false;\nexport function createEncryptWorker() {\n throw new Error(\"The encrypt worker is only available in the ESM build.\");\n}\n","import { proxy, transfer, wrap, type Remote } from \"comlink\";\nimport type { EIP1193Provider } from \"viem\";\nimport { EncryptOffloadUnavailableError } from \"../errors/encryption\";\nimport type { FhevmClientOptions } from \"../relayer/types\";\nimport type { LoggerService } from \"../services/logger-service\";\nimport type {\n EncryptOffloadBackend,\n EncryptWorkerApi,\n WireInitPayload,\n WireProgressEvent,\n WireRequestOptions,\n} from \"./protocol\";\nimport { WORKER_READY_MESSAGE, fromWireError, isWireError, toWireError } from \"./protocol\";\nimport { createEncryptWorker } from \"./spawn\";\n\n/**\n * Watchdog deadlines, in milliseconds, for worker lifecycle steps: each is a\n * ceiling on \"the worker never answered\", not on legitimate slow work. Encrypt\n * operations themselves are not watched: nothing bounds local WASM compute, so\n * a proof may run for as long as it needs.\n */\nexport type EncryptWorkerTimeouts = {\n /** Worker startup + module-graph load; a bundler that mishandled the worker URL fails here. */\n readonly spawn: number;\n /** Client init inside the worker realm: chain reads and WASM compilation. */\n readonly init: number;\n};\n\nexport const DEFAULT_ENCRYPT_WORKER_TIMEOUTS: EncryptWorkerTimeouts = {\n spawn: 10_000,\n init: 300_000,\n};\n\n/** Second crash pins the client to the calling thread. */\nconst CRASH_PIN_THRESHOLD = 2;\n\n/** Stable prefix of every degrade warning. */\nexport const ENCRYPT_OFFLOAD_WARN_PREFIX = \"Encrypt offload unavailable\";\n\n/** Workers already returned by an `offloadWorker` factory, to catch a factory that hands out one worker forever. */\nconst handedOutWorkers = new WeakSet<Worker>();\n\n/** Internal signal: the worker infrastructure failed; the operation itself was not rejected. */\nclass WorkerUnavailableError extends Error {\n /** True when a worker that had already signalled ready died under us, so a respawn is worth trying. */\n readonly crashed: boolean;\n\n constructor(message: string, options?: ErrorOptions & { readonly crashed?: boolean }) {\n super(message, options);\n this.name = \"WorkerUnavailableError\";\n this.crashed = options?.crashed ?? false;\n }\n}\n\n/**\n * A payload Comlink could not clone into the worker (`DataCloneError`) or could\n * not return out of it (its own `TypeError`): a boundary failure, so it degrades\n * rather than reaching the caller as an application error.\n */\nfunction isCloneFailure(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) {\n return false;\n }\n const { name, message } = error as { name?: unknown; message?: unknown };\n return (\n name === \"DataCloneError\" ||\n (name === \"TypeError\" &&\n typeof message === \"string\" &&\n message.includes(\"Unserializable return value\"))\n );\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException(\"The operation was aborted.\", \"AbortError\");\n }\n}\n\n/** What the client remembers about worker crashes, dropped whole by a worker answer and by a release. */\ntype CrashHistory = {\n readonly count: number;\n /** The crash that killed the current worker, so a call landing after it degrades as a crash too. */\n readonly last: WorkerUnavailableError | undefined;\n /** Crash count the degrade warning was last emitted for, so one failure warns once. */\n readonly warnedFor: number;\n};\n\nconst NO_CRASHES: CrashHistory = { count: 0, last: undefined, warnedFor: -1 };\n\n/**\n * The key copied for the crossing plus the buffers to transfer, so the wire copy\n * is moved instead of cloned. Anything but the known binary shape crosses\n * unchanged.\n */\nfunction keyForTransfer(key: FhevmClientOptions[\"fheEncryptionKey\"]): {\n readonly key: FhevmClientOptions[\"fheEncryptionKey\"];\n readonly transfers: Transferable[];\n} {\n if (key === undefined) {\n return { key, transfers: [] };\n }\n const publicKeyBytes = key.publicKeyBytes.bytes;\n const crsBytes = key.crsBytes.bytes;\n if (!(publicKeyBytes instanceof Uint8Array) || !(crsBytes instanceof Uint8Array)) {\n return { key, transfers: [] };\n }\n // `slice` yields a fresh exactly-sized buffer, so transferring it leaves this\n // thread's cached key intact.\n const publicKeyCopy = publicKeyBytes.slice();\n const crsCopy = crsBytes.slice();\n return {\n key: {\n ...key,\n publicKeyBytes: { ...key.publicKeyBytes, bytes: publicKeyCopy },\n crsBytes: { ...key.crsBytes, bytes: crsCopy },\n },\n transfers: [publicKeyCopy.buffer as ArrayBuffer, crsCopy.buffer as ArrayBuffer],\n };\n}\n\n/**\n * Per-call options: `signal` is forwarded as an `abort` call, `onProgress` is\n * served from the worker's shared progress channel, and `never` keeps the\n * callback contravariantly compatible with each operation's own event type.\n */\ntype CallOptions = WireRequestOptions & {\n readonly signal?: AbortSignal;\n readonly onProgress?: (args: never) => void;\n};\n\n/**\n * Everything scoped to one spawned worker, created by the init that spawns it\n * and dropped whole by a teardown. A late event carrying its own generation can\n * therefore only settle that generation, never the worker running in its place.\n */\ntype WorkerGeneration = {\n /** Memoized bring-up for this worker; it dies with the generation, so the next call re-runs it. */\n initPromise: Promise<void> | undefined;\n worker: Worker | undefined;\n api: Remote<EncryptWorkerApi> | undefined;\n /** Never resolves; teardown rejects it, and every boundary crossing races it so all of them settle together. */\n readonly doomed: Promise<never>;\n /** Rejects `doomed` with the teardown's `WorkerUnavailableError`. */\n readonly doom: (error: WorkerUnavailableError) => void;\n};\n\nfunction createWorkerGeneration(): WorkerGeneration {\n let doom!: (error: WorkerUnavailableError) => void;\n const doomed = new Promise<never>((_resolve, reject) => {\n doom = reject;\n });\n // An idle teardown dooms a generation with no crossing racing it; this\n // handler keeps that from surfacing as an unhandled rejection.\n doomed.catch(() => {});\n return { initPromise: undefined, worker: undefined, api: undefined, doomed, doom };\n}\n\nexport type EncryptWorkerClientConfig = {\n readonly initPayload: Omit<WireInitPayload, \"rpcUrl\">;\n /** The chain's RPC endpoint: a URL crosses into the worker; a provider is proxied per request. */\n readonly network: EIP1193Provider | string;\n /** Fetches the FHE key on the calling thread, where the chain's auth applies; the worker realm never downloads it itself. */\n readonly prefetchKey: () => Promise<FhevmClientOptions[\"fheEncryptionKey\"]>;\n readonly createInlineClient: () => EncryptOffloadBackend;\n readonly logger: LoggerService;\n readonly timeouts: EncryptWorkerTimeouts;\n /** A string or `URL` is spawned with the SDK's worker options; a factory is called for the worker itself. */\n readonly workerSource?: string | URL | (() => Worker);\n /**\n * A pre-known reason offload cannot work in this session: init degrades with\n * it immediately, so strict rejects at call time rather than at config time.\n */\n readonly blockedReason?: string;\n /**\n * Strict offload (`offloadEncrypt: true`): never run encryption on the\n * calling thread. Every path that would degrade rejects with\n * {@link EncryptOffloadUnavailableError} instead.\n */\n readonly strict: boolean;\n};\n\n/**\n * Encrypt backend that runs `@fhevm/sdk` in a dedicated module worker so proof\n * generation never blocks the main thread. Only infrastructure failure degrades\n * to inline (or rejects under `strict`); worker-reported errors are rethrown,\n * since inline would fail the same way.\n */\nexport class EncryptWorkerClient implements EncryptOffloadBackend {\n readonly #config: EncryptWorkerClientConfig;\n /** Resources of the worker currently being brought up or served; undefined while none runs. */\n #generation: WorkerGeneration | undefined;\n /** True once the client runs inline for the rest of its life, with no further spawn attempts. */\n #pinnedInline = false;\n #crashes: CrashHistory = NO_CRASHES;\n /** Wire ids, allocated across generations so a late reply can never be read as a live operation. */\n #sequence = 0;\n /** Per-operation `onProgress`, keyed by wire id and routed over one channel registered at init: one channel per worker avoids minting a `MessageChannel` per call, whose local port and listener would linger until garbage collection after terminate. */\n readonly #progressListeners = new Map<number, (event: WireProgressEvent) => void>();\n /** Memoized inline backend. Kept, with its key copy, across a worker recovery so a later degrade skips the refetch. */\n #degradePromise: Promise<EncryptOffloadBackend> | undefined;\n /** Operations that must drain before a requested release terminates the worker. */\n #active = 0;\n #releaseRequested = false;\n\n constructor(config: EncryptWorkerClientConfig) {\n this.#config = config;\n }\n\n init = (): Promise<void> => {\n // A call landing mid-drain rides the worker being released rather than\n // canceling the release: the drain still completes, and the call after it\n // spawns a fresh worker.\n const generation = (this.#generation ??= createWorkerGeneration());\n if (generation.initPromise === undefined) {\n // Only a successful cycle is memoized: a failure a retry could clear must\n // not be replayed to every later call.\n const attempt: Promise<void> = this.#withActive(() => this.#initOnce(generation)).catch(\n (error: unknown) => {\n if (generation.initPromise === attempt) {\n generation.initPromise = undefined;\n }\n throw error;\n },\n );\n generation.initPromise = attempt;\n }\n return generation.initPromise;\n };\n\n encryptValue: EncryptOffloadBackend[\"encryptValue\"] = (parameters) =>\n this.#withActive(() =>\n this.#dispatch(\n (backend) => backend.encryptValue(parameters),\n // Spread, so a field upstream adds to the parameters still crosses; the\n // stripped `options` replaces the caller's, which carries `signal`.\n (api, id, options) => api.encryptValue(id, { ...parameters, options }),\n parameters.options,\n ),\n );\n\n encryptValues: EncryptOffloadBackend[\"encryptValues\"] = (parameters) =>\n this.#withActive(() =>\n this.#dispatch(\n (backend) => backend.encryptValues(parameters),\n (api, id, options) => api.encryptValues(id, { ...parameters, options }),\n parameters.options,\n ),\n );\n\n /**\n * Releases the worker without changing what callers observe: in-flight\n * operations (an init included) run to completion over the worker, and the\n * worker is terminated as soon as the last one settles, immediately if the\n * client is idle. The client is not spent: the release resets it whole, so a\n * later call re-fetches the key and spawns a fresh worker exactly like the\n * first one, even if the client had degraded to the calling thread. The drain\n * is not bounded: a worker wedged inside an operation is only terminated once\n * that operation settles.\n */\n dispose(): void {\n this.#releaseRequested = true;\n this.#releaseIfIdle();\n }\n\n /**\n * The one place that decides between the worker and the calling thread:\n * inline once pinned or while no worker is running; otherwise the worker,\n * falling back to inline on infrastructure failure while application errors\n * pass through.\n */\n async #dispatch<T>(\n invoke: (backend: EncryptOffloadBackend) => Promise<T>,\n overWorker: (\n api: Remote<EncryptWorkerApi>,\n id: number,\n options: WireRequestOptions,\n ) => Promise<T>,\n callOptions: CallOptions | undefined,\n ): Promise<T> {\n const { signal, onProgress, ...options } = callOptions ?? {};\n // The worker dequeues an abort only after the proof, so a dispatched call always runs whole.\n throwIfAborted(signal);\n await this.init();\n // A listener added after the abort never fires, so an abort during init needs this recheck.\n throwIfAborted(signal);\n const generation = this.#generation;\n const api = generation?.api;\n // An existing degrade attempt already carries the decision that created it,\n // and its inline backend caches the key, so reuse it rather than degrading again.\n if (this.#degradePromise !== undefined && (this.#pinnedInline || api === undefined)) {\n return invoke(await this.#degradePromise);\n }\n if (generation === undefined || api === undefined) {\n return invoke(\n await this.#degrade(\n generation,\n this.#crashes.last ?? new WorkerUnavailableError(\"Encrypt worker not running.\"),\n ),\n );\n }\n const id = this.#sequence++;\n const onAbort = () => void api.abort(id).catch(() => {});\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (onProgress) {\n this.#progressListeners.set(id, onProgress as (event: WireProgressEvent) => void);\n }\n try {\n const result = await this.#overBoundary(generation, overWorker(api, id, options));\n // A worker operation that answered clears the crash history: two unrelated\n // crashes far apart must not add up to a permanent degrade.\n this.#crashes = NO_CRASHES;\n return result;\n } catch (error) {\n if (error instanceof WorkerUnavailableError) {\n return invoke(await this.#degrade(generation, error));\n }\n throw error;\n } finally {\n this.#progressListeners.delete(id);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n }\n\n async #initOnce(generation: WorkerGeneration): Promise<void> {\n if (this.#pinnedInline) {\n // The degrade that pinned the client already initialized the backend every call now runs on.\n return;\n }\n const blockedReason = this.#config.blockedReason;\n if (blockedReason !== undefined) {\n // Handled before any resource is spent: non-strict callers never get here\n // (the relayer inlines directly), and strict throws out of the degrade.\n await this.#degrade(generation, new WorkerUnavailableError(blockedReason));\n return;\n }\n // Outside the degrade guard: a failed key fetch is an application/network\n // error, and the inline backend would refetch the same key from the same\n // relayer. It rejects out of init exactly as the inline arm's would.\n const fheEncryptionKey = await this.#config.prefetchKey();\n try {\n const api = await this.#spawn(generation);\n const network = this.#config.network;\n const rpcRequest =\n typeof network === \"string\"\n ? null\n : proxy(async (args: { method: string; params?: unknown }) => {\n try {\n return await network.request(args as Parameters<EIP1193Provider[\"request\"]>[0]);\n } catch (error) {\n // Comlink keeps only name/message/stack on a thrown error, which\n // would strip the provider's `code` (4001, -32005) the worker's\n // classifiers read; flatten it so those fields cross.\n throw toWireError(error);\n }\n });\n // A callback that throws would reject the Comlink proxy call back in the\n // worker realm, where nothing can report it, so it is contained here.\n const log = proxy((level: \"debug\" | \"warn\" | \"error\", message: string) => {\n try {\n this.#config.logger[level](message);\n } catch (error) {\n this.#warnCallbackThrew(\"logger\", error);\n }\n });\n const onProgress = proxy((id: number, event: WireProgressEvent) => {\n try {\n this.#progressListeners.get(id)?.(event);\n } catch (error) {\n this.#warnCallbackThrew(\"onProgress\", error);\n }\n });\n // The copy stays on this thread so a later degrade to inline reuses the\n // key instead of refetching; transferring the wire copy avoids a third\n // in-transit copy of it.\n const wireKey = keyForTransfer(fheEncryptionKey);\n await this.#overBoundary(\n generation,\n api.init(\n transfer(\n {\n ...this.#config.initPayload,\n clientOptions: {\n ...this.#config.initPayload.clientOptions,\n fheEncryptionKey: wireKey.key,\n },\n rpcUrl: typeof network === \"string\" ? network : undefined,\n },\n wireKey.transfers,\n ),\n rpcRequest,\n log,\n onProgress,\n ),\n { ms: this.#config.timeouts.init, operation: \"init\" },\n );\n generation.api = api;\n this.#crashes = { ...this.#crashes, last: undefined };\n } catch (error) {\n // Only \"the worker never answered or crashed\" is infrastructure. An error\n // the worker itself reported (a chain read, bad key material) would fail\n // the same way inline, so it reaches the caller unchanged.\n if (!(error instanceof WorkerUnavailableError)) {\n this.#teardown(generation, new WorkerUnavailableError(\"Encrypt worker init failed.\"));\n throw error;\n }\n await this.#degrade(generation, error);\n }\n }\n\n /** Reports a caller callback that threw; the reporting itself must not throw back into the worker. */\n #warnCallbackThrew(callback: string, error: unknown): void {\n const reason = error instanceof Error ? error.message : String(error);\n try {\n this.#config.logger.warn(`Encrypt offload ${callback} callback threw: ${reason}`);\n } catch {\n // A logger that throws on its own warning leaves nowhere left to report.\n }\n }\n\n /**\n * The count spans a whole public entry, its init included, so a release\n * requested mid-call cannot terminate the worker between the init and the\n * operation.\n */\n async #withActive<T>(work: () => Promise<T>): Promise<T> {\n this.#active++;\n try {\n return await work();\n } finally {\n this.#active--;\n this.#releaseIfIdle();\n }\n }\n\n #releaseIfIdle(): void {\n if (!this.#releaseRequested || this.#active > 0) {\n return;\n }\n this.#releaseRequested = false;\n this.#generation?.worker?.terminate();\n // A full reset, so a release is the recovery lever for a degraded client:\n // the next call re-fetches the key and spawns a fresh worker either way.\n this.#generation = undefined;\n this.#degradePromise = undefined;\n this.#pinnedInline = false;\n this.#crashes = NO_CRASHES;\n }\n\n #createWorker(): Worker {\n const source = this.#config.workerSource;\n if (source === undefined) {\n return createEncryptWorker();\n }\n if (typeof source === \"function\") {\n const worker = source();\n // A memoized factory would hand the client a worker it already terminated,\n // so the contract is one fresh Worker per call.\n if (handedOutWorkers.has(worker)) {\n this.#config.logger.warnAlways(\n \"The offloadWorker factory returned a worker it already handed out; each call must construct a fresh Worker.\",\n );\n }\n handedOutWorkers.add(worker);\n return worker;\n }\n return new Worker(source, { type: \"module\", name: \"zama-fhe-encrypt\" });\n }\n\n /** Resolves once the worker's module graph has loaded. */\n async #spawn(generation: WorkerGeneration): Promise<Remote<EncryptWorkerApi>> {\n let worker: Worker;\n try {\n worker = this.#createWorker();\n } catch (error) {\n // A blocked construction is infrastructure, so it must reach the\n // degrade path as such rather than as the raw thrown error.\n throw new WorkerUnavailableError(error instanceof Error ? error.message : String(error), {\n cause: error,\n });\n }\n generation.worker = worker;\n const api = await this.#raceReady(generation, worker);\n this.#armCrashHandler(generation, worker);\n return api;\n }\n\n /** Resolves with the Comlink API on the worker's ready message; rejects on the spawn deadline or a pre-ready error. */\n #raceReady(generation: WorkerGeneration, worker: Worker): Promise<Remote<EncryptWorkerApi>> {\n return new Promise<Remote<EncryptWorkerApi>>((resolve, reject) => {\n const settle = () => {\n clearTimeout(timer);\n worker.removeEventListener(\"message\", onReady);\n worker.removeEventListener(\"error\", onError);\n };\n const timer = setTimeout(() => {\n settle();\n reject(\n new WorkerUnavailableError(\n `Encrypt worker did not start within ${this.#config.timeouts.spawn}ms.`,\n ),\n );\n }, this.#config.timeouts.spawn);\n const onReady = (event: MessageEvent) => {\n if (event.data === WORKER_READY_MESSAGE) {\n settle();\n resolve(wrap<EncryptWorkerApi>(worker));\n }\n };\n const onError = (event: ErrorEvent) => {\n settle();\n const message = event.message || \"Encrypt worker error.\";\n // A worker that never came up is not worth respawning per call, so\n // this failure is not flagged as a crash.\n reject(new WorkerUnavailableError(message));\n this.#teardown(generation, new WorkerUnavailableError(message));\n };\n worker.addEventListener(\"message\", onReady);\n worker.addEventListener(\"error\", onError);\n });\n }\n\n /** Permanent crash detector, armed only after ready so a pre-ready failure never counts as a crash. */\n #armCrashHandler(generation: WorkerGeneration, worker: Worker): void {\n worker.addEventListener(\"error\", (event: ErrorEvent) => {\n // A generation already torn down cannot crash the client again: nothing\n // is waiting on it, and the worker running in its place is unaffected.\n if (this.#generation !== generation) {\n return;\n }\n // A ready worker died under us: the teardown drops the memoized init so\n // the next call spawns a fresh one, and the operations it took down\n // finish inline.\n const crash = new WorkerUnavailableError(event.message || \"Encrypt worker error.\", {\n crashed: true,\n });\n this.#crashes = { ...this.#crashes, count: this.#crashes.count + 1, last: crash };\n this.#teardown(generation, crash);\n });\n }\n\n /**\n * Awaits one promise crossing the worker boundary, racing the generation's\n * `doomed` promise so a teardown settles it with the teardown's\n * `WorkerUnavailableError`, which degrades it inline. Without a `deadline` it\n * settles whenever the worker answers; a `deadline` bounds a lifecycle step,\n * and missing it means the worker is presumed stuck, so the generation is\n * torn down whole.\n */\n async #overBoundary<T>(\n generation: WorkerGeneration,\n work: Promise<T>,\n deadline?: { readonly ms: number; readonly operation: string },\n ): Promise<T> {\n const timer =\n deadline === undefined\n ? undefined\n : setTimeout(() => {\n this.#teardown(\n generation,\n new WorkerUnavailableError(\n `Encrypt worker ${deadline.operation} timed out after ${deadline.ms}ms.`,\n ),\n );\n }, deadline.ms);\n try {\n return await Promise.race([\n work.catch((error: unknown) => {\n const failure = isWireError(error) ? fromWireError(error) : (error as Error);\n // A payload Comlink could not carry is infrastructure, so it degrades\n // instead of reaching the caller as the operation's own failure.\n throw isCloneFailure(failure)\n ? new WorkerUnavailableError(failure.message, { cause: failure })\n : failure;\n }),\n generation.doomed,\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n }\n\n /**\n * Rejects and drops one generation whole: its worker, its memoized init, and\n * every crossing racing its `doomed` promise. The next call therefore re-runs\n * the cycle on a fresh generation, so a spurious teardown costs a respawn\n * rather than a permanent degrade.\n */\n #teardown(generation: WorkerGeneration | undefined, error: WorkerUnavailableError): void {\n if (generation === undefined) {\n return;\n }\n if (this.#generation === generation) {\n this.#generation = undefined;\n }\n generation.worker?.terminate();\n generation.worker = undefined;\n generation.api = undefined;\n generation.initPromise = undefined;\n generation.doom(error);\n }\n\n async #degrade(\n generation: WorkerGeneration | undefined,\n cause: unknown,\n ): Promise<EncryptOffloadBackend> {\n const reason = cause instanceof Error ? cause.message : String(cause);\n if (this.#config.strict) {\n this.#teardown(generation, new WorkerUnavailableError(\"Encrypt worker unavailable.\"));\n throw new EncryptOffloadUnavailableError(\n `Encrypt offload required (offloadEncrypt: true) but unavailable: ${reason}`,\n { cause },\n );\n }\n const { transient, pinning } = this.#classifyDegrade(cause);\n this.#pinnedInline ||= !transient;\n this.#teardown(generation, new WorkerUnavailableError(\"Encrypt worker degraded to inline.\"));\n this.#warnDegraded(reason, transient, pinning);\n if (this.#degradePromise === undefined) {\n // Only a live backend is memoized: an inline init is a key refetch, and a\n // transient failure there must not close the degrade path for the session.\n const attempt: Promise<EncryptOffloadBackend> = (async () => {\n const inline = this.#config.createInlineClient();\n await inline.init();\n return inline;\n })().catch((error: unknown) => {\n if (this.#degradePromise === attempt) {\n this.#degradePromise = undefined;\n }\n this.#config.logger.warnAlways(\n `Encrypt inline fallback failed to initialize: ${error instanceof Error ? error.message : String(error)}`,\n );\n throw error;\n });\n this.#degradePromise = attempt;\n }\n return this.#degradePromise;\n }\n\n /**\n * How one failure degrades, read off the state before the degrade mutates it:\n * `transient` diverts only this call, `pinning` settles the client inline now.\n * One crash is treated as transient; a repeat crash, or a worker that never\n * came up, settles the client inline rather than spawning a replacement per call.\n */\n #classifyDegrade(cause: unknown): { readonly transient: boolean; readonly pinning: boolean } {\n const transient =\n cause instanceof WorkerUnavailableError &&\n cause.crashed &&\n this.#crashes.count < CRASH_PIN_THRESHOLD;\n return { transient, pinning: !transient && !this.#pinnedInline };\n }\n\n /** One warning per failure, whether it pins the client inline or only diverts this call. */\n #warnDegraded(reason: string, transient: boolean, pinning: boolean): void {\n if (!pinning && this.#crashes.warnedFor === this.#crashes.count) {\n return;\n }\n this.#crashes = { ...this.#crashes, warnedFor: this.#crashes.count };\n const scope = transient ? \"in-flight encryption falls back\" : \"encryption falls back\";\n // Always on the console: a silent return to main-thread encryption is the\n // freeze this offload prevents.\n this.#config.logger.warnAlways(\n `${ENCRYPT_OFFLOAD_WARN_PREFIX}, ${scope} to the calling thread: ${reason}`,\n );\n }\n}\n","import { createUnsignedLegacyDecryptionPermitEip712 as createUnsignedLegacyDecryptionPermitEip712Action } from \"@fhevm/sdk/actions/base\";\nimport {\n createFhevmBaseClient,\n createFhevmDecryptClient,\n createFhevmEncryptClient,\n hasFhevmRuntimeConfig,\n} from \"@fhevm/sdk/viem\";\nimport {\n createFhevmCleartextBaseClient,\n createFhevmCleartextDecryptClient,\n createFhevmCleartextEncryptClient,\n} from \"@fhevm/sdk/viem/cleartext\";\nimport { createPublicClient, custom, http } from \"viem\";\nimport { toFhevmChain } from \"../chains/to-fhevm-chain\";\nimport type { FheChain } from \"../chains/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { getAppliedWireRuntime, hasAppliedLocateFile } from \"./applied-runtime\";\nimport type { LoggerService } from \"../services/logger-service\";\nimport { type RelayerTelemetry, telemetryHeaders } from \"../telemetry\";\nimport {\n DEFAULT_ENCRYPT_WORKER_TIMEOUTS,\n EncryptWorkerClient,\n type EncryptWorkerClientConfig,\n type EncryptWorkerTimeouts,\n} from \"../worker/encrypt-worker-client\";\nimport { BUNDLED_ENCRYPT_WORKER } from \"../worker/spawn\";\nimport type {\n FhevmBaseClient,\n FhevmClient,\n FhevmDecryptClient,\n FhevmEncryptBackend,\n FhevmRelayerOptions,\n RelayerRequestOptions,\n RelayerSDK,\n RelayerOptions,\n WireRuntimeConfig,\n} from \"./types\";\n\n/** The `@fhevm/sdk` client inputs the worker realm rebuilds its own client from. */\ntype EncryptInitPayload = EncryptWorkerClientConfig[\"initPayload\"];\n\n/** Construction config for {@link FhevmRelayer}. */\nexport interface FhevmRelayerConfig {\n /** FHE chain configuration. */\n chain: FheChain;\n /**\n * Cleartext mode for local dev/test chains without FHE infrastructure — reads\n * mock cleartexts from the on-chain executor (discovered automatically)\n * instead of calling the relayer.\n */\n cleartext?: boolean;\n /**\n * Per-transport {@link RelayerOptions}: `@fhevm/sdk` client options plus a\n * default request `timeout` applied to every relayer round-trip on the chain.\n */\n options?: RelayerOptions;\n /** Encrypt-worker offload mode; see `web()`'s `offloadEncrypt` option. */\n offloadEncrypt?: \"auto\" | boolean;\n /** Watchdog deadlines for the encrypt worker; `web()` defaults every field before it gets here. */\n offloadTimeouts?: EncryptWorkerTimeouts;\n /** Custom source for the encrypt worker; see `web()`'s `offloadWorker` option. */\n offloadWorker?: string | URL | (() => Worker);\n /** Receives worker log lines and offload-fallback warnings. */\n logger: LoggerService;\n telemetry?: RelayerTelemetry;\n}\n\n/**\n * Single-chain FHE backend that drives `@fhevm/sdk` on the calling thread with\n * capability-scoped lazy initialization.\n * EIP-712 signing is done by the signer layer; this backend builds the typed\n * data and, on decrypt, reassembles the new SDK's signed permit from the\n * interface's params + the previously returned signature.\n *\n * @remarks\n * Each method delegates to the narrowest base, decrypt, or encrypt client,\n * adding two cross-cutting behaviors that the delegated signatures don't\n * express:\n *\n * - **Lazy init.** Each operation initializes only the capability it requires.\n * Public decrypt avoids WASM, private decrypt loads TKMS only, and encryption\n * alone loads TFHE and the FHE encryption key.\n * - **Option merging.** The chain's default options (`auth`, `timeout`, `debug`)\n * are spread in first, then the per-call `options`, so a per-call value always\n * wins over the chain default. Serialization helpers make no relayer\n * round-trip, so they inject no options.\n *\n * @internal\n */\nexport class FhevmRelayer implements RelayerSDK {\n readonly #chain: FheChain;\n readonly #base: FhevmBaseClient;\n readonly #decrypt: FhevmDecryptClient;\n readonly #encrypt: FhevmEncryptBackend;\n readonly #defaultOptions: Partial<FhevmRelayerOptions>;\n readonly #telemetry: RelayerTelemetry | undefined;\n #encryptInitPromise: Promise<void> | undefined;\n\n /**\n * Builds capability-scoped `@fhevm/sdk` clients for the chain and captures\n * the chain's `auth`/`timeout`/`debug` as request defaults. Construction is\n * cheap; each client's one-time init is deferred to its first operation.\n */\n constructor(config: FhevmRelayerConfig) {\n this.#chain = config.chain;\n const { timeout, debug, batchRpcCalls, moduleVersions, fheEncryptionKey } =\n config.options ?? {};\n const auth = this.#chain.auth ? toFhevmAuth(this.#chain.auth) : undefined;\n const transport =\n typeof this.#chain.network === \"string\"\n ? http(this.#chain.network)\n : custom(this.#chain.network);\n const params = {\n publicClient: createPublicClient({ transport }),\n chain: toFhevmChain(this.#chain),\n options: { batchRpcCalls, moduleVersions, fheEncryptionKey },\n };\n this.#defaultOptions = {\n ...(auth !== undefined && { auth }),\n ...(timeout !== undefined && { timeout }),\n ...(debug !== undefined && { debug }),\n };\n this.#telemetry = config.telemetry;\n // The FHE key is always fetched here, on the calling thread, so the chain's\n // default request options (auth in particular) apply; a worker realm has no\n // access to them.\n const prefetchKey = () =>\n this.#base.fetchFheEncryptionKeyBytes({ options: this.#requestOptions(undefined) });\n // Re-listed rather than spread: the upstream client exposes an enumerable\n // `ready` getter, and a spread would call it, starting init at construction.\n const withInlineInit = (client: FhevmEncryptBackend): FhevmEncryptBackend => ({\n init: async () => {\n await prefetchKey();\n await client.init();\n },\n encryptValue: (parameters) => client.encryptValue(parameters),\n encryptValues: (parameters) => client.encryptValues(parameters),\n fetchFheEncryptionKeyBytes: (parameters) => client.fetchFheEncryptionKeyBytes(parameters),\n });\n if (config.cleartext) {\n this.#base = createFhevmCleartextBaseClient(params);\n this.#decrypt = createFhevmCleartextDecryptClient(params);\n this.#encrypt = withInlineInit(createFhevmCleartextEncryptClient(params));\n } else {\n this.#base = createFhevmBaseClient(params);\n this.#decrypt = createFhevmDecryptClient(params);\n this.#encrypt = this.#buildEncryptBackend(config, params, {\n prefetchKey,\n createInlineClient: () => withInlineInit(createFhevmEncryptClient(params)),\n });\n }\n }\n\n /**\n * Picks the encrypt backend for a non-cleartext chain: the worker client when\n * offload is on and reachable, the inline calling-thread client otherwise.\n */\n #buildEncryptBackend(\n config: FhevmRelayerConfig,\n params: { chain: EncryptInitPayload[\"chain\"]; options: EncryptInitPayload[\"clientOptions\"] },\n inline: {\n prefetchKey: EncryptWorkerClientConfig[\"prefetchKey\"];\n createInlineClient: () => FhevmEncryptBackend;\n },\n ): FhevmEncryptBackend {\n const offload = config.offloadEncrypt ?? false;\n const strict = offload === true;\n const workerAvailable =\n typeof Worker === \"function\" &&\n (config.offloadWorker !== undefined || BUNDLED_ENCRYPT_WORKER);\n // Silent both ways: offload off is what the caller asked for, and a realm\n // with no Worker is an environment fact that would warn on every SSR\n // render. Strict skips the capability check, since construction runs during\n // that render and the failure must surface at call time instead.\n if (offload === false || !(strict || workerAvailable)) {\n return inline.createInlineClient();\n }\n const runtime = getAppliedWireRuntime();\n const blocker = encryptOffloadBlocker(runtime);\n if (blocker !== undefined && !strict) {\n // Always on the console: the alternative is an opaque rejection at\n // encrypt time, or WASM assets silently resolved from the default URLs.\n config.logger.warnAlways(`Encryption runs on the calling thread: ${blocker}.`);\n return inline.createInlineClient();\n }\n const workerClient = new EncryptWorkerClient({\n initPayload: { chain: params.chain, clientOptions: params.options, runtime: runtime ?? {} },\n network: this.#chain.network,\n prefetchKey: inline.prefetchKey,\n createInlineClient: inline.createInlineClient,\n logger: config.logger,\n timeouts: config.offloadTimeouts ?? DEFAULT_ENCRYPT_WORKER_TIMEOUTS,\n workerSource: config.offloadWorker,\n // Strict with a blocker: the client degrades at init, which rejects at\n // call time rather than at config time.\n blockedReason: blocker,\n strict,\n });\n return {\n init: () => workerClient.init(),\n encryptValue: (parameters) => workerClient.encryptValue(parameters),\n encryptValues: (parameters) => workerClient.encryptValues(parameters),\n // Served from the calling thread: routing it through the worker would\n // structured-clone the ~50 MB key back out on every call. `ignoreCache`\n // therefore refreshes this thread's cache, not the worker's seeded key.\n fetchFheEncryptionKeyBytes: (parameters) => this.#base.fetchFheEncryptionKeyBytes(parameters),\n dispose: () => workerClient.dispose(),\n };\n }\n\n /** The FHE chain this backend is bound to. */\n get chain() {\n return this.#chain;\n }\n\n // `operation` becomes a header here and must never reach `@fhevm/sdk`.\n #requestOptions<T extends Partial<FhevmRelayerOptions> | undefined>(\n options: T,\n ): Omit<Partial<FhevmRelayerOptions> & NonNullable<T>, \"operation\"> {\n const { operation, ...merged } = {\n ...this.#defaultOptions,\n ...options,\n } as Partial<FhevmRelayerOptions> & NonNullable<T> & RelayerRequestOptions;\n if (this.#telemetry === undefined) {\n return merged;\n }\n return {\n ...merged,\n headers: { ...merged.headers, ...telemetryHeaders(this.#telemetry, operation) },\n };\n }\n\n // Only a fulfilled init is memoized: a rejection clears the memo so the next\n // encryption retries instead of inheriting a transient key-fetch failure.\n #initEncrypt = (): Promise<void> => {\n this.#encryptInitPromise ??= this.#encrypt.init().catch((error: unknown) => {\n this.#encryptInitPromise = undefined;\n throw error;\n });\n return this.#encryptInitPromise;\n };\n\n /**\n * Releases the encrypt worker once in-flight encryptions settle and drops the\n * memoized init; the next encryption spawns a fresh worker and re-initializes.\n */\n dispose = (): void => {\n this.#encryptInitPromise = undefined;\n this.#encrypt.dispose?.();\n };\n\n /**\n * Decrypts a single publicly-decryptable value — one whose contract granted\n * public access, so no permit or key pair is needed — into its typed clear\n * value.\n *\n * @example\n * ```ts\n * const { type, value } = await relayer.decryptPublicValue({\n * encryptedValue: handle, // a bytes32 ciphertext reference\n * });\n * ```\n */\n decryptPublicValue: FhevmClient[\"decryptPublicValue\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.decryptPublicValue({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Batch form of {@link decryptPublicValue}: decrypts many publicly-decryptable\n * values in one relayer round-trip, returning their typed clear values in\n * order.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptPublicValues({\n * encryptedValues: [handleA, handleB],\n * });\n * ```\n */\n decryptPublicValues: FhevmClient[\"decryptPublicValues\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.decryptPublicValues({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Like {@link decryptPublicValues}, but also returns the KMS signature bundle —\n * the handles list, ABI-encoded cleartexts, and decryption proof — needed to\n * verify or replay the result on-chain.\n *\n * @example\n * ```ts\n * const { clearValues, checkSignaturesArgs } =\n * await relayer.decryptPublicValuesWithSignatures({ encryptedValues: [handle] });\n * // checkSignaturesArgs: { handlesList, abiEncodedCleartexts, decryptionProof }\n * ```\n */\n decryptPublicValuesWithSignatures: FhevmClient[\"decryptPublicValuesWithSignatures\"] = async (\n parameters,\n ) => {\n await this.#base.init();\n return this.#base.decryptPublicValuesWithSignatures({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Encrypts one typed input under the chain's FHE key, bound to the contract it\n * targets and the user submitting it, and returns the ciphertext handle plus\n * the input proof the contract verifies on-chain. `type` is the FHE type\n * with the `e` prefix (`\"euint64\"`, `\"ebool\"`, `\"eaddress\"`).\n *\n * @example\n * ```ts\n * const { encryptedValue, inputProof } = await relayer.encryptValue({\n * value: { type: \"euint64\", value: 1000n },\n * contractAddress: \"0xToken…\",\n * userAddress: \"0xUser…\",\n * });\n * ```\n */\n encryptValue: FhevmClient[\"encryptValue\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.encryptValue({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Batch form of {@link encryptValue}: encrypts several inputs for the same\n * contract and user in one call, returning all ciphertext handles under a\n * single shared input proof.\n *\n * @example\n * ```ts\n * const { encryptedValues, inputProof } = await relayer.encryptValues({\n * values: [\n * { type: \"euint64\", value: 1000n },\n * { type: \"ebool\", value: true },\n * ],\n * contractAddress: \"0xToken…\",\n * userAddress: \"0xUser…\",\n * });\n * ```\n */\n encryptValues: FhevmClient[\"encryptValues\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.encryptValues({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * User-decrypts a single access-controlled value: the relayer re-encrypts it\n * to the ephemeral transport key pair, gated by the signed permit, and this\n * returns the typed clear value. Build the key pair with\n * {@link generateTransportKeyPair} and the permit with\n * {@link signDecryptionPermit}.\n *\n * @example\n * ```ts\n * const { type, value } = await relayer.decryptValue({\n * encryptedValue: handle,\n * contractAddress: \"0xToken…\",\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValue: FhevmClient[\"decryptValue\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValue({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Batch form of {@link decryptValue} for values that all belong to the same\n * contract; returns the typed clear values positionally. For values spanning\n * multiple contracts, use {@link decryptValuesFromPairs}.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptValues({\n * encryptedValues: [handleA, handleB],\n * contractAddress: \"0xToken…\",\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValues: FhevmClient[\"decryptValues\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValues({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * User-decrypts values that span multiple contracts: each pair carries its own\n * `contractAddress`, so one permit covering those contracts decrypts them all\n * in a single round-trip. Returns the typed clear values positionally.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptValuesFromPairs({\n * pairs: [\n * { encryptedValue: handleA, contractAddress: \"0xTokenA…\" },\n * { encryptedValue: handleB, contractAddress: \"0xTokenB…\" },\n * ],\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValuesFromPairs: FhevmClient[\"decryptValuesFromPairs\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValuesFromPairs({\n ...parameters,\n options: this.#requestOptions(parameters.options),\n });\n };\n\n /**\n * Fetches the chain's raw FHE public-key bytes — the key encryption uses —\n * served from cache unless `ignoreCache` forces a refetch. Rarely called\n * directly: {@link encryptValue}/{@link encryptValues} fetch the key for you.\n *\n * @example\n * ```ts\n * const keyBytes = await relayer.fetchFheEncryptionKeyBytes();\n * const fresh = await relayer.fetchFheEncryptionKeyBytes({ ignoreCache: true });\n * ```\n */\n fetchFheEncryptionKeyBytes: FhevmClient[\"fetchFheEncryptionKeyBytes\"] = async (parameters) => {\n // Served from the base client, which shares the key cache with the encrypt\n // client: initializing encryption here would spawn the encrypt worker and\n // wait out its bring-up for a key this thread fetches itself.\n await this.#base.init();\n return this.#base.fetchFheEncryptionKeyBytes({\n ...parameters,\n options: this.#requestOptions(parameters?.options),\n });\n };\n\n /**\n * Builds the EIP-712 user-decrypt permit and signs it with the given signer,\n * authorizing the transport key pair to decrypt the listed contracts' values\n * for `durationSeconds` starting at `startTimestamp`. Pass `delegatorAddress`\n * to sign a delegated permit — decrypting values owned by that account instead\n * of the signer's own. Persist the result via\n * {@link serializeSignedDecryptionPermit}.\n *\n * @example\n * ```ts\n * const signedPermit = await relayer.signDecryptionPermit({\n * transportKeyPair,\n * contractAddresses: [\"0xToken…\"],\n * startTimestamp: Math.floor(Date.now() / 1000),\n * durationSeconds: 60 * 60 * 24,\n * signerAddress: \"0xUser…\",\n * signer,\n * // delegatorAddress: \"0xOwner…\", // omit for a self permit\n * });\n * ```\n */\n signDecryptionPermit: FhevmClient[\"signDecryptionPermit\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.signDecryptionPermit(parameters);\n };\n\n /**\n * Builds the unsigned EIP-712 typed data for a V1 decryption permit, without\n * signing it — the signer-less counterpart to {@link signDecryptionPermit}.\n * Hand the result to an out-of-process signer for `eth_signTypedData_v4`,\n * then verify the returned signature via {@link parseSignedDecryptionPermit}.\n *\n * Not on `@fhevm/sdk`'s client decorator, so it's called directly against\n * the base client rather than through a decorated method.\n *\n * @example\n * ```ts\n * const eip712 = await relayer.createUnsignedLegacyDecryptionPermitEip712({\n * transportKeyPair,\n * contractAddresses: [\"0xToken…\"],\n * startTimestamp: Math.floor(Date.now() / 1000),\n * durationSeconds: 60 * 60 * 24,\n * // delegatorAddress: \"0xOwner…\", // omit for a self permit\n * });\n * ```\n */\n createUnsignedLegacyDecryptionPermitEip712: RelayerSDK[\"createUnsignedLegacyDecryptionPermitEip712\"] =\n (parameters) => createUnsignedLegacyDecryptionPermitEip712Action(this.#base, parameters);\n\n // Permit/key-pair helpers carry no request options. Parsing explicitly\n // initializes the capability that validates the restored value; serialization\n // resolves the frozen context internally (via initPublicAction), which reads\n // on-chain state.\n\n /**\n * Serializes a transport key pair to a hex `{ publicKey, privateKey }` pair for\n * storage or transport, so a decryption session can resume without regenerating\n * keys. Reverse of {@link parseTransportKeyPair}.\n *\n * @example\n * ```ts\n * const stored = await relayer.serializeTransportKeyPair({ transportKeyPair });\n * // { publicKey: \"0x…\", privateKey: \"0x…\" }\n * ```\n */\n serializeTransportKeyPair: FhevmClient[\"serializeTransportKeyPair\"] = (parameters) =>\n this.#decrypt.serializeTransportKeyPair(parameters);\n\n /**\n * Serializes a signed permit to a plain, JSON-stringifiable object (version,\n * EIP-712 payload, signature, signer) for caching or transport. Reverse of\n * {@link parseSignedDecryptionPermit}.\n *\n * @example\n * ```ts\n * const serialized = await relayer.serializeSignedDecryptionPermit({ signedPermit });\n * localStorage.setItem(\"permit\", JSON.stringify(serialized));\n * ```\n */\n serializeSignedDecryptionPermit: FhevmClient[\"serializeSignedDecryptionPermit\"] = (parameters) =>\n this.#base.serializeSignedDecryptionPermit(parameters);\n\n /**\n * Rebuilds a transport key pair from its serialized hex\n * `{ publicKey, privateKey }` form. Reverse of {@link serializeTransportKeyPair}.\n *\n * @example\n * ```ts\n * const transportKeyPair = await relayer.parseTransportKeyPair({\n * publicKey: stored.publicKey,\n * privateKey: stored.privateKey,\n * });\n * ```\n */\n parseTransportKeyPair: FhevmClient[\"parseTransportKeyPair\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.parseTransportKeyPair(parameters);\n };\n\n /**\n * Rebuilds a signed permit from its serialized form and validates it: checks\n * the EIP-712 structure, verifies the signature against the on-chain verifier,\n * and confirms the permit's public key matches `transportKeyPair`. Reverse of\n * {@link serializeSignedDecryptionPermit}.\n *\n * @throws if the permit is malformed, expired, or its signature is invalid.\n *\n * @example\n * ```ts\n * const signedPermit = await relayer.parseSignedDecryptionPermit({\n * serializedPermit,\n * transportKeyPair,\n * });\n * ```\n */\n parseSignedDecryptionPermit: FhevmClient[\"parseSignedDecryptionPermit\"] = async (parameters) => {\n await this.#base.init();\n const { serializedPermit } = parameters;\n return this.#base.parseSignedDecryptionPermit({\n ...parameters,\n serializedPermit: {\n ...serializedPermit,\n signature: normalizeSignatureV(serializedPermit.signature),\n },\n });\n };\n\n /**\n * Generates a fresh ephemeral transport key pair for a user-decrypt session.\n * The relayer re-encrypts decrypted values to this pair's public key, so only\n * the holder of the private key can read them; bind it to a permit via\n * {@link signDecryptionPermit}.\n *\n * @example\n * ```ts\n * const transportKeyPair = await relayer.generateTransportKeyPair();\n * ```\n */\n generateTransportKeyPair: FhevmClient[\"generateTransportKeyPair\"] = async () => {\n await this.#decrypt.init();\n return this.#decrypt.generateTransportKeyPair();\n };\n}\n\n/**\n * Rewrites a 65-byte signature's recovery byte from 0/1 to 27/28. The gateway\n * verifies V1 permits on-chain with OpenZeppelin `ECDSA.recover`, which rejects\n * 0/1. Longer signatures (ERC-1271, concatenated) pass through untouched.\n */\nfunction normalizeSignatureV(signature: string): string {\n if (signature.length !== 132) {\n return signature;\n }\n const v = parseInt(signature.slice(130), 16);\n if (v !== 0 && v !== 1) {\n return signature;\n }\n return `${signature.slice(0, 130)}${v === 0 ? \"1b\" : \"1c\"}`;\n}\n\n/**\n * The one reason, if any, this thread's configuration cannot be reproduced in\n * the worker realm, so offload is worse than inline there.\n */\nfunction encryptOffloadBlocker(runtime: WireRuntimeConfig | undefined): string | undefined {\n // A runtime `locateFile` is a function: it cannot be cloned into the worker\n // realm, which would silently resolve WASM assets from the default URLs.\n if (hasAppliedLocateFile()) {\n return \"a runtime locateFile cannot cross the encrypt worker boundary\";\n }\n // Unreadable here, so the worker would run on fhevm defaults: an auth it\n // carries would 401 inside the worker as an application error, which never degrades.\n if (runtime === undefined && hasFhevmRuntimeConfig()) {\n return \"a runtime config set outside createConfig cannot be replicated in the encrypt worker realm\";\n }\n return undefined;\n}\n\n/**\n * Translates the SDK's public {@link FheChain.auth} shape (discriminated by\n * `__type`) into the `type`-discriminated `auth` that `@fhevm/sdk` expects.\n *\n * @throws if the auth discriminator is not one of the supported kinds.\n */\nfunction toFhevmAuth(\n auth: NonNullable<FheChain[\"auth\"]>,\n): NonNullable<FhevmRelayerOptions[\"auth\"]> {\n const type = auth[\"__type\"];\n switch (type) {\n case \"ApiKeyHeader\":\n return { type, value: auth.value, header: auth.header };\n case \"ApiKeyCookie\":\n return { type, value: auth.value, cookie: auth.cookie };\n case \"BearerToken\":\n return { type, token: auth.token };\n default:\n throw new ConfigurationError(`Unknown auth type: ${String(type)}`);\n }\n}\n"],"x_google_ignoreList":[1],"mappings":"qUAYA,SAAgB,EAAa,EAA6B,CACxD,MAAO,CACL,GAAI,EAAM,GACV,MAAO,CACL,UAAW,CACT,IAAK,CAAE,QAAS,EAAM,kBAAmB,EACzC,cAAe,CAAE,QAAS,EAAM,4BAA6B,EAC7D,YAAa,CAAE,QAAS,EAAM,kBAAmB,EACjD,eAAgB,IAAA,EAClB,EACA,WAAY,EAAM,WAClB,QAAS,CACP,GAAI,EAAM,eACV,UAAW,CACT,WAAY,CAAE,QAAS,EAAM,kCAAmC,EAChE,kBAAmB,CAAE,QAAS,EAAM,yCAA0C,CAChF,CACF,CACF,CACF,CACF;;;;;;kBChCC,SAAU,EAAQ,EAAS,CACxB,OAAO,GAAY,UAAmB,IAAW,OAAc,EAAQ,CAAO,EAC9E,OAAO,QAAW,YAAc,OAAO,IAAM,OAAO,CAAC,SAAS,EAAG,CAAO,GACvE,EAAS,OAAO,WAAe,IAAc,WAAa,GAAU,KAAM,EAAQ,EAAO,QAAU,CAAC,CAAC,EAC1G,EAAA,CAAC,GAAS,SAAU,EAAS,CAAE,aAO3B,IAAM,EAAc,OAAO,eAAe,EACpC,EAAiB,OAAO,kBAAkB,EAC1C,EAAe,OAAO,sBAAsB,EAC5C,EAAY,OAAO,mBAAmB,EACtC,EAAc,OAAO,gBAAgB,EACrC,EAAY,GAAS,OAAO,GAAQ,YAAY,GAAiB,OAAO,GAAQ,WAgDhF,EAAmB,IAAI,IAAI,CAC7B,CAAC,QAAS,CA5CV,UAAY,GAAQ,EAAS,CAAG,GAAK,EAAI,GACzC,UAAU,EAAK,CACX,GAAM,CAAE,QAAO,SAAU,IAAI,eAE7B,OADA,EAAO,EAAK,CAAK,EACV,CAAC,EAAO,CAAC,CAAK,CAAC,CAC1B,EACA,YAAY,EAAM,CAEd,OADA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