@zama-fhe/sdk 3.9.0-beta.13 → 3.9.0-beta.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{t as e}from"./cleartext-BGZFvhAr.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-By5QjfHf.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 xe,L as Se,M as Ce,N as we,O as Te,P as Ee,S as De,T as Oe,U as ke,W as Ae,X as v,Y as je,_ as Me,a as Ne,b as Pe,c as Fe,d as Ie,f as y,h as Le,j as Re,k as ze,l as Be,m as b,n as Ve,o as He,p as x,q as Ue,s as We,t as S,u as Ge,v as Ke,w as qe,x as Je,y as Ye,z as Xe}from"./alignment-D1cVCzw8.js";import{C,_ as Ze,a as Qe,c as w,f as $e,g as et,h as tt,i as T,m as nt,n as E,o as rt,r as D,s as it,t as O,v as at,x as ot,y as st}from"./relayer-Cki3j_Ba.js";import{c as k,d as ct,f as lt,i as ut,l as dt,n as ft,o as pt,p as mt,r as ht,s as gt,t as _t,u as A}from"./token-DnriE-3y.js";import{n as vt,r as j,t as M}from"./encryption-QHaWnnx-.js";import{a as yt,c as bt,d as xt,i as St,l as N,n as Ct,o as wt,s as Tt,t as Et,u as Dt}from"./signing-DX-xyved.js";import{n as Ot,r as P}from"./fatal-batch-CI0ESPnd.js";import{i as kt,n as At,r as jt,t as Mt}from"./unshield-xO66p_da.js";import{a as F,c as Nt,i as Pt,l as Ft,n as I,o as It,r as Lt,s as Rt,t as L,u as zt}from"./log-decoding-Cl4zZCe8.js";import{r as R}from"./telemetry-Ct7Tktxt.js";import{t as z}from"./validation-BLmG7UVk.js";import{a as Bt,i as Vt,n as Ht,o as Ut,r as Wt,s as Gt,t as Kt}from"./wrappers-registry-Cm3JJeqx.js";import{getAddress as B,size as qt,zeroAddress as Jt}from"viem";import{z as V}from"zod/mini";function Yt(e,t){if(e instanceof D){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var Xt=class extends D{encryptedValue;contractAddress;account;constructor(e,t){super(T.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},H=class extends D{constructor(e,t){super(T.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},Zt=class extends D{constructor(e,t){super(T.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},U=class extends D{constructor(e,t){super(T.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},Qt=class extends D{constructor(e,t){super(T.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},W=class extends D{constructor(e,t){super(T.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},G=class extends D{constructor(e,t){super(T.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},$t=class extends D{constructor(e,t){super(T.DelegationDelegateCannotBeWildcard,e,t),this.name=`DelegationDelegateCannotBeWildcardError`}},en=class extends D{constructor(e,t){super(T.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},tn=class extends D{constructor(e,t){super(T.AclPaused,e,t),this.name=`AclPausedError`}},K=class extends D{constructor(e,t){super(T.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},q=class extends D{constructor(e,t){super(T.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};const nn=[M,wt,E,q,Ct,Et,Xt,P,St,N];function J(e,t,n={}){if(nn.some(t=>e instanceof t))return e;let r=e instanceof Error?e.message:t;if(e instanceof Error&&nt(e.message))return new St(e.message,{cause:e});if(at(e))return new N(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:e});if(e instanceof Error&&tt(e.message))return n.isDelegated?new q(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new Xt({encryptedValue:ot(e.message)??``,contractAddress:n.contractAddress??``,account:n.account??``},{cause:e});if($e(e))return new P(r,{cause:e,retryAfter:w(e)});let i=it(e);return i===void 0&&st(e)?new P(r,{cause:e,retryAfter:w(e)}):i===400?new wt(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):n.isDelegated&&i===500?new q(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):et(e)||i!==void 0?new E(r,i,{cause:e,retryAfter:w(e),retryable:Ze(e)||void 0}):new M(t,{cause:e})}function rn(e,t){if(e instanceof D)return e;let n=it(e),r=Ze(e);return n!==void 0||et(e)?new E(e instanceof Error?e.message:t,n,{cause:e,retryAfter:w(e),retryable:r||void 0}):new j(t,{cause:e})}const an=[{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 on(e,t,n,r=`0x`){return{address:e,abi:an,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 sn(e,t,n,r){return{address:e,abi:Y,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function cn(e,t,n){return{address:e,abi:Y,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function ln(e,t,n,r){return{address:e,abi:Y,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function un(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 dn(e){return c(e.signer,e.provider,e)}const Q={ConfidentialTransfer:L(`ConfidentialTransfer(address,address,bytes32)`),Wrap:L(`Wrap(address,uint256,bytes32)`),UnwrapRequested:L(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:L(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function fn(e){return e.topics[0]!==Q.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:I(e.topics[1]),to:I(e.topics[2]),encryptedAmount:Lt(e.topics[3])}}function pn(e){return e.topics[0]!==Q.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:I(e.topics[1]),roundedAmount:F(e.data,0),encryptedWrappedAmount:It(e.data,1)}}function mn(e){return e.topics[0]!==Q.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:I(e.topics[1]),unwrapRequestId:Lt(e.topics[2]),encryptedAmount:It(e.data,0)}}function hn(e){return e.topics[0]!==Q.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:I(e.topics[1]),unwrapRequestId:Lt(e.topics[2]),encryptedAmount:It(e.data,0),cleartextAmount:F(e.data,1)}}function gn(e){return fn(e)??pn(e)??mn(e)??hn(e)}function _n(e){let t=[];for(let n of e){let e=gn(n);e&&t.push(e)}return t}function vn(e){for(let t of e){let e=mn(t);if(e)return e}return null}function yn(e){for(let t of e){let e=pn(t);if(e)return e}return null}const bn=[Q.ConfidentialTransfer,Q.Wrap,Q.UnwrapRequested,Q.UnwrapFinalized],$={DelegatedForUserDecryption:L(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:L(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function xn(e){return e.topics[0]!==$.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:I(e.topics[1]),delegate:I(e.topics[2]),contractAddress:Pt(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2),newExpirationDate:F(e.data,3)}}function Sn(e){return e.topics[0]!==$.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:I(e.topics[1]),delegate:I(e.topics[2]),contractAddress:Pt(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2)}}function Cn(e){return xn(e)??Sn(e)}function wn(e){let t=[];for(let n of e){let e=Cn(n);e&&t.push(e)}return t}function Tn(e){for(let t of e){let e=xn(t);if(e)return e}return null}function En(e){for(let t of e){let e=Sn(t);if(e)return e}return null}const Dn=[$.DelegatedForUserDecryption,$.RevokedDelegationForUserDecryption];var On=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 xe(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 Ve(`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 Ve(`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 S(`revokePermits`,this.#e,this.#t),r=B(n.address);try{await t.revokePermits(e)}finally{await this.#c(r)}}async clear(){let e=this.#o(`clear`),t=await S(`clear`,this.#e,this.#t),n=B(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)}},kn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return xe(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await S(`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 S(`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)}},An=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 xe(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await S(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,R(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await S(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,R(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=R(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{Xe(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 J(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 S(`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`})}},jn=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)}},Mn=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 Nn=new Mn;async function Pn(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 Fn(e){return`zama:pending-unshields:${i(e)}`}function In(e){return`zama:pending-unshield:${i(e)}`}function Ln(e){return{version:2,unwrapTxHashes:e}}const Rn=V.union([p,V.pipe(V.object({version:V.literal(1),unwrapTxHash:p}),V.transform(({unwrapTxHash:e})=>e))]),zn=V.object({version:V.number(),unwrapTxHashes:V.optional(V.unknown())}),Bn=(e,t)=>e.toLowerCase()===t.toLowerCase();async function Vn(e,t,n){let r=await e.get(t);if(r==null)return{hashes:[],writable:!0};let i=zn.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 Hn(e,t,n){let r=await Vn(e,Fn(t),n),i=Rn.safeParse(await e.get(In(t)));return!i.success||!r.writable?{...r,hasLegacy:!1}:{hashes:r.hashes.some(e=>Bn(e,i.data))?r.hashes:[i.data,...r.hashes],writable:!0,hasLegacy:!0}}async function Un(e,t,n){let r=Fn(t);await(n.length===0?e.delete(r):e.set(r,Ln(n)))}const Wn=/* @__PURE__ */ new WeakMap;function Gn(e,t){let n=(Wn.get(e)??Promise.resolve()).then(t);return Wn.set(e,n.then(()=>{},()=>{})),n}function Kn(e,t,n,r){return Gn(e,async()=>{let{hashes:i,writable:a,hasLegacy:o}=await Hn(e,t,n);if(!a)return;let s=r(i);(o||s.length!==i.length)&&await Un(e,t,s),o&&await e.delete(In(t))})}async function qn(e,t,n){return(await Gn(e,()=>Hn(e,t,n))).hashes}function Jn(e,t,n,r){return Kn(e,t,r,e=>e.some(e=>Bn(e,n))?e:[...e,n])}function Yn(e,t,n,r){return Kn(e,t,r,e=>e.filter(e=>!Bn(e,n)))}function Xn(e,t){let n=B(t);return vn(e.filter(e=>e.address===void 0||B(e.address)===n))?.unwrapRequestId}function Zn(e,t){if(!e)return`unknown`;let n=e.status===`reverted`?void 0:Xn(e.logs,t);return n===void 0?`settled`:{unwrapRequestId:n}}var Qn=class extends _t{#e;#t=null;#n=null;#r(e){try{return Xe(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(Ge(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#m();return this.sdk.provider.readContract(y(t,B(e),this.address))}async shield(e,t){let n=await S(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),i=await this.#m(),a=B(n.address),o;try{o=await this.sdk.provider.readContract(b(i,a))}catch(e){throw e instanceof D?e:new A(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:C(e)})}if(o<e)throw new mt(`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?B(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:on(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await S(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#m(),i=B(n.address),a;try{a=await this.sdk.provider.readContract(b(r,i))}catch(e){throw e instanceof D?e:new A(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:C(e)})}if(a<e)throw new mt(`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(y(r,i,this.address))}catch(e){throw e instanceof D?e:new A(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:C(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?B(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?B(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 S(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#m(),r=B(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(y(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:x(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:x(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 Pn(this.sdk.provider,e)}catch(e){throw e instanceof D?e:new v(`Failed to get unwrap receipt`,{cause:e})}let r=Zn(n,this.address);if(r===`unknown`)throw new At(`Unwrap transaction ${e} is not mined, so there is nothing to resume yet`,e);if(r===`settled`)throw await this.#p(`resumeUnshield`,e),new v(`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 Mt(`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 qn(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 S(`unwrap`,this.sdk.signer,this.sdk.provider),i=B(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 j(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:Ce(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 S(`unwrapAll`,this.sdk.signer,this.sdk.provider),n=B(t.address),r=await this.readConfidentialBalanceOf(n);if(k(r))throw new M(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:we(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 Ve(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e],{operation:t}),r=n.clearValues[e];return Se(r,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:Oe(this.address,e,r,n.decryptionProof)})}#l(e){let t=Xn(e,this.address);if(t===void 0)throw new v(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t}async#u(e){try{return await this.sdk.provider.readContract(Ee(this.address,e))===Jt?`settled`:`open`}catch{return`unknown`}}#d(e){return Jn(this.sdk.storage,this.address,e,this.sdk.logger)}async#f(e){let t;try{t=await Pn(this.sdk.provider,e)}catch{return`unknown`}let n=Zn(t,this.address);return typeof n==`string`?n:this.#u(n.unwrapRequestId)}async#p(e,t){await _(`${e}: clearPendingUnshield`,()=>Yn(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 jt(n)||n instanceof v&&await this.#u(e)===`settled`?(await this.#p(`unshield`,t),new Mt(`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 S(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=B(i.address),o=await this.sdk.provider.readContract(y(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:x(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:x(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};const $n=V.union([V.bigint(),V.boolean(),a]),er=V.array(V.string());var tr=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=$n.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=B(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}:${B(e)}:${B(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=er.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 nr(e,t){let n=rr(e,t);if(!n)throw new M(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function rr(e,t){let n=i(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const ir=e=>new Promise(t=>setTimeout(t,e));var ar=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=B(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=B(t),o=B(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:B(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 q))throw t;await ir(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:B(e.contractAddress)}));if(s.length===0)return{items:s};let c=B(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(Ot(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:B(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(Ot(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:B(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=nr(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&&nt(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:B(e.contractAddress)})),a={},o=[];for(let e of i)k(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 st(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 gt(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 N)||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 Et?new N(`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 D&&e.cause instanceof Error?e.cause:e;throw this.#i({type:h.DecryptError,error:C(n),durationMs:Date.now()-p,encryptedValues:m}),J(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 N)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw J(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 M(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new M(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new P(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:w(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new M(`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 D?e:J(e,t,n)}#p(){throw new M(`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 or={AlreadyDelegatedOrRevokedInSameBlock:e=>new Zt(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new en(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new tn(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new H(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new G(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new $t(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new K(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new W(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new U(`Cannot revoke: no active delegation exists.`,{cause:e})};function sr(e){return Object.hasOwn(or,e)}function cr(e,t){let n=kt(e);if(n&&sr(n))return or[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(or))if(r.includes(e))return n(t);return null}var lr=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 K(`Expiration date must be at least 1 hour in the future`);let a=B(t),o=B(n),s=B(r);if(o===s)throw new H(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===B(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new $t(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new G(`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 W(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==B(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:sn(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=B(t),a=B(n),o=B(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 U(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:cn(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=B(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(ln(r,B(t),B(n),B(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 v))return;let t=cr(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 U||t instanceof Qt){let n=B(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=B(e),i=B(t),a=B(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new U(`No active delegation from ${i} to ${a} for ${r}`):new Qt(`Delegation from ${i} to ${a} for ${r} has expired`)}},ur=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=B(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:C(e),durationMs:Date.now()-n},r),rn(e,`Encryption failed`)}}},dr=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 fr=V.object({kind:V.literal(`ConfidentialTransfer`),from:a,token:a,to:a,amount:V.bigint()}),pr=V.object({kind:V.literal(`ConfidentialTransferFrom`),from:a,token:a,owner:a,to:a,amount:V.bigint()}),mr=V.object({kind:V.literal(`SetOperator`),from:a,token:a,operator:a,until:u}),hr=V.object({kind:V.literal(`Unwrap`),from:a,token:a,to:a,amount:V.bigint()}),gr=V.object({kind:V.literal(`UnwrapAll`),from:a,token:a,to:a}),_r=V.object({kind:V.literal(`FinalizeUnwrap`),from:a,wrapper:a,unwrapRequestIdOrAmount:p}),vr=V.object({kind:V.literal(`ApproveUnderlying`),from:a,underlying:a,spender:a,amount:V.bigint()}),yr=V.object({kind:V.literal(`Wrap`),from:a,wrapper:a,to:a,amount:V.bigint()}),br=p.check(V.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`)),xr=V.object({kind:V.literal(`TransferAndCall`),from:a,underlying:a,wrapper:a,amount:V.bigint(),recipientData:V.optional(br)}),Sr=V.object({kind:V.literal(`DelegateDecryption`),from:a,contractAddress:a,delegateAddress:a,expirationDate:V.optional(V.date())}),Cr=V.object({kind:V.literal(`RevokeDelegation`),from:a,contractAddress:a,delegateAddress:a});V.discriminatedUnion(`kind`,[fr,pr,mr,hr,gr,_r,vr,yr,xr,Sr,Cr]);const wr=V.strictObject({maxFeePerGas:V.bigint(),maxPriorityFeePerGas:V.bigint()}),Tr=V.object({nonce:V.optional(V.int().check(V.nonnegative())),gasLimit:V.optional(V.bigint()),fees:V.optional(wr)}),Er=V.object({address:a,abi:V.array(V.unknown()),functionName:V.string(),args:V.array(V.unknown()),value:V.optional(V.bigint()),gas:V.optional(V.bigint())}),Dr=V.extend(Tr,{from:a,calldata:Er});var Or=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=z(Tr,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new O(`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=z(Dr,i),o=await this.#e.prepareTransaction(a).catch(t=>{throw ht(t,`prepare ${e.kind}`)??t});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 O(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=z(fr,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 j(`Encryption returned no handles for ConfidentialTransfer`);return De(e.token,e.to,r,n)}async#a(e){e=z(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-confidential-transfer-from`}),r=t[0];if(!r)throw new j(`Encryption returned no handles for ConfidentialTransferFrom`);return qe(e.token,e.owner,e.to,r,n)}#o(e){return e=z(mr,e),ze(e.token,e.operator,e.until)}async#s(e){e=z(hr,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 j(`Encryption returned no handles for Unwrap`);return Ce(e.token,e.from,e.to,r,n)}async#c(e){e=z(gr,e);let t=await this.#e.readContract(Ye(e.token,e.from));return we(e.token,e.from,e.to,t)}async#l(e){e=z(_r,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount],options:{operation:`offline-finalize-unwrap`}}).catch(e=>{throw J(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return Se(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),Oe(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=z(vr,e),x(e.underlying,e.spender,e.amount)}#d(e){return e=z(yr,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=z(xr,e),on(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=z(Sr,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new K(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new H(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new G(`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 sn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=z(Cr,e),cn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function kr(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new O(`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 Ar(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new O(`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 jr(e){if(e===void 0)return;let t=z(l,e);return new ne(typeof t==`string`?t:new Uint8Array(t))}var Mr=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){kr(t),Ar(t.transportKeyPairDerivationSecret);let n=jr(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 tr(e.storage,this.#i),this.#u=new lr({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 ar({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new ur({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new dr({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new Or({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new On({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new kn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new An({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new jn(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,R(t,`encrypt`))}createToken(e){return new _t(this,e)}createWrappedToken(e){return new Qn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{Dn as ACL_TOPICS,tn as AclPausedError,$ as AclTopics,dt as BalanceCheckUnavailableError,te as BaseSigner,Ue as ChainMismatchError,Mn as ChromeSessionStorage,O as ConfigurationError,An as Decryption,M as DecryptionFailedError,n as DefaultRegistryAddresses,en as DelegationContractIsSelfError,Zt as DelegationCooldownError,$t as DelegationDelegateCannotBeWildcardError,G as DelegationDelegateEqualsContractError,K as DelegationExpirationTooSoonError,Qt as DelegationExpiredError,W as DelegationExpiryUnchangedError,U as DelegationNotFoundError,q as DelegationNotPropagatedError,H as DelegationSelfNotAllowedError,kn as Delegations,Ne as ERC1363_INTERFACE_ID,A as ERC20ReadFailedError,He as ERC7984_INTERFACE_ID,We as ERC7984_WRAPPER_INTERFACE_ID,vt as EncryptOffloadUnavailableError,j as EncryptionFailedError,be as HcuBlockLimitExceededError,je as HcuTransactionLimitExceededError,t as IndexedDBStorage,ct as InsufficientAllowanceError,lt as InsufficientConfidentialBalanceError,mt as InsufficientERC20BalanceError,St as InvalidTransportKeyPairError,yt as KeyWrappingError,X as MAX_UINT64,s as MemoryStorage,d as MutableWalletAccountStore,wt as NoCiphertextError,Xt as NotEntitledError,jn as Offline,On as Permits,Tt as PreparedPermitChainMismatchError,bt as PreparedPermitExpiredError,E as RelayerRequestFailedError,N as RevokedKmsContextError,P as RpcRateLimitError,ye as SignerNotConfiguredError,ke as SignerRequiredError,Et as SigningFailedError,Ct as SigningRejectedError,bn as TOKEN_TOPICS,_t as Token,Q as Topics,v as TransactionRevertedError,Dt as TransportKeyPairChangedError,xt as TransportKeyPairExpiredError,Mt as UnshieldAlreadyFinalizedError,At as UnwrapNotMinedError,Rt as VaultBatchNotDispatchedError,Nt as VaultBatcherPausedError,Ft as VaultBatcherReadFailedError,zt as VaultJoinUnconfirmedError,Z as WILDCARD_CONTRACT,Ae as WalletAccountNotReadyError,ve as WalletNotConnectedError,Qn as WrappedToken,f as WrappersRegistry,pt as ZERO_ENCRYPTED_VALUE,D as ZamaError,T as ZamaErrorCode,Mr as ZamaSDK,h as ZamaSDKEvents,y as allowanceContract,fe as anvil,x as approveContract,b as balanceOfContract,ce as bscTestnet,ue as chains,Nn as chromeSessionStorage,e as cleartext,Ye as confidentialBalanceOfContract,Pe as confidentialTotalSupplyContract,Je as confidentialTransferAndCallContract,De as confidentialTransferContract,he as confidentialTransferFromAndCallContract,qe as confidentialTransferFromContract,dn as createConfig,m as createWalletAccountStore,Le as decimalsContract,Cn as decodeAclEvent,wn as decodeAclEvents,fn as decodeConfidentialTransfer,xn as decodeDelegatedForUserDecryption,gn as decodeOnChainEvent,_n as decodeOnChainEvents,Sn as decodeRevokedDelegationForUserDecryption,hn as decodeUnwrapFinalized,mn as decodeUnwrapRequested,pn as decodeWrap,sn as delegateForUserDecryptionContract,Oe as finalizeUnwrapContract,Tn as findDelegatedForUserDecryption,En as findRevokedDelegationForUserDecryption,vn as findUnwrapRequested,yn as findWrap,Kt as getConfidentialTokenAddressContract,ln as getDelegationExpiryContract,Ht as getTokenAddressContract,Wt as getTokenPairContract,Vt as getTokenPairsContract,Bt as getTokenPairsLengthContract,Ut as getTokenPairsSliceContract,oe as hardhat,ie as hoodi,re as indexedDBStorage,_e as inferredTotalSupplyContract,Fe as isConfidentialTokenContract,Gt as isConfidentialTokenValidContract,Be as isConfidentialWrapperContract,k as isEncryptedValueZero,un as isHandleDelegatedContract,ge as isOperatorContract,Qe as isRetryable,le as mainnet,Yt as matchZamaError,o as memoryStorage,Me as nameContract,r as parsePreparedPermit,de as polygon,ae as polygonAmoy,Te as rateContract,rt as retryAfterSeconds,cn as revokeDelegationContract,se as sepolia,ze as setOperatorContract,Ie as supportsInterfaceContract,Ke as symbolContract,on as transferAndCallContract,me as underlyingContract,Re as unwrapAmountContract,Ce as unwrapContract,we as unwrapFromBalanceContract,Ee as unwrapRequesterContract,g as wrapContract,pe as zenithTrexTestnet};
1
+ import{t as e}from"./cleartext-DvDvR_Pc.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-nWo4_O8s.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 xe,L as Se,M as Ce,N as we,O as Te,P as Ee,S as De,T as Oe,U as ke,W as Ae,X as v,Y as je,_ as Me,a as Ne,b as Pe,c as Fe,d as Ie,f as y,h as Le,j as Re,k as ze,l as Be,m as b,n as Ve,o as He,p as x,q as Ue,s as We,t as S,u as Ge,v as Ke,w as qe,x as Je,y as Ye,z as Xe}from"./alignment-D1cVCzw8.js";import{C,_ as Ze,a as Qe,c as w,f as $e,g as et,h as tt,i as T,m as nt,n as E,o as rt,r as D,s as it,t as O,v as at,x as ot,y as st}from"./relayer-Cki3j_Ba.js";import{c as k,d as ct,f as lt,i as ut,l as dt,n as ft,o as pt,p as mt,r as ht,s as gt,t as _t,u as A}from"./token-DnriE-3y.js";import{n as vt,r as j,t as M}from"./encryption-QHaWnnx-.js";import{a as yt,c as bt,d as xt,i as St,l as N,n as Ct,o as wt,s as Tt,t as Et,u as Dt}from"./signing-DX-xyved.js";import{n as Ot,r as P}from"./fatal-batch-CI0ESPnd.js";import{i as kt,n as At,r as jt,t as Mt}from"./unshield-xO66p_da.js";import{a as F,c as Nt,i as Pt,l as Ft,n as I,o as It,r as Lt,s as Rt,t as L,u as zt}from"./log-decoding-Cl4zZCe8.js";import{r as R}from"./telemetry-DSOCwVh_.js";import{t as z}from"./validation-BLmG7UVk.js";import{a as Bt,i as Vt,n as Ht,o as Ut,r as Wt,s as Gt,t as Kt}from"./wrappers-registry-Cm3JJeqx.js";import{getAddress as B,size as qt,zeroAddress as Jt}from"viem";import{z as V}from"zod/mini";function Yt(e,t){if(e instanceof D){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var Xt=class extends D{encryptedValue;contractAddress;account;constructor(e,t){super(T.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},H=class extends D{constructor(e,t){super(T.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},Zt=class extends D{constructor(e,t){super(T.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},U=class extends D{constructor(e,t){super(T.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},Qt=class extends D{constructor(e,t){super(T.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},W=class extends D{constructor(e,t){super(T.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},G=class extends D{constructor(e,t){super(T.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},$t=class extends D{constructor(e,t){super(T.DelegationDelegateCannotBeWildcard,e,t),this.name=`DelegationDelegateCannotBeWildcardError`}},en=class extends D{constructor(e,t){super(T.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},tn=class extends D{constructor(e,t){super(T.AclPaused,e,t),this.name=`AclPausedError`}},K=class extends D{constructor(e,t){super(T.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},q=class extends D{constructor(e,t){super(T.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};const nn=[M,wt,E,q,Ct,Et,Xt,P,St,N];function J(e,t,n={}){if(nn.some(t=>e instanceof t))return e;let r=e instanceof Error?e.message:t;if(e instanceof Error&&nt(e.message))return new St(e.message,{cause:e});if(at(e))return new N(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:e});if(e instanceof Error&&tt(e.message))return n.isDelegated?new q(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new Xt({encryptedValue:ot(e.message)??``,contractAddress:n.contractAddress??``,account:n.account??``},{cause:e});if($e(e))return new P(r,{cause:e,retryAfter:w(e)});let i=it(e);return i===void 0&&st(e)?new P(r,{cause:e,retryAfter:w(e)}):i===400?new wt(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):n.isDelegated&&i===500?new q(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):et(e)||i!==void 0?new E(r,i,{cause:e,retryAfter:w(e),retryable:Ze(e)||void 0}):new M(t,{cause:e})}function rn(e,t){if(e instanceof D)return e;let n=it(e),r=Ze(e);return n!==void 0||et(e)?new E(e instanceof Error?e.message:t,n,{cause:e,retryAfter:w(e),retryable:r||void 0}):new j(t,{cause:e})}const an=[{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 on(e,t,n,r=`0x`){return{address:e,abi:an,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 sn(e,t,n,r){return{address:e,abi:Y,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function cn(e,t,n){return{address:e,abi:Y,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function ln(e,t,n,r){return{address:e,abi:Y,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function un(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 dn(e){return c(e.signer,e.provider,e)}const Q={ConfidentialTransfer:L(`ConfidentialTransfer(address,address,bytes32)`),Wrap:L(`Wrap(address,uint256,bytes32)`),UnwrapRequested:L(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:L(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function fn(e){return e.topics[0]!==Q.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:I(e.topics[1]),to:I(e.topics[2]),encryptedAmount:Lt(e.topics[3])}}function pn(e){return e.topics[0]!==Q.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:I(e.topics[1]),roundedAmount:F(e.data,0),encryptedWrappedAmount:It(e.data,1)}}function mn(e){return e.topics[0]!==Q.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:I(e.topics[1]),unwrapRequestId:Lt(e.topics[2]),encryptedAmount:It(e.data,0)}}function hn(e){return e.topics[0]!==Q.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:I(e.topics[1]),unwrapRequestId:Lt(e.topics[2]),encryptedAmount:It(e.data,0),cleartextAmount:F(e.data,1)}}function gn(e){return fn(e)??pn(e)??mn(e)??hn(e)}function _n(e){let t=[];for(let n of e){let e=gn(n);e&&t.push(e)}return t}function vn(e){for(let t of e){let e=mn(t);if(e)return e}return null}function yn(e){for(let t of e){let e=pn(t);if(e)return e}return null}const bn=[Q.ConfidentialTransfer,Q.Wrap,Q.UnwrapRequested,Q.UnwrapFinalized],$={DelegatedForUserDecryption:L(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:L(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function xn(e){return e.topics[0]!==$.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:I(e.topics[1]),delegate:I(e.topics[2]),contractAddress:Pt(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2),newExpirationDate:F(e.data,3)}}function Sn(e){return e.topics[0]!==$.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:I(e.topics[1]),delegate:I(e.topics[2]),contractAddress:Pt(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2)}}function Cn(e){return xn(e)??Sn(e)}function wn(e){let t=[];for(let n of e){let e=Cn(n);e&&t.push(e)}return t}function Tn(e){for(let t of e){let e=xn(t);if(e)return e}return null}function En(e){for(let t of e){let e=Sn(t);if(e)return e}return null}const Dn=[$.DelegatedForUserDecryption,$.RevokedDelegationForUserDecryption];var On=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 xe(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 Ve(`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 Ve(`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 S(`revokePermits`,this.#e,this.#t),r=B(n.address);try{await t.revokePermits(e)}finally{await this.#c(r)}}async clear(){let e=this.#o(`clear`),t=await S(`clear`,this.#e,this.#t),n=B(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)}},kn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return xe(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await S(`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 S(`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)}},An=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 xe(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await S(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,R(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await S(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,R(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=R(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{Xe(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 J(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 S(`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`})}},jn=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)}},Mn=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 Nn=new Mn;async function Pn(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 Fn(e){return`zama:pending-unshields:${i(e)}`}function In(e){return`zama:pending-unshield:${i(e)}`}function Ln(e){return{version:2,unwrapTxHashes:e}}const Rn=V.union([p,V.pipe(V.object({version:V.literal(1),unwrapTxHash:p}),V.transform(({unwrapTxHash:e})=>e))]),zn=V.object({version:V.number(),unwrapTxHashes:V.optional(V.unknown())}),Bn=(e,t)=>e.toLowerCase()===t.toLowerCase();async function Vn(e,t,n){let r=await e.get(t);if(r==null)return{hashes:[],writable:!0};let i=zn.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 Hn(e,t,n){let r=await Vn(e,Fn(t),n),i=Rn.safeParse(await e.get(In(t)));return!i.success||!r.writable?{...r,hasLegacy:!1}:{hashes:r.hashes.some(e=>Bn(e,i.data))?r.hashes:[i.data,...r.hashes],writable:!0,hasLegacy:!0}}async function Un(e,t,n){let r=Fn(t);await(n.length===0?e.delete(r):e.set(r,Ln(n)))}const Wn=/* @__PURE__ */ new WeakMap;function Gn(e,t){let n=(Wn.get(e)??Promise.resolve()).then(t);return Wn.set(e,n.then(()=>{},()=>{})),n}function Kn(e,t,n,r){return Gn(e,async()=>{let{hashes:i,writable:a,hasLegacy:o}=await Hn(e,t,n);if(!a)return;let s=r(i);(o||s.length!==i.length)&&await Un(e,t,s),o&&await e.delete(In(t))})}async function qn(e,t,n){return(await Gn(e,()=>Hn(e,t,n))).hashes}function Jn(e,t,n,r){return Kn(e,t,r,e=>e.some(e=>Bn(e,n))?e:[...e,n])}function Yn(e,t,n,r){return Kn(e,t,r,e=>e.filter(e=>!Bn(e,n)))}function Xn(e,t){let n=B(t);return vn(e.filter(e=>e.address===void 0||B(e.address)===n))?.unwrapRequestId}function Zn(e,t){if(!e)return`unknown`;let n=e.status===`reverted`?void 0:Xn(e.logs,t);return n===void 0?`settled`:{unwrapRequestId:n}}var Qn=class extends _t{#e;#t=null;#n=null;#r(e){try{return Xe(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(Ge(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#m();return this.sdk.provider.readContract(y(t,B(e),this.address))}async shield(e,t){let n=await S(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),i=await this.#m(),a=B(n.address),o;try{o=await this.sdk.provider.readContract(b(i,a))}catch(e){throw e instanceof D?e:new A(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:C(e)})}if(o<e)throw new mt(`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?B(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:on(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await S(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#m(),i=B(n.address),a;try{a=await this.sdk.provider.readContract(b(r,i))}catch(e){throw e instanceof D?e:new A(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:C(e)})}if(a<e)throw new mt(`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(y(r,i,this.address))}catch(e){throw e instanceof D?e:new A(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:C(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?B(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?B(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 S(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#m(),r=B(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(y(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:x(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:x(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 Pn(this.sdk.provider,e)}catch(e){throw e instanceof D?e:new v(`Failed to get unwrap receipt`,{cause:e})}let r=Zn(n,this.address);if(r===`unknown`)throw new At(`Unwrap transaction ${e} is not mined, so there is nothing to resume yet`,e);if(r===`settled`)throw await this.#p(`resumeUnshield`,e),new v(`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 Mt(`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 qn(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 S(`unwrap`,this.sdk.signer,this.sdk.provider),i=B(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 j(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:Ce(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 S(`unwrapAll`,this.sdk.signer,this.sdk.provider),n=B(t.address),r=await this.readConfidentialBalanceOf(n);if(k(r))throw new M(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:we(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 Ve(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e],{operation:t}),r=n.clearValues[e];return Se(r,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:Oe(this.address,e,r,n.decryptionProof)})}#l(e){let t=Xn(e,this.address);if(t===void 0)throw new v(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t}async#u(e){try{return await this.sdk.provider.readContract(Ee(this.address,e))===Jt?`settled`:`open`}catch{return`unknown`}}#d(e){return Jn(this.sdk.storage,this.address,e,this.sdk.logger)}async#f(e){let t;try{t=await Pn(this.sdk.provider,e)}catch{return`unknown`}let n=Zn(t,this.address);return typeof n==`string`?n:this.#u(n.unwrapRequestId)}async#p(e,t){await _(`${e}: clearPendingUnshield`,()=>Yn(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 jt(n)||n instanceof v&&await this.#u(e)===`settled`?(await this.#p(`unshield`,t),new Mt(`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 S(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=B(i.address),o=await this.sdk.provider.readContract(y(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:x(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:x(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};const $n=V.union([V.bigint(),V.boolean(),a]),er=V.array(V.string());var tr=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=$n.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=B(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}:${B(e)}:${B(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=er.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 nr(e,t){let n=rr(e,t);if(!n)throw new M(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function rr(e,t){let n=i(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const ir=e=>new Promise(t=>setTimeout(t,e));var ar=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=B(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=B(t),o=B(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:B(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 q))throw t;await ir(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:B(e.contractAddress)}));if(s.length===0)return{items:s};let c=B(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(Ot(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:B(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(Ot(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:B(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=nr(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&&nt(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:B(e.contractAddress)})),a={},o=[];for(let e of i)k(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 st(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 gt(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 N)||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 Et?new N(`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 D&&e.cause instanceof Error?e.cause:e;throw this.#i({type:h.DecryptError,error:C(n),durationMs:Date.now()-p,encryptedValues:m}),J(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 N)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw J(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 M(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new M(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new P(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:w(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new M(`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 D?e:J(e,t,n)}#p(){throw new M(`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 or={AlreadyDelegatedOrRevokedInSameBlock:e=>new Zt(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new en(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new tn(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new H(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new G(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new $t(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new K(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new W(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new U(`Cannot revoke: no active delegation exists.`,{cause:e})};function sr(e){return Object.hasOwn(or,e)}function cr(e,t){let n=kt(e);if(n&&sr(n))return or[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(or))if(r.includes(e))return n(t);return null}var lr=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 K(`Expiration date must be at least 1 hour in the future`);let a=B(t),o=B(n),s=B(r);if(o===s)throw new H(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===B(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new $t(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new G(`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 W(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==B(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:sn(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=B(t),a=B(n),o=B(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 U(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:cn(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=B(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(ln(r,B(t),B(n),B(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 v))return;let t=cr(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 U||t instanceof Qt){let n=B(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=B(e),i=B(t),a=B(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new U(`No active delegation from ${i} to ${a} for ${r}`):new Qt(`Delegation from ${i} to ${a} for ${r} has expired`)}},ur=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=B(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:C(e),durationMs:Date.now()-n},r),rn(e,`Encryption failed`)}}},dr=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 fr=V.object({kind:V.literal(`ConfidentialTransfer`),from:a,token:a,to:a,amount:V.bigint()}),pr=V.object({kind:V.literal(`ConfidentialTransferFrom`),from:a,token:a,owner:a,to:a,amount:V.bigint()}),mr=V.object({kind:V.literal(`SetOperator`),from:a,token:a,operator:a,until:u}),hr=V.object({kind:V.literal(`Unwrap`),from:a,token:a,to:a,amount:V.bigint()}),gr=V.object({kind:V.literal(`UnwrapAll`),from:a,token:a,to:a}),_r=V.object({kind:V.literal(`FinalizeUnwrap`),from:a,wrapper:a,unwrapRequestIdOrAmount:p}),vr=V.object({kind:V.literal(`ApproveUnderlying`),from:a,underlying:a,spender:a,amount:V.bigint()}),yr=V.object({kind:V.literal(`Wrap`),from:a,wrapper:a,to:a,amount:V.bigint()}),br=p.check(V.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`)),xr=V.object({kind:V.literal(`TransferAndCall`),from:a,underlying:a,wrapper:a,amount:V.bigint(),recipientData:V.optional(br)}),Sr=V.object({kind:V.literal(`DelegateDecryption`),from:a,contractAddress:a,delegateAddress:a,expirationDate:V.optional(V.date())}),Cr=V.object({kind:V.literal(`RevokeDelegation`),from:a,contractAddress:a,delegateAddress:a});V.discriminatedUnion(`kind`,[fr,pr,mr,hr,gr,_r,vr,yr,xr,Sr,Cr]);const wr=V.strictObject({maxFeePerGas:V.bigint(),maxPriorityFeePerGas:V.bigint()}),Tr=V.object({nonce:V.optional(V.int().check(V.nonnegative())),gasLimit:V.optional(V.bigint()),fees:V.optional(wr)}),Er=V.object({address:a,abi:V.array(V.unknown()),functionName:V.string(),args:V.array(V.unknown()),value:V.optional(V.bigint()),gas:V.optional(V.bigint())}),Dr=V.extend(Tr,{from:a,calldata:Er});var Or=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=z(Tr,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new O(`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=z(Dr,i),o=await this.#e.prepareTransaction(a).catch(t=>{throw ht(t,`prepare ${e.kind}`)??t});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 O(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=z(fr,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 j(`Encryption returned no handles for ConfidentialTransfer`);return De(e.token,e.to,r,n)}async#a(e){e=z(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-confidential-transfer-from`}),r=t[0];if(!r)throw new j(`Encryption returned no handles for ConfidentialTransferFrom`);return qe(e.token,e.owner,e.to,r,n)}#o(e){return e=z(mr,e),ze(e.token,e.operator,e.until)}async#s(e){e=z(hr,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 j(`Encryption returned no handles for Unwrap`);return Ce(e.token,e.from,e.to,r,n)}async#c(e){e=z(gr,e);let t=await this.#e.readContract(Ye(e.token,e.from));return we(e.token,e.from,e.to,t)}async#l(e){e=z(_r,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount],options:{operation:`offline-finalize-unwrap`}}).catch(e=>{throw J(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return Se(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),Oe(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=z(vr,e),x(e.underlying,e.spender,e.amount)}#d(e){return e=z(yr,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=z(xr,e),on(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=z(Sr,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new K(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new H(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new G(`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 sn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=z(Cr,e),cn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function kr(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new O(`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 Ar(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new O(`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 jr(e){if(e===void 0)return;let t=z(l,e);return new ne(typeof t==`string`?t:new Uint8Array(t))}var Mr=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){kr(t),Ar(t.transportKeyPairDerivationSecret);let n=jr(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 tr(e.storage,this.#i),this.#u=new lr({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 ar({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new ur({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new dr({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new Or({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new On({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new kn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new An({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new jn(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,R(t,`encrypt`))}createToken(e){return new _t(this,e)}createWrappedToken(e){return new Qn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{Dn as ACL_TOPICS,tn as AclPausedError,$ as AclTopics,dt as BalanceCheckUnavailableError,te as BaseSigner,Ue as ChainMismatchError,Mn as ChromeSessionStorage,O as ConfigurationError,An as Decryption,M as DecryptionFailedError,n as DefaultRegistryAddresses,en as DelegationContractIsSelfError,Zt as DelegationCooldownError,$t as DelegationDelegateCannotBeWildcardError,G as DelegationDelegateEqualsContractError,K as DelegationExpirationTooSoonError,Qt as DelegationExpiredError,W as DelegationExpiryUnchangedError,U as DelegationNotFoundError,q as DelegationNotPropagatedError,H as DelegationSelfNotAllowedError,kn as Delegations,Ne as ERC1363_INTERFACE_ID,A as ERC20ReadFailedError,He as ERC7984_INTERFACE_ID,We as ERC7984_WRAPPER_INTERFACE_ID,vt as EncryptOffloadUnavailableError,j as EncryptionFailedError,be as HcuBlockLimitExceededError,je as HcuTransactionLimitExceededError,t as IndexedDBStorage,ct as InsufficientAllowanceError,lt as InsufficientConfidentialBalanceError,mt as InsufficientERC20BalanceError,St as InvalidTransportKeyPairError,yt as KeyWrappingError,X as MAX_UINT64,s as MemoryStorage,d as MutableWalletAccountStore,wt as NoCiphertextError,Xt as NotEntitledError,jn as Offline,On as Permits,Tt as PreparedPermitChainMismatchError,bt as PreparedPermitExpiredError,E as RelayerRequestFailedError,N as RevokedKmsContextError,P as RpcRateLimitError,ye as SignerNotConfiguredError,ke as SignerRequiredError,Et as SigningFailedError,Ct as SigningRejectedError,bn as TOKEN_TOPICS,_t as Token,Q as Topics,v as TransactionRevertedError,Dt as TransportKeyPairChangedError,xt as TransportKeyPairExpiredError,Mt as UnshieldAlreadyFinalizedError,At as UnwrapNotMinedError,Rt as VaultBatchNotDispatchedError,Nt as VaultBatcherPausedError,Ft as VaultBatcherReadFailedError,zt as VaultJoinUnconfirmedError,Z as WILDCARD_CONTRACT,Ae as WalletAccountNotReadyError,ve as WalletNotConnectedError,Qn as WrappedToken,f as WrappersRegistry,pt as ZERO_ENCRYPTED_VALUE,D as ZamaError,T as ZamaErrorCode,Mr as ZamaSDK,h as ZamaSDKEvents,y as allowanceContract,fe as anvil,x as approveContract,b as balanceOfContract,ce as bscTestnet,ue as chains,Nn as chromeSessionStorage,e as cleartext,Ye as confidentialBalanceOfContract,Pe as confidentialTotalSupplyContract,Je as confidentialTransferAndCallContract,De as confidentialTransferContract,he as confidentialTransferFromAndCallContract,qe as confidentialTransferFromContract,dn as createConfig,m as createWalletAccountStore,Le as decimalsContract,Cn as decodeAclEvent,wn as decodeAclEvents,fn as decodeConfidentialTransfer,xn as decodeDelegatedForUserDecryption,gn as decodeOnChainEvent,_n as decodeOnChainEvents,Sn as decodeRevokedDelegationForUserDecryption,hn as decodeUnwrapFinalized,mn as decodeUnwrapRequested,pn as decodeWrap,sn as delegateForUserDecryptionContract,Oe as finalizeUnwrapContract,Tn as findDelegatedForUserDecryption,En as findRevokedDelegationForUserDecryption,vn as findUnwrapRequested,yn as findWrap,Kt as getConfidentialTokenAddressContract,ln as getDelegationExpiryContract,Ht as getTokenAddressContract,Wt as getTokenPairContract,Vt as getTokenPairsContract,Bt as getTokenPairsLengthContract,Ut as getTokenPairsSliceContract,oe as hardhat,ie as hoodi,re as indexedDBStorage,_e as inferredTotalSupplyContract,Fe as isConfidentialTokenContract,Gt as isConfidentialTokenValidContract,Be as isConfidentialWrapperContract,k as isEncryptedValueZero,un as isHandleDelegatedContract,ge as isOperatorContract,Qe as isRetryable,le as mainnet,Yt as matchZamaError,o as memoryStorage,Me as nameContract,r as parsePreparedPermit,de as polygon,ae as polygonAmoy,Te as rateContract,rt as retryAfterSeconds,cn as revokeDelegationContract,se as sepolia,ze as setOperatorContract,Ie as supportsInterfaceContract,Ke as symbolContract,on as transferAndCallContract,me as underlyingContract,Re as unwrapAmountContract,Ce as unwrapContract,we as unwrapFromBalanceContract,Ee as unwrapRequesterContract,g as wrapContract,pe as zenithTrexTestnet};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{b as e,i as t,r as n}from"../relayer-Cki3j_Ba.js";import{t as r}from"../fatal-batch-CI0ESPnd.js";import{n as i}from"../fhevm-relayer-BQs1LVxv.js";import{t as a}from"../typed-data-eAgGr9V-.js";const o=r;function s(r,i,a){let s=o[r],c=s?new s(i):new n(r,i,r===t.RelayerRequestFailed?{retryable:a.retryable}:void 0);return c.retryable&&e(a.retryAfter)?Object.assign(c,{retryAfter:a.retryAfter}):c}function c(e,t){return e.onWalletAccountChange(t)}export{s as reviveZamaError,c as subscribeWalletAccountChanges,i as toFhevmAuth,a as toViemTypedData};
1
+ import{b as e,i as t,r as n}from"../relayer-Cki3j_Ba.js";import{t as r}from"../fatal-batch-CI0ESPnd.js";import{n as i}from"../fhevm-relayer-DNQAoJtM.js";import{t as a}from"../typed-data-eAgGr9V-.js";const o=r;function s(r,i,a){let s=o[r],c=s?new s(i):new n(r,i,r===t.RelayerRequestFailed?{retryable:a.retryable}:void 0);return c.retryable&&e(a.retryAfter)?Object.assign(c,{retryAfter:a.retryAfter}):c}function c(e,t){return e.onWalletAccountChange(t)}export{s as reviveZamaError,c as subscribeWalletAccountChanges,i as toFhevmAuth,a as toViemTypedData};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{t as e}from"../fhevm-relayer-BQs1LVxv.js";import{t}from"../telemetry-Ct7Tktxt.js";import{t as n}from"../cleartext-BGZFvhAr.js";import{a as r,c as i,i as a,l as o,n as s,o as c,r as l,s as u,t as d,u as f}from"../configs-9EL-DJHq.js";import{AsyncLocalStorage as p}from"node:async_hooks";function m(n){return{type:`node`,createRelayer:(r,i,a)=>{let o=t(globalThis.process?.env?.ZAMA_SDK_TELEMETRY)??a?.mode;return new e({chain:r,options:n,logger:i,telemetry:a&&o!==void 0&&o!==`off`?{state:a,runtime:`node`,mode:o}:void 0})}}}var h=class{#e=new p;run(e){return this.#e.run(/* @__PURE__ */ new Map,e)}async get(e){return this.#e.getStore()?.get(e)??null}async set(e,t){this.#e.getStore()?.set(e,t)}async delete(e){this.#e.getStore()?.delete(e)}};const g=new h;export{h as AsyncLocalMapStorage,d as anvil,g as asyncLocalStorage,s as bscTestnet,l as chains,n as cleartext,a as hardhat,r as hoodi,c as mainnet,m as node,u as polygon,i as polygonAmoy,o as sepolia,f as zenithTrexTestnet};
1
+ import{t as e}from"../fhevm-relayer-DNQAoJtM.js";import{t}from"../telemetry-DSOCwVh_.js";import{t as n}from"../cleartext-DvDvR_Pc.js";import{a as r,c as i,i as a,l as o,n as s,o as c,r as l,s as u,t as d,u as f}from"../configs-9EL-DJHq.js";import{AsyncLocalStorage as p}from"node:async_hooks";function m(n){return{type:`node`,createRelayer:(r,i,a)=>{let o=t(globalThis.process?.env?.ZAMA_SDK_TELEMETRY)??a?.mode;return new e({chain:r,options:n,logger:i,telemetry:a&&o!==void 0&&o!==`off`?{state:a,runtime:`node`,mode:o}:void 0})}}}var h=class{#e=new p;run(e){return this.#e.run(/* @__PURE__ */ new Map,e)}async get(e){return this.#e.getStore()?.get(e)??null}async set(e,t){this.#e.getStore()?.set(e,t)}async delete(e){this.#e.getStore()?.delete(e)}};const g=new h;export{h as AsyncLocalMapStorage,d as anvil,g as asyncLocalStorage,s as bscTestnet,l as chains,n as cleartext,a as hardhat,r as hoodi,c as mainnet,m as node,u as polygon,i as polygonAmoy,o as sepolia,f as zenithTrexTestnet};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{t as e}from"./relayer-Cki3j_Ba.js";import{r as t}from"./configs-9EL-DJHq.js";function n(e){let n=t[e.id];return e.keyVerification!==void 0||n===void 0||n.aclContractAddress.toLowerCase()!==e.aclContractAddress.toLowerCase()?e:{...e,keyVerification:n.keyVerification}}function r(e){let t=e.keyVerification;return t!==void 0&&`chain`in t?t.chain:void 0}function i(t){let n=r(t)??t;if(!(n.keyVerification!==void 0&&`contract`in n.keyVerification))throw new e(`Chain ${t.id} has no KMSGeneration contract to check the FHE public key and CRS against. Set keyVerification on its FheChain: { contract } on an Ethereum host chain, or { chain } with the Ethereum chain that holds it on other host chains.`)}let a,o=!1;function s(e){a=Object.freeze({wasmAssetLoadMode:e.wasmAssetLoadMode,moduleVersions:e.moduleVersions,singleThread:e.singleThread,numberOfThreads:e.numberOfThreads,auth:e.auth}),o=e.locateFile!==void 0}function c(){return a}function l(){return o}function u(e,t){let{layer:n,daemonClient:r}=e.state,i=Object.entries({version:`3.9.0-beta.13`,layer:n,...r===void 0?{runtime:e.runtime}:{runtime:`daemon`,client:r},...t!==void 0&&{operation:t}}),a=e=>Object.fromEntries(i.map(([t,n])=>[`${e}${t}`,n]));return e.mode===`query`?{query:a(`zama_sdk_`)}:{headers:a(`x-zama-sdk-`)}}function d(e,t){return Object.assign({},e,{operation:e?.operation??t})}function f(e){if(typeof e==`boolean`)return e?`header`:`off`;let t=typeof e==`string`?e.trim().toLowerCase():void 0;return t===`0`||t===`false`?`off`:t===`header`||t===`query`||t===`off`?t:void 0}export{l as a,r as c,c as i,n as l,u as n,s as o,d as r,i as s,f as t};
2
- //# sourceMappingURL=telemetry-Ct7Tktxt.js.map
1
+ import{t as e}from"./relayer-Cki3j_Ba.js";import{r as t}from"./configs-9EL-DJHq.js";function n(e){let n=t[e.id];return e.keyVerification!==void 0||n===void 0||n.aclContractAddress.toLowerCase()!==e.aclContractAddress.toLowerCase()?e:{...e,keyVerification:n.keyVerification}}function r(e){let t=e.keyVerification;return t!==void 0&&`chain`in t?t.chain:void 0}function i(t){let n=r(t)??t;if(!(n.keyVerification!==void 0&&`contract`in n.keyVerification))throw new e(`Chain ${t.id} has no KMSGeneration contract to check the FHE public key and CRS against. Set keyVerification on its FheChain: { contract } on an Ethereum host chain, or { chain } with the Ethereum chain that holds it on other host chains.`)}let a,o=!1;function s(e){a=Object.freeze({wasmAssetLoadMode:e.wasmAssetLoadMode,moduleVersions:e.moduleVersions,singleThread:e.singleThread,numberOfThreads:e.numberOfThreads,auth:e.auth}),o=e.locateFile!==void 0}function c(){return a}function l(){return o}function u(e,t){let{layer:n,daemonClient:r}=e.state,i=Object.entries({version:`3.9.0-beta.15`,layer:n,...r===void 0?{runtime:e.runtime}:{runtime:`daemon`,client:r},...t!==void 0&&{operation:t}}),a=e=>Object.fromEntries(i.map(([t,n])=>[`${e}${t}`,n]));return e.mode===`query`?{query:a(`zama_sdk_`)}:{headers:a(`x-zama-sdk-`)}}function d(e,t){return Object.assign({},e,{operation:e?.operation??t})}function f(e){if(typeof e==`boolean`)return e?`header`:`off`;let t=typeof e==`string`?e.trim().toLowerCase():void 0;return t===`0`||t===`false`?`off`:t===`header`||t===`query`||t===`off`?t:void 0}export{l as a,r as c,c as i,n as l,u as n,s as o,d as r,i as s,f as t};
2
+ //# sourceMappingURL=telemetry-DSOCwVh_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-Ct7Tktxt.js","names":["packageJson.version","ConfigurationError","chains","withPresetKeyVerification","preset","chain","keyVerificationChain","keyVerification","assertKeyVerification","holder","appliedWireRuntime","appliedLocateFile","recordAppliedRuntimeConfig","runtime","getAppliedWireRuntime","hasAppliedLocateFile","telemetryRequestOptions","telemetry","fields","daemonClient","operation","prefixed","name","value","prefix","withOperation","options","parseTelemetryMode","mode"],"sources":["../../src/chains/key-verification.ts","../../src/relayer/applied-runtime.ts","../../package.json","../../src/version.ts","../../src/telemetry.ts"],"sourcesContent":["import { ConfigurationError } from \"../errors\";\nimport { chains } from \"./configs\";\nimport type { FheChain } from \"./types\";\n\n/** A chain with a preset's id and ACL is that preset's deployment, so it inherits its `keyVerification`. */\nexport function withPresetKeyVerification(chain: FheChain): FheChain {\n const preset: FheChain | undefined = chains[chain.id];\n if (\n chain.keyVerification !== undefined ||\n preset === undefined ||\n preset.aclContractAddress.toLowerCase() !== chain.aclContractAddress.toLowerCase()\n ) {\n return chain;\n }\n return { ...chain, keyVerification: preset.keyVerification };\n}\n\nexport function keyVerificationChain(chain: FheChain): FheChain | undefined {\n const keyVerification = chain.keyVerification;\n return keyVerification !== undefined && \"chain\" in keyVerification\n ? keyVerification.chain\n : undefined;\n}\n\n/** Throws `ConfigurationError` when a non-cleartext `chain` has no `KMSGeneration` contract to verify its FHE key against. */\nexport function assertKeyVerification(chain: FheChain): void {\n const holder = keyVerificationChain(chain) ?? chain;\n if (holder.keyVerification !== undefined && \"contract\" in holder.keyVerification) {\n return;\n }\n throw new ConfigurationError(\n `Chain ${chain.id} has no KMSGeneration contract to check the FHE public key and CRS against. ` +\n `Set keyVerification on its FheChain: { contract } on an Ethereum host chain, or { chain } with ` +\n `the Ethereum chain that holds it on other host chains.`,\n );\n}\n","import type { FhevmRuntimeConfig, WireRuntimeConfig } from \"./types\";\n\n/**\n * Mirror of the runtime config this package applied via the upstream\n * `setFhevmRuntimeConfig`, which is itself a process-wide one-shot. An encrypt\n * worker realm replicates it, since the upstream lock offers no getter.\n */\nlet appliedWireRuntime: WireRuntimeConfig | undefined;\n\n/** `locateFile` is a function, so it stays off the wire and is only flagged here. */\nlet appliedLocateFile = false;\n\n/** Projects the applied runtime onto the fields a worker realm replicates. */\nexport function recordAppliedRuntimeConfig(runtime: FhevmRuntimeConfig): void {\n appliedWireRuntime = Object.freeze({\n wasmAssetLoadMode: runtime.wasmAssetLoadMode,\n moduleVersions: runtime.moduleVersions,\n singleThread: runtime.singleThread,\n numberOfThreads: runtime.numberOfThreads,\n auth: runtime.auth,\n });\n appliedLocateFile = runtime.locateFile !== undefined;\n}\n\n/** `undefined` when the upstream lock was set outside this package. */\nexport function getAppliedWireRuntime(): WireRuntimeConfig | undefined {\n return appliedWireRuntime;\n}\n\nexport function hasAppliedLocateFile(): boolean {\n return appliedLocateFile;\n}\n\n/** @internal */\nexport function resetAppliedRuntimeConfig(): void {\n appliedWireRuntime = undefined;\n appliedLocateFile = false;\n}\n","","import packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const SDK_VERSION: string = packageJson.version;\n","import { SDK_VERSION } from \"./version\";\n\n// No telemetry field may carry a wallet address, encrypted value, amount or identifier.\n\nexport type TelemetryLayer = \"core\" | \"react\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryRuntime = \"web\" | \"node\" | \"daemon\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryClient = \"go\" | \"rust\" | \"unknown\";\n\nexport type TelemetryMode = \"header\" | \"query\" | \"off\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive method renames. */\nexport type TelemetryOperation =\n | \"balance-of\"\n | \"decrypt-balance-as\"\n | \"batch-balances-of\"\n | \"batch-decrypt-balances-as\"\n | \"confidential-transfer\"\n | \"confidential-transfer-from\"\n | \"confidential-transfer-and-call\"\n | \"confidential-transfer-from-and-call\"\n | \"unshield\"\n | \"unshield-all\"\n | \"resume-unshield\"\n | \"unwrap\"\n | \"finalize-unwrap\"\n | \"vault-deposit\"\n | \"vault-redeem\"\n | \"vault-join\"\n | \"vault-deposit-of\"\n | \"vault-finalize\"\n | \"encrypt\"\n | \"decrypt-values\"\n | \"delegated-decrypt-values\"\n | \"delegated-batch-decrypt-values\"\n | \"decrypt-public-values\"\n | \"offline-confidential-transfer\"\n | \"offline-confidential-transfer-from\"\n | \"offline-unwrap\"\n | \"offline-finalize-unwrap\";\n\n/**\n * Shared by every relayer of a config; `layer` and `daemonClient` are set on it\n * after the relayers exist.\n *\n * @internal\n */\nexport interface TelemetryState {\n layer: TelemetryLayer;\n /** Set only by the daemon; overrides the reported runtime with `daemon`. */\n daemonClient?: TelemetryClient;\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport interface RelayerTelemetry {\n readonly state: TelemetryState;\n readonly runtime: Exclude<TelemetryRuntime, \"daemon\">;\n /** The config's `mode`, unless `ZAMA_SDK_TELEMETRY` overrode it on Node. */\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport function telemetryRequestOptions(\n telemetry: RelayerTelemetry,\n operation: TelemetryOperation | undefined,\n): { headers?: Record<string, string>; query?: Record<string, string> } {\n const { layer, daemonClient } = telemetry.state;\n const fields = Object.entries({\n version: SDK_VERSION,\n layer,\n ...(daemonClient === undefined\n ? { runtime: telemetry.runtime }\n : { runtime: \"daemon\" satisfies TelemetryRuntime, client: daemonClient }),\n ...(operation !== undefined && { operation }),\n });\n const prefixed = (prefix: string) =>\n Object.fromEntries(fields.map(([name, value]) => [`${prefix}${name}`, value]));\n return telemetry.mode === \"query\"\n ? { query: prefixed(\"zama_sdk_\") }\n : { headers: prefixed(\"x-zama-sdk-\") };\n}\n\n/** `options` labelled with `operation`, unless the caller already labelled it. */\nexport function withOperation<T extends { readonly operation?: TelemetryOperation }>(\n options: T | undefined,\n operation: TelemetryOperation,\n): Partial<T> & { readonly operation: TelemetryOperation } {\n return Object.assign({}, options, { operation: options?.operation ?? operation });\n}\n\nexport function parseTelemetryMode(value: string | boolean | undefined): TelemetryMode | undefined {\n if (typeof value === \"boolean\") {\n return value ? \"header\" : \"off\";\n }\n // JavaScript callers can pass anything; only a string can name a mode.\n const mode = typeof value === \"string\" ? value.trim().toLowerCase() : undefined;\n // `0` and `false` predate the named modes and still mean off.\n if (mode === \"0\" || mode === \"false\") {\n return \"off\";\n }\n return mode === \"header\" || mode === \"query\" || mode === \"off\" ? mode : undefined;\n}\n"],"mappings":"A,oFAKA,SAAgBG,EAA0B,EAA2B,CACnE,IAAMC,EAA+BF,EAAOG,EAAM,IAQlD,OANEA,EAAM,kBAAoB,IAAA,IAC1BD,IAAW,IAAA,IACXA,EAAO,mBAAmB,YAAY,IAAMC,EAAM,mBAAmB,YAAY,EAE1EA,EAEF,CAAE,GAAGA,EAAO,gBAAiBD,EAAO,eAAgB,CAC7D,CAEA,SAAgBE,EAAqB,EAAuC,CAC1E,IAAMC,EAAkBF,EAAM,gBAC9B,OAAOE,IAAoB,IAAA,IAAa,UAAWA,EAC/CA,EAAgB,MAChB,IAAA,EACN,CAGA,SAAgBC,EAAsB,EAAuB,CAC3D,IAAMC,EAASH,EAAqBD,CAAK,GAAKA,EAC9C,GAAI,IAAO,kBAAoB,IAAA,IAAa,aAAcI,EAAO,iBAGjE,MAAM,IAAIR,EACR,SAASI,EAAM,GAAG,kOAGpB,CACF,CC5BA,IAAIK,EAGAC,EAAoB,GAGxB,SAAgBC,EAA2B,EAAmC,CAC5E,EAAqB,OAAO,OAAO,CACjC,kBAAmBC,EAAQ,kBAC3B,eAAgBA,EAAQ,eACxB,aAAcA,EAAQ,aACtB,gBAAiBA,EAAQ,gBACzB,KAAMA,EAAQ,IAChB,CAAC,EACD,EAAoBA,EAAQ,aAAe,IAAA,EAC7C,CAGA,SAAgBC,GAAuD,CACrE,OAAOJ,CACT,CAEA,SAAgBK,GAAgC,CAC9C,OAAOJ,CACT,CGiCA,SAAgBK,EACd,EACA,EACsE,CACtE,GAAM,CAAE,QAAO,gBAAiBC,EAAU,MACpCC,EAAS,OAAO,QAAQ,CAC5B,QAAS,gBACT,QACA,GAAIC,IAAiB,IAAA,GACjB,CAAE,QAASF,EAAU,OAAQ,EAC7B,CAAE,QAAS,SAAqC,OAAQE,CAAa,EACzE,GAAIC,IAAc,IAAA,IAAa,CAAE,WAAU,CAC7C,CAAC,EACKC,EAAY,GAChB,OAAO,YAAYH,EAAO,KAAK,CAACI,EAAMC,KAAW,CAAC,GAAGC,IAASF,IAAQC,CAAK,CAAC,CAAC,EAC/E,OAAON,EAAU,OAAS,QACtB,CAAE,MAAOI,EAAS,WAAW,CAAE,EAC/B,CAAE,QAASA,EAAS,aAAa,CAAE,CACzC,CAGA,SAAgBI,EACd,EACA,EACyD,CACzD,OAAO,OAAO,OAAO,CAAC,EAAGC,EAAS,CAAE,UAAWA,GAAS,WAAaN,CAAU,CAAC,CAClF,CAEA,SAAgBO,EAAmB,EAAgE,CACjG,GAAI,OAAOJ,GAAU,UACnB,OAAOA,EAAQ,SAAW,MAG5B,IAAMK,EAAO,OAAOL,GAAU,SAAWA,EAAM,KAAK,CAAC,CAAC,YAAY,EAAI,IAAA,GAKtE,OAHIK,IAAS,KAAOA,IAAS,QACpB,MAEFA,IAAS,UAAYA,IAAS,SAAWA,IAAS,MAAQA,EAAO,IAAA,EAC1E,C"}
1
+ {"version":3,"file":"telemetry-DSOCwVh_.js","names":["packageJson.version","ConfigurationError","chains","withPresetKeyVerification","preset","chain","keyVerificationChain","keyVerification","assertKeyVerification","holder","appliedWireRuntime","appliedLocateFile","recordAppliedRuntimeConfig","runtime","getAppliedWireRuntime","hasAppliedLocateFile","telemetryRequestOptions","telemetry","fields","daemonClient","operation","prefixed","name","value","prefix","withOperation","options","parseTelemetryMode","mode"],"sources":["../../src/chains/key-verification.ts","../../src/relayer/applied-runtime.ts","../../package.json","../../src/version.ts","../../src/telemetry.ts"],"sourcesContent":["import { ConfigurationError } from \"../errors\";\nimport { chains } from \"./configs\";\nimport type { FheChain } from \"./types\";\n\n/** A chain with a preset's id and ACL is that preset's deployment, so it inherits its `keyVerification`. */\nexport function withPresetKeyVerification(chain: FheChain): FheChain {\n const preset: FheChain | undefined = chains[chain.id];\n if (\n chain.keyVerification !== undefined ||\n preset === undefined ||\n preset.aclContractAddress.toLowerCase() !== chain.aclContractAddress.toLowerCase()\n ) {\n return chain;\n }\n return { ...chain, keyVerification: preset.keyVerification };\n}\n\nexport function keyVerificationChain(chain: FheChain): FheChain | undefined {\n const keyVerification = chain.keyVerification;\n return keyVerification !== undefined && \"chain\" in keyVerification\n ? keyVerification.chain\n : undefined;\n}\n\n/** Throws `ConfigurationError` when a non-cleartext `chain` has no `KMSGeneration` contract to verify its FHE key against. */\nexport function assertKeyVerification(chain: FheChain): void {\n const holder = keyVerificationChain(chain) ?? chain;\n if (holder.keyVerification !== undefined && \"contract\" in holder.keyVerification) {\n return;\n }\n throw new ConfigurationError(\n `Chain ${chain.id} has no KMSGeneration contract to check the FHE public key and CRS against. ` +\n `Set keyVerification on its FheChain: { contract } on an Ethereum host chain, or { chain } with ` +\n `the Ethereum chain that holds it on other host chains.`,\n );\n}\n","import type { FhevmRuntimeConfig, WireRuntimeConfig } from \"./types\";\n\n/**\n * Mirror of the runtime config this package applied via the upstream\n * `setFhevmRuntimeConfig`, which is itself a process-wide one-shot. An encrypt\n * worker realm replicates it, since the upstream lock offers no getter.\n */\nlet appliedWireRuntime: WireRuntimeConfig | undefined;\n\n/** `locateFile` is a function, so it stays off the wire and is only flagged here. */\nlet appliedLocateFile = false;\n\n/** Projects the applied runtime onto the fields a worker realm replicates. */\nexport function recordAppliedRuntimeConfig(runtime: FhevmRuntimeConfig): void {\n appliedWireRuntime = Object.freeze({\n wasmAssetLoadMode: runtime.wasmAssetLoadMode,\n moduleVersions: runtime.moduleVersions,\n singleThread: runtime.singleThread,\n numberOfThreads: runtime.numberOfThreads,\n auth: runtime.auth,\n });\n appliedLocateFile = runtime.locateFile !== undefined;\n}\n\n/** `undefined` when the upstream lock was set outside this package. */\nexport function getAppliedWireRuntime(): WireRuntimeConfig | undefined {\n return appliedWireRuntime;\n}\n\nexport function hasAppliedLocateFile(): boolean {\n return appliedLocateFile;\n}\n\n/** @internal */\nexport function resetAppliedRuntimeConfig(): void {\n appliedWireRuntime = undefined;\n appliedLocateFile = false;\n}\n","","import packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const SDK_VERSION: string = packageJson.version;\n","import { SDK_VERSION } from \"./version\";\n\n// No telemetry field may carry a wallet address, encrypted value, amount or identifier.\n\nexport type TelemetryLayer = \"core\" | \"react\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryRuntime = \"web\" | \"node\" | \"daemon\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryClient = \"go\" | \"rust\" | \"unknown\";\n\nexport type TelemetryMode = \"header\" | \"query\" | \"off\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive method renames. */\nexport type TelemetryOperation =\n | \"balance-of\"\n | \"decrypt-balance-as\"\n | \"batch-balances-of\"\n | \"batch-decrypt-balances-as\"\n | \"confidential-transfer\"\n | \"confidential-transfer-from\"\n | \"confidential-transfer-and-call\"\n | \"confidential-transfer-from-and-call\"\n | \"unshield\"\n | \"unshield-all\"\n | \"resume-unshield\"\n | \"unwrap\"\n | \"finalize-unwrap\"\n | \"vault-deposit\"\n | \"vault-redeem\"\n | \"vault-join\"\n | \"vault-deposit-of\"\n | \"vault-finalize\"\n | \"encrypt\"\n | \"decrypt-values\"\n | \"delegated-decrypt-values\"\n | \"delegated-batch-decrypt-values\"\n | \"decrypt-public-values\"\n | \"offline-confidential-transfer\"\n | \"offline-confidential-transfer-from\"\n | \"offline-unwrap\"\n | \"offline-finalize-unwrap\";\n\n/**\n * Shared by every relayer of a config; `layer` and `daemonClient` are set on it\n * after the relayers exist.\n *\n * @internal\n */\nexport interface TelemetryState {\n layer: TelemetryLayer;\n /** Set only by the daemon; overrides the reported runtime with `daemon`. */\n daemonClient?: TelemetryClient;\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport interface RelayerTelemetry {\n readonly state: TelemetryState;\n readonly runtime: Exclude<TelemetryRuntime, \"daemon\">;\n /** The config's `mode`, unless `ZAMA_SDK_TELEMETRY` overrode it on Node. */\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport function telemetryRequestOptions(\n telemetry: RelayerTelemetry,\n operation: TelemetryOperation | undefined,\n): { headers?: Record<string, string>; query?: Record<string, string> } {\n const { layer, daemonClient } = telemetry.state;\n const fields = Object.entries({\n version: SDK_VERSION,\n layer,\n ...(daemonClient === undefined\n ? { runtime: telemetry.runtime }\n : { runtime: \"daemon\" satisfies TelemetryRuntime, client: daemonClient }),\n ...(operation !== undefined && { operation }),\n });\n const prefixed = (prefix: string) =>\n Object.fromEntries(fields.map(([name, value]) => [`${prefix}${name}`, value]));\n return telemetry.mode === \"query\"\n ? { query: prefixed(\"zama_sdk_\") }\n : { headers: prefixed(\"x-zama-sdk-\") };\n}\n\n/** `options` labelled with `operation`, unless the caller already labelled it. */\nexport function withOperation<T extends { readonly operation?: TelemetryOperation }>(\n options: T | undefined,\n operation: TelemetryOperation,\n): Partial<T> & { readonly operation: TelemetryOperation } {\n return Object.assign({}, options, { operation: options?.operation ?? operation });\n}\n\nexport function parseTelemetryMode(value: string | boolean | undefined): TelemetryMode | undefined {\n if (typeof value === \"boolean\") {\n return value ? \"header\" : \"off\";\n }\n // JavaScript callers can pass anything; only a string can name a mode.\n const mode = typeof value === \"string\" ? value.trim().toLowerCase() : undefined;\n // `0` and `false` predate the named modes and still mean off.\n if (mode === \"0\" || mode === \"false\") {\n return \"off\";\n }\n return mode === \"header\" || mode === \"query\" || mode === \"off\" ? mode : undefined;\n}\n"],"mappings":"A,oFAKA,SAAgBG,EAA0B,EAA2B,CACnE,IAAMC,EAA+BF,EAAOG,EAAM,IAQlD,OANEA,EAAM,kBAAoB,IAAA,IAC1BD,IAAW,IAAA,IACXA,EAAO,mBAAmB,YAAY,IAAMC,EAAM,mBAAmB,YAAY,EAE1EA,EAEF,CAAE,GAAGA,EAAO,gBAAiBD,EAAO,eAAgB,CAC7D,CAEA,SAAgBE,EAAqB,EAAuC,CAC1E,IAAMC,EAAkBF,EAAM,gBAC9B,OAAOE,IAAoB,IAAA,IAAa,UAAWA,EAC/CA,EAAgB,MAChB,IAAA,EACN,CAGA,SAAgBC,EAAsB,EAAuB,CAC3D,IAAMC,EAASH,EAAqBD,CAAK,GAAKA,EAC9C,GAAI,IAAO,kBAAoB,IAAA,IAAa,aAAcI,EAAO,iBAGjE,MAAM,IAAIR,EACR,SAASI,EAAM,GAAG,kOAGpB,CACF,CC5BA,IAAIK,EAGAC,EAAoB,GAGxB,SAAgBC,EAA2B,EAAmC,CAC5E,EAAqB,OAAO,OAAO,CACjC,kBAAmBC,EAAQ,kBAC3B,eAAgBA,EAAQ,eACxB,aAAcA,EAAQ,aACtB,gBAAiBA,EAAQ,gBACzB,KAAMA,EAAQ,IAChB,CAAC,EACD,EAAoBA,EAAQ,aAAe,IAAA,EAC7C,CAGA,SAAgBC,GAAuD,CACrE,OAAOJ,CACT,CAEA,SAAgBK,GAAgC,CAC9C,OAAOJ,CACT,CGiCA,SAAgBK,EACd,EACA,EACsE,CACtE,GAAM,CAAE,QAAO,gBAAiBC,EAAU,MACpCC,EAAS,OAAO,QAAQ,CAC5B,QAAS,gBACT,QACA,GAAIC,IAAiB,IAAA,GACjB,CAAE,QAASF,EAAU,OAAQ,EAC7B,CAAE,QAAS,SAAqC,OAAQE,CAAa,EACzE,GAAIC,IAAc,IAAA,IAAa,CAAE,WAAU,CAC7C,CAAC,EACKC,EAAY,GAChB,OAAO,YAAYH,EAAO,KAAK,CAACI,EAAMC,KAAW,CAAC,GAAGC,IAASF,IAAQC,CAAK,CAAC,CAAC,EAC/E,OAAON,EAAU,OAAS,QACtB,CAAE,MAAOI,EAAS,WAAW,CAAE,EAC/B,CAAE,QAASA,EAAS,aAAa,CAAE,CACzC,CAGA,SAAgBI,EACd,EACA,EACyD,CACzD,OAAO,OAAO,OAAO,CAAC,EAAGC,EAAS,CAAE,UAAWA,GAAS,WAAaN,CAAU,CAAC,CAClF,CAEA,SAAgBO,EAAmB,EAAgE,CACjG,GAAI,OAAOJ,GAAU,UACnB,OAAOA,EAAQ,SAAW,MAG5B,IAAMK,EAAO,OAAOL,GAAU,SAAWA,EAAM,KAAK,CAAC,CAAC,YAAY,EAAI,IAAA,GAKtE,OAHIK,IAAS,KAAOA,IAAS,QACpB,MAEFA,IAAS,UAAYA,IAAS,SAAWA,IAAS,MAAQA,EAAO,IAAA,EAC1E,C"}
@@ -1,2 +1,2 @@
1
- import{D as e,H as t,L as n,i as r,j as i,k as a,q as o,x as s,z as c}from"../alignment-D1cVCzw8.js";import{a as l,c as u,l as d,n as f,t as p}from"../token-DnriE-3y.js";import{p as m,t as h}from"../relayer-Cki3j_Ba.js";import{r as g,t as _}from"../encryption-QHaWnnx-.js";import{c as v,l as y,n as b,s as x,t as S,u as C}from"../log-decoding-Cl4zZCe8.js";import{t as w}from"../query-keys-CSPxPLBB.js";import{encodeAbiParameters as ee,encodeFunctionData as T,getAbiItem as te,getAddress as E,isAddress as ne}from"viem";const re=8;function ie(e){return e}function ae(e){return e}function oe(e){return`vaults`in e?e.vaults[0].chainId:e.chainId}function D(e){if(!(`vaults`in e))return{group:void 0,vaults:[e],chainId:e.chainId};let t=`Vault group "${e.id}"`,[n]=e.vaults;if(e.vaults.length>8)throw new h(`${t} has ${e.vaults.length} vaults, more than 8`);let r=/* @__PURE__ */ new Set;for(let i of e.vaults){if(i.chainId!==n.chainId)throw new h(`${t} mixes chains: vault "${i.id}" is on chain ${i.chainId}, vault "${n.id}" on chain ${n.chainId}`);if(r.has(i.id))throw new h(`${t} names vault "${i.id}" twice`);r.add(i.id)}return{group:e,vaults:e.vaults,chainId:n.chainId}}function se(e,t){let n=`Vault "${e.id}" ${t} batcher`,[r,...i]=ce(e.batchers[t],n).map(e=>ue(e,n));if(r===void 0)throw new h(`${n} list is empty`);return[r,...i]}function ce(e,t){if(typeof e==`string`)return[e];if(le(e))return e;if(!(`latest`in e))throw new h(`${t} must be an address or a list`);let n=e.retired.find(e=>e.lastBatchId===void 0);if(n!==void 0)throw new h(`${t} ${n.address} has an invalid lastBatchId: undefined`);return[...e.retired,e.latest]}function le(e){return Array.isArray(e)}function ue(e,t){if(typeof e==`string`)return{address:O(e,t)};let n=O(e.address,t),{lastBatchId:r}=e;if(r===void 0)return{address:n};if(typeof r!=`bigint`||r<0n)throw new h(`${t} ${n} has an invalid lastBatchId: ${String(r)}`);return{address:n,lastBatchId:r}}function O(e,t){if(typeof e!=`string`||!ne(e,{strict:!1}))throw new h(`${t} is not an address: ${String(e)}`);return E(e)}const k=[{type:`function`,name:`batchCallbackDeadline`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchCreatedAt`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchDispatchedAt`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchMaxSlippageBps`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint16`,internalType:`uint16`}],stateMutability:`view`},{type:`function`,name:`batchMinBatchAge`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchState`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint8`,internalType:`enum BatcherConfidential.BatchState`}],stateMutability:`view`},{type:`function`,name:`callbackDeadline`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`claim`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`currentBatchId`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`deposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`dispatchBatch`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`dispatchBatchCallback`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`unwrapAmountCleartext`,type:`uint64`,internalType:`uint64`},{name:`decryptionProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`exchangeRate`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`exchangeRateDecimals`,inputs:[],outputs:[{name:``,type:`uint8`,internalType:`uint8`}],stateMutability:`pure`},{type:`function`,name:`fromToken`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC7984ERC20Wrapper`}],stateMutability:`view`},{type:`function`,name:`join`,inputs:[{name:`beneficiary`,type:`address`,internalType:`address`},{name:`encryptedAmount`,type:`bytes32`,internalType:`externalEuint64`},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[{name:`joined`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`maxSlippageBps`,inputs:[],outputs:[{name:``,type:`uint16`,internalType:`uint16`}],stateMutability:`view`},{type:`function`,name:`minBatchAge`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`closed`,inputs:[],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`paused`,inputs:[],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`quit`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`recover`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:`refunded`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`toToken`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC7984ERC20Wrapper`}],stateMutability:`view`},{type:`function`,name:`totalDeposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`unwrapRequestId`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`vault`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC4626`}],stateMutability:`view`},{type:`event`,name:`BatchCanceled`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`BatchDispatched`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`BatchFinalized`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`exchangeRate`,type:`uint64`,indexed:!1,internalType:`uint64`}],anonymous:!1},{type:`event`,name:`Claimed`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Joined`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Quit`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`error`,name:`BatchNonexistent`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`BatchTooYoung`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`elapsed`,type:`uint256`,internalType:`uint256`},{name:`required`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`BatchUnexpectedState`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`current`,type:`uint8`,internalType:`enum BatcherConfidential.BatchState`},{name:`expectedStates`,type:`bytes32`,internalType:`bytes32`}]},{type:`error`,name:`DuplicateUnderlyingTokens`,inputs:[]},{type:`error`,name:`EnforcedPause`,inputs:[]},{type:`error`,name:`ExpectedPause`,inputs:[]},{type:`error`,name:`IntermediateStepToTokenBalanceChanged`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`InvalidBeneficiary`,inputs:[]},{type:`error`,name:`InvalidCallbackDeadline`,inputs:[]},{type:`error`,name:`InvalidExchangeRate`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`totalDeposits`,type:`uint256`,internalType:`uint256`},{name:`exchangeRate`,type:`uint64`,internalType:`uint64`}]},{type:`error`,name:`InvalidKMSSignatures`,inputs:[]},{type:`error`,name:`InvalidMaxSlippageBps`,inputs:[]},{type:`error`,name:`InvalidMinBatchAge`,inputs:[]},{type:`error`,name:`InvalidTokenRate`,inputs:[]},{type:`error`,name:`InvalidWrapperToken`,inputs:[{name:`token`,type:`address`,internalType:`address`}]},{type:`error`,name:`OwnableInvalidOwner`,inputs:[{name:`owner`,type:`address`,internalType:`address`}]},{type:`error`,name:`OwnableUnauthorizedAccount`,inputs:[{name:`account`,type:`address`,internalType:`address`}]},{type:`error`,name:`ReentrancyGuardReentrantCall`,inputs:[]},{type:`error`,name:`RouteAssetMismatch`,inputs:[{name:`actualAsset`,type:`address`,internalType:`address`},{name:`expectedAsset`,type:`address`,internalType:`address`}]},{type:`error`,name:`RouteShareMismatch`,inputs:[{name:`actualShare`,type:`address`,internalType:`address`},{name:`expectedShare`,type:`address`,internalType:`address`}]},{type:`error`,name:`SafeCastOverflowedUintDowncast`,inputs:[{name:`bits`,type:`uint8`,internalType:`uint8`},{name:`value`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`SafeERC20FailedOperation`,inputs:[{name:`token`,type:`address`,internalType:`address`}]},{type:`error`,name:`SenderNotAllowedToUseHandle`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`sender`,type:`address`,internalType:`address`}]},{type:`error`,name:`SlippageExceeded`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`actual`,type:`uint256`,internalType:`uint256`},{name:`minimum`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`Unauthorized`,inputs:[]},{type:`error`,name:`ZamaProtocolUnsupported`,inputs:[]},{type:`error`,name:`ZeroDeposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}]}];function A(e,t,n){return{address:e,abi:k,functionName:`claim`,args:[t,n]}}function j(e,t){return{address:e,abi:k,functionName:`quit`,args:[t]}}function M(e){return{address:e,abi:k,functionName:`dispatchBatch`,args:[]}}function de(e){return{address:e,abi:k,functionName:`currentBatchId`,args:[]}}function fe(e,t){return{address:e,abi:k,functionName:`batchState`,args:[t]}}function pe(e,t,n){return{address:e,abi:k,functionName:`deposits`,args:[t,n]}}function me(e){return{address:e,abi:k,functionName:`fromToken`,args:[]}}function N(e,t){return{address:e,abi:k,functionName:`batchMinBatchAge`,args:[t]}}function he(e,t){return{address:e,abi:k,functionName:`batchCallbackDeadline`,args:[t]}}function P(e,t){return{address:e,abi:k,functionName:`batchCreatedAt`,args:[t]}}function F(e,t){return{address:e,abi:k,functionName:`batchDispatchedAt`,args:[t]}}function I(e,t){return{address:e,abi:k,functionName:`exchangeRate`,args:[t]}}function L(e){return{address:e,abi:k,functionName:`exchangeRateDecimals`,args:[]}}function R(e){return{address:e,abi:k,functionName:`paused`,args:[]}}function ge(e){return{address:e,abi:k,functionName:`closed`,args:[]}}function _e(e,t){return{address:e,abi:k,functionName:`unwrapRequestId`,args:[t]}}function ve(e,t,n,r){return{address:e,abi:k,functionName:`dispatchBatchCallback`,args:[t,n,r]}}const z=[{type:`function`,name:`join`,inputs:[{name:`legs`,type:`tuple[]`,internalType:`struct IVaultBatcherConfidentialRouter.Allocation[]`,components:[{name:`batcher`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`amount`,type:`bytes32`,internalType:`externalEuint64`}]},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`tokenWrapperRegistry`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract ITokenWrapperRegistry`}],stateMutability:`view`},{type:`error`,name:`InvalidTokenWrapperRegistry`,inputs:[]},{type:`error`,name:`MissingInputProof`,inputs:[]},{type:`error`,name:`ReentrancyGuardReentrantCall`,inputs:[]},{type:`error`,name:`ZamaProtocolUnsupported`,inputs:[]},{type:`error`,name:`UnlistedConfidentialToken`,inputs:[{name:`token`,type:`address`,internalType:`address`}]}];function ye(e,t,n){return{address:e,abi:z,functionName:`join`,args:[t,n]}}const be=te({abi:z,name:`join`}).inputs;function xe(e,t){return ee(be,[e.map(e=>({...e})),t])}const Se=[`pending`,`dispatched`,`finalized`,`canceled`];function B(e){return[...e].sort((e,t)=>{if(e.dispatchableAt!==t.dispatchableAt)return e.dispatchableAt<t.dispatchableAt?-1:1;let[n,r]=[e.batcher.toLowerCase(),t.batcher.toLowerCase()];return n<r?-1:+(n>r)})[0]}function Ce(e,t){let n=e.filter(e=>e.status===`open`);return B(n.filter(e=>!e.blocked&&e.dispatchableAt>=t+60n))??B(n.filter(e=>e.blocked))??B(n)??e.find(e=>e.status===`paused`)}async function V(e,t,n,r){let[i,a]=await Promise.all([e.getBlockTimestamp(t),Promise.all(n.map(async n=>{let i=se(n,r);return{vault:n,entries:i,offers:await Promise.all(i.map(r=>we(e,t,n.id,r)))}}))]);return{now:i,next:a.map(({vault:e,entries:t,offers:n})=>({vault:e,offer:Ce(n,i)??{status:`closed`,batcher:t[0].address}}))}}async function H(e,t,n,r){let i=await e.readContract({...fe(n,r),chainId:t}),a=Se[i];if(a===void 0)throw new h(`Batcher ${n} returned unknown batch state ${i} for batch ${r}; is it a vault batcher?`);return a}async function U(e,t,n,r){return r>1n&&await H(e,t,n,r-1n)===`dispatched`}async function we(e,t,n,r){let i={batcher:r.address,vaultId:n},a=`vault "${n}"`;try{let n=await W(e,t,r)??await W(e,t,r);if(n!==void 0)return n}catch(e){throw e instanceof h?e:new y(`Could not read batcher ${r.address} of ${a}`,i,{cause:e})}throw new y(`Batcher ${r.address} of ${a} has no open batch but is not closed; the RPC returned reads from different blocks`,i,{retryable:!0})}async function W(e,t,{address:n,lastBatchId:r}){let[i,a]=await Promise.all([e.readContract({...R(n),chainId:t}),e.readContract({...de(n),chainId:t})]);if(r!==void 0&&a>r)return{status:`closed`,batcher:n};let[o,s,c]=await Promise.all([e.readContract({...P(n,a),chainId:t}),e.readContract({...N(n,a),chainId:t}),!i&&U(e,t,n,a)]);if(o===0n)return await Te(e,t,n)?{status:`closed`,batcher:n}:void 0;let l=o+s;return i?{status:`paused`,batcher:n,batchId:a,dispatchableAt:l}:{status:`open`,batcher:n,batchId:a,dispatchableAt:l,blocked:c}}async function Te(e,t,n){try{return await e.readContract({...ge(n),chainId:t})}catch(e){if(m(e))return!1;throw e}}const Ee=S(`Joined(uint256,address,bytes32)`);function De(e,t,n){for(let[r,i]of e.entries()){let[a,o,s]=i.topics;if(!(a!==Ee||o===void 0||s===void 0||i.address!==void 0&&E(i.address)!==t||b(s)!==n))return e.splice(r,1),BigInt(o)}return null}const Oe=365n*24n*60n*60n,ke={deposit:`vault-deposit`,redeem:`vault-redeem`},Ae={direct:`vault:join`,router:`vault:routerJoin`};function G(e,t){let n=e[t];return c(n,`vault leg ${t}`),n}function K(e){return{to:e.address,data:T({abi:e.abi,functionName:e.functionName,args:e.args}),value:0n}}function je(e,t){let n=e.vaults.find(e=>e.id===t);if(n===void 0)throw new h(`Vault group "${e.id}" has no vault "${t}"`);return n}function q(e,t,n,r){let i=r===void 0?``:` in group "${r.id}"`,a=n.status===`closed`?`is closed, so the vault takes no joins`:`is paused or closed, so the vault cannot be joined until one resumes`;return new v(`Every ${e} batcher of vault "${t.id}"${i} ${a}`,{batcher:n.batcher,vaultId:t.id})}function J(e){let[t,...n]=e;return c(t,`vault calls`),[t,...n]}function Me(e,t,n){let r=e.get(t);return r===void 0&&(r=n().catch(n=>{throw e.delete(t),n}),e.set(t,r)),r}var Ne=class{#e;#t=/* @__PURE__ */ new Map;constructor(e){this.#e=e}async prepareDeposit(e,t,n){return(await this.#r(`deposit`,e,t,n)).prepared}async prepareRedeem(e,t,n){return(await this.#r(`redeem`,e,t,n)).prepared}prepareClaim(e,t){return K(A(E(e.batcher),e.batchId,E(t)))}prepareQuit(e){return K(j(E(e.batcher),e.batchId))}prepareDispatch(e){return K(M(E(e.batcher)))}async prepareFinalize(e){return(await this.#n(e)).call}async#n(e){let t=E(e.batcher),[r,a,o]=await Promise.all([H(this.#e.provider,e.chainId,t,e.batchId),this.#g(e.chainId,_e(t,e.batchId)),this.#o(e.chainId,t)]);if(r!==`dispatched`)throw new x(`Batch ${e.batchId} of batcher ${t} is ${r}, but only a dispatched batch can be finalized`,{batcher:t,batchId:e.batchId,state:r});let s=await this.#g(e.chainId,i(o,a));await this.#m(e.chainId,`vault finalize`);let{clearValues:c,decryptionProof:l}=await this.#e.decryption.decryptPublicValues([s],{operation:`vault-finalize`}),u=c[s];if(u===void 0)throw new _(`Public decryption returned no value for ${s}`);n(u,`finalize: clearValues[handle]`);let d=ve(t,e.batchId,u,l);return{config:d,call:{chainId:e.chainId,batcher:t,batchId:e.batchId,unwrapAmountCleartext:u,decryptionProof:l,call:K(d)}}}async deposit(e,t,n){return this.#i(`deposit`,e,t,n)}async redeem(e,t,n){return this.#i(`redeem`,e,t,n)}async claim(e,t){let n=await this.#f(e.chainId,`claim`),r=A(E(e.batcher),e.batchId,E(t??n));return this.#p(r,`vault:claim`)}async quit(e){return await this.#f(e.chainId,`quit`),this.#p(j(E(e.batcher),e.batchId),`vault:quit`)}async dispatch(e){return await this.#f(e.chainId,`dispatch`),this.#p(M(E(e.batcher)),`vault:dispatchBatch`)}async finalize(e){return await this.#f(e.chainId,`finalize`),this.#p((await this.#n(e)).config,`vault:finalize`)}async readBatch(e,t){let{chainId:n,batchId:r}=e,i=E(e.batcher),a=t===void 0?void 0:E(t),[o,s,c,l,d,f,p,m,h,g,_]=await Promise.all([H(this.#e.provider,n,i,r),this.#g(n,P(i,r)),this.#g(n,N(i,r)),this.#g(n,F(i,r)),this.#g(n,he(i,r)),this.#g(n,R(i)),this.#g(n,I(i,r)),this.#h(`decimals:${n}:${i}`,()=>this.#g(n,L(i))),a===void 0?null:this.#g(n,pe(i,r,a)),this.#e.provider.getBlockTimestamp(n),U(this.#e.provider,n,i,r)]),v=s+c,y=l+d,b=h!==null&&!u(h),x=[[`claim`,b&&o===`finalized`],[`quit`,b&&(o===`pending`||o===`canceled`)],[`dispatch`,o===`pending`&&!f&&!_&&v<=g],[`finalize`,o===`dispatched`]].flatMap(([e,t])=>t?[e]:[]),S=o===`pending`?v:o===`dispatched`?y:null,C={chainId:n,batcher:i,batchId:r,createdAt:s,dispatchableAt:v,paused:f,deposit:h,actions:x,observedAt:g,nextChangeAt:S!==null&&S>g?S:null};switch(o){case`pending`:return{...C,state:o};case`finalized`:return{...C,state:o,dispatchedAt:l,cancelsAt:y,exchangeRate:{rate:p,decimals:m}};default:return{...C,state:o,dispatchedAt:l,cancelsAt:y}}}async readOpenBatches(e,t){let{group:n,vaults:r,chainId:i}=D(e),{now:a,next:o}=await V(this.#e.provider,i,r,t),s=o.flatMap(({vault:e,offer:r})=>{if(r.status===`closed`){if(n!==void 0)return[];throw q(t,e,r)}let{status:o,batcher:s,batchId:c,dispatchableAt:l}=r;return[{vaultId:e.id,chainId:i,batcher:s,batchId:c,dispatchableAt:l,paused:o===`paused`,observedAt:a}]});if(n!==void 0&&s.length===0){let{vault:e,offer:r}=G(o,0);throw new v(`Every ${t} batcher of every vault in group "${n.id}" is closed, so the group takes no joins`,{batcher:r.batcher,vaultId:e.id})}return s}async#r(e,t,n,r){let{group:i,vaults:a,chainId:o}=D(t),l=i===void 0?a[0]:je(i,n.vaultId),u=E(n.account),d=i===void 0?`direct`:r?.route??`router`;await this.#m(o,`vault ${e}`);let f=i!==void 0&&d===`router`?this.#a(i):void 0,{next:p}=await V(this.#e.provider,o,a,e),m=p.find(({vault:e})=>e===l);if(c(m,`vault ${l.id}`),m.offer.status!==`open`)throw q(e,l,m.offer,i);let g=J(await Promise.all(p.flatMap(({vault:e,offer:t})=>t.status===`open`?[this.#o(o,t.batcher).then(r=>({vaultId:e.id,batcher:t.batcher,token:r,amount:e===l?n.amount:0n}))]:[]))),_=g.find(e=>e.vaultId===l.id);c(_,`vault leg ${l.id}`);let v=g.find(t=>e===`deposit`&&t.token!==_.token);if(v!==void 0)throw new h(`Vault group "${t.id}" mixes deposit assets: vault "${v.vaultId}" takes ${v.token}, vault "${_.vaultId}" takes ${_.token}`);r?.skipBalanceCheck!==!0&&await this.#s(e,g,_,u);let y=ke[e],b=(e,t)=>({config:e,call:{...K(e),kind:`join`,leg:t}}),x,S=[];if(f!==void 0){let t=g.map(e=>e.amount),r=e=>g.map((t,n)=>({batcher:t.batcher,token:t.token,amount:G(e,n)}));if(e===`redeem`){let[[e,n],i]=await Promise.all([this.#c(f,u,t,y),this.#u(o,g,u,f)]);S=i,x=[b(ye(f,r(e),n),_)]}else{let e=_.token,[[i,a],[[o],c]]=await Promise.all([this.#c(f,u,t,y),this.#c(e,u,[n.amount],y)]),l=xe(r(i),a);x=[b(s(e,f,o,c,l),_)]}}else{let e=await this.#l(g,u,y);x=g.map((t,n)=>{let{handle:r,inputProof:i}=G(e,n);return b(s(t.token,t.batcher,r,i,`0x`),t)})}let C=[...S,...x];return{prepared:{direction:e,chainId:o,groupId:i?.id,vaultId:l.id,account:u,amount:n.amount,route:d,legs:g,calls:J(C.map(({call:e})=>e))},planned:C}}async#i(e,t,n,r){let i=this.#d(e),{chainId:a}=D(t),o=await this.#f(a,e),{prepared:s,planned:l}=await this.#r(e,t,{...n,account:o},{skipBalanceCheck:r?.skipBalanceCheck}),u=[],d;for(let[e,{call:t,config:n}]of l.entries())d=await f({operation:t.kind===`operatorApproval`?`setOperator`:Ae[s.route],signer:i,provider:this.#e.provider,config:n,onSubmitted:e===l.length-1?r?.onJoinSubmitted:void 0,emit:e=>this.#e.emitEvent(e,t.to),logger:this.#e.logger}),u.push(d.txHash);c(d,`vault ${e}: last transaction`);let p=[...d.receipt.logs],m=[],h=[];for(let e of s.legs){let t=De(p,e.batcher,o);t===null?h.push(e.vaultId):m.push({vaultId:e.vaultId,chainId:a,batcher:e.batcher,batchId:t})}if(h.length>0)throw new C(`Transaction ${d.txHash} was mined, but its receipt has no Joined event for ${o} from the batcher of ${h.map(e=>`vault "${e}"`).join(`, `)}${`vaults`in t?` in group "${t.id}"`:``}`,{txHash:d.txHash,receipt:d.receipt,unconfirmedVaultIds:h});return{batches:m,txHashes:u}}#a(e){let{chainId:t}=D(e),n=this.#e.chains.find(e=>e.id===t)?.vaultRouterAddress;if(n===void 0)throw new h(`Vault group "${e.id}" has ${e.vaults.length} vaults, but chain ${t} has no router; set vaultRouterAddress on the chain`);return E(n)}#o(e,t){return this.#h(`fromToken:${e}:${t}`,async()=>E(await this.#g(e,me(t))))}async#s(e,t,n,r){let i=this.#e.signer?.walletAccount.getSnapshot()?.address;if(i===void 0||E(i)!==r)throw new d(`Cannot check the balance of ${r} for a vault ${e}: ${i===void 0?`no signer is connected`:`the signer is another account`}. Check it yourself, decrypting every leg's token together, and pass skipBalanceCheck: true`);await l({operation:e,tokenAddress:n.token,amount:n.amount,account:r,signer:this.#e.signer,provider:this.#e.provider,readBalance:async e=>{let r=[...new Set(t.map(e=>e.token))].map(e=>new p(this.#e,e)),{results:i,errors:a}=await p.batchBalancesOf(r,e),o=i.get(n.token);if(o===void 0)throw a.get(n.token)??new d(`Balance validation failed (token: ${n.token})`);return o}})}async#c(e,t,n,r){let{encryptedValues:i,inputProof:a}=await this.#e.encrypt({values:n.map(e=>({value:e,type:`euint64`})),contractAddress:e,userAddress:t},{operation:r}),[o,...s]=i;if(o===void 0||i.length!==n.length)throw new g(`Encryption returned ${i.length} values for ${n.length} legs`);return[[o,...s],a]}async#l(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all([...new Set(e.map(e=>e.token))].map(async i=>{let a=e.filter(e=>e.token===i),[o,s]=await this.#c(i,t,a.map(e=>e.amount),n);a.forEach((e,t)=>r.set(e,{handle:G(o,t),inputProof:s}))})),e.map(e=>{let t=r.get(e);return c(t,`vault leg ${e.vaultId}`),t})}async#u(t,n,r,i){let o=await Promise.all(n.map(n=>this.#g(t,e(n.token,r,i)))),s=n.filter((e,t)=>!o[t]);if(s.length===0)return[];let c=await this.#e.provider.getBlockTimestamp(t)+Oe;return s.map(e=>{let t=a(e.token,i,Number(c));return{config:t,call:{...K(t),kind:`operatorApproval`,vaultId:e.vaultId,operator:i,until:c}}})}#d(e){if(this.#e.signer===void 0)throw new t(e);return this.#e.signer}async#f(e,t){let n=await r(`vault ${t}`,this.#d(t),this.#e.provider,e);return E(n.address)}async#p(e,t){return f({operation:t,signer:this.#d(t),provider:this.#e.provider,config:e,emit:t=>this.#e.emitEvent(t,e.address),logger:this.#e.logger})}async#m(e,t){let n=await this.#e.provider.getChainId();if(n===e)return;let r=this.#e.signer?.walletAccount.getSnapshot();throw r===void 0?new h(`Operation "${t}" encrypts or decrypts on chain ${e}, but the provider is on chain ${n}`):new o({operation:t,signerChainId:r.chainId,providerChainId:n,targetChainId:e})}#h(e,t){return Me(this.#t,e,t)}#g(e,t){return this.#e.provider.readContract({...t,chainId:e})}};function Pe(e){return new Ne(e)}const Y=15e3,X={all:[`zama.vault`],batch:(e,t)=>[`zama.vault`,{kind:`batch`,chainId:e?.chainId,batcher:e===void 0?void 0:E(e.batcher),batchId:e?.batchId,account:t===void 0?void 0:E(t)}],openBatches:(e,t)=>[`zama.vault`,{kind:`openBatches`,chainId:oe(e),scope:`vaults`in e?`group`:`vault`,id:e.id,direction:t}]};function Z(e,t){return Math.min(Number(e-t)*1e3+1e3,36e5)}function Fe(e){if(e===void 0||e.state===`finalized`||e.state===`canceled`)return!1;if(e.nextChangeAt===null)return Y;let t=Z(e.nextChangeAt,e.observedAt);return e.state===`dispatched`?Math.min(t,Y):t}function Ie(e,t={}){let{batch:n,account:r}=t;return{refetchInterval:e=>Fe(e.state.data),queryKey:X.batch(n,r),queryFn:async()=>(c(n,`batchQueryOptions: batch`),e.readBatch(n,r)),enabled:n!==void 0&&t.query?.enabled!==!1}}function Le(e){return e.vault??e.group}function Re(e){let t=(e??[]).filter(e=>!e.paused).map(e=>{let t=e.dispatchableAt-60n;return t>e.observedAt?Z(t,e.observedAt):Y});return t.length!==0&&Math.min(...t)}function Q(e,t){let n=Le(t);return{refetchInterval:e=>Re(e.state.data),queryKey:X.openBatches(n,t.direction),queryFn:async()=>e.readOpenBatches(n,t.direction)}}function ze(e){e.invalidateQueries({queryKey:X.all}),e.invalidateQueries({queryKey:w.confidentialBalance.all}),e.invalidateQueries({queryKey:w.confidentialBalances.all})}function $(e,t){return{mutationKey:[`zama.vault.${t}`],mutationFn:async({skipBalanceCheck:n,onJoinSubmitted:r,amount:i,...a})=>{let o={skipBalanceCheck:n,onJoinSubmitted:r};return a.vault===void 0?e[t](a.group,{vaultId:a.vaultId,amount:i},o):e[t](a.vault,{amount:i},o)}}}function Be(e){return $(e,`deposit`)}function Ve(e){return $(e,`redeem`)}function He(e){return{mutationKey:[`zama.vault.claim`],mutationFn:async({account:t,...n})=>e.claim(n,t)}}function Ue(e){return{mutationKey:[`zama.vault.quit`],mutationFn:async t=>e.quit(t)}}function We(e){return{mutationKey:[`zama.vault.dispatch`],mutationFn:async t=>e.dispatch(t)}}function Ge(e){return{mutationKey:[`zama.vault.finalize`],mutationFn:async t=>e.finalize(t)}}export{re as MAX_GROUP_VAULTS,Ie as batchQueryOptions,He as claimMutationOptions,Pe as createVaultClient,ie as defineVault,ae as defineVaultGroup,Be as depositMutationOptions,We as dispatchMutationOptions,Ge as finalizeMutationOptions,ze as invalidateAfterVaultAction,Q as openBatchesQueryOptions,Ue as quitMutationOptions,Ve as redeemMutationOptions,X as vaultQueryKeys};
1
+ import{D as e,H as t,L as n,i as r,j as i,k as a,q as o,x as s,z as c}from"../alignment-D1cVCzw8.js";import{a as l,c as u,l as d,n as f,t as p}from"../token-DnriE-3y.js";import{p as m,t as h}from"../relayer-Cki3j_Ba.js";import{r as g,t as _}from"../encryption-QHaWnnx-.js";import{c as v,l as y,n as b,s as x,t as S,u as C}from"../log-decoding-Cl4zZCe8.js";import{t as w}from"../query-keys-CSPxPLBB.js";import{encodeAbiParameters as ee,encodeFunctionData as te,getAbiItem as ne,getAddress as T,isAddress as re,zeroHash as ie}from"viem";const ae=8;function oe(e){return e}function se(e){return e}function ce(e){return`vaults`in e?e.vaults[0].chainId:e.chainId}function E(e){if(!(`vaults`in e))return{group:void 0,vaults:[e],chainId:e.chainId};let t=`Vault group "${e.id}"`,[n]=e.vaults;if(e.vaults.length>8)throw new h(`${t} has ${e.vaults.length} vaults, more than 8`);let r=/* @__PURE__ */ new Set;for(let i of e.vaults){if(i.chainId!==n.chainId)throw new h(`${t} mixes chains: vault "${i.id}" is on chain ${i.chainId}, vault "${n.id}" on chain ${n.chainId}`);if(r.has(i.id))throw new h(`${t} names vault "${i.id}" twice`);r.add(i.id)}return{group:e,vaults:e.vaults,chainId:n.chainId}}function le(e,t){let n=`Vault "${e.id}" ${t} batcher`,[r,...i]=ue(e.batchers[t],n).map(e=>fe(e,n));if(r===void 0)throw new h(`${n} list is empty`);return[r,...i]}function ue(e,t){if(typeof e==`string`)return[e];if(de(e))return e;if(!(`latest`in e))throw new h(`${t} must be an address or a list`);let n=e.retired.find(e=>e.lastBatchId===void 0);if(n!==void 0)throw new h(`${t} ${n.address} has an invalid lastBatchId: undefined`);return[...e.retired,e.latest]}function de(e){return Array.isArray(e)}function fe(e,t){if(typeof e==`string`)return{address:D(e,t)};let n=D(e.address,t),{lastBatchId:r}=e;if(r===void 0)return{address:n};if(typeof r!=`bigint`||r<0n)throw new h(`${t} ${n} has an invalid lastBatchId: ${String(r)}`);return{address:n,lastBatchId:r}}function D(e,t){if(typeof e!=`string`||!re(e,{strict:!1}))throw new h(`${t} is not an address: ${String(e)}`);return T(e)}const O=[{type:`function`,name:`batchCallbackDeadline`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchCreatedAt`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchDispatchedAt`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchMaxSlippageBps`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint16`,internalType:`uint16`}],stateMutability:`view`},{type:`function`,name:`batchMinBatchAge`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`batchState`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint8`,internalType:`enum BatcherConfidential.BatchState`}],stateMutability:`view`},{type:`function`,name:`callbackDeadline`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`claim`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`currentBatchId`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`deposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`dispatchBatch`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`dispatchBatchCallback`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`unwrapAmountCleartext`,type:`uint64`,internalType:`uint64`},{name:`decryptionProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`exchangeRate`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`exchangeRateDecimals`,inputs:[],outputs:[{name:``,type:`uint8`,internalType:`uint8`}],stateMutability:`pure`},{type:`function`,name:`fromToken`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC7984ERC20Wrapper`}],stateMutability:`view`},{type:`function`,name:`join`,inputs:[{name:`beneficiary`,type:`address`,internalType:`address`},{name:`encryptedAmount`,type:`bytes32`,internalType:`externalEuint64`},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[{name:`joined`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`maxSlippageBps`,inputs:[],outputs:[{name:``,type:`uint16`,internalType:`uint16`}],stateMutability:`view`},{type:`function`,name:`minBatchAge`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`closed`,inputs:[],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`paused`,inputs:[],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`quit`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`recover`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:`refunded`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`toToken`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC7984ERC20Wrapper`}],stateMutability:`view`},{type:`function`,name:`totalDeposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`unwrapRequestId`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`vault`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract IERC4626`}],stateMutability:`view`},{type:`event`,name:`BatchCanceled`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`BatchDispatched`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`BatchFinalized`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`exchangeRate`,type:`uint64`,indexed:!1,internalType:`uint64`}],anonymous:!1},{type:`event`,name:`Claimed`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Joined`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Quit`,inputs:[{name:`batchId`,type:`uint256`,indexed:!0,internalType:`uint256`},{name:`account`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`error`,name:`BatchNonexistent`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`BatchTooYoung`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`elapsed`,type:`uint256`,internalType:`uint256`},{name:`required`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`BatchUnexpectedState`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`current`,type:`uint8`,internalType:`enum BatcherConfidential.BatchState`},{name:`expectedStates`,type:`bytes32`,internalType:`bytes32`}]},{type:`error`,name:`DuplicateUnderlyingTokens`,inputs:[]},{type:`error`,name:`EnforcedPause`,inputs:[]},{type:`error`,name:`ExpectedPause`,inputs:[]},{type:`error`,name:`IntermediateStepToTokenBalanceChanged`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`InvalidBeneficiary`,inputs:[]},{type:`error`,name:`InvalidCallbackDeadline`,inputs:[]},{type:`error`,name:`InvalidExchangeRate`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`totalDeposits`,type:`uint256`,internalType:`uint256`},{name:`exchangeRate`,type:`uint64`,internalType:`uint64`}]},{type:`error`,name:`InvalidKMSSignatures`,inputs:[]},{type:`error`,name:`InvalidMaxSlippageBps`,inputs:[]},{type:`error`,name:`InvalidMinBatchAge`,inputs:[]},{type:`error`,name:`InvalidTokenRate`,inputs:[]},{type:`error`,name:`InvalidWrapperToken`,inputs:[{name:`token`,type:`address`,internalType:`address`}]},{type:`error`,name:`OwnableInvalidOwner`,inputs:[{name:`owner`,type:`address`,internalType:`address`}]},{type:`error`,name:`OwnableUnauthorizedAccount`,inputs:[{name:`account`,type:`address`,internalType:`address`}]},{type:`error`,name:`ReentrancyGuardReentrantCall`,inputs:[]},{type:`error`,name:`RouteAssetMismatch`,inputs:[{name:`actualAsset`,type:`address`,internalType:`address`},{name:`expectedAsset`,type:`address`,internalType:`address`}]},{type:`error`,name:`RouteShareMismatch`,inputs:[{name:`actualShare`,type:`address`,internalType:`address`},{name:`expectedShare`,type:`address`,internalType:`address`}]},{type:`error`,name:`SafeCastOverflowedUintDowncast`,inputs:[{name:`bits`,type:`uint8`,internalType:`uint8`},{name:`value`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`SafeERC20FailedOperation`,inputs:[{name:`token`,type:`address`,internalType:`address`}]},{type:`error`,name:`SenderNotAllowedToUseHandle`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`sender`,type:`address`,internalType:`address`}]},{type:`error`,name:`SlippageExceeded`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`actual`,type:`uint256`,internalType:`uint256`},{name:`minimum`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`Unauthorized`,inputs:[]},{type:`error`,name:`ZamaProtocolUnsupported`,inputs:[]},{type:`error`,name:`ZeroDeposits`,inputs:[{name:`batchId`,type:`uint256`,internalType:`uint256`},{name:`account`,type:`address`,internalType:`address`}]}];function k(e,t,n){return{address:e,abi:O,functionName:`claim`,args:[t,n]}}function A(e,t){return{address:e,abi:O,functionName:`quit`,args:[t]}}function j(e){return{address:e,abi:O,functionName:`dispatchBatch`,args:[]}}function pe(e){return{address:e,abi:O,functionName:`currentBatchId`,args:[]}}function me(e,t){return{address:e,abi:O,functionName:`batchState`,args:[t]}}function he(e,t,n){return{address:e,abi:O,functionName:`deposits`,args:[t,n]}}function ge(e){return{address:e,abi:O,functionName:`fromToken`,args:[]}}function M(e,t){return{address:e,abi:O,functionName:`batchMinBatchAge`,args:[t]}}function _e(e,t){return{address:e,abi:O,functionName:`batchCallbackDeadline`,args:[t]}}function N(e,t){return{address:e,abi:O,functionName:`batchCreatedAt`,args:[t]}}function P(e,t){return{address:e,abi:O,functionName:`batchDispatchedAt`,args:[t]}}function F(e,t){return{address:e,abi:O,functionName:`exchangeRate`,args:[t]}}function I(e){return{address:e,abi:O,functionName:`exchangeRateDecimals`,args:[]}}function L(e){return{address:e,abi:O,functionName:`paused`,args:[]}}function ve(e){return{address:e,abi:O,functionName:`closed`,args:[]}}function R(e,t){return{address:e,abi:O,functionName:`unwrapRequestId`,args:[t]}}function ye(e,t,n,r){return{address:e,abi:O,functionName:`dispatchBatchCallback`,args:[t,n,r]}}const z=[{type:`function`,name:`join`,inputs:[{name:`legs`,type:`tuple[]`,internalType:`struct IVaultBatcherConfidentialRouter.Allocation[]`,components:[{name:`batcher`,type:`address`,internalType:`address`},{name:`token`,type:`address`,internalType:`address`},{name:`amount`,type:`bytes32`,internalType:`externalEuint64`}]},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`tokenWrapperRegistry`,inputs:[],outputs:[{name:``,type:`address`,internalType:`contract ITokenWrapperRegistry`}],stateMutability:`view`},{type:`error`,name:`InvalidTokenWrapperRegistry`,inputs:[]},{type:`error`,name:`MissingInputProof`,inputs:[]},{type:`error`,name:`ReentrancyGuardReentrantCall`,inputs:[]},{type:`error`,name:`ZamaProtocolUnsupported`,inputs:[]},{type:`error`,name:`UnlistedConfidentialToken`,inputs:[{name:`token`,type:`address`,internalType:`address`}]}];function be(e,t,n){return{address:e,abi:z,functionName:`join`,args:[t,n]}}const xe=ne({abi:z,name:`join`}).inputs;function Se(e,t){return ee(xe,[e.map(e=>({...e})),t])}const Ce=[`pending`,`dispatched`,`finalized`,`canceled`];function B(e){return[...e].sort((e,t)=>{if(e.dispatchableAt!==t.dispatchableAt)return e.dispatchableAt<t.dispatchableAt?-1:1;let[n,r]=[e.batcher.toLowerCase(),t.batcher.toLowerCase()];return n<r?-1:+(n>r)})[0]}function we(e,t){let n=e.filter(e=>e.status===`open`);return B(n.filter(e=>!e.blocked&&e.dispatchableAt>=t+60n))??B(n.filter(e=>e.blocked))??B(n)??e.find(e=>e.status===`paused`)}async function V(e,t,n,r){let[i,a]=await Promise.all([e.getBlockTimestamp(t),Promise.all(n.map(async n=>{let i=le(n,r);return{vault:n,entries:i,offers:await Promise.all(i.map(r=>Te(e,t,n.id,r)))}}))]);return{now:i,next:a.map(({vault:e,entries:t,offers:n})=>({vault:e,offer:we(n,i)??{status:`closed`,batcher:t[0].address}}))}}async function H(e,t,n,r){let i=await e.readContract({...me(n,r),chainId:t}),a=Ce[i];if(a===void 0)throw new h(`Batcher ${n} returned unknown batch state ${i} for batch ${r}; is it a vault batcher?`);return a}async function U(e,t,n,r){if(r<=1n)return!1;let i=r-1n;return await e.readContract({...R(n,i),chainId:t})!==ie&&await H(e,t,n,i)===`dispatched`}async function Te(e,t,n,r){let i={batcher:r.address,vaultId:n},a=`vault "${n}"`;try{let n=await W(e,t,r)??await W(e,t,r);if(n!==void 0)return n}catch(e){throw e instanceof h?e:new y(`Could not read batcher ${r.address} of ${a}`,i,{cause:e})}throw new y(`Batcher ${r.address} of ${a} has no open batch but is not closed; the RPC returned reads from different blocks`,i,{retryable:!0})}async function W(e,t,{address:n,lastBatchId:r}){let[i,a]=await Promise.all([e.readContract({...L(n),chainId:t}),e.readContract({...pe(n),chainId:t})]);if(r!==void 0&&a>r)return{status:`closed`,batcher:n};let[o,s,c]=await Promise.all([e.readContract({...N(n,a),chainId:t}),e.readContract({...M(n,a),chainId:t}),!i&&U(e,t,n,a)]);if(o===0n)return await Ee(e,t,n)?{status:`closed`,batcher:n}:void 0;let l=o+s;return i?{status:`paused`,batcher:n,batchId:a,dispatchableAt:l}:{status:`open`,batcher:n,batchId:a,dispatchableAt:l,blocked:c}}async function Ee(e,t,n){try{return await e.readContract({...ve(n),chainId:t})}catch(e){if(m(e))return!1;throw e}}const De=S(`Joined(uint256,address,bytes32)`);function Oe(e,t,n){for(let[r,i]of e.entries()){let[a,o,s]=i.topics;if(!(a!==De||o===void 0||s===void 0||i.address!==void 0&&T(i.address)!==t||b(s)!==n))return e.splice(r,1),BigInt(o)}return null}const ke=365n*24n*60n*60n,Ae={deposit:`vault-deposit`,redeem:`vault-redeem`},je={direct:`vault:join`,router:`vault:routerJoin`};function G(e,t){let n=e[t];return c(n,`vault leg ${t}`),n}function K(e){return{to:e.address,data:te({abi:e.abi,functionName:e.functionName,args:e.args}),value:0n}}function Me(e,t){let n=e.vaults.find(e=>e.id===t);if(n===void 0)throw new h(`Vault group "${e.id}" has no vault "${t}"`);return n}function q(e,t,n,r){let i=r===void 0?``:` in group "${r.id}"`,a=n.status===`closed`?`is closed, so the vault takes no joins`:`is paused or closed, so the vault cannot be joined until one resumes`;return new v(`Every ${e} batcher of vault "${t.id}"${i} ${a}`,{batcher:n.batcher,vaultId:t.id})}function J(e){let[t,...n]=e;return c(t,`vault calls`),[t,...n]}function Ne(e,t,n){let r=e.get(t);return r===void 0&&(r=n().catch(n=>{throw e.delete(t),n}),e.set(t,r)),r}var Pe=class{#e;#t=/* @__PURE__ */ new Map;constructor(e){this.#e=e}async prepareDeposit(e,t,n){return(await this.#r(`deposit`,e,t,n)).prepared}async prepareRedeem(e,t,n){return(await this.#r(`redeem`,e,t,n)).prepared}prepareClaim(e,t){return K(k(T(e.batcher),e.batchId,T(t)))}prepareQuit(e){return K(A(T(e.batcher),e.batchId))}prepareDispatch(e){return K(j(T(e.batcher)))}async prepareFinalize(e){return(await this.#n(e)).call}async#n(e){let t=T(e.batcher),[r,a,o]=await Promise.all([H(this.#e.provider,e.chainId,t,e.batchId),this.#g(e.chainId,R(t,e.batchId)),this.#o(e.chainId,t)]);if(r!==`dispatched`)throw new x(`Batch ${e.batchId} of batcher ${t} is ${r}, but only a dispatched batch can be finalized`,{batcher:t,batchId:e.batchId,state:r});let s=await this.#g(e.chainId,i(o,a));await this.#m(e.chainId,`vault finalize`);let{clearValues:c,decryptionProof:l}=await this.#e.decryption.decryptPublicValues([s],{operation:`vault-finalize`}),u=c[s];if(u===void 0)throw new _(`Public decryption returned no value for ${s}`);n(u,`finalize: clearValues[handle]`);let d=ye(t,e.batchId,u,l);return{config:d,call:{chainId:e.chainId,batcher:t,batchId:e.batchId,unwrapAmountCleartext:u,decryptionProof:l,call:K(d)}}}async deposit(e,t,n){return this.#i(`deposit`,e,t,n)}async redeem(e,t,n){return this.#i(`redeem`,e,t,n)}async claim(e,t){let n=await this.#f(e.chainId,`claim`),r=k(T(e.batcher),e.batchId,T(t??n));return this.#p(r,`vault:claim`)}async quit(e){return await this.#f(e.chainId,`quit`),this.#p(A(T(e.batcher),e.batchId),`vault:quit`)}async dispatch(e){return await this.#f(e.chainId,`dispatch`),this.#p(j(T(e.batcher)),`vault:dispatchBatch`)}async finalize(e){return await this.#f(e.chainId,`finalize`),this.#p((await this.#n(e)).config,`vault:finalize`)}async readBatch(e,t){let{chainId:n,batchId:r}=e,i=T(e.batcher),a=t===void 0?void 0:T(t),[o,s,c,l,d,f,p,m,h,g,_]=await Promise.all([H(this.#e.provider,n,i,r),this.#g(n,N(i,r)),this.#g(n,M(i,r)),this.#g(n,P(i,r)),this.#g(n,_e(i,r)),this.#g(n,L(i)),this.#g(n,F(i,r)),this.#h(`decimals:${n}:${i}`,()=>this.#g(n,I(i))),a===void 0?null:this.#g(n,he(i,r,a)),this.#e.provider.getBlockTimestamp(n),U(this.#e.provider,n,i,r)]),v=s+c,y=l+d,b=h!==null&&!u(h),x=[[`claim`,b&&o===`finalized`],[`quit`,b&&(o===`pending`||o===`canceled`)],[`dispatch`,o===`pending`&&!f&&!_&&v<=g],[`finalize`,o===`dispatched`]].flatMap(([e,t])=>t?[e]:[]),S=o===`pending`?v:o===`dispatched`?y:null,C={chainId:n,batcher:i,batchId:r,createdAt:s,dispatchableAt:v,paused:f,deposit:h,actions:x,observedAt:g,nextChangeAt:S!==null&&S>g?S:null};switch(o){case`pending`:return{...C,state:o};case`finalized`:return{...C,state:o,dispatchedAt:l,cancelsAt:y,exchangeRate:{rate:p,decimals:m}};default:return{...C,state:o,dispatchedAt:l,cancelsAt:y}}}async readOpenBatches(e,t){let{group:n,vaults:r,chainId:i}=E(e),{now:a,next:o}=await V(this.#e.provider,i,r,t),s=o.flatMap(({vault:e,offer:r})=>{if(r.status===`closed`){if(n!==void 0)return[];throw q(t,e,r)}let{status:o,batcher:s,batchId:c,dispatchableAt:l}=r;return[{vaultId:e.id,chainId:i,batcher:s,batchId:c,dispatchableAt:l,paused:o===`paused`,observedAt:a}]});if(n!==void 0&&s.length===0){let{vault:e,offer:r}=G(o,0);throw new v(`Every ${t} batcher of every vault in group "${n.id}" is closed, so the group takes no joins`,{batcher:r.batcher,vaultId:e.id})}return s}async#r(e,t,n,r){let{group:i,vaults:a,chainId:o}=E(t),l=i===void 0?a[0]:Me(i,n.vaultId),u=T(n.account),d=i===void 0?`direct`:r?.route??`router`;await this.#m(o,`vault ${e}`);let f=i!==void 0&&d===`router`?this.#a(i):void 0,{next:p}=await V(this.#e.provider,o,a,e),m=p.find(({vault:e})=>e===l);if(c(m,`vault ${l.id}`),m.offer.status!==`open`)throw q(e,l,m.offer,i);let g=J(await Promise.all(p.flatMap(({vault:e,offer:t})=>t.status===`open`?[this.#o(o,t.batcher).then(r=>({vaultId:e.id,batcher:t.batcher,token:r,amount:e===l?n.amount:0n}))]:[]))),_=g.find(e=>e.vaultId===l.id);c(_,`vault leg ${l.id}`);let v=g.find(t=>e===`deposit`&&t.token!==_.token);if(v!==void 0)throw new h(`Vault group "${t.id}" mixes deposit assets: vault "${v.vaultId}" takes ${v.token}, vault "${_.vaultId}" takes ${_.token}`);r?.skipBalanceCheck!==!0&&await this.#s(e,g,_,u);let y=Ae[e],b=(e,t)=>({config:e,call:{...K(e),kind:`join`,leg:t}}),x,S=[];if(f!==void 0){let t=g.map(e=>e.amount),r=e=>g.map((t,n)=>({batcher:t.batcher,token:t.token,amount:G(e,n)}));if(e===`redeem`){let[[e,n],i]=await Promise.all([this.#c(f,u,t,y),this.#u(o,g,u,f)]);S=i,x=[b(be(f,r(e),n),_)]}else{let e=_.token,[[i,a],[[o],c]]=await Promise.all([this.#c(f,u,t,y),this.#c(e,u,[n.amount],y)]),l=Se(r(i),a);x=[b(s(e,f,o,c,l),_)]}}else{let e=await this.#l(g,u,y);x=g.map((t,n)=>{let{handle:r,inputProof:i}=G(e,n);return b(s(t.token,t.batcher,r,i,`0x`),t)})}let C=[...S,...x];return{prepared:{direction:e,chainId:o,groupId:i?.id,vaultId:l.id,account:u,amount:n.amount,route:d,legs:g,calls:J(C.map(({call:e})=>e))},planned:C}}async#i(e,t,n,r){let i=this.#d(e),{chainId:a}=E(t),o=await this.#f(a,e),{prepared:s,planned:l}=await this.#r(e,t,{...n,account:o},{skipBalanceCheck:r?.skipBalanceCheck}),u=[],d;for(let[e,{call:t,config:n}]of l.entries())d=await f({operation:t.kind===`operatorApproval`?`setOperator`:je[s.route],signer:i,provider:this.#e.provider,config:n,onSubmitted:e===l.length-1?r?.onJoinSubmitted:void 0,emit:e=>this.#e.emitEvent(e,t.to),logger:this.#e.logger}),u.push(d.txHash);c(d,`vault ${e}: last transaction`);let p=[...d.receipt.logs],m=[],h=[];for(let e of s.legs){let t=Oe(p,e.batcher,o);t===null?h.push(e.vaultId):m.push({vaultId:e.vaultId,chainId:a,batcher:e.batcher,batchId:t})}if(h.length>0)throw new C(`Transaction ${d.txHash} was mined, but its receipt has no Joined event for ${o} from the batcher of ${h.map(e=>`vault "${e}"`).join(`, `)}${`vaults`in t?` in group "${t.id}"`:``}`,{txHash:d.txHash,receipt:d.receipt,unconfirmedVaultIds:h});return{batches:m,txHashes:u}}#a(e){let{chainId:t}=E(e),n=this.#e.chains.find(e=>e.id===t)?.vaultRouterAddress;if(n===void 0)throw new h(`Vault group "${e.id}" has ${e.vaults.length} vaults, but chain ${t} has no router; set vaultRouterAddress on the chain`);return T(n)}#o(e,t){return this.#h(`fromToken:${e}:${t}`,async()=>T(await this.#g(e,ge(t))))}async#s(e,t,n,r){let i=this.#e.signer?.walletAccount.getSnapshot()?.address;if(i===void 0||T(i)!==r)throw new d(`Cannot check the balance of ${r} for a vault ${e}: ${i===void 0?`no signer is connected`:`the signer is another account`}. Check it yourself, decrypting every leg's token together, and pass skipBalanceCheck: true`);await l({operation:e,tokenAddress:n.token,amount:n.amount,account:r,signer:this.#e.signer,provider:this.#e.provider,readBalance:async e=>{let r=[...new Set(t.map(e=>e.token))].map(e=>new p(this.#e,e)),{results:i,errors:a}=await p.batchBalancesOf(r,e),o=i.get(n.token);if(o===void 0)throw a.get(n.token)??new d(`Balance validation failed (token: ${n.token})`);return o}})}async#c(e,t,n,r){let{encryptedValues:i,inputProof:a}=await this.#e.encrypt({values:n.map(e=>({value:e,type:`euint64`})),contractAddress:e,userAddress:t},{operation:r}),[o,...s]=i;if(o===void 0||i.length!==n.length)throw new g(`Encryption returned ${i.length} values for ${n.length} legs`);return[[o,...s],a]}async#l(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all([...new Set(e.map(e=>e.token))].map(async i=>{let a=e.filter(e=>e.token===i),[o,s]=await this.#c(i,t,a.map(e=>e.amount),n);a.forEach((e,t)=>r.set(e,{handle:G(o,t),inputProof:s}))})),e.map(e=>{let t=r.get(e);return c(t,`vault leg ${e.vaultId}`),t})}async#u(t,n,r,i){let o=await Promise.all(n.map(n=>this.#g(t,e(n.token,r,i)))),s=n.filter((e,t)=>!o[t]);if(s.length===0)return[];let c=await this.#e.provider.getBlockTimestamp(t)+ke;return s.map(e=>{let t=a(e.token,i,Number(c));return{config:t,call:{...K(t),kind:`operatorApproval`,vaultId:e.vaultId,operator:i,until:c}}})}#d(e){if(this.#e.signer===void 0)throw new t(e);return this.#e.signer}async#f(e,t){let n=await r(`vault ${t}`,this.#d(t),this.#e.provider,e);return T(n.address)}async#p(e,t){return f({operation:t,signer:this.#d(t),provider:this.#e.provider,config:e,emit:t=>this.#e.emitEvent(t,e.address),logger:this.#e.logger})}async#m(e,t){let n=await this.#e.provider.getChainId();if(n===e)return;let r=this.#e.signer?.walletAccount.getSnapshot();throw r===void 0?new h(`Operation "${t}" encrypts or decrypts on chain ${e}, but the provider is on chain ${n}`):new o({operation:t,signerChainId:r.chainId,providerChainId:n,targetChainId:e})}#h(e,t){return Ne(this.#t,e,t)}#g(e,t){return this.#e.provider.readContract({...t,chainId:e})}};function Fe(e){return new Pe(e)}const Y=15e3,X={all:[`zama.vault`],batch:(e,t)=>[`zama.vault`,{kind:`batch`,chainId:e?.chainId,batcher:e===void 0?void 0:T(e.batcher),batchId:e?.batchId,account:t===void 0?void 0:T(t)}],openBatches:(e,t)=>[`zama.vault`,{kind:`openBatches`,chainId:ce(e),scope:`vaults`in e?`group`:`vault`,id:e.id,direction:t}]};function Z(e,t){return Math.min(Number(e-t)*1e3+1e3,36e5)}function Q(e){if(e===void 0||e.state===`finalized`||e.state===`canceled`)return!1;if(e.nextChangeAt===null)return Y;let t=Z(e.nextChangeAt,e.observedAt);return e.state===`dispatched`?Math.min(t,Y):t}function Ie(e,t={}){let{batch:n,account:r}=t;return{refetchInterval:e=>Q(e.state.data),queryKey:X.batch(n,r),queryFn:async()=>(c(n,`batchQueryOptions: batch`),e.readBatch(n,r)),enabled:n!==void 0&&t.query?.enabled!==!1}}function Le(e){return e.vault??e.group}function Re(e){let t=(e??[]).filter(e=>!e.paused).map(e=>{let t=e.dispatchableAt-60n;return t>e.observedAt?Z(t,e.observedAt):Y});return t.length!==0&&Math.min(...t)}function ze(e,t){let n=Le(t);return{refetchInterval:e=>Re(e.state.data),queryKey:X.openBatches(n,t.direction),queryFn:async()=>e.readOpenBatches(n,t.direction)}}function Be(e){e.invalidateQueries({queryKey:X.all}),e.invalidateQueries({queryKey:w.confidentialBalance.all}),e.invalidateQueries({queryKey:w.confidentialBalances.all})}function $(e,t){return{mutationKey:[`zama.vault.${t}`],mutationFn:async({skipBalanceCheck:n,onJoinSubmitted:r,amount:i,...a})=>{let o={skipBalanceCheck:n,onJoinSubmitted:r};return a.vault===void 0?e[t](a.group,{vaultId:a.vaultId,amount:i},o):e[t](a.vault,{amount:i},o)}}}function Ve(e){return $(e,`deposit`)}function He(e){return $(e,`redeem`)}function Ue(e){return{mutationKey:[`zama.vault.claim`],mutationFn:async({account:t,...n})=>e.claim(n,t)}}function We(e){return{mutationKey:[`zama.vault.quit`],mutationFn:async t=>e.quit(t)}}function Ge(e){return{mutationKey:[`zama.vault.dispatch`],mutationFn:async t=>e.dispatch(t)}}function Ke(e){return{mutationKey:[`zama.vault.finalize`],mutationFn:async t=>e.finalize(t)}}export{ae as MAX_GROUP_VAULTS,Ie as batchQueryOptions,Ue as claimMutationOptions,Fe as createVaultClient,oe as defineVault,se as defineVaultGroup,Ve as depositMutationOptions,Ge as dispatchMutationOptions,Ke as finalizeMutationOptions,Be as invalidateAfterVaultAction,ze as openBatchesQueryOptions,We as quitMutationOptions,He as redeemMutationOptions,X as vaultQueryKeys};
2
2
  //# sourceMappingURL=index.js.map