@zama-fhe/sdk 3.9.1-beta.2 → 3.9.1-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/cjs/telemetry.cjs +1 -1
- package/dist/esm/{base-signer-CysprC2L.js → base-signer-D-GNuCyg.js} +2 -2
- package/dist/esm/{base-signer-CysprC2L.js.map → base-signer-D-GNuCyg.js.map} +1 -1
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-C0DXenyT.js → cleartext-Cmrc_kxS.js} +2 -2
- package/dist/esm/{cleartext-C0DXenyT.js.map → cleartext-Cmrc_kxS.js.map} +1 -1
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/{fhevm-relayer-DCQ-Oaa1.js → fhevm-relayer-BI-D7Wcy.js} +2 -2
- package/dist/esm/{fhevm-relayer-DCQ-Oaa1.js.map → fhevm-relayer-BI-D7Wcy.js.map} +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/internal/index.js +1 -1
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/{telemetry-CW2RgPxb.js → telemetry-PsdiUPnw.js} +2 -2
- package/dist/esm/{telemetry-CW2RgPxb.js.map → telemetry-PsdiUPnw.js.map} +1 -1
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/web/index.js +1 -1
- package/package.json +1 -1
package/dist/esm/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./cleartext-C0DXenyT.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as ee,t as te,u as ne,v as re}from"./base-signer-CysprC2L.js";import{a as ie,c as ae,i as oe,l as se,n as ce,o as le,r as ue,s as de,t as fe,u as pe}from"./configs-9EL-DJHq.js";import{A as me,B as h,C as he,D as ge,E as _e,F as g,G as ve,H as ye,I as _,J as be,K as v,M as y,N as xe,O as Se,P as Ce,S as we,T as Te,U as Ee,W as De,X as b,Y as Oe,_ as ke,a as Ae,b as je,c as Me,d as Ne,f as x,h as Pe,j as Fe,k as Ie,l as Le,m as Re,n as S,o as ze,p as C,q as Be,s as Ve,t as w,u as He,v as Ue,w as We,x as Ge,y as Ke,z as qe}from"./alignment-D1cVCzw8.js";import{C as T,S as Je,_ as E,a as Ye,b as Xe,c as D,d as Ze,f as Qe,g as $e,h as et,i as tt,l as nt,m as rt,n as O,o as k,p as it,r as A,s as j,t as at,u as ot,v as M,w as st,x as N,y as P}from"./public-decrypt-Bec9uoNY.js";import{c as F,d as ct,f as lt,i as ut,l as dt,n as ft,o as pt,p as I,r as mt,s as ht,t as L,u as R}from"./token-DnriE-3y.js";import{C as z,_ as gt,a as _t,c as vt,g as yt,i as bt,m as xt,n as St,o as Ct,r as B,s as wt,t as V,y as Tt}from"./relayer-Cki3j_Ba.js";import{n as Et,r as H,t as U}from"./encryption-QHaWnnx-.js";import{a as Dt,c as Ot,d as kt,i as At,l as W,n as jt,o as Mt,s as Nt,t as Pt,u as Ft}from"./signing-DX-xyved.js";import{n as It,r as Lt}from"./fatal-batch-CI0ESPnd.js";import{i as Rt,n as zt,r as Bt,t as Vt}from"./unshield-xO66p_da.js";import{r as G}from"./telemetry-CW2RgPxb.js";import{t as K}from"./validation-BLmG7UVk.js";import{a as Ht,i as Ut,n as Wt,o as Gt,r as Kt,s as qt,t as Jt}from"./wrappers-registry-Cm3JJeqx.js";import{encodeFunctionData as Yt,getAddress as q,isAddressEqual as Xt,parseTransaction as Zt,size as Qt,zeroAddress as $t}from"viem";import{z as J}from"zod/mini";function en(e,t){if(e instanceof B){let n=t[e.code];if(n)return n(e)}return t._?.(e)}function tn(e,t){if(e instanceof B)return e;let n=wt(e),r=gt(e);return n!==void 0||yt(e)?new St(e instanceof Error?e.message:t,n,{cause:e,retryAfter:vt(e),retryable:r||void 0}):new H(t,{cause:e})}const nn=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function rn(e,t,n,r=`0x`){return{address:e,abi:nn,functionName:`transferAndCall`,args:[t,n,r]}}const Y=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function an(e,t,n,r){return{address:e,abi:Y,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function on(e,t,n){return{address:e,abi:Y,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function sn(e,t,n,r){return{address:e,abi:Y,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function cn(e,t,n,r,i){return{address:e,abi:Y,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const X=2n**64n-1n,Z=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function ln(e){return c(e.signer,e.provider,e)}const Q={ConfidentialTransfer:O(`ConfidentialTransfer(address,address,bytes32)`),Wrap:O(`Wrap(address,uint256,bytes32)`),UnwrapRequested:O(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:O(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function un(e){return e.topics[0]!==Q.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:A(e.topics[1]),to:A(e.topics[2]),encryptedAmount:tt(e.topics[3])}}function dn(e){return e.topics[0]!==Q.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:A(e.topics[1]),roundedAmount:k(e.data,0),encryptedWrappedAmount:j(e.data,1)}}function fn(e){return e.topics[0]!==Q.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:A(e.topics[1]),unwrapRequestId:tt(e.topics[2]),encryptedAmount:j(e.data,0)}}function pn(e){return e.topics[0]!==Q.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:A(e.topics[1]),unwrapRequestId:tt(e.topics[2]),encryptedAmount:j(e.data,0),cleartextAmount:k(e.data,1)}}function mn(e){return un(e)??dn(e)??fn(e)??pn(e)}function hn(e){let t=[];for(let n of e){let e=mn(n);e&&t.push(e)}return t}function gn(e){for(let t of e){let e=fn(t);if(e)return e}return null}function _n(e){for(let t of e){let e=dn(t);if(e)return e}return null}const vn=[Q.ConfidentialTransfer,Q.Wrap,Q.UnwrapRequested,Q.UnwrapFinalized],$={DelegatedForUserDecryption:O(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:O(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function yn(e){return e.topics[0]!==$.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:Ye(e.data,0),delegationCounter:k(e.data,1),oldExpirationDate:k(e.data,2),newExpirationDate:k(e.data,3)}}function bn(e){return e.topics[0]!==$.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:Ye(e.data,0),delegationCounter:k(e.data,1),oldExpirationDate:k(e.data,2)}}function xn(e){return yn(e)??bn(e)}function Sn(e){let t=[];for(let n of e){let e=xn(n);e&&t.push(e)}return t}function Cn(e){for(let t of e){let e=yn(t);if(e)return e}return null}function wn(e){for(let t of e){let e=bn(t);if(e)return e}return null}const Tn=[$.DelegatedForUserDecryption,$.RevokedDelegationForUserDecryption];var En=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return v(this.#r,e)}#s(e,t){throw this.#a({type:h.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await S(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await S(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}registerPermit(e,t){return this.batchRegisterPermits([{prepared:e,signature:t}])}async batchRegisterPermits(e){let t;try{t=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await t.batchRegisterPermits(e),await Promise.all([...new Set(e.map(e=>e.prepared.signerAddress))].map(e=>this.#c(e)))}async revokePermits(e){let t=this.#o(`revokePermits`),n=await w(`revokePermits`,this.#e,this.#t),r=q(n.address);try{await t.revokePermits(e)}finally{await this.#c(r)}}async clear(){let e=this.#o(`clear`),t=await w(`clear`,this.#e,this.#t),n=q(t.address);try{await e.clearCredentials()}finally{await this.#c(n)}}async#c(e){await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},Dn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return v(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await w(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await w(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},On=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return v(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await w(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,G(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await w(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,G(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=G(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{qe(t.clearValues[n],`result.clearValues[${n}]`),r[e]=t.clearValues[n].value}),{clearValues:r,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw D(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i,operation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await w(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i,operation:a??`delegated-batch-decrypt-values`})}},kn=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}batchPreparePermits(e){return this.#t.batchPreparePermits(e)}},An=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const jn=new An;async function Mn(e,t){if(e.getTransactionReceipt)return e.getTransactionReceipt(t);let n,r=new Promise(e=>{n=setTimeout(()=>e(null),5e3)});try{return await Promise.race([e.waitForTransactionReceipt(t),r])}finally{clearTimeout(n)}}function Nn(e){return`zama:pending-unshields:${i(e)}`}function Pn(e){return`zama:pending-unshield:${i(e)}`}function Fn(e){return{version:2,unwrapTxHashes:e}}const In=J.union([p,J.pipe(J.object({version:J.literal(1),unwrapTxHash:p}),J.transform(({unwrapTxHash:e})=>e))]),Ln=J.object({version:J.number(),unwrapTxHashes:J.optional(J.unknown())}),Rn=(e,t)=>e.toLowerCase()===t.toLowerCase();async function zn(e,t,n){let r=await e.get(t);if(r==null)return{hashes:[],writable:!0};let i=Ln.safeParse(r);if(i.success&&i.data.version!==2)return n?.warn(`pending unshields saved by an unknown SDK version were left as is`,{version:i.data.version}),{hashes:[],writable:!1};let a=i.success?i.data.unwrapTxHashes:void 0;if(!Array.isArray(a))return n?.warn(`unreadable pending unshields were dropped`,{value:r}),{hashes:[],writable:!0};let o=a.filter(e=>p.safeParse(e).success);return o.length!==a.length&&n?.warn(`unreadable pending unshield entries were dropped`,{unwrapTxHashes:a}),{hashes:o,writable:!0}}async function Bn(e,t,n){let r=await zn(e,Nn(t),n),i=In.safeParse(await e.get(Pn(t)));return!i.success||!r.writable?{...r,hasLegacy:!1}:{hashes:r.hashes.some(e=>Rn(e,i.data))?r.hashes:[i.data,...r.hashes],writable:!0,hasLegacy:!0}}async function Vn(e,t,n){let r=Nn(t);await(n.length===0?e.delete(r):e.set(r,Fn(n)))}const Hn=/* @__PURE__ */ new WeakMap;function Un(e,t){let n=(Hn.get(e)??Promise.resolve()).then(t);return Hn.set(e,n.then(()=>{},()=>{})),n}function Wn(e,t,n,r){return Un(e,async()=>{let{hashes:i,writable:a,hasLegacy:o}=await Bn(e,t,n);if(!a)return;let s=r(i);(o||s.length!==i.length)&&await Vn(e,t,s),o&&await e.delete(Pn(t))})}async function Gn(e,t,n){return(await Un(e,()=>Bn(e,t,n))).hashes}function Kn(e,t,n,r){return Wn(e,t,r,e=>e.some(e=>Rn(e,n))?e:[...e,n])}function qn(e,t,n,r){return Wn(e,t,r,e=>e.filter(e=>!Rn(e,n)))}function Jn(e,t){let n=q(t);return gn(e.filter(e=>e.address===void 0||q(e.address)===n))?.unwrapRequestId}function Yn(e,t){if(!e)return`unknown`;let n=e.status===`reverted`?void 0:Jn(e.logs,t);return n===void 0?`settled`:{unwrapRequestId:n}}var Xn=class extends L{#e;#t=null;#n=null;#r(e){try{return qe(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new ye(e,{cause:t})}}async underlying(){return this.#m()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#m();this.#n=await this.sdk.provider.readContract(He(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#m();return this.sdk.provider.readContract(x(t,q(e),this.address))}async shield(e,t){let n=await w(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),i=await this.#m(),a=q(n.address),o;try{o=await this.sdk.provider.readContract(Re(i,a))}catch(e){throw e instanceof B?e:new R(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:z(e)})}if(o<e)throw new I(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${i})`,{requested:e,available:o,token:i});return r?this.#i(e,i,a,t):this.#a(e,a,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?q(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:rn(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await w(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#m(),i=q(n.address),a;try{a=await this.sdk.provider.readContract(Re(r,i))}catch(e){throw e instanceof B?e:new R(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:z(e)})}if(a<e)throw new I(`Insufficient ERC-20 balance: requested ${e}, available ${a} (token: ${r})`,{requested:e,available:a,token:r});let o;try{o=await this.sdk.provider.readContract(x(r,i,this.address))}catch(e){throw e instanceof B?e:new R(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:z(e)})}if(o<e)throw new ct(`Insufficient allowance for wrap: requested ${e}, approved ${o}. Call approveUnderlying() first (token: ${r}).`,{requested:e,available:o,token:r});let s=t?.to?q(t.to):i;return this.submitTransaction({operation:`wrap`,config:g(this.address,s,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#g(e,r===`max`,n);let i=n?.to?q(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:g(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await w(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#m(),r=q(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(x(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:C(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:C(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.#o(e,`unshield`,e=>this.#d(e));return _(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#h(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.#s(e=>this.#d(e));return _(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#h(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await Mn(this.sdk.provider,e)}catch(e){throw e instanceof B?e:new b(`Failed to get unwrap receipt`,{cause:e})}let r=Yn(n,this.address);if(r===`unknown`)throw new zt(`Unwrap transaction ${e} is not mined, so there is nothing to resume yet`,e);if(r===`settled`)throw await this.#p(`resumeUnshield`,e),new b(`Unwrap transaction ${e} reverted or opened no unwrap request from this wrapper, so there is nothing to resume`);let{unwrapRequestId:i}=r;if(await this.#u(i)===`settled`)throw await this.#p(`resumeUnshield`,e),new Vt(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:i});return await _(`resumeUnshield: savePendingUnshield`,()=>this.#d(e),this.sdk.logger),this.#h(i,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=null,t=await Gn(this.sdk.storage,this.address,this.sdk.logger);for(let n of t){let t=await this.#f(n);if(t===`open`)return n;t===`settled`?await this.#p(`getPendingUnshield`,n):e??=n}return e}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t,n){this.#r(`unwrap`);let r=await w(`unwrap`,this.sdk.signer,this.sdk.provider),i=q(r.address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i},{operation:t}),[s]=a;if(!s)throw new H(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:y(this.address,i,i,s,o),beforeReceipt:n});return{...c,unwrapRequestId:this.#l(c.receipt.logs)}}async unwrapAll(){return this.#s()}async#s(e){this.#r(`unwrapAll`);let t=await w(`unwrapAll`,this.sdk.signer,this.sdk.provider),n=q(t.address),r=await this.readConfidentialBalanceOf(n);if(F(r))throw new U(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:xe(this.address,n,n,r),beforeReceipt:e});return{...i,unwrapRequestId:this.#l(i.receipt.logs)}}async finalizeUnwrap(e){return this.#c(e,`finalize-unwrap`)}async#c(e,t){this.#r(`finalizeUnwrap`),await S(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let{value:n,decryptionProof:r}=await at(this.sdk.relayer,e,{operation:t});return this.submitTransaction({operation:`finalizeUnwrap`,config:Te(this.address,e,n,r)})}#l(e){let t=Jn(e,this.address);if(t===void 0)throw new b(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t}async#u(e){try{return await this.sdk.provider.readContract(Ce(this.address,e))===$t?`settled`:`open`}catch{return`unknown`}}#d(e){return Kn(this.sdk.storage,this.address,e,this.sdk.logger)}async#f(e){let t;try{t=await Mn(this.sdk.provider,e)}catch{return`unknown`}let n=Yn(t,this.address);return typeof n==`string`?n:this.#u(n.unwrapRequestId)}async#p(e,t){await _(`${e}: clearPendingUnshield`,()=>qn(this.sdk.storage,this.address,t,this.sdk.logger),this.sdk.logger)}async#m(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(me(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#h(e,t,n,r,i){this.emit({type:h.UnshieldPhase1Submitted,txHash:t,operationId:n}),this.emit({type:h.UnshieldPhase2Started,operationId:n}),_(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#c(e,i)}catch(n){throw Bt(n)||n instanceof b&&await this.#u(e)===`settled`?(await this.#p(`unshield`,t),new Vt(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:h.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),_(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#p(`unshield`,t),a}async#g(e,t,n){this.#r(`approveUnderlying`);let r=await this.#m(),i=await w(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=q(i.address),o=await this.sdk.provider.readContract(x(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:C(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:C(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};const Zn=J.union([J.bigint(),J.boolean(),a]),Qn=J.array(J.string());var $n=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=Zn.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=q(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${q(e)}:${q(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Qn.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function er(e,t){let n=tr(e,t);if(!n)throw new U(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function tr(e,t){let n=i(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const nr=e=>new Promise(t=>setTimeout(t,e));var rr=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=q(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=q(t),o=q(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:q(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:i?.operation},s))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof Je))throw t;await nr(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0,operation:o}){let s=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:q(e.contractAddress)}));if(s.length===0)return{items:s};let c=q(r);try{let e=await this.delegatedDecryptValues(s.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,c,{waitForPropagation:a,operation:o});for(let t of s)this.#d(t,e);return{items:s}}catch(e){if(It(e))throw e;if(s.length===1){let[n=this.#p()]=s;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:q(t)}),{items:s}}}let l=!1,u;if(await ut(s.map(e=>async()=>{if(!l)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,c,{waitForPropagation:!1,operation:o});this.#d(e,r)}catch(n){if(It(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:q(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=er(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&xt(e.message)&&await this.#t.evictTransportKeyPair(),e}let o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n,r={spent:!1}){if(e.length===0)return{};let i=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:q(e.contractAddress)})),a={},o=[];for(let e of i)F(e.encryptedValue)?a[e.encryptedValue]=0n:o.push(e);if(o.length===0)return a;let s=Array.from(new Set(i.map(e=>e.contractAddress))),c=Array.from(new Set(o.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(c)}catch(e){throw Tt(e)?this.#u(e,`the delegation pre-check`):e}let l=[];for(let e of o){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?l.push(e):a[e.encryptedValue]=n}if(l.length===0)return a;let u=await this.#t.grantPermit(s,t.delegator),d=/* @__PURE__ */ new Map;for(let e of l){let t=d.get(e.contractAddress);t?t.push(e.encryptedValue):d.set(e.contractAddress,[e.encryptedValue])}let f=[];for(let[e,t]of d)for(let n of ht(t))f.push({contractAddress:e,encryptedValues:n});let p=Date.now(),m=l.map(e=>e.encryptedValue);try{this.#i({type:h.DecryptStart,encryptedValues:m});try{await this.#c(t,u,f,a,n)}catch(e){if(!(e instanceof W)||r.spent)throw e;let i=u.permissions.map(e=>e.serializedPermit.signature);r.spent=!0;try{u=await this.#t.recoverPermits(s,t.delegator,i)}catch(e){throw e instanceof Pt?new W(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(t,u,f.filter(({encryptedValues:e})=>e.some(e=>a[e]===void 0)),a,n)}let e={};for(let t of m){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:h.DecryptEnd,durationMs:Date.now()-p,encryptedValues:m,result:e}),a}catch(e){let n=e instanceof B&&e.cause instanceof Error?e.cause:e;throw this.#i({type:h.DecryptError,error:z(n),durationMs:Date.now()-p,encryptedValues:m}),D(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await ut(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(a.length>0)throw a.find(e=>e instanceof W)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw D(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new U(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new U(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new Lt(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:vt(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new U(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`):e.value=n}#f(e,t,n){return e instanceof B?e:D(e,t,n)}#p(){throw new U(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};const ir={AlreadyDelegatedOrRevokedInSameBlock:e=>new et(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new rt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new it(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new T(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new E(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new $e(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new M(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new Xe(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new N(`Cannot revoke: no active delegation exists.`,{cause:e})};function ar(e){return Object.hasOwn(ir,e)}function or(e,t){let n=Rt(e);if(n&&ar(n))return ir[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(ir))if(r.includes(e))return n(t);return null}var sr=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new M(`Expiration date must be at least 1 hour in the future`);let a=q(t),o=q(n),s=q(r);if(o===s)throw new T(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===q(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new $e(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new E(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):X,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new Xe(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==q(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:an(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=q(t),a=q(n),o=q(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new N(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:on(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=q(e.contractAddress)===Z,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:Z})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:Z});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==X}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===X?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(sn(r,q(t),q(n),q(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await ft({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#c(e),e}}#c(e){if(!(e instanceof b))return;let t=or(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof N||t instanceof P){let n=q(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=q(e),i=q(t),a=q(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new N(`No active delegation from ${i} to ${a} for ${r}`):new P(`Delegation from ${i} to ${a} for ${r} has expired`)}},cr=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=q(e.contractAddress);try{this.#t({type:h.EncryptStart},r);let i=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:h.EncryptEnd,durationMs:Date.now()-n},r),i}catch(e){throw this.#t({type:h.EncryptError,error:z(e),durationMs:Date.now()-n},r),tn(e,`Encryption failed`)}}},lr=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.clearCredentialsOnWalletChange,this.#a=e.logger,this.#e&&(this.#s=this.#e.walletAccount.subscribe(e=>{this.#c(e).catch(e=>{this.#a.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#o.add(e),()=>{this.#o.delete(e)}}dispose(){this.#s?.(),this.#s=void 0,this.#o.clear()}async#c(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await _(`switch relayer chain`,()=>this.#t.switchChain(r),this.#a),this.#i&&await this.#l(t,n),await Promise.all(Array.from(this.#o,t=>_(`wallet account listener`,()=>t(e),this.#a)))}async#l(e,t){let n=this.#r;n&&await _(`credential wallet account change`,()=>n.handleWalletAccountChange(e,t),this.#a),e&&await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e.address),this.#a)}};const ur=J.object({kind:J.literal(`ConfidentialTransfer`),from:a,token:a,to:a,amount:J.bigint()}),dr=J.object({kind:J.literal(`ConfidentialTransferFrom`),from:a,token:a,owner:a,to:a,amount:J.bigint()}),fr=J.object({kind:J.literal(`SetOperator`),from:a,token:a,operator:a,until:u}),pr=J.object({kind:J.literal(`Unwrap`),from:a,token:a,to:a,amount:J.bigint()}),mr=J.object({kind:J.literal(`UnwrapAll`),from:a,token:a,to:a}),hr=J.object({kind:J.literal(`FinalizeUnwrap`),from:a,wrapper:a,unwrapRequestIdOrAmount:p}),gr=J.object({kind:J.literal(`ApproveUnderlying`),from:a,underlying:a,spender:a,amount:J.bigint()}),_r=J.object({kind:J.literal(`Wrap`),from:a,wrapper:a,to:a,amount:J.bigint()}),vr=p.check(J.refine(e=>e===`0x`||Qt(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),yr=J.object({kind:J.literal(`TransferAndCall`),from:a,underlying:a,wrapper:a,amount:J.bigint(),recipientData:J.optional(vr)}),br=J.object({kind:J.literal(`DelegateDecryption`),from:a,contractAddress:a,delegateAddress:a,expirationDate:J.optional(J.date())}),xr=J.object({kind:J.literal(`RevokeDelegation`),from:a,contractAddress:a,delegateAddress:a});J.discriminatedUnion(`kind`,[ur,dr,fr,pr,mr,hr,gr,_r,yr,br,xr]);const Sr=J.strictObject({maxFeePerGas:J.bigint(),maxPriorityFeePerGas:J.bigint()}),Cr=J.object({nonce:J.optional(J.int().check(J.nonnegative())),gasLimit:J.optional(J.bigint()),fees:J.optional(Sr)}),wr=J.object({address:a,abi:J.array(J.unknown()),functionName:J.string(),args:J.array(J.unknown()),value:J.optional(J.bigint()),gas:J.optional(J.bigint())}),Tr=J.extend(Cr,{from:a,calldata:wr});var Er=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=K(Cr,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new V(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i={calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees},a=K(Tr,i),o=await this.#e.prepareTransaction(a).catch(t=>{throw mt(t,`prepare ${e.kind}`)??t}),s=Zt(o),c=Yt({abi:a.calldata.abi,functionName:a.calldata.functionName,args:a.calldata.args});if(s.chainId!==r||!s.to||!Xt(s.to,a.calldata.address)||s.data?.toLowerCase()!==c.toLowerCase()||(s.value??0n)!==(a.calldata.value??0n))throw new V(`Offline.prepare: the provider returned a transaction that does not match the prepared ${e.kind} call on chain ${r}.`);return{kind:e.kind,unsignedTx:o,from:a.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new V(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=K(ur,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer`}),r=t[0];if(!r)throw new H(`Encryption returned no handles for ConfidentialTransfer`);return we(e.token,e.to,r,n)}async#a(e){e=K(dr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer-from`}),r=t[0];if(!r)throw new H(`Encryption returned no handles for ConfidentialTransferFrom`);return We(e.token,e.owner,e.to,r,n)}#o(e){return e=K(fr,e),Ie(e.token,e.operator,e.until)}async#s(e){e=K(pr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-unwrap`}),r=t[0];if(!r)throw new H(`Encryption returned no handles for Unwrap`);return y(e.token,e.from,e.to,r,n)}async#c(e){e=K(mr,e);let t=await this.#e.readContract(Ke(e.token,e.from));return xe(e.token,e.from,e.to,t)}async#l(e){e=K(hr,e);let{value:t,decryptionProof:n}=await at(this.#t.relayer,e.unwrapRequestIdOrAmount,{operation:`offline-finalize-unwrap`});return Te(e.wrapper,e.unwrapRequestIdOrAmount,t,n)}#u(e){return e=K(gr,e),C(e.underlying,e.spender,e.amount)}#d(e){return e=K(_r,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=K(yr,e),rn(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=K(br,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new M(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new T(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new E(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):X;return an(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=K(xr,e),on(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Dr(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new V(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function Or(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new V(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function kr(e){if(e===void 0)return;let t=K(l,e);return new ne(typeof t==`string`?t:new Uint8Array(t))}var Ar=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Dr(t),Or(t.transportKeyPairDerivationSecret);let n=kr(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new $n(e.storage,this.#i),this.#u=new sr({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new f({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new ee({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new rr({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new cr({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new lr({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new Er({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new En({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new Dn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new On({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new kn(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}get chains(){return this.#e.chains}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new f({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,G(t,`encrypt`))}createToken(e){return new L(this,e)}createWrappedToken(e){return new Xn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{Tn as ACL_TOPICS,it as AclPausedError,$ as AclTopics,dt as BalanceCheckUnavailableError,te as BaseSigner,Be as ChainMismatchError,An as ChromeSessionStorage,V as ConfigurationError,On as Decryption,U as DecryptionFailedError,n as DefaultRegistryAddresses,rt as DelegationContractIsSelfError,et as DelegationCooldownError,$e as DelegationDelegateCannotBeWildcardError,E as DelegationDelegateEqualsContractError,M as DelegationExpirationTooSoonError,P as DelegationExpiredError,Xe as DelegationExpiryUnchangedError,N as DelegationNotFoundError,Je as DelegationNotPropagatedError,T as DelegationSelfNotAllowedError,Dn as Delegations,Ae as ERC1363_INTERFACE_ID,R as ERC20ReadFailedError,ze as ERC7984_INTERFACE_ID,Ve as ERC7984_WRAPPER_INTERFACE_ID,Et as EncryptOffloadUnavailableError,H as EncryptionFailedError,be as HcuBlockLimitExceededError,Oe as HcuTransactionLimitExceededError,t as IndexedDBStorage,ct as InsufficientAllowanceError,lt as InsufficientConfidentialBalanceError,I as InsufficientERC20BalanceError,At as InvalidTransportKeyPairError,Dt as KeyWrappingError,X as MAX_UINT64,s as MemoryStorage,d as MutableWalletAccountStore,Mt as NoCiphertextError,st as NotEntitledError,kn as Offline,En as Permits,Nt as PreparedPermitChainMismatchError,Ot as PreparedPermitExpiredError,St as RelayerRequestFailedError,W as RevokedKmsContextError,Lt as RpcRateLimitError,ye as SignerNotConfiguredError,Ee as SignerRequiredError,Pt as SigningFailedError,jt as SigningRejectedError,vn as TOKEN_TOPICS,L as Token,Q as Topics,b as TransactionRevertedError,Ft as TransportKeyPairChangedError,kt as TransportKeyPairExpiredError,Vt as UnshieldAlreadyFinalizedError,zt as UnwrapNotMinedError,nt as VaultBatchNotDispatchedError,ot as VaultBatcherPausedError,Ze as VaultBatcherReadFailedError,Qe as VaultJoinUnconfirmedError,Z as WILDCARD_CONTRACT,De as WalletAccountNotReadyError,ve as WalletNotConnectedError,Xn as WrappedToken,f as WrappersRegistry,pt as ZERO_ENCRYPTED_VALUE,B as ZamaError,bt as ZamaErrorCode,Ar as ZamaSDK,h as ZamaSDKEvents,x as allowanceContract,fe as anvil,C as approveContract,Re as balanceOfContract,ce as bscTestnet,ue as chains,jn as chromeSessionStorage,e as cleartext,Ke as confidentialBalanceOfContract,je as confidentialTotalSupplyContract,Ge as confidentialTransferAndCallContract,we as confidentialTransferContract,he as confidentialTransferFromAndCallContract,We as confidentialTransferFromContract,ln as createConfig,m as createWalletAccountStore,Pe as decimalsContract,xn as decodeAclEvent,Sn as decodeAclEvents,un as decodeConfidentialTransfer,yn as decodeDelegatedForUserDecryption,mn as decodeOnChainEvent,hn as decodeOnChainEvents,bn as decodeRevokedDelegationForUserDecryption,pn as decodeUnwrapFinalized,fn as decodeUnwrapRequested,dn as decodeWrap,an as delegateForUserDecryptionContract,Te as finalizeUnwrapContract,Cn as findDelegatedForUserDecryption,wn as findRevokedDelegationForUserDecryption,gn as findUnwrapRequested,_n as findWrap,Jt as getConfidentialTokenAddressContract,sn as getDelegationExpiryContract,Wt as getTokenAddressContract,Kt as getTokenPairContract,Ut as getTokenPairsContract,Ht as getTokenPairsLengthContract,Gt as getTokenPairsSliceContract,oe as hardhat,ie as hoodi,re as indexedDBStorage,_e as inferredTotalSupplyContract,Me as isConfidentialTokenContract,qt as isConfidentialTokenValidContract,Le as isConfidentialWrapperContract,F as isEncryptedValueZero,cn as isHandleDelegatedContract,ge as isOperatorContract,_t as isRetryable,le as mainnet,en as matchZamaError,o as memoryStorage,ke as nameContract,r as parsePreparedPermit,de as polygon,ae as polygonAmoy,Se as rateContract,Ct as retryAfterSeconds,on as revokeDelegationContract,se as sepolia,Ie as setOperatorContract,Ne as supportsInterfaceContract,Ue as symbolContract,rn as transferAndCallContract,me as underlyingContract,Fe as unwrapAmountContract,y as unwrapContract,xe as unwrapFromBalanceContract,Ce as unwrapRequesterContract,g as wrapContract,pe as zenithTrexTestnet};
|
|
1
|
+
import{t as e}from"./cleartext-Cmrc_kxS.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as ee,t as te,u as ne,v as re}from"./base-signer-D-GNuCyg.js";import{a as ie,c as ae,i as oe,l as se,n as ce,o as le,r as ue,s as de,t as fe,u as pe}from"./configs-9EL-DJHq.js";import{A as me,B as h,C as he,D as ge,E as _e,F as g,G as ve,H as ye,I as _,J as be,K as v,M as y,N as xe,O as Se,P as Ce,S as we,T as Te,U as Ee,W as De,X as b,Y as Oe,_ as ke,a as Ae,b as je,c as Me,d as Ne,f as x,h as Pe,j as Fe,k as Ie,l as Le,m as Re,n as S,o as ze,p as C,q as Be,s as Ve,t as w,u as He,v as Ue,w as We,x as Ge,y as Ke,z as qe}from"./alignment-D1cVCzw8.js";import{C as T,S as Je,_ as E,a as Ye,b as Xe,c as D,d as Ze,f as Qe,g as $e,h as et,i as tt,l as nt,m as rt,n as O,o as k,p as it,r as A,s as j,t as at,u as ot,v as M,w as st,x as N,y as P}from"./public-decrypt-Bec9uoNY.js";import{c as F,d as ct,f as lt,i as ut,l as dt,n as ft,o as pt,p as I,r as mt,s as ht,t as L,u as R}from"./token-DnriE-3y.js";import{C as z,_ as gt,a as _t,c as vt,g as yt,i as bt,m as xt,n as St,o as Ct,r as B,s as wt,t as V,y as Tt}from"./relayer-Cki3j_Ba.js";import{n as Et,r as H,t as U}from"./encryption-QHaWnnx-.js";import{a as Dt,c as Ot,d as kt,i as At,l as W,n as jt,o as Mt,s as Nt,t as Pt,u as Ft}from"./signing-DX-xyved.js";import{n as It,r as Lt}from"./fatal-batch-CI0ESPnd.js";import{i as Rt,n as zt,r as Bt,t as Vt}from"./unshield-xO66p_da.js";import{r as G}from"./telemetry-PsdiUPnw.js";import{t as K}from"./validation-BLmG7UVk.js";import{a as Ht,i as Ut,n as Wt,o as Gt,r as Kt,s as qt,t as Jt}from"./wrappers-registry-Cm3JJeqx.js";import{encodeFunctionData as Yt,getAddress as q,isAddressEqual as Xt,parseTransaction as Zt,size as Qt,zeroAddress as $t}from"viem";import{z as J}from"zod/mini";function en(e,t){if(e instanceof B){let n=t[e.code];if(n)return n(e)}return t._?.(e)}function tn(e,t){if(e instanceof B)return e;let n=wt(e),r=gt(e);return n!==void 0||yt(e)?new St(e instanceof Error?e.message:t,n,{cause:e,retryAfter:vt(e),retryable:r||void 0}):new H(t,{cause:e})}const nn=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function rn(e,t,n,r=`0x`){return{address:e,abi:nn,functionName:`transferAndCall`,args:[t,n,r]}}const Y=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function an(e,t,n,r){return{address:e,abi:Y,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function on(e,t,n){return{address:e,abi:Y,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function sn(e,t,n,r){return{address:e,abi:Y,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function cn(e,t,n,r,i){return{address:e,abi:Y,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const X=2n**64n-1n,Z=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function ln(e){return c(e.signer,e.provider,e)}const Q={ConfidentialTransfer:O(`ConfidentialTransfer(address,address,bytes32)`),Wrap:O(`Wrap(address,uint256,bytes32)`),UnwrapRequested:O(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:O(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function un(e){return e.topics[0]!==Q.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:A(e.topics[1]),to:A(e.topics[2]),encryptedAmount:tt(e.topics[3])}}function dn(e){return e.topics[0]!==Q.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:A(e.topics[1]),roundedAmount:k(e.data,0),encryptedWrappedAmount:j(e.data,1)}}function fn(e){return e.topics[0]!==Q.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:A(e.topics[1]),unwrapRequestId:tt(e.topics[2]),encryptedAmount:j(e.data,0)}}function pn(e){return e.topics[0]!==Q.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:A(e.topics[1]),unwrapRequestId:tt(e.topics[2]),encryptedAmount:j(e.data,0),cleartextAmount:k(e.data,1)}}function mn(e){return un(e)??dn(e)??fn(e)??pn(e)}function hn(e){let t=[];for(let n of e){let e=mn(n);e&&t.push(e)}return t}function gn(e){for(let t of e){let e=fn(t);if(e)return e}return null}function _n(e){for(let t of e){let e=dn(t);if(e)return e}return null}const vn=[Q.ConfidentialTransfer,Q.Wrap,Q.UnwrapRequested,Q.UnwrapFinalized],$={DelegatedForUserDecryption:O(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:O(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function yn(e){return e.topics[0]!==$.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:Ye(e.data,0),delegationCounter:k(e.data,1),oldExpirationDate:k(e.data,2),newExpirationDate:k(e.data,3)}}function bn(e){return e.topics[0]!==$.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:Ye(e.data,0),delegationCounter:k(e.data,1),oldExpirationDate:k(e.data,2)}}function xn(e){return yn(e)??bn(e)}function Sn(e){let t=[];for(let n of e){let e=xn(n);e&&t.push(e)}return t}function Cn(e){for(let t of e){let e=yn(t);if(e)return e}return null}function wn(e){for(let t of e){let e=bn(t);if(e)return e}return null}const Tn=[$.DelegatedForUserDecryption,$.RevokedDelegationForUserDecryption];var En=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#a=e.emitEvent}#o(e){return v(this.#r,e)}#s(e,t){throw this.#a({type:h.PermitError,operation:e,error:t instanceof Error?t:Error(String(t))}),t}async grantPermit(e){if(e.length===0)return;let t;try{t=this.#o(`grantPermit`),await S(`grantPermit`,this.#e,this.#t)}catch(e){this.#s(`grantPermit`,e)}await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n;try{n=this.#o(`grantDelegationPermit`),await S(`grantDelegationPermit`,this.#e,this.#t)}catch(e){this.#s(`grantDelegationPermit`,e)}await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}registerPermit(e,t){return this.batchRegisterPermits([{prepared:e,signature:t}])}async batchRegisterPermits(e){let t;try{t=this.#o(`registerPermit`)}catch(e){this.#s(`registerPermit`,e)}await t.batchRegisterPermits(e),await Promise.all([...new Set(e.map(e=>e.prepared.signerAddress))].map(e=>this.#c(e)))}async revokePermits(e){let t=this.#o(`revokePermits`),n=await w(`revokePermits`,this.#e,this.#t),r=q(n.address);try{await t.revokePermits(e)}finally{await this.#c(r)}}async clear(){let e=this.#o(`clear`),t=await w(`clear`,this.#e,this.#t),n=q(t.address);try{await e.clearCredentials()}finally{await this.#c(n)}}async#c(e){await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},Dn=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return v(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await w(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),r=await w(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:r.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},On=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return v(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await w(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,G(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await w(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,G(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=G(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{qe(t.clearValues[n],`result.clearValues[${n}]`),r[e]=t.clearValues[n].value}),{clearValues:r,abiEncodedClearValues:t.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:t.checkSignaturesArgs.decryptionProof}}catch(e){throw D(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:r,waitForPropagation:i,operation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await w(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:n,maxConcurrency:r,waitForPropagation:i,operation:a??`delegated-batch-decrypt-values`})}},kn=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}prepare(e,t){return this.#e.prepare(e,t)}preparePermit(e){return this.#t.preparePermit(e)}batchPreparePermits(e){return this.#t.batchPreparePermits(e)}},An=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const jn=new An;async function Mn(e,t){if(e.getTransactionReceipt)return e.getTransactionReceipt(t);let n,r=new Promise(e=>{n=setTimeout(()=>e(null),5e3)});try{return await Promise.race([e.waitForTransactionReceipt(t),r])}finally{clearTimeout(n)}}function Nn(e){return`zama:pending-unshields:${i(e)}`}function Pn(e){return`zama:pending-unshield:${i(e)}`}function Fn(e){return{version:2,unwrapTxHashes:e}}const In=J.union([p,J.pipe(J.object({version:J.literal(1),unwrapTxHash:p}),J.transform(({unwrapTxHash:e})=>e))]),Ln=J.object({version:J.number(),unwrapTxHashes:J.optional(J.unknown())}),Rn=(e,t)=>e.toLowerCase()===t.toLowerCase();async function zn(e,t,n){let r=await e.get(t);if(r==null)return{hashes:[],writable:!0};let i=Ln.safeParse(r);if(i.success&&i.data.version!==2)return n?.warn(`pending unshields saved by an unknown SDK version were left as is`,{version:i.data.version}),{hashes:[],writable:!1};let a=i.success?i.data.unwrapTxHashes:void 0;if(!Array.isArray(a))return n?.warn(`unreadable pending unshields were dropped`,{value:r}),{hashes:[],writable:!0};let o=a.filter(e=>p.safeParse(e).success);return o.length!==a.length&&n?.warn(`unreadable pending unshield entries were dropped`,{unwrapTxHashes:a}),{hashes:o,writable:!0}}async function Bn(e,t,n){let r=await zn(e,Nn(t),n),i=In.safeParse(await e.get(Pn(t)));return!i.success||!r.writable?{...r,hasLegacy:!1}:{hashes:r.hashes.some(e=>Rn(e,i.data))?r.hashes:[i.data,...r.hashes],writable:!0,hasLegacy:!0}}async function Vn(e,t,n){let r=Nn(t);await(n.length===0?e.delete(r):e.set(r,Fn(n)))}const Hn=/* @__PURE__ */ new WeakMap;function Un(e,t){let n=(Hn.get(e)??Promise.resolve()).then(t);return Hn.set(e,n.then(()=>{},()=>{})),n}function Wn(e,t,n,r){return Un(e,async()=>{let{hashes:i,writable:a,hasLegacy:o}=await Bn(e,t,n);if(!a)return;let s=r(i);(o||s.length!==i.length)&&await Vn(e,t,s),o&&await e.delete(Pn(t))})}async function Gn(e,t,n){return(await Un(e,()=>Bn(e,t,n))).hashes}function Kn(e,t,n,r){return Wn(e,t,r,e=>e.some(e=>Rn(e,n))?e:[...e,n])}function qn(e,t,n,r){return Wn(e,t,r,e=>e.filter(e=>!Rn(e,n)))}function Jn(e,t){let n=q(t);return gn(e.filter(e=>e.address===void 0||q(e.address)===n))?.unwrapRequestId}function Yn(e,t){if(!e)return`unknown`;let n=e.status===`reverted`?void 0:Jn(e.logs,t);return n===void 0?`settled`:{unwrapRequestId:n}}var Xn=class extends L{#e;#t=null;#n=null;#r(e){try{return qe(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new ye(e,{cause:t})}}async underlying(){return this.#m()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#m();this.#n=await this.sdk.provider.readContract(He(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#m();return this.sdk.provider.readContract(x(t,q(e),this.address))}async shield(e,t){let n=await w(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),i=await this.#m(),a=q(n.address),o;try{o=await this.sdk.provider.readContract(Re(i,a))}catch(e){throw e instanceof B?e:new R(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:z(e)})}if(o<e)throw new I(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${i})`,{requested:e,available:o,token:i});return r?this.#i(e,i,a,t):this.#a(e,a,t)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?q(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:rn(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await w(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#m(),i=q(n.address),a;try{a=await this.sdk.provider.readContract(Re(r,i))}catch(e){throw e instanceof B?e:new R(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:z(e)})}if(a<e)throw new I(`Insufficient ERC-20 balance: requested ${e}, available ${a} (token: ${r})`,{requested:e,available:a,token:r});let o;try{o=await this.sdk.provider.readContract(x(r,i,this.address))}catch(e){throw e instanceof B?e:new R(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:z(e)})}if(o<e)throw new ct(`Insufficient allowance for wrap: requested ${e}, approved ${o}. Call approveUnderlying() first (token: ${r}).`,{requested:e,available:o,token:r});let s=t?.to?q(t.to):i;return this.submitTransaction({operation:`wrap`,config:g(this.address,s,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#g(e,r===`max`,n);let i=n?.to?q(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:g(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await w(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#m(),r=q(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(x(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:C(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:C(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.#o(e,`unshield`,e=>this.#d(e));return _(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#h(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.#s(e=>this.#d(e));return _(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#h(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await Mn(this.sdk.provider,e)}catch(e){throw e instanceof B?e:new b(`Failed to get unwrap receipt`,{cause:e})}let r=Yn(n,this.address);if(r===`unknown`)throw new zt(`Unwrap transaction ${e} is not mined, so there is nothing to resume yet`,e);if(r===`settled`)throw await this.#p(`resumeUnshield`,e),new b(`Unwrap transaction ${e} reverted or opened no unwrap request from this wrapper, so there is nothing to resume`);let{unwrapRequestId:i}=r;if(await this.#u(i)===`settled`)throw await this.#p(`resumeUnshield`,e),new Vt(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:i});return await _(`resumeUnshield: savePendingUnshield`,()=>this.#d(e),this.sdk.logger),this.#h(i,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=null,t=await Gn(this.sdk.storage,this.address,this.sdk.logger);for(let n of t){let t=await this.#f(n);if(t===`open`)return n;t===`settled`?await this.#p(`getPendingUnshield`,n):e??=n}return e}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t,n){this.#r(`unwrap`);let r=await w(`unwrap`,this.sdk.signer,this.sdk.provider),i=q(r.address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i},{operation:t}),[s]=a;if(!s)throw new H(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:y(this.address,i,i,s,o),beforeReceipt:n});return{...c,unwrapRequestId:this.#l(c.receipt.logs)}}async unwrapAll(){return this.#s()}async#s(e){this.#r(`unwrapAll`);let t=await w(`unwrapAll`,this.sdk.signer,this.sdk.provider),n=q(t.address),r=await this.readConfidentialBalanceOf(n);if(F(r))throw new U(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:xe(this.address,n,n,r),beforeReceipt:e});return{...i,unwrapRequestId:this.#l(i.receipt.logs)}}async finalizeUnwrap(e){return this.#c(e,`finalize-unwrap`)}async#c(e,t){this.#r(`finalizeUnwrap`),await S(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let{value:n,decryptionProof:r}=await at(this.sdk.relayer,e,{operation:t});return this.submitTransaction({operation:`finalizeUnwrap`,config:Te(this.address,e,n,r)})}#l(e){let t=Jn(e,this.address);if(t===void 0)throw new b(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t}async#u(e){try{return await this.sdk.provider.readContract(Ce(this.address,e))===$t?`settled`:`open`}catch{return`unknown`}}#d(e){return Kn(this.sdk.storage,this.address,e,this.sdk.logger)}async#f(e){let t;try{t=await Mn(this.sdk.provider,e)}catch{return`unknown`}let n=Yn(t,this.address);return typeof n==`string`?n:this.#u(n.unwrapRequestId)}async#p(e,t){await _(`${e}: clearPendingUnshield`,()=>qn(this.sdk.storage,this.address,t,this.sdk.logger),this.sdk.logger)}async#m(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(me(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#h(e,t,n,r,i){this.emit({type:h.UnshieldPhase1Submitted,txHash:t,operationId:n}),this.emit({type:h.UnshieldPhase2Started,operationId:n}),_(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#c(e,i)}catch(n){throw Bt(n)||n instanceof b&&await this.#u(e)===`settled`?(await this.#p(`unshield`,t),new Vt(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:h.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),_(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#p(`unshield`,t),a}async#g(e,t,n){this.#r(`approveUnderlying`);let r=await this.#m(),i=await w(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=q(i.address),o=await this.sdk.provider.readContract(x(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:C(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:C(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};const Zn=J.union([J.bigint(),J.boolean(),a]),Qn=J.array(J.string());var $n=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=Zn.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=q(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${q(e)}:${q(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Qn.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function er(e,t){let n=tr(e,t);if(!n)throw new U(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function tr(e,t){let n=i(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const nr=e=>new Promise(t=>setTimeout(t,e));var rr=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=q(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=q(t),o=q(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:q(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:i?.operation},s))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof Je))throw t;await nr(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0,operation:o}){let s=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:q(e.contractAddress)}));if(s.length===0)return{items:s};let c=q(r);try{let e=await this.delegatedDecryptValues(s.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,c,{waitForPropagation:a,operation:o});for(let t of s)this.#d(t,e);return{items:s}}catch(e){if(It(e))throw e;if(s.length===1){let[n=this.#p()]=s;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:q(t)}),{items:s}}}let l=!1,u;if(await ut(s.map(e=>async()=>{if(!l)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,c,{waitForPropagation:!1,operation:o});this.#d(e,r)}catch(n){if(It(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:q(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=er(e,t),a;try{a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey,tkmsVersion:e.keypair.tkmsVersion})}catch(e){throw e instanceof Error&&xt(e.message)&&await this.#t.evictTransportKeyPair(),e}let o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n,r={spent:!1}){if(e.length===0)return{};let i=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:q(e.contractAddress)})),a={},o=[];for(let e of i)F(e.encryptedValue)?a[e.encryptedValue]=0n:o.push(e);if(o.length===0)return a;let s=Array.from(new Set(i.map(e=>e.contractAddress))),c=Array.from(new Set(o.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(c)}catch(e){throw Tt(e)?this.#u(e,`the delegation pre-check`):e}let l=[];for(let e of o){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?l.push(e):a[e.encryptedValue]=n}if(l.length===0)return a;let u=await this.#t.grantPermit(s,t.delegator),d=/* @__PURE__ */ new Map;for(let e of l){let t=d.get(e.contractAddress);t?t.push(e.encryptedValue):d.set(e.contractAddress,[e.encryptedValue])}let f=[];for(let[e,t]of d)for(let n of ht(t))f.push({contractAddress:e,encryptedValues:n});let p=Date.now(),m=l.map(e=>e.encryptedValue);try{this.#i({type:h.DecryptStart,encryptedValues:m});try{await this.#c(t,u,f,a,n)}catch(e){if(!(e instanceof W)||r.spent)throw e;let i=u.permissions.map(e=>e.serializedPermit.signature);r.spent=!0;try{u=await this.#t.recoverPermits(s,t.delegator,i)}catch(e){throw e instanceof Pt?new W(`The permit's KMS context has been revoked on-chain and the automatic re-grant failed, so the decrypt cannot proceed. Establish a new permit for this scope and retry.`,{cause:e}):e}await this.#c(t,u,f.filter(({encryptedValues:e})=>e.some(e=>a[e]===void 0)),a,n)}let e={};for(let t of m){let n=a[t];n!==void 0&&(e[t]=n)}return this.#i({type:h.DecryptEnd,durationMs:Date.now()-p,encryptedValues:m,result:e}),a}catch(e){let n=e instanceof B&&e.cause instanceof Error?e.cause:e;throw this.#i({type:h.DecryptError,error:z(n),durationMs:Date.now()-p,encryptedValues:m}),D(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await ut(n.map(({contractAddress:n,encryptedValues:a})=>async()=>{try{await this.#l(e,t,n,a,r,i);return}catch(e){return e}}),5)).filter(e=>e!==void 0);if(a.length>0)throw a.find(e=>e instanceof W)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw D(t,e.errorMessage,{isDelegated:e.delegator!==void 0,contractAddress:n,account:e.delegator??e.requesterAddress})}for(let t=0;t<r.length;t++){let a=r[t],s=o[t]?.value;a!==void 0&&s!==void 0&&(i[a]=s,await this.#e.set(e.requesterAddress,n,a,s))}let s=r.filter(e=>i[e]===void 0);if(s.length>0)throw new U(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new U(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new Lt(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:vt(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new U(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`):e.value=n}#f(e,t,n){return e instanceof B?e:D(e,t,n)}#p(){throw new U(`Batch delegated decryption invariant failed: missing item`)}async#m(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};const ir={AlreadyDelegatedOrRevokedInSameBlock:e=>new et(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new rt(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new it(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new T(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new E(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new $e(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new M(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new Xe(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new N(`Cannot revoke: no active delegation exists.`,{cause:e})};function ar(e){return Object.hasOwn(ir,e)}function or(e,t){let n=Rt(e);if(n&&ar(n))return ir[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(ir))if(r.includes(e))return n(t);return null}var sr=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new M(`Expiration date must be at least 1 hour in the future`);let a=q(t),o=q(n),s=q(r);if(o===s)throw new T(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===q(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new $e(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new E(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):X,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new Xe(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==q(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:an(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=q(t),a=q(n),o=q(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new N(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:on(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=q(e.contractAddress)===Z,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:Z})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:Z});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==X}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===X?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(sn(r,q(t),q(n),q(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await ft({operation:e,signer:t,provider:this.#t,config:r,emit:e=>this.#n(e,n),logger:this.#r})}catch(e){throw this.#c(e),e}}#c(e){if(!(e instanceof b))return;let t=or(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=/* @__PURE__ */ new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof N||t instanceof P){let n=q(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=q(e),i=q(t),a=q(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new N(`No active delegation from ${i} to ${a} for ${r}`):new P(`Delegation from ${i} to ${a} for ${r} has expired`)}},cr=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=q(e.contractAddress);try{this.#t({type:h.EncryptStart},r);let i=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:h.EncryptEnd,durationMs:Date.now()-n},r),i}catch(e){throw this.#t({type:h.EncryptError,error:z(e),durationMs:Date.now()-n},r),tn(e,`Encryption failed`)}}},lr=class{#e;#t;#n;#r;#i;#a;#o=/* @__PURE__ */ new Set;#s;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.clearCredentialsOnWalletChange,this.#a=e.logger,this.#e&&(this.#s=this.#e.walletAccount.subscribe(e=>{this.#c(e).catch(e=>{this.#a.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#o.add(e),()=>{this.#o.delete(e)}}dispose(){this.#s?.(),this.#s=void 0,this.#o.clear()}async#c(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await _(`switch relayer chain`,()=>this.#t.switchChain(r),this.#a),this.#i&&await this.#l(t,n),await Promise.all(Array.from(this.#o,t=>_(`wallet account listener`,()=>t(e),this.#a)))}async#l(e,t){let n=this.#r;n&&await _(`credential wallet account change`,()=>n.handleWalletAccountChange(e,t),this.#a),e&&await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e.address),this.#a)}};const ur=J.object({kind:J.literal(`ConfidentialTransfer`),from:a,token:a,to:a,amount:J.bigint()}),dr=J.object({kind:J.literal(`ConfidentialTransferFrom`),from:a,token:a,owner:a,to:a,amount:J.bigint()}),fr=J.object({kind:J.literal(`SetOperator`),from:a,token:a,operator:a,until:u}),pr=J.object({kind:J.literal(`Unwrap`),from:a,token:a,to:a,amount:J.bigint()}),mr=J.object({kind:J.literal(`UnwrapAll`),from:a,token:a,to:a}),hr=J.object({kind:J.literal(`FinalizeUnwrap`),from:a,wrapper:a,unwrapRequestIdOrAmount:p}),gr=J.object({kind:J.literal(`ApproveUnderlying`),from:a,underlying:a,spender:a,amount:J.bigint()}),_r=J.object({kind:J.literal(`Wrap`),from:a,wrapper:a,to:a,amount:J.bigint()}),vr=p.check(J.refine(e=>e===`0x`||Qt(e)===20,`TransferAndCall.recipientData must be "0x" (self-shield to the sender) or a raw 20-byte address, not a 32-byte ABI-encoded value the wrapper would truncate to a garbage address`)),yr=J.object({kind:J.literal(`TransferAndCall`),from:a,underlying:a,wrapper:a,amount:J.bigint(),recipientData:J.optional(vr)}),br=J.object({kind:J.literal(`DelegateDecryption`),from:a,contractAddress:a,delegateAddress:a,expirationDate:J.optional(J.date())}),xr=J.object({kind:J.literal(`RevokeDelegation`),from:a,contractAddress:a,delegateAddress:a});J.discriminatedUnion(`kind`,[ur,dr,fr,pr,mr,hr,gr,_r,yr,br,xr]);const Sr=J.strictObject({maxFeePerGas:J.bigint(),maxPriorityFeePerGas:J.bigint()}),Cr=J.object({nonce:J.optional(J.int().check(J.nonnegative())),gasLimit:J.optional(J.bigint()),fees:J.optional(Sr)}),wr=J.object({address:a,abi:J.array(J.unknown()),functionName:J.string(),args:J.array(J.unknown()),value:J.optional(J.bigint()),gas:J.optional(J.bigint())}),Tr=J.extend(Cr,{from:a,calldata:wr});var Er=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=K(Cr,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new V(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i={calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees},a=K(Tr,i),o=await this.#e.prepareTransaction(a).catch(t=>{throw mt(t,`prepare ${e.kind}`)??t}),s=Zt(o),c=Yt({abi:a.calldata.abi,functionName:a.calldata.functionName,args:a.calldata.args});if(s.chainId!==r||!s.to||!Xt(s.to,a.calldata.address)||s.data?.toLowerCase()!==c.toLowerCase()||(s.value??0n)!==(a.calldata.value??0n))throw new V(`Offline.prepare: the provider returned a transaction that does not match the prepared ${e.kind} call on chain ${r}.`);return{kind:e.kind,unsignedTx:o,from:a.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new V(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=K(ur,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer`}),r=t[0];if(!r)throw new H(`Encryption returned no handles for ConfidentialTransfer`);return we(e.token,e.to,r,n)}async#a(e){e=K(dr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-confidential-transfer-from`}),r=t[0];if(!r)throw new H(`Encryption returned no handles for ConfidentialTransferFrom`);return We(e.token,e.owner,e.to,r,n)}#o(e){return e=K(fr,e),Ie(e.token,e.operator,e.until)}async#s(e){e=K(pr,e);let{encryptedValues:t,inputProof:n}=await this.#n.encryptValues({values:[{value:e.amount,type:`euint64`}],contractAddress:e.token,userAddress:e.from},{operation:`offline-unwrap`}),r=t[0];if(!r)throw new H(`Encryption returned no handles for Unwrap`);return y(e.token,e.from,e.to,r,n)}async#c(e){e=K(mr,e);let t=await this.#e.readContract(Ke(e.token,e.from));return xe(e.token,e.from,e.to,t)}async#l(e){e=K(hr,e);let{value:t,decryptionProof:n}=await at(this.#t.relayer,e.unwrapRequestIdOrAmount,{operation:`offline-finalize-unwrap`});return Te(e.wrapper,e.unwrapRequestIdOrAmount,t,n)}#u(e){return e=K(gr,e),C(e.underlying,e.spender,e.amount)}#d(e){return e=K(_r,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=K(yr,e),rn(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=K(br,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new M(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new T(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new E(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):X;return an(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=K(xr,e),on(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Dr(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new V(`transportKeyPairDerivationSecret was passed as undefined, which usually means the environment variable it reads is unset (e.g. process.env.ZAMA_DERIVATION_SECRET). Supply the secret, or omit the option entirely to persist transport key pairs in cleartext on purpose.`)}function Or(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new V(`transportKeyPairDerivationSecret is supported in headless environments only (CLI tools, servers, agents). Remove the option: an environment with a platform keystore, or one that ships a bundle, must delegate at-rest security of the transport key pair to the storage backend.`)}function kr(e){if(e===void 0)return;let t=K(l,e);return new ne(typeof t==`string`?t:new Uint8Array(t))}var Ar=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Dr(t),Or(t.transportKeyPairDerivationSecret);let n=kr(t.transportKeyPairDerivationSecret);this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new $n(e.storage,this.#i),this.#u=new sr({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let r={};for(let t of e.chains)t.registryAddress&&(r[t.id]=t.registryAddress);this.registry=new f({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new ee({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,derivationSecret:n,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),e.signer&&(this.#c=new rr({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new cr({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new lr({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new Er({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new En({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new Dn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new On({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new kn(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}get chains(){return this.#e.chains}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new f({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,G(t,`encrypt`))}createToken(e){return new L(this,e)}createWrappedToken(e){return new Xn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{Tn as ACL_TOPICS,it as AclPausedError,$ as AclTopics,dt as BalanceCheckUnavailableError,te as BaseSigner,Be as ChainMismatchError,An as ChromeSessionStorage,V as ConfigurationError,On as Decryption,U as DecryptionFailedError,n as DefaultRegistryAddresses,rt as DelegationContractIsSelfError,et as DelegationCooldownError,$e as DelegationDelegateCannotBeWildcardError,E as DelegationDelegateEqualsContractError,M as DelegationExpirationTooSoonError,P as DelegationExpiredError,Xe as DelegationExpiryUnchangedError,N as DelegationNotFoundError,Je as DelegationNotPropagatedError,T as DelegationSelfNotAllowedError,Dn as Delegations,Ae as ERC1363_INTERFACE_ID,R as ERC20ReadFailedError,ze as ERC7984_INTERFACE_ID,Ve as ERC7984_WRAPPER_INTERFACE_ID,Et as EncryptOffloadUnavailableError,H as EncryptionFailedError,be as HcuBlockLimitExceededError,Oe as HcuTransactionLimitExceededError,t as IndexedDBStorage,ct as InsufficientAllowanceError,lt as InsufficientConfidentialBalanceError,I as InsufficientERC20BalanceError,At as InvalidTransportKeyPairError,Dt as KeyWrappingError,X as MAX_UINT64,s as MemoryStorage,d as MutableWalletAccountStore,Mt as NoCiphertextError,st as NotEntitledError,kn as Offline,En as Permits,Nt as PreparedPermitChainMismatchError,Ot as PreparedPermitExpiredError,St as RelayerRequestFailedError,W as RevokedKmsContextError,Lt as RpcRateLimitError,ye as SignerNotConfiguredError,Ee as SignerRequiredError,Pt as SigningFailedError,jt as SigningRejectedError,vn as TOKEN_TOPICS,L as Token,Q as Topics,b as TransactionRevertedError,Ft as TransportKeyPairChangedError,kt as TransportKeyPairExpiredError,Vt as UnshieldAlreadyFinalizedError,zt as UnwrapNotMinedError,nt as VaultBatchNotDispatchedError,ot as VaultBatcherPausedError,Ze as VaultBatcherReadFailedError,Qe as VaultJoinUnconfirmedError,Z as WILDCARD_CONTRACT,De as WalletAccountNotReadyError,ve as WalletNotConnectedError,Xn as WrappedToken,f as WrappersRegistry,pt as ZERO_ENCRYPTED_VALUE,B as ZamaError,bt as ZamaErrorCode,Ar as ZamaSDK,h as ZamaSDKEvents,x as allowanceContract,fe as anvil,C as approveContract,Re as balanceOfContract,ce as bscTestnet,ue as chains,jn as chromeSessionStorage,e as cleartext,Ke as confidentialBalanceOfContract,je as confidentialTotalSupplyContract,Ge as confidentialTransferAndCallContract,we as confidentialTransferContract,he as confidentialTransferFromAndCallContract,We as confidentialTransferFromContract,ln as createConfig,m as createWalletAccountStore,Pe as decimalsContract,xn as decodeAclEvent,Sn as decodeAclEvents,un as decodeConfidentialTransfer,yn as decodeDelegatedForUserDecryption,mn as decodeOnChainEvent,hn as decodeOnChainEvents,bn as decodeRevokedDelegationForUserDecryption,pn as decodeUnwrapFinalized,fn as decodeUnwrapRequested,dn as decodeWrap,an as delegateForUserDecryptionContract,Te as finalizeUnwrapContract,Cn as findDelegatedForUserDecryption,wn as findRevokedDelegationForUserDecryption,gn as findUnwrapRequested,_n as findWrap,Jt as getConfidentialTokenAddressContract,sn as getDelegationExpiryContract,Wt as getTokenAddressContract,Kt as getTokenPairContract,Ut as getTokenPairsContract,Ht as getTokenPairsLengthContract,Gt as getTokenPairsSliceContract,oe as hardhat,ie as hoodi,re as indexedDBStorage,_e as inferredTotalSupplyContract,Me as isConfidentialTokenContract,qt as isConfidentialTokenValidContract,Le as isConfidentialWrapperContract,F as isEncryptedValueZero,cn as isHandleDelegatedContract,ge as isOperatorContract,_t as isRetryable,le as mainnet,en as matchZamaError,o as memoryStorage,ke as nameContract,r as parsePreparedPermit,de as polygon,ae as polygonAmoy,Se as rateContract,Ct as retryAfterSeconds,on as revokeDelegationContract,se as sepolia,Ie as setOperatorContract,Ne as supportsInterfaceContract,Ue as symbolContract,rn as transferAndCallContract,me as underlyingContract,Fe as unwrapAmountContract,y as unwrapContract,xe as unwrapFromBalanceContract,Ce as unwrapRequesterContract,g as wrapContract,pe as zenithTrexTestnet};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as e,i as t,r as n}from"../relayer-Cki3j_Ba.js";import{t as r}from"../fatal-batch-CI0ESPnd.js";import{n as i}from"../fhevm-relayer-
|
|
1
|
+
import{b as e,i as t,r as n}from"../relayer-Cki3j_Ba.js";import{t as r}from"../fatal-batch-CI0ESPnd.js";import{n as i}from"../fhevm-relayer-BI-D7Wcy.js";import{t as a}from"../typed-data-eAgGr9V-.js";const o=r;function s(r,i,a){let s=o[r],c=s?new s(i):new n(r,i,r===t.RelayerRequestFailed?{retryable:a.retryable}:void 0);return c.retryable&&e(a.retryAfter)?Object.assign(c,{retryAfter:a.retryAfter}):c}function c(e,t){return e.onWalletAccountChange(t)}export{s as reviveZamaError,c as subscribeWalletAccountChanges,i as toFhevmAuth,a as toViemTypedData};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/esm/node/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"../fhevm-relayer-
|
|
1
|
+
import{t as e}from"../fhevm-relayer-BI-D7Wcy.js";import{t}from"../telemetry-PsdiUPnw.js";import{t as n}from"../cleartext-Cmrc_kxS.js";import{a as r,c as i,i as a,l as o,n as s,o as c,r as l,s as u,t as d,u as f}from"../configs-9EL-DJHq.js";import{AsyncLocalStorage as p}from"node:async_hooks";function m(n){return{type:`node`,createRelayer:(r,i,a)=>{let o=t(globalThis.process?.env?.ZAMA_SDK_TELEMETRY)??a?.mode;return new e({chain:r,options:n,logger:i,telemetry:a&&o!==void 0&&o!==`off`?{state:a,runtime:`node`,mode:o}:void 0})}}}var h=class{#e=new p;run(e){return this.#e.run(/* @__PURE__ */ new Map,e)}async get(e){return this.#e.getStore()?.get(e)??null}async set(e,t){this.#e.getStore()?.set(e,t)}async delete(e){this.#e.getStore()?.delete(e)}};const g=new h;export{h as AsyncLocalMapStorage,d as anvil,g as asyncLocalStorage,s as bscTestnet,l as chains,n as cleartext,a as hardhat,r as hoodi,c as mainnet,m as node,u as polygon,i as polygonAmoy,o as sepolia,f as zenithTrexTestnet};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./relayer-Cki3j_Ba.js";import{r as t}from"./configs-9EL-DJHq.js";function n(e){let n=t[e.id];return e.keyVerification!==void 0||n===void 0||n.aclContractAddress.toLowerCase()!==e.aclContractAddress.toLowerCase()?e:{...e,keyVerification:n.keyVerification}}function r(e){let t=e.keyVerification;return t!==void 0&&`chain`in t?t.chain:void 0}function i(t){let n=r(t)??t;if(!(n.keyVerification!==void 0&&`contract`in n.keyVerification))throw new e(`Chain ${t.id} has no KMSGeneration contract to check the FHE public key and CRS against. Set keyVerification on its FheChain: { contract } on an Ethereum host chain, or { chain } with the Ethereum chain that holds it on other host chains.`)}let a,o=!1;function s(e){a=Object.freeze({wasmAssetLoadMode:e.wasmAssetLoadMode,moduleVersions:e.moduleVersions,singleThread:e.singleThread,numberOfThreads:e.numberOfThreads,auth:e.auth}),o=e.locateFile!==void 0}function c(){return a}function l(){return o}function u(e,t){let{layer:n,daemonClient:r}=e.state,i=Object.entries({version:`3.9.1-beta.
|
|
2
|
-
//# sourceMappingURL=telemetry-
|
|
1
|
+
import{t as e}from"./relayer-Cki3j_Ba.js";import{r as t}from"./configs-9EL-DJHq.js";function n(e){let n=t[e.id];return e.keyVerification!==void 0||n===void 0||n.aclContractAddress.toLowerCase()!==e.aclContractAddress.toLowerCase()?e:{...e,keyVerification:n.keyVerification}}function r(e){let t=e.keyVerification;return t!==void 0&&`chain`in t?t.chain:void 0}function i(t){let n=r(t)??t;if(!(n.keyVerification!==void 0&&`contract`in n.keyVerification))throw new e(`Chain ${t.id} has no KMSGeneration contract to check the FHE public key and CRS against. Set keyVerification on its FheChain: { contract } on an Ethereum host chain, or { chain } with the Ethereum chain that holds it on other host chains.`)}let a,o=!1;function s(e){a=Object.freeze({wasmAssetLoadMode:e.wasmAssetLoadMode,moduleVersions:e.moduleVersions,singleThread:e.singleThread,numberOfThreads:e.numberOfThreads,auth:e.auth}),o=e.locateFile!==void 0}function c(){return a}function l(){return o}function u(e,t){let{layer:n,daemonClient:r}=e.state,i=Object.entries({version:`3.9.1-beta.3`,layer:n,...r===void 0?{runtime:e.runtime}:{runtime:`daemon`,client:r},...t!==void 0&&{operation:t}}),a=e=>Object.fromEntries(i.map(([t,n])=>[`${e}${t}`,n]));return e.mode===`query`?{query:a(`zama_sdk_`)}:{headers:a(`x-zama-sdk-`)}}function d(e,t){return Object.assign({},e,{operation:e?.operation??t})}function f(e){if(typeof e==`boolean`)return e?`header`:`off`;let t=typeof e==`string`?e.trim().toLowerCase():void 0;return t===`0`||t===`false`?`off`:t===`header`||t===`query`||t===`off`?t:void 0}export{l as a,r as c,c as i,n as l,u as n,s as o,d as r,i as s,f as t};
|
|
2
|
+
//# sourceMappingURL=telemetry-PsdiUPnw.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"telemetry-
|
|
1
|
+
{"version":3,"file":"telemetry-PsdiUPnw.js","names":["packageJson.version","ConfigurationError","chains","withPresetKeyVerification","preset","chain","keyVerificationChain","keyVerification","assertKeyVerification","holder","appliedWireRuntime","appliedLocateFile","recordAppliedRuntimeConfig","runtime","getAppliedWireRuntime","hasAppliedLocateFile","telemetryRequestOptions","telemetry","fields","daemonClient","operation","prefixed","name","value","prefix","withOperation","options","parseTelemetryMode","mode"],"sources":["../../src/chains/key-verification.ts","../../src/relayer/applied-runtime.ts","../../package.json","../../src/version.ts","../../src/telemetry.ts"],"sourcesContent":["import { ConfigurationError } from \"../errors\";\nimport { chains } from \"./configs\";\nimport type { FheChain } from \"./types\";\n\n/** A chain with a preset's id and ACL is that preset's deployment, so it inherits its `keyVerification`. */\nexport function withPresetKeyVerification(chain: FheChain): FheChain {\n const preset: FheChain | undefined = chains[chain.id];\n if (\n chain.keyVerification !== undefined ||\n preset === undefined ||\n preset.aclContractAddress.toLowerCase() !== chain.aclContractAddress.toLowerCase()\n ) {\n return chain;\n }\n return { ...chain, keyVerification: preset.keyVerification };\n}\n\nexport function keyVerificationChain(chain: FheChain): FheChain | undefined {\n const keyVerification = chain.keyVerification;\n return keyVerification !== undefined && \"chain\" in keyVerification\n ? keyVerification.chain\n : undefined;\n}\n\n/** Throws `ConfigurationError` when a non-cleartext `chain` has no `KMSGeneration` contract to verify its FHE key against. */\nexport function assertKeyVerification(chain: FheChain): void {\n const holder = keyVerificationChain(chain) ?? chain;\n if (holder.keyVerification !== undefined && \"contract\" in holder.keyVerification) {\n return;\n }\n throw new ConfigurationError(\n `Chain ${chain.id} has no KMSGeneration contract to check the FHE public key and CRS against. ` +\n `Set keyVerification on its FheChain: { contract } on an Ethereum host chain, or { chain } with ` +\n `the Ethereum chain that holds it on other host chains.`,\n );\n}\n","import type { FhevmRuntimeConfig, WireRuntimeConfig } from \"./types\";\n\n/**\n * Mirror of the runtime config this package applied via the upstream\n * `setFhevmRuntimeConfig`, which is itself a process-wide one-shot. An encrypt\n * worker realm replicates it, since the upstream lock offers no getter.\n */\nlet appliedWireRuntime: WireRuntimeConfig | undefined;\n\n/** `locateFile` is a function, so it stays off the wire and is only flagged here. */\nlet appliedLocateFile = false;\n\n/** Projects the applied runtime onto the fields a worker realm replicates. */\nexport function recordAppliedRuntimeConfig(runtime: FhevmRuntimeConfig): void {\n appliedWireRuntime = Object.freeze({\n wasmAssetLoadMode: runtime.wasmAssetLoadMode,\n moduleVersions: runtime.moduleVersions,\n singleThread: runtime.singleThread,\n numberOfThreads: runtime.numberOfThreads,\n auth: runtime.auth,\n });\n appliedLocateFile = runtime.locateFile !== undefined;\n}\n\n/** `undefined` when the upstream lock was set outside this package. */\nexport function getAppliedWireRuntime(): WireRuntimeConfig | undefined {\n return appliedWireRuntime;\n}\n\nexport function hasAppliedLocateFile(): boolean {\n return appliedLocateFile;\n}\n\n/** @internal */\nexport function resetAppliedRuntimeConfig(): void {\n appliedWireRuntime = undefined;\n appliedLocateFile = false;\n}\n","","import packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const SDK_VERSION: string = packageJson.version;\n","import { SDK_VERSION } from \"./version\";\n\n// No telemetry field may carry a wallet address, encrypted value, amount or identifier.\n\nexport type TelemetryLayer = \"core\" | \"react\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryRuntime = \"web\" | \"node\" | \"daemon\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive renames. */\nexport type TelemetryClient = \"go\" | \"rust\" | \"unknown\";\n\nexport type TelemetryMode = \"header\" | \"query\" | \"off\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive method renames. */\nexport type TelemetryOperation =\n | \"balance-of\"\n | \"decrypt-balance-as\"\n | \"batch-balances-of\"\n | \"batch-decrypt-balances-as\"\n | \"confidential-transfer\"\n | \"confidential-transfer-from\"\n | \"confidential-transfer-and-call\"\n | \"confidential-transfer-from-and-call\"\n | \"unshield\"\n | \"unshield-all\"\n | \"resume-unshield\"\n | \"unwrap\"\n | \"finalize-unwrap\"\n | \"vault-deposit\"\n | \"vault-redeem\"\n | \"vault-join\"\n | \"vault-deposit-of\"\n | \"vault-finalize\"\n | \"encrypt\"\n | \"decrypt-values\"\n | \"delegated-decrypt-values\"\n | \"delegated-batch-decrypt-values\"\n | \"decrypt-public-values\"\n | \"offline-confidential-transfer\"\n | \"offline-confidential-transfer-from\"\n | \"offline-unwrap\"\n | \"offline-finalize-unwrap\";\n\n/**\n * Shared by every relayer of a config; `layer` and `daemonClient` are set on it\n * after the relayers exist.\n *\n * @internal\n */\nexport interface TelemetryState {\n layer: TelemetryLayer;\n /** Set only by the daemon; overrides the reported runtime with `daemon`. */\n daemonClient?: TelemetryClient;\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport interface RelayerTelemetry {\n readonly state: TelemetryState;\n readonly runtime: Exclude<TelemetryRuntime, \"daemon\">;\n /** The config's `mode`, unless `ZAMA_SDK_TELEMETRY` overrode it on Node. */\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport function telemetryRequestOptions(\n telemetry: RelayerTelemetry,\n operation: TelemetryOperation | undefined,\n): { headers?: Record<string, string>; query?: Record<string, string> } {\n const { layer, daemonClient } = telemetry.state;\n const fields = Object.entries({\n version: SDK_VERSION,\n layer,\n ...(daemonClient === undefined\n ? { runtime: telemetry.runtime }\n : { runtime: \"daemon\" satisfies TelemetryRuntime, client: daemonClient }),\n ...(operation !== undefined && { operation }),\n });\n const prefixed = (prefix: string) =>\n Object.fromEntries(fields.map(([name, value]) => [`${prefix}${name}`, value]));\n return telemetry.mode === \"query\"\n ? { query: prefixed(\"zama_sdk_\") }\n : { headers: prefixed(\"x-zama-sdk-\") };\n}\n\n/** `options` labelled with `operation`, unless the caller already labelled it. */\nexport function withOperation<T extends { readonly operation?: TelemetryOperation }>(\n options: T | undefined,\n operation: TelemetryOperation,\n): Partial<T> & { readonly operation: TelemetryOperation } {\n return Object.assign({}, options, { operation: options?.operation ?? operation });\n}\n\nexport function parseTelemetryMode(value: string | boolean | undefined): TelemetryMode | undefined {\n if (typeof value === \"boolean\") {\n return value ? \"header\" : \"off\";\n }\n // JavaScript callers can pass anything; only a string can name a mode.\n const mode = typeof value === \"string\" ? value.trim().toLowerCase() : undefined;\n // `0` and `false` predate the named modes and still mean off.\n if (mode === \"0\" || mode === \"false\") {\n return \"off\";\n }\n return mode === \"header\" || mode === \"query\" || mode === \"off\" ? mode : undefined;\n}\n"],"mappings":"A,oFAKA,SAAgBG,EAA0B,EAA2B,CACnE,IAAMC,EAA+BF,EAAOG,EAAM,IAQlD,OANEA,EAAM,kBAAoB,IAAA,IAC1BD,IAAW,IAAA,IACXA,EAAO,mBAAmB,YAAY,IAAMC,EAAM,mBAAmB,YAAY,EAE1EA,EAEF,CAAE,GAAGA,EAAO,gBAAiBD,EAAO,eAAgB,CAC7D,CAEA,SAAgBE,EAAqB,EAAuC,CAC1E,IAAMC,EAAkBF,EAAM,gBAC9B,OAAOE,IAAoB,IAAA,IAAa,UAAWA,EAC/CA,EAAgB,MAChB,IAAA,EACN,CAGA,SAAgBC,EAAsB,EAAuB,CAC3D,IAAMC,EAASH,EAAqBD,CAAK,GAAKA,EAC9C,GAAI,IAAO,kBAAoB,IAAA,IAAa,aAAcI,EAAO,iBAGjE,MAAM,IAAIR,EACR,SAASI,EAAM,GAAG,kOAGpB,CACF,CC5BA,IAAIK,EAGAC,EAAoB,GAGxB,SAAgBC,EAA2B,EAAmC,CAC5E,EAAqB,OAAO,OAAO,CACjC,kBAAmBC,EAAQ,kBAC3B,eAAgBA,EAAQ,eACxB,aAAcA,EAAQ,aACtB,gBAAiBA,EAAQ,gBACzB,KAAMA,EAAQ,IAChB,CAAC,EACD,EAAoBA,EAAQ,aAAe,IAAA,EAC7C,CAGA,SAAgBC,GAAuD,CACrE,OAAOJ,CACT,CAEA,SAAgBK,GAAgC,CAC9C,OAAOJ,CACT,CGiCA,SAAgBK,EACd,EACA,EACsE,CACtE,GAAM,CAAE,QAAO,gBAAiBC,EAAU,MACpCC,EAAS,OAAO,QAAQ,CAC5B,QAAS,eACT,QACA,GAAIC,IAAiB,IAAA,GACjB,CAAE,QAASF,EAAU,OAAQ,EAC7B,CAAE,QAAS,SAAqC,OAAQE,CAAa,EACzE,GAAIC,IAAc,IAAA,IAAa,CAAE,WAAU,CAC7C,CAAC,EACKC,EAAY,GAChB,OAAO,YAAYH,EAAO,KAAK,CAACI,EAAMC,KAAW,CAAC,GAAGC,IAASF,IAAQC,CAAK,CAAC,CAAC,EAC/E,OAAON,EAAU,OAAS,QACtB,CAAE,MAAOI,EAAS,WAAW,CAAE,EAC/B,CAAE,QAASA,EAAS,aAAa,CAAE,CACzC,CAGA,SAAgBI,EACd,EACA,EACyD,CACzD,OAAO,OAAO,OAAO,CAAC,EAAGC,EAAS,CAAE,UAAWA,GAAS,WAAaN,CAAU,CAAC,CAClF,CAEA,SAAgBO,EAAmB,EAAgE,CACjG,GAAI,OAAOJ,GAAU,UACnB,OAAOA,EAAQ,SAAW,MAG5B,IAAMK,EAAO,OAAOL,GAAU,SAAWA,EAAM,KAAK,CAAC,CAAC,YAAY,EAAI,IAAA,GAKtE,OAHIK,IAAS,KAAOA,IAAS,QACpB,MAEFA,IAAS,UAAYA,IAAS,SAAWA,IAAS,MAAQA,EAAO,IAAA,EAC1E,C"}
|
package/dist/esm/viem/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as e,B as t,F as n,G as r,M as i,N as a,S as o,T as s,X as c,d as l,k as u,r as d,y as f}from"../alignment-D1cVCzw8.js";import{i as p,t as m}from"../base-signer-
|
|
1
|
+
import{A as e,B as t,F as n,G as r,M as i,N as a,S as o,T as s,X as c,d as l,k as u,r as d,y as f}from"../alignment-D1cVCzw8.js";import{i as p,t as m}from"../base-signer-D-GNuCyg.js";import{t as h}from"../eip1193-subscribe-DxAQh8dY.js";import{t as g}from"../typed-data-eAgGr9V-.js";import{a as _,i as v,n as y,o as b,r as x,s as S,t as C}from"../wrappers-registry-Cm3JJeqx.js";import{TransactionReceiptNotFoundError as w,encodeFunctionData as T,getAddress as E,serializeTransaction as D}from"viem";var O=class{#e;constructor(e){this.#e=e.publicClient}async getChainId(){return this.#e.getChainId()}async readContract(e){let{chainId:t,...n}=e;return await d(`ViemProvider`,t,()=>this.getChainId()),this.#e.readContract(n)}async multicall(e){return await d(`ViemProvider`,e.chainId,()=>this.getChainId()),await this.#e.multicall({contracts:e.calls.map(({chainId:e,...t})=>t),allowFailure:!1,deployless:this.#e.chain?.contracts?.multicall3===void 0})}async waitForTransactionReceipt(e){return this.#e.waitForTransactionReceipt({hash:e})}async getTransactionReceipt(e){try{return await this.#e.getTransactionReceipt({hash:e})}catch(e){if(e instanceof w)return null;throw e}}async getBlockTimestamp(e){return await d(`ViemProvider`,e,()=>this.getChainId()),(await this.#e.getBlock()).timestamp}async prepareTransaction(e){let{from:t,calldata:n}=e,r=T({abi:n.abi,functionName:n.functionName,args:n.args}),i=this.#e.getChainId(),a=e.nonce===void 0?this.#e.getTransactionCount({address:t,blockTag:`pending`}):Promise.resolve(e.nonce),o=e.gasLimit===void 0?n.gas??this.#e.estimateGas({account:t,to:n.address,data:r,value:n.value??0n}).catch(e=>{throw new c(`ViemProvider.prepareTransaction: gas estimation reverted for ${n.functionName} on ${n.address}`,{cause:e})}):Promise.resolve(e.gasLimit),s=e.fees??this.#e.estimateFeesPerGas(),[l,u,d,f]=await Promise.all([i,a,o,s]);return D({type:`eip1559`,chainId:l,nonce:u,to:n.address,data:r,value:n.value??0n,gas:d,maxFeePerGas:f.maxFeePerGas,maxPriorityFeePerGas:f.maxPriorityFeePerGas})}};function k(e){if(e.account&&e.chain)return{address:E(e.account.address),chainId:e.chain.id}}var A=class extends m{#e;#t;#n;constructor(e){super(k(e.walletClient)),this.#e=e.walletClient,this.#t=e.ethereum,this.#n=this.#i()}#r(e){if(!this.#e.account)throw new r(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,...g(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?h({provider:this.#t,getInitialWalletAccount:()=>k(this.#e),onWalletAccountChange:({next:e})=>{this.walletAccount.setSnapshot(e)}}):()=>{}}onDispose(){this.#n()}};function j(e){let t=new A({walletClient:e.walletClient,ethereum:e.ethereum}),n=new O({publicClient:e.publicClient});return p(t,n,e)}function M(e){if(!e.account)throw TypeError(`WalletClient has no account`);return e.account}function N(e,t,n){return e.readContract(f(t,n))}function P(t,n){return t.readContract(e(n))}function F(e,t,n){return e.readContract(l(t,n))}function I(e,t,n,r,i){return e.writeContract({chain:e.chain,account:M(e),...o(t,n,r,i)})}function L(e,t,n,r,a,o){return e.writeContract({chain:e.chain,account:M(e),...i(t,n,r,a,o)})}function R(e,t,n,r,i){return e.writeContract({chain:e.chain,account:M(e),...a(t,n,r,i)})}function z(e,t,n,r,i){return e.writeContract({chain:e.chain,account:M(e),...s(t,n,r,i)})}function B(e,t,n,r){return e.writeContract({chain:e.chain,account:M(e),...u(t,n,r)})}function V(e,t,r,i){return e.writeContract({chain:e.chain,account:M(e),...n(t,r,i)})}function H(e,t){return e.readContract(v(t))}function U(e,t){return e.readContract(_(t))}function W(e,t,n,r){return e.readContract(b(t,n,r))}function G(e,t,n){return e.readContract(x(t,n))}function K(e,t,n){return e.readContract(C(t,n))}function q(e,t,n){return e.readContract(y(t,n))}function J(e,t,n){return e.readContract(S(t,n))}export{m as BaseSigner,O as ViemProvider,A as ViemSigner,t as ZamaSDKEvents,j as createConfig,N as readConfidentialBalanceOfContract,K as readConfidentialTokenAddressContract,J as readIsConfidentialTokenValidContract,F as readSupportsInterfaceContract,q as readTokenAddressContract,G as readTokenPairContract,H as readTokenPairsContract,U as readTokenPairsLengthContract,W as readTokenPairsSliceContract,P as readUnderlyingTokenContract,I as writeConfidentialTransferContract,z as writeFinalizeUnwrapContract,B as writeSetOperatorContract,L as writeUnwrapContract,R as writeUnwrapFromBalanceContract,V as writeWrapContract};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/esm/web/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e,t}from"../fhevm-relayer-
|
|
1
|
+
import{r as e,t}from"../fhevm-relayer-BI-D7Wcy.js";import{t as n}from"../validation-BLmG7UVk.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`,mode:r.mode},offloadEncrypt:c.offloadEncrypt,offloadTimeouts:c.offloadTimeouts,offloadWorker:c.offloadWorker,logger:n})}}export{s as web};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|