@zama-fhe/sdk 3.2.0 → 3.3.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/cjs/assertions.cjs +1 -1
  2. package/dist/cjs/assertions.cjs.map +1 -1
  3. package/dist/cjs/base-signer.cjs +1 -1
  4. package/dist/cjs/base-signer.cjs.map +1 -1
  5. package/dist/cjs/ethers/index.cjs +1 -1
  6. package/dist/cjs/index.cjs +1 -1
  7. package/dist/cjs/index.cjs.map +1 -1
  8. package/dist/cjs/query/index.cjs +1 -1
  9. package/dist/cjs/query/index.cjs.map +1 -1
  10. package/dist/cjs/relayer-cleartext.cjs +1 -1
  11. package/dist/cjs/relayer-cleartext.cjs.map +1 -1
  12. package/dist/cjs/relayer-sdk.worker.js +134 -34
  13. package/dist/cjs/relayer.cjs +1 -1
  14. package/dist/cjs/relayer.cjs.map +1 -1
  15. package/dist/cjs/timeout.cjs +2 -0
  16. package/dist/cjs/timeout.cjs.map +1 -0
  17. package/dist/cjs/token.cjs +1 -1
  18. package/dist/cjs/token.cjs.map +1 -1
  19. package/dist/cjs/viem/index.cjs +1 -1
  20. package/dist/cjs/viem/index.cjs.map +1 -1
  21. package/dist/cjs/web/index.cjs +136 -36
  22. package/dist/cjs/web/index.cjs.map +1 -1
  23. package/dist/cjs/wrappers-registry.cjs +1 -1
  24. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  25. package/dist/esm/assertions-zYseN5Xz.js +2 -0
  26. package/dist/esm/assertions-zYseN5Xz.js.map +1 -0
  27. package/dist/esm/{base-signer-ByGw5ReU.d.ts → base-signer-C3Wc5oi9.d.ts} +2 -2
  28. package/dist/esm/base-signer-DjytqPkd.js +2 -0
  29. package/dist/esm/base-signer-DjytqPkd.js.map +1 -0
  30. package/dist/esm/cleartext/index.d.ts +1 -1
  31. package/dist/esm/cleartext/index.js +1 -1
  32. package/dist/esm/{cleartext-DMW5nK1M.d.ts → cleartext-DAkOTlrE.d.ts} +2 -2
  33. package/dist/esm/{cleartext-CTla3A3O.js → cleartext-rTWFctyd.js} +2 -2
  34. package/dist/esm/{cleartext-CTla3A3O.js.map → cleartext-rTWFctyd.js.map} +1 -1
  35. package/dist/esm/{encryption-BGmINekJ.js → encryption-x4Z_Icqk.js} +2 -2
  36. package/dist/esm/{encryption-BGmINekJ.js.map → encryption-x4Z_Icqk.js.map} +1 -1
  37. package/dist/esm/ethers/index.d.ts +4 -4
  38. package/dist/esm/ethers/index.js +1 -1
  39. package/dist/esm/ethers/index.js.map +1 -1
  40. package/dist/esm/{hex-CxtyupeQ.js → hex-A72GrTf9.js} +2 -2
  41. package/dist/esm/{hex-CxtyupeQ.js.map → hex-A72GrTf9.js.map} +1 -1
  42. package/dist/esm/{index-DoVo9J1n.d.ts → index-C1Mtc8Rw.d.ts} +450 -163
  43. package/dist/esm/index.d.ts +17 -13
  44. package/dist/esm/index.js +1 -1
  45. package/dist/esm/index.js.map +1 -1
  46. package/dist/esm/node/index.d.ts +25 -7
  47. package/dist/esm/node/index.js +1 -1
  48. package/dist/esm/node/index.js.map +1 -1
  49. package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
  50. package/dist/esm/node/relayer-sdk.node-worker.js.map +1 -1
  51. package/dist/esm/query/index.d.ts +42 -4
  52. package/dist/esm/query/index.js +1 -1
  53. package/dist/esm/query/index.js.map +1 -1
  54. package/dist/esm/relayer-cleartext-Bp6jtxDd.js +2 -0
  55. package/dist/esm/relayer-cleartext-Bp6jtxDd.js.map +1 -0
  56. package/dist/esm/{relayer-cleartext-DkKKjfI6.d.ts → relayer-cleartext-CSeMlmGO.d.ts} +102 -13
  57. package/dist/esm/relayer-eavK5bfZ.js +2 -0
  58. package/dist/esm/relayer-eavK5bfZ.js.map +1 -0
  59. package/dist/esm/relayer-sdk.worker.js +134 -34
  60. package/dist/esm/timeout-CNVfiaJD.js +2 -0
  61. package/dist/esm/timeout-CNVfiaJD.js.map +1 -0
  62. package/dist/esm/token-Bt33g0zQ.js +2 -0
  63. package/dist/esm/token-Bt33g0zQ.js.map +1 -0
  64. package/dist/esm/{types-BjDu-RZg.d.ts → types-Gn5MeDsr.d.ts} +14 -2
  65. package/dist/esm/{types-Xg_On_yY.d.ts → types-OHIaPwCy.d.ts} +2 -2
  66. package/dist/esm/{types-DiZhtG8i.d.ts → types-piBsdTIP.d.ts} +2 -2
  67. package/dist/esm/{validation-DHZ3JPOn.js → validation-DLszOweh.js} +2 -2
  68. package/dist/esm/{validation-DHZ3JPOn.js.map → validation-DLszOweh.js.map} +1 -1
  69. package/dist/esm/viem/index.d.ts +4 -4
  70. package/dist/esm/viem/index.js +1 -1
  71. package/dist/esm/viem/index.js.map +1 -1
  72. package/dist/esm/web/index.d.ts +2 -2
  73. package/dist/esm/web/index.js +135 -35
  74. package/dist/esm/web/index.js.map +1 -1
  75. package/dist/esm/worker.base-client-BVnT4yJa.js +2 -0
  76. package/dist/esm/worker.base-client-BVnT4yJa.js.map +1 -0
  77. package/dist/esm/{wrappers-registry-BWWG0aze.js → wrappers-registry-C1oK8Bi6.js} +2 -2
  78. package/dist/esm/wrappers-registry-C1oK8Bi6.js.map +1 -0
  79. package/package.json +51 -51
  80. package/dist/esm/assertions-CnPIS0VN.js +0 -2
  81. package/dist/esm/assertions-CnPIS0VN.js.map +0 -1
  82. package/dist/esm/base-signer-BVqcM5jt.js +0 -2
  83. package/dist/esm/base-signer-BVqcM5jt.js.map +0 -1
  84. package/dist/esm/error-W1N-FGwV.js +0 -2
  85. package/dist/esm/error-W1N-FGwV.js.map +0 -1
  86. package/dist/esm/relayer-D-nicEYJ.js +0 -2
  87. package/dist/esm/relayer-D-nicEYJ.js.map +0 -1
  88. package/dist/esm/relayer-cleartext-DGcb5qtE.js +0 -2
  89. package/dist/esm/relayer-cleartext-DGcb5qtE.js.map +0 -1
  90. package/dist/esm/token-TQ-VFHS4.js +0 -2
  91. package/dist/esm/token-TQ-VFHS4.js.map +0 -1
  92. package/dist/esm/worker.base-client-x522sMBy.js +0 -2
  93. package/dist/esm/worker.base-client-x522sMBy.js.map +0 -1
  94. package/dist/esm/wrappers-registry-BWWG0aze.js.map +0 -1
@@ -1,4 +1,121 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../assertions.cjs"),t=require("../validation.cjs");let n=require("viem"),r=require("zod/mini");var i=class{#e=null;async ensureInit(){return this.#e||=this.init().catch(e=>{throw this.#e=null,e}),this.#e}resetInit(){this.#e=null}async getAclAddress(){return this.chain.aclContractAddress}};const a=r.z.object({artifactUrl:r.z.optional(r.z.string()),etag:r.z.optional(r.z.string()),lastModified:r.z.optional(r.z.string()),lastValidatedAt:r.z._default(r.z.optional(r.z.number().check(r.z.nonnegative())),0)}),o=r.z.extend(a,{publicKeyId:r.z.string(),publicKey:r.z.string()}),s=r.z.extend(a,{publicParamsId:r.z.string(),publicParams:r.z.string()}),c=r.z.array(r.z.int().check(r.z.nonnegative())),l=r.z.object({status:r.z.literal(`succeeded`),response:r.z.object({fheKeyInfo:r.z.array(r.z.object({fhePublicKey:r.z.object({urls:r.z.array(r.z.string()).check(r.z.minLength(1))})})).check(r.z.minLength(1)),crs:r.z.record(r.z.string(),r.z.object({urls:r.z.array(r.z.string()).check(r.z.minLength(1))}))})}),u=8192,d=300*1e3;function f(e){let t=[];for(let n=0;n<e.length;n+=u)t.push(String.fromCharCode(...e.subarray(n,n+u)));return btoa(t.join(``))}function p(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function m(e){return`fhe:pubkey:${e}`}function h(e,t){return`fhe:params:${e}:${t}`}function g(e){return`fhe:params-index:${e}`}var _=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger}async fetchFheEncryptionKeyBytes(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(t){let n=m(this.#t),r=await this.#g(n,o,`public key`,`Failed to read public key from persistent storage, falling back to network fetch`);if(r)try{let e={publicKeyId:r.publicKeyId,publicKey:p(r.publicKey)};return this.#a=e,e}catch(t){await this.#y(n,`public key`,{error:e.c(t).message})}let i=await t();if(i===null)return null;this.#a=i;try{let e={publicKeyId:i.publicKeyId,publicKey:f(i.publicKey),lastValidatedAt:Date.now()};await this.#e.set(n,e)}catch(t){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:e.c(t).message})}return i}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(t,n){let r=h(this.#t,t),i=await this.#g(r,s,`params`,`Failed to read public params from persistent storage, falling back to network fetch`,{bits:t});if(i)try{let e={publicParamsId:i.publicParamsId,publicParams:p(i.publicParams)};return this.#o.set(t,e),e}catch(n){await this.#y(r,`params`,{bits:t,error:e.c(n).message})}let a=await n();if(a===null)return null;this.#o.set(t,a);try{let e={publicParamsId:a.publicParamsId,publicParams:f(a.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,e);let n=g(this.#t),i=await this.#v(`Failed to read params index from storage`);i.includes(t)||await this.#e.set(n,[...i,t])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:t,error:e.c(n).message})}return a}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let t=Date.now();if(this.#u!==null&&t-this.#u<this.#r||!this.#n)return!1;let n=m(this.#t),i=null,a=[];try{let[s,c]=await Promise.all([this.#e.get(n),this.#h()]);if(s!=null&&(i=await this.#_(n,s,o,`public key`)),a=c,!i)return!1;if([i,...a.map(e=>e.data)].every(e=>t-e.lastValidatedAt<this.#r))return this.#u=t,!1;let u=await globalThis.fetch(`${this.#n}/keyurl`);if(!u.ok){let e=t-this.#r+d;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:u.status,relayerUrl:this.#n}),await this.#S(n,{...i,lastValidatedAt:e},a.map(t=>({...t,data:{...t.data,lastValidatedAt:e}}))),this.#u=e,!1}let f=l.safeParse(await u.json());if(!f.success){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,error:r.z.prettifyError(f.error)});let e=t-this.#r+d;return await this.#S(n,{...i,lastValidatedAt:e},a.map(t=>({...t,data:{...t.data,lastValidatedAt:e}}))),this.#u=e,!1}let p=f.data.response,m=p.fheKeyInfo[0];e.r(m,`manifest.response.fheKeyInfo[0]`);let h=m.fhePublicKey.urls[0];if(i.artifactUrl&&h&&h!==i.artifactUrl)return await this.#x(n,a),this.#u=null,!0;let g={...i,lastValidatedAt:t};if(h){let e=await this.#m(h,i);if(!e.fresh)return await this.#x(n,a),this.#u=null,!0;g={...g,artifactUrl:h,etag:e.etag,lastModified:e.lastModified}}let _=[];for(let e of a){let r=p.crs[String(e.bits)]?.urls[0];if(e.data.artifactUrl&&r&&r!==e.data.artifactUrl)return await this.#x(n,a),this.#u=null,!0;let i={...e.data,lastValidatedAt:t};if(r){let t=await this.#m(r,e.data);if(!t.fresh)return await this.#x(n,a),this.#u=null,!0;i={...i,artifactUrl:r,etag:t.etag,lastModified:t.lastModified}}_.push({...e,data:i})}return await this.#S(n,g,_),this.#u=t,!1}catch(r){let o=e.c(r),s=r instanceof TypeError||r instanceof ReferenceError||r instanceof RangeError||r instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=t-this.#r+d;try{i&&await this.#S(n,{...i,lastValidatedAt:l},a.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(t){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:e.c(t).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let t=await this.#v(`Failed to read params index, CRS revalidation may be incomplete`),n=new Set([...this.#o.keys(),...t]),r=Array.from(n);return(await Promise.all(r.map(async t=>{let n=h(this.#t,t),r;try{r=await this.#e.get(n)}catch(n){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:t,error:e.c(n).message}),null}if(r==null)return null;let i=await this.#_(n,r,s,`params`,{bits:t});return i?{bits:t,key:n,data:i}:null}))).filter(e=>e!==null)}async#g(t,n,r,i,a={}){let o;try{o=await this.#e.get(t)}catch(t){return this.#i.warn(i,{chainId:this.#t,...a,error:e.c(t).message}),null}return o==null?null:this.#_(t,o,n,r,a)}async#_(e,t,n,i,a={}){let o=r.z.safeParse(n,t);return o.success?o.data:(await this.#y(e,i,{...a,error:r.z.prettifyError(o.error)}),null)}async#v(e){let t=g(this.#t);return await this.#g(t,c,`params index`,e)??[]}async#y(e,t,n={}){await this.#b(e),this.#i.warn(`Corrupt ${t} cache entry detected, deleting`,{chainId:this.#t,...n})}async#b(t){await this.#e.delete(t).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:t,error:e.c(n).message})})}async#x(t,n){let r=g(this.#t);try{await Promise.all([this.#e.delete(t),this.#e.delete(r),...n.map(e=>this.#e.delete(e.key))])}catch(t){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:e.c(t).message})}this.#a=void 0,this.#o.clear()}async#S(t,n,r){let i=[this.#e.set(t,n).catch(t=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:e.c(t).message})}),...r.map(t=>this.#e.set(t.key,t.data).catch(t=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:e.c(t).message})}))];await Promise.all(i)}};async function v(e,t=2){let n;for(let r=0;r<=t;r++)try{return await e()}catch(e){if(n=e,r<t&&y(e)){await b(500*2**r);continue}throw e}throw n}function y(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`timed out`)||t.includes(`timeout`)||t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`network`)||t.includes(`fetch failed`)||t.includes(`socket hang up`)||t.includes(`502`)||t.includes(`503`)||t.includes(`504`)}function b(e){return new Promise(t=>setTimeout(t,e))}var x=class extends i{#e=null;#t=null;#n;constructor(e){super(),this.#n=e}get chain(){return this.#n.chain}async init(){await this.#r.initWorker()}get#r(){return this.#n.worker}#i(){return this.#e||=(this.#t||=this.#n.fheArtifactStorage??new t.n(`FheArtifactCache`,1,`artifacts`),new _({storage:this.#t,chainId:this.chain.id,relayerUrl:this.chain.relayerUrl,ttl:this.#n.fheArtifactCacheTTL,logger:this.#n.logger})),this.#e}terminate(){this.#e=null,this.resetInit()}[Symbol.dispose](){this.terminate()}async#a(){let e=this.#n.security?.getCsrfToken?.()??``;e&&await this.#r.updateCsrf(e)}async generateTransportKeyPair(){await this.ensureInit();let e=this.chain.id,t=await this.#r.generateKeypair({chainId:e});return{publicKey:t.publicKey,privateKey:t.privateKey}}async createEIP712(e,t,n,r=7){await this.ensureInit();let i=this.chain.id;return this.#r.createEIP712({chainId:i,publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r})}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;await this.ensureInit();let a=this.chain.id;return v(async()=>{await this.#a();let e=await this.#r.encrypt({chainId:a,values:t,contractAddress:r,userAddress:i});return{encryptedValues:e.handles.map(e=>(0,n.toHex)(e)),inputProof:(0,n.toHex)(e.inputProof)}})}async userDecrypt(e){await this.ensureInit();let t=this.chain.id;return v(async()=>(await this.#a(),(await this.#r.userDecrypt({chainId:t,...e})).clearValues))}async publicDecrypt(e){await this.ensureInit();let t=this.chain.id;return v(async()=>{await this.#a();let n=await this.#r.publicDecrypt({chainId:t,encryptedValues:e});return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){await this.ensureInit();let a=this.chain.id;return this.#r.createDelegatedUserDecryptEIP712({chainId:a,publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){await this.ensureInit();let t=this.chain.id;return v(async()=>(await this.#a(),(await this.#r.delegatedUserDecrypt({chainId:t,...e})).clearValues))}async requestZKProofVerification(e){await this.ensureInit();let t=this.chain.id;return v(async()=>(await this.#a(),this.#r.requestZKProofVerification({chainId:t,zkProof:e})))}async fetchFheEncryptionKeyBytes(){await this.ensureInit();let e=this.chain.id;return this.#i().fetchFheEncryptionKeyBytes(async()=>(await this.#r.getPublicKey({chainId:e})).result)}async getPublicParams(e){await this.ensureInit();let t=this.chain.id;return this.#i().getPublicParams(e,async()=>(await this.#r.getPublicParams({chainId:t,bits:e})).result)}};const S=3e4;var C=class{#e=null;#t=new Map;#n=null;config;logger;constructor(e,t){this.config=e,this.logger=t}async initWorker(){return this.#e?this.#e:(this.#n||=this.#r().catch(e=>{throw this.#n=null,e}),this.#n)}async#r(){let e=this.createWorker();this.wireEvents(e);try{let{type:t,payload:n}=this.getInitPayload();await this.sendRequestTo(e,t,n,6e4),this.onWorkerReady?.(e),this.#e=e}catch(t){throw this.terminateWorker(e),t}return this.#e}terminate(){if(this.#e){for(let[e,t]of this.#t)clearTimeout(t.timeoutId),t.reject(Error(`Worker terminated`)),this.#t.delete(e);this.terminateWorker(this.#e),this.#e=null}this.#n=null}handleResponse(e){let t=this.#t.get(e.id);if(!t){this.logger.warn(`[WorkerClient] Received response for unknown request`,{id:e.id});return}let n=Math.round(performance.now()-t.startTime);if(clearTimeout(t.timeoutId),this.#t.delete(e.id),e.success)this.logger.debug(`[WorkerClient] ← ${t.type} OK`,{id:e.id,elapsed:n}),t.resolve(e.data);else{this.logger.debug(`[WorkerClient] ← ${t.type} FAILED`,{id:e.id,elapsed:n,error:e.error});let r=Error(e.error);`statusCode`in e&&typeof e.statusCode==`number`&&(r.statusCode=e.statusCode),t.reject(r)}}handleWorkerError(e){this.logger.error(`[WorkerClient] Worker error`,{error:e});let t=this.#e;this.#e=null,this.#i(`Worker error: ${e}`),t&&this.terminateWorker(t)}handleWorkerMessageError(){this.logger.error(`[WorkerClient] Message deserialization failed`);let e=this.#e;this.#e=null,this.#i(`Worker message deserialization failed`),e&&this.terminateWorker(e)}sendRequestTo(e,t,n,r=S){return new Promise((i,a)=>{let o=this.generateRequestId(),s=performance.now();this.logger.debug(`[WorkerClient] → ${t}`,{id:o});let c=setTimeout(()=>{this.#t.delete(o);let e=Math.round(performance.now()-s);this.logger.debug(`[WorkerClient] ${t} timed out after ${r}ms`,{id:o,elapsed:e}),a(Error(`Request ${t} timed out after ${r}ms`))},r);this.#t.set(o,{resolve:i,reject:a,timeoutId:c,startTime:s,type:t});let l={id:o,type:t,payload:n};this.postMessage(e,l)})}async sendRequest(e,t,n=S){let r=await this.initWorker();return this.sendRequestTo(r,e,t,n)}async generateKeypair(e){return this.sendRequest(`GENERATE_KEYPAIR`,e)}async createEIP712(e){return this.sendRequest(`CREATE_EIP712`,e)}async encrypt(e){return this.sendRequest(`ENCRYPT`,e)}async userDecrypt(e){return this.sendRequest(`USER_DECRYPT`,e)}async publicDecrypt(e){return this.sendRequest(`PUBLIC_DECRYPT`,e)}async createDelegatedUserDecryptEIP712(e){return this.sendRequest(`CREATE_DELEGATED_EIP712`,e)}async delegatedUserDecrypt(e){return this.sendRequest(`DELEGATED_USER_DECRYPT`,e)}async requestZKProofVerification(e){return this.sendRequest(`REQUEST_ZK_PROOF_VERIFICATION`,e)}async getPublicKey(e){return this.sendRequest(`GET_PUBLIC_KEY`,e)}async getPublicParams(e){return this.sendRequest(`GET_PUBLIC_PARAMS`,e)}#i(e){for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(Error(e)),this.#t.delete(t)}};function w(t){try{return e.i(t,`runtime`),e.a(t,`id`,`runtime.id`),e.n(t,`getURL`,`runtime.getURL`),!0}catch{return!1}}function T(){let t=globalThis;for(let n of[t.chrome,t.browser])try{if(e.i(n,`ns`),w(n.runtime))return n.runtime}catch{continue}}var E=class extends C{env=`web`;constructor(e){super(e,e.logger)}createWorker(){let e=T();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../timeout.cjs"),t=require("../assertions.cjs"),n=require("../validation.cjs");let r=require("viem"),i=require("zod/mini");var a=class{#e=null;async ensureInit(){return this.#e||=this.init().catch(e=>{throw this.#e=null,e}),this.#e}resetInit(){this.#e=null}async getAclAddress(){return this.chain.aclContractAddress}};const o=i.z.object({artifactUrl:i.z.optional(i.z.string()),etag:i.z.optional(i.z.string()),lastModified:i.z.optional(i.z.string()),lastValidatedAt:i.z._default(i.z.optional(i.z.number().check(i.z.nonnegative())),0)}),s=i.z.extend(o,{publicKeyId:i.z.string(),publicKey:i.z.string()}),c=i.z.extend(o,{publicParamsId:i.z.string(),publicParams:i.z.string()}),l=i.z.array(i.z.int().check(i.z.nonnegative())),u=i.z.object({status:i.z.literal(`succeeded`),response:i.z.object({fheKeyInfo:i.z.array(i.z.object({fhePublicKey:i.z.object({urls:i.z.array(i.z.string()).check(i.z.minLength(1))})})).check(i.z.minLength(1)),crs:i.z.record(i.z.string(),i.z.object({urls:i.z.array(i.z.string()).check(i.z.minLength(1))}))})}),d=8192,f=300*1e3;function p(e){let t=[];for(let n=0;n<e.length;n+=d)t.push(String.fromCharCode(...e.subarray(n,n+d)));return btoa(t.join(``))}function m(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function h(e){return`fhe:pubkey:${e}`}function g(e,t){return`fhe:params:${e}:${t}`}function _(e){return`fhe:params-index:${e}`}var v=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger}async fetchFheEncryptionKeyBytes(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let n=h(this.#t),r=await this.#g(n,s,`public key`,`Failed to read public key from persistent storage, falling back to network fetch`);if(r)try{let e={publicKeyId:r.publicKeyId,publicKey:m(r.publicKey)};return this.#a=e,e}catch(e){await this.#y(n,`public key`,{error:t.h(e).message})}let i=await e();if(i===null)return null;this.#a=i;try{let e={publicKeyId:i.publicKeyId,publicKey:p(i.publicKey),lastValidatedAt:Date.now()};await this.#e.set(n,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:t.h(e).message})}return i}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,n){let r=g(this.#t,e),i=await this.#g(r,c,`params`,`Failed to read public params from persistent storage, falling back to network fetch`,{bits:e});if(i)try{let t={publicParamsId:i.publicParamsId,publicParams:m(i.publicParams)};return this.#o.set(e,t),t}catch(n){await this.#y(r,`params`,{bits:e,error:t.h(n).message})}let a=await n();if(a===null)return null;this.#o.set(e,a);try{let t={publicParamsId:a.publicParamsId,publicParams:p(a.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,t);let n=_(this.#t),i=await this.#v(`Failed to read params index from storage`);i.includes(e)||await this.#e.set(n,[...i,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.h(n).message})}return a}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let n=h(this.#t),r=null,a=[];try{let[o,c]=await Promise.all([this.#e.get(n),this.#h()]);if(o!=null&&(r=await this.#_(n,o,s,`public key`)),a=c,!r)return!1;if([r,...a.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let l=await globalThis.fetch(`${this.#n}/keyurl`);if(!l.ok){let t=e-this.#r+f;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:l.status,relayerUrl:this.#n}),await this.#S(n,{...r,lastValidatedAt:t},a.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let d=u.safeParse(await l.json());if(!d.success){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,error:i.z.prettifyError(d.error)});let t=e-this.#r+f;return await this.#S(n,{...r,lastValidatedAt:t},a.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let p=d.data.response,m=p.fheKeyInfo[0];t.r(m,`manifest.response.fheKeyInfo[0]`);let h=m.fhePublicKey.urls[0];if(r.artifactUrl&&h&&h!==r.artifactUrl)return await this.#x(n,a),this.#u=null,!0;let g={...r,lastValidatedAt:e};if(h){let e=await this.#m(h,r);if(!e.fresh)return await this.#x(n,a),this.#u=null,!0;g={...g,artifactUrl:h,etag:e.etag,lastModified:e.lastModified}}let _=[];for(let t of a){let r=p.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#x(n,a),this.#u=null,!0;let i={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#x(n,a),this.#u=null,!0;i={...i,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}_.push({...t,data:i})}return await this.#S(n,g,_),this.#u=e,!1}catch(i){let o=t.h(i),s=i instanceof TypeError||i instanceof ReferenceError||i instanceof RangeError||i instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+f;try{r&&await this.#S(n,{...r,lastValidatedAt:l},a.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:t.h(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=await this.#v(`Failed to read params index, CRS revalidation may be incomplete`),n=new Set([...this.#o.keys(),...e]),r=Array.from(n);return(await Promise.all(r.map(async e=>{let n=g(this.#t,e),r;try{r=await this.#e.get(n)}catch(n){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:t.h(n).message}),null}if(r==null)return null;let i=await this.#_(n,r,c,`params`,{bits:e});return i?{bits:e,key:n,data:i}:null}))).filter(e=>e!==null)}async#g(e,n,r,i,a={}){let o;try{o=await this.#e.get(e)}catch(e){return this.#i.warn(i,{chainId:this.#t,...a,error:t.h(e).message}),null}return o==null?null:this.#_(e,o,n,r,a)}async#_(e,t,n,r,a={}){let o=i.z.safeParse(n,t);return o.success?o.data:(await this.#y(e,r,{...a,error:i.z.prettifyError(o.error)}),null)}async#v(e){let t=_(this.#t);return await this.#g(t,l,`params index`,e)??[]}async#y(e,t,n={}){await this.#b(e),this.#i.warn(`Corrupt ${t} cache entry detected, deleting`,{chainId:this.#t,...n})}async#b(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.h(n).message})})}async#x(e,n){let r=_(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(r),...n.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:t.h(e).message})}this.#a=void 0,this.#o.clear()}async#S(e,n,r){let i=[this.#e.set(e,n).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:t.h(e).message})}),...r.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:t.h(e).message})}))];await Promise.all(i)}};async function y(e,n=2){let r;for(let i=0;i<=n;i++)try{return await e()}catch(e){if(r=e,i<n&&t.f(e)){await b(500*2**i);continue}throw e}throw r}function b(e){return new Promise(t=>setTimeout(t,e))}var x=class extends a{#e=null;#t=null;#n;constructor(e){super(),this.#n=e}get chain(){return this.#n.chain}async init(){await this.#r.initWorker()}get#r(){return this.#n.worker}#i(){return this.#e||=(this.#t||=this.#n.fheArtifactStorage??new n.n(`FheArtifactCache`,1,`artifacts`),new v({storage:this.#t,chainId:this.chain.id,relayerUrl:this.chain.relayerUrl,ttl:this.#n.fheArtifactCacheTTL,logger:this.#n.logger})),this.#e}terminate(){this.#e=null,this.resetInit()}[Symbol.dispose](){this.terminate()}async#a(){let e=this.#n.security?.getCsrfToken?.()??``;e&&await this.#r.updateCsrf(e)}async generateTransportKeyPair(){await this.ensureInit();let e=this.chain.id,t=await this.#r.generateKeypair({chainId:e});return{publicKey:t.publicKey,privateKey:t.privateKey}}async createEIP712(e,t,n,r=7){await this.ensureInit();let i=this.chain.id;return this.#r.createEIP712({chainId:i,publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r})}async encrypt(e){let{values:t,contractAddress:n,userAddress:i}=e;await this.ensureInit();let a=this.chain.id;return y(async()=>{await this.#a();let e=await this.#r.encrypt({chainId:a,values:t,contractAddress:n,userAddress:i});return{encryptedValues:e.handles.map(e=>(0,r.toHex)(e)),inputProof:(0,r.toHex)(e.inputProof)}})}async userDecrypt(e){await this.ensureInit();let t=this.chain.id;return y(async()=>(await this.#a(),(await this.#r.userDecrypt({chainId:t,...e})).clearValues))}async publicDecrypt(e){await this.ensureInit();let t=this.chain.id;return y(async()=>{await this.#a();let n=await this.#r.publicDecrypt({chainId:t,encryptedValues:e});return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){await this.ensureInit();let a=this.chain.id;return this.#r.createDelegatedUserDecryptEIP712({chainId:a,publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){await this.ensureInit();let t=this.chain.id;return y(async()=>(await this.#a(),(await this.#r.delegatedUserDecrypt({chainId:t,...e})).clearValues))}async requestZKProofVerification(e){await this.ensureInit();let t=this.chain.id;return y(async()=>(await this.#a(),this.#r.requestZKProofVerification({chainId:t,zkProof:e})))}async fetchFheEncryptionKeyBytes(){await this.ensureInit();let e=this.chain.id;return this.#i().fetchFheEncryptionKeyBytes(async()=>(await this.#r.getPublicKey({chainId:e})).result)}async getPublicParams(e){await this.ensureInit();let t=this.chain.id;return this.#i().getPublicParams(e,async()=>(await this.#r.getPublicParams({chainId:t,bits:e})).result)}},S=class{#e=null;#t=new Map;#n=null;config;logger;constructor(e,t){this.config=e,this.logger=t}async initWorker(){return this.#e?this.#e:(this.#n||=this.#r().catch(e=>{throw this.#n=null,e}),this.#n)}async#r(){let e=this.createWorker();this.wireEvents(e);try{let{type:t,payload:n}=this.getInitPayload();await this.sendRequestTo(e,t,n,this.config.initTimeout===void 0?6e4:this.config.initTimeout*1e3),this.onWorkerReady?.(e),this.#e=e}catch(t){throw this.terminateWorker(e),t}return this.#e}terminate(){if(this.#e){for(let[e,t]of this.#t)clearTimeout(t.timeoutId),t.reject(Error(`Worker terminated`)),this.#t.delete(e);this.terminateWorker(this.#e),this.#e=null}this.#n=null}handleResponse(e){let n=this.#t.get(e.id);if(!n){this.logger.warn(`[WorkerClient] Received response for unknown request`,{id:e.id});return}let r=Math.round(performance.now()-n.startTime);if(clearTimeout(n.timeoutId),this.#t.delete(e.id),e.success)this.logger.debug(`[WorkerClient] ← ${n.type} OK`,{id:e.id,elapsed:r}),n.resolve(e.data);else{this.logger.debug(`[WorkerClient] ← ${n.type} FAILED`,{id:e.id,elapsed:r,error:e.error});let i=e.serialized?t.o(e.serialized):Error(e.error);n.reject(i)}}handleWorkerError(e){this.logger.error(`[WorkerClient] Worker error`,{error:e});let t=this.#e;this.#e=null,this.#a(`Worker error: ${e}`),t&&this.terminateWorker(t)}handleWorkerMessageError(){this.logger.error(`[WorkerClient] Message deserialization failed`);let e=this.#e;this.#e=null,this.#a(`Worker message deserialization failed`),e&&this.terminateWorker(e)}sendRequestTo(t,n,r,i=3e4){return new Promise((a,o)=>{let s=this.generateRequestId(),c=performance.now();this.logger.debug(`[WorkerClient] → ${n}`,{id:s});let l=setTimeout(()=>{this.#t.delete(s);let t=Math.round(performance.now()-c);this.logger.debug(`[WorkerClient] ${n} timed out after ${i}ms`,{id:s,elapsed:t}),o(new e.n({operation:n,timeout:i/1e3,elapsed:t/1e3,worker:this.config.workerLabel})),this.config.recycleWorkerOnTimeout!==!1&&this.#i()},i);this.#t.set(s,{resolve:a,reject:o,timeoutId:l,startTime:c,type:n});let u={id:s,type:n,payload:r};this.postMessage(t,u)})}async sendRequest(e,t,n){let r=await this.initWorker();return this.sendRequestTo(r,e,t,n??(this.config.operationTimeout===void 0?3e4:this.config.operationTimeout*1e3))}#i(){let t=this.#e;if(t){this.#e=null,this.#n=null;for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(new e.t({operation:n.type,worker:this.config.workerLabel})),this.#t.delete(t);this.logger.warn(`[WorkerClient] recycled worker after a timeout`,{worker:this.config.workerLabel}),this.terminateWorker(t)}}async generateKeypair(e){return this.sendRequest(`GENERATE_KEYPAIR`,e)}async createEIP712(e){return this.sendRequest(`CREATE_EIP712`,e)}async encrypt(e){return this.sendRequest(`ENCRYPT`,e)}async userDecrypt(e){return this.sendRequest(`USER_DECRYPT`,e)}async publicDecrypt(e){return this.sendRequest(`PUBLIC_DECRYPT`,e)}async createDelegatedUserDecryptEIP712(e){return this.sendRequest(`CREATE_DELEGATED_EIP712`,e)}async delegatedUserDecrypt(e){return this.sendRequest(`DELEGATED_USER_DECRYPT`,e)}async requestZKProofVerification(e){return this.sendRequest(`REQUEST_ZK_PROOF_VERIFICATION`,e)}async getPublicKey(e){return this.sendRequest(`GET_PUBLIC_KEY`,e)}async getPublicParams(e){return this.sendRequest(`GET_PUBLIC_PARAMS`,e)}#a(e){for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(Error(e)),this.#t.delete(t)}};function C(e){try{return t.i(e,`runtime`),t.a(e,`id`,`runtime.id`),t.n(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function w(){let e=globalThis;for(let n of[e.chrome,e.browser])try{if(t.i(n,`ns`),C(n.runtime))return n.runtime}catch{continue}}var T=class extends S{env=`web`;constructor(e){super({workerLabel:`web-worker`,...e,recycleWorkerOnTimeout:!1},e.logger)}createWorker(){let e=w();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
2
+ //#region src/utils/error.ts
3
+ /** Coerce an unknown caught value to an Error instance. */
4
+ function toError(error) {
5
+ if (error instanceof Error) return error;
6
+ if (typeof error === "object" && error !== null && "message" in error) return new Error(String(error.message));
7
+ return new Error(String(error));
8
+ }
9
+ /** Properties that may nest a lower-level cause across viem / ethers / fetch. */
10
+ const NESTED_ERROR_KEYS = [
11
+ "cause",
12
+ "error",
13
+ "info"
14
+ ];
15
+ /**
16
+ * ethers reports its HTTP status only as a string on \`info.responseStatus\`
17
+ * (e.g. \`"429 Too Many Requests"\`). Read it directly off the node — not via the
18
+ * cause-chain flattening, which descends a single branch — so it survives even
19
+ * when the error also carries an \`error\` link that would be walked first.
20
+ */
21
+ function responseStatusFromNode(node) {
22
+ const info = node.info;
23
+ if (info !== null && typeof info === "object") {
24
+ const responseStatus = info.responseStatus;
25
+ if (typeof responseStatus === "string") return responseStatus;
26
+ }
27
+ }
28
+ /**
29
+ * Copy the scalar signal fields the classifier keys on from a raw error node
30
+ * onto the envelope, only where not already set — so a shallower node keeps
31
+ * priority. Also lifts ethers' string \`info.responseStatus\` and the relayer's
32
+ * \`Retry-After\` header (both destroyed by structured clone: the header lives on
33
+ * a non-cloneable \`Headers\`, the status on a nested \`info\` the flattening skips).
34
+ */
35
+ function captureNodeSignals(node, into) {
36
+ if (into.code === void 0 && (typeof node.code === "string" || typeof node.code === "number")) into.code = node.code;
37
+ if (into.status === void 0 && typeof node.status === "number") into.status = node.status;
38
+ if (into.statusCode === void 0 && typeof node.statusCode === "number") into.statusCode = node.statusCode;
39
+ if (into.responseStatus === void 0) {
40
+ const responseStatus = responseStatusFromNode(node);
41
+ if (responseStatus !== void 0) into.responseStatus = responseStatus;
42
+ }
43
+ if (into.retryAfter === void 0) if (typeof node.retryAfter === "number") into.retryAfter = node.retryAfter;
44
+ else {
45
+ const fromHeader = retryAfterFromHeader(node);
46
+ if (fromHeader !== void 0) into.retryAfter = fromHeader;
47
+ }
48
+ }
49
+ /** Lift any still-missing scalar signal from an already-serialized child up. */
50
+ function hoistMissingSignals(from, into) {
51
+ if (into.code === void 0 && from.code !== void 0) into.code = from.code;
52
+ if (into.status === void 0 && from.status !== void 0) into.status = from.status;
53
+ if (into.statusCode === void 0 && from.statusCode !== void 0) into.statusCode = from.statusCode;
54
+ if (into.responseStatus === void 0 && from.responseStatus !== void 0) into.responseStatus = from.responseStatus;
55
+ if (into.retryAfter === void 0 && from.retryAfter !== void 0) into.retryAfter = from.retryAfter;
56
+ }
57
+ /**
58
+ * Flatten an error (and its \`cause\` / \`error\` / \`info\` chain) into a
59
+ * structured-clone-safe {@link SerializedError}. Depth-bounded to mirror
60
+ * {@link findInErrorChain} and guard against cyclic structures.
61
+ */
62
+ function serializeError(error, depth = 6) {
63
+ const coerced = toError(error);
64
+ const node = typeof error === "object" && error !== null ? error : coerced;
65
+ const serialized = {
66
+ name: coerced.name,
67
+ message: coerced.message
68
+ };
69
+ captureNodeSignals(node, serialized);
70
+ if (depth > 0) for (const key of NESTED_ERROR_KEYS) {
71
+ const next = node[key];
72
+ if (next !== void 0 && next !== null && typeof next === "object") {
73
+ const child = serializeError(next, depth - 1);
74
+ if (serialized.cause === void 0) serialized.cause = child;
75
+ hoistMissingSignals(child, serialized);
76
+ }
77
+ }
78
+ return serialized;
79
+ }
80
+ /**
81
+ * Parse an HTTP \`Retry-After\` header value into **seconds** (the SDK's duration
82
+ * unit and the header's own unit), or \`undefined\` when absent/unparseable. Per
83
+ * RFC 9110 the value is either a non-negative number of seconds (\`"120"\`) or an
84
+ * HTTP-date; a past date floors to \`0\`.
85
+ */
86
+ function parseRetryAfterHeader(value) {
87
+ if (value === null || value === void 0) return;
88
+ const trimmed = value.trim();
89
+ if (trimmed === "") return;
90
+ if (/^\\d+$/.test(trimmed)) return Number(trimmed);
91
+ if (/[a-zA-Z]/.test(trimmed)) {
92
+ const dateMs = Date.parse(trimmed);
93
+ if (!Number.isNaN(dateMs)) return Math.max(0, Math.round((dateMs - Date.now()) / 1e3));
94
+ }
95
+ }
96
+ /** Read a \`Retry-After\` header (→ seconds) off a \`Headers\`-like object, if present. */
97
+ function readRetryAfterHeader(headers) {
98
+ if (headers === null || typeof headers !== "object") return;
99
+ const get = headers.get;
100
+ if (typeof get !== "function") return;
101
+ return parseRetryAfterHeader(get.call(headers, "Retry-After"));
102
+ }
103
+ /**
104
+ * A node's **relayer** \`Retry-After\` header (seconds), read from a wrapped fetch
105
+ * \`Response\` (the relayer SDK's \`cause.response.headers\`). The SDK owns the
106
+ * relayer fetch, so parsing the header there is legitimate.
107
+ *
108
+ * The viem/chain side (\`HttpRequestError.headers\`) is deliberately **not** read:
109
+ * for consumer RPC the integrator's viem/ethers transport already honors
110
+ * \`Retry-After\` in its own retry loop (and retries) before the error ever
111
+ * surfaces, so re-reading it here would re-implement a transport concern.
112
+ * Chain-RPC backoff is configured on the consumer's transport (\`chain.network\`).
113
+ */
114
+ function retryAfterFromHeader(node) {
115
+ const response = node.response;
116
+ if (response !== null && typeof response === "object") return readRetryAfterHeader(response.headers);
117
+ }
118
+ //#endregion
2
119
  //#region src/utils/assertions.ts
3
120
  function assertObject(value, context) {
4
121
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(\`\${context} must be an object, got \${typeof value}\`);
@@ -130,15 +247,14 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
130
247
  /**
131
248
  * Send an error response back to the main thread.
132
249
  */
133
- function sendError(id, type, error, statusCode) {
134
- const response = {
250
+ function sendError(id, type, error) {
251
+ self.postMessage({
135
252
  id,
136
253
  type,
137
254
  success: false,
138
- error
139
- };
140
- if (statusCode !== void 0) response.statusCode = statusCode;
141
- self.postMessage(response);
255
+ error: error instanceof Error ? error.message : String(error),
256
+ serialized: serializeError(error)
257
+ });
142
258
  }
143
259
  const originalFetch = fetch;
144
260
  /** Allowed CDN hostnames for loading the relayer SDK script. */
@@ -240,7 +356,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
240
356
  for (const chain of payload.chains) configs.set(chain.id, chain);
241
357
  sendSuccess(id, type, { initialized: true });
242
358
  } catch (error) {
243
- sendError(id, type, error instanceof Error ? error.message : String(error));
359
+ sendError(id, type, error);
244
360
  }
245
361
  }
246
362
  /** Coerce a boolean to bigint for numeric FHE types. */
@@ -295,7 +411,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
295
411
  inputProof: encrypted.inputProof
296
412
  }, [encrypted.inputProof.buffer, ...encrypted.handles.map((h) => h.buffer)]);
297
413
  } catch (error) {
298
- sendError(id, type, error instanceof Error ? error.message : String(error), extractHttpStatus(error));
414
+ sendError(id, type, error);
299
415
  }
300
416
  }
301
417
  /**
@@ -311,22 +427,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
311
427
  }));
312
428
  sendSuccess(id, type, { clearValues: await instance.userDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.signerAddress, payload.startTimestamp, payload.durationDays) });
313
429
  } catch (error) {
314
- sendError(id, type, error instanceof Error ? error.message : String(error), extractHttpStatus(error));
315
- }
316
- }
317
- /**
318
- * Extract an HTTP status code from an error, if present.
319
- * Relayer SDK errors may carry a \`status\` or \`statusCode\` property.
320
- */
321
- function extractHttpStatus(error) {
322
- if (error === null || error === void 0 || typeof error !== "object") return;
323
- const e = error;
324
- if (typeof e.statusCode === "number") return e.statusCode;
325
- if (typeof e.status === "number") return e.status;
326
- if (e.cause !== null && e.cause !== void 0 && typeof e.cause === "object") {
327
- const cause = e.cause;
328
- if (typeof cause.statusCode === "number") return cause.statusCode;
329
- if (typeof cause.status === "number") return cause.status;
430
+ sendError(id, type, error);
330
431
  }
331
432
  }
332
433
  /**
@@ -337,7 +438,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
337
438
  try {
338
439
  sendSuccess(id, type, { ...await (await getInstance(payload.chainId)).publicDecrypt(payload.encryptedValues) });
339
440
  } catch (error) {
340
- sendError(id, type, error instanceof Error ? error.message : String(error), extractHttpStatus(error));
441
+ sendError(id, type, error);
341
442
  }
342
443
  }
343
444
  /**
@@ -352,7 +453,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
352
453
  privateKey: prefixHex(keypair.privateKey)
353
454
  });
354
455
  } catch (error) {
355
- sendError(id, type, error instanceof Error ? error.message : String(error));
456
+ sendError(id, type, error);
356
457
  }
357
458
  }
358
459
  /**
@@ -363,7 +464,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
363
464
  try {
364
465
  sendSuccess(id, type, (await getInstance(payload.chainId)).createEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.startTimestamp, payload.durationDays));
365
466
  } catch (error) {
366
- sendError(id, type, error instanceof Error ? error.message : String(error));
467
+ sendError(id, type, error);
367
468
  }
368
469
  }
369
470
  /**
@@ -374,7 +475,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
374
475
  try {
375
476
  sendSuccess(id, type, (await getInstance(payload.chainId)).createDelegatedUserDecryptEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.delegatorAddress, payload.startTimestamp, payload.durationDays));
376
477
  } catch (error) {
377
- sendError(id, type, error instanceof Error ? error.message : String(error));
478
+ sendError(id, type, error);
378
479
  }
379
480
  }
380
481
  /**
@@ -390,7 +491,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
390
491
  }));
391
492
  sendSuccess(id, type, { clearValues: await instance.delegatedUserDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.delegatorAddress, payload.delegateAddress, payload.startTimestamp, payload.durationDays) });
392
493
  } catch (error) {
393
- sendError(id, type, error instanceof Error ? error.message : String(error), extractHttpStatus(error));
494
+ sendError(id, type, error);
394
495
  }
395
496
  }
396
497
  /**
@@ -402,7 +503,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
402
503
  const result = await (await getInstance(payload.chainId)).requestZKProofVerification(payload.zkProof);
403
504
  sendSuccess(id, type, result, [result.inputProof.buffer, ...result.handles.map((h) => h.buffer)]);
404
505
  } catch (error) {
405
- sendError(id, type, error instanceof Error ? error.message : String(error), extractHttpStatus(error));
506
+ sendError(id, type, error);
406
507
  }
407
508
  }
408
509
  /**
@@ -413,7 +514,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
413
514
  try {
414
515
  sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicKey() });
415
516
  } catch (error) {
416
- sendError(id, type, error instanceof Error ? error.message : String(error), extractHttpStatus(error));
517
+ sendError(id, type, error);
417
518
  }
418
519
  }
419
520
  /**
@@ -424,7 +525,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
424
525
  try {
425
526
  sendSuccess(id, type, { result: (await getInstance(payload.chainId)).getPublicParams(payload.bits) });
426
527
  } catch (error) {
427
- sendError(id, type, error instanceof Error ? error.message : String(error), extractHttpStatus(error));
528
+ sendError(id, type, error);
428
529
  }
429
530
  }
430
531
  /**
@@ -481,11 +582,10 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
481
582
  default: throw new Error(\`Unknown request type: \${request.type}\`);
482
583
  }
483
584
  } catch (error) {
484
- const message = error instanceof Error ? error.message : String(error);
485
- sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", message);
585
+ sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", error);
486
586
  }
487
587
  };
488
588
  //#endregion
489
589
  })();
490
- `],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{env:`web`,cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};const D=r.z.object({threads:r.z.optional(r.z.int().check(r.z.positive())),fheArtifactCacheTTL:r.z.optional(r.z.int().check(r.z.nonnegative()))});function O(e){return e!==void 0&&t.t(D,e),{type:`web`,createWorker:(t,n)=>new E({cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.4/relayer-sdk-js.umd.cjs`,chains:t,csrfToken:e?.security?.getCsrfToken?.()??``,integrity:e?.security?.integrityCheck===!1?void 0:`a50426aae8440e802102c8674dd8451f34fe79352d5e2cc6b89d9f1aa340296176c2ee33d9aa4657752f8ca96f74f921`,logger:n,thread:e?.threads}),createRelayer:(t,n,r)=>new x({chain:t,worker:n,...e,logger:r})}}exports.RelayerWeb=x,exports.web=O;
590
+ `],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{env:`web`,cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};const E=i.z.object({threads:i.z.optional(i.z.int().check(i.z.positive())),fheArtifactCacheTTL:i.z.optional(i.z.int().check(i.z.nonnegative()))});function D(e){return e!==void 0&&n.t(E,e),{type:`web`,createWorker:(t,n)=>new T({cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.4/relayer-sdk-js.umd.cjs`,chains:t,csrfToken:e?.security?.getCsrfToken?.()??``,integrity:e?.security?.integrityCheck===!1?void 0:`a50426aae8440e802102c8674dd8451f34fe79352d5e2cc6b89d9f1aa340296176c2ee33d9aa4657752f8ca96f74f921`,logger:n,thread:e?.threads}),createRelayer:(t,n,r)=>new x({chain:t,worker:n,...e,logger:r})}}exports.RelayerWeb=x,exports.web=D;
491
591
  //# sourceMappingURL=index.cjs.map