@zama-fhe/sdk 2.3.1-alpha.2 → 2.3.1-alpha.4

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.
@@ -511,5 +511,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
511
511
  };
512
512
  //#endregion
513
513
  })();
514
- `],{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,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};const S=8192,C=300*1e3;function w(e){let t=[];for(let n=0;n<e.length;n+=S)t.push(String.fromCharCode(...e.subarray(n,n+S)));return btoa(t.join(``))}function T(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 E(e){return`fhe:pubkey:${e}`}function D(e,t){return`fhe:params:${e}:${t}`}function O(e){return`fhe:params-index:${e}`}function k(e){t.Q(e,`CachedPublicKey`),t.$(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),t.$(e,`publicKey`,`CachedPublicKey.publicKey`)}function A(e){t.Q(e,`CachedPublicParams`),t.$(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),t.$(e,`publicParams`,`CachedPublicParams.publicParams`)}var j=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??console}async getPublicKey(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=E(this.#t);try{let e=await this.#e.get(n);if(e){k(e);let t={publicKeyId:e.publicKeyId,publicKey:T(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(n),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:t.Y(e).message})}let r=await e();if(r===null)return null;this.#a=r;try{let e={publicKeyId:r.publicKeyId,publicKey:w(r.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.Y(e).message})}return r}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=D(this.#t,e);try{let t=await this.#e.get(r);if(t){A(t);let n={publicParamsId:t.publicParamsId,publicParams:T(t.publicParams)};return this.#o.set(e,n),n}}catch(n){await this.#g(r),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:t.Y(n).message})}let i=await n();if(i===null)return null;this.#o.set(e,i);try{let n={publicParamsId:i.publicParamsId,publicParams:w(i.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,n);let a=O(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:t.Y(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.Y(n).message})}return i}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=E(this.#t),r=null,i=[];try{let[a,o]=await Promise.all([this.#e.get(n),this.#h()]);if(a)try{k(a),r={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:t.Y(e).message}),await this.#g(n)}if(i=o,!r)return!1;if([r,...i.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let t=e-this.#r+C;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let c=await s.json();if(!c||typeof c!=`object`||!(`fhePublicKey`in c)||!c.fhePublicKey?.urls?.length||!(`crs`in c)||typeof c.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let t=e-this.#r+C;return await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let l=c,u=l.fhePublicKey.urls[0];if(r.artifactUrl&&u&&u!==r.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let d={...r,lastValidatedAt:e};if(u){let e=await this.#m(u,r);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;d={...d,artifactUrl:u,etag:e.etag,lastModified:e.lastModified}}let f=[];for(let t of i){let r=l.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let a={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;a={...a,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}f.push({...t,data:a})}return await this.#v(n,d,f),this.#u=e,!1}catch(a){let o=t.Y(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a 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+C;try{r&&await this.#v(n,{...r,lastValidatedAt:l},i.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.Y(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=O(this.#t),n=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:t.Y(e).message}),null))??[],r=new Set([...this.#o.keys(),...n]),i=Array.from(r);return(await Promise.all(i.map(async e=>{let n=D(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.Y(n).message}),null}if(!r)return null;try{return A(r),{bits:e,key:n,data:{...r,lastValidatedAt:r.lastValidatedAt??0}}}catch(r){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:t.Y(r).message}),await this.#g(n),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.Y(n).message})})}async#_(e,n){let r=O(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.Y(e).message})}this.#a=void 0,this.#o.clear()}async#v(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.Y(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.Y(e).message})}))];await Promise.all(i)}},M=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:r,threads:i}=this.#l;if(i!==void 0&&(!Number.isInteger(i)||i<1))throw Error(`Invalid thread count: ${i}. Must be a positive integer.`);return i!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},n.i[e],t[e]),csrfToken:r?.getCsrfToken?.()??``,integrity:r?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:i}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let t=await this.#l.getChainId();if(this.#i!==null&&t!==this.#i&&this.#p(),this.#i=t,this.#o||=this.#l.fheArtifactStorage??new h(`FheArtifactCache`,1,`artifacts`),!this.#a){let e=Object.assign({},n.i[t],this.#l.transports[t]);this.#a=new j({storage:this.#o,chainId:t,relayerUrl:e.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(t=>{this.#t=null;let n=t instanceof e.a?t:new e.t(`Failed to initialize FHE worker`,{cause:t});throw this.#u(`error`,n),n})),this.#t}async#h(){let e=new x(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,r,i=7){let a=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:r,durationDays:i}),o={name:a.domain.name,version:a.domain.version,chainId:a.domain.chainId,verifyingContract:a.domain.verifyingContract};return{domain:o,types:{EIP712Domain:n.c(o),UserDecryptRequestVerification:a.types.UserDecryptRequestVerification},message:{publicKey:a.message.publicKey,contractAddresses:a.message.contractAddresses,startTimestamp:a.message.startTimestamp,durationDays:a.message.durationDays,extraData:a.message.extraData}}}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;return n.l(async()=>{let e=await this.#f();await this.#g();let n=await e.encrypt({values:t,contractAddress:r,userAddress:i});return{handles:n.handles,inputProof:n.inputProof}})}async userDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return n.l(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let t=await this.#l.getChainId(),r=Object.assign({},n.i[t],this.#l.transports[t]);if(!r.aclContractAddress)throw new e.t(`No ACL address configured for chain ${t}`);return r.aclContractAddress}},N=class n extends t.w{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?(0,a.getAddress)(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(r.m(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(n,i,o){let{skipBalanceCheck:c=!1,onEncryptComplete:l,onTransferSubmitted:u}=o??{},d=(0,a.getAddress)(n);c||await this.#i(i);let f,p,m=Date.now();try{this.emit({type:t.k.EncryptStart}),{handles:f,inputProof:p}=await this.relayer.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:t.k.EncryptEnd,durationMs:Date.now()-m}),P(()=>l?.())}catch(n){throw this.emit({type:t.k.EncryptError,error:t.Y(n),durationMs:Date.now()-m}),n instanceof e.a?n:new e.i(`Failed to encrypt transfer amount`,{cause:n})}if(f.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.y(this.address,d,f[0],p));return this.emit({type:t.k.TransferSubmitted,txHash:e}),P(()=>u?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`transfer`,error:t.Y(n)}),n instanceof e.a?n:new s(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(n,i,o,c){let l=(0,a.getAddress)(n),u=(0,a.getAddress)(i),d,f,p=Date.now();try{this.emit({type:t.k.EncryptStart}),{handles:d,inputProof:f}=await this.relayer.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:l}),this.emit({type:t.k.EncryptEnd,durationMs:Date.now()-p}),P(()=>c?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.k.EncryptError,error:t.Y(n),durationMs:Date.now()-p}),n instanceof e.a?n:new e.i(`Failed to encrypt transferFrom amount`,{cause:n})}if(d.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.b(this.address,l,u,d[0],f));return this.emit({type:t.k.TransferFromSubmitted,txHash:e}),P(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`transferFrom`,error:t.Y(n)}),n instanceof e.a?n:new s(`TransferFrom transaction failed`,{cause:n})}}async approve(n,i){let s=(0,a.getAddress)(n);try{let e=await this.signer.writeContract(r.E(this.address,s,i));return this.emit({type:t.k.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`approve`,error:t.Y(n)}),n instanceof e.a?n:new o(`Operator approval failed`,{cause:n})}}async isApproved(e,t){let n=(0,a.getAddress)(e),i=t?(0,a.getAddress)(t):await this.signer.getAddress();return this.signer.readContract(r.C(this.address,i,n))}async shield(i,o){let c=await this.#n();if(c===n.ZERO_ADDRESS)return this.shieldETH(i,i+(o?.fees??0n));let u;try{let e=await this.signer.getAddress();u=await this.signer.readContract(t.U(c,e))}catch(n){throw n instanceof e.a?n:new d(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:t.Y(n)})}if(u<i)throw new l(`Insufficient ERC-20 balance: requested ${i}, available ${u} (token: ${c})`,{requested:i,available:u,token:c});let f=o?.approvalStrategy??`exact`;f!==`skip`&&await this.#o(i,f===`max`,o);try{let e=o?.to?(0,a.getAddress)(o.to):await this.signer.getAddress(),n=await this.signer.writeContract(r.h(this.wrapper,e,i));return this.emit({type:t.k.ShieldSubmitted,txHash:n}),P(()=>o?.onShieldSubmitted?.(n)),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`shield`,error:t.Y(n)}),n instanceof e.a?n:new s(`Shield transaction failed`,{cause:n})}}async shieldETH(n,i){try{let e=await this.signer.getAddress(),a=await this.signer.writeContract(r.g(this.wrapper,e,n,i??n));return this.emit({type:t.k.ShieldSubmitted,txHash:a}),{txHash:a,receipt:await this.signer.waitForTransactionReceipt(a)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`shieldETH`,error:t.Y(n)}),n instanceof e.a?n:new s(`Shield ETH transaction failed`,{cause:n})}}async unwrap(n){let i=await this.signer.getAddress(),a,o,c=Date.now();try{this.emit({type:t.k.EncryptStart}),{handles:a,inputProof:o}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.wrapper,userAddress:i}),this.emit({type:t.k.EncryptEnd,durationMs:Date.now()-c})}catch(n){throw this.emit({type:t.k.EncryptError,error:t.Y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.i(`Failed to encrypt unshield amount`,{cause:n})}if(a.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.O(this.address,i,i,a[0],o));return this.emit({type:t.k.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`unwrap`,error:t.Y(n)}),n instanceof e.a?n:new s(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let n=await this.signer.getAddress(),i=await this.readConfidentialBalanceOf(n);if(this.isZeroHandle(i))throw new e.r(`Cannot unshield: balance is zero`);try{let e=await this.signer.writeContract(r.k(this.address,n,n,i));return this.emit({type:t.k.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`unwrap`,error:t.Y(n)}),n instanceof e.a?n:new s(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return P(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return P(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let i,o,c=Date.now();try{this.emit({type:t.k.DecryptStart});let r=await this.relayer.publicDecrypt([n]);this.emit({type:t.k.DecryptEnd,durationMs:Date.now()-c}),o=r.decryptionProof;try{i=(0,a.hexToBigInt)(r.abiEncodedClearValues)}catch(t){throw new e.r(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`,{cause:t})}}catch(n){throw this.emit({type:t.k.DecryptError,error:t.Y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.r(`Failed to finalize unshield`,{cause:n})}try{let e=await this.signer.writeContract(r.p(this.wrapper,n,i,o));return this.emit({type:t.k.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`finalizeUnwrap`,error:t.Y(n)}),n instanceof e.a?n:new s(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=await this.#n(),i=n??2n**256n-1n;try{if(i>0n){let e=await this.signer.getAddress();await this.signer.readContract(t.V(r,e,this.wrapper))>0n&&await this.signer.writeContract(t.H(r,this.wrapper,0n))}let e=await this.signer.writeContract(t.H(r,this.wrapper,i));return this.emit({type:t.k.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`approveUnderlying`,error:t.Y(n)}),n instanceof e.a?n:new o(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){if(r&&r.getTime()<Date.now()+36e5)throw new t.it(`Expiration date must be at least 1 hour in the future`);let i=(0,a.getAddress)(n),o=await this.signer.getAddress();if(i===(0,a.getAddress)(o))throw new t.lt(`Cannot delegate to yourself (delegate === msg.sender).`);if(i===this.address)throw new t.rt(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.M;if(await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:i})===l)throw new t.ot(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(t.N(c,i,this.address,l));return this.emit({type:t.k.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`delegateDecryption`,error:t.Y(n)}),n instanceof e.a?n:m(n)||new s(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=(0,a.getAddress)(n),i=await this.signer.getAddress(),o=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:r})===0n)throw new t.st(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await this.signer.writeContract(t.I(o,r,this.address));return this.emit({type:t.k.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`revokeDelegation`,error:t.Y(n)}),n instanceof e.a?n:m(n)||new s(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:r}){return n.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return n.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.a?i.set(t[a].address,n):i.set(t[a].address,new s(r,{cause:n}))}return i}async#i(n){if(n===0n)return;let r,i;try{r=await this.signer.getAddress(),i=await this.readConfidentialBalanceOf(r)}catch(n){throw n instanceof e.a?n:new u(`Could not read confidential balance handle (token: ${this.address})`,{cause:t.Y(n)})}if(this.isZeroHandle(i))throw new c(`Insufficient confidential balance: requested ${n}, available 0 (token: ${this.address})`,{requested:n,available:0n,token:this.address});let a=await t.E({storage:this.storage,tokenAddress:this.address,owner:r,handle:i});if(a!==null){if(a<n)throw new c(`Insufficient confidential balance: requested ${n}, available ${a} (token: ${this.address})`,{requested:n,available:a,token:this.address});return}let o;try{o=await this.isAllowed()}catch(t){throw t instanceof e.a?t:new u(`Could not check credential status for balance validation (token: ${this.address})`,{cause:t})}if(!o)throw new u(`Cannot validate confidential balance: no cached credentials. Call allow() first or use skipBalanceCheck: true for smart wallets (token: ${this.address})`);let s;try{s=await this.decryptBalance(i,r)}catch(t){throw t instanceof e.a?t:new u(`Balance validation failed: could not decrypt confidential balance (token: ${this.address})`,{cause:t})}if(s<n)throw new c(`Insufficient confidential balance: requested ${n}, available ${s} (token: ${this.address})`,{requested:n,available:s,token:this.address})}async#a(n,r,i){this.emit({type:t.k.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.signer.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.a?t:new s(`Failed to get unshield receipt`,{cause:t})}let o=t.S(a.logs);if(!o)throw new s(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.k.UnshieldPhase2Started,operationId:r}),P(()=>i?.onFinalizing?.());let c=await this.finalizeUnwrap(o.encryptedAmount);return this.emit({type:t.k.UnshieldPhase2Submitted,txHash:c.txHash,operationId:r}),P(()=>i?.onFinalizeSubmitted?.(c.txHash)),c}async#o(n,r,i){let a=await this.#n(),s=await this.signer.getAddress(),c=await this.signer.readContract(t.V(a,s,this.wrapper));if(!(c>=n))try{c>0n&&await this.signer.writeContract(t.H(a,this.wrapper,0n));let e=r?2n**256n-1n:n,o=await this.signer.writeContract(t.H(a,this.wrapper,e));this.emit({type:t.k.ApproveUnderlyingSubmitted,txHash:o}),P(()=>i?.onApprovalSubmitted?.(o))}catch(t){throw t instanceof e.a?t:new o(`ERC-20 approval failed`,{cause:t})}}};function P(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const F={[n.o.chainId]:n.o.registryAddress,[n.s.chainId]:n.s.registryAddress,[n.n.chainId]:n.n.registryAddress},I=300*1e3;var L=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},F,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.signer.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,a.getAddress)(n)}async listPairs(t={}){let n=t.page??1,i=t.pageSize??100,a=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.signer.readContract(r.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.signer.readContract(r.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?I:void 0)}return{items:m,total:c,page:n,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.signer.readContract(t.K(e.tokenAddress)),this.signer.readContract(t.q(e.tokenAddress)),this.signer.readContract(t.W(e.tokenAddress)),this.signer.readContract(t.G(e.tokenAddress)),this.signer.readContract(t.K(e.confidentialTokenAddress)),this.signer.readContract(t.q(e.confidentialTokenAddress)),this.signer.readContract(t.W(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,a.getAddress)(e),i=`ct:${t}:${n}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.t(t,n));if(!s)return this.#i(i,null,I);let l=await this.signer.readContract(r.s(t,c));return this.#i(i,{confidentialTokenAddress:c,isValid:l})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,a.getAddress)(e),i=`ut:${t}:${n}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.n(t,n));if(!s)return this.#i(i,null,I);let l=await this.signer.readContract(r.s(t,n));return this.#i(i,{tokenAddress:c,isValid:l})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(r.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(r.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(r.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.t(t,(0,a.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.n(t,(0,a.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.s(t,(0,a.getAddress)(e)))}},R=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new t.A,this.#t=e.onEvent??function(){},this.registry=new L({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0)throw Error(`keypairTTL must be a positive number (seconds)`);return t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new t.O(n),this.delegatedCredentials=new t.D(n),this.#r=this.#o(),this.signer.subscribe){let n=e.signerLifecycleCallbacks,r=(e,n)=>{n().catch(n=>{this.#t?.({type:t.k.TransactionError,operation:e,error:t.Y(n),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{r(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,n?.onDisconnect?.()})},onAccountChange:e=>{r(`signerAccountChange`,async()=>{await this.#s(),this.#i=(0,a.getAddress)(e);try{this.#a=await this.signer.getChainId()}catch{}n?.onAccountChange?.(e)})},onChainChange:e=>{r(`signerChainChange`,async()=>{await this.#s(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}n?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await t.O.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new t.w({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:(0,a.getAddress)(e),onEvent:this.#t})}createToken(e,t){return new N({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:(0,a.getAddress)(e),wrapper:t?(0,a.getAddress)(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new L({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),n=this.#a??await this.signer.getChainId(),r=await t.O.computeStoreKey(e,n);await this.credentials.revokeByKey(r)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function z(e){return`zama:pending-unshield:${e}`}async function B(e,t,n){await e.set(z(t),n)}async function V(e,t){return e.get(z(t))}async function H(e,t){await e.delete(z(t))}var U=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const W=new U;exports.ACL_TOPICS=t.a,exports.AclPausedError=t.et,exports.AclTopics=t.o,exports.ApprovalFailedError=o,exports.BalanceCheckUnavailableError=u,exports.ChromeSessionStorage=U,exports.ConfigurationError=e.t,exports.CredentialsManager=t.O,exports.DecryptionFailedError=e.r,exports.DefaultRegistryAddresses=F,exports.DelegatedCredentialsManager=t.D,exports.DelegationContractIsSelfError=t.tt,exports.DelegationCooldownError=t.nt,exports.DelegationDelegateEqualsContractError=t.rt,exports.DelegationExpirationTooSoonError=t.it,exports.DelegationExpiredError=t.at,exports.DelegationExpiryUnchangedError=t.ot,exports.DelegationNotFoundError=t.st,exports.DelegationNotPropagatedError=t.ct,exports.DelegationSelfNotAllowedError=t.lt,exports.ERC20ReadFailedError=d,exports.ERC7984_INTERFACE_ID=r.c,exports.ERC7984_WRAPPER_INTERFACE_ID=r.l,exports.EncryptionFailedError=e.i,exports.HardhatConfig=n.a,exports.IndexedDBStorage=h,exports.InsufficientConfidentialBalanceError=c,exports.InsufficientERC20BalanceError=l,exports.InvalidKeypairError=t.ut,exports.KeypairExpiredError=t.dt,exports.MainnetConfig=n.o,exports.MemoryStorage=t.A,exports.NoCiphertextError=t.ft,exports.ReadonlyToken=t.w,exports.RelayerRequestFailedError=e.n,exports.RelayerWeb=M,exports.SepoliaConfig=n.s,exports.SigningFailedError=t.pt,exports.SigningRejectedError=t.mt,exports.TOKEN_TOPICS=t.s,exports.Token=N,exports.Topics=t.c,exports.TransactionRevertedError=s,exports.WrappersRegistry=L,exports.ZERO_HANDLE=t.T,exports.ZamaError=e.a,exports.ZamaErrorCode=e.o,exports.ZamaSDK=R,exports.ZamaSDKEvents=t.k,exports.allowanceContract=t.V,exports.applyDecryptedValues=t.t,exports.approveContract=t.H,exports.balanceOfContract=t.U,exports.chromeSessionStorage=W,exports.clearPendingUnshield=H,exports.confidentialBalanceOfContract=r._,exports.confidentialBatchTransferContract=i.t,exports.confidentialTotalSupplyContract=r.v,exports.confidentialTransferContract=r.y,exports.confidentialTransferFromContract=r.b,exports.decimalsContract=t.W,exports.decodeAclEvent=t.l,exports.decodeAclEvents=t.u,exports.decodeConfidentialTransfer=t.d,exports.decodeDelegatedForUserDecryption=t.f,exports.decodeOnChainEvent=t.p,exports.decodeOnChainEvents=t.m,exports.decodeRevokedDelegationForUserDecryption=t.h,exports.decodeUnwrapRequested=t.g,exports.decodeUnwrappedFinalized=t._,exports.decodeUnwrappedStarted=t.v,exports.decodeWrapped=t.y,exports.delegateForUserDecryptionContract=t.N,exports.deploymentCoordinatorContract=r.x,exports.extractEncryptedHandles=t.n,exports.finalizeUnwrapContract=r.p,exports.findDelegatedForUserDecryption=t.b,exports.findRevokedDelegationForUserDecryption=t.x,exports.findUnwrapRequested=t.S,exports.findWrapped=t.C,exports.getBatchTransferFeeContract=t.L,exports.getConfidentialTokenAddressContract=r.t,exports.getDelegationExpiryContract=t.P,exports.getFeeRecipientContract=t.R,exports.getTokenAddressContract=r.n,exports.getTokenPairContract=r.r,exports.getTokenPairsContract=r.i,exports.getTokenPairsLengthContract=r.a,exports.getTokenPairsSliceContract=r.o,exports.getUnwrapFeeContract=t.z,exports.getWrapFeeContract=t.B,exports.getWrapperContract=i.n,exports.indexedDBStorage=g,exports.isConfidentialTokenContract=r.u,exports.isConfidentialTokenValidContract=r.s,exports.isConfidentialWrapperContract=r.d,exports.isFinalizeUnwrapOperatorContract=r.S,exports.isHandleDelegatedContract=t.F,exports.isOperatorContract=r.C,exports.loadPendingUnshield=V,exports.matchAclRevert=m,exports.matchZamaError=e.s,exports.memoryStorage=t.j,exports.nameContract=t.K,exports.parseActivityFeed=t.r,exports.rateContract=r.w,exports.revokeDelegationContract=t.I,exports.savePendingUnshield=B,exports.setFinalizeUnwrapOperatorContract=r.T,exports.setOperatorContract=r.E,exports.sortByBlockNumber=t.i,exports.supportsInterfaceContract=r.f,exports.symbolContract=t.q,exports.totalSupplyContract=r.D,exports.underlyingContract=r.m,exports.unwrapContract=r.O,exports.unwrapFromBalanceContract=r.k,exports.wrapContract=r.h,exports.wrapETHContract=r.g,exports.wrapperExistsContract=i.r;
514
+ `],{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,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};const S=8192,C=300*1e3;function w(e){let t=[];for(let n=0;n<e.length;n+=S)t.push(String.fromCharCode(...e.subarray(n,n+S)));return btoa(t.join(``))}function T(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 E(e){return`fhe:pubkey:${e}`}function D(e,t){return`fhe:params:${e}:${t}`}function O(e){return`fhe:params-index:${e}`}function k(e){t.Q(e,`CachedPublicKey`),t.$(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),t.$(e,`publicKey`,`CachedPublicKey.publicKey`)}function A(e){t.Q(e,`CachedPublicParams`),t.$(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),t.$(e,`publicParams`,`CachedPublicParams.publicParams`)}var j=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??console}async getPublicKey(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=E(this.#t);try{let e=await this.#e.get(n);if(e){k(e);let t={publicKeyId:e.publicKeyId,publicKey:T(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(n),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:t.Y(e).message})}let r=await e();if(r===null)return null;this.#a=r;try{let e={publicKeyId:r.publicKeyId,publicKey:w(r.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.Y(e).message})}return r}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=D(this.#t,e);try{let t=await this.#e.get(r);if(t){A(t);let n={publicParamsId:t.publicParamsId,publicParams:T(t.publicParams)};return this.#o.set(e,n),n}}catch(n){await this.#g(r),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:t.Y(n).message})}let i=await n();if(i===null)return null;this.#o.set(e,i);try{let n={publicParamsId:i.publicParamsId,publicParams:w(i.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,n);let a=O(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:t.Y(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.Y(n).message})}return i}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=E(this.#t),r=null,i=[];try{let[a,o]=await Promise.all([this.#e.get(n),this.#h()]);if(a)try{k(a),r={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:t.Y(e).message}),await this.#g(n)}if(i=o,!r)return!1;if([r,...i.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let t=e-this.#r+C;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let c=await s.json();if(!c||typeof c!=`object`||!(`fhePublicKey`in c)||!c.fhePublicKey?.urls?.length||!(`crs`in c)||typeof c.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let t=e-this.#r+C;return await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let l=c,u=l.fhePublicKey.urls[0];if(r.artifactUrl&&u&&u!==r.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let d={...r,lastValidatedAt:e};if(u){let e=await this.#m(u,r);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;d={...d,artifactUrl:u,etag:e.etag,lastModified:e.lastModified}}let f=[];for(let t of i){let r=l.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let a={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;a={...a,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}f.push({...t,data:a})}return await this.#v(n,d,f),this.#u=e,!1}catch(a){let o=t.Y(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a 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+C;try{r&&await this.#v(n,{...r,lastValidatedAt:l},i.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.Y(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=O(this.#t),n=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:t.Y(e).message}),null))??[],r=new Set([...this.#o.keys(),...n]),i=Array.from(r);return(await Promise.all(i.map(async e=>{let n=D(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.Y(n).message}),null}if(!r)return null;try{return A(r),{bits:e,key:n,data:{...r,lastValidatedAt:r.lastValidatedAt??0}}}catch(r){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:t.Y(r).message}),await this.#g(n),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.Y(n).message})})}async#_(e,n){let r=O(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.Y(e).message})}this.#a=void 0,this.#o.clear()}async#v(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.Y(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.Y(e).message})}))];await Promise.all(i)}},M=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:r,threads:i}=this.#l;if(i!==void 0&&(!Number.isInteger(i)||i<1))throw Error(`Invalid thread count: ${i}. Must be a positive integer.`);return i!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},n.i[e],t[e]),csrfToken:r?.getCsrfToken?.()??``,integrity:r?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:i}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let t=await this.#l.getChainId();if(this.#i!==null&&t!==this.#i&&this.#p(),this.#i=t,this.#o||=this.#l.fheArtifactStorage??new h(`FheArtifactCache`,1,`artifacts`),!this.#a){let e=Object.assign({},n.i[t],this.#l.transports[t]);this.#a=new j({storage:this.#o,chainId:t,relayerUrl:e.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(t=>{this.#t=null;let n=t instanceof e.a?t:new e.t(`Failed to initialize FHE worker`,{cause:t});throw this.#u(`error`,n),n})),this.#t}async#h(){let e=new x(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,r,i=7){let a=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:r,durationDays:i}),o={name:a.domain.name,version:a.domain.version,chainId:a.domain.chainId,verifyingContract:a.domain.verifyingContract};return{domain:o,types:{EIP712Domain:n.c(o),UserDecryptRequestVerification:a.types.UserDecryptRequestVerification},message:{publicKey:a.message.publicKey,contractAddresses:a.message.contractAddresses,startTimestamp:a.message.startTimestamp,durationDays:a.message.durationDays,extraData:a.message.extraData}}}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;return n.l(async()=>{let e=await this.#f();await this.#g();let n=await e.encrypt({values:t,contractAddress:r,userAddress:i});return{handles:n.handles,inputProof:n.inputProof}})}async userDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return n.l(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let t=await this.#l.getChainId(),r=Object.assign({},n.i[t],this.#l.transports[t]);if(!r.aclContractAddress)throw new e.t(`No ACL address configured for chain ${t}`);return r.aclContractAddress}},N=class n extends t.w{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e){super(e),this.wrapper=e.wrapper?(0,a.getAddress)(e.wrapper):this.address}async#n(){return this.#e===void 0?(this.#t||=this.signer.readContract(r.m(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(n,i,o){let{skipBalanceCheck:c=!1,onEncryptComplete:l,onTransferSubmitted:u}=o??{},d=(0,a.getAddress)(n);c||await this.#i(i);let f,p,m=Date.now();try{this.emit({type:t.k.EncryptStart}),{handles:f,inputProof:p}=await this.relayer.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await this.signer.getAddress()}),this.emit({type:t.k.EncryptEnd,durationMs:Date.now()-m}),P(()=>l?.())}catch(n){throw this.emit({type:t.k.EncryptError,error:t.Y(n),durationMs:Date.now()-m}),n instanceof e.a?n:new e.i(`Failed to encrypt transfer amount`,{cause:n})}if(f.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.y(this.address,d,f[0],p));return this.emit({type:t.k.TransferSubmitted,txHash:e}),P(()=>u?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`transfer`,error:t.Y(n)}),n instanceof e.a?n:new s(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(n,i,o,c){let l=(0,a.getAddress)(n),u=(0,a.getAddress)(i),d,f,p=Date.now();try{this.emit({type:t.k.EncryptStart}),{handles:d,inputProof:f}=await this.relayer.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:l}),this.emit({type:t.k.EncryptEnd,durationMs:Date.now()-p}),P(()=>c?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.k.EncryptError,error:t.Y(n),durationMs:Date.now()-p}),n instanceof e.a?n:new e.i(`Failed to encrypt transferFrom amount`,{cause:n})}if(d.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.b(this.address,l,u,d[0],f));return this.emit({type:t.k.TransferFromSubmitted,txHash:e}),P(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`transferFrom`,error:t.Y(n)}),n instanceof e.a?n:new s(`TransferFrom transaction failed`,{cause:n})}}async approve(n,i){let s=(0,a.getAddress)(n);try{let e=await this.signer.writeContract(r.E(this.address,s,i));return this.emit({type:t.k.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`approve`,error:t.Y(n)}),n instanceof e.a?n:new o(`Operator approval failed`,{cause:n})}}async isApproved(e,t){let n=(0,a.getAddress)(e),i=t?(0,a.getAddress)(t):await this.signer.getAddress();return this.signer.readContract(r.C(this.address,i,n))}async shield(i,o){let c=await this.#n();if(c===n.ZERO_ADDRESS)return this.shieldETH(i,i+(o?.fees??0n));let u;try{let e=await this.signer.getAddress();u=await this.signer.readContract(t.U(c,e))}catch(n){throw n instanceof e.a?n:new d(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:t.Y(n)})}if(u<i)throw new l(`Insufficient ERC-20 balance: requested ${i}, available ${u} (token: ${c})`,{requested:i,available:u,token:c});let f=o?.approvalStrategy??`exact`;f!==`skip`&&await this.#o(i,f===`max`,o);try{let e=o?.to?(0,a.getAddress)(o.to):await this.signer.getAddress(),n=await this.signer.writeContract(r.h(this.wrapper,e,i));return this.emit({type:t.k.ShieldSubmitted,txHash:n}),P(()=>o?.onShieldSubmitted?.(n)),{txHash:n,receipt:await this.signer.waitForTransactionReceipt(n)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`shield`,error:t.Y(n)}),n instanceof e.a?n:new s(`Shield transaction failed`,{cause:n})}}async shieldETH(n,i){try{let e=await this.signer.getAddress(),a=await this.signer.writeContract(r.g(this.wrapper,e,n,i??n));return this.emit({type:t.k.ShieldSubmitted,txHash:a}),{txHash:a,receipt:await this.signer.waitForTransactionReceipt(a)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`shieldETH`,error:t.Y(n)}),n instanceof e.a?n:new s(`Shield ETH transaction failed`,{cause:n})}}async unwrap(n){let i=await this.signer.getAddress(),a,o,c=Date.now();try{this.emit({type:t.k.EncryptStart}),{handles:a,inputProof:o}=await this.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.wrapper,userAddress:i}),this.emit({type:t.k.EncryptEnd,durationMs:Date.now()-c})}catch(n){throw this.emit({type:t.k.EncryptError,error:t.Y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.i(`Failed to encrypt unshield amount`,{cause:n})}if(a.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.signer.writeContract(r.O(this.address,i,i,a[0],o));return this.emit({type:t.k.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`unwrap`,error:t.Y(n)}),n instanceof e.a?n:new s(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let n=await this.signer.getAddress(),i=await this.readConfidentialBalanceOf(n);if(this.isZeroHandle(i))throw new e.r(`Cannot unshield: balance is zero`);try{let e=await this.signer.writeContract(r.k(this.address,n,n,i));return this.emit({type:t.k.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`unwrap`,error:t.Y(n)}),n instanceof e.a?n:new s(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return P(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return P(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let i,o,c=Date.now();try{this.emit({type:t.k.DecryptStart});let r=await this.relayer.publicDecrypt([n]);this.emit({type:t.k.DecryptEnd,durationMs:Date.now()-c}),o=r.decryptionProof;try{i=(0,a.hexToBigInt)(r.abiEncodedClearValues)}catch(t){throw new e.r(`Cannot parse decrypted value: ${r.abiEncodedClearValues}`,{cause:t})}}catch(n){throw this.emit({type:t.k.DecryptError,error:t.Y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.r(`Failed to finalize unshield`,{cause:n})}try{let e=await this.signer.writeContract(r.p(this.wrapper,n,i,o));return this.emit({type:t.k.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`finalizeUnwrap`,error:t.Y(n)}),n instanceof e.a?n:new s(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=await this.#n(),i=n??2n**256n-1n;try{if(i>0n){let e=await this.signer.getAddress();await this.signer.readContract(t.V(r,e,this.wrapper))>0n&&await this.signer.writeContract(t.H(r,this.wrapper,0n))}let e=await this.signer.writeContract(t.H(r,this.wrapper,i));return this.emit({type:t.k.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`approveUnderlying`,error:t.Y(n)}),n instanceof e.a?n:new o(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){if(r&&r.getTime()<Date.now()+36e5)throw new t.it(`Expiration date must be at least 1 hour in the future`);let i=(0,a.getAddress)(n),o=await this.signer.getAddress();if(i===(0,a.getAddress)(o))throw new t.lt(`Cannot delegate to yourself (delegate === msg.sender).`);if(i===this.address)throw new t.rt(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.M;if(await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:i})===l)throw new t.ot(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await this.signer.writeContract(t.N(c,i,this.address,l));return this.emit({type:t.k.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`delegateDecryption`,error:t.Y(n)}),n instanceof e.a?n:m(n)||new s(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=(0,a.getAddress)(n),i=await this.signer.getAddress(),o=await this.getAclAddress();if(await this.getDelegationExpiry({delegatorAddress:i,delegateAddress:r})===0n)throw new t.st(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await this.signer.writeContract(t.I(o,r,this.address));return this.emit({type:t.k.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.k.TransactionError,operation:`revokeDelegation`,error:t.Y(n)}),n instanceof e.a?n:m(n)||new s(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:r}){return n.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return n.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.a?i.set(t[a].address,n):i.set(t[a].address,new s(r,{cause:n}))}return i}async#i(n){if(n===0n)return;let r,i;try{r=await this.signer.getAddress(),i=await this.readConfidentialBalanceOf(r)}catch(n){throw n instanceof e.a?n:new u(`Could not read confidential balance handle (token: ${this.address})`,{cause:t.Y(n)})}if(this.isZeroHandle(i))throw new c(`Insufficient confidential balance: requested ${n}, available 0 (token: ${this.address})`,{requested:n,available:0n,token:this.address});let a=await t.E({storage:this.storage,tokenAddress:this.address,owner:r,handle:i});if(a!==null){if(a<n)throw new c(`Insufficient confidential balance: requested ${n}, available ${a} (token: ${this.address})`,{requested:n,available:a,token:this.address});return}let o;try{o=await this.isAllowed()}catch(t){throw t instanceof e.a?t:new u(`Could not check credential status for balance validation (token: ${this.address})`,{cause:t})}if(!o)throw new u(`Cannot validate confidential balance: no cached credentials. Call allow() first or use skipBalanceCheck: true for smart wallets (token: ${this.address})`);let s;try{s=await this.decryptBalance(i,r)}catch(t){throw t instanceof e.a?t:new u(`Balance validation failed: could not decrypt confidential balance (token: ${this.address})`,{cause:t})}if(s<n)throw new c(`Insufficient confidential balance: requested ${n}, available ${s} (token: ${this.address})`,{requested:n,available:s,token:this.address})}async#a(n,r,i){this.emit({type:t.k.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.signer.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.a?t:new s(`Failed to get unshield receipt`,{cause:t})}let o=t.S(a.logs);if(!o)throw new s(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.k.UnshieldPhase2Started,operationId:r}),P(()=>i?.onFinalizing?.());let c=await this.finalizeUnwrap(o.encryptedAmount);return this.emit({type:t.k.UnshieldPhase2Submitted,txHash:c.txHash,operationId:r}),P(()=>i?.onFinalizeSubmitted?.(c.txHash)),c}async#o(n,r,i){let a=await this.#n(),s=await this.signer.getAddress(),c=await this.signer.readContract(t.V(a,s,this.wrapper));if(!(c>=n))try{c>0n&&await this.signer.writeContract(t.H(a,this.wrapper,0n));let e=r?2n**256n-1n:n,o=await this.signer.writeContract(t.H(a,this.wrapper,e));this.emit({type:t.k.ApproveUnderlyingSubmitted,txHash:o}),P(()=>i?.onApprovalSubmitted?.(o))}catch(t){throw t instanceof e.a?t:new o(`ERC-20 approval failed`,{cause:t})}}};function P(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const F={[n.o.chainId]:n.o.registryAddress,[n.s.chainId]:n.s.registryAddress,[n.n.chainId]:n.n.registryAddress},I=300*1e3;var L=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},F,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.signer.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,a.getAddress)(n)}async listPairs(t={}){let n=t.page??1,i=t.pageSize??100,a=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.signer.readContract(r.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.signer.readContract(r.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?I:void 0)}return{items:m,total:c,page:n,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.signer.readContract(t.K(e.tokenAddress)),this.signer.readContract(t.q(e.tokenAddress)),this.signer.readContract(t.W(e.tokenAddress)),this.signer.readContract(t.G(e.tokenAddress)),this.signer.readContract(t.K(e.confidentialTokenAddress)),this.signer.readContract(t.q(e.confidentialTokenAddress)),this.signer.readContract(t.W(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,a.getAddress)(e),i=`ct:${t}:${n}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.t(t,n));if(!s)return this.#i(i,null,I);let l=await this.signer.readContract(r.s(t,c));return this.#i(i,{confidentialTokenAddress:c,isValid:l})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,a.getAddress)(e),i=`ut:${t}:${n}`,o=this.#r(i);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.n(t,n));if(!s)return this.#i(i,null,I);let l=await this.signer.readContract(r.s(t,n));return this.#i(i,{tokenAddress:c,isValid:l})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(r.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(r.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(r.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.t(t,(0,a.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.n(t,(0,a.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.s(t,(0,a.getAddress)(e)))}};const R=365*86400;var z=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new t.A,this.#t=e.onEvent??function(){},this.registry=new L({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>R?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${R}s); capping to ${R}s.`),R):t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new t.O(n),this.delegatedCredentials=new t.D(n),this.#r=this.#o(),this.signer.subscribe){let n=e.signerLifecycleCallbacks,r=(e,n)=>{n().catch(n=>{this.#t?.({type:t.k.TransactionError,operation:e,error:t.Y(n),timestamp:Date.now()})})};this.#n=this.signer.subscribe({onDisconnect:()=>{r(`signerDisconnect`,async()=>{await this.#s(),this.#i=null,this.#a=null,n?.onDisconnect?.()})},onAccountChange:e=>{r(`signerAccountChange`,async()=>{await this.#s(),this.#i=(0,a.getAddress)(e);try{this.#a=await this.signer.getChainId()}catch{}n?.onAccountChange?.(e)})},onChainChange:e=>{r(`signerChainChange`,async()=>{await this.#s(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}n?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await t.O.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new t.w({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:(0,a.getAddress)(e),onEvent:this.#t})}createToken(e,t){return new N({relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,credentials:this.credentials,delegatedCredentials:this.delegatedCredentials,address:(0,a.getAddress)(e),wrapper:t?(0,a.getAddress)(t):void 0,onEvent:this.#t})}createWrappersRegistry(e){return new L({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),n=this.#a??await this.signer.getChainId(),r=await t.O.computeStoreKey(e,n);await this.credentials.revokeByKey(r)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function B(e){return`zama:pending-unshield:${e}`}async function V(e,t,n){await e.set(B(t),n)}async function H(e,t){return e.get(B(t))}async function U(e,t){await e.delete(B(t))}var W=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const G=new W;exports.ACL_TOPICS=t.a,exports.AclPausedError=t.et,exports.AclTopics=t.o,exports.ApprovalFailedError=o,exports.BalanceCheckUnavailableError=u,exports.ChromeSessionStorage=W,exports.ConfigurationError=e.t,exports.CredentialsManager=t.O,exports.DecryptionFailedError=e.r,exports.DefaultRegistryAddresses=F,exports.DelegatedCredentialsManager=t.D,exports.DelegationContractIsSelfError=t.tt,exports.DelegationCooldownError=t.nt,exports.DelegationDelegateEqualsContractError=t.rt,exports.DelegationExpirationTooSoonError=t.it,exports.DelegationExpiredError=t.at,exports.DelegationExpiryUnchangedError=t.ot,exports.DelegationNotFoundError=t.st,exports.DelegationNotPropagatedError=t.ct,exports.DelegationSelfNotAllowedError=t.lt,exports.ERC20ReadFailedError=d,exports.ERC7984_INTERFACE_ID=r.c,exports.ERC7984_WRAPPER_INTERFACE_ID=r.l,exports.EncryptionFailedError=e.i,exports.HardhatConfig=n.a,exports.IndexedDBStorage=h,exports.InsufficientConfidentialBalanceError=c,exports.InsufficientERC20BalanceError=l,exports.InvalidKeypairError=t.ut,exports.KeypairExpiredError=t.dt,exports.MainnetConfig=n.o,exports.MemoryStorage=t.A,exports.NoCiphertextError=t.ft,exports.ReadonlyToken=t.w,exports.RelayerRequestFailedError=e.n,exports.RelayerWeb=M,exports.SepoliaConfig=n.s,exports.SigningFailedError=t.pt,exports.SigningRejectedError=t.mt,exports.TOKEN_TOPICS=t.s,exports.Token=N,exports.Topics=t.c,exports.TransactionRevertedError=s,exports.WrappersRegistry=L,exports.ZERO_HANDLE=t.T,exports.ZamaError=e.a,exports.ZamaErrorCode=e.o,exports.ZamaSDK=z,exports.ZamaSDKEvents=t.k,exports.allowanceContract=t.V,exports.applyDecryptedValues=t.t,exports.approveContract=t.H,exports.balanceOfContract=t.U,exports.chromeSessionStorage=G,exports.clearPendingUnshield=U,exports.confidentialBalanceOfContract=r._,exports.confidentialBatchTransferContract=i.t,exports.confidentialTotalSupplyContract=r.v,exports.confidentialTransferContract=r.y,exports.confidentialTransferFromContract=r.b,exports.decimalsContract=t.W,exports.decodeAclEvent=t.l,exports.decodeAclEvents=t.u,exports.decodeConfidentialTransfer=t.d,exports.decodeDelegatedForUserDecryption=t.f,exports.decodeOnChainEvent=t.p,exports.decodeOnChainEvents=t.m,exports.decodeRevokedDelegationForUserDecryption=t.h,exports.decodeUnwrapRequested=t.g,exports.decodeUnwrappedFinalized=t._,exports.decodeUnwrappedStarted=t.v,exports.decodeWrapped=t.y,exports.delegateForUserDecryptionContract=t.N,exports.deploymentCoordinatorContract=r.x,exports.extractEncryptedHandles=t.n,exports.finalizeUnwrapContract=r.p,exports.findDelegatedForUserDecryption=t.b,exports.findRevokedDelegationForUserDecryption=t.x,exports.findUnwrapRequested=t.S,exports.findWrapped=t.C,exports.getBatchTransferFeeContract=t.L,exports.getConfidentialTokenAddressContract=r.t,exports.getDelegationExpiryContract=t.P,exports.getFeeRecipientContract=t.R,exports.getTokenAddressContract=r.n,exports.getTokenPairContract=r.r,exports.getTokenPairsContract=r.i,exports.getTokenPairsLengthContract=r.a,exports.getTokenPairsSliceContract=r.o,exports.getUnwrapFeeContract=t.z,exports.getWrapFeeContract=t.B,exports.getWrapperContract=i.n,exports.indexedDBStorage=g,exports.isConfidentialTokenContract=r.u,exports.isConfidentialTokenValidContract=r.s,exports.isConfidentialWrapperContract=r.d,exports.isFinalizeUnwrapOperatorContract=r.S,exports.isHandleDelegatedContract=t.F,exports.isOperatorContract=r.C,exports.loadPendingUnshield=H,exports.matchAclRevert=m,exports.matchZamaError=e.s,exports.memoryStorage=t.j,exports.nameContract=t.K,exports.parseActivityFeed=t.r,exports.rateContract=r.w,exports.revokeDelegationContract=t.I,exports.savePendingUnshield=V,exports.setFinalizeUnwrapOperatorContract=r.T,exports.setOperatorContract=r.E,exports.sortByBlockNumber=t.i,exports.supportsInterfaceContract=r.f,exports.symbolContract=t.q,exports.totalSupplyContract=r.D,exports.underlyingContract=r.m,exports.unwrapContract=r.O,exports.unwrapFromBalanceContract=r.k,exports.wrapContract=r.h,exports.wrapETHContract=r.g,exports.wrapperExistsContract=i.r;
515
515
  //# sourceMappingURL=index.cjs.map