@zama-fhe/sdk 3.9.0 → 3.9.1-beta.2
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/base-signer.cjs +1 -1
- package/dist/cjs/base-signer.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/telemetry.cjs +1 -1
- package/dist/cjs/telemetry.cjs.map +1 -1
- package/dist/esm/base-signer-CysprC2L.js +2 -0
- package/dist/esm/base-signer-CysprC2L.js.map +1 -0
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-Bmwhc1xE.js → cleartext-C0DXenyT.js} +2 -2
- package/dist/esm/{cleartext-Bmwhc1xE.js.map → cleartext-C0DXenyT.js.map} +1 -1
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/{fhevm-relayer-ClfJ8FQG.js → fhevm-relayer-DCQ-Oaa1.js} +2 -2
- package/dist/esm/{fhevm-relayer-ClfJ8FQG.js.map → fhevm-relayer-DCQ-Oaa1.js.map} +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/internal/index.js +1 -1
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/{telemetry-B0ypjU_K.js → telemetry-CW2RgPxb.js} +2 -2
- package/dist/esm/{telemetry-B0ypjU_K.js.map → telemetry-CW2RgPxb.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/base-signer-CD9a2hyy.js +0 -2
- package/dist/esm/base-signer-CD9a2hyy.js.map +0 -1
package/dist/esm/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./cleartext-Bmwhc1xE.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-CD9a2hyy.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 xe,N as Se,O as Ce,P as we,S as Te,T as Ee,U as De,W as Oe,X as y,Y as ke,_ as Ae,a as je,b as Me,c as Ne,d as Pe,f as b,h as Fe,j as Ie,k as Le,l as Re,m as x,n as ze,o as Be,p as S,q as Ve,s as He,t as C,u as Ue,v as We,w as Ge,x as Ke,y as qe,z as Je}from"./alignment-D1cVCzw8.js";import{C as w,S as Ye,_ as T,a as Xe,b as Ze,c as E,d as Qe,f as $e,g as et,h as tt,i as D,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 gt,u as L}from"./token-DnriE-3y.js";import{C as R,_ as _t,a as vt,c as yt,g as bt,i as xt,m as St,n as Ct,o as wt,r as z,s as Tt,t as B,y as Et}from"./relayer-Cki3j_Ba.js";import{n as Dt,r as V,t as H}from"./encryption-QHaWnnx-.js";import{a as Ot,c as kt,d as At,i as jt,l as U,n as Mt,o as Nt,s as Pt,t as Ft,u as It}from"./signing-DX-xyved.js";import{n as Lt,r as Rt}from"./fatal-batch-CI0ESPnd.js";import{i as zt,n as Bt,r as Vt,t as Ht}from"./unshield-xO66p_da.js";import{r as W}from"./telemetry-B0ypjU_K.js";import{t as G}from"./validation-BLmG7UVk.js";import{a as Ut,i as Wt,n as Gt,o as Kt,r as qt,s as Jt,t as Yt}from"./wrappers-registry-Cm3JJeqx.js";import{getAddress as K,size as Xt,zeroAddress as Zt}from"viem";import{z as q}from"zod/mini";function Qt(e,t){if(e instanceof z){let n=t[e.code];if(n)return n(e)}return t._?.(e)}function $t(e,t){if(e instanceof z)return e;let n=Tt(e),r=_t(e);return n!==void 0||bt(e)?new Ct(e instanceof Error?e.message:t,n,{cause:e,retryAfter:yt(e),retryable:r||void 0}):new V(t,{cause:e})}const en=[{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 tn(e,t,n,r=`0x`){return{address:e,abi:en,functionName:`transferAndCall`,args:[t,n,r]}}const J=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function nn(e,t,n,r){return{address:e,abi:J,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function rn(e,t,n){return{address:e,abi:J,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function an(e,t,n,r){return{address:e,abi:J,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function on(e,t,n,r,i){return{address:e,abi:J,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const Y=2n**64n-1n,X=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function sn(e){return c(e.signer,e.provider,e)}const Z={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 cn(e){return e.topics[0]!==Z.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:A(e.topics[1]),to:A(e.topics[2]),encryptedAmount:D(e.topics[3])}}function ln(e){return e.topics[0]!==Z.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:A(e.topics[1]),roundedAmount:k(e.data,0),encryptedWrappedAmount:j(e.data,1)}}function un(e){return e.topics[0]!==Z.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:A(e.topics[1]),unwrapRequestId:D(e.topics[2]),encryptedAmount:j(e.data,0)}}function dn(e){return e.topics[0]!==Z.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:A(e.topics[1]),unwrapRequestId:D(e.topics[2]),encryptedAmount:j(e.data,0),cleartextAmount:k(e.data,1)}}function fn(e){return cn(e)??ln(e)??un(e)??dn(e)}function pn(e){let t=[];for(let n of e){let e=fn(n);e&&t.push(e)}return t}function mn(e){for(let t of e){let e=un(t);if(e)return e}return null}function hn(e){for(let t of e){let e=ln(t);if(e)return e}return null}const gn=[Z.ConfidentialTransfer,Z.Wrap,Z.UnwrapRequested,Z.UnwrapFinalized],Q={DelegatedForUserDecryption:O(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:O(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function _n(e){return e.topics[0]!==Q.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:Xe(e.data,0),delegationCounter:k(e.data,1),oldExpirationDate:k(e.data,2),newExpirationDate:k(e.data,3)}}function vn(e){return e.topics[0]!==Q.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:A(e.topics[1]),delegate:A(e.topics[2]),contractAddress:Xe(e.data,0),delegationCounter:k(e.data,1),oldExpirationDate:k(e.data,2)}}function yn(e){return _n(e)??vn(e)}function bn(e){let t=[];for(let n of e){let e=yn(n);e&&t.push(e)}return t}function xn(e){for(let t of e){let e=_n(t);if(e)return e}return null}function Sn(e){for(let t of e){let e=vn(t);if(e)return e}return null}const Cn=[Q.DelegatedForUserDecryption,Q.RevokedDelegationForUserDecryption];var wn=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 ze(`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 ze(`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 C(`revokePermits`,this.#e,this.#t),r=K(n.address);try{await t.revokePermits(e)}finally{await this.#c(r)}}async clear(){let e=this.#o(`clear`),t=await C(`clear`,this.#e,this.#t),n=K(t.address);try{await e.clearCredentials()}finally{await this.#c(n)}}async#c(e){await _(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#o(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#o(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}},Tn=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 C(`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 C(`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)}},En=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 C(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,W(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await C(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,W(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=W(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{Je(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 E(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 C(`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`})}},Dn=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)}},On=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 kn=new On;async function An(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 jn(e){return`zama:pending-unshields:${i(e)}`}function Mn(e){return`zama:pending-unshield:${i(e)}`}function Nn(e){return{version:2,unwrapTxHashes:e}}const Pn=q.union([p,q.pipe(q.object({version:q.literal(1),unwrapTxHash:p}),q.transform(({unwrapTxHash:e})=>e))]),Fn=q.object({version:q.number(),unwrapTxHashes:q.optional(q.unknown())}),In=(e,t)=>e.toLowerCase()===t.toLowerCase();async function Ln(e,t,n){let r=await e.get(t);if(r==null)return{hashes:[],writable:!0};let i=Fn.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 Rn(e,t,n){let r=await Ln(e,jn(t),n),i=Pn.safeParse(await e.get(Mn(t)));return!i.success||!r.writable?{...r,hasLegacy:!1}:{hashes:r.hashes.some(e=>In(e,i.data))?r.hashes:[i.data,...r.hashes],writable:!0,hasLegacy:!0}}async function zn(e,t,n){let r=jn(t);await(n.length===0?e.delete(r):e.set(r,Nn(n)))}const Bn=/* @__PURE__ */ new WeakMap;function Vn(e,t){let n=(Bn.get(e)??Promise.resolve()).then(t);return Bn.set(e,n.then(()=>{},()=>{})),n}function Hn(e,t,n,r){return Vn(e,async()=>{let{hashes:i,writable:a,hasLegacy:o}=await Rn(e,t,n);if(!a)return;let s=r(i);(o||s.length!==i.length)&&await zn(e,t,s),o&&await e.delete(Mn(t))})}async function Un(e,t,n){return(await Vn(e,()=>Rn(e,t,n))).hashes}function Wn(e,t,n,r){return Hn(e,t,r,e=>e.some(e=>In(e,n))?e:[...e,n])}function Gn(e,t,n,r){return Hn(e,t,r,e=>e.filter(e=>!In(e,n)))}function Kn(e,t){let n=K(t);return mn(e.filter(e=>e.address===void 0||K(e.address)===n))?.unwrapRequestId}function qn(e,t){if(!e)return`unknown`;let n=e.status===`reverted`?void 0:Kn(e.logs,t);return n===void 0?`settled`:{unwrapRequestId:n}}var Jn=class extends gt{#e;#t=null;#n=null;#r(e){try{return Je(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(Ue(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#m();return this.sdk.provider.readContract(b(t,K(e),this.address))}async shield(e,t){let n=await C(`shield`,this.sdk.signer,this.sdk.provider),r=await this.isPayable(),i=await this.#m(),a=K(n.address),o;try{o=await this.sdk.provider.readContract(x(i,a))}catch(e){throw e instanceof z?e:new L(`Could not read ERC-20 balance for shield validation (token: ${i})`,{cause:R(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?K(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:tn(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await C(`wrap`,this.sdk.signer,this.sdk.provider),r=await this.#m(),i=K(n.address),a;try{a=await this.sdk.provider.readContract(x(r,i))}catch(e){throw e instanceof z?e:new L(`Could not read ERC-20 balance for wrap validation (token: ${r})`,{cause:R(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(b(r,i,this.address))}catch(e){throw e instanceof z?e:new L(`Could not read ERC-20 allowance for wrap validation (token: ${r})`,{cause:R(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?K(t.to):i;return this.submitTransaction({operation:`wrap`,config:g(this.address,s,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#g(e,r===`max`,n);let i=n?.to?K(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:g(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await C(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#m(),r=K(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(b(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:S(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:S(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 An(this.sdk.provider,e)}catch(e){throw e instanceof z?e:new y(`Failed to get unwrap receipt`,{cause:e})}let r=qn(n,this.address);if(r===`unknown`)throw new Bt(`Unwrap transaction ${e} is not mined, so there is nothing to resume yet`,e);if(r===`settled`)throw await this.#p(`resumeUnshield`,e),new y(`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 Ht(`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 Un(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 C(`unwrap`,this.sdk.signer,this.sdk.provider),i=K(r.address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i},{operation:t}),[s]=a;if(!s)throw new V(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:xe(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 C(`unwrapAll`,this.sdk.signer,this.sdk.provider),n=K(t.address),r=await this.readConfidentialBalanceOf(n);if(F(r))throw new H(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:Se(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 ze(`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:Ee(this.address,e,n,r)})}#l(e){let t=Kn(e,this.address);if(t===void 0)throw new y(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t}async#u(e){try{return await this.sdk.provider.readContract(we(this.address,e))===Zt?`settled`:`open`}catch{return`unknown`}}#d(e){return Wn(this.sdk.storage,this.address,e,this.sdk.logger)}async#f(e){let t;try{t=await An(this.sdk.provider,e)}catch{return`unknown`}let n=qn(t,this.address);return typeof n==`string`?n:this.#u(n.unwrapRequestId)}async#p(e,t){await _(`${e}: clearPendingUnshield`,()=>Gn(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 Vt(n)||n instanceof y&&await this.#u(e)===`settled`?(await this.#p(`unshield`,t),new Ht(`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 C(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=K(i.address),o=await this.sdk.provider.readContract(b(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:S(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:S(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};const Yn=q.union([q.bigint(),q.boolean(),a]),Xn=q.array(q.string());var Zn=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=Yn.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=K(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}:${K(e)}:${K(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=Xn.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 Qn(e,t){let n=$n(e,t);if(!n)throw new H(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function $n(e,t){let n=i(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const er=e=>new Promise(t=>setTimeout(t,e));var tr=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=K(t);return this.#s(e,{requesterAddress:r,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=K(t),o=K(n),s={spent:!1};return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:K(r),delegator:a,validate:e=>this.#m(e,{delegatorAddress:a,delegateAddress:o}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:i?.operation},s))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof Ye))throw t;await er(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:r,maxConcurrency:i=5,waitForPropagation:a=!0,operation:o}){let s=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:K(e.contractAddress)}));if(s.length===0)return{items:s};let c=K(r);try{let e=await this.delegatedDecryptValues(s.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,c,{waitForPropagation:a,operation:o});for(let t of s)this.#d(t,e);return{items:s}}catch(e){if(Lt(e))throw e;if(s.length===1){let[n=this.#p()]=s;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:K(t)}),{items:s}}}let l=!1,u;if(await 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(Lt(n)){l=!0,u??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:K(t)})}}),i),u!==void 0)throw u;return{items:s}}async#o(e,t,n,r){let i=Qn(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&&St(e.message)&&await this.#t.evictTransportKeyPair(),e}let o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(e,t,n,r={spent:!1}){if(e.length===0)return{};let i=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:K(e.contractAddress)})),a={},o=[];for(let e of i)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 Et(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 U)||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 Ft?new U(`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 z&&e.cause instanceof Error?e.cause:e;throw this.#i({type:h.DecryptError,error:R(n),durationMs:Date.now()-p,encryptedValues:m}),E(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 U)??a[0]}async#l(e,t,n,r,i,a){let o;try{o=await this.#o(t,n,r,a)}catch(t){throw E(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 H(`${e.errorMessage}: relayer returned no clear value for ${s.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(s.map(e=>new H(`No clear value for handle ${e} on ${n}`)),`${s.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new Rt(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:yt(e)})}#d(e,t){let n=t[e.encryptedValue];n===void 0?e.error=new H(`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 z?e:E(e,t,n)}#p(){throw new H(`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 $={AlreadyDelegatedOrRevokedInSameBlock:e=>new tt(`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 w(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new T(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new et(`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 Ze(`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 nr(e){return Object.hasOwn($,e)}function rr(e,t){let n=zt(e);if(n&&nr(n))return $[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries($))if(r.includes(e))return n(t);return null}var ir=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=K(t),o=K(n),s=K(r);if(o===s)throw new w(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===K(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new et(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(o===a)throw new T(`Delegate address cannot be the same as the contract address (${a}).`);let c=this.#e.relayer.chain.aclContractAddress,l=i?BigInt(Math.floor(i.getTime()/1e3)):Y,u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),u=-1n}if(u===l)throw new Ze(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);return a!==K(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:a,delegatorAddress:s,delegateAddress:o}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:a,config:nn(c,o,a,l)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=K(t),a=K(n),o=K(r),s=this.#e.relayer.chain.aclContractAddress,c;try{c=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:o,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),c=1n}if(c===0n)throw new N(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:i,config:rn(s,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=K(e.contractAddress)===X,[n,r]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:X})]),i=this.#a(n)||this.#a(r)?await this.#t.getBlockTimestamp():void 0,a=this.#o(n,i);if(a.isActive)return a;let o=this.#o(r,i);return o.isActive?o:n>=r?a:o}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:X});t&&this.#r.warn(`delegateDecryption: ${e.delegateAddress} already holds an active wildcard delegation from ${e.delegatorAddress}; this grant for ${e.contractAddress} is redundant.`)}catch(e){this.#r.warn(`delegateDecryption: wildcard redundancy check failed`,{error:e})}}#a(e){return e!==0n&&e!==Y}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===Y?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(an(r,K(t),K(n),K(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 y))return;let t=rr(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=K(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=K(e),i=K(t),a=K(n),{isActive:o,expiryTimestamp:s}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!o)throw s===0n?new N(`No active delegation from ${i} to ${a} for ${r}`):new P(`Delegation from ${i} to ${a} for ${r} has expired`)}},ar=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),r=K(e.contractAddress);try{this.#t({type:h.EncryptStart},r);let i=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:h.EncryptEnd,durationMs:Date.now()-n},r),i}catch(e){throw this.#t({type:h.EncryptError,error:R(e),durationMs:Date.now()-n},r),$t(e,`Encryption failed`)}}},or=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 sr=q.object({kind:q.literal(`ConfidentialTransfer`),from:a,token:a,to:a,amount:q.bigint()}),cr=q.object({kind:q.literal(`ConfidentialTransferFrom`),from:a,token:a,owner:a,to:a,amount:q.bigint()}),lr=q.object({kind:q.literal(`SetOperator`),from:a,token:a,operator:a,until:u}),ur=q.object({kind:q.literal(`Unwrap`),from:a,token:a,to:a,amount:q.bigint()}),dr=q.object({kind:q.literal(`UnwrapAll`),from:a,token:a,to:a}),fr=q.object({kind:q.literal(`FinalizeUnwrap`),from:a,wrapper:a,unwrapRequestIdOrAmount:p}),pr=q.object({kind:q.literal(`ApproveUnderlying`),from:a,underlying:a,spender:a,amount:q.bigint()}),mr=q.object({kind:q.literal(`Wrap`),from:a,wrapper:a,to:a,amount:q.bigint()}),hr=p.check(q.refine(e=>e===`0x`||Xt(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`)),gr=q.object({kind:q.literal(`TransferAndCall`),from:a,underlying:a,wrapper:a,amount:q.bigint(),recipientData:q.optional(hr)}),_r=q.object({kind:q.literal(`DelegateDecryption`),from:a,contractAddress:a,delegateAddress:a,expirationDate:q.optional(q.date())}),vr=q.object({kind:q.literal(`RevokeDelegation`),from:a,contractAddress:a,delegateAddress:a});q.discriminatedUnion(`kind`,[sr,cr,lr,ur,dr,fr,pr,mr,gr,_r,vr]);const yr=q.strictObject({maxFeePerGas:q.bigint(),maxPriorityFeePerGas:q.bigint()}),br=q.object({nonce:q.optional(q.int().check(q.nonnegative())),gasLimit:q.optional(q.bigint()),fees:q.optional(yr)}),xr=q.object({address:a,abi:q.array(q.unknown()),functionName:q.string(),args:q.array(q.unknown()),value:q.optional(q.bigint()),gas:q.optional(q.bigint())}),Sr=q.extend(br,{from:a,calldata:xr});var Cr=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=G(br,t);let n=await this.#e.getChainId(),r=this.#t.chain.id;if(n!==r)throw new B(`Offline.prepare: provider is on chain ${n} but the SDK is configured for chain ${r}. The prepared transaction's contract addresses and encrypted inputs are bound to chain ${r} — point the provider at the same chain.`);let i={calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees},a=G(Sr,i),o=await this.#e.prepareTransaction(a).catch(t=>{throw mt(t,`prepare ${e.kind}`)??t});return{kind:e.kind,unsignedTx:o,from:a.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new B(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=G(sr,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 V(`Encryption returned no handles for ConfidentialTransfer`);return Te(e.token,e.to,r,n)}async#a(e){e=G(cr,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 V(`Encryption returned no handles for ConfidentialTransferFrom`);return Ge(e.token,e.owner,e.to,r,n)}#o(e){return e=G(lr,e),Le(e.token,e.operator,e.until)}async#s(e){e=G(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-unwrap`}),r=t[0];if(!r)throw new V(`Encryption returned no handles for Unwrap`);return xe(e.token,e.from,e.to,r,n)}async#c(e){e=G(dr,e);let t=await this.#e.readContract(qe(e.token,e.from));return Se(e.token,e.from,e.to,t)}async#l(e){e=G(fr,e);let{value:t,decryptionProof:n}=await at(this.#t.relayer,e.unwrapRequestIdOrAmount,{operation:`offline-finalize-unwrap`});return Ee(e.wrapper,e.unwrapRequestIdOrAmount,t,n)}#u(e){return e=G(pr,e),S(e.underlying,e.spender,e.amount)}#d(e){return e=G(mr,e),g(e.wrapper,e.to,e.amount)}#f(e){return e=G(gr,e),tn(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=G(_r,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 w(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new T(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):Y;return nn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=G(vr,e),rn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function wr(e){if(Object.hasOwn(e,`transportKeyPairDerivationSecret`)&&e.transportKeyPairDerivationSecret===void 0)throw new B(`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 Tr(e){if(e===void 0)return;let{importScripts:t}=globalThis;if(typeof window<`u`||typeof document<`u`||typeof t==`function`)throw new B(`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 Er(e){if(e===void 0)return;let t=G(l,e);return new ne(typeof t==`string`?t:new Uint8Array(t))}var Dr=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){wr(t),Tr(t.transportKeyPairDerivationSecret);let n=Er(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 Zn(e.storage,this.#i),this.#u=new ir({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 tr({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new ar({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new or({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,clearCredentialsOnWalletChange:e.clearCredentialsOnWalletChange,logger:this.#i}),this.#d=new Cr({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new wn({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new Tn({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new En({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new Dn(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}get chains(){return this.#e.chains}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new f({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,W(t,`encrypt`))}createToken(e){return new gt(this,e)}createWrappedToken(e){return new Jn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{Cn as ACL_TOPICS,it as AclPausedError,Q as AclTopics,dt as BalanceCheckUnavailableError,te as BaseSigner,Ve as ChainMismatchError,On as ChromeSessionStorage,B as ConfigurationError,En as Decryption,H as DecryptionFailedError,n as DefaultRegistryAddresses,rt as DelegationContractIsSelfError,tt as DelegationCooldownError,et as DelegationDelegateCannotBeWildcardError,T as DelegationDelegateEqualsContractError,M as DelegationExpirationTooSoonError,P as DelegationExpiredError,Ze as DelegationExpiryUnchangedError,N as DelegationNotFoundError,Ye as DelegationNotPropagatedError,w as DelegationSelfNotAllowedError,Tn as Delegations,je as ERC1363_INTERFACE_ID,L as ERC20ReadFailedError,Be as ERC7984_INTERFACE_ID,He as ERC7984_WRAPPER_INTERFACE_ID,Dt as EncryptOffloadUnavailableError,V as EncryptionFailedError,be as HcuBlockLimitExceededError,ke as HcuTransactionLimitExceededError,t as IndexedDBStorage,ct as InsufficientAllowanceError,lt as InsufficientConfidentialBalanceError,I as InsufficientERC20BalanceError,jt as InvalidTransportKeyPairError,Ot as KeyWrappingError,Y as MAX_UINT64,s as MemoryStorage,d as MutableWalletAccountStore,Nt as NoCiphertextError,st as NotEntitledError,Dn as Offline,wn as Permits,Pt as PreparedPermitChainMismatchError,kt as PreparedPermitExpiredError,Ct as RelayerRequestFailedError,U as RevokedKmsContextError,Rt as RpcRateLimitError,ye as SignerNotConfiguredError,De as SignerRequiredError,Ft as SigningFailedError,Mt as SigningRejectedError,gn as TOKEN_TOPICS,gt as Token,Z as Topics,y as TransactionRevertedError,It as TransportKeyPairChangedError,At as TransportKeyPairExpiredError,Ht as UnshieldAlreadyFinalizedError,Bt as UnwrapNotMinedError,nt as VaultBatchNotDispatchedError,ot as VaultBatcherPausedError,Qe as VaultBatcherReadFailedError,$e as VaultJoinUnconfirmedError,X as WILDCARD_CONTRACT,Oe as WalletAccountNotReadyError,ve as WalletNotConnectedError,Jn as WrappedToken,f as WrappersRegistry,pt as ZERO_ENCRYPTED_VALUE,z as ZamaError,xt as ZamaErrorCode,Dr as ZamaSDK,h as ZamaSDKEvents,b as allowanceContract,fe as anvil,S as approveContract,x as balanceOfContract,ce as bscTestnet,ue as chains,kn as chromeSessionStorage,e as cleartext,qe as confidentialBalanceOfContract,Me as confidentialTotalSupplyContract,Ke as confidentialTransferAndCallContract,Te as confidentialTransferContract,he as confidentialTransferFromAndCallContract,Ge as confidentialTransferFromContract,sn as createConfig,m as createWalletAccountStore,Fe as decimalsContract,yn as decodeAclEvent,bn as decodeAclEvents,cn as decodeConfidentialTransfer,_n as decodeDelegatedForUserDecryption,fn as decodeOnChainEvent,pn as decodeOnChainEvents,vn as decodeRevokedDelegationForUserDecryption,dn as decodeUnwrapFinalized,un as decodeUnwrapRequested,ln as decodeWrap,nn as delegateForUserDecryptionContract,Ee as finalizeUnwrapContract,xn as findDelegatedForUserDecryption,Sn as findRevokedDelegationForUserDecryption,mn as findUnwrapRequested,hn as findWrap,Yt as getConfidentialTokenAddressContract,an as getDelegationExpiryContract,Gt as getTokenAddressContract,qt as getTokenPairContract,Wt as getTokenPairsContract,Ut as getTokenPairsLengthContract,Kt as getTokenPairsSliceContract,oe as hardhat,ie as hoodi,re as indexedDBStorage,_e as inferredTotalSupplyContract,Ne as isConfidentialTokenContract,Jt as isConfidentialTokenValidContract,Re as isConfidentialWrapperContract,F as isEncryptedValueZero,on as isHandleDelegatedContract,ge as isOperatorContract,vt as isRetryable,le as mainnet,Qt as matchZamaError,o as memoryStorage,Ae as nameContract,r as parsePreparedPermit,de as polygon,ae as polygonAmoy,Ce as rateContract,wt as retryAfterSeconds,rn as revokeDelegationContract,se as sepolia,Le as setOperatorContract,Pe as supportsInterfaceContract,We as symbolContract,tn as transferAndCallContract,me as underlyingContract,Ie as unwrapAmountContract,xe as unwrapContract,Se as unwrapFromBalanceContract,we as unwrapRequesterContract,g as wrapContract,pe as zenithTrexTestnet};
|
|
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};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|