@zama-fhe/sdk 3.9.1-beta.2 → 3.9.1-beta.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.
Files changed (30) hide show
  1. package/dist/cjs/base-signer.cjs +1 -1
  2. package/dist/cjs/base-signer.cjs.map +1 -1
  3. package/dist/cjs/index.cjs +1 -1
  4. package/dist/cjs/index.cjs.map +1 -1
  5. package/dist/cjs/telemetry.cjs +1 -1
  6. package/dist/esm/base-signer-DUflPI8d.js +2 -0
  7. package/dist/esm/base-signer-DUflPI8d.js.map +1 -0
  8. package/dist/esm/cleartext/index.js +1 -1
  9. package/dist/esm/{cleartext-C0DXenyT.js → cleartext-Dt_G8a-Y.js} +2 -2
  10. package/dist/esm/{cleartext-C0DXenyT.js.map → cleartext-Dt_G8a-Y.js.map} +1 -1
  11. package/dist/esm/{decryption-BvvhpFM2.d.ts → decryption-CMNWWt0M.d.ts} +6 -3
  12. package/dist/esm/ethers/index.js +1 -1
  13. package/dist/esm/{fhevm-relayer-DCQ-Oaa1.js → fhevm-relayer-BRF_qaSG.js} +2 -2
  14. package/dist/esm/{fhevm-relayer-DCQ-Oaa1.js.map → fhevm-relayer-BRF_qaSG.js.map} +1 -1
  15. package/dist/esm/{index-B7M2GEtA.d.ts → index-Dh3aBqpo.d.ts} +1 -1
  16. package/dist/esm/index.d.ts +2 -2
  17. package/dist/esm/index.js +1 -1
  18. package/dist/esm/index.js.map +1 -1
  19. package/dist/esm/internal/index.d.ts +1 -1
  20. package/dist/esm/internal/index.js +1 -1
  21. package/dist/esm/node/index.js +1 -1
  22. package/dist/esm/query/index.d.ts +2 -2
  23. package/dist/esm/{telemetry-CW2RgPxb.js → telemetry-DgZG8yT6.js} +2 -2
  24. package/dist/esm/{telemetry-CW2RgPxb.js.map → telemetry-DgZG8yT6.js.map} +1 -1
  25. package/dist/esm/vaults/index.d.ts +1 -1
  26. package/dist/esm/viem/index.js +1 -1
  27. package/dist/esm/web/index.js +1 -1
  28. package/package.json +1 -1
  29. package/dist/esm/base-signer-CysprC2L.js +0 -2
  30. package/dist/esm/base-signer-CysprC2L.js.map +0 -1
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{t as e}from"./cleartext-C0DXenyT.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as ee,t as te,u as ne,v as re}from"./base-signer-CysprC2L.js";import{a as ie,c as ae,i as oe,l as se,n as ce,o as le,r as ue,s as de,t as fe,u as pe}from"./configs-9EL-DJHq.js";import{A as me,B as h,C as he,D as ge,E as _e,F as g,G as ve,H as ye,I as _,J as be,K as v,M as y,N as xe,O as Se,P as Ce,S as we,T as Te,U as Ee,W as De,X as b,Y as Oe,_ as ke,a as Ae,b as je,c as Me,d as Ne,f as x,h as Pe,j as Fe,k as Ie,l as Le,m as Re,n as S,o as ze,p as C,q as Be,s as Ve,t as w,u as He,v as Ue,w as We,x as Ge,y as Ke,z as qe}from"./alignment-D1cVCzw8.js";import{C as T,S as Je,_ as E,a as Ye,b as Xe,c as D,d as Ze,f as Qe,g as $e,h as et,i as tt,l as nt,m as rt,n as O,o as k,p as it,r as A,s as j,t as at,u as ot,v as M,w as st,x as N,y as P}from"./public-decrypt-Bec9uoNY.js";import{c as F,d as ct,f as lt,i as ut,l as dt,n as ft,o as pt,p as I,r as mt,s as ht,t as L,u as R}from"./token-DnriE-3y.js";import{C as z,_ as gt,a as _t,c as vt,g as yt,i as bt,m as xt,n as St,o as Ct,r as B,s as wt,t as V,y as Tt}from"./relayer-Cki3j_Ba.js";import{n as Et,r as H,t as U}from"./encryption-QHaWnnx-.js";import{a as Dt,c as Ot,d as kt,i as At,l as W,n as jt,o as Mt,s as Nt,t as Pt,u as Ft}from"./signing-DX-xyved.js";import{n as It,r as Lt}from"./fatal-batch-CI0ESPnd.js";import{i as Rt,n as zt,r as Bt,t as Vt}from"./unshield-xO66p_da.js";import{r as G}from"./telemetry-CW2RgPxb.js";import{t as K}from"./validation-BLmG7UVk.js";import{a as Ht,i as Ut,n as Wt,o as Gt,r as Kt,s as qt,t as Jt}from"./wrappers-registry-Cm3JJeqx.js";import{encodeFunctionData as Yt,getAddress as q,isAddressEqual as Xt,parseTransaction as Zt,size as Qt,zeroAddress as $t}from"viem";import{z as J}from"zod/mini";function en(e,t){if(e instanceof B){let n=t[e.code];if(n)return n(e)}return t._?.(e)}function tn(e,t){if(e instanceof B)return e;let n=wt(e),r=gt(e);return n!==void 0||yt(e)?new St(e instanceof Error?e.message:t,n,{cause:e,retryAfter:vt(e),retryable:r||void 0}):new H(t,{cause:e})}const nn=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function rn(e,t,n,r=`0x`){return{address:e,abi:nn,functionName:`transferAndCall`,args:[t,n,r]}}const Y=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function an(e,t,n,r){return{address:e,abi:Y,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function on(e,t,n){return{address:e,abi:Y,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function sn(e,t,n,r){return{address:e,abi:Y,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function cn(e,t,n,r,i){return{address:e,abi:Y,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const X=2n**64n-1n,Z=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function ln(e){return c(e.signer,e.provider,e)}const Q={ConfidentialTransfer:O(`ConfidentialTransfer(address,address,bytes32)`),Wrap:O(`Wrap(address,uint256,bytes32)`),UnwrapRequested:O(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:O(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function un(e){return e.topics[0]!==Q.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:A(e.topics[1]),to:A(e.topics[2]),encryptedAmount:tt(e.topics[3])}}function dn(e){return e.topics[0]!==Q.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:A(e.topics[1]),roundedAmount:k(e.data,0),encryptedWrappedAmount:j(e.data,1)}}function fn(e){return e.topics[0]!==Q.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:A(e.topics[1]),unwrapRequestId:tt(e.topics[2]),encryptedAmount:j(e.data,0)}}function pn(e){return e.topics[0]!==Q.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:A(e.topics[1]),unwrapRequestId:tt(e.topics[2]),encryptedAmount:j(e.data,0),cleartextAmount:k(e.data,1)}}function mn(e){return un(e)??dn(e)??fn(e)??pn(e)}function hn(e){let t=[];for(let n of e){let e=mn(n);e&&t.push(e)}return t}function gn(e){for(let t of e){let e=fn(t);if(e)return e}return null}function _n(e){for(let t of e){let e=dn(t);if(e)return e}return null}const vn=[Q.ConfidentialTransfer,Q.Wrap,Q.UnwrapRequested,Q.UnwrapFinalized],$={DelegatedForUserDecryption:O(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:O(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function yn(e){return e.topics[0]!==$.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:Ye(e.data,0),delegationCounter:k(e.data,1),oldExpirationDate:k(e.data,2),newExpirationDate:k(e.data,3)}}function bn(e){return e.topics[0]!==$.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:Ye(e.data,0),delegationCounter:k(e.data,1),oldExpirationDate:k(e.data,2)}}function xn(e){return yn(e)??bn(e)}function Sn(e){let t=[];for(let n of e){let e=xn(n);e&&t.push(e)}return t}function Cn(e){for(let t of e){let e=yn(t);if(e)return e}return null}function wn(e){for(let t of e){let e=bn(t);if(e)return e}return null}const Tn=[$.DelegatedForUserDecryption,$.RevokedDelegationForUserDecryption];var En=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return v(this.#r,e)}#s(e,t){throw this.#a({type:h.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await S(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await S(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}registerPermit(e,t){return this.batchRegisterPermits([{prepared:e,signature:t}])}async batchRegisterPermits(e){let t;try{t=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await t.batchRegisterPermits(e),await Promise.all([...new Set(e.map(e=>e.prepared.signerAddress))].map(e=>this.#c(e)))}async revokePermits(e){let t=this.#o(`revokePermits`),n=await w(`revokePermits`,this.#e,this.#t),r=q(n.address);try{await t.revokePermits(e)}finally{await this.#c(r)}}async clear(){let e=this.#o(`clear`),t=await w(`clear`,this.#e,this.#t),n=q(t.address);try{await e.clearCredentials()}finally{await this.#c(n)}}async#c(e){await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},Dn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return v(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await w(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await w(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},On=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return v(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await w(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,G(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await w(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,G(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=G(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{qe(t.clearValues[n],`result.clearValues[${n}]`),r[e]=t.clearValues[n].value}),{clearValues:r,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw D(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i,operation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await w(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i,operation:a??`delegated-batch-decrypt-values`})}},kn=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}batchPreparePermits(e){return this.#t.batchPreparePermits(e)}},An=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 jn=new An;async function Mn(e,t){if(e.getTransactionReceipt)return e.getTransactionReceipt(t);let n,r=new Promise(e=>{n=setTimeout(()=>e(null),5e3)});try{return await Promise.race([e.waitForTransactionReceipt(t),r])}finally{clearTimeout(n)}}function Nn(e){return`zama:pending-unshields:${i(e)}`}function Pn(e){return`zama:pending-unshield:${i(e)}`}function Fn(e){return{version:2,unwrapTxHashes:e}}const In=J.union([p,J.pipe(J.object({version:J.literal(1),unwrapTxHash:p}),J.transform(({unwrapTxHash:e})=>e))]),Ln=J.object({version:J.number(),unwrapTxHashes:J.optional(J.unknown())}),Rn=(e,t)=>e.toLowerCase()===t.toLowerCase();async function zn(e,t,n){let r=await e.get(t);if(r==null)return{hashes:[],writable:!0};let i=Ln.safeParse(r);if(i.success&&i.data.version!==2)return n?.warn(`pending unshields saved by an unknown SDK version were left as is`,{version:i.data.version}),{hashes:[],writable:!1};let a=i.success?i.data.unwrapTxHashes:void 0;if(!Array.isArray(a))return n?.warn(`unreadable pending unshields were dropped`,{value:r}),{hashes:[],writable:!0};let o=a.filter(e=>p.safeParse(e).success);return o.length!==a.length&&n?.warn(`unreadable pending unshield entries were dropped`,{unwrapTxHashes:a}),{hashes:o,writable:!0}}async function Bn(e,t,n){let r=await zn(e,Nn(t),n),i=In.safeParse(await e.get(Pn(t)));return!i.success||!r.writable?{...r,hasLegacy:!1}:{hashes:r.hashes.some(e=>Rn(e,i.data))?r.hashes:[i.data,...r.hashes],writable:!0,hasLegacy:!0}}async function Vn(e,t,n){let r=Nn(t);await(n.length===0?e.delete(r):e.set(r,Fn(n)))}const Hn=/* @__PURE__ */ new WeakMap;function Un(e,t){let n=(Hn.get(e)??Promise.resolve()).then(t);return Hn.set(e,n.then(()=>{},()=>{})),n}function Wn(e,t,n,r){return Un(e,async()=>{let{hashes:i,writable:a,hasLegacy:o}=await Bn(e,t,n);if(!a)return;let s=r(i);(o||s.length!==i.length)&&await Vn(e,t,s),o&&await e.delete(Pn(t))})}async function Gn(e,t,n){return(await Un(e,()=>Bn(e,t,n))).hashes}function Kn(e,t,n,r){return Wn(e,t,r,e=>e.some(e=>Rn(e,n))?e:[...e,n])}function qn(e,t,n,r){return Wn(e,t,r,e=>e.filter(e=>!Rn(e,n)))}function Jn(e,t){let n=q(t);return gn(e.filter(e=>e.address===void 0||q(e.address)===n))?.unwrapRequestId}function Yn(e,t){if(!e)return`unknown`;let n=e.status===`reverted`?void 0:Jn(e.logs,t);return n===void 0?`settled`:{unwrapRequestId:n}}var Xn=class extends L{#e;#t=null;#n=null;#r(e){try{return qe(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new ye(e,{cause:t})}}async underlying(){return this.#m()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#m();this.#n=await this.sdk.provider.readContract(He(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#m();return this.sdk.provider.readContract(x(t,q(e),this.address))}async shield(e,t){let n=await w(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),i=await this.#m(),a=q(n.address),o;try{o=await this.sdk.provider.readContract(Re(i,a))}catch(e){throw e instanceof B?e:new R(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:z(e)})}if(o<e)throw new I(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${i})`,{requested:e,available:o,token:i});return r?this.#i(e,i,a,t):this.#a(e,a,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?q(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:rn(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await w(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#m(),i=q(n.address),a;try{a=await this.sdk.provider.readContract(Re(r,i))}catch(e){throw e instanceof B?e:new R(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:z(e)})}if(a<e)throw new I(`Insufficient ERC-20 balance: requested ${e}, available ${a} (token: ${r})`,{requested:e,available:a,token:r});let o;try{o=await this.sdk.provider.readContract(x(r,i,this.address))}catch(e){throw e instanceof B?e:new R(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:z(e)})}if(o<e)throw new ct(`Insufficient allowance for wrap: requested ${e}, approved ${o}. Call approveUnderlying() first (token: ${r}).`,{requested:e,available:o,token:r});let s=t?.to?q(t.to):i;return this.submitTransaction({operation:`wrap`,config:g(this.address,s,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#g(e,r===`max`,n);let i=n?.to?q(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:g(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await w(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#m(),r=q(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(x(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:C(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:C(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.#o(e,`unshield`,e=>this.#d(e));return _(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#h(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.#s(e=>this.#d(e));return _(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#h(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await Mn(this.sdk.provider,e)}catch(e){throw e instanceof B?e:new b(`Failed to get unwrap receipt`,{cause:e})}let r=Yn(n,this.address);if(r===`unknown`)throw new zt(`Unwrap transaction ${e} is not mined, so there is nothing to resume yet`,e);if(r===`settled`)throw await this.#p(`resumeUnshield`,e),new b(`Unwrap transaction ${e} reverted or opened no unwrap request from this wrapper, so there is nothing to resume`);let{unwrapRequestId:i}=r;if(await this.#u(i)===`settled`)throw await this.#p(`resumeUnshield`,e),new Vt(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:i});return await _(`resumeUnshield: savePendingUnshield`,()=>this.#d(e),this.sdk.logger),this.#h(i,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=null,t=await Gn(this.sdk.storage,this.address,this.sdk.logger);for(let n of t){let t=await this.#f(n);if(t===`open`)return n;t===`settled`?await this.#p(`getPendingUnshield`,n):e??=n}return e}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t,n){this.#r(`unwrap`);let r=await w(`unwrap`,this.sdk.signer,this.sdk.provider),i=q(r.address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i},{operation:t}),[s]=a;if(!s)throw new H(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:y(this.address,i,i,s,o),beforeReceipt:n});return{...c,unwrapRequestId:this.#l(c.receipt.logs)}}async unwrapAll(){return this.#s()}async#s(e){this.#r(`unwrapAll`);let t=await w(`unwrapAll`,this.sdk.signer,this.sdk.provider),n=q(t.address),r=await this.readConfidentialBalanceOf(n);if(F(r))throw new U(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:xe(this.address,n,n,r),beforeReceipt:e});return{...i,unwrapRequestId:this.#l(i.receipt.logs)}}async finalizeUnwrap(e){return this.#c(e,`finalize-unwrap`)}async#c(e,t){this.#r(`finalizeUnwrap`),await S(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let{value:n,decryptionProof:r}=await at(this.sdk.relayer,e,{operation:t});return this.submitTransaction({operation:`finalizeUnwrap`,config:Te(this.address,e,n,r)})}#l(e){let t=Jn(e,this.address);if(t===void 0)throw new b(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t}async#u(e){try{return await this.sdk.provider.readContract(Ce(this.address,e))===$t?`settled`:`open`}catch{return`unknown`}}#d(e){return Kn(this.sdk.storage,this.address,e,this.sdk.logger)}async#f(e){let t;try{t=await Mn(this.sdk.provider,e)}catch{return`unknown`}let n=Yn(t,this.address);return typeof n==`string`?n:this.#u(n.unwrapRequestId)}async#p(e,t){await _(`${e}: clearPendingUnshield`,()=>qn(this.sdk.storage,this.address,t,this.sdk.logger),this.sdk.logger)}async#m(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(me(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#h(e,t,n,r,i){this.emit({type:h.UnshieldPhase1Submitted,txHash:t,operationId:n}),this.emit({type:h.UnshieldPhase2Started,operationId:n}),_(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#c(e,i)}catch(n){throw Bt(n)||n instanceof b&&await this.#u(e)===`settled`?(await this.#p(`unshield`,t),new Vt(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:h.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),_(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#p(`unshield`,t),a}async#g(e,t,n){this.#r(`approveUnderlying`);let r=await this.#m(),i=await w(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=q(i.address),o=await this.sdk.provider.readContract(x(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:C(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:C(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};const Zn=J.union([J.bigint(),J.boolean(),a]),Qn=J.array(J.string());var $n=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=Zn.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=q(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${q(e)}:${q(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Qn.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function er(e,t){let n=tr(e,t);if(!n)throw new U(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function tr(e,t){let n=i(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const nr=e=>new Promise(t=>setTimeout(t,e));var rr=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=q(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=q(t),o=q(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:q(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:i?.operation},s))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof Je))throw t;await nr(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0,operation:o}){let s=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:q(e.contractAddress)}));if(s.length===0)return{items:s};let c=q(r);try{let e=await this.delegatedDecryptValues(s.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,c,{waitForPropagation:a,operation:o});for(let t of s)this.#d(t,e);return{items:s}}catch(e){if(It(e))throw e;if(s.length===1){let[n=this.#p()]=s;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:q(t)}),{items:s}}}let l=!1,u;if(await ut(s.map(e=>async()=>{if(!l)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,c,{waitForPropagation:!1,operation:o});this.#d(e,r)}catch(n){if(It(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:q(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=er(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&xt(e.message)&&await this.#t.evictTransportKeyPair(),e}let o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n,r={spent:!1}){if(e.length===0)return{};let i=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:q(e.contractAddress)})),a={},o=[];for(let e of i)F(e.encryptedValue)?a[e.encryptedValue]=0n:o.push(e);if(o.length===0)return a;let s=Array.from(new Set(i.map(e=>e.contractAddress))),c=Array.from(new Set(o.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(c)}catch(e){throw Tt(e)?this.#u(e,`the delegation pre-check`):e}let l=[];for(let e of o){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?l.push(e):a[e.encryptedValue]=n}if(l.length===0)return a;let u=await this.#t.grantPermit(s,t.delegator),d=/* @__PURE__ */ new Map;for(let e of l){let t=d.get(e.contractAddress);t?t.push(e.encryptedValue):d.set(e.contractAddress,[e.encryptedValue])}let f=[];for(let[e,t]of d)for(let n of ht(t))f.push({contractAddress:e,encryptedValues:n});let p=Date.now(),m=l.map(e=>e.encryptedValue);try{this.#i({type:h.DecryptStart,encryptedValues:m});try{await this.#c(t,u,f,a,n)}catch(e){if(!(e instanceof W)||r.spent)throw e;let i=u.permissions.map(e=>e.serializedPermit.signature);r.spent=!0;try{u=await this.#t.recoverPermits(s,t.delegator,i)}catch(e){throw e instanceof Pt?new W(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(t,u,f.filter(({encryptedValues:e})=>e.some(e=>a[e]===void 0)),a,n)}let e={};for(let t of m){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:h.DecryptEnd,durationMs:Date.now()-p,encryptedValues:m,result:e}),a}catch(e){let n=e instanceof B&&e.cause instanceof Error?e.cause:e;throw this.#i({type:h.DecryptError,error:z(n),durationMs:Date.now()-p,encryptedValues:m}),D(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await ut(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(a.length>0)throw a.find(e=>e instanceof W)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw D(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new U(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new U(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new Lt(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:vt(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new U(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`):e.value=n}#f(e,t,n){return e instanceof B?e:D(e,t,n)}#p(){throw new U(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};const ir={AlreadyDelegatedOrRevokedInSameBlock:e=>new et(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new rt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new it(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new T(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new E(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new $e(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new M(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new Xe(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new N(`Cannot revoke: no active delegation exists.`,{cause:e})};function ar(e){return Object.hasOwn(ir,e)}function or(e,t){let n=Rt(e);if(n&&ar(n))return ir[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(ir))if(r.includes(e))return n(t);return null}var sr=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new M(`Expiration date must be at least 1 hour in the future`);let a=q(t),o=q(n),s=q(r);if(o===s)throw new T(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===q(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new $e(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new E(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):X,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new Xe(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==q(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:an(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=q(t),a=q(n),o=q(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new N(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:on(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=q(e.contractAddress)===Z,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:Z})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:Z});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==X}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===X?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(sn(r,q(t),q(n),q(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await ft({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#c(e),e}}#c(e){if(!(e instanceof b))return;let t=or(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof N||t instanceof P){let n=q(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=q(e),i=q(t),a=q(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new N(`No active delegation from ${i} to ${a} for ${r}`):new P(`Delegation from ${i} to ${a} for ${r} has expired`)}},cr=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=q(e.contractAddress);try{this.#t({type:h.EncryptStart},r);let i=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:h.EncryptEnd,durationMs:Date.now()-n},r),i}catch(e){throw this.#t({type:h.EncryptError,error:z(e),durationMs:Date.now()-n},r),tn(e,`Encryption failed`)}}},lr=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.clearCredentialsOnWalletChange,this.#a=e.logger,this.#e&&(this.#s=this.#e.walletAccount.subscribe(e=>{this.#c(e).catch(e=>{this.#a.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#o.add(e),()=>{this.#o.delete(e)}}dispose(){this.#s?.(),this.#s=void 0,this.#o.clear()}async#c(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await _(`switch relayer chain`,()=>this.#t.switchChain(r),this.#a),this.#i&&await this.#l(t,n),await Promise.all(Array.from(this.#o,t=>_(`wallet account listener`,()=>t(e),this.#a)))}async#l(e,t){let n=this.#r;n&&await _(`credential wallet account change`,()=>n.handleWalletAccountChange(e,t),this.#a),e&&await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e.address),this.#a)}};const ur=J.object({kind:J.literal(`ConfidentialTransfer`),from:a,token:a,to:a,amount:J.bigint()}),dr=J.object({kind:J.literal(`ConfidentialTransferFrom`),from:a,token:a,owner:a,to:a,amount:J.bigint()}),fr=J.object({kind:J.literal(`SetOperator`),from:a,token:a,operator:a,until:u}),pr=J.object({kind:J.literal(`Unwrap`),from:a,token:a,to:a,amount:J.bigint()}),mr=J.object({kind:J.literal(`UnwrapAll`),from:a,token:a,to:a}),hr=J.object({kind:J.literal(`FinalizeUnwrap`),from:a,wrapper:a,unwrapRequestIdOrAmount:p}),gr=J.object({kind:J.literal(`ApproveUnderlying`),from:a,underlying:a,spender:a,amount:J.bigint()}),_r=J.object({kind:J.literal(`Wrap`),from:a,wrapper:a,to:a,amount:J.bigint()}),vr=p.check(J.refine(e=>e===`0x`||Qt(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),yr=J.object({kind:J.literal(`TransferAndCall`),from:a,underlying:a,wrapper:a,amount:J.bigint(),recipientData:J.optional(vr)}),br=J.object({kind:J.literal(`DelegateDecryption`),from:a,contractAddress:a,delegateAddress:a,expirationDate:J.optional(J.date())}),xr=J.object({kind:J.literal(`RevokeDelegation`),from:a,contractAddress:a,delegateAddress:a});J.discriminatedUnion(`kind`,[ur,dr,fr,pr,mr,hr,gr,_r,yr,br,xr]);const Sr=J.strictObject({maxFeePerGas:J.bigint(),maxPriorityFeePerGas:J.bigint()}),Cr=J.object({nonce:J.optional(J.int().check(J.nonnegative())),gasLimit:J.optional(J.bigint()),fees:J.optional(Sr)}),wr=J.object({address:a,abi:J.array(J.unknown()),functionName:J.string(),args:J.array(J.unknown()),value:J.optional(J.bigint()),gas:J.optional(J.bigint())}),Tr=J.extend(Cr,{from:a,calldata:wr});var Er=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=K(Cr,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new V(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i={calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees},a=K(Tr,i),o=await this.#e.prepareTransaction(a).catch(t=>{throw mt(t,`prepare ${e.kind}`)??t}),s=Zt(o),c=Yt({abi:a.calldata.abi,functionName:a.calldata.functionName,args:a.calldata.args});if(s.chainId!==r||!s.to||!Xt(s.to,a.calldata.address)||s.data?.toLowerCase()!==c.toLowerCase()||(s.value??0n)!==(a.calldata.value??0n))throw new V(`Offline.prepare: the provider returned a transaction that does not match the prepared ${e.kind} call on chain ${r}.`);return{kind:e.kind,unsignedTx:o,from:a.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new V(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=K(ur,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer`}),r=t[0];if(!r)throw new H(`Encryption returned no handles for ConfidentialTransfer`);return we(e.token,e.to,r,n)}async#a(e){e=K(dr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer-from`}),r=t[0];if(!r)throw new H(`Encryption returned no handles for ConfidentialTransferFrom`);return We(e.token,e.owner,e.to,r,n)}#o(e){return e=K(fr,e),Ie(e.token,e.operator,e.until)}async#s(e){e=K(pr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-unwrap`}),r=t[0];if(!r)throw new H(`Encryption returned no handles for Unwrap`);return y(e.token,e.from,e.to,r,n)}async#c(e){e=K(mr,e);let t=await this.#e.readContract(Ke(e.token,e.from));return xe(e.token,e.from,e.to,t)}async#l(e){e=K(hr,e);let{value:t,decryptionProof:n}=await at(this.#t.relayer,e.unwrapRequestIdOrAmount,{operation:`offline-finalize-unwrap`});return Te(e.wrapper,e.unwrapRequestIdOrAmount,t,n)}#u(e){return e=K(gr,e),C(e.underlying,e.spender,e.amount)}#d(e){return e=K(_r,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=K(yr,e),rn(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=K(br,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new M(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new T(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new E(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):X;return an(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=K(xr,e),on(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Dr(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new V(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function Or(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new V(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function kr(e){if(e===void 0)return;let t=K(l,e);return new ne(typeof t==`string`?t:new Uint8Array(t))}var Ar=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Dr(t),Or(t.transportKeyPairDerivationSecret);let n=kr(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new $n(e.storage,this.#i),this.#u=new sr({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new f({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new ee({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new rr({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new cr({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new lr({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new Er({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new En({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new Dn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new On({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new kn(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}get chains(){return this.#e.chains}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new f({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,G(t,`encrypt`))}createToken(e){return new L(this,e)}createWrappedToken(e){return new Xn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{Tn as ACL_TOPICS,it as AclPausedError,$ as AclTopics,dt as BalanceCheckUnavailableError,te as BaseSigner,Be as ChainMismatchError,An as ChromeSessionStorage,V as ConfigurationError,On as Decryption,U as DecryptionFailedError,n as DefaultRegistryAddresses,rt as DelegationContractIsSelfError,et as DelegationCooldownError,$e as DelegationDelegateCannotBeWildcardError,E as DelegationDelegateEqualsContractError,M as DelegationExpirationTooSoonError,P as DelegationExpiredError,Xe as DelegationExpiryUnchangedError,N as DelegationNotFoundError,Je as DelegationNotPropagatedError,T as DelegationSelfNotAllowedError,Dn as Delegations,Ae as ERC1363_INTERFACE_ID,R as ERC20ReadFailedError,ze as ERC7984_INTERFACE_ID,Ve as ERC7984_WRAPPER_INTERFACE_ID,Et as EncryptOffloadUnavailableError,H as EncryptionFailedError,be as HcuBlockLimitExceededError,Oe as HcuTransactionLimitExceededError,t as IndexedDBStorage,ct as InsufficientAllowanceError,lt as InsufficientConfidentialBalanceError,I as InsufficientERC20BalanceError,At as InvalidTransportKeyPairError,Dt as KeyWrappingError,X as MAX_UINT64,s as MemoryStorage,d as MutableWalletAccountStore,Mt as NoCiphertextError,st as NotEntitledError,kn as Offline,En as Permits,Nt as PreparedPermitChainMismatchError,Ot as PreparedPermitExpiredError,St as RelayerRequestFailedError,W as RevokedKmsContextError,Lt as RpcRateLimitError,ye as SignerNotConfiguredError,Ee as SignerRequiredError,Pt as SigningFailedError,jt as SigningRejectedError,vn as TOKEN_TOPICS,L as Token,Q as Topics,b as TransactionRevertedError,Ft as TransportKeyPairChangedError,kt as TransportKeyPairExpiredError,Vt as UnshieldAlreadyFinalizedError,zt as UnwrapNotMinedError,nt as VaultBatchNotDispatchedError,ot as VaultBatcherPausedError,Ze as VaultBatcherReadFailedError,Qe as VaultJoinUnconfirmedError,Z as WILDCARD_CONTRACT,De as WalletAccountNotReadyError,ve as WalletNotConnectedError,Xn as WrappedToken,f as WrappersRegistry,pt as ZERO_ENCRYPTED_VALUE,B as ZamaError,bt as ZamaErrorCode,Ar as ZamaSDK,h as ZamaSDKEvents,x as allowanceContract,fe as anvil,C as approveContract,Re as balanceOfContract,ce as bscTestnet,ue as chains,jn as chromeSessionStorage,e as cleartext,Ke as confidentialBalanceOfContract,je as confidentialTotalSupplyContract,Ge as confidentialTransferAndCallContract,we as confidentialTransferContract,he as confidentialTransferFromAndCallContract,We as confidentialTransferFromContract,ln as createConfig,m as createWalletAccountStore,Pe as decimalsContract,xn as decodeAclEvent,Sn as decodeAclEvents,un as decodeConfidentialTransfer,yn as decodeDelegatedForUserDecryption,mn as decodeOnChainEvent,hn as decodeOnChainEvents,bn as decodeRevokedDelegationForUserDecryption,pn as decodeUnwrapFinalized,fn as decodeUnwrapRequested,dn as decodeWrap,an as delegateForUserDecryptionContract,Te as finalizeUnwrapContract,Cn as findDelegatedForUserDecryption,wn as findRevokedDelegationForUserDecryption,gn as findUnwrapRequested,_n as findWrap,Jt as getConfidentialTokenAddressContract,sn as getDelegationExpiryContract,Wt as getTokenAddressContract,Kt as getTokenPairContract,Ut as getTokenPairsContract,Ht as getTokenPairsLengthContract,Gt as getTokenPairsSliceContract,oe as hardhat,ie as hoodi,re as indexedDBStorage,_e as inferredTotalSupplyContract,Me as isConfidentialTokenContract,qt as isConfidentialTokenValidContract,Le as isConfidentialWrapperContract,F as isEncryptedValueZero,cn as isHandleDelegatedContract,ge as isOperatorContract,_t as isRetryable,le as mainnet,en as matchZamaError,o as memoryStorage,ke as nameContract,r as parsePreparedPermit,de as polygon,ae as polygonAmoy,Se as rateContract,Ct as retryAfterSeconds,on as revokeDelegationContract,se as sepolia,Ie as setOperatorContract,Ne as supportsInterfaceContract,Ue as symbolContract,rn as transferAndCallContract,me as underlyingContract,Fe as unwrapAmountContract,y as unwrapContract,xe as unwrapFromBalanceContract,Ce as unwrapRequesterContract,g as wrapContract,pe as zenithTrexTestnet};
1
+ import{t as e}from"./cleartext-Dt_G8a-Y.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as ee,t as te,u as ne,v as re,y as ie}from"./base-signer-DUflPI8d.js";import{a as ae,c as oe,i as se,l as ce,n as le,o as ue,r as de,s as fe,t as pe,u as me}from"./configs-9EL-DJHq.js";import{A as he,B as h,C as ge,D as _e,E as ve,F as g,G as ye,H as be,I as _,J as xe,K as v,M as y,N as b,O as Se,P as Ce,S as we,T as x,U as Te,W as Ee,X as S,Y as De,_ as Oe,a as ke,b as Ae,c as je,d as Me,f as C,h as Ne,j as Pe,k as Fe,l as Ie,m as Le,n as w,o as Re,p as T,q as ze,s as Be,t as E,u as Ve,v as He,w as Ue,x as We,y as Ge,z as Ke}from"./alignment-D1cVCzw8.js";import{C as D,S as qe,_ as O,a as Je,b as Ye,c as k,d as Xe,f as Ze,g as Qe,h as $e,i as et,l as tt,m as nt,n as A,o as j,p as rt,r as M,s as N,t as it,u as at,v as P,w as ot,x as F,y as st}from"./public-decrypt-Bec9uoNY.js";import{c as ct,d as lt,f as ut,i as dt,l as ft,n as pt,o as mt,p as ht,r as gt,s as _t,t as vt,u as I}from"./token-DnriE-3y.js";import{C as L,_ as yt,a as bt,c as xt,g as St,i as Ct,m as wt,n as Tt,o as Et,r as R,s as Dt,t as z,y as Ot}from"./relayer-Cki3j_Ba.js";import{n as kt,r as B,t as V}from"./encryption-QHaWnnx-.js";import{a as At,c as jt,d as Mt,i as Nt,l as H,n as Pt,o as Ft,s as It,t as Lt,u as Rt}from"./signing-DX-xyved.js";import{n as zt,r as Bt}from"./fatal-batch-CI0ESPnd.js";import{i as Vt,n as Ht,r as Ut,t as U}from"./unshield-xO66p_da.js";import{r as W}from"./telemetry-DgZG8yT6.js";import{t as G}from"./validation-BLmG7UVk.js";import{a as Wt,i as Gt,n as Kt,o as qt,r as Jt,s as Yt,t as Xt}from"./wrappers-registry-Cm3JJeqx.js";import{encodeFunctionData as Zt,getAddress as K,isAddressEqual as Qt,parseTransaction as $t,size as en,toBytes as tn,toHex as nn,zeroAddress as rn}from"viem";import{z as q}from"zod/mini";function an(e,t){if(e instanceof R){let n=t[e.code];if(n)return n(e)}return t._?.(e)}function on(e,t){if(e instanceof R)return e;let n=Dt(e),r=yt(e);return n!==void 0||St(e)?new Tt(e instanceof Error?e.message:t,n,{cause:e,retryAfter:xt(e),retryable:r||void 0}):new B(t,{cause:e})}const sn=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function cn(e,t,n,r=`0x`){return{address:e,abi:sn,functionName:`transferAndCall`,args:[t,n,r]}}const J=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function ln(e,t,n,r){return{address:e,abi:J,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function un(e,t,n){return{address:e,abi:J,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function dn(e,t,n,r){return{address:e,abi:J,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function fn(e,t,n,r,i){return{address:e,abi:J,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const Y=2n**64n-1n,X=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function pn(e){return c(e.signer,e.provider,e)}const Z={ConfidentialTransfer:A(`ConfidentialTransfer(address,address,bytes32)`),Wrap:A(`Wrap(address,uint256,bytes32)`),UnwrapRequested:A(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:A(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function mn(e){return e.topics[0]!==Z.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:M(e.topics[1]),to:M(e.topics[2]),encryptedAmount:et(e.topics[3])}}function Q(e){return e.topics[0]!==Z.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:M(e.topics[1]),roundedAmount:j(e.data,0),encryptedWrappedAmount:N(e.data,1)}}function hn(e){return e.topics[0]!==Z.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:M(e.topics[1]),unwrapRequestId:et(e.topics[2]),encryptedAmount:N(e.data,0)}}function gn(e){return e.topics[0]!==Z.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:M(e.topics[1]),unwrapRequestId:et(e.topics[2]),encryptedAmount:N(e.data,0),cleartextAmount:j(e.data,1)}}function _n(e){return mn(e)??Q(e)??hn(e)??gn(e)}function vn(e){let t=[];for(let n of e){let e=_n(n);e&&t.push(e)}return t}function yn(e){for(let t of e){let e=hn(t);if(e)return e}return null}function bn(e){for(let t of e){let e=Q(t);if(e)return e}return null}const xn=[Z.ConfidentialTransfer,Z.Wrap,Z.UnwrapRequested,Z.UnwrapFinalized],$={DelegatedForUserDecryption:A(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:A(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function Sn(e){return e.topics[0]!==$.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:M(e.topics[1]),delegate:M(e.topics[2]),contractAddress:Je(e.data,0),delegationCounter:j(e.data,1),oldExpirationDate:j(e.data,2),newExpirationDate:j(e.data,3)}}function Cn(e){return e.topics[0]!==$.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:M(e.topics[1]),delegate:M(e.topics[2]),contractAddress:Je(e.data,0),delegationCounter:j(e.data,1),oldExpirationDate:j(e.data,2)}}function wn(e){return Sn(e)??Cn(e)}function Tn(e){let t=[];for(let n of e){let e=wn(n);e&&t.push(e)}return t}function En(e){for(let t of e){let e=Sn(t);if(e)return e}return null}function Dn(e){for(let t of e){let e=Cn(t);if(e)return e}return null}const On=[$.DelegatedForUserDecryption,$.RevokedDelegationForUserDecryption];var kn=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return v(this.#r,e)}#s(e,t){throw this.#a({type:h.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await w(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await w(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}registerPermit(e,t){return this.batchRegisterPermits([{prepared:e,signature:t}])}async batchRegisterPermits(e){let t;try{t=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await t.batchRegisterPermits(e),await Promise.all([...new Set(e.map(e=>e.prepared.signerAddress))].map(e=>this.#c(e)))}async revokePermits(e){let t=this.#o(`revokePermits`),n=await E(`revokePermits`,this.#e,this.#t),r=K(n.address);try{await t.revokePermits(e)}finally{await this.#c(r)}}async clear(){let e=this.#o(`clear`),t=await E(`clear`,this.#e,this.#t),n=K(t.address);try{await e.clearCredentials()}finally{await this.#c(n)}}async#c(e){await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},An=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return v(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await E(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await E(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},jn=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return v(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await E(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,W(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await E(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,W(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=W(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{Ke(t.clearValues[n],`result.clearValues[${n}]`),r[e]=t.clearValues[n].value}),{clearValues:r,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw k(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i,operation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await E(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i,operation:a??`delegated-batch-decrypt-values`})}},Mn=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}batchPreparePermits(e){return this.#t.batchPreparePermits(e)}},Nn=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 Pn=new Nn;async function Fn(e,t){if(e.getTransactionReceipt)return e.getTransactionReceipt(t);let n,r=new Promise(e=>{n=setTimeout(()=>e(null),5e3)});try{return await Promise.race([e.waitForTransactionReceipt(t),r])}finally{clearTimeout(n)}}function In(e){return`zama:pending-unshields:${a(e)}`}function Ln(e){return`zama:pending-unshield:${a(e)}`}function Rn(e){return{version:2,unwrapTxHashes:e}}const zn=q.union([u,q.pipe(q.object({version:q.literal(1),unwrapTxHash:u}),q.transform(({unwrapTxHash:e})=>e))]),Bn=q.object({version:q.number(),unwrapTxHashes:q.optional(q.unknown())}),Vn=(e,t)=>e.toLowerCase()===t.toLowerCase();async function Hn(e,t,n){let r=await e.get(t);if(r==null)return{hashes:[],writable:!0};let i=Bn.safeParse(r);if(i.success&&i.data.version!==2)return n?.warn(`pending unshields saved by an unknown SDK version were left as is`,{version:i.data.version}),{hashes:[],writable:!1};let a=i.success?i.data.unwrapTxHashes:void 0;if(!Array.isArray(a))return n?.warn(`unreadable pending unshields were dropped`,{value:r}),{hashes:[],writable:!0};let o=a.filter(e=>u.safeParse(e).success);return o.length!==a.length&&n?.warn(`unreadable pending unshield entries were dropped`,{unwrapTxHashes:a}),{hashes:o,writable:!0}}async function Un(e,t,n){let r=await Hn(e,In(t),n),i=zn.safeParse(await e.get(Ln(t)));return!i.success||!r.writable?{...r,hasLegacy:!1}:{hashes:r.hashes.some(e=>Vn(e,i.data))?r.hashes:[i.data,...r.hashes],writable:!0,hasLegacy:!0}}async function Wn(e,t,n){let r=In(t);await(n.length===0?e.delete(r):e.set(r,Rn(n)))}const Gn=/* @__PURE__ */ new WeakMap;function Kn(e,t){let n=(Gn.get(e)??Promise.resolve()).then(t);return Gn.set(e,n.then(()=>{},()=>{})),n}function qn(e,t,n,r){return Kn(e,async()=>{let{hashes:i,writable:a,hasLegacy:o}=await Un(e,t,n);if(!a)return;let s=r(i);(o||s.length!==i.length)&&await Wn(e,t,s),o&&await e.delete(Ln(t))})}async function Jn(e,t,n){return(await Kn(e,()=>Un(e,t,n))).hashes}function Yn(e,t,n,r){return qn(e,t,r,e=>e.some(e=>Vn(e,n))?e:[...e,n])}function Xn(e,t,n,r){return qn(e,t,r,e=>e.filter(e=>!Vn(e,n)))}function Zn(e,t){let n=K(t);return yn(e.filter(e=>e.address===void 0||K(e.address)===n))?.unwrapRequestId}function Qn(e,t){if(!e)return`unknown`;let n=e.status===`reverted`?void 0:Zn(e.logs,t);return n===void 0?`settled`:{unwrapRequestId:n}}var $n=class extends vt{#e;#t=null;#n=null;#r(e){try{return Ke(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new be(e,{cause:t})}}async underlying(){return this.#m()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#m();this.#n=await this.sdk.provider.readContract(Ve(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#m();return this.sdk.provider.readContract(C(t,K(e),this.address))}async shield(e,t){let n=await E(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),i=await this.#m(),a=K(n.address),o;try{o=await this.sdk.provider.readContract(Le(i,a))}catch(e){throw e instanceof R?e:new I(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:L(e)})}if(o<e)throw new ht(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${i})`,{requested:e,available:o,token:i});return r?this.#i(e,i,a,t):this.#a(e,a,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?K(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:cn(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await E(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#m(),i=K(n.address),a;try{a=await this.sdk.provider.readContract(Le(r,i))}catch(e){throw e instanceof R?e:new I(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:L(e)})}if(a<e)throw new ht(`Insufficient ERC-20 balance: requested ${e}, available ${a} (token: ${r})`,{requested:e,available:a,token:r});let o;try{o=await this.sdk.provider.readContract(C(r,i,this.address))}catch(e){throw e instanceof R?e:new I(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:L(e)})}if(o<e)throw new lt(`Insufficient allowance for wrap: requested ${e}, approved ${o}. Call approveUnderlying() first (token: ${r}).`,{requested:e,available:o,token:r});let s=t?.to?K(t.to):i;return this.submitTransaction({operation:`wrap`,config:g(this.address,s,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#g(e,r===`max`,n);let i=n?.to?K(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:g(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await E(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#m(),r=K(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(C(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:T(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:T(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.#o(e,`unshield`,e=>this.#d(e));return _(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#h(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.#s(e=>this.#d(e));return _(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#h(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await Fn(this.sdk.provider,e)}catch(e){throw e instanceof R?e:new S(`Failed to get unwrap receipt`,{cause:e})}let r=Qn(n,this.address);if(r===`unknown`)throw new Ht(`Unwrap transaction ${e} is not mined, so there is nothing to resume yet`,e);if(r===`settled`)throw await this.#p(`resumeUnshield`,e),new S(`Unwrap transaction ${e} reverted or opened no unwrap request from this wrapper, so there is nothing to resume`);let{unwrapRequestId:i}=r;if(await this.#u(i)===`settled`)throw await this.#p(`resumeUnshield`,e),new U(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:i});return await _(`resumeUnshield: savePendingUnshield`,()=>this.#d(e),this.sdk.logger),this.#h(i,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=null,t=await Jn(this.sdk.storage,this.address,this.sdk.logger);for(let n of t){let t=await this.#f(n);if(t===`open`)return n;t===`settled`?await this.#p(`getPendingUnshield`,n):e??=n}return e}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t,n){this.#r(`unwrap`);let r=await E(`unwrap`,this.sdk.signer,this.sdk.provider),i=K(r.address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i},{operation:t}),[s]=a;if(!s)throw new B(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:y(this.address,i,i,s,o),beforeReceipt:n});return{...c,unwrapRequestId:this.#l(c.receipt.logs)}}async unwrapAll(){return this.#s()}async#s(e){this.#r(`unwrapAll`);let t=await E(`unwrapAll`,this.sdk.signer,this.sdk.provider),n=K(t.address),r=await this.readConfidentialBalanceOf(n);if(ct(r))throw new V(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:b(this.address,n,n,r),beforeReceipt:e});return{...i,unwrapRequestId:this.#l(i.receipt.logs)}}async finalizeUnwrap(e){return this.#c(e,`finalize-unwrap`)}async#c(e,t){this.#r(`finalizeUnwrap`),await w(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let{value:n,decryptionProof:r}=await it(this.sdk.relayer,e,{operation:t});return this.submitTransaction({operation:`finalizeUnwrap`,config:x(this.address,e,n,r)})}#l(e){let t=Zn(e,this.address);if(t===void 0)throw new S(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t}async#u(e){try{return await this.sdk.provider.readContract(Ce(this.address,e))===rn?`settled`:`open`}catch{return`unknown`}}#d(e){return Yn(this.sdk.storage,this.address,e,this.sdk.logger)}async#f(e){let t;try{t=await Fn(this.sdk.provider,e)}catch{return`unknown`}let n=Qn(t,this.address);return typeof n==`string`?n:this.#u(n.unwrapRequestId)}async#p(e,t){await _(`${e}: clearPendingUnshield`,()=>Xn(this.sdk.storage,this.address,t,this.sdk.logger),this.sdk.logger)}async#m(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(he(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#h(e,t,n,r,i){this.emit({type:h.UnshieldPhase1Submitted,txHash:t,operationId:n}),this.emit({type:h.UnshieldPhase2Started,operationId:n}),_(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#c(e,i)}catch(n){throw Ut(n)||n instanceof S&&await this.#u(e)===`settled`?(await this.#p(`unshield`,t),new U(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:h.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),_(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#p(`unshield`,t),a}async#g(e,t,n){this.#r(`approveUnderlying`);let r=await this.#m(),i=await E(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=K(i.address),o=await this.sdk.provider.readContract(C(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:T(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:T(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};const er=q.union([q.bigint(),q.boolean(),p]),tr=q.object({value:er,tag:u}),nr=q.array(q.string()),rr={encode:async(e,t)=>t,decode:async(e,t)=>er.safeParse(t).data??null};function ir(e,t){return new TextEncoder().encode(JSON.stringify([e,typeof t,String(t)]))}function ar(e){let t,n=()=>t??=i(e);return{async encode(e,t){let r=await crypto.subtle.sign(`HMAC`,await n(),ir(e,t));return{value:t,tag:nn(new Uint8Array(r))}},async decode(e,t){let r=tr.safeParse(t);if(!r.success)return null;let{value:i,tag:a}=r.data;return await crypto.subtle.verify(`HMAC`,await n(),new Uint8Array(tn(a)),ir(e,i))?i:null}}}var or=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i;#a=Promise.resolve();constructor(e,t,n){this.#e=e,this.#t=t,this.#i=n?ar(n):rr}async get(e,t,n){try{let r=this.#l(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=await this.#i.decode(r,i);return a===null&&await this.delete(e,t,n),a}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#l(e,t,n);await this.#e.set(i,await this.#i.encode(i,er.parse(r))),this.#a=this.#a.then(()=>this.#d(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#a}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#l(e,t,n);this.#a=this.#a.then(()=>this.#o(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#a}async clearForRequester(e){this.#a=this.#a.then(()=>this.#s(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#a}async clearAll(){this.#a=this.#a.then(()=>this.#c().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#a}async#o(e){await this.#e.delete(e).catch(()=>{});let t=await this.#u(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#s(e){let t=K(e),n=`${this.#n}:${t}:`,r=await this.#u(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#c(){let e=await this.#u();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#l(e,t,n){return`${this.#n}:${K(e)}:${K(t)}:${n.toLowerCase()}`}async#u(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=nr.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#d(e){let t=await this.#u();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function sr(e,t){let n=cr(e,t);if(!n)throw new V(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function cr(e,t){let n=a(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const lr=e=>new Promise(t=>setTimeout(t,e));var ur=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=K(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=K(t),o=K(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:K(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:i?.operation},s))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof qe))throw t;await lr(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0,operation:o}){let s=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:K(e.contractAddress)}));if(s.length===0)return{items:s};let c=K(r);try{let e=await this.delegatedDecryptValues(s.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,c,{waitForPropagation:a,operation:o});for(let t of s)this.#d(t,e);return{items:s}}catch(e){if(zt(e))throw e;if(s.length===1){let[n=this.#p()]=s;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:K(t)}),{items:s}}}let l=!1,u;if(await dt(s.map(e=>async()=>{if(!l)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,c,{waitForPropagation:!1,operation:o});this.#d(e,r)}catch(n){if(zt(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:K(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=sr(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&wt(e.message)&&await this.#t.evictTransportKeyPair(),e}let o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n,r={spent:!1}){if(e.length===0)return{};let i=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:K(e.contractAddress)})),a={},o=[];for(let e of i)ct(e.encryptedValue)?a[e.encryptedValue]=0n:o.push(e);if(o.length===0)return a;let s=Array.from(new Set(i.map(e=>e.contractAddress))),c=Array.from(new Set(o.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(c)}catch(e){throw Ot(e)?this.#u(e,`the delegation pre-check`):e}let l=[];for(let e of o){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?l.push(e):a[e.encryptedValue]=n}if(l.length===0)return a;let u=await this.#t.grantPermit(s,t.delegator),d=/* @__PURE__ */ new Map;for(let e of l){let t=d.get(e.contractAddress);t?t.push(e.encryptedValue):d.set(e.contractAddress,[e.encryptedValue])}let f=[];for(let[e,t]of d)for(let n of _t(t))f.push({contractAddress:e,encryptedValues:n});let p=Date.now(),m=l.map(e=>e.encryptedValue);try{this.#i({type:h.DecryptStart,encryptedValues:m});try{await this.#c(t,u,f,a,n)}catch(e){if(!(e instanceof H)||r.spent)throw e;let i=u.permissions.map(e=>e.serializedPermit.signature);r.spent=!0;try{u=await this.#t.recoverPermits(s,t.delegator,i)}catch(e){throw e instanceof Lt?new H(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(t,u,f.filter(({encryptedValues:e})=>e.some(e=>a[e]===void 0)),a,n)}let e={};for(let t of m){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:h.DecryptEnd,durationMs:Date.now()-p,encryptedValues:m,result:e}),a}catch(e){let n=e instanceof R&&e.cause instanceof Error?e.cause:e;throw this.#i({type:h.DecryptError,error:L(n),durationMs:Date.now()-p,encryptedValues:m}),k(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await dt(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(a.length>0)throw a.find(e=>e instanceof H)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw k(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new V(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new V(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new Bt(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:xt(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new V(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`):e.value=n}#f(e,t,n){return e instanceof R?e:k(e,t,n)}#p(){throw new V(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};const dr={AlreadyDelegatedOrRevokedInSameBlock:e=>new $e(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new nt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new rt(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new D(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new O(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new Qe(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new P(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new Ye(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new F(`Cannot revoke: no active delegation exists.`,{cause:e})};function fr(e){return Object.hasOwn(dr,e)}function pr(e,t){let n=Vt(e);if(n&&fr(n))return dr[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(dr))if(r.includes(e))return n(t);return null}var mr=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new P(`Expiration date must be at least 1 hour in the future`);let a=K(t),o=K(n),s=K(r);if(o===s)throw new D(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===K(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new Qe(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new O(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):Y,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new Ye(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==K(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:ln(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=K(t),a=K(n),o=K(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new F(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:un(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=K(e.contractAddress)===X,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:X})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:X});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==Y}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===Y?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(dn(r,K(t),K(n),K(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await pt({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#c(e),e}}#c(e){if(!(e instanceof S))return;let t=pr(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof F||t instanceof st){let n=K(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=K(e),i=K(t),a=K(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new F(`No active delegation from ${i} to ${a} for ${r}`):new st(`Delegation from ${i} to ${a} for ${r} has expired`)}},hr=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=K(e.contractAddress);try{this.#t({type:h.EncryptStart},r);let i=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:h.EncryptEnd,durationMs:Date.now()-n},r),i}catch(e){throw this.#t({type:h.EncryptError,error:L(e),durationMs:Date.now()-n},r),on(e,`Encryption failed`)}}},gr=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.clearCredentialsOnWalletChange,this.#a=e.logger,this.#e&&(this.#s=this.#e.walletAccount.subscribe(e=>{this.#c(e).catch(e=>{this.#a.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#o.add(e),()=>{this.#o.delete(e)}}dispose(){this.#s?.(),this.#s=void 0,this.#o.clear()}async#c(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await _(`switch relayer chain`,()=>this.#t.switchChain(r),this.#a),this.#i&&await this.#l(t,n),await Promise.all(Array.from(this.#o,t=>_(`wallet account listener`,()=>t(e),this.#a)))}async#l(e,t){let n=this.#r;n&&await _(`credential wallet account change`,()=>n.handleWalletAccountChange(e,t),this.#a),e&&await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e.address),this.#a)}};const _r=q.object({kind:q.literal(`ConfidentialTransfer`),from:p,token:p,to:p,amount:q.bigint()}),vr=q.object({kind:q.literal(`ConfidentialTransferFrom`),from:p,token:p,owner:p,to:p,amount:q.bigint()}),yr=q.object({kind:q.literal(`SetOperator`),from:p,token:p,operator:p,until:s}),br=q.object({kind:q.literal(`Unwrap`),from:p,token:p,to:p,amount:q.bigint()}),xr=q.object({kind:q.literal(`UnwrapAll`),from:p,token:p,to:p}),Sr=q.object({kind:q.literal(`FinalizeUnwrap`),from:p,wrapper:p,unwrapRequestIdOrAmount:u}),Cr=q.object({kind:q.literal(`ApproveUnderlying`),from:p,underlying:p,spender:p,amount:q.bigint()}),wr=q.object({kind:q.literal(`Wrap`),from:p,wrapper:p,to:p,amount:q.bigint()}),Tr=u.check(q.refine(e=>e===`0x`||en(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),Er=q.object({kind:q.literal(`TransferAndCall`),from:p,underlying:p,wrapper:p,amount:q.bigint(),recipientData:q.optional(Tr)}),Dr=q.object({kind:q.literal(`DelegateDecryption`),from:p,contractAddress:p,delegateAddress:p,expirationDate:q.optional(q.date())}),Or=q.object({kind:q.literal(`RevokeDelegation`),from:p,contractAddress:p,delegateAddress:p});q.discriminatedUnion(`kind`,[_r,vr,yr,br,xr,Sr,Cr,wr,Er,Dr,Or]);const kr=q.strictObject({maxFeePerGas:q.bigint(),maxPriorityFeePerGas:q.bigint()}),Ar=q.object({nonce:q.optional(q.int().check(q.nonnegative())),gasLimit:q.optional(q.bigint()),fees:q.optional(kr)}),jr=q.object({address:p,abi:q.array(q.unknown()),functionName:q.string(),args:q.array(q.unknown()),value:q.optional(q.bigint()),gas:q.optional(q.bigint())}),Mr=q.extend(Ar,{from:p,calldata:jr});var Nr=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=G(Ar,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new z(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i={calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees},a=G(Mr,i),o=await this.#e.prepareTransaction(a).catch(t=>{throw gt(t,`prepare ${e.kind}`)??t}),s=$t(o),c=Zt({abi:a.calldata.abi,functionName:a.calldata.functionName,args:a.calldata.args});if(s.chainId!==r||!s.to||!Qt(s.to,a.calldata.address)||s.data?.toLowerCase()!==c.toLowerCase()||(s.value??0n)!==(a.calldata.value??0n))throw new z(`Offline.prepare: the provider returned a transaction that does not match the prepared ${e.kind} call on chain ${r}.`);return{kind:e.kind,unsignedTx:o,from:a.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new z(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=G(_r,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer`}),r=t[0];if(!r)throw new B(`Encryption returned no handles for ConfidentialTransfer`);return we(e.token,e.to,r,n)}async#a(e){e=G(vr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer-from`}),r=t[0];if(!r)throw new B(`Encryption returned no handles for ConfidentialTransferFrom`);return Ue(e.token,e.owner,e.to,r,n)}#o(e){return e=G(yr,e),Fe(e.token,e.operator,e.until)}async#s(e){e=G(br,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-unwrap`}),r=t[0];if(!r)throw new B(`Encryption returned no handles for Unwrap`);return y(e.token,e.from,e.to,r,n)}async#c(e){e=G(xr,e);let t=await this.#e.readContract(Ge(e.token,e.from));return b(e.token,e.from,e.to,t)}async#l(e){e=G(Sr,e);let{value:t,decryptionProof:n}=await it(this.#t.relayer,e.unwrapRequestIdOrAmount,{operation:`offline-finalize-unwrap`});return x(e.wrapper,e.unwrapRequestIdOrAmount,t,n)}#u(e){return e=G(Cr,e),T(e.underlying,e.spender,e.amount)}#d(e){return e=G(wr,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=G(Er,e),cn(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=G(Dr,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new P(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new D(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new O(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):Y;return ln(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=G(Or,e),un(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Pr(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new z(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function Fr(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new z(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function Ir(e){if(e===void 0)return;let t=G(l,e);return new ne(typeof t==`string`?t:new Uint8Array(t))}var Lr=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Pr(t),Fr(t.transportKeyPairDerivationSecret);let n=Ir(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new or(e.storage,this.#i,n),this.#u=new mr({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new f({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new ee({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new ur({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new hr({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new gr({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new Nr({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new kn({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new An({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new jn({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new Mn(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}get chains(){return this.#e.chains}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new f({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,W(t,`encrypt`))}createToken(e){return new vt(this,e)}createWrappedToken(e){return new $n(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{On as ACL_TOPICS,rt as AclPausedError,$ as AclTopics,ft as BalanceCheckUnavailableError,te as BaseSigner,ze as ChainMismatchError,Nn as ChromeSessionStorage,z as ConfigurationError,jn as Decryption,V as DecryptionFailedError,n as DefaultRegistryAddresses,nt as DelegationContractIsSelfError,$e as DelegationCooldownError,Qe as DelegationDelegateCannotBeWildcardError,O as DelegationDelegateEqualsContractError,P as DelegationExpirationTooSoonError,st as DelegationExpiredError,Ye as DelegationExpiryUnchangedError,F as DelegationNotFoundError,qe as DelegationNotPropagatedError,D as DelegationSelfNotAllowedError,An as Delegations,ke as ERC1363_INTERFACE_ID,I as ERC20ReadFailedError,Re as ERC7984_INTERFACE_ID,Be as ERC7984_WRAPPER_INTERFACE_ID,kt as EncryptOffloadUnavailableError,B as EncryptionFailedError,xe as HcuBlockLimitExceededError,De as HcuTransactionLimitExceededError,re as IndexedDBStorage,lt as InsufficientAllowanceError,ut as InsufficientConfidentialBalanceError,ht as InsufficientERC20BalanceError,Nt as InvalidTransportKeyPairError,At as KeyWrappingError,Y as MAX_UINT64,o as MemoryStorage,d as MutableWalletAccountStore,Ft as NoCiphertextError,ot as NotEntitledError,Mn as Offline,kn as Permits,It as PreparedPermitChainMismatchError,jt as PreparedPermitExpiredError,Tt as RelayerRequestFailedError,H as RevokedKmsContextError,Bt as RpcRateLimitError,be as SignerNotConfiguredError,Te as SignerRequiredError,Lt as SigningFailedError,Pt as SigningRejectedError,xn as TOKEN_TOPICS,vt as Token,Z as Topics,S as TransactionRevertedError,Rt as TransportKeyPairChangedError,Mt as TransportKeyPairExpiredError,U as UnshieldAlreadyFinalizedError,Ht as UnwrapNotMinedError,tt as VaultBatchNotDispatchedError,at as VaultBatcherPausedError,Xe as VaultBatcherReadFailedError,Ze as VaultJoinUnconfirmedError,X as WILDCARD_CONTRACT,Ee as WalletAccountNotReadyError,ye as WalletNotConnectedError,$n as WrappedToken,f as WrappersRegistry,mt as ZERO_ENCRYPTED_VALUE,R as ZamaError,Ct as ZamaErrorCode,Lr as ZamaSDK,h as ZamaSDKEvents,C as allowanceContract,pe as anvil,T as approveContract,Le as balanceOfContract,le as bscTestnet,de as chains,Pn as chromeSessionStorage,e as cleartext,Ge as confidentialBalanceOfContract,Ae as confidentialTotalSupplyContract,We as confidentialTransferAndCallContract,we as confidentialTransferContract,ge as confidentialTransferFromAndCallContract,Ue as confidentialTransferFromContract,pn as createConfig,m as createWalletAccountStore,Ne as decimalsContract,wn as decodeAclEvent,Tn as decodeAclEvents,mn as decodeConfidentialTransfer,Sn as decodeDelegatedForUserDecryption,_n as decodeOnChainEvent,vn as decodeOnChainEvents,Cn as decodeRevokedDelegationForUserDecryption,gn as decodeUnwrapFinalized,hn as decodeUnwrapRequested,Q as decodeWrap,ln as delegateForUserDecryptionContract,x as finalizeUnwrapContract,En as findDelegatedForUserDecryption,Dn as findRevokedDelegationForUserDecryption,yn as findUnwrapRequested,bn as findWrap,Xt as getConfidentialTokenAddressContract,dn as getDelegationExpiryContract,Kt as getTokenAddressContract,Jt as getTokenPairContract,Gt as getTokenPairsContract,Wt as getTokenPairsLengthContract,qt as getTokenPairsSliceContract,se as hardhat,ae as hoodi,ie as indexedDBStorage,ve as inferredTotalSupplyContract,je as isConfidentialTokenContract,Yt as isConfidentialTokenValidContract,Ie as isConfidentialWrapperContract,ct as isEncryptedValueZero,fn as isHandleDelegatedContract,_e as isOperatorContract,bt as isRetryable,ue as mainnet,an as matchZamaError,t as memoryStorage,Oe as nameContract,r as parsePreparedPermit,fe as polygon,oe as polygonAmoy,Se as rateContract,Et as retryAfterSeconds,un as revokeDelegationContract,ce as sepolia,Fe as setOperatorContract,Me as supportsInterfaceContract,He as symbolContract,cn as transferAndCallContract,he as underlyingContract,Pe as unwrapAmountContract,y as unwrapContract,b as unwrapFromBalanceContract,Ce as unwrapRequesterContract,g as wrapContract,me as zenithTrexTestnet};
2
2
  //# sourceMappingURL=index.js.map