@zama-fhe/sdk 3.8.0-beta.2 → 3.8.0-beta.3

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{S as e,_ as t,a as n,b as r,c as i,d as a,g as o,h as s,i as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,v as ee}from"./relayer-C3jVhqSK.js";import{a as g,c as te,d as ne,i as _,l as v,n as re,o as y,s as ie,t as b,u as ae}from"./signing-C6nbPCyd.js";import{n as oe,r as x,t as S}from"./encryption-6AVd-82z.js";import{A as se,B as ce,C as le,D as ue,E as de,F as C,H as fe,L as pe,M as me,O as he,P as ge,R as _e,S as ve,T as ye,V as w,a as be,b as xe,c as Se,d as Ce,g as we,h as Te,i as Ee,j as T,k as De,l as E,m as Oe,n as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe,v as D,w as Fe,x as O,z as Ie}from"./erc165-B8gx2luK.js";import{n as Le,r as k}from"./fatal-batch-BiiS7KdS.js";import{a as A,c as Re,d as ze,f as Be,h as Ve,l as He,m as Ue,n as We,o as Ge,p as Ke,r as qe,s as Je,t as Ye,u as Xe}from"./token-g6sinwTx.js";import{C as Ze,T as Qe,_ as $e,a as et,c as tt,d as nt,f as rt,g as it,h as at,i as ot,l as st,m as ct,n as lt,o as ut,p as dt,r as ft,s as pt,t as mt,u as ht,v as gt,w as _t,y as vt}from"./wrapped-token-3usJd0oi.js";import{r as j}from"./telemetry-BDnhC-vh.js";import{t as yt}from"./cleartext-CvCakQal.js";import{a as bt,c as xt,d as St,f as Ct,i as wt,l as Tt,m as Et,n as Dt,o as M,p as Ot,r as kt,s as At,t as jt,u as Mt}from"./base-signer-BoBsvn5Q.js";import{n as N,r as Nt,s as Pt,t as Ft}from"./primitives-Cym-3HKa.js";import{t as P}from"./validation-ClSvPh6P.js";import{a as It,i as Lt,n as Rt,o as zt,r as Bt,s as Vt,t as Ht}from"./wrappers-registry-Cm3JJeqx.js";import{a as Ut,c as Wt,i as Gt,l as Kt,n as qt,o as Jt,r as Yt,s as Xt,t as Zt,u as Qt}from"./chains-BwlDI944.js";import{getAddress as F,size as $t}from"viem";import{z as I}from"zod/mini";function en(e,t){if(e instanceof p){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var L=class extends p{encryptedValue;contractAddress;account;constructor(e,t){super(c.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}},R=class extends p{constructor(e,t){super(c.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},tn=class extends p{constructor(e,t){super(c.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},z=class extends p{constructor(e,t){super(c.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},B=class extends p{constructor(e,t){super(c.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},V=class extends p{constructor(e,t){super(c.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},H=class extends p{constructor(e,t){super(c.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},U=class extends p{constructor(e,t){super(c.DelegationDelegateCannotBeWildcard,e,t),this.name=`DelegationDelegateCannotBeWildcardError`}},nn=class extends p{constructor(e,t){super(c.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},rn=class extends p{constructor(e,t){super(c.AclPaused,e,t),this.name=`AclPausedError`}},W=class extends p{constructor(e,t){super(c.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},G=class extends p{constructor(e,t){super(c.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};const an=[S,y,u,G,re,b,L,k,_,v];function K(e,n,c={}){if(an.some(t=>e instanceof t))return e;let d=e instanceof Error?e.message:n;if(e instanceof Error&&f(e.message))return new _(e.message,{cause:e});if(t(e))return new v(`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&&l(e.message))return c.isDelegated?new G(`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 L({encryptedValue:r(e.message)??``,contractAddress:c.contractAddress??``,account:c.account??``},{cause:e});if(a(e))return new k(d,{cause:e,retryAfter:i(e)});let p=m(e);return p===void 0&&ee(e)?new k(d,{cause:e,retryAfter:i(e)}):p===400?new y(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):c.isDelegated&&p===500?new G(`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}):s(e)||p!==void 0?new u(d,p,{cause:e,retryAfter:i(e),retryable:o(e)||void 0}):new S(n,{cause:e})}function on(e,t){if(e instanceof p)return e;let n=m(e),r=o(e);return n!==void 0||s(e)?new u(e instanceof Error?e.message:t,n,{cause:e,retryAfter:i(e),retryable:r||void 0}):new x(t,{cause:e})}const q=[{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 J(e,t,n,r){return{address:e,abi:q,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function Y(e,t,n){return{address:e,abi:q,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function sn(e,t,n,r){return{address:e,abi:q,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function cn(e,t,n,r,i){return{address:e,abi:q,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const X=2n**64n-1n,Z=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function ln(e){return wt(e.signer,e.provider,e)}var un=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 w(this.#r,e)}#s(e,t){throw this.#a({type:C.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 Ge(`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 Ge(`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=F((await A(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#c(n)}}async clear(){let e=this.#o(`clear`),t=F((await A(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#c(t)}}async#c(e){await T(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},dn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return w(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await A(`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 A(`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)}},fn=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 w(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await A(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,j(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await A(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,j(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=j(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{ge(t.clearValues[n],`result.clearValues[${n}]`),r[e]=t.clearValues[n].value}),{clearValues:r,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw K(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i,operation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await A(`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`})}},pn=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 hn=new mn,gn=I.union([I.bigint(),I.boolean(),N]),_n=I.array(I.string());var vn=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=gn.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=F(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}:${F(e)}:${F(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=_n.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 yn(e,t){let n=bn(e,t);if(!n)throw new S(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function bn(e,t){let n=Ft(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const xn=e=>new Promise(t=>setTimeout(t,e));var Sn=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=F(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=F(t),o=F(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:F(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 G))throw t;await xn(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:F(e.contractAddress)}));if(s.length===0)return{items:s};let c=F(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(Le(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:F(t)}),{items:s}}}let l=!1,u;if(await qe(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(Le(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:F(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=yn(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&&f(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(t,n,r,i={spent:!1}){if(t.length===0)return{};let a=t.map(e=>({encryptedValue:e.encryptedValue,contractAddress:F(e.contractAddress)})),o={},s=[];for(let e of a)He(e.encryptedValue)?o[e.encryptedValue]=0n:s.push(e);if(s.length===0)return o;let c=Array.from(new Set(a.map(e=>e.contractAddress))),l=Array.from(new Set(s.map(e=>e.contractAddress)));if(n.validate)try{await n.validate(l)}catch(e){throw ee(e)?this.#u(e,`the delegation pre-check`):e}let u=[];for(let e of s){let t=await this.#e.get(n.requesterAddress,e.contractAddress,e.encryptedValue);t===null?u.push(e):o[e.encryptedValue]=t}if(u.length===0)return o;let d=await this.#t.grantPermit(c,n.delegator),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.encryptedValue):f.set(e.contractAddress,[e.encryptedValue])}let m=[];for(let[e,t]of f)for(let n of Re(t))m.push({contractAddress:e,encryptedValues:n});let h=Date.now(),g=u.map(e=>e.encryptedValue);try{this.#i({type:C.DecryptStart,encryptedValues:g});try{await this.#c(n,d,m,o,r)}catch(e){if(!(e instanceof v)||i.spent)throw e;let t=d.permissions.map(e=>e.serializedPermit.signature);i.spent=!0;try{d=await this.#t.recoverPermits(c,n.delegator,t)}catch(e){throw e instanceof b?new v(`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(n,d,m.filter(({encryptedValues:e})=>e.some(e=>o[e]===void 0)),o,r)}let e={};for(let t of g){let n=o[t];n!==void 0&&(e[t]=n)}return this.#i({type:C.DecryptEnd,durationMs:Date.now()-h,encryptedValues:g,result:e}),o}catch(t){let r=t instanceof p&&t.cause instanceof Error?t.cause:t;throw this.#i({type:C.DecryptError,error:e(r),durationMs:Date.now()-h,encryptedValues:g}),K(t,n.errorMessage,{isDelegated:n.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await qe(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 v)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw K(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new S(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new S(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new k(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:i(e)})}#d(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new S(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#f(e,t,n){return e instanceof p?e:K(e,t,n)}#p(){throw new S(`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 Q={AlreadyDelegatedOrRevokedInSameBlock:e=>new tn(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new nn(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new rn(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new R(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new H(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new U(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new W(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new V(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new z(`Cannot revoke: no active delegation exists.`,{cause:e})};function Cn(e){return Object.hasOwn(Q,e)}function wn(e,t){let n=Qe(e);if(n&&Cn(n))return Q[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Q))if(r.includes(e))return n(t);return null}var Tn=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 W(`Expiration date must be at least 1 hour in the future`);let a=F(t),o=F(n),s=F(r);if(o===s)throw new R(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===F(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new U(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new H(`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 V(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==F(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:J(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=F(t),a=F(n),o=F(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 z(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:Y(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=F(e.contractAddress)===Z,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:Z})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:Z});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==X}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===X?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(sn(r,F(t),F(n),F(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await We({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 fe))return;let t=wn(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof z||t instanceof B){let n=F(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=F(e),i=F(t),a=F(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new z(`No active delegation from ${i} to ${a} for ${r}`):new B(`Delegation from ${i} to ${a} for ${r} has expired`)}},En=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(t,n){let r=Date.now(),i=F(t.contractAddress);try{this.#t({type:C.EncryptStart},i);let e=await this.#e.relayer.encryptValues({...t,options:n});return this.#t({type:C.EncryptEnd,durationMs:Date.now()-r},i),e}catch(t){throw this.#t({type:C.EncryptError,error:e(t),durationMs:Date.now()-r},i),on(t,`Encryption failed`)}}},Dn=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await T(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await T(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await T(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>T(`wallet account listener`,()=>t(e),this.#i)))}};const On=I.object({kind:I.literal(`ConfidentialTransfer`),from:N,token:N,to:N,amount:I.bigint()}),kn=I.object({kind:I.literal(`ConfidentialTransferFrom`),from:N,token:N,owner:N,to:N,amount:I.bigint()}),An=I.object({kind:I.literal(`SetOperator`),from:N,token:N,operator:N,until:Pt}),jn=I.object({kind:I.literal(`Unwrap`),from:N,token:N,to:N,amount:I.bigint()}),Mn=I.object({kind:I.literal(`UnwrapAll`),from:N,token:N,to:N}),Nn=I.object({kind:I.literal(`FinalizeUnwrap`),from:N,wrapper:N,unwrapRequestIdOrAmount:Nt}),$=I.object({kind:I.literal(`ApproveUnderlying`),from:N,underlying:N,spender:N,amount:I.bigint()}),Pn=I.object({kind:I.literal(`Wrap`),from:N,wrapper:N,to:N,amount:I.bigint()}),Fn=Nt.check(I.refine(e=>e===`0x`||$t(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`)),In=I.object({kind:I.literal(`TransferAndCall`),from:N,underlying:N,wrapper:N,amount:I.bigint(),recipientData:I.optional(Fn)}),Ln=I.object({kind:I.literal(`DelegateDecryption`),from:N,contractAddress:N,delegateAddress:N,expirationDate:I.optional(I.date())}),Rn=I.object({kind:I.literal(`RevokeDelegation`),from:N,contractAddress:N,delegateAddress:N});I.discriminatedUnion(`kind`,[On,kn,An,jn,Mn,Nn,$,Pn,In,Ln,Rn]);const zn=I.strictObject({maxFeePerGas:I.bigint(),maxPriorityFeePerGas:I.bigint()}),Bn=I.object({nonce:I.optional(I.int().check(I.nonnegative())),gasLimit:I.optional(I.bigint()),fees:I.optional(zn)}),Vn=I.object({address:N,abi:I.array(I.unknown()),functionName:I.string(),args:I.array(I.unknown()),value:I.optional(I.bigint()),gas:I.optional(I.bigint())}),Hn=I.extend(Bn,{from:N,calldata:Vn});var Un=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=P(Bn,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new h(`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=P(Hn,{calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees}),a=await this.#e.prepareTransaction(i);return{kind:e.kind,unsignedTx:a,from:i.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 h(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=P(On,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 x(`Encryption returned no handles for ConfidentialTransfer`);return D(e.token,e.to,r,n)}async#a(e){e=P(kn,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 x(`Encryption returned no handles for ConfidentialTransferFrom`);return xe(e.token,e.owner,e.to,r,n)}#o(e){return e=P(An,e),ye(e.token,e.operator,e.until)}async#s(e){e=P(jn,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 x(`Encryption returned no handles for Unwrap`);return ue(e.token,e.from,e.to,r,n)}async#c(e){e=P(Mn,e);let t=await this.#e.readContract(Te(e.token,e.from));return he(e.token,e.from,e.to,t)}async#l(e){e=P(Nn,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount],options:{operation:`offline-finalize-unwrap`}}).catch(e=>{throw K(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return me(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),O(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=P($,e),E(e.underlying,e.spender,e.amount)}#d(e){return e=P(Pn,e),se(e.wrapper,e.to,e.amount)}#f(e){return e=P(In,e),Ze(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=P(Ln,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new W(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new R(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new H(`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 J(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=P(Rn,e),Y(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Wn(e){if(!(!Object.hasOwn(e,`transportKeyPairDerivationSecret`)||e.transportKeyPairDerivationSecret!==void 0))throw new h(`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 Gn(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(!(typeof window>`u`&&typeof document>`u`&&typeof t!=`function`))throw new h(`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 Kn(e){if(e===void 0)return;let t=P(Tt,e);return new Mt(typeof t==`string`?t:new Uint8Array(t))}var qn=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Wn(t),Gn(t.transportKeyPairDerivationSecret);let n=Kn(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 vn(e.storage,this.#i),this.#u=new Tn({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 M({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new At({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 Sn({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new En({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Dn({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new Un({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new un({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new dn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new fn({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new pn(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}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 M({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,j(t,`encrypt`))}createToken(e){return new Ye(this,e)}createWrappedToken(e){return new mt(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{lt as ACL_TOPICS,rn as AclPausedError,ft as AclTopics,Xe as BalanceCheckUnavailableError,jt as BaseSigner,Ve as ChainMismatchError,mn as ChromeSessionStorage,h as ConfigurationError,fn as Decryption,S as DecryptionFailedError,bt as DefaultRegistryAddresses,nn as DelegationContractIsSelfError,tn as DelegationCooldownError,U as DelegationDelegateCannotBeWildcardError,H as DelegationDelegateEqualsContractError,W as DelegationExpirationTooSoonError,B as DelegationExpiredError,V as DelegationExpiryUnchangedError,z as DelegationNotFoundError,G as DelegationNotPropagatedError,R as DelegationSelfNotAllowedError,dn as Delegations,Ne as ERC1363_INTERFACE_ID,ze as ERC20ReadFailedError,ke as ERC7984_INTERFACE_ID,je as ERC7984_WRAPPER_INTERFACE_ID,oe as EncryptOffloadUnavailableError,x as EncryptionFailedError,Ot as IndexedDBStorage,Be as InsufficientAllowanceError,Ke as InsufficientConfidentialBalanceError,Ue as InsufficientERC20BalanceError,_ as InvalidTransportKeyPairError,g as KeyWrappingError,X as MAX_UINT64,St as MemoryStorage,Dt as MutableWalletAccountStore,y as NoCiphertextError,L as NotEntitledError,pn as Offline,un as Permits,ie as PreparedPermitChainMismatchError,te as PreparedPermitExpiredError,u as RelayerRequestFailedError,v as RevokedKmsContextError,k as RpcRateLimitError,pe as SignerNotConfiguredError,_e as SignerRequiredError,b as SigningFailedError,re as SigningRejectedError,ot as TOKEN_TOPICS,Ye as Token,et as Topics,fe as TransactionRevertedError,ae as TransportKeyPairChangedError,ne as TransportKeyPairExpiredError,_t as UnshieldAlreadyFinalizedError,Z as WILDCARD_CONTRACT,Ie as WalletAccountNotReadyError,ce as WalletNotConnectedError,mt as WrappedToken,M as WrappersRegistry,Je as ZERO_ENCRYPTED_VALUE,p as ZamaError,c as ZamaErrorCode,qn as ZamaSDK,C as ZamaSDKEvents,Se as allowanceContract,Zt as anvil,E as approveContract,Pe as balanceOfContract,qt as bscTestnet,Yt as chains,hn as chromeSessionStorage,yt as cleartext,Te as confidentialBalanceOfContract,we as confidentialTotalSupplyContract,D as confidentialTransferContract,xe as confidentialTransferFromContract,ln as createConfig,kt as createWalletAccountStore,Ce as decimalsContract,ut as decodeAclEvent,pt as decodeAclEvents,tt as decodeConfidentialTransfer,st as decodeDelegatedForUserDecryption,ht as decodeOnChainEvent,nt as decodeOnChainEvents,rt as decodeRevokedDelegationForUserDecryption,dt as decodeUnwrapFinalized,ct as decodeUnwrapRequested,at as decodeWrap,J as delegateForUserDecryptionContract,O as finalizeUnwrapContract,it as findDelegatedForUserDecryption,$e as findRevokedDelegationForUserDecryption,gt as findUnwrapRequested,vt as findWrap,Ht as getConfidentialTokenAddressContract,sn as getDelegationExpiryContract,Rt as getTokenAddressContract,Bt as getTokenPairContract,Lt as getTokenPairsContract,It as getTokenPairsLengthContract,zt as getTokenPairsSliceContract,Gt as hardhat,Ut as hoodi,Et as indexedDBStorage,ve as inferredTotalSupplyContract,Ee as isConfidentialTokenContract,Vt as isConfidentialTokenValidContract,be as isConfidentialWrapperContract,He as isEncryptedValueZero,cn as isHandleDelegatedContract,le as isOperatorContract,n as isRetryable,Jt as mainnet,en as matchZamaError,Ct as memoryStorage,Ae as nameContract,xt as parsePreparedPermit,Xt as polygon,Wt as polygonAmoy,Fe as rateContract,d as retryAfterSeconds,Y as revokeDelegationContract,Kt as sepolia,ye as setOperatorContract,Me as supportsInterfaceContract,Oe as symbolContract,Ze as transferAndCallContract,de as underlyingContract,ue as unwrapContract,he as unwrapFromBalanceContract,De as unwrapRequesterContract,se as wrapContract,Qt as zenithTrexTestnet};
1
+ import{S as e,_ as t,a as n,b as r,c as i,d as a,g as o,h as s,i as c,m as l,n as u,o as d,p as f,r as p,s as m,t as h,v as ee}from"./relayer-C3jVhqSK.js";import{a as g,c as te,d as ne,i as _,l as v,n as re,o as y,s as ie,t as b,u as ae}from"./signing-C6nbPCyd.js";import{n as oe,r as x,t as S}from"./encryption-6AVd-82z.js";import{A as se,B as ce,C as le,D as ue,E as de,F as C,H as fe,L as pe,M as me,O as he,P as ge,R as _e,S as ve,T as ye,V as w,a as be,b as xe,c as Se,d as Ce,g as we,h as Te,i as Ee,j as T,k as De,l as E,m as Oe,n as ke,p as Ae,r as je,s as Me,t as Ne,u as Pe,v as D,w as Fe,x as O,z as Ie}from"./erc165-B8gx2luK.js";import{n as Le,r as k}from"./fatal-batch-BiiS7KdS.js";import{a as A,c as Re,d as ze,f as Be,h as Ve,l as He,m as Ue,n as We,o as Ge,p as Ke,r as qe,s as Je,t as Ye,u as Xe}from"./token-g6sinwTx.js";import{C as Ze,T as Qe,_ as $e,a as et,c as tt,d as nt,f as rt,g as it,h as at,i as ot,l as st,m as ct,n as lt,o as ut,p as dt,r as ft,s as pt,t as mt,u as ht,v as gt,w as _t,y as vt}from"./wrapped-token-3usJd0oi.js";import{r as j}from"./telemetry-CbV9KkHE.js";import{t as yt}from"./cleartext-D8GGwj7W.js";import{a as bt,c as xt,d as St,f as Ct,i as wt,l as Tt,m as Et,n as Dt,o as M,p as Ot,r as kt,s as At,t as jt,u as Mt}from"./base-signer-BoBsvn5Q.js";import{n as N,r as Nt,s as Pt,t as Ft}from"./primitives-Cym-3HKa.js";import{t as P}from"./validation-ClSvPh6P.js";import{a as It,i as Lt,n as Rt,o as zt,r as Bt,s as Vt,t as Ht}from"./wrappers-registry-Cm3JJeqx.js";import{a as Ut,c as Wt,i as Gt,l as Kt,n as qt,o as Jt,r as Yt,s as Xt,t as Zt,u as Qt}from"./chains-BwlDI944.js";import{getAddress as F,size as $t}from"viem";import{z as I}from"zod/mini";function en(e,t){if(e instanceof p){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var L=class extends p{encryptedValue;contractAddress;account;constructor(e,t){super(c.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}},R=class extends p{constructor(e,t){super(c.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},tn=class extends p{constructor(e,t){super(c.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},z=class extends p{constructor(e,t){super(c.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},B=class extends p{constructor(e,t){super(c.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},V=class extends p{constructor(e,t){super(c.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},H=class extends p{constructor(e,t){super(c.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},U=class extends p{constructor(e,t){super(c.DelegationDelegateCannotBeWildcard,e,t),this.name=`DelegationDelegateCannotBeWildcardError`}},nn=class extends p{constructor(e,t){super(c.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},rn=class extends p{constructor(e,t){super(c.AclPaused,e,t),this.name=`AclPausedError`}},W=class extends p{constructor(e,t){super(c.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},G=class extends p{constructor(e,t){super(c.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}};const an=[S,y,u,G,re,b,L,k,_,v];function K(e,n,c={}){if(an.some(t=>e instanceof t))return e;let d=e instanceof Error?e.message:n;if(e instanceof Error&&f(e.message))return new _(e.message,{cause:e});if(t(e))return new v(`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&&l(e.message))return c.isDelegated?new G(`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 L({encryptedValue:r(e.message)??``,contractAddress:c.contractAddress??``,account:c.account??``},{cause:e});if(a(e))return new k(d,{cause:e,retryAfter:i(e)});let p=m(e);return p===void 0&&ee(e)?new k(d,{cause:e,retryAfter:i(e)}):p===400?new y(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):c.isDelegated&&p===500?new G(`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}):s(e)||p!==void 0?new u(d,p,{cause:e,retryAfter:i(e),retryable:o(e)||void 0}):new S(n,{cause:e})}function on(e,t){if(e instanceof p)return e;let n=m(e),r=o(e);return n!==void 0||s(e)?new u(e instanceof Error?e.message:t,n,{cause:e,retryAfter:i(e),retryable:r||void 0}):new x(t,{cause:e})}const q=[{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 J(e,t,n,r){return{address:e,abi:q,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function Y(e,t,n){return{address:e,abi:q,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function sn(e,t,n,r){return{address:e,abi:q,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function cn(e,t,n,r,i){return{address:e,abi:q,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const X=2n**64n-1n,Z=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function ln(e){return wt(e.signer,e.provider,e)}var un=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 w(this.#r,e)}#s(e,t){throw this.#a({type:C.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 Ge(`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 Ge(`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=F((await A(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#c(n)}}async clear(){let e=this.#o(`clear`),t=F((await A(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#c(t)}}async#c(e){await T(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},dn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return w(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await A(`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 A(`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)}},fn=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 w(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await A(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,j(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await A(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,j(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=j(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{ge(t.clearValues[n],`result.clearValues[${n}]`),r[e]=t.clearValues[n].value}),{clearValues:r,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw K(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i,operation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await A(`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`})}},pn=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 hn=new mn,gn=I.union([I.bigint(),I.boolean(),N]),_n=I.array(I.string());var vn=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=gn.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=F(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}:${F(e)}:${F(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=_n.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 yn(e,t){let n=bn(e,t);if(!n)throw new S(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function bn(e,t){let n=Ft(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const xn=e=>new Promise(t=>setTimeout(t,e));var Sn=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=F(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=F(t),o=F(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:F(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 G))throw t;await xn(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:F(e.contractAddress)}));if(s.length===0)return{items:s};let c=F(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(Le(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:F(t)}),{items:s}}}let l=!1,u;if(await qe(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(Le(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:F(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=yn(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&&f(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(t,n,r,i={spent:!1}){if(t.length===0)return{};let a=t.map(e=>({encryptedValue:e.encryptedValue,contractAddress:F(e.contractAddress)})),o={},s=[];for(let e of a)He(e.encryptedValue)?o[e.encryptedValue]=0n:s.push(e);if(s.length===0)return o;let c=Array.from(new Set(a.map(e=>e.contractAddress))),l=Array.from(new Set(s.map(e=>e.contractAddress)));if(n.validate)try{await n.validate(l)}catch(e){throw ee(e)?this.#u(e,`the delegation pre-check`):e}let u=[];for(let e of s){let t=await this.#e.get(n.requesterAddress,e.contractAddress,e.encryptedValue);t===null?u.push(e):o[e.encryptedValue]=t}if(u.length===0)return o;let d=await this.#t.grantPermit(c,n.delegator),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.encryptedValue):f.set(e.contractAddress,[e.encryptedValue])}let m=[];for(let[e,t]of f)for(let n of Re(t))m.push({contractAddress:e,encryptedValues:n});let h=Date.now(),g=u.map(e=>e.encryptedValue);try{this.#i({type:C.DecryptStart,encryptedValues:g});try{await this.#c(n,d,m,o,r)}catch(e){if(!(e instanceof v)||i.spent)throw e;let t=d.permissions.map(e=>e.serializedPermit.signature);i.spent=!0;try{d=await this.#t.recoverPermits(c,n.delegator,t)}catch(e){throw e instanceof b?new v(`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(n,d,m.filter(({encryptedValues:e})=>e.some(e=>o[e]===void 0)),o,r)}let e={};for(let t of g){let n=o[t];n!==void 0&&(e[t]=n)}return this.#i({type:C.DecryptEnd,durationMs:Date.now()-h,encryptedValues:g,result:e}),o}catch(t){let r=t instanceof p&&t.cause instanceof Error?t.cause:t;throw this.#i({type:C.DecryptError,error:e(r),durationMs:Date.now()-h,encryptedValues:g}),K(t,n.errorMessage,{isDelegated:n.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await qe(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 v)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw K(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new S(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new S(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new k(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:i(e)})}#d(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new S(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#f(e,t,n){return e instanceof p?e:K(e,t,n)}#p(){throw new S(`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 Q={AlreadyDelegatedOrRevokedInSameBlock:e=>new tn(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new nn(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new rn(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new R(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new H(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new U(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new W(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new V(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new z(`Cannot revoke: no active delegation exists.`,{cause:e})};function Cn(e){return Object.hasOwn(Q,e)}function wn(e,t){let n=Qe(e);if(n&&Cn(n))return Q[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(Q))if(r.includes(e))return n(t);return null}var Tn=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 W(`Expiration date must be at least 1 hour in the future`);let a=F(t),o=F(n),s=F(r);if(o===s)throw new R(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===F(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new U(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new H(`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 V(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==F(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:J(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=F(t),a=F(n),o=F(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 z(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:Y(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=F(e.contractAddress)===Z,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:Z})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:Z});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==X}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===X?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(sn(r,F(t),F(n),F(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await We({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 fe))return;let t=wn(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof z||t instanceof B){let n=F(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=F(e),i=F(t),a=F(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new z(`No active delegation from ${i} to ${a} for ${r}`):new B(`Delegation from ${i} to ${a} for ${r} has expired`)}},En=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(t,n){let r=Date.now(),i=F(t.contractAddress);try{this.#t({type:C.EncryptStart},i);let e=await this.#e.relayer.encryptValues({...t,options:n});return this.#t({type:C.EncryptEnd,durationMs:Date.now()-r},i),e}catch(t){throw this.#t({type:C.EncryptError,error:e(t),durationMs:Date.now()-r},i),on(t,`Encryption failed`)}}},Dn=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await T(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await T(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await T(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>T(`wallet account listener`,()=>t(e),this.#i)))}};const On=I.object({kind:I.literal(`ConfidentialTransfer`),from:N,token:N,to:N,amount:I.bigint()}),kn=I.object({kind:I.literal(`ConfidentialTransferFrom`),from:N,token:N,owner:N,to:N,amount:I.bigint()}),An=I.object({kind:I.literal(`SetOperator`),from:N,token:N,operator:N,until:Pt}),jn=I.object({kind:I.literal(`Unwrap`),from:N,token:N,to:N,amount:I.bigint()}),Mn=I.object({kind:I.literal(`UnwrapAll`),from:N,token:N,to:N}),Nn=I.object({kind:I.literal(`FinalizeUnwrap`),from:N,wrapper:N,unwrapRequestIdOrAmount:Nt}),$=I.object({kind:I.literal(`ApproveUnderlying`),from:N,underlying:N,spender:N,amount:I.bigint()}),Pn=I.object({kind:I.literal(`Wrap`),from:N,wrapper:N,to:N,amount:I.bigint()}),Fn=Nt.check(I.refine(e=>e===`0x`||$t(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`)),In=I.object({kind:I.literal(`TransferAndCall`),from:N,underlying:N,wrapper:N,amount:I.bigint(),recipientData:I.optional(Fn)}),Ln=I.object({kind:I.literal(`DelegateDecryption`),from:N,contractAddress:N,delegateAddress:N,expirationDate:I.optional(I.date())}),Rn=I.object({kind:I.literal(`RevokeDelegation`),from:N,contractAddress:N,delegateAddress:N});I.discriminatedUnion(`kind`,[On,kn,An,jn,Mn,Nn,$,Pn,In,Ln,Rn]);const zn=I.strictObject({maxFeePerGas:I.bigint(),maxPriorityFeePerGas:I.bigint()}),Bn=I.object({nonce:I.optional(I.int().check(I.nonnegative())),gasLimit:I.optional(I.bigint()),fees:I.optional(zn)}),Vn=I.object({address:N,abi:I.array(I.unknown()),functionName:I.string(),args:I.array(I.unknown()),value:I.optional(I.bigint()),gas:I.optional(I.bigint())}),Hn=I.extend(Bn,{from:N,calldata:Vn});var Un=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=P(Bn,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new h(`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=P(Hn,{calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees}),a=await this.#e.prepareTransaction(i);return{kind:e.kind,unsignedTx:a,from:i.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 h(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=P(On,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 x(`Encryption returned no handles for ConfidentialTransfer`);return D(e.token,e.to,r,n)}async#a(e){e=P(kn,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 x(`Encryption returned no handles for ConfidentialTransferFrom`);return xe(e.token,e.owner,e.to,r,n)}#o(e){return e=P(An,e),ye(e.token,e.operator,e.until)}async#s(e){e=P(jn,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 x(`Encryption returned no handles for Unwrap`);return ue(e.token,e.from,e.to,r,n)}async#c(e){e=P(Mn,e);let t=await this.#e.readContract(Te(e.token,e.from));return he(e.token,e.from,e.to,t)}async#l(e){e=P(Nn,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount],options:{operation:`offline-finalize-unwrap`}}).catch(e=>{throw K(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return me(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),O(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=P($,e),E(e.underlying,e.spender,e.amount)}#d(e){return e=P(Pn,e),se(e.wrapper,e.to,e.amount)}#f(e){return e=P(In,e),Ze(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=P(Ln,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new W(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new R(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new H(`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 J(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=P(Rn,e),Y(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Wn(e){if(!(!Object.hasOwn(e,`transportKeyPairDerivationSecret`)||e.transportKeyPairDerivationSecret!==void 0))throw new h(`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 Gn(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(!(typeof window>`u`&&typeof document>`u`&&typeof t!=`function`))throw new h(`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 Kn(e){if(e===void 0)return;let t=P(Tt,e);return new Mt(typeof t==`string`?t:new Uint8Array(t))}var qn=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Wn(t),Gn(t.transportKeyPairDerivationSecret);let n=Kn(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 vn(e.storage,this.#i),this.#u=new Tn({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 M({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new At({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 Sn({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new En({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new Dn({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new Un({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new un({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new dn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new fn({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new pn(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}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 M({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,j(t,`encrypt`))}createToken(e){return new Ye(this,e)}createWrappedToken(e){return new mt(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{lt as ACL_TOPICS,rn as AclPausedError,ft as AclTopics,Xe as BalanceCheckUnavailableError,jt as BaseSigner,Ve as ChainMismatchError,mn as ChromeSessionStorage,h as ConfigurationError,fn as Decryption,S as DecryptionFailedError,bt as DefaultRegistryAddresses,nn as DelegationContractIsSelfError,tn as DelegationCooldownError,U as DelegationDelegateCannotBeWildcardError,H as DelegationDelegateEqualsContractError,W as DelegationExpirationTooSoonError,B as DelegationExpiredError,V as DelegationExpiryUnchangedError,z as DelegationNotFoundError,G as DelegationNotPropagatedError,R as DelegationSelfNotAllowedError,dn as Delegations,Ne as ERC1363_INTERFACE_ID,ze as ERC20ReadFailedError,ke as ERC7984_INTERFACE_ID,je as ERC7984_WRAPPER_INTERFACE_ID,oe as EncryptOffloadUnavailableError,x as EncryptionFailedError,Ot as IndexedDBStorage,Be as InsufficientAllowanceError,Ke as InsufficientConfidentialBalanceError,Ue as InsufficientERC20BalanceError,_ as InvalidTransportKeyPairError,g as KeyWrappingError,X as MAX_UINT64,St as MemoryStorage,Dt as MutableWalletAccountStore,y as NoCiphertextError,L as NotEntitledError,pn as Offline,un as Permits,ie as PreparedPermitChainMismatchError,te as PreparedPermitExpiredError,u as RelayerRequestFailedError,v as RevokedKmsContextError,k as RpcRateLimitError,pe as SignerNotConfiguredError,_e as SignerRequiredError,b as SigningFailedError,re as SigningRejectedError,ot as TOKEN_TOPICS,Ye as Token,et as Topics,fe as TransactionRevertedError,ae as TransportKeyPairChangedError,ne as TransportKeyPairExpiredError,_t as UnshieldAlreadyFinalizedError,Z as WILDCARD_CONTRACT,Ie as WalletAccountNotReadyError,ce as WalletNotConnectedError,mt as WrappedToken,M as WrappersRegistry,Je as ZERO_ENCRYPTED_VALUE,p as ZamaError,c as ZamaErrorCode,qn as ZamaSDK,C as ZamaSDKEvents,Se as allowanceContract,Zt as anvil,E as approveContract,Pe as balanceOfContract,qt as bscTestnet,Yt as chains,hn as chromeSessionStorage,yt as cleartext,Te as confidentialBalanceOfContract,we as confidentialTotalSupplyContract,D as confidentialTransferContract,xe as confidentialTransferFromContract,ln as createConfig,kt as createWalletAccountStore,Ce as decimalsContract,ut as decodeAclEvent,pt as decodeAclEvents,tt as decodeConfidentialTransfer,st as decodeDelegatedForUserDecryption,ht as decodeOnChainEvent,nt as decodeOnChainEvents,rt as decodeRevokedDelegationForUserDecryption,dt as decodeUnwrapFinalized,ct as decodeUnwrapRequested,at as decodeWrap,J as delegateForUserDecryptionContract,O as finalizeUnwrapContract,it as findDelegatedForUserDecryption,$e as findRevokedDelegationForUserDecryption,gt as findUnwrapRequested,vt as findWrap,Ht as getConfidentialTokenAddressContract,sn as getDelegationExpiryContract,Rt as getTokenAddressContract,Bt as getTokenPairContract,Lt as getTokenPairsContract,It as getTokenPairsLengthContract,zt as getTokenPairsSliceContract,Gt as hardhat,Ut as hoodi,Et as indexedDBStorage,ve as inferredTotalSupplyContract,Ee as isConfidentialTokenContract,Vt as isConfidentialTokenValidContract,be as isConfidentialWrapperContract,He as isEncryptedValueZero,cn as isHandleDelegatedContract,le as isOperatorContract,n as isRetryable,Jt as mainnet,en as matchZamaError,Ct as memoryStorage,Ae as nameContract,xt as parsePreparedPermit,Xt as polygon,Wt as polygonAmoy,Fe as rateContract,d as retryAfterSeconds,Y as revokeDelegationContract,Kt as sepolia,ye as setOperatorContract,Me as supportsInterfaceContract,Oe as symbolContract,Ze as transferAndCallContract,de as underlyingContract,ue as unwrapContract,he as unwrapFromBalanceContract,De as unwrapRequesterContract,se as wrapContract,Qt as zenithTrexTestnet};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,8 @@
1
1
  import { f as FheChain } from "../index-D1Wtji3m.js";
2
- import { A as WalletAccountListener, dn as FhevmRelayerOptions } from "../types-CHepK8MK.js";
2
+ import { A as WalletAccountListener, dn as FhevmRelayerOptions, in as EIP712TypedData } from "../types-CHepK8MK.js";
3
3
  import { _t as ZamaError, f as ZamaSDK, vt as ZamaErrorCode } from "../decryption-B0mY2M8N.js";
4
4
  import "../encrypt-worker-client-BW88njEe.js";
5
+ import { TypedDataDefinition } from "viem";
5
6
  //#region src/errors/revive.d.ts
6
7
  /** Restores callback failures whose class identity controls batch termination. */
7
8
  declare function reviveZamaError(code: ZamaErrorCode, message: string, options: {
@@ -22,5 +23,12 @@ declare function toFhevmAuth(auth: NonNullable<FheChain["auth"]>): NonNullable<F
22
23
  /** Subscribe after the SDK's wallet cleanup, through the internal integration entry point. */
23
24
  declare function subscribeWalletAccountChanges(sdk: ZamaSDK, listener: WalletAccountListener): () => void;
24
25
  //#endregion
25
- export { reviveZamaError, subscribeWalletAccountChanges, toFhevmAuth };
26
+ //#region src/viem/typed-data.d.ts
27
+ /**
28
+ * Convert a decryption-permit {@link EIP712TypedData} into what viem's `signTypedData`
29
+ * takes: `EIP712Domain` removed, `chainId` a number, no `bigint` left in the payload.
30
+ */
31
+ declare function toViemTypedData(typedData: EIP712TypedData): TypedDataDefinition;
32
+ //#endregion
33
+ export { reviveZamaError, subscribeWalletAccountChanges, toFhevmAuth, toViemTypedData };
26
34
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,2 @@
1
- import{i as e,r as t,y as n}from"../relayer-C3jVhqSK.js";import{t as r}from"../fatal-batch-BiiS7KdS.js";import{n as i}from"../fhevm-relayer-CGvejcdJ.js";const a=r;function o(r,i,o){let s=a[r],c=s?new s(i):new t(r,i,r===e.RelayerRequestFailed?{retryable:o.retryable}:void 0);return c.retryable&&n(o.retryAfter)?Object.assign(c,{retryAfter:o.retryAfter}):c}function s(e,t){return e.onWalletAccountChange(t)}export{o as reviveZamaError,s as subscribeWalletAccountChanges,i as toFhevmAuth};
1
+ import{i as e,r as t,y as n}from"../relayer-C3jVhqSK.js";import{t as r}from"../fatal-batch-BiiS7KdS.js";import{n as i}from"../fhevm-relayer-OOqMoa_P.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 t(r,i,r===e.RelayerRequestFailed?{retryable:a.retryable}:void 0);return c.retryable&&n(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 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/errors/revive.ts","../../../src/internal/wallet-events.ts"],"sourcesContent":["import { isValidRetryAfterSeconds } from \"../utils/error\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\nimport { fatalBatchErrors } from \"./fatal-batch\";\n\nconst callbackErrors: Partial<Record<ZamaErrorCode, new (message: string) => ZamaError>> =\n fatalBatchErrors;\n\n/** Restores callback failures whose class identity controls batch termination. */\nexport function reviveZamaError(\n code: ZamaErrorCode,\n message: string,\n options: { retryable: boolean; retryAfter?: number },\n): ZamaError {\n const Constructor = callbackErrors[code];\n const error = Constructor\n ? new Constructor(message)\n : new ZamaError(\n code,\n message,\n code === ZamaErrorCode.RelayerRequestFailed ? { retryable: options.retryable } : undefined,\n );\n if (error.retryable && isValidRetryAfterSeconds(options.retryAfter)) {\n return Object.assign(error, { retryAfter: options.retryAfter });\n }\n return error;\n}\n","import type { WalletAccountListener } from \"../types/signer\";\nimport type { ZamaSDK } from \"../zama-sdk\";\n\n/** Subscribe after the SDK's wallet cleanup, through the internal integration entry point. */\nexport function subscribeWalletAccountChanges(\n sdk: ZamaSDK,\n listener: WalletAccountListener,\n): () => void {\n return sdk.onWalletAccountChange(listener);\n}\n"],"mappings":"yJAIA,MAAM,EACJ,EAGF,SAAgB,EACd,EACA,EACA,EACW,CACX,IAAM,EAAc,EAAe,GAC7B,EAAQ,EACV,IAAI,EAAY,CAAO,EACvB,IAAI,EACF,EACA,EACA,IAAS,EAAc,qBAAuB,CAAE,UAAW,EAAQ,SAAU,EAAI,IAAA,EACnF,EAIJ,OAHI,EAAM,WAAa,EAAyB,EAAQ,UAAU,EACzD,OAAO,OAAO,EAAO,CAAE,WAAY,EAAQ,UAAW,CAAC,EAEzD,CACT,CCrBA,SAAgB,EACd,EACA,EACY,CACZ,OAAO,EAAI,sBAAsB,CAAQ,CAC3C"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/errors/revive.ts","../../../src/internal/wallet-events.ts"],"sourcesContent":["import { isValidRetryAfterSeconds } from \"../utils/error\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\nimport { fatalBatchErrors } from \"./fatal-batch\";\n\nconst callbackErrors: Partial<Record<ZamaErrorCode, new (message: string) => ZamaError>> =\n fatalBatchErrors;\n\n/** Restores callback failures whose class identity controls batch termination. */\nexport function reviveZamaError(\n code: ZamaErrorCode,\n message: string,\n options: { retryable: boolean; retryAfter?: number },\n): ZamaError {\n const Constructor = callbackErrors[code];\n const error = Constructor\n ? new Constructor(message)\n : new ZamaError(\n code,\n message,\n code === ZamaErrorCode.RelayerRequestFailed ? { retryable: options.retryable } : undefined,\n );\n if (error.retryable && isValidRetryAfterSeconds(options.retryAfter)) {\n return Object.assign(error, { retryAfter: options.retryAfter });\n }\n return error;\n}\n","import type { WalletAccountListener } from \"../types/signer\";\nimport type { ZamaSDK } from \"../zama-sdk\";\n\n/** Subscribe after the SDK's wallet cleanup, through the internal integration entry point. */\nexport function subscribeWalletAccountChanges(\n sdk: ZamaSDK,\n listener: WalletAccountListener,\n): () => void {\n return sdk.onWalletAccountChange(listener);\n}\n"],"mappings":"uMAIA,MAAM,EACJ,EAGF,SAAgB,EACd,EACA,EACA,EACW,CACX,IAAM,EAAc,EAAe,GAC7B,EAAQ,EACV,IAAI,EAAY,CAAO,EACvB,IAAI,EACF,EACA,EACA,IAAS,EAAc,qBAAuB,CAAE,UAAW,EAAQ,SAAU,EAAI,IAAA,EACnF,EAIJ,OAHI,EAAM,WAAa,EAAyB,EAAQ,UAAU,EACzD,OAAO,OAAO,EAAO,CAAE,WAAY,EAAQ,UAAW,CAAC,EAEzD,CACT,CCrBA,SAAgB,EACd,EACA,EACY,CACZ,OAAO,EAAI,sBAAsB,CAAQ,CAC3C"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"../fhevm-relayer-CGvejcdJ.js";import{t}from"../telemetry-BDnhC-vh.js";import{t as n}from"../cleartext-CvCakQal.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"../chains-BwlDI944.js";import{AsyncLocalStorage as p}from"node:async_hooks";function m(n){return{type:`node`,createRelayer:(r,i,a)=>new e({chain:r,options:n,logger:i,telemetry:a&&!t(globalThis.process?.env??{})?{state:a,runtime:`node`}:void 0})}}var h=class{#e=new p;run(e){return this.#e.run(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-OOqMoa_P.js";import{t}from"../telemetry-CbV9KkHE.js";import{t as n}from"../cleartext-D8GGwj7W.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"../chains-BwlDI944.js";import{AsyncLocalStorage as p}from"node:async_hooks";function m(n){return{type:`node`,createRelayer:(r,i,a)=>new e({chain:r,options:n,logger:i,telemetry:a&&!t(globalThis.process?.env??{})?{state:a,runtime:`node`}:void 0})}}var h=class{#e=new p;run(e){return this.#e.run(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
- function e(e,t){return{"x-zama-sdk-version":`3.8.0-beta.2`,"x-zama-sdk-layer":e.state.layer,"x-zama-sdk-runtime":e.runtime,...t!==void 0&&{"x-zama-sdk-operation":t}}}function t(e,t){return Object.assign({},e,{operation:e?.operation??t})}function n(e){let t=e.ZAMA_SDK_TELEMETRY?.trim().toLowerCase();return t===`0`||t===`false`}export{e as n,t as r,n as t};
2
- //# sourceMappingURL=telemetry-BDnhC-vh.js.map
1
+ function e(e,t){return{"x-zama-sdk-version":`3.8.0-beta.3`,"x-zama-sdk-layer":e.state.layer,"x-zama-sdk-runtime":e.runtime,...t!==void 0&&{"x-zama-sdk-operation":t}}}function t(e,t){return Object.assign({},e,{operation:e?.operation??t})}function n(e){let t=e.ZAMA_SDK_TELEMETRY?.trim().toLowerCase();return t===`0`||t===`false`}export{e as n,t as r,n as t};
2
+ //# sourceMappingURL=telemetry-CbV9KkHE.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-BDnhC-vh.js","names":["packageJson.version"],"sources":["../../package.json","../../src/version.ts","../../src/telemetry.ts"],"sourcesContent":["","import packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const SDK_VERSION: string = packageJson.version;\n","import { SDK_VERSION } from \"./version\";\n\n// Usage telemetry: `x-zama-sdk-*` headers on the relayer calls the SDK already\n// makes. No header may carry a wallet address, encrypted value, amount or identifier.\n\nexport type TelemetryLayer = \"core\" | \"react\";\n\nexport type TelemetryRuntime = \"web\" | \"node\";\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 | \"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` flips to `react` once\n * `ZamaProvider` marks the config, after the relayers exist.\n *\n * @internal\n */\nexport interface TelemetryState {\n layer: TelemetryLayer;\n}\n\nexport interface RelayerTelemetry {\n readonly state: TelemetryState;\n readonly runtime: TelemetryRuntime;\n}\n\nexport function telemetryHeaders(\n telemetry: RelayerTelemetry,\n operation: TelemetryOperation | undefined,\n): Record<string, string> {\n return {\n \"x-zama-sdk-version\": SDK_VERSION,\n \"x-zama-sdk-layer\": telemetry.state.layer,\n \"x-zama-sdk-runtime\": telemetry.runtime,\n ...(operation !== undefined && { \"x-zama-sdk-operation\": operation }),\n };\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 isTelemetryDisabledByEnv(env: Record<string, string | undefined>): boolean {\n const value = env.ZAMA_SDK_TELEMETRY?.trim().toLowerCase();\n return value === \"0\" || value === \"false\";\n}\n"],"mappings":"AEqDA,SAAgB,EACd,EACA,EACwB,CACxB,MAAO,CACL,qBAAsB,eACtB,mBAAoB,EAAU,MAAM,MACpC,qBAAsB,EAAU,QAChC,GAAI,IAAc,IAAA,IAAa,CAAE,uBAAwB,CAAU,CACrE,CACF,CAGA,SAAgB,EACd,EACA,EACyD,CACzD,OAAO,OAAO,OAAO,CAAC,EAAG,EAAS,CAAE,UAAW,GAAS,WAAa,CAAU,CAAC,CAClF,CAEA,SAAgB,EAAyB,EAAkD,CACzF,IAAM,EAAQ,EAAI,oBAAoB,KAAK,CAAC,CAAC,YAAY,EACzD,OAAO,IAAU,KAAO,IAAU,OACpC"}
1
+ {"version":3,"file":"telemetry-CbV9KkHE.js","names":["packageJson.version"],"sources":["../../package.json","../../src/version.ts","../../src/telemetry.ts"],"sourcesContent":["","import packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const SDK_VERSION: string = packageJson.version;\n","import { SDK_VERSION } from \"./version\";\n\n// Usage telemetry: `x-zama-sdk-*` headers on the relayer calls the SDK already\n// makes. No header may carry a wallet address, encrypted value, amount or identifier.\n\nexport type TelemetryLayer = \"core\" | \"react\";\n\nexport type TelemetryRuntime = \"web\" | \"node\";\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 | \"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` flips to `react` once\n * `ZamaProvider` marks the config, after the relayers exist.\n *\n * @internal\n */\nexport interface TelemetryState {\n layer: TelemetryLayer;\n}\n\nexport interface RelayerTelemetry {\n readonly state: TelemetryState;\n readonly runtime: TelemetryRuntime;\n}\n\nexport function telemetryHeaders(\n telemetry: RelayerTelemetry,\n operation: TelemetryOperation | undefined,\n): Record<string, string> {\n return {\n \"x-zama-sdk-version\": SDK_VERSION,\n \"x-zama-sdk-layer\": telemetry.state.layer,\n \"x-zama-sdk-runtime\": telemetry.runtime,\n ...(operation !== undefined && { \"x-zama-sdk-operation\": operation }),\n };\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 isTelemetryDisabledByEnv(env: Record<string, string | undefined>): boolean {\n const value = env.ZAMA_SDK_TELEMETRY?.trim().toLowerCase();\n return value === \"0\" || value === \"false\";\n}\n"],"mappings":"AEqDA,SAAgB,EACd,EACA,EACwB,CACxB,MAAO,CACL,qBAAsB,eACtB,mBAAoB,EAAU,MAAM,MACpC,qBAAsB,EAAU,QAChC,GAAI,IAAc,IAAA,IAAa,CAAE,uBAAwB,CAAU,CACrE,CACF,CAGA,SAAgB,EACd,EACA,EACyD,CACzD,OAAO,OAAO,OAAO,CAAC,EAAG,EAAS,CAAE,UAAW,GAAS,WAAa,CAAU,CAAC,CAClF,CAEA,SAAgB,EAAyB,EAAkD,CACzF,IAAM,EAAQ,EAAI,oBAAoB,KAAK,CAAC,CAAC,YAAY,EACzD,OAAO,IAAU,KAAO,IAAU,OACpC"}
@@ -0,0 +1,2 @@
1
+ function e(t){return typeof t==`bigint`?t.toString():Array.isArray(t)?t.map(e):typeof t==`object`&&t&&Object.getPrototypeOf(t)===Object.prototype?Object.fromEntries(Object.entries(t).map(([t,n])=>[t,e(n)])):t}function t(t){let{EIP712Domain:n,...r}=t.types,{chainId:i,...a}=t.domain;return{primaryType:t.primaryType,types:r,domain:i===void 0?a:{...a,chainId:Number(i)},message:e(t.message)}}export{t};
2
+ //# sourceMappingURL=typed-data-eAgGr9V-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typed-data-eAgGr9V-.js","names":[],"sources":["../../src/viem/typed-data.ts"],"sourcesContent":["import type { TypedDataDefinition } from \"viem\";\nimport type { EIP712TypedData } from \"../relayer/types\";\n\n// A browser extension that patches bigint JSON serialization turns `1n` into `\"1n\"` and the wallet rejects it.\nfunction withoutBigInts(value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n if (Array.isArray(value)) {\n return value.map(withoutBigInts);\n }\n // A `Uint8Array` rebuilt as a plain object makes viem throw.\n if (\n value !== null &&\n typeof value === \"object\" &&\n Object.getPrototypeOf(value) === Object.prototype\n ) {\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [key, withoutBigInts(entry)]),\n );\n }\n return value;\n}\n\n/**\n * Convert a decryption-permit {@link EIP712TypedData} into what viem's `signTypedData`\n * takes: `EIP712Domain` removed, `chainId` a number, no `bigint` left in the payload.\n */\nexport function toViemTypedData(typedData: EIP712TypedData): TypedDataDefinition {\n const { EIP712Domain: _, ...types } = typedData.types;\n // viem derives `EIP712Domain` from runtime value types and drops a string `chainId` from the signed domain.\n const { chainId, ...domain } = typedData.domain;\n return {\n primaryType: typedData.primaryType,\n types,\n domain: chainId === undefined ? domain : { ...domain, chainId: Number(chainId) },\n message: withoutBigInts(typedData.message),\n // Cast: the input is structurally typed, so viem's generics cannot correlate `primaryType`, `types` and `message`.\n } as TypedDataDefinition;\n}\n"],"mappings":"AAIA,SAAS,EAAe,EAAyB,CAiB/C,OAhBI,OAAO,GAAU,SACZ,EAAM,SAAS,EAEpB,MAAM,QAAQ,CAAK,EACd,EAAM,IAAI,CAAc,EAK/B,OAAO,GAAU,UADjB,GAEA,OAAO,eAAe,CAAK,IAAM,OAAO,UAEjC,OAAO,YACZ,OAAO,QAAQ,CAAK,CAAC,CAAC,KAAK,CAAC,EAAK,KAAW,CAAC,EAAK,EAAe,CAAK,CAAC,CAAC,CAC1E,EAEK,CACT,CAMA,SAAgB,EAAgB,EAAiD,CAC/E,GAAM,CAAE,aAAc,EAAG,GAAG,GAAU,EAAU,MAE1C,CAAE,UAAS,GAAG,GAAW,EAAU,OACzC,MAAO,CACL,YAAa,EAAU,YACvB,QACA,OAAQ,IAAY,IAAA,GAAY,EAAS,CAAE,GAAG,EAAQ,QAAS,OAAO,CAAO,CAAE,EAC/E,QAAS,EAAe,EAAU,OAAO,CAE3C,CACF"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"../relayer-C3jVhqSK.js";import{r as t,t as n}from"../encryption-6AVd-82z.js";import{H as r,L as i,M as a,P as o}from"../erc165-B8gx2luK.js";import{a as s,i as c,l,n as u,o as d,t as f}from"../token-g6sinwTx.js";import{S as p,b as m,t as h,x as g}from"../wrapped-token-3usJd0oi.js";import{r as _}from"../telemetry-BDnhC-vh.js";import{l as v,p as y}from"../invalidation-BgFjmXeQ.js";import{getAddress as b}from"viem";const x=[{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:`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:`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 S(e,t,n,r){return{address:e,abi:x,functionName:`join`,args:[t,n,r]}}function C(e,t,n){return{address:e,abi:x,functionName:`claim`,args:[t,n]}}function w(e,t){return{address:e,abi:x,functionName:`quit`,args:[t]}}function T(e,t,n){return{address:e,abi:x,functionName:`recover`,args:[t,n]}}function E(e){return{address:e,abi:x,functionName:`dispatchBatch`,args:[]}}function D(e){return{address:e,abi:x,functionName:`currentBatchId`,args:[]}}function O(e,t){return{address:e,abi:x,functionName:`batchState`,args:[t]}}function k(e,t){return{address:e,abi:x,functionName:`totalDeposits`,args:[t]}}function A(e,t,n){return{address:e,abi:x,functionName:`deposits`,args:[t,n]}}function j(e){return{address:e,abi:x,functionName:`vault`,args:[]}}function M(e){return{address:e,abi:x,functionName:`fromToken`,args:[]}}function N(e){return{address:e,abi:x,functionName:`toToken`,args:[]}}function P(e){return{address:e,abi:x,functionName:`minBatchAge`,args:[]}}function F(e,t){return{address:e,abi:x,functionName:`batchMinBatchAge`,args:[t]}}function I(e){return{address:e,abi:x,functionName:`callbackDeadline`,args:[]}}function L(e,t){return{address:e,abi:x,functionName:`batchCallbackDeadline`,args:[t]}}function R(e,t){return{address:e,abi:x,functionName:`batchCreatedAt`,args:[t]}}function z(e,t){return{address:e,abi:x,functionName:`batchDispatchedAt`,args:[t]}}function B(e,t){return{address:e,abi:x,functionName:`exchangeRate`,args:[t]}}function V(e){return{address:e,abi:x,functionName:`exchangeRateDecimals`,args:[]}}function H(e){return{address:e,abi:x,functionName:`paused`,args:[]}}const U={Joined:m(`Joined(uint256,address,bytes32)`)};function W(e){let[t,n,r]=e.topics;return t!==U.Joined||n===void 0||r===void 0?null:{batchId:BigInt(n),account:g(r),confidentialAmount:p(e.data,0)}}function G(e,t,n){let r=n?b(n):void 0;for(let n of e){if(n.address!==void 0&&b(n.address)!==t)continue;let e=W(n);if(e&&(r===void 0||e.account===r))return e}return null}const K={Pending:0,Dispatched:1,Finalized:2,Canceled:3};function q(e){let t,n=null;return()=>t===void 0?(n||=e().then(e=>(t=e,n=null,e)).catch(e=>{throw n=null,e}),n):Promise.resolve(t)}var J=class{sdk;address;#e;#t;#n;#r=null;constructor(e,t){this.sdk=e,this.address=b(t),this.#e=q(()=>e.provider.readContract(j(this.address))),this.#t=q(()=>e.provider.readContract(M(this.address))),this.#n=q(()=>e.provider.readContract(N(this.address)))}async vault(){return this.#e()}async fromToken(){return this.#t()}async toToken(){return this.#n()}async currentBatchId(){return this.sdk.provider.readContract(D(this.address))}async batchState(e){return await this.sdk.provider.readContract(O(this.address,e))}async paused(){return this.sdk.provider.readContract(H(this.address))}async minBatchAge(){return this.sdk.provider.readContract(P(this.address))}async batchMinBatchAge(e){return this.sdk.provider.readContract(F(this.address,e))}async callbackDeadline(){return this.sdk.provider.readContract(I(this.address))}async batchCallbackDeadline(e){return this.sdk.provider.readContract(L(this.address,e))}async batchCreatedAt(e){return this.sdk.provider.readContract(R(this.address,e))}async batchDispatchedAt(e){return this.sdk.provider.readContract(z(this.address,e))}async exchangeRate(e){return this.sdk.provider.readContract(B(this.address,e))}async exchangeRateDecimals(){return this.sdk.provider.readContract(V(this.address))}async timeUntilDispatchable(e){let[t,n,r,i]=await Promise.all([this.batchState(e),this.batchCreatedAt(e),this.batchMinBatchAge(e),this.sdk.provider.getBlockTimestamp()]);if(t!==K.Pending)return null;let a=n+r;return a>i?a-i:0n}async confidentialTotalDeposits(e){return this.sdk.provider.readContract(k(this.address,e))}async confidentialDepositOf(e,t){return this.sdk.provider.readContract(A(this.address,e,b(t)))}async depositOf(e,t){let r=b(t),i=await this.confidentialDepositOf(e,r);if(l(i))return 0n;let o=(await this.sdk.decryption.decryptValues([{encryptedValue:i,contractAddress:this.address}],{operation:`vault-deposit-of`}))[i];if(o===void 0)throw new n(`Decryption returned no value for ${i}`);return a(o,`depositOf: result[encryptedValue]`),o}async join(e,n,i){let{operation:a}=_(i,`vault-join`);this.#i(`join`);let o=b((await s(`join`,this.sdk.signer,this.sdk.provider)).address),c=n?b(n):o;i?.skipBalanceCheck||await this.#o(e,a);let{encryptedValues:l,inputProof:u}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:o},{operation:a}),d=l[0];if(!d)throw new t(`Encryption returned no encrypted values`);let f=await this.#c(`vault:join`,S(this.address,c,d,u)),p=G(f.receipt.logs,this.address,c);if(!p)throw new r(`No Joined event for ${c} from batcher ${this.address} found in the join receipt`);return{...f,batchId:p.batchId,beneficiary:p.account,confidentialJoinedAmount:p.confidentialAmount}}async quit(e){return this.#i(`quit`),await d(`quit`,this.sdk.signer,this.sdk.provider),this.#c(`vault:quit`,w(this.address,e))}async recover(e,t){let n=await this.#s(`recover`,t);return this.#c(`vault:recover`,T(this.address,e,n))}async claim(e,t){let n=await this.#s(`claim`,t);return this.#c(`vault:claim`,C(this.address,e,n))}async dispatchBatch(){return this.#i(`dispatchBatch`),await d(`dispatchBatch`,this.sdk.signer,this.sdk.provider),this.#c(`vault:dispatchBatch`,E(this.address))}#i(e){if(!this.sdk.signer)throw new i(e);return this.sdk.signer}async#a(){return this.#r??=this.fromToken().then(e=>new f(this.sdk,e)).catch(e=>{throw this.#r=null,e}),this.#r}async#o(e,t){let n=await this.#a();return c({operation:`join`,tokenAddress:n.address,amount:e,signer:this.sdk.signer,provider:this.sdk.provider,readBalance:e=>n.decryptBalance(e,t)})}async#s(e,t){return this.#i(e),t?(await d(e,this.sdk.signer,this.sdk.provider),b(t)):b((await s(e,this.sdk.signer,this.sdk.provider)).address)}async#c(e,t){return u({operation:e,signer:this.#i(e),provider:this.sdk.provider,config:t,emit:e=>this.sdk.emitEvent(e,this.address),logger:this.sdk.logger})}};function Y(e,t){return new J(e,t)}var X=class{sdk;depositBatcher;redeemBatcher;#e=null;#t=null;#n=null;#r;constructor(e,t){this.sdk=e,this.#r=t.vault?b(t.vault):void 0,this.depositBatcher=new J(e,t.depositBatcher),this.redeemBatcher=new J(e,t.redeemBatcher)}async vaultAddress(){return this.#e??=this.#i().catch(e=>{throw this.#e=null,e}),this.#e}async cAsset(){return this.#t??=this.depositBatcher.fromToken().then(e=>new h(this.sdk,e)).catch(e=>{throw this.#t=null,e}),this.#t}async cShare(){return this.#n??=this.redeemBatcher.fromToken().then(e=>new h(this.sdk,e)).catch(e=>{throw this.#n=null,e}),this.#n}async deposit(e,t){let[,n]=await Promise.all([this.vaultAddress(),this.cAsset()]);return await this.#a(`deposit`,n,this.depositBatcher.address,t?.operatorUntil),this.depositBatcher.join(e,t?.beneficiary,{skipBalanceCheck:t?.skipBalanceCheck,operation:`vault-deposit`})}async redeem(e,t){let[,n]=await Promise.all([this.vaultAddress(),this.cShare()]);return await this.#a(`redeem`,n,this.redeemBatcher.address,t?.operatorUntil),this.redeemBatcher.join(e,t?.beneficiary,{skipBalanceCheck:t?.skipBalanceCheck,operation:`vault-redeem`})}async#i(){let[t,n]=await Promise.all([this.depositBatcher.vault(),this.redeemBatcher.vault()]);if(b(t)!==b(n))throw new e(`Vault batchers point at different ERC-4626 vaults: deposit batcher ${this.depositBatcher.address} reports ${t}, redeem batcher ${this.redeemBatcher.address} reports ${n}`);let r=b(t);if(this.#r!==void 0&&this.#r!==r)throw new e(`Configured vault address ${this.#r} does not match the ${r} both batchers report`);return r}async#a(e,t,n,r){if(!this.sdk.signer)throw new i(e);let a=this.sdk.signer.requireWalletAccount(e);await t.isOperator(a.address,n)||await t.setOperator(n,r)}};function Z(e,t){return new X(e,t)}const Q={currentBatchId:{batcher:e=>[`zama.vault.currentBatchId`,{batcherAddress:b(e)}]},batchState:{batcher:e=>[`zama.vault.batchState`,{batcherAddress:b(e)}],batch:(e,t)=>[`zama.vault.batchState`,{batcherAddress:b(e),batchId:t}]},timeUntilDispatchable:{batcher:e=>[`zama.vault.timeUntilDispatchable`,{batcherAddress:b(e)}],batch:(e,t)=>[`zama.vault.timeUntilDispatchable`,{batcherAddress:b(e),batchId:t}]}};function $(e,t){e.invalidateQueries({queryKey:Q.currentBatchId.batcher(t)}),e.invalidateQueries({queryKey:Q.batchState.batcher(t)}),e.invalidateQueries({queryKey:Q.timeUntilDispatchable.batcher(t)})}function ee(e,t){v(e,t.fromToken),$(e,t.batcherAddress)}function te(e,t){v(e,t.fromToken),$(e,t.batcherAddress)}function ne(e,t){v(e,t.toToken)}function re(e,t){$(e,t)}function ie(e,t={}){let n=t.query??{};return{...y(n),queryKey:Q.currentBatchId.batcher(e.address),queryFn:async()=>e.currentBatchId(),enabled:n.enabled!==!1}}function ae(e,t={}){let n=t.query??{};return{...y(n),queryKey:Q.batchState.batch(e.address,t.batchId),queryFn:async t=>{let[,{batchId:n}]=t.queryKey;return o(n,`batchStateQueryOptions: batchId`),e.batchState(n)},enabled:t.batchId!==void 0&&n.enabled!==!1}}function oe(e,t={}){let n=t.query??{};return{...y(n),queryKey:Q.timeUntilDispatchable.batch(e.address,t.batchId),queryFn:async t=>{let[,{batchId:n}]=t.queryKey;return o(n,`timeUntilDispatchableQueryOptions: batchId`),e.timeUntilDispatchable(n)},enabled:t.batchId!==void 0&&n.enabled!==!1}}function se(e){return{mutationKey:[`zama.vault.deposit`,e.depositBatcher.address],mutationFn:async({amount:t,...n})=>e.deposit(t,n)}}function ce(e){return{mutationKey:[`zama.vault.redeem`,e.redeemBatcher.address],mutationFn:async({amount:t,...n})=>e.redeem(t,n)}}function le(e){return{mutationKey:[`zama.vault.join`,e.address],mutationFn:async({amount:t,beneficiary:n,...r})=>e.join(t,n,r)}}function ue(e){return{mutationKey:[`zama.vault.claim`,e.address],mutationFn:async({batchId:t,account:n})=>e.claim(t,n)}}function de(e){return{mutationKey:[`zama.vault.quit`,e.address],mutationFn:async({batchId:t})=>e.quit(t)}}function fe(e){return{mutationKey:[`zama.vault.recover`,e.address],mutationFn:async({batchId:t,account:n})=>e.recover(t,n)}}function pe(e){return{mutationKey:[`zama.vault.dispatchBatch`,e.address],mutationFn:async()=>e.dispatchBatch()}}export{K as BatchState,X as Vault,J as VaultBatcher,U as VaultTopics,L as batchCallbackDeadlineContract,R as batchCreatedAtContract,z as batchDispatchedAtContract,F as batchMinBatchAgeContract,O as batchStateContract,ae as batchStateQueryOptions,I as callbackDeadlineContract,C as claimContract,ue as claimMutationOptions,Z as createVault,Y as createVaultBatcher,D as currentBatchIdContract,ie as currentBatchIdQueryOptions,W as decodeJoined,se as depositMutationOptions,A as depositsContract,E as dispatchBatchContract,pe as dispatchBatchMutationOptions,B as exchangeRateContract,V as exchangeRateDecimalsContract,G as findJoined,M as fromTokenContract,ne as invalidateAfterClaim,re as invalidateAfterDispatchBatch,ee as invalidateAfterJoin,te as invalidateAfterQuit,$ as invalidateBatchQueries,S as joinContract,le as joinMutationOptions,P as minBatchAgeContract,H as pausedContract,w as quitContract,de as quitMutationOptions,T as recoverContract,fe as recoverMutationOptions,ce as redeemMutationOptions,oe as timeUntilDispatchableQueryOptions,N as toTokenContract,k as totalDepositsContract,j as vaultContract,Q as vaultQueryKeys};
1
+ import{t as e}from"../relayer-C3jVhqSK.js";import{r as t,t as n}from"../encryption-6AVd-82z.js";import{H as r,L as i,M as a,P as o}from"../erc165-B8gx2luK.js";import{a as s,i as c,l,n as u,o as d,t as f}from"../token-g6sinwTx.js";import{S as p,b as m,t as h,x as g}from"../wrapped-token-3usJd0oi.js";import{r as _}from"../telemetry-CbV9KkHE.js";import{l as v,p as y}from"../invalidation-BgFjmXeQ.js";import{getAddress as b}from"viem";const x=[{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:`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:`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 S(e,t,n,r){return{address:e,abi:x,functionName:`join`,args:[t,n,r]}}function C(e,t,n){return{address:e,abi:x,functionName:`claim`,args:[t,n]}}function w(e,t){return{address:e,abi:x,functionName:`quit`,args:[t]}}function T(e,t,n){return{address:e,abi:x,functionName:`recover`,args:[t,n]}}function E(e){return{address:e,abi:x,functionName:`dispatchBatch`,args:[]}}function D(e){return{address:e,abi:x,functionName:`currentBatchId`,args:[]}}function O(e,t){return{address:e,abi:x,functionName:`batchState`,args:[t]}}function k(e,t){return{address:e,abi:x,functionName:`totalDeposits`,args:[t]}}function A(e,t,n){return{address:e,abi:x,functionName:`deposits`,args:[t,n]}}function j(e){return{address:e,abi:x,functionName:`vault`,args:[]}}function M(e){return{address:e,abi:x,functionName:`fromToken`,args:[]}}function N(e){return{address:e,abi:x,functionName:`toToken`,args:[]}}function P(e){return{address:e,abi:x,functionName:`minBatchAge`,args:[]}}function F(e,t){return{address:e,abi:x,functionName:`batchMinBatchAge`,args:[t]}}function I(e){return{address:e,abi:x,functionName:`callbackDeadline`,args:[]}}function L(e,t){return{address:e,abi:x,functionName:`batchCallbackDeadline`,args:[t]}}function R(e,t){return{address:e,abi:x,functionName:`batchCreatedAt`,args:[t]}}function z(e,t){return{address:e,abi:x,functionName:`batchDispatchedAt`,args:[t]}}function B(e,t){return{address:e,abi:x,functionName:`exchangeRate`,args:[t]}}function V(e){return{address:e,abi:x,functionName:`exchangeRateDecimals`,args:[]}}function H(e){return{address:e,abi:x,functionName:`paused`,args:[]}}const U={Joined:m(`Joined(uint256,address,bytes32)`)};function W(e){let[t,n,r]=e.topics;return t!==U.Joined||n===void 0||r===void 0?null:{batchId:BigInt(n),account:g(r),confidentialAmount:p(e.data,0)}}function G(e,t,n){let r=n?b(n):void 0;for(let n of e){if(n.address!==void 0&&b(n.address)!==t)continue;let e=W(n);if(e&&(r===void 0||e.account===r))return e}return null}const K={Pending:0,Dispatched:1,Finalized:2,Canceled:3};function q(e){let t,n=null;return()=>t===void 0?(n||=e().then(e=>(t=e,n=null,e)).catch(e=>{throw n=null,e}),n):Promise.resolve(t)}var J=class{sdk;address;#e;#t;#n;#r=null;constructor(e,t){this.sdk=e,this.address=b(t),this.#e=q(()=>e.provider.readContract(j(this.address))),this.#t=q(()=>e.provider.readContract(M(this.address))),this.#n=q(()=>e.provider.readContract(N(this.address)))}async vault(){return this.#e()}async fromToken(){return this.#t()}async toToken(){return this.#n()}async currentBatchId(){return this.sdk.provider.readContract(D(this.address))}async batchState(e){return await this.sdk.provider.readContract(O(this.address,e))}async paused(){return this.sdk.provider.readContract(H(this.address))}async minBatchAge(){return this.sdk.provider.readContract(P(this.address))}async batchMinBatchAge(e){return this.sdk.provider.readContract(F(this.address,e))}async callbackDeadline(){return this.sdk.provider.readContract(I(this.address))}async batchCallbackDeadline(e){return this.sdk.provider.readContract(L(this.address,e))}async batchCreatedAt(e){return this.sdk.provider.readContract(R(this.address,e))}async batchDispatchedAt(e){return this.sdk.provider.readContract(z(this.address,e))}async exchangeRate(e){return this.sdk.provider.readContract(B(this.address,e))}async exchangeRateDecimals(){return this.sdk.provider.readContract(V(this.address))}async timeUntilDispatchable(e){let[t,n,r,i]=await Promise.all([this.batchState(e),this.batchCreatedAt(e),this.batchMinBatchAge(e),this.sdk.provider.getBlockTimestamp()]);if(t!==K.Pending)return null;let a=n+r;return a>i?a-i:0n}async confidentialTotalDeposits(e){return this.sdk.provider.readContract(k(this.address,e))}async confidentialDepositOf(e,t){return this.sdk.provider.readContract(A(this.address,e,b(t)))}async depositOf(e,t){let r=b(t),i=await this.confidentialDepositOf(e,r);if(l(i))return 0n;let o=(await this.sdk.decryption.decryptValues([{encryptedValue:i,contractAddress:this.address}],{operation:`vault-deposit-of`}))[i];if(o===void 0)throw new n(`Decryption returned no value for ${i}`);return a(o,`depositOf: result[encryptedValue]`),o}async join(e,n,i){let{operation:a}=_(i,`vault-join`);this.#i(`join`);let o=b((await s(`join`,this.sdk.signer,this.sdk.provider)).address),c=n?b(n):o;i?.skipBalanceCheck||await this.#o(e,a);let{encryptedValues:l,inputProof:u}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:o},{operation:a}),d=l[0];if(!d)throw new t(`Encryption returned no encrypted values`);let f=await this.#c(`vault:join`,S(this.address,c,d,u)),p=G(f.receipt.logs,this.address,c);if(!p)throw new r(`No Joined event for ${c} from batcher ${this.address} found in the join receipt`);return{...f,batchId:p.batchId,beneficiary:p.account,confidentialJoinedAmount:p.confidentialAmount}}async quit(e){return this.#i(`quit`),await d(`quit`,this.sdk.signer,this.sdk.provider),this.#c(`vault:quit`,w(this.address,e))}async recover(e,t){let n=await this.#s(`recover`,t);return this.#c(`vault:recover`,T(this.address,e,n))}async claim(e,t){let n=await this.#s(`claim`,t);return this.#c(`vault:claim`,C(this.address,e,n))}async dispatchBatch(){return this.#i(`dispatchBatch`),await d(`dispatchBatch`,this.sdk.signer,this.sdk.provider),this.#c(`vault:dispatchBatch`,E(this.address))}#i(e){if(!this.sdk.signer)throw new i(e);return this.sdk.signer}async#a(){return this.#r??=this.fromToken().then(e=>new f(this.sdk,e)).catch(e=>{throw this.#r=null,e}),this.#r}async#o(e,t){let n=await this.#a();return c({operation:`join`,tokenAddress:n.address,amount:e,signer:this.sdk.signer,provider:this.sdk.provider,readBalance:e=>n.decryptBalance(e,t)})}async#s(e,t){return this.#i(e),t?(await d(e,this.sdk.signer,this.sdk.provider),b(t)):b((await s(e,this.sdk.signer,this.sdk.provider)).address)}async#c(e,t){return u({operation:e,signer:this.#i(e),provider:this.sdk.provider,config:t,emit:e=>this.sdk.emitEvent(e,this.address),logger:this.sdk.logger})}};function Y(e,t){return new J(e,t)}var X=class{sdk;depositBatcher;redeemBatcher;#e=null;#t=null;#n=null;#r;constructor(e,t){this.sdk=e,this.#r=t.vault?b(t.vault):void 0,this.depositBatcher=new J(e,t.depositBatcher),this.redeemBatcher=new J(e,t.redeemBatcher)}async vaultAddress(){return this.#e??=this.#i().catch(e=>{throw this.#e=null,e}),this.#e}async cAsset(){return this.#t??=this.depositBatcher.fromToken().then(e=>new h(this.sdk,e)).catch(e=>{throw this.#t=null,e}),this.#t}async cShare(){return this.#n??=this.redeemBatcher.fromToken().then(e=>new h(this.sdk,e)).catch(e=>{throw this.#n=null,e}),this.#n}async deposit(e,t){let[,n]=await Promise.all([this.vaultAddress(),this.cAsset()]);return await this.#a(`deposit`,n,this.depositBatcher.address,t?.operatorUntil),this.depositBatcher.join(e,t?.beneficiary,{skipBalanceCheck:t?.skipBalanceCheck,operation:`vault-deposit`})}async redeem(e,t){let[,n]=await Promise.all([this.vaultAddress(),this.cShare()]);return await this.#a(`redeem`,n,this.redeemBatcher.address,t?.operatorUntil),this.redeemBatcher.join(e,t?.beneficiary,{skipBalanceCheck:t?.skipBalanceCheck,operation:`vault-redeem`})}async#i(){let[t,n]=await Promise.all([this.depositBatcher.vault(),this.redeemBatcher.vault()]);if(b(t)!==b(n))throw new e(`Vault batchers point at different ERC-4626 vaults: deposit batcher ${this.depositBatcher.address} reports ${t}, redeem batcher ${this.redeemBatcher.address} reports ${n}`);let r=b(t);if(this.#r!==void 0&&this.#r!==r)throw new e(`Configured vault address ${this.#r} does not match the ${r} both batchers report`);return r}async#a(e,t,n,r){if(!this.sdk.signer)throw new i(e);let a=this.sdk.signer.requireWalletAccount(e);await t.isOperator(a.address,n)||await t.setOperator(n,r)}};function Z(e,t){return new X(e,t)}const Q={currentBatchId:{batcher:e=>[`zama.vault.currentBatchId`,{batcherAddress:b(e)}]},batchState:{batcher:e=>[`zama.vault.batchState`,{batcherAddress:b(e)}],batch:(e,t)=>[`zama.vault.batchState`,{batcherAddress:b(e),batchId:t}]},timeUntilDispatchable:{batcher:e=>[`zama.vault.timeUntilDispatchable`,{batcherAddress:b(e)}],batch:(e,t)=>[`zama.vault.timeUntilDispatchable`,{batcherAddress:b(e),batchId:t}]}};function $(e,t){e.invalidateQueries({queryKey:Q.currentBatchId.batcher(t)}),e.invalidateQueries({queryKey:Q.batchState.batcher(t)}),e.invalidateQueries({queryKey:Q.timeUntilDispatchable.batcher(t)})}function ee(e,t){v(e,t.fromToken),$(e,t.batcherAddress)}function te(e,t){v(e,t.fromToken),$(e,t.batcherAddress)}function ne(e,t){v(e,t.toToken)}function re(e,t){$(e,t)}function ie(e,t={}){let n=t.query??{};return{...y(n),queryKey:Q.currentBatchId.batcher(e.address),queryFn:async()=>e.currentBatchId(),enabled:n.enabled!==!1}}function ae(e,t={}){let n=t.query??{};return{...y(n),queryKey:Q.batchState.batch(e.address,t.batchId),queryFn:async t=>{let[,{batchId:n}]=t.queryKey;return o(n,`batchStateQueryOptions: batchId`),e.batchState(n)},enabled:t.batchId!==void 0&&n.enabled!==!1}}function oe(e,t={}){let n=t.query??{};return{...y(n),queryKey:Q.timeUntilDispatchable.batch(e.address,t.batchId),queryFn:async t=>{let[,{batchId:n}]=t.queryKey;return o(n,`timeUntilDispatchableQueryOptions: batchId`),e.timeUntilDispatchable(n)},enabled:t.batchId!==void 0&&n.enabled!==!1}}function se(e){return{mutationKey:[`zama.vault.deposit`,e.depositBatcher.address],mutationFn:async({amount:t,...n})=>e.deposit(t,n)}}function ce(e){return{mutationKey:[`zama.vault.redeem`,e.redeemBatcher.address],mutationFn:async({amount:t,...n})=>e.redeem(t,n)}}function le(e){return{mutationKey:[`zama.vault.join`,e.address],mutationFn:async({amount:t,beneficiary:n,...r})=>e.join(t,n,r)}}function ue(e){return{mutationKey:[`zama.vault.claim`,e.address],mutationFn:async({batchId:t,account:n})=>e.claim(t,n)}}function de(e){return{mutationKey:[`zama.vault.quit`,e.address],mutationFn:async({batchId:t})=>e.quit(t)}}function fe(e){return{mutationKey:[`zama.vault.recover`,e.address],mutationFn:async({batchId:t,account:n})=>e.recover(t,n)}}function pe(e){return{mutationKey:[`zama.vault.dispatchBatch`,e.address],mutationFn:async()=>e.dispatchBatch()}}export{K as BatchState,X as Vault,J as VaultBatcher,U as VaultTopics,L as batchCallbackDeadlineContract,R as batchCreatedAtContract,z as batchDispatchedAtContract,F as batchMinBatchAgeContract,O as batchStateContract,ae as batchStateQueryOptions,I as callbackDeadlineContract,C as claimContract,ue as claimMutationOptions,Z as createVault,Y as createVaultBatcher,D as currentBatchIdContract,ie as currentBatchIdQueryOptions,W as decodeJoined,se as depositMutationOptions,A as depositsContract,E as dispatchBatchContract,pe as dispatchBatchMutationOptions,B as exchangeRateContract,V as exchangeRateDecimalsContract,G as findJoined,M as fromTokenContract,ne as invalidateAfterClaim,re as invalidateAfterDispatchBatch,ee as invalidateAfterJoin,te as invalidateAfterQuit,$ as invalidateBatchQueries,S as joinContract,le as joinMutationOptions,P as minBatchAgeContract,H as pausedContract,w as quitContract,de as quitMutationOptions,T as recoverContract,fe as recoverMutationOptions,ce as redeemMutationOptions,oe as timeUntilDispatchableQueryOptions,N as toTokenContract,k as totalDepositsContract,j as vaultContract,Q as vaultQueryKeys};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import{A as e,B as t,D as n,E as r,F as i,H as a,O as o,T as s,h as c,s as l,v as u,x as d}from"../erc165-B8gx2luK.js";import{i as f,t as p}from"../base-signer-BoBsvn5Q.js";import{a as m,i as h,n as g,o as _,r as v,s as y,t as b}from"../wrappers-registry-Cm3JJeqx.js";import{t as x}from"../eip1193-subscribe-CNxVHW6y.js";import{encodeFunctionData as S,getAddress as C,serializeTransaction as w}from"viem";var T=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){return this.#e.readContract(e)}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getBlockTimestamp(){return(await this.#e.getBlock()).timestamp}async prepareTransaction(e){let{from:t,calldata:n}=e,r=S({abi:n.abi,functionName:n.functionName,args:n.args}),i=this.#e.getChainId(),o=e.nonce===void 0?this.#e.getTransactionCount({address:t,blockTag:`pending`}):Promise.resolve(e.nonce),s=e.gasLimit===void 0?n.gas??this.#e.estimateGas({account:t,to:n.address,data:r,value:n.value??0n}).catch(e=>{throw new a(`ViemProvider.prepareTransaction: gas estimation reverted for ${n.functionName} on ${n.address}`,{cause:e})}):Promise.resolve(e.gasLimit),c=e.fees??this.#e.estimateFeesPerGas(),[l,u,d,f]=await Promise.all([i,o,s,c]);return w({type:`eip1559`,chainId:l,nonce:u,to:n.address,data:r,value:n.value??0n,gas:d,maxFeePerGas:f.maxFeePerGas,maxPriorityFeePerGas:f.maxPriorityFeePerGas})}};function E(e){let t=(e.primaryType?e.types[e.primaryType]:void 0)??[],n={...e.message};for(let{name:e,type:r}of t)/^uint\d*$/.test(r)&&(n[e]=BigInt(n[e]));return n}function D(e){if(!(!e.account||!e.chain))return{address:C(e.account.address),chainId:e.chain.id}}var O=class extends p{#e;#t;#n;constructor(e){super(D(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(e){if(!this.#e.account)throw new t(e);return{walletClient:this.#e,account:this.#e.account}}async signTypedData(e){let{walletClient:t,account:n}=this.#r(`signTypedData`),{EIP712Domain:r,...i}=e.types;return t.signTypedData({account:n,primaryType:e.primaryType,types:i,domain:e.domain,message:E(e)})}async writeContract(e){let{walletClient:t,account:n}=this.#r(`writeContract`);return t.writeContract({chain:t.chain,account:n,...e})}#i(){return this.#t?x({provider:this.#t,getInitialWalletAccount:()=>D(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function k(e){return f(new O({walletClient:e.walletClient,ethereum:e.ethereum}),new T({publicClient:e.publicClient}),e)}function A(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function j(e,t,n){return e.readContract(c(t,n))}function M(e,t){return e.readContract(r(t))}function N(e,t,n){return e.readContract(l(t,n))}function P(e,t,n,r,i){return e.writeContract({chain:e.chain,account:A(e),...u(t,n,r,i)})}function F(e,t,r,i,a,o){return e.writeContract({chain:e.chain,account:A(e),...n(t,r,i,a,o)})}function I(e,t,n,r,i){return e.writeContract({chain:e.chain,account:A(e),...o(t,n,r,i)})}function L(e,t,n,r,i){return e.writeContract({chain:e.chain,account:A(e),...d(t,n,r,i)})}function R(e,t,n,r){return e.writeContract({chain:e.chain,account:A(e),...s(t,n,r)})}function z(t,n,r,i){return t.writeContract({chain:t.chain,account:A(t),...e(n,r,i)})}function B(e,t){return e.readContract(h(t))}function V(e,t){return e.readContract(m(t))}function H(e,t,n,r){return e.readContract(_(t,n,r))}function U(e,t,n){return e.readContract(v(t,n))}function W(e,t,n){return e.readContract(b(t,n))}function G(e,t,n){return e.readContract(g(t,n))}function K(e,t,n){return e.readContract(y(t,n))}export{p as BaseSigner,T as ViemProvider,O as ViemSigner,i as ZamaSDKEvents,k as createConfig,j as readConfidentialBalanceOfContract,W as readConfidentialTokenAddressContract,K as readIsConfidentialTokenValidContract,N as readSupportsInterfaceContract,G as readTokenAddressContract,U as readTokenPairContract,B as readTokenPairsContract,V as readTokenPairsLengthContract,H as readTokenPairsSliceContract,M as readUnderlyingTokenContract,P as writeConfidentialTransferContract,L as writeFinalizeUnwrapContract,R as writeSetOperatorContract,F as writeUnwrapContract,I as writeUnwrapFromBalanceContract,z as writeWrapContract};
1
+ import{A as e,B as t,D as n,E as r,F as i,H as a,O as o,T as s,h as c,s as l,v as u,x as d}from"../erc165-B8gx2luK.js";import{i as f,t as p}from"../base-signer-BoBsvn5Q.js";import{a as m,i as h,n as g,o as _,r as v,s as y,t as b}from"../wrappers-registry-Cm3JJeqx.js";import{t as x}from"../typed-data-eAgGr9V-.js";import{t as S}from"../eip1193-subscribe-CNxVHW6y.js";import{encodeFunctionData as C,getAddress as w,serializeTransaction as T}from"viem";var E=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){return this.#e.readContract(e)}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getBlockTimestamp(){return(await this.#e.getBlock()).timestamp}async prepareTransaction(e){let{from:t,calldata:n}=e,r=C({abi:n.abi,functionName:n.functionName,args:n.args}),i=this.#e.getChainId(),o=e.nonce===void 0?this.#e.getTransactionCount({address:t,blockTag:`pending`}):Promise.resolve(e.nonce),s=e.gasLimit===void 0?n.gas??this.#e.estimateGas({account:t,to:n.address,data:r,value:n.value??0n}).catch(e=>{throw new a(`ViemProvider.prepareTransaction: gas estimation reverted for ${n.functionName} on ${n.address}`,{cause:e})}):Promise.resolve(e.gasLimit),c=e.fees??this.#e.estimateFeesPerGas(),[l,u,d,f]=await Promise.all([i,o,s,c]);return T({type:`eip1559`,chainId:l,nonce:u,to:n.address,data:r,value:n.value??0n,gas:d,maxFeePerGas:f.maxFeePerGas,maxPriorityFeePerGas:f.maxPriorityFeePerGas})}};function D(e){if(!(!e.account||!e.chain))return{address:w(e.account.address),chainId:e.chain.id}}var O=class extends p{#e;#t;#n;constructor(e){super(D(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(e){if(!this.#e.account)throw new t(e);return{walletClient:this.#e,account:this.#e.account}}async signTypedData(e){let{walletClient:t,account:n}=this.#r(`signTypedData`);return t.signTypedData({account:n,...x(e)})}async writeContract(e){let{walletClient:t,account:n}=this.#r(`writeContract`);return t.writeContract({chain:t.chain,account:n,...e})}#i(){return this.#t?S({provider:this.#t,getInitialWalletAccount:()=>D(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function k(e){return f(new O({walletClient:e.walletClient,ethereum:e.ethereum}),new E({publicClient:e.publicClient}),e)}function A(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function j(e,t,n){return e.readContract(c(t,n))}function M(e,t){return e.readContract(r(t))}function N(e,t,n){return e.readContract(l(t,n))}function P(e,t,n,r,i){return e.writeContract({chain:e.chain,account:A(e),...u(t,n,r,i)})}function F(e,t,r,i,a,o){return e.writeContract({chain:e.chain,account:A(e),...n(t,r,i,a,o)})}function I(e,t,n,r,i){return e.writeContract({chain:e.chain,account:A(e),...o(t,n,r,i)})}function L(e,t,n,r,i){return e.writeContract({chain:e.chain,account:A(e),...d(t,n,r,i)})}function R(e,t,n,r){return e.writeContract({chain:e.chain,account:A(e),...s(t,n,r)})}function z(t,n,r,i){return t.writeContract({chain:t.chain,account:A(t),...e(n,r,i)})}function B(e,t){return e.readContract(h(t))}function V(e,t){return e.readContract(m(t))}function H(e,t,n,r){return e.readContract(_(t,n,r))}function U(e,t,n){return e.readContract(v(t,n))}function W(e,t,n){return e.readContract(b(t,n))}function G(e,t,n){return e.readContract(g(t,n))}function K(e,t,n){return e.readContract(y(t,n))}export{p as BaseSigner,E as ViemProvider,O as ViemSigner,i as ZamaSDKEvents,k as createConfig,j as readConfidentialBalanceOfContract,W as readConfidentialTokenAddressContract,K as readIsConfidentialTokenValidContract,N as readSupportsInterfaceContract,G as readTokenAddressContract,U as readTokenPairContract,B as readTokenPairsContract,V as readTokenPairsLengthContract,H as readTokenPairsSliceContract,M as readUnderlyingTokenContract,P as writeConfidentialTransferContract,L as writeFinalizeUnwrapContract,R as writeSetOperatorContract,F as writeUnwrapContract,I as writeUnwrapFromBalanceContract,z as writeWrapContract};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#publicClient","#walletClient","#ethereum","#unsubscribeProvider","#subscribeToProvider","#requireAccount"],"sources":["../../../src/viem/viem-provider.ts","../../../src/viem/viem-signer.ts","../../../src/viem/config.ts","../../../src/viem/contracts.ts"],"sourcesContent":["import {\n encodeFunctionData,\n serializeTransaction,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\n\n/** Configuration for {@link ViemProvider}. */\nexport interface ViemProviderConfig {\n /** A viem `PublicClient` backing all read operations. */\n publicClient: PublicClient;\n}\n\n/**\n * Read-only {@link GenericProvider} backed by a viem `PublicClient`.\n *\n * Use this for integrations that only need public chain reads before the user has Pair with a\n * {@link ViemSigner} when wallet authority is required; the two can share a transport or point at\n * independent RPCs.\n *\n * @example\n * ```ts\n * const publicClient = createPublicClient({ chain: sepolia, transport: http(ALCHEMY_URL) });\n * const provider = new ViemProvider({ publicClient });\n * ```\n */\nexport class ViemProvider implements GenericProvider {\n readonly #publicClient: PublicClient;\n\n constructor(config: ViemProviderConfig) {\n this.#publicClient = config.publicClient;\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n return this.#publicClient.getChainId();\n }\n\n /** Execute a read-only call and return the decoded result. */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n return this.#publicClient.readContract(config);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n return this.#publicClient.waitForTransactionReceipt({ hash });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#publicClient.getBlock();\n return block.timestamp;\n }\n\n /** Build a fully-populated, RLP-encoded unsigned transaction ready to be signed offline. */\n async prepareTransaction<\n const TAbi extends ContractAbi,\n TFunctionName extends WriteFunctionName<TAbi>,\n const TArgs extends WriteContractArgs<TAbi, TFunctionName>,\n >(args: {\n from: Address;\n calldata: WriteContractConfig<TAbi, TFunctionName, TArgs>;\n nonce?: number;\n gasLimit?: bigint;\n fees?: { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint };\n }): Promise<Hex> {\n const { from, calldata } = args;\n const data = encodeFunctionData({\n abi: calldata.abi as Abi,\n functionName: calldata.functionName as string,\n args: calldata.args as readonly unknown[],\n });\n // Wrap the estimateGas leg so a pre-flight revert (the most common\n // prepareTransaction failure) surfaces as a typed error with the\n // function name + cause. Other legs propagate as-is — failures there\n // (chainId, nonce, fee data) are rare and usually self-explanatory.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const chainIdPromise = this.#publicClient.getChainId();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#publicClient.getTransactionCount({ address: from, blockTag: \"pending\" });\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#publicClient\n .estimateGas({ account: from, to: calldata.address, data, value: calldata.value ?? 0n })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `ViemProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feesPromise = args.fees ?? this.#publicClient.estimateFeesPerGas();\n const [chainId, nonce, gas, fees] = await Promise.all([\n chainIdPromise,\n noncePromise,\n gasPromise,\n feesPromise,\n ]);\n return serializeTransaction({\n type: \"eip1559\",\n chainId,\n nonce,\n to: calldata.address,\n data,\n value: calldata.value ?? 0n,\n gas,\n maxFeePerGas: fees.maxFeePerGas,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n });\n }\n}\n","import type {\n Account,\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n EIP1193Provider,\n WalletClient,\n Hex,\n} from \"viem\";\nimport { getAddress } from \"viem\";\nimport type { writeContract } from \"viem/actions\";\nimport { WalletNotConnectedError } from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\n\n/**\n * Configuration for {@link ViemSigner}.\n *\n * The optional `ethereum` field is needed for `subscribe()` (EIP-1193\n * `accountsChanged` / `disconnect` events). It cannot be auto-extracted from\n * `walletClient` because viem's `custom(ethereum)` transport captures the\n * provider in a closure and does **not** expose `on` / `removeListener` on\n * `walletClient.transport`.\n *\n * If you omit `ethereum`, `subscribe()` returns a no-op. For automatic\n * wallet lifecycle handling, consider using `WagmiSigner` instead.\n */\nexport interface ViemSignerConfig {\n /** Wallet client for signing and write operations. */\n walletClient: WalletClient;\n /** Raw EIP-1193 provider enabling wallet lifecycle events; omit for a no-op `subscribe()`. */\n ethereum?: EIP1193Provider;\n}\n\n// viem requires uint values as bigints, but the KMS permit message carries them\n// as decimal strings. Convert by declared field type rather than by name so every\n// permit version is covered (V1 `durationDays`, V2 `durationSeconds`, ...).\nfunction messageWithBigIntUints(typedData: EIP712TypedData): Record<string, unknown> {\n const fields = (typedData.primaryType ? typedData.types[typedData.primaryType] : undefined) ?? [];\n const message: Record<string, unknown> = { ...typedData.message };\n for (const { name, type } of fields) {\n if (/^uint\\d*$/.test(type)) {\n message[name] = BigInt(message[name] as string | number | bigint);\n }\n }\n return message;\n}\n\nfunction walletAccountFromWalletClient(walletClient: WalletClient): WalletAccount | undefined {\n if (!walletClient.account || !walletClient.chain) {\n return undefined;\n }\n const address = getAddress(walletClient.account.address);\n return { address, chainId: walletClient.chain.id };\n}\n\n/**\n * {@link GenericSigner} backed by a viem `WalletClient` for EIP-712 signing and\n * write transactions. Pass `ethereum` in {@link ViemSignerConfig} to track\n * wallet lifecycle events.\n */\nexport class ViemSigner extends BaseSigner {\n readonly #walletClient: WalletClient;\n readonly #ethereum?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n\n constructor(config: ViemSignerConfig) {\n super(walletAccountFromWalletClient(config.walletClient));\n this.#walletClient = config.walletClient;\n this.#ethereum = config.ethereum;\n this.#unsubscribeProvider = this.#subscribeToProvider();\n }\n\n #requireAccount(operation: string): { walletClient: WalletClient; account: Account } {\n if (!this.#walletClient.account) {\n throw new WalletNotConnectedError(operation);\n }\n return { walletClient: this.#walletClient, account: this.#walletClient.account };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"signTypedData\");\n const { EIP712Domain: _, ...sigTypes } = typedData.types;\n return walletClient.signTypedData({\n account,\n primaryType: typedData.primaryType,\n types: sigTypes,\n domain: typedData.domain,\n message: messageWithBigIntUints(typedData),\n // Cast: EIP712TypedData is structural (`Eip712Like`), so viem cannot correlate primaryType/types/message and the inferred `message` collapses to `never`.\n } as Parameters<typeof walletClient.signTypedData>[0]);\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"writeContract\");\n return walletClient.writeContract({\n chain: walletClient.chain,\n account,\n ...config,\n } as Parameters<typeof writeContract>[1]);\n }\n\n #subscribeToProvider(): () => void {\n if (!this.#ethereum) {\n return () => {};\n }\n return eip1193Subscribe({\n provider: this.#ethereum,\n getInitialWalletAccount: () => walletAccountFromWalletClient(this.#walletClient),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n}\n","import type { FheChain } from \"../chains\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { buildZamaConfig } from \"../config/build\";\nimport { ViemProvider } from \"./viem-provider\";\nimport { ViemSigner } from \"./viem-signer\";\nimport type { ZamaConfigViem } from \"./types\";\n\n/** Create a {@link ZamaConfig} from viem clients. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigViem<TChains>,\n): ZamaConfig {\n const signer = new ViemSigner({ walletClient: params.walletClient, ethereum: params.ethereum });\n const provider = new ViemProvider({ publicClient: params.publicClient });\n return buildZamaConfig(signer, provider, params);\n}\n","import type { PublicClient, WalletClient, Address, Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\n// ── Helpers ────────────────────────────────────────────────\n\nfunction requireAccount(client: WalletClient) {\n if (!client.account) {\n throw new TypeError(\"WalletClient has no account\");\n }\n return client.account;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via a viem client. */\nexport function readConfidentialBalanceOfContract(\n client: PublicClient,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return client.readContract(confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via a viem client. */\nexport function readUnderlyingTokenContract(client: PublicClient, wrapperAddress: Address) {\n return client.readContract(underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via a viem client. */\nexport function readSupportsInterfaceContract(\n client: PublicClient,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return client.readContract(supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via a viem wallet client. */\nexport function writeConfidentialTransferContract(\n client: WalletClient,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via a viem wallet client. */\nexport function writeUnwrapContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via a viem wallet client. */\nexport function writeUnwrapFromBalanceContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance),\n });\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via a viem wallet client. */\nexport function writeFinalizeUnwrapContract(\n client: WalletClient,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n });\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via a viem wallet client. */\nexport function writeSetOperatorContract(\n client: WalletClient,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...setOperatorContract(tokenAddress, operator, until),\n });\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via a viem wallet client. */\nexport function writeWrapContract(\n client: WalletClient,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...wrapContract(wrapperAddress, to, amount),\n });\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via a viem client. */\nexport function readTokenPairsContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via a viem client. */\nexport function readTokenPairsLengthContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via a viem client. */\nexport function readTokenPairsSliceContract(\n client: PublicClient,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return client.readContract(getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via a viem client. */\nexport function readTokenPairContract(client: PublicClient, registry: Address, index: bigint) {\n return client.readContract(getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via a viem client. */\nexport function readConfidentialTokenAddressContract(\n client: PublicClient,\n registry: Address,\n tokenAddress: Address,\n) {\n return client.readContract(getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via a viem client. */\nexport function readTokenAddressContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via a viem client. */\nexport function readIsConfidentialTokenValidContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"index.js","names":["#publicClient","#walletClient","#ethereum","#unsubscribeProvider","#subscribeToProvider","#requireAccount"],"sources":["../../../src/viem/viem-provider.ts","../../../src/viem/viem-signer.ts","../../../src/viem/config.ts","../../../src/viem/contracts.ts"],"sourcesContent":["import {\n encodeFunctionData,\n serializeTransaction,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { TransactionRevertedError } from \"../errors\";\nimport type {\n ContractAbi,\n GenericProvider,\n ReadContractConfig,\n TransactionReceipt,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\n\n/** Configuration for {@link ViemProvider}. */\nexport interface ViemProviderConfig {\n /** A viem `PublicClient` backing all read operations. */\n publicClient: PublicClient;\n}\n\n/**\n * Read-only {@link GenericProvider} backed by a viem `PublicClient`.\n *\n * Use this for integrations that only need public chain reads before the user has Pair with a\n * {@link ViemSigner} when wallet authority is required; the two can share a transport or point at\n * independent RPCs.\n *\n * @example\n * ```ts\n * const publicClient = createPublicClient({ chain: sepolia, transport: http(ALCHEMY_URL) });\n * const provider = new ViemProvider({ publicClient });\n * ```\n */\nexport class ViemProvider implements GenericProvider {\n readonly #publicClient: PublicClient;\n\n constructor(config: ViemProviderConfig) {\n this.#publicClient = config.publicClient;\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n return this.#publicClient.getChainId();\n }\n\n /** Execute a read-only call and return the decoded result. */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n return this.#publicClient.readContract(config);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n return this.#publicClient.waitForTransactionReceipt({ hash });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#publicClient.getBlock();\n return block.timestamp;\n }\n\n /** Build a fully-populated, RLP-encoded unsigned transaction ready to be signed offline. */\n async prepareTransaction<\n const TAbi extends ContractAbi,\n TFunctionName extends WriteFunctionName<TAbi>,\n const TArgs extends WriteContractArgs<TAbi, TFunctionName>,\n >(args: {\n from: Address;\n calldata: WriteContractConfig<TAbi, TFunctionName, TArgs>;\n nonce?: number;\n gasLimit?: bigint;\n fees?: { maxFeePerGas: bigint; maxPriorityFeePerGas: bigint };\n }): Promise<Hex> {\n const { from, calldata } = args;\n const data = encodeFunctionData({\n abi: calldata.abi as Abi,\n functionName: calldata.functionName as string,\n args: calldata.args as readonly unknown[],\n });\n // Wrap the estimateGas leg so a pre-flight revert (the most common\n // prepareTransaction failure) surfaces as a typed error with the\n // function name + cause. Other legs propagate as-is — failures there\n // (chainId, nonce, fee data) are rare and usually self-explanatory.\n // Skip the network round-trips entirely when the caller supplied\n // overrides — useful for custodians with their own nonce/fee managers.\n const chainIdPromise = this.#publicClient.getChainId();\n const noncePromise =\n args.nonce !== undefined\n ? Promise.resolve(args.nonce)\n : this.#publicClient.getTransactionCount({ address: from, blockTag: \"pending\" });\n const gasPromise =\n args.gasLimit !== undefined\n ? Promise.resolve(args.gasLimit)\n : (calldata.gas ??\n this.#publicClient\n .estimateGas({ account: from, to: calldata.address, data, value: calldata.value ?? 0n })\n .catch((error: unknown) => {\n throw new TransactionRevertedError(\n `ViemProvider.prepareTransaction: gas estimation reverted for ${calldata.functionName} on ${calldata.address}`,\n { cause: error },\n );\n }));\n const feesPromise = args.fees ?? this.#publicClient.estimateFeesPerGas();\n const [chainId, nonce, gas, fees] = await Promise.all([\n chainIdPromise,\n noncePromise,\n gasPromise,\n feesPromise,\n ]);\n return serializeTransaction({\n type: \"eip1559\",\n chainId,\n nonce,\n to: calldata.address,\n data,\n value: calldata.value ?? 0n,\n gas,\n maxFeePerGas: fees.maxFeePerGas,\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas,\n });\n }\n}\n","import type {\n Account,\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n EIP1193Provider,\n WalletClient,\n Hex,\n} from \"viem\";\nimport { getAddress } from \"viem\";\nimport type { writeContract } from \"viem/actions\";\nimport { WalletNotConnectedError } from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\nimport { toViemTypedData } from \"./typed-data\";\n\n/**\n * Configuration for {@link ViemSigner}.\n *\n * The optional `ethereum` field is needed for `subscribe()` (EIP-1193\n * `accountsChanged` / `disconnect` events). It cannot be auto-extracted from\n * `walletClient` because viem's `custom(ethereum)` transport captures the\n * provider in a closure and does **not** expose `on` / `removeListener` on\n * `walletClient.transport`.\n *\n * If you omit `ethereum`, `subscribe()` returns a no-op. For automatic\n * wallet lifecycle handling, consider using `WagmiSigner` instead.\n */\nexport interface ViemSignerConfig {\n /** Wallet client for signing and write operations. */\n walletClient: WalletClient;\n /** Raw EIP-1193 provider enabling wallet lifecycle events; omit for a no-op `subscribe()`. */\n ethereum?: EIP1193Provider;\n}\n\nfunction walletAccountFromWalletClient(walletClient: WalletClient): WalletAccount | undefined {\n if (!walletClient.account || !walletClient.chain) {\n return undefined;\n }\n const address = getAddress(walletClient.account.address);\n return { address, chainId: walletClient.chain.id };\n}\n\n/**\n * {@link GenericSigner} backed by a viem `WalletClient` for EIP-712 signing and\n * write transactions. Pass `ethereum` in {@link ViemSignerConfig} to track\n * wallet lifecycle events.\n */\nexport class ViemSigner extends BaseSigner {\n readonly #walletClient: WalletClient;\n readonly #ethereum?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n\n constructor(config: ViemSignerConfig) {\n super(walletAccountFromWalletClient(config.walletClient));\n this.#walletClient = config.walletClient;\n this.#ethereum = config.ethereum;\n this.#unsubscribeProvider = this.#subscribeToProvider();\n }\n\n #requireAccount(operation: string): { walletClient: WalletClient; account: Account } {\n if (!this.#walletClient.account) {\n throw new WalletNotConnectedError(operation);\n }\n return { walletClient: this.#walletClient, account: this.#walletClient.account };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"signTypedData\");\n return walletClient.signTypedData({ account, ...toViemTypedData(typedData) });\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const { walletClient, account } = this.#requireAccount(\"writeContract\");\n return walletClient.writeContract({\n chain: walletClient.chain,\n account,\n ...config,\n } as Parameters<typeof writeContract>[1]);\n }\n\n #subscribeToProvider(): () => void {\n if (!this.#ethereum) {\n return () => {};\n }\n return eip1193Subscribe({\n provider: this.#ethereum,\n getInitialWalletAccount: () => walletAccountFromWalletClient(this.#walletClient),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n}\n","import type { FheChain } from \"../chains\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { buildZamaConfig } from \"../config/build\";\nimport { ViemProvider } from \"./viem-provider\";\nimport { ViemSigner } from \"./viem-signer\";\nimport type { ZamaConfigViem } from \"./types\";\n\n/** Create a {@link ZamaConfig} from viem clients. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigViem<TChains>,\n): ZamaConfig {\n const signer = new ViemSigner({ walletClient: params.walletClient, ethereum: params.ethereum });\n const provider = new ViemProvider({ publicClient: params.publicClient });\n return buildZamaConfig(signer, provider, params);\n}\n","import type { PublicClient, WalletClient, Address, Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\n// ── Helpers ────────────────────────────────────────────────\n\nfunction requireAccount(client: WalletClient) {\n if (!client.account) {\n throw new TypeError(\"WalletClient has no account\");\n }\n return client.account;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via a viem client. */\nexport function readConfidentialBalanceOfContract(\n client: PublicClient,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return client.readContract(confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via a viem client. */\nexport function readUnderlyingTokenContract(client: PublicClient, wrapperAddress: Address) {\n return client.readContract(underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via a viem client. */\nexport function readSupportsInterfaceContract(\n client: PublicClient,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return client.readContract(supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via a viem wallet client. */\nexport function writeConfidentialTransferContract(\n client: WalletClient,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via a viem wallet client. */\nexport function writeUnwrapContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof),\n });\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via a viem wallet client. */\nexport function writeUnwrapFromBalanceContract(\n client: WalletClient,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance),\n });\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via a viem wallet client. */\nexport function writeFinalizeUnwrapContract(\n client: WalletClient,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n });\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via a viem wallet client. */\nexport function writeSetOperatorContract(\n client: WalletClient,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...setOperatorContract(tokenAddress, operator, until),\n });\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via a viem wallet client. */\nexport function writeWrapContract(\n client: WalletClient,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return client.writeContract({\n chain: client.chain,\n account: requireAccount(client),\n ...wrapContract(wrapperAddress, to, amount),\n });\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via a viem client. */\nexport function readTokenPairsContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via a viem client. */\nexport function readTokenPairsLengthContract(client: PublicClient, registry: Address) {\n return client.readContract(getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via a viem client. */\nexport function readTokenPairsSliceContract(\n client: PublicClient,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return client.readContract(getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via a viem client. */\nexport function readTokenPairContract(client: PublicClient, registry: Address, index: bigint) {\n return client.readContract(getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via a viem client. */\nexport function readConfidentialTokenAddressContract(\n client: PublicClient,\n registry: Address,\n tokenAddress: Address,\n) {\n return client.readContract(getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via a viem client. */\nexport function readTokenAddressContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via a viem client. */\nexport function readIsConfidentialTokenValidContract(\n client: PublicClient,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return client.readContract(isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"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"}
@@ -1,2 +1,2 @@
1
- import{r as e,t}from"../fhevm-relayer-CGvejcdJ.js";import{t as n}from"../validation-ClSvPh6P.js";import{z as r}from"zod/mini";const i=e=>r._default(r.number().check(r.positive()),e),a=r.custom(e=>typeof e==`function`),o=r.object({offloadEncrypt:r._default(r.union([r.literal(`auto`),r.boolean()]),`auto`),offloadTimeouts:r.optional(r.object({spawn:i(e.spawn),init:i(e.init)})),offloadWorker:r.optional(r.union([r.string().check(r.minLength(1)),r.instanceof(URL),a]))});function s(e){let{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a,...s}=e??{},c=n(o,{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a});return{type:`web`,createRelayer:(e,n,r)=>new t({chain:e,options:s,telemetry:r&&{state:r,runtime:`web`},offloadEncrypt:c.offloadEncrypt,offloadTimeouts:c.offloadTimeouts,offloadWorker:c.offloadWorker,logger:n})}}export{s as web};
1
+ import{r as e,t}from"../fhevm-relayer-OOqMoa_P.js";import{t as n}from"../validation-ClSvPh6P.js";import{z as r}from"zod/mini";const i=e=>r._default(r.number().check(r.positive()),e),a=r.custom(e=>typeof e==`function`),o=r.object({offloadEncrypt:r._default(r.union([r.literal(`auto`),r.boolean()]),`auto`),offloadTimeouts:r.optional(r.object({spawn:i(e.spawn),init:i(e.init)})),offloadWorker:r.optional(r.union([r.string().check(r.minLength(1)),r.instanceof(URL),a]))});function s(e){let{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a,...s}=e??{},c=n(o,{offloadEncrypt:r,offloadTimeouts:i,offloadWorker:a});return{type:`web`,createRelayer:(e,n,r)=>new t({chain:e,options:s,telemetry:r&&{state:r,runtime:`web`},offloadEncrypt:c.offloadEncrypt,offloadTimeouts:c.offloadTimeouts,offloadWorker:c.offloadWorker,logger:n})}}export{s as web};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zama-fhe/sdk",
3
- "version": "3.8.0-beta.2",
3
+ "version": "3.8.0-beta.3",
4
4
  "description": "TypeScript SDK for Zama fhEVM confidential smart contracts",
5
5
  "keywords": [
6
6
  "blockchain",