@stakekit/widget 0.0.293 → 0.0.294
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/bundle/{DateTime-BBRIKkPv.js → DateTime-CMMZj2i-.js} +54 -54
- package/dist/bundle/{assets-vw12jo1v.js → assets-Bc9gJ-IT.js} +6 -6
- package/dist/bundle/{cardano-connector-DCWdS4Lt.js → cardano-connector-4FH7sm5s.js} +2 -2
- package/dist/bundle/{configured-chains-Bc6_pgMo.js → configured-chains-DF5IpaPp.js} +1 -1
- package/dist/bundle/{cosmos-connector-meta-Br67nymZ.js → cosmos-connector-meta-BKRBGzAs.js} +1 -1
- package/dist/bundle/index.bundle.js +13834 -13695
- package/dist/bundle/{ledger-connector-wZ-AWITi.js → ledger-connector-Em3Ex6Ns.js} +5 -5
- package/dist/bundle/{network-D8-Flo2u.js → network-D2ajkWp0.js} +1 -1
- package/dist/bundle/{reward-rate-chart-B41r4AU4.js → reward-rate-chart-6q6gJawR.js} +4 -4
- package/dist/bundle/{solana-connector-CXe_nU4I.js → solana-connector-DHrdMGZC.js} +3 -3
- package/dist/bundle/{stellar-connector-Cdl9Hnba.js → stellar-connector-DkR_jg41.js} +2 -2
- package/dist/bundle/{styles.css-BJ7-ORZP.js → styles.css-DQG3ba8V.js} +6 -6
- package/dist/bundle/{substrate-connector-DFeFqV_q.js → substrate-connector-CzewVoQ6.js} +1 -1
- package/dist/bundle/{ton-connector-CWmOukzn.js → ton-connector-CcahoFeW.js} +3 -3
- package/dist/bundle/{transaction-BwhgjU0e.js → transaction-BGiGADTK.js} +1 -1
- package/dist/bundle/{transaction-CUoDE6CU.js → transaction-BvpQWKqm.js} +1 -1
- package/dist/bundle/{transaction-B8S7Vgaq.js → transaction-CD_QhA6u.js} +2 -2
- package/dist/bundle/{transaction-DxrR2BHC.js → transaction-CiEShf7a.js} +1 -1
- package/dist/bundle/{tron-connector--M_0_Iy7.js → tron-connector-Dy_36o_J.js} +3 -3
- package/dist/bundle/{utils-CoW929-6.js → utils-BMTuLksW.js} +1 -1
- package/dist/bundle/{wallet-manager-C3rmOq7t.js → wallet-manager-BLaLHs2U.js} +11 -11
- package/dist/package/{DateTime-DJZXpaqx.js → DateTime-CGVpQQm9.js} +24 -2
- package/dist/package/{assets-BuIo5TOF.js → assets-CEn8BPdT.js} +1 -1
- package/dist/package/{cardano-connector-DIZuipB7.js → cardano-connector-BDWTBXaS.js} +2 -2
- package/dist/package/{configured-chains-B6PD9hvx.js → configured-chains-CRuy8tse.js} +1 -1
- package/dist/package/{cosmos-connector-meta-CgvZWkLV.js → cosmos-connector-meta-B-ke1Dvw.js} +1 -1
- package/dist/package/index.package.js +1682 -1449
- package/dist/package/{ledger-connector-B3kEcKjM.js → ledger-connector-BQDRUjOJ.js} +5 -5
- package/dist/package/{network-B4Qs3uRl.js → network-K03Uj00V.js} +1 -1
- package/dist/package/{reward-rate-chart-B42ZCby7.js → reward-rate-chart-DBx39GdL.js} +2 -2
- package/dist/package/{solana-connector-VG2pC1EJ.js → solana-connector-fL70NOkD.js} +3 -3
- package/dist/package/{stellar-connector-DO9tJUOg.js → stellar-connector-C_33sqO5.js} +2 -2
- package/dist/package/{styles.css-DwJjrmLr.js → styles.css-BOghDWGq.js} +1 -1
- package/dist/package/{substrate-connector-P80MVt5T.js → substrate-connector-Cr7LEt2o.js} +1 -1
- package/dist/package/{ton-connector-3rqiqNZO.js → ton-connector-81-rUhzX.js} +3 -3
- package/dist/package/{transaction-DTbU7sxm.js → transaction-BHIZ9rKF.js} +1 -1
- package/dist/package/{transaction-CuMGfUeE.js → transaction-C5e_gCK6.js} +1 -1
- package/dist/package/{transaction-V39s0qKU.js → transaction-DMMfLvk1.js} +2 -2
- package/dist/package/{transaction-Do_oUKxl.js → transaction-DgdU5pHH.js} +1 -1
- package/dist/package/{tron-connector-CKUZFHDh.js → tron-connector-Cuez3U16.js} +3 -3
- package/dist/package/{wallet-manager-CioQJQ5H.js → wallet-manager-DWFwmdLb.js} +2 -2
- package/dist/website/assets/AlertController-Dd3t1FDe.js +1 -0
- package/dist/website/assets/{CaipNetworkUtil-CIgzbD6k.js → CaipNetworkUtil-CyIDQhS0.js} +1 -1
- package/dist/website/assets/DateTime-ByC3zr_K.js +1 -0
- package/dist/website/assets/{HelpersUtil-BokHy7la.js → HelpersUtil-Bpil3MMz.js} +1 -1
- package/dist/website/assets/ModalController-BhWRBcfd.js +5 -0
- package/dist/website/assets/{albedo.module-Dn9vkw3f.js → albedo.module-DkOe0Unb.js} +1 -1
- package/dist/website/assets/assets-DXO6qW6R.js +2 -0
- package/dist/website/assets/{axios-Dl6BaS8Y.js → axios-rFNl7rAx.js} +2 -2
- package/dist/website/assets/{base-signer-b1ff2VPI-DF_m1Hx-.js → base-signer-b1ff2VPI-DEykpag5.js} +1 -1
- package/dist/website/assets/{basic-Bt_YnOIC.js → basic-By5_muQ4.js} +1 -1
- package/dist/website/assets/bignumber-FohbSRh0.js +1 -0
- package/dist/website/assets/blakejs-x6iaQxOd.js +3 -0
- package/dist/website/assets/bn-Ck4DeaX2.js +1 -0
- package/dist/website/assets/{browser-ponyfill-_v4sZCld.js → browser-ponyfill-lHyeX8iJ.js} +1 -1
- package/dist/website/assets/{bs58-CiFyCgrv.js → bs58-gzsgdke5.js} +1 -1
- package/dist/website/assets/{build-DM4Sawu1.js → build-ClRxYQRR.js} +1 -1
- package/dist/website/assets/{build-Butjcagw.js → build-TBrHU398.js} +1 -1
- package/dist/website/assets/{build-B5AnTSOq.js → build-Tl3I8dhV.js} +1 -1
- package/dist/website/assets/{cardano-connector-BC5bF4Y2.js → cardano-connector-8El4Ztf_.js} +9 -9
- package/dist/website/assets/{configured-chains-Bp7rWkOZ.js → configured-chains-DQ_M8-li.js} +1 -1
- package/dist/website/assets/core-BiDQVY37.js +2 -0
- package/dist/website/assets/{cosmos-connector-meta-CZFaunIB.js → cosmos-connector-meta-DRTieEt0.js} +1 -1
- package/dist/website/assets/dist-BVuLBvyS.js +7 -0
- package/dist/website/assets/{dist-BKdXTi2f.js → dist-Bo7ZdXT8.js} +3 -3
- package/dist/website/assets/{dist-7PipG_eL.js → dist-DlLKQSrv.js} +3 -3
- package/dist/website/assets/dist-ZKTSEBXW.js +1 -0
- package/dist/website/assets/{elliptic-j9CClrcl.js → elliptic-BdE4gFqn.js} +2 -2
- package/dist/website/assets/{esm-DVfwo40P.js → esm-BjyHrLEJ.js} +1 -1
- package/dist/website/assets/events-CMzhc0tf.js +1 -0
- package/dist/website/assets/{extrinsic-encoding-B3zynq2U.js → extrinsic-encoding-BIj1XBpl.js} +1 -1
- package/dist/website/assets/{features-LE43LGiF.js → features-Cy1CFK9a.js} +1 -1
- package/dist/website/assets/{fhevm-relayer-DXLb4mIw-bVmGMiQn.js → fhevm-relayer-DXLb4mIw-Bbrz0cha.js} +5 -3
- package/dist/website/assets/freighter.module-DsmrpiWT.js +1 -0
- package/dist/website/assets/index-7hHJ2eI5.js +558 -0
- package/dist/website/assets/index-zFAIWvcU.css +1 -0
- package/dist/website/assets/{index.es-D6B6PG3M.js → index.es-BGzDKZr_.js} +1 -1
- package/dist/website/assets/index.es-BHs2-Pa6.js +1 -0
- package/dist/website/assets/{index.es-wqX1ruQA.js → index.es-Bpga9r91.js} +5 -5
- package/dist/website/assets/{kms_lib-mPebVu09.js → kms_lib-BgnOy0xU.js} +1 -1
- package/dist/website/assets/{kms_lib-Bh_Z1nH6.js → kms_lib-w0jRi8cP.js} +1 -1
- package/dist/website/assets/{ledger-connector-BOOoTKx_.js → ledger-connector-CNNjVgC1.js} +3 -3
- package/dist/website/assets/{lib-es-5LFNYQ9J.js → lib-es-DmH9FYVZ.js} +1 -1
- package/dist/website/assets/lobstr.module-BUAItZUt.js +1 -0
- package/dist/website/assets/{nacl-fast-BI97gFtf.js → nacl-fast-B5R4wpqG.js} +1 -1
- package/dist/website/assets/{nacl-util-DCWJejqG.js → nacl-util-6167mj42.js} +1 -1
- package/dist/website/assets/{network-CEcIzsgc.js → network-BVzpe0Ii.js} +1 -1
- package/dist/website/assets/{polkadot-ledger-transaction-DaDP252u.js → polkadot-ledger-transaction-Dp6EFfyV.js} +1 -1
- package/dist/website/assets/registry-BgQw-qJW.js +1 -0
- package/dist/website/assets/{reward-rate-chart-COP_M115.js → reward-rate-chart-CO_yI4og.js} +4 -4
- package/dist/website/assets/{safe-buffer-Dz6e-rwu.js → safe-buffer-BUgQmBOp.js} +1 -1
- package/dist/website/assets/{safe-connector-DG2cXEO5.js → safe-connector-BObu9WgG.js} +2 -2
- package/dist/website/assets/{solana-connector-DSpWnxwA.js → solana-connector-CVuV_EKp.js} +1 -1
- package/dist/website/assets/{src-Zq1Jw-Sn.js → src-DbdC_Alu.js} +1 -1
- package/dist/website/assets/{src-hSPfFTzN.js → src-Dl7INWvU.js} +1 -1
- package/dist/website/assets/state-D5Nw1L4F.js +1 -0
- package/dist/website/assets/{stellar-connector-BAbbdkSK.js → stellar-connector-Ba7Jcrbg.js} +1 -1
- package/dist/website/assets/styles.css-NtRiu07M.js +1 -0
- package/dist/website/assets/substrate-connector-hQ3vc47X.js +2 -0
- package/dist/website/assets/tfhe-BACovsAk.js +1 -0
- package/dist/website/assets/{tfhe-DuWT_ao1.js → tfhe-BSAXrnM6.js} +1 -1
- package/dist/website/assets/ton-connector-CU1xiP2u.js +2264 -0
- package/dist/website/assets/tracking-variants-CtfEiKNR.js +93 -0
- package/dist/website/assets/{transaction-BH4ssPh3.js → transaction-B5hUD0AE.js} +1 -1
- package/dist/website/assets/{transaction-BVuftLt1.js → transaction-BWEzzOww.js} +1 -1
- package/dist/website/assets/transaction-BmFUkzQv.js +2 -0
- package/dist/website/assets/{transaction-1KdJeqcp.js → transaction-C_iyacpP.js} +1 -1
- package/dist/website/assets/{tron-connector-CJURHEQe.js → tron-connector-gXtlAAuG.js} +7 -7
- package/dist/website/assets/{tx-Bkou_ALe.js → tx-Cosvp39i.js} +1 -1
- package/dist/website/assets/{utils-CH0e59XB.js → utils-meUBO1X1.js} +1 -1
- package/dist/website/assets/{viem-BQ_7aeKB.js → viem-8-EtcU49.js} +1 -1
- package/dist/website/assets/{w3m-modal-BLY--NNS.js → w3m-modal-HS9RLkN8.js} +2 -2
- package/dist/website/assets/wallet-manager-BQrZx180.js +5 -0
- package/dist/website/assets/{web-4qAQ-Ymk.js → web-azgm2Psf.js} +1 -1
- package/dist/website/assets/{wui-list-item-1gzb5UQJ.js → wui-list-item-CfZ1WQql.js} +1 -1
- package/dist/website/assets/{xbull.module-B4N1LGQD.js → xbull.module-DQx6rh7x.js} +1 -1
- package/dist/website/index.html +19 -19
- package/package.json +2 -2
- package/dist/website/assets/AlertController-CH5fpr36.js +0 -1
- package/dist/website/assets/DateTime-DR7XeJxF.js +0 -1
- package/dist/website/assets/ModalController-CWwEAkfw.js +0 -5
- package/dist/website/assets/assets-Dk5ppLtc.js +0 -2
- package/dist/website/assets/bignumber-CziKLYjt.js +0 -1
- package/dist/website/assets/blakejs-Dx-Zt5zT.js +0 -3
- package/dist/website/assets/bn-CJG5j3KW.js +0 -1
- package/dist/website/assets/core-uatW2d6Y.js +0 -2
- package/dist/website/assets/dist-CELdgNh9.js +0 -1
- package/dist/website/assets/dist-omv2KNC4.js +0 -5
- package/dist/website/assets/events-D2w4OsQJ.js +0 -1
- package/dist/website/assets/freighter.module-CaBNS6Y-.js +0 -1
- package/dist/website/assets/index-CRRnuuvK.js +0 -540
- package/dist/website/assets/index-mVJBJZFp.css +0 -1
- package/dist/website/assets/index.es-DCi2xZ1b.js +0 -1
- package/dist/website/assets/lobstr.module-GQjJAf8P.js +0 -1
- package/dist/website/assets/registry-DVfYVrCY.js +0 -1
- package/dist/website/assets/state-B8Vu3fYx.js +0 -1
- package/dist/website/assets/styles.css-BK5OO2Hh.js +0 -1
- package/dist/website/assets/substrate-connector-CwnGlD2K.js +0 -2
- package/dist/website/assets/tfhe-PDJAG8Bv.js +0 -1
- package/dist/website/assets/ton-connector-DMNOeieX.js +0 -2264
- package/dist/website/assets/tracking-variants-CuRpr0B_.js +0 -85
- package/dist/website/assets/transaction-CbxrIerN.js +0 -2
- package/dist/website/assets/wallet-manager-D8tOJ1jy.js +0 -5
- package/dist/website/mockServiceWorker.js +0 -460
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dr as e,mn as t,nr as n,pn as r}from"./call-ttPZjh8C.js";import{a as i,i as a,n as o,o as s,r as c}from"./fhevm-relayer-DXLb4mIw-bVmGMiQn.js";import{l}from"./internal-C7OFf8M2.js";import{a as u,c as d,d as f,i as p,l as ee,n as m,o as te,r as ne,s as re,t as ie,u as ae}from"./chains-iPpnjXql-CuWJAl6V.js";import{A as h,B as oe,D as se,E as ce,F as g,G as le,H as ue,K as de,L as fe,M as _,N as pe,O as me,P as he,R as ge,S as _e,T as ve,U as ye,V as v,W as be,Y as y,_ as xe,b,d as Se,f as x,g as Ce,h as we,k as Te,p as Ee,q as De,t as S,v as C,w as Oe,x as w,z as T}from"./validation-ClSvPh6P-BSUH7TNc.js";import{$ as ke,A as Ae,B as je,C as Me,D as Ne,E as Pe,F as Fe,G as E,H as Ie,I as Le,J as Re,K as ze,L as Be,M as Ve,N as D,O,P as He,Q as Ue,R as We,S as Ge,T as Ke,U as k,V as qe,W as Je,X as Ye,Y as A,Z as j,_ as Xe,_t as Ze,a as Qe,at as $e,b as et,bt as tt,c as nt,ct as rt,d as it,dt as M,et as at,f as ot,ft as N,g as st,gt as ct,h as lt,ht as ut,i as dt,it as ft,j as pt,k as mt,l as ht,lt as gt,m as _t,mt as vt,n as yt,nt as P,o as bt,ot as F,p as xt,pt as St,q as Ct,r as wt,rt as Tt,s as Et,st as Dt,t as Ot,tt as kt,u as At,ut as jt,v as Mt,vt as Nt,w as I,x as L,y as Pt,yt as Ft,z as It}from"./base-signer-b1ff2VPI-DF_m1Hx-.js";import{z as Lt}from"./api-DpIjV5BK.js";var R=class extends _{retryAfter;constructor(e,t){let{retryAfter:n,...r}=t??{};super(g.RpcRateLimited,e,r),this.name=`RpcRateLimitError`,this.retryAfter=n}},Rt=class extends _{operation;signerChainId;providerChainId;constructor({operation:e,signerChainId:t,providerChainId:n},r){super(g.ChainMismatch,`Operation "${e}" requires signer and provider to be on the same chain, but signer is on chain ${t} and provider is on chain ${n}.`,r),this.name=`ChainMismatchError`,this.operation=e,this.signerChainId=t,this.providerChainId=n}},zt=class extends _{requested;available;token;constructor(e,t,n){super(g.InsufficientConfidentialBalance,e,n),this.name=`InsufficientConfidentialBalanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},Bt=class extends _{requested;available;token;constructor(e,t,n){super(g.InsufficientERC20Balance,e,n),this.name=`InsufficientERC20BalanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},Vt=class extends _{requested;available;token;constructor(e,t,n){super(g.InsufficientAllowance,e,n),this.name=`InsufficientAllowanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},Ht=class extends _{constructor(e,t){super(g.BalanceCheckUnavailable,e,t),this.name=`BalanceCheckUnavailableError`}},z=class extends _{constructor(e,t){super(g.ERC20ReadFailed,e,t),this.name=`ERC20ReadFailedError`}};function B(e){return e instanceof Dt||e instanceof P||e instanceof v||e instanceof R||e instanceof ke||e instanceof F}var Ut={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},Wt={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},Gt={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(Ut),Object.freeze(Wt),Object.freeze(Gt),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function Kt(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function qt(e){if(!Kt(e))throw Error(`Invalid FheType id '${e}'`);let t=Gt[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}var Jt=`0x0000000000000000000000000000000000000000000000000000000000000000`;function V(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}function Yt(e){let t;try{t=BigInt(e)}catch{return 256}let n=Number(t>>8n&255n);return Kt(n)?qt(n):256}function Xt(e,t=2048){let n=[],r=[],i=0;for(let a of e){let e=Yt(a);r.length>0&&i+e>t&&(n.push(r),r=[],i=0),r.push(a),i+=e}return r.length>0&&n.push(r),n}async function H(e,t,n){if(!t)throw new Ft(e);let r;try{r=t.requireWalletAccount(e)}catch(n){if(!(n instanceof rt)||!t.refreshWalletAccount)throw n;await t.refreshWalletAccount(),r=t.requireWalletAccount(e)}let i=await n.getChainId();if(r.chainId!==i)throw new Rt({operation:e,signerChainId:r.chainId,providerChainId:i});return r}async function U(e,t,n){return(await H(e,t,n)).chainId}async function Zt(e){let{operation:t,tokenAddress:n,amount:i,signer:a,provider:o,readBalance:s}=e;if(i===0n)return;let c;try{c=await s(r((await H(t,a,o)).address))}catch(e){throw e instanceof _?e:new Ht(`Balance validation failed (token: ${n})`,{cause:e})}if(c<i)throw new zt(`Insufficient confidential balance: requested ${i}, available ${c} (token: ${n})`,{requested:i,available:c,token:n})}async function W(e,t=1/0){if(Number.isFinite(t)&&t<=0)throw Error(`maxConcurrency must be a positive number`);if(!Number.isFinite(t)||t>=e.length)return Promise.all(e.map(e=>e()));let n=Array.from({length:e.length}),r=0;async function i(){for(;r<e.length;){let t=r++;e[t]&&(n[t]=await e[t]())}}return await Promise.all(Array.from({length:t},i)),n}async function Qt(e){let{operation:t,signer:n,provider:r,config:i,emit:a,onSubmitted:o,logger:s}=e,c=Nt[t];try{let e=await n.writeContract(i);return a(c.submittedEvent(e)),k(`${t}: onSubmitted`,()=>o?.(e),s),{txHash:e,receipt:await r.waitForTransactionReceipt(e)}}catch(e){let n=e instanceof _?e:new A(`Transaction failed during ${t}`,{cause:e});throw a({type:j.TransactionError,operation:t,error:n}),n}}var $t=class e{sdk;address;constructor(e,t){this.sdk=e,this.address=r(t)}#e(e){return N(this.sdk.signer,e)}async name(){return this.sdk.provider.readContract(pt(this.address))}async symbol(){return this.sdk.provider.readContract(Je(this.address))}async decimals(){return this.sdk.provider.readContract(ze(this.address))}async isConfidential(){return this.sdk.provider.readContract(Ke(this.address,Ct))}async isWrapper(){return this.sdk.provider.readContract(Ke(this.address,Re))}async balanceOf(e){return this.decryptBalance(e,`balance-of`)}async decryptBalance(e,t){let n=r(e),i=await this.readConfidentialBalanceOf(n),o=(await this.sdk.decryption.decryptValues([{encryptedValue:i,contractAddress:this.address}],{operation:t}))[i];if(o===void 0)throw new a(`Decryption returned no value for ${i}`);return O(o,`balanceOf: result[encryptedValue]`),o}async confidentialBalanceOf(e){return this.readConfidentialBalanceOf(r(e))}async decryptBalanceAs({delegatorAddress:e,accountAddress:t}){await U(`decryptBalanceAs`,this.sdk.signer,this.sdk.provider);let n=r(e),i=t?r(t):n,o=await this.readConfidentialBalanceOf(i);if(V(o))return 0n;let s=(await this.sdk.decryption.delegatedDecryptValues([{encryptedValue:o,contractAddress:this.address}],n,i,{operation:`decrypt-balance-as`}))[o];if(s===void 0)throw new a(`Delegated decryption returned no value for ${o}`);return O(s,`decryptBalanceAs: result[encryptedValue]`),s}static async batchBalancesOf(t,n){let r=new Map,i=new Map;if(t.length===0)return{results:r,errors:i};let o=e.assertSameSdk(t);await U(`batchBalancesOf`,o.signer,o.provider),await o.permits.grantPermit(t.map(e=>e.address));let s=!1,c,l=await W(t.map(e=>async()=>{if(s)return{status:`aborted`};try{return{status:`fulfilled`,value:await e.decryptBalance(n,`batch-balances-of`)}}catch(e){return B(e)?(s=!0,c??=e,{status:`aborted`}):{status:`rejected`,reason:e}}}),5);if(c!==void 0)throw c;for(let e=0;e<t.length;e++){let n=t[e].address,o=l[e];if(o.status!==`aborted`){if(o.status===`fulfilled`)r.set(n,o.value);else{let e=o.reason,t=e instanceof _?e:new a(T(e).message,{cause:e});i.set(n,t)}}}if(i.size===t.length)throw i.values().next().value??new a(`All token balance decryptions failed`);return{results:r,errors:i}}static async batchDecryptBalancesAs(t,n){if(t.length===0)return new Map;let i=e.assertSameSdk(t),o=new Map,s=new Map,c=n.accountAddress?r(n.accountAddress):r(n.delegatorAddress),l=n.maxConcurrency??10;if(n.encryptedValues&&t.length!==n.encryptedValues.length)throw new a(`tokens.length (${t.length}) must equal encryptedValues.length (${n.encryptedValues.length})`);let u=n.encryptedValues??await e.readBalanceHandlesBatch(t,c,s,l),d=[];for(let[e,n]of t.entries()){let t=u[e];!t||s.has(n.address)||(V(t)?o.set(n.address,0n):d.push({token:n,encryptedValue:t}))}if(d.length>0){let e=await i.decryption.delegatedBatchDecryptValues({encryptedInputs:d.map(({token:e,encryptedValue:t})=>({encryptedValue:t,contractAddress:e.address})),delegatorAddress:n.delegatorAddress,accountAddress:n.accountAddress,maxConcurrency:l,operation:`batch-decrypt-balances-as`});for(let[t,n]of e.items.entries()){let e=d[t];if(!e)continue;if(n.error){s.set(e.token.address,n.error);continue}let r=n.value;if(r===void 0){s.set(e.token.address,new a(`Batch delegated decryption returned no value for ${n.encryptedValue} on token ${e.token.address}`));continue}O(r,`batchDecryptBalancesAs: result[encryptedValue]`),o.set(e.token.address,r)}}if(s.size===0)return o;if(n.onError){let e=[];for(let[t,r]of s)try{o.set(t,n.onError(r,t))}catch(n){e.push({address:t,error:T(n)})}if(e.length>0){let t=e.map(({address:e,error:t})=>`${e}: ${t.message}`).join(`; `);throw new a(`Batch delegated decryption onError callback failed for ${e.length} token(s): ${t}`,{cause:e[0]?.error})}return o}let f=Array.from(s.entries()),p=f.map(([e,t])=>`${e}: ${t.message}`).join(`; `);throw new a(`Batch delegated decryption failed for ${s.size} token(s): ${p}`,{cause:f[0]?.[1]})}static async readBalanceHandlesBatch(e,t,n,r){let i=!1,o,s=await W(e.map(e=>async()=>{if(i)return{status:`aborted`};try{return{status:`fulfilled`,value:await e.readConfidentialBalanceOf(t)}}catch(e){return B(e)?(i=!0,o??=e,{status:`aborted`}):{status:`rejected`,reason:e}}}),r);if(o!==void 0)throw o;let c=[];for(let[t,r]of e.entries()){let e=s[t];if(e&&e.status!==`aborted`){if(e.status===`fulfilled`){c[t]=e.value;continue}n.set(r.address,e.reason instanceof _?e.reason:new a(T(e.reason).message,{cause:e.reason}))}}return c}async confidentialTransfer(e,t,n){this.#e(`confidentialTransfer`);let a=await H(`confidentialTransfer`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:o=!1,onEncryptComplete:s,onTransferSubmitted:c}=n??{},l=r(e);o||await this.assertConfidentialBalance(t,`confidential-transfer`);let{encryptedValues:u,inputProof:d}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:r(a.address)},{operation:`confidential-transfer`});if(k(`transfer: onEncryptComplete`,()=>s?.(),this.sdk.logger),u.length===0)throw new i(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transfer`,config:We(this.address,l,u[0],d),onSubmitted:c})}async confidentialTransferFrom(e,t,n,a){this.#e(`confidentialTransferFrom`);let o=await H(`confidentialTransferFrom`,this.sdk.signer,this.sdk.provider),s=r(e),c=r(t),{encryptedValues:l,inputProof:u}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:r(o.address)},{operation:`confidential-transfer-from`});if(k(`transferFrom: onEncryptComplete`,()=>a?.onEncryptComplete?.(),this.sdk.logger),l.length===0)throw new i(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFrom`,config:$e(this.address,s,c,l[0],u),onSubmitted:a?.onTransferSubmitted})}async confidentialTransferAndCall(e,t,n,a){this.#e(`confidentialTransferAndCall`);let o=await H(`confidentialTransferAndCall`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:s=!1,onEncryptComplete:c,onTransferSubmitted:l}=a??{},u=r(e);s||await this.assertConfidentialBalance(t,`confidential-transfer-and-call`);let{encryptedValues:d,inputProof:f}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:r(o.address)},{operation:`confidential-transfer-and-call`});if(k(`transferAndCall: onEncryptComplete`,()=>c?.(),this.sdk.logger),d.length===0)throw new i(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferAndCall`,config:Pe(this.address,u,d[0],f,n),onSubmitted:l})}async confidentialTransferFromAndCall(e,t,n,a,o){this.#e(`confidentialTransferFromAndCall`);let s=await H(`confidentialTransferFromAndCall`,this.sdk.signer,this.sdk.provider),c=r(e),l=r(t),{encryptedValues:u,inputProof:d}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:r(s.address)},{operation:`confidential-transfer-from-and-call`});if(k(`transferFromAndCall: onEncryptComplete`,()=>o?.onEncryptComplete?.(),this.sdk.logger),u.length===0)throw new i(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFromAndCall`,config:ft(this.address,c,l,u[0],d,a),onSubmitted:o?.onTransferSubmitted})}async setOperator(e,t){this.#e(`setOperator`),await U(`setOperator`,this.sdk.signer,this.sdk.provider);let n=r(e);return this.submitTransaction({operation:`setOperator`,config:Be(this.address,n,t)})}async isOperator(e,t){return this.sdk.provider.readContract(Le(this.address,r(e),r(t)))}async readConfidentialBalanceOf(e){return await this.sdk.provider.readContract(mt(this.address,e))}async assertConfidentialBalance(e,t){return Zt({operation:`assertConfidentialBalance`,tokenAddress:this.address,amount:e,signer:this.sdk.signer,provider:this.sdk.provider,readBalance:e=>this.decryptBalance(e,t)})}emit(e){this.sdk.emitEvent(e,this.address)}async submitTransaction(e){let{operation:t,config:n,onSubmitted:r}=e;return Qt({operation:t,signer:this.#e(t),provider:this.sdk.provider,config:n,emit:e=>this.emit(e),onSubmitted:r,logger:this.sdk.logger})}static assertSameSdk(e){let t=e[0].sdk;for(let n=1;n<e.length;n++)if(e[n].sdk!==t)throw new v(`All tokens in a batch operation must share the same ZamaSDK instance`);return t}};function en(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}var tn=class extends _{unwrapTxHash;unwrapRequestId;constructor(e,t,n){super(g.UnshieldAlreadyFinalized,e,n),this.name=`UnshieldAlreadyFinalizedError`,this.unwrapTxHash=t.unwrapTxHash,this.unwrapRequestId=t.unwrapRequestId}},nn=`InvalidUnwrapRequest`,rn=t(n(`${nn}(bytes32)`)).slice(0,10);function an(e){for(let t=e;t instanceof Error;t=t.cause)if(en(t)===nn||t.message.includes(nn)||t.message.includes(rn))return!0;return!1}var on=[{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 sn(e,t,n,r=`0x`){return{address:e,abi:on,functionName:`transferAndCall`,args:[t,n,r]}}function cn(e){return e.startsWith(`0x`)?e:`0x${e}`}function G(e){return t(n(e))}function K(e){return r(cn(e.slice(-40)))}function ln(e){return e}function un(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function dn(e,t){return r(cn(un(e,t).slice(-40)))}function q(e,t){return BigInt(`0x`+un(e,t))}function fn(e,t){return cn(un(e,t))}var J={ConfidentialTransfer:G(`ConfidentialTransfer(address,address,bytes32)`),Wrap:G(`Wrap(address,uint256,bytes32)`),UnwrapRequested:G(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:G(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function pn(e){return e.topics[0]!==J.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:K(e.topics[1]),to:K(e.topics[2]),encryptedAmount:ln(e.topics[3])}}function mn(e){return e.topics[0]!==J.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:K(e.topics[1]),roundedAmount:q(e.data,0),encryptedWrappedAmount:fn(e.data,1)}}function hn(e){return e.topics[0]!==J.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:K(e.topics[1]),unwrapRequestId:ln(e.topics[2]),encryptedAmount:fn(e.data,0)}}function gn(e){return e.topics[0]!==J.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:K(e.topics[1]),unwrapRequestId:ln(e.topics[2]),encryptedAmount:fn(e.data,0),cleartextAmount:q(e.data,1)}}function _n(e){return pn(e)??mn(e)??hn(e)??gn(e)}function vn(e){let t=[];for(let n of e){let e=_n(n);e&&t.push(e)}return t}function yn(e){for(let t of e){let e=hn(t);if(e)return e}return null}function bn(e){for(let t of e){let e=mn(t);if(e)return e}return null}var xn=[J.ConfidentialTransfer,J.Wrap,J.UnwrapRequested,J.UnwrapFinalized],Y={DelegatedForUserDecryption:G(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:G(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function Sn(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:K(e.topics[1]),delegate:K(e.topics[2]),contractAddress:dn(e.data,0),delegationCounter:q(e.data,1),oldExpirationDate:q(e.data,2),newExpirationDate:q(e.data,3)}}function Cn(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:K(e.topics[1]),delegate:K(e.topics[2]),contractAddress:dn(e.data,0),delegationCounter:q(e.data,1),oldExpirationDate:q(e.data,2)}}function wn(e){return Sn(e)??Cn(e)}function Tn(e){let t=[];for(let n of e){let e=wn(n);e&&t.push(e)}return t}function En(e){for(let t of e){let e=Sn(t);if(e)return e}return null}function Dn(e){for(let t of e){let e=Cn(t);if(e)return e}return null}var On=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];function kn(e){return`zama:pending-unshield:${Me(e)}`}var An=me([_e(L,se(e=>({unwrapTxHash:e}))),_e(b({version:C(1),unwrapTxHash:L,unwrapRequestId:w(L)}),se(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function jn(e,t,n,r){if(r===void 0){await e.set(kn(t),n);return}await e.set(kn(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Mn(e,t){let n=kn(t),r=await e.get(n);if(r==null)return null;let i=An.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Nn(e,t){await e.delete(kn(t))}var Pn=class extends $t{#e;#t=null;#n=null;#r(e){try{return Ie(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new Ft(e,{cause:t})}}async underlying(){return this.#f()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#f();this.#n=await this.sdk.provider.readContract(vt(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#f();return this.sdk.provider.readContract(M(t,r(e),this.address))}async shield(e,t){let n=await H(`shield`,this.sdk.signer,this.sdk.provider),i=await this.isPayable(),a=await this.#f(),o=r(n.address),s;try{s=await this.sdk.provider.readContract(He(a,o))}catch(e){throw e instanceof _?e:new z(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:T(e)})}if(s<e)throw new Bt(`Insufficient ERC-20 balance: requested ${e}, available ${s} (token: ${a})`,{requested:e,available:s,token:a});return i?this.#i(e,a,o,t):this.#a(e,o,t)}async#i(e,t,n,i){this.#r(`shield`);let a=i?.to?r(i.to):n,o=a===n?`0x`:a;return this.submitTransaction({operation:`shield:transferAndCall`,config:sn(t,this.address,e,o),onSubmitted:i?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await H(`wrap`,this.sdk.signer,this.sdk.provider),i=await this.#f(),a=r(n.address),o;try{o=await this.sdk.provider.readContract(He(i,a))}catch(e){throw e instanceof _?e:new z(`Could not read ERC-20 balance for wrap validation (token: ${i})`,{cause:T(e)})}if(o<e)throw new Bt(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${i})`,{requested:e,available:o,token:i});let s;try{s=await this.sdk.provider.readContract(M(i,a,this.address))}catch(e){throw e instanceof _?e:new z(`Could not read ERC-20 allowance for wrap validation (token: ${i})`,{cause:T(e)})}if(s<e)throw new Vt(`Insufficient allowance for wrap: requested ${e}, approved ${s}. Call approveUnderlying() first (token: ${i}).`,{requested:e,available:s,token:i});let c=t?.to?r(t.to):a;return this.submitTransaction({operation:`wrap`,config:E(this.address,c,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let i=n?.approvalStrategy??`exact`;i!==`skip`&&await this.#m(e,i===`max`,n);let a=n?.to?r(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:E(this.address,a,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await H(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#f(),i=r(t.address),a=e??2n**256n-1n;return a>0n&&await this.sdk.provider.readContract(M(n,i,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:D(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:D(n,this.address,a)})}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`);return k(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#p(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return k(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#p(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof _?e:new A(`Failed to get unwrap receipt`,{cause:e})}let r=this.#c(n.logs);if(await this.#l(r))throw await this.#d(`resumeUnshield`),new tn(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:r});return this.#p(r,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=await Mn(this.sdk.storage,this.address);return e?await this.#u(e)?(await this.#d(`getPendingUnshield`),null):e.unwrapTxHash:null}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t){this.#r(`unwrap`);let n=r((await H(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:n},{operation:t}),[s]=a;if(!s)throw new i(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:It(this.address,n,n,s,o)});return{...c,unwrapRequestId:this.#c(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=r((await H(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),t=await this.readConfidentialBalanceOf(e);if(V(t))throw new a(`Cannot unshield: balance is zero`);let n=await this.submitTransaction({operation:`unwrapAll`,config:Ae(this.address,e,e,t)});return{...n,unwrapRequestId:this.#c(n.receipt.logs)}}async finalizeUnwrap(e){return this.#s(e,`finalize-unwrap`)}async#s(e,t){this.#r(`finalizeUnwrap`),await U(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e],{operation:t}),r=n.clearValues[e];return O(r,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:Fe(this.address,e,r,n.decryptionProof)})}#c(e){let t=yn(e.filter(e=>e.address===void 0||r(e.address)===this.address));if(!t)throw new A(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t.unwrapRequestId}async#l(e){try{return await this.sdk.provider.readContract(qe(this.address,e))===l}catch{return!1}}async#u(e){let t=e.unwrapRequestId;if(t===void 0)try{let n=await this.sdk.provider.waitForTransactionReceipt(e.unwrapTxHash);t=this.#c(n.logs)}catch{return!1}return this.#l(t)}async#d(e){await k(`${e}: clearPendingUnshield`,()=>Nn(this.sdk.storage,this.address),this.sdk.logger)}async#f(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(tt(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#p(e,t,n,r,i){this.emit({type:j.UnshieldPhase1Submitted,txHash:t,operationId:n}),await k(`unshield: savePendingUnshield`,()=>jn(this.sdk.storage,this.address,t,e),this.sdk.logger),this.emit({type:j.UnshieldPhase2Started,operationId:n}),k(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#s(e,i)}catch(n){throw an(n)?(await this.#d(`unshield`),new tn(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:j.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),k(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#d(`unshield`),a}async#m(e,t,n){this.#r(`approveUnderlying`);let i=await this.#f(),a=r((await H(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),o=await this.sdk.provider.readContract(M(i,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:D(i,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:D(i,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};function Fn(e){return{type:`cleartext`,createRelayer:(t,n)=>{if(!t.executorAddress)throw new v(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new o({chain:t,options:e,cleartext:!0,logger:n})}}}function In(e,t){if(e instanceof _){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var Ln=class extends _{encryptedValue;contractAddress;account;constructor(e,t){super(g.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},Rn=class extends _{constructor(e,t){super(g.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},zn=class extends _{constructor(e,t){super(g.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},X=class extends _{constructor(e,t){super(g.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},Bn=class extends _{constructor(e,t){super(g.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},Vn=class extends _{constructor(e,t){super(g.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},Hn=class extends _{constructor(e,t){super(g.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},Un=class extends _{constructor(e,t){super(g.DelegationDelegateCannotBeWildcard,e,t),this.name=`DelegationDelegateCannotBeWildcardError`}},Wn=class extends _{constructor(e,t){super(g.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},Gn=class extends _{constructor(e,t){super(g.AclPaused,e,t),this.name=`AclPausedError`}},Kn=class extends _{constructor(e,t){super(g.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},Z=class extends _{constructor(e,t){super(g.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}},qn=[a,ct,h,Z,Dt,P,Ln,R,Ue,F];function Q(e,t,n={}){if(qn.some(t=>e instanceof t))return e;let r=e instanceof Error?e.message:t;if(e instanceof Error&&ge(e.message))return new Ue(e.message,{cause:e});if(be(e))return new F(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:e});if(e instanceof Error&&De(e.message))return n.isDelegated?new Z(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new Ln({encryptedValue:oe(e.message)??``,contractAddress:n.contractAddress??``,account:n.account??``},{cause:e});if(ye(e))return new R(r,{cause:e,retryAfter:y(e)});let i=he(e);return i===void 0&&fe(e)?new R(r,{cause:e,retryAfter:y(e)}):i===400?new ct(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):n.isDelegated&&i===500?new Z(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):le(e)||i!==void 0?new h(r,i,{cause:e,retryAfter:y(e),retryable:de(e)||void 0}):new a(t,{cause:e})}function Jn(e,t){if(e instanceof _)return e;let n=he(e),r=de(e);return n!==void 0||le(e)?new h(e instanceof Error?e.message:t,n,{cause:e,retryAfter:y(e),retryable:r||void 0}):new i(t,{cause:e})}var Yn=[{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 Xn(e,t,n,r){return{address:e,abi:Yn,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function Zn(e,t,n){return{address:e,abi:Yn,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function Qn(e,t,n,r){return{address:e,abi:Yn,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function $n(e,t,n,r,i){return{address:e,abi:Yn,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}var $=2n**64n-1n,er=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function tr(e){return it(e.signer,e.provider,e)}var nr=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 N(this.#r,e)}#s(e,t){throw this.#a({type:j.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 U(`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 U(`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=r((await H(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#c(n)}}async clear(){let e=this.#o(`clear`),t=r((await H(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#c(t)}}async#c(e){await k(`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)}},rr=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return N(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await H(`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 H(`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)}},ir=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 N(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await H(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,c(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await H(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,c(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=c(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{Ie(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 Q(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 H(`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`})}},ar=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)}},or=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)}},sr=new or,cr=me([x(),Ee(),I]),lr=Se(ce()),ur=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=cr.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=r(e),n=`${this.#n}:${t}:`,i=await this.#l(),a=[],o=[];for(let e of i)e.startsWith(n)?a.push(e):o.push(e);await Promise.all(a.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,o)}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}:${r(e)}:${r(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=lr.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 dr(e,t){let n=fr(e,t);if(!n)throw new a(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function fr(e,t){let n=Me(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}var pr=e=>new Promise(t=>setTimeout(t,e)),mr=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 i=r(t);return this.#s(e,{requesterAddress:i,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,i,a){let o=r(t),s=r(n),c={spent:!1};return this.#a(a?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:r(i),delegator:o,validate:e=>this.#m(e,{delegatorAddress:o,delegateAddress:s}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:a?.operation},c))}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 Z))throw t;await pr(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0,operation:s}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:r(e.contractAddress)}));if(c.length===0)return{items:c};let l=r(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,l,{waitForPropagation:o,operation:s});for(let t of c)this.#d(t,e);return{items:c}}catch(e){if(B(e))throw e;if(c.length===1){let[n=this.#p()]=c;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:r(t)}),{items:c}}}let u=!1,d;if(await W(c.map(e=>async()=>{if(!u)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,l,{waitForPropagation:!1,operation:s});this.#d(e,r)}catch(n){if(B(n)){u=!0,d??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:r(t)})}}),a),d!==void 0)throw d;return{items:c}}async#o(e,t,n,r){let i=dr(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&&ge(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,i={spent:!1}){if(e.length===0)return{};let a=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:r(e.contractAddress)})),o={},s=[];for(let e of a)V(e.encryptedValue)?o[e.encryptedValue]=0n:s.push(e);if(s.length===0)return o;let c=Array.from(new Set(a.map(e=>e.contractAddress))),l=Array.from(new Set(s.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(l)}catch(e){throw fe(e)?this.#u(e,`the delegation pre-check`):e}let u=[];for(let e of s){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?u.push(e):o[e.encryptedValue]=n}if(u.length===0)return o;let d=await this.#t.grantPermit(c,t.delegator),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.encryptedValue):f.set(e.contractAddress,[e.encryptedValue])}let p=[];for(let[e,t]of f)for(let n of Xt(t))p.push({contractAddress:e,encryptedValues:n});let ee=Date.now(),m=u.map(e=>e.encryptedValue);try{this.#i({type:j.DecryptStart,encryptedValues:m});try{await this.#c(t,d,p,o,n)}catch(e){if(!(e instanceof F)||i.spent)throw e;let r=d.permissions.map(e=>e.serializedPermit.signature);i.spent=!0;try{d=await this.#t.recoverPermits(c,t.delegator,r)}catch(e){throw e instanceof P?new F(`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,d,p.filter(({encryptedValues:e})=>e.some(e=>o[e]===void 0)),o,n)}let e={};for(let t of m){let n=o[t];n!==void 0&&(e[t]=n)}return this.#i({type:j.DecryptEnd,durationMs:Date.now()-ee,encryptedValues:m,result:e}),o}catch(e){let n=e instanceof _&&e.cause instanceof Error?e.cause:e;throw this.#i({type:j.DecryptError,error:T(n),durationMs:Date.now()-ee,encryptedValues:m}),Q(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await W(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 F)??a[0]}async#l(e,t,n,r,i,o){let s;try{s=await this.#o(t,n,r,o)}catch(t){throw Q(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],o=s[t]?.value;a!==void 0&&o!==void 0&&(i[a]=o,await this.#e.set(e.requesterAddress,n,a,o))}let c=r.filter(e=>i[e]===void 0);if(c.length>0)throw new a(`${e.errorMessage}: relayer returned no clear value for ${c.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(c.map(e=>new a(`No clear value for handle ${e} on ${n}`)),`${c.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new R(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:y(e)})}#d(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new a(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#f(e,t,n){return e instanceof _?e:Q(e,t,n)}#p(){throw new a(`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}},hr={AlreadyDelegatedOrRevokedInSameBlock:e=>new zn(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new Wn(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new Gn(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new Rn(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new Hn(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new Un(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new Kn(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new Vn(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new X(`Cannot revoke: no active delegation exists.`,{cause:e})};function gr(e){return Object.hasOwn(hr,e)}function _r(e,t){let n=en(e);if(n&&gr(n))return hr[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(hr))if(r.includes(e))return n(t);return null}var vr=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:i,expirationDate:a}){if(a&&a.getTime()<Date.now()+36e5)throw new Kn(`Expiration date must be at least 1 hour in the future`);let o=r(t),s=r(n),c=r(i);if(s===c)throw new Rn(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===r(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new Un(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(s===o)throw new Hn(`Delegate address cannot be the same as the contract address (${o}).`);let l=this.#e.relayer.chain.aclContractAddress,u=a?BigInt(Math.floor(a.getTime()/1e3)):$,d;try{d=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),d=-1n}if(d===u)throw new Vn(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return o!==r(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:o,delegatorAddress:c,delegateAddress:s}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:o,config:Xn(l,s,o,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i}){let a=r(t),o=r(n),s=r(i),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new X(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:a,config:Zn(c,o,a)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=r(e.contractAddress)===er,[n,i]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:er})]),a=this.#a(n)||this.#a(i)?await this.#t.getBlockTimestamp():void 0,o=this.#o(n,a);if(o.isActive)return o;let s=this.#o(i,a);return s.isActive?s:n>=i?o:s}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:er});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!==$}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===$?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let i=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(Qn(i,r(t),r(n),r(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await Qt({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 A))return;let t=_r(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let i=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof X||t instanceof Bn){let n=r(e);i.set(n,t);return}throw t}})),i}async assertDelegationActive(e,t,n){let i=r(e),a=r(t),o=r(n),{isActive:s,expiryTimestamp:c}=await this.getStatus({contractAddress:i,delegatorAddress:a,delegateAddress:o});if(!s)throw c===0n?new X(`No active delegation from ${a} to ${o} for ${i}`):new Bn(`Delegation from ${a} to ${o} for ${i} has expired`)}},yr=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),i=r(e.contractAddress);try{this.#t({type:j.EncryptStart},i);let r=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:j.EncryptEnd,durationMs:Date.now()-n},i),r}catch(e){throw this.#t({type:j.EncryptError,error:T(e),durationMs:Date.now()-n},i),Jn(e,`Encryption failed`)}}},br=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await k(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await k(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await k(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>k(`wallet account listener`,()=>t(e),this.#i)))}},xr=b({kind:C(`ConfidentialTransfer`),from:I,token:I,to:I,amount:x()}),Sr=b({kind:C(`ConfidentialTransferFrom`),from:I,token:I,owner:I,to:I,amount:x()}),Cr=b({kind:C(`SetOperator`),from:I,token:I,operator:I,until:Ge}),wr=b({kind:C(`Unwrap`),from:I,token:I,to:I,amount:x()}),Tr=b({kind:C(`UnwrapAll`),from:I,token:I,to:I}),Er=b({kind:C(`FinalizeUnwrap`),from:I,wrapper:I,unwrapRequestIdOrAmount:L}),Dr=b({kind:C(`ApproveUnderlying`),from:I,underlying:I,spender:I,amount:x()}),Or=b({kind:C(`Wrap`),from:I,wrapper:I,to:I,amount:x()}),kr=L.check(Oe(t=>t===`0x`||e(t)===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`)),Ar=b({kind:C(`TransferAndCall`),from:I,underlying:I,wrapper:I,amount:x(),recipientData:w(kr)}),jr=b({kind:C(`DelegateDecryption`),from:I,contractAddress:I,delegateAddress:I,expirationDate:w(we())}),Mr=b({kind:C(`RevokeDelegation`),from:I,contractAddress:I,delegateAddress:I}),Nr=ve({maxFeePerGas:x(),maxPriorityFeePerGas:x()}),Pr=b({nonce:w(xe().check(Lt())),gasLimit:w(x()),fees:w(Nr)}),Fr=b({address:I,abi:Se(Te()),functionName:ce(),args:Se(Te()),value:w(x()),gas:w(x())}),Ir=Ce(Pr,{from:I,calldata:Fr}),Lr=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=S(Pr,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=S(Ir,{calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees}),a=await this.#e.prepareTransaction(i);return{kind:e.kind,unsignedTx:a,from:i.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new v(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=S(xr,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 i(`Encryption returned no handles for ConfidentialTransfer`);return We(e.token,e.to,r,n)}async#a(e){e=S(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-from`}),r=t[0];if(!r)throw new i(`Encryption returned no handles for ConfidentialTransferFrom`);return $e(e.token,e.owner,e.to,r,n)}#o(e){return e=S(Cr,e),Be(e.token,e.operator,e.until)}async#s(e){e=S(wr,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 i(`Encryption returned no handles for Unwrap`);return It(e.token,e.from,e.to,r,n)}async#c(e){e=S(Tr,e);let t=await this.#e.readContract(mt(e.token,e.from));return Ae(e.token,e.from,e.to,t)}async#l(e){e=S(Er,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount],options:{operation:`offline-finalize-unwrap`}}).catch(e=>{throw Q(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return O(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),Fe(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=S(Dr,e),D(e.underlying,e.spender,e.amount)}#d(e){return e=S(Or,e),E(e.wrapper,e.to,e.amount)}#f(e){return e=S(Ar,e),sn(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=S(jr,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new Kn(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new Rn(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new Hn(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):$;return Xn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=S(Mr,e),Zn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Rr(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 zr(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 Br(e){if(e===void 0)return;let t=S(wt,e);return new xt(typeof t==`string`?t:new Uint8Array(t))}var Vr=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Rr(t),zr(t.transportKeyPairDerivationSecret);let n=Br(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 ur(e.storage,this.#i),this.#u=new vr({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 Qe({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new ot({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 mr({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new yr({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new br({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new Lr({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new nr({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new rr({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new ir({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new ar(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new Qe({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,c(t,`encrypt`))}createToken(e){return new $t(this,e)}createWrappedToken(e){return new Pn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{On as ACL_TOPICS,Gn as AclPausedError,Y as AclTopics,Ht as BalanceCheckUnavailableError,bt as BaseSigner,Rt as ChainMismatchError,or as ChromeSessionStorage,v as ConfigurationError,ir as Decryption,a as DecryptionFailedError,ht as DefaultRegistryAddresses,Wn as DelegationContractIsSelfError,zn as DelegationCooldownError,Un as DelegationDelegateCannotBeWildcardError,Hn as DelegationDelegateEqualsContractError,Kn as DelegationExpirationTooSoonError,Bn as DelegationExpiredError,Vn as DelegationExpiryUnchangedError,X as DelegationNotFoundError,Z as DelegationNotPropagatedError,Rn as DelegationSelfNotAllowedError,rr as Delegations,je as ERC1363_INTERFACE_ID,z as ERC20ReadFailedError,Ct as ERC7984_INTERFACE_ID,Re as ERC7984_WRAPPER_INTERFACE_ID,s as EncryptOffloadUnavailableError,i as EncryptionFailedError,dt as IndexedDBStorage,Vt as InsufficientAllowanceError,zt as InsufficientConfidentialBalanceError,Bt as InsufficientERC20BalanceError,Ue as InvalidTransportKeyPairError,ke as KeyWrappingError,$ as MAX_UINT64,yt as MemoryStorage,Ot as MutableWalletAccountStore,ct as NoCiphertextError,Ln as NotEntitledError,ar as Offline,nr as Permits,jt as PreparedPermitChainMismatchError,at as PreparedPermitExpiredError,h as RelayerRequestFailedError,F as RevokedKmsContextError,R as RpcRateLimitError,Ft as SignerNotConfiguredError,Ze as SignerRequiredError,P as SigningFailedError,Dt as SigningRejectedError,xn as TOKEN_TOPICS,$t as Token,J as Topics,A as TransactionRevertedError,kt as TransportKeyPairChangedError,St as TransportKeyPairExpiredError,tn as UnshieldAlreadyFinalizedError,er as WILDCARD_CONTRACT,rt as WalletAccountNotReadyError,ut as WalletNotConnectedError,Pn as WrappedToken,Qe as WrappersRegistry,Jt as ZERO_ENCRYPTED_VALUE,_ as ZamaError,g as ZamaErrorCode,Vr as ZamaSDK,j as ZamaSDKEvents,M as allowanceContract,u as anvil,D as approveContract,He as balanceOfContract,ee as bscTestnet,f as chains,sr as chromeSessionStorage,Fn as cleartext,mt as confidentialBalanceOfContract,Tt as confidentialTotalSupplyContract,We as confidentialTransferContract,$e as confidentialTransferFromContract,tr as createConfig,nt as createWalletAccountStore,ze as decimalsContract,wn as decodeAclEvent,Tn as decodeAclEvents,pn as decodeConfidentialTransfer,Sn as decodeDelegatedForUserDecryption,_n as decodeOnChainEvent,vn as decodeOnChainEvents,Cn as decodeRevokedDelegationForUserDecryption,gn as decodeUnwrapFinalized,hn as decodeUnwrapRequested,mn as decodeWrap,Xn as delegateForUserDecryptionContract,Fe as finalizeUnwrapContract,En as findDelegatedForUserDecryption,Dn as findRevokedDelegationForUserDecryption,yn as findUnwrapRequested,bn as findWrap,_t as getConfidentialTokenAddressContract,Qn as getDelegationExpiryContract,Xe as getTokenAddressContract,lt as getTokenPairContract,et as getTokenPairsContract,st as getTokenPairsLengthContract,Mt as getTokenPairsSliceContract,m as hardhat,p as hoodi,At as indexedDBStorage,Ne as inferredTotalSupplyContract,ie as ingenTestnet,Ye as isConfidentialTokenContract,Pt as isConfidentialTokenValidContract,gt as isConfidentialWrapperContract,V as isEncryptedValueZero,$n as isHandleDelegatedContract,Le as isOperatorContract,pe as isRetryable,ne as mainnet,In as matchZamaError,Et as memoryStorage,pt as nameContract,ae as polygon,d as polygonAmoy,Ve as rateContract,ue as retryAfterSeconds,Zn as revokeDelegationContract,te as sepolia,Be as setOperatorContract,Ke as supportsInterfaceContract,Je as symbolContract,sn as transferAndCallContract,tt as underlyingContract,It as unwrapContract,Ae as unwrapFromBalanceContract,qe as unwrapRequesterContract,E as wrapContract,re as zenithTrexTestnet};
|
|
1
|
+
import{dr as e,mn as t,nr as n,pn as r}from"./call-ttPZjh8C.js";import{a as i,i as a,n as o,o as s,r as c}from"./fhevm-relayer-DXLb4mIw-Bbrz0cha.js";import{l}from"./internal-C7OFf8M2.js";import{a as u,c as d,d as f,i as p,l as ee,n as m,o as te,r as ne,s as re,t as ie,u as ae}from"./chains-iPpnjXql-CuWJAl6V.js";import{A as h,B as oe,D as se,E as ce,F as g,G as le,H as ue,K as de,L as fe,M as _,N as pe,O as me,P as he,R as ge,S as _e,T as ve,U as ye,V as v,W as be,Y as y,_ as xe,b,d as Se,f as x,g as Ce,h as we,k as Te,p as Ee,q as De,t as S,v as C,w as Oe,x as w,z as T}from"./validation-ClSvPh6P-BSUH7TNc.js";import{$ as ke,A as Ae,B as je,C as Me,D as Ne,E as Pe,F as Fe,G as E,H as Ie,I as Le,J as Re,K as ze,L as Be,M as Ve,N as D,O,P as He,Q as Ue,R as We,S as Ge,T as Ke,U as k,V as qe,W as Je,X as Ye,Y as A,Z as j,_ as Xe,_t as Ze,a as Qe,at as $e,b as et,bt as tt,c as nt,ct as rt,d as it,dt as M,et as at,f as ot,ft as N,g as st,gt as ct,h as lt,ht as ut,i as dt,it as ft,j as pt,k as mt,l as ht,lt as gt,m as _t,mt as vt,n as yt,nt as P,o as bt,ot as F,p as xt,pt as St,q as Ct,r as wt,rt as Tt,s as Et,st as Dt,t as Ot,tt as kt,u as At,ut as jt,v as Mt,vt as Nt,w as I,x as L,y as Pt,yt as Ft,z as It}from"./base-signer-b1ff2VPI-DEykpag5.js";import{z as Lt}from"./api-DpIjV5BK.js";var R=class extends _{retryAfter;constructor(e,t){let{retryAfter:n,...r}=t??{};super(g.RpcRateLimited,e,r),this.name=`RpcRateLimitError`,this.retryAfter=n}},Rt=class extends _{operation;signerChainId;providerChainId;constructor({operation:e,signerChainId:t,providerChainId:n},r){super(g.ChainMismatch,`Operation "${e}" requires signer and provider to be on the same chain, but signer is on chain ${t} and provider is on chain ${n}.`,r),this.name=`ChainMismatchError`,this.operation=e,this.signerChainId=t,this.providerChainId=n}},zt=class extends _{requested;available;token;constructor(e,t,n){super(g.InsufficientConfidentialBalance,e,n),this.name=`InsufficientConfidentialBalanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},Bt=class extends _{requested;available;token;constructor(e,t,n){super(g.InsufficientERC20Balance,e,n),this.name=`InsufficientERC20BalanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},Vt=class extends _{requested;available;token;constructor(e,t,n){super(g.InsufficientAllowance,e,n),this.name=`InsufficientAllowanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},Ht=class extends _{constructor(e,t){super(g.BalanceCheckUnavailable,e,t),this.name=`BalanceCheckUnavailableError`}},z=class extends _{constructor(e,t){super(g.ERC20ReadFailed,e,t),this.name=`ERC20ReadFailedError`}};function B(e){return e instanceof Dt||e instanceof P||e instanceof v||e instanceof R||e instanceof ke||e instanceof F}var Ut={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},Wt={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},Gt={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(Ut),Object.freeze(Wt),Object.freeze(Gt),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function Kt(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function qt(e){if(!Kt(e))throw Error(`Invalid FheType id '${e}'`);let t=Gt[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}var Jt=`0x0000000000000000000000000000000000000000000000000000000000000000`;function V(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}function Yt(e){let t;try{t=BigInt(e)}catch{return 256}let n=Number(t>>8n&255n);return Kt(n)?qt(n):256}function Xt(e,t=2048){let n=[],r=[],i=0;for(let a of e){let e=Yt(a);r.length>0&&i+e>t&&(n.push(r),r=[],i=0),r.push(a),i+=e}return r.length>0&&n.push(r),n}async function H(e,t,n){if(!t)throw new Ft(e);let r;try{r=t.requireWalletAccount(e)}catch(n){if(!(n instanceof rt)||!t.refreshWalletAccount)throw n;await t.refreshWalletAccount(),r=t.requireWalletAccount(e)}let i=await n.getChainId();if(r.chainId!==i)throw new Rt({operation:e,signerChainId:r.chainId,providerChainId:i});return r}async function U(e,t,n){return(await H(e,t,n)).chainId}async function Zt(e){let{operation:t,tokenAddress:n,amount:i,signer:a,provider:o,readBalance:s}=e;if(i===0n)return;let c;try{c=await s(r((await H(t,a,o)).address))}catch(e){throw e instanceof _?e:new Ht(`Balance validation failed (token: ${n})`,{cause:e})}if(c<i)throw new zt(`Insufficient confidential balance: requested ${i}, available ${c} (token: ${n})`,{requested:i,available:c,token:n})}async function W(e,t=1/0){if(Number.isFinite(t)&&t<=0)throw Error(`maxConcurrency must be a positive number`);if(!Number.isFinite(t)||t>=e.length)return Promise.all(e.map(e=>e()));let n=Array.from({length:e.length}),r=0;async function i(){for(;r<e.length;){let t=r++;e[t]&&(n[t]=await e[t]())}}return await Promise.all(Array.from({length:t},i)),n}async function Qt(e){let{operation:t,signer:n,provider:r,config:i,emit:a,onSubmitted:o,logger:s}=e,c=Nt[t];try{let e=await n.writeContract(i);return a(c.submittedEvent(e)),k(`${t}: onSubmitted`,()=>o?.(e),s),{txHash:e,receipt:await r.waitForTransactionReceipt(e)}}catch(e){let n=e instanceof _?e:new A(`Transaction failed during ${t}`,{cause:e});throw a({type:j.TransactionError,operation:t,error:n}),n}}var $t=class e{sdk;address;constructor(e,t){this.sdk=e,this.address=r(t)}#e(e){return N(this.sdk.signer,e)}async name(){return this.sdk.provider.readContract(pt(this.address))}async symbol(){return this.sdk.provider.readContract(Je(this.address))}async decimals(){return this.sdk.provider.readContract(ze(this.address))}async isConfidential(){return this.sdk.provider.readContract(Ke(this.address,Ct))}async isWrapper(){return this.sdk.provider.readContract(Ke(this.address,Re))}async balanceOf(e){return this.decryptBalance(e,`balance-of`)}async decryptBalance(e,t){let n=r(e),i=await this.readConfidentialBalanceOf(n),o=(await this.sdk.decryption.decryptValues([{encryptedValue:i,contractAddress:this.address}],{operation:t}))[i];if(o===void 0)throw new a(`Decryption returned no value for ${i}`);return O(o,`balanceOf: result[encryptedValue]`),o}async confidentialBalanceOf(e){return this.readConfidentialBalanceOf(r(e))}async decryptBalanceAs({delegatorAddress:e,accountAddress:t}){await U(`decryptBalanceAs`,this.sdk.signer,this.sdk.provider);let n=r(e),i=t?r(t):n,o=await this.readConfidentialBalanceOf(i);if(V(o))return 0n;let s=(await this.sdk.decryption.delegatedDecryptValues([{encryptedValue:o,contractAddress:this.address}],n,i,{operation:`decrypt-balance-as`}))[o];if(s===void 0)throw new a(`Delegated decryption returned no value for ${o}`);return O(s,`decryptBalanceAs: result[encryptedValue]`),s}static async batchBalancesOf(t,n){let r=new Map,i=new Map;if(t.length===0)return{results:r,errors:i};let o=e.assertSameSdk(t);await U(`batchBalancesOf`,o.signer,o.provider),await o.permits.grantPermit(t.map(e=>e.address));let s=!1,c,l=await W(t.map(e=>async()=>{if(s)return{status:`aborted`};try{return{status:`fulfilled`,value:await e.decryptBalance(n,`batch-balances-of`)}}catch(e){return B(e)?(s=!0,c??=e,{status:`aborted`}):{status:`rejected`,reason:e}}}),5);if(c!==void 0)throw c;for(let e=0;e<t.length;e++){let n=t[e].address,o=l[e];if(o.status!==`aborted`){if(o.status===`fulfilled`)r.set(n,o.value);else{let e=o.reason,t=e instanceof _?e:new a(T(e).message,{cause:e});i.set(n,t)}}}if(i.size===t.length)throw i.values().next().value??new a(`All token balance decryptions failed`);return{results:r,errors:i}}static async batchDecryptBalancesAs(t,n){if(t.length===0)return new Map;let i=e.assertSameSdk(t),o=new Map,s=new Map,c=n.accountAddress?r(n.accountAddress):r(n.delegatorAddress),l=n.maxConcurrency??10;if(n.encryptedValues&&t.length!==n.encryptedValues.length)throw new a(`tokens.length (${t.length}) must equal encryptedValues.length (${n.encryptedValues.length})`);let u=n.encryptedValues??await e.readBalanceHandlesBatch(t,c,s,l),d=[];for(let[e,n]of t.entries()){let t=u[e];!t||s.has(n.address)||(V(t)?o.set(n.address,0n):d.push({token:n,encryptedValue:t}))}if(d.length>0){let e=await i.decryption.delegatedBatchDecryptValues({encryptedInputs:d.map(({token:e,encryptedValue:t})=>({encryptedValue:t,contractAddress:e.address})),delegatorAddress:n.delegatorAddress,accountAddress:n.accountAddress,maxConcurrency:l,operation:`batch-decrypt-balances-as`});for(let[t,n]of e.items.entries()){let e=d[t];if(!e)continue;if(n.error){s.set(e.token.address,n.error);continue}let r=n.value;if(r===void 0){s.set(e.token.address,new a(`Batch delegated decryption returned no value for ${n.encryptedValue} on token ${e.token.address}`));continue}O(r,`batchDecryptBalancesAs: result[encryptedValue]`),o.set(e.token.address,r)}}if(s.size===0)return o;if(n.onError){let e=[];for(let[t,r]of s)try{o.set(t,n.onError(r,t))}catch(n){e.push({address:t,error:T(n)})}if(e.length>0){let t=e.map(({address:e,error:t})=>`${e}: ${t.message}`).join(`; `);throw new a(`Batch delegated decryption onError callback failed for ${e.length} token(s): ${t}`,{cause:e[0]?.error})}return o}let f=Array.from(s.entries()),p=f.map(([e,t])=>`${e}: ${t.message}`).join(`; `);throw new a(`Batch delegated decryption failed for ${s.size} token(s): ${p}`,{cause:f[0]?.[1]})}static async readBalanceHandlesBatch(e,t,n,r){let i=!1,o,s=await W(e.map(e=>async()=>{if(i)return{status:`aborted`};try{return{status:`fulfilled`,value:await e.readConfidentialBalanceOf(t)}}catch(e){return B(e)?(i=!0,o??=e,{status:`aborted`}):{status:`rejected`,reason:e}}}),r);if(o!==void 0)throw o;let c=[];for(let[t,r]of e.entries()){let e=s[t];if(e&&e.status!==`aborted`){if(e.status===`fulfilled`){c[t]=e.value;continue}n.set(r.address,e.reason instanceof _?e.reason:new a(T(e.reason).message,{cause:e.reason}))}}return c}async confidentialTransfer(e,t,n){this.#e(`confidentialTransfer`);let a=await H(`confidentialTransfer`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:o=!1,onEncryptComplete:s,onTransferSubmitted:c}=n??{},l=r(e);o||await this.assertConfidentialBalance(t,`confidential-transfer`);let{encryptedValues:u,inputProof:d}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:r(a.address)},{operation:`confidential-transfer`});if(k(`transfer: onEncryptComplete`,()=>s?.(),this.sdk.logger),u.length===0)throw new i(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transfer`,config:We(this.address,l,u[0],d),onSubmitted:c})}async confidentialTransferFrom(e,t,n,a){this.#e(`confidentialTransferFrom`);let o=await H(`confidentialTransferFrom`,this.sdk.signer,this.sdk.provider),s=r(e),c=r(t),{encryptedValues:l,inputProof:u}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:r(o.address)},{operation:`confidential-transfer-from`});if(k(`transferFrom: onEncryptComplete`,()=>a?.onEncryptComplete?.(),this.sdk.logger),l.length===0)throw new i(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFrom`,config:$e(this.address,s,c,l[0],u),onSubmitted:a?.onTransferSubmitted})}async confidentialTransferAndCall(e,t,n,a){this.#e(`confidentialTransferAndCall`);let o=await H(`confidentialTransferAndCall`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:s=!1,onEncryptComplete:c,onTransferSubmitted:l}=a??{},u=r(e);s||await this.assertConfidentialBalance(t,`confidential-transfer-and-call`);let{encryptedValues:d,inputProof:f}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:r(o.address)},{operation:`confidential-transfer-and-call`});if(k(`transferAndCall: onEncryptComplete`,()=>c?.(),this.sdk.logger),d.length===0)throw new i(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferAndCall`,config:Pe(this.address,u,d[0],f,n),onSubmitted:l})}async confidentialTransferFromAndCall(e,t,n,a,o){this.#e(`confidentialTransferFromAndCall`);let s=await H(`confidentialTransferFromAndCall`,this.sdk.signer,this.sdk.provider),c=r(e),l=r(t),{encryptedValues:u,inputProof:d}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:r(s.address)},{operation:`confidential-transfer-from-and-call`});if(k(`transferFromAndCall: onEncryptComplete`,()=>o?.onEncryptComplete?.(),this.sdk.logger),u.length===0)throw new i(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFromAndCall`,config:ft(this.address,c,l,u[0],d,a),onSubmitted:o?.onTransferSubmitted})}async setOperator(e,t){this.#e(`setOperator`),await U(`setOperator`,this.sdk.signer,this.sdk.provider);let n=r(e);return this.submitTransaction({operation:`setOperator`,config:Be(this.address,n,t)})}async isOperator(e,t){return this.sdk.provider.readContract(Le(this.address,r(e),r(t)))}async readConfidentialBalanceOf(e){return await this.sdk.provider.readContract(mt(this.address,e))}async assertConfidentialBalance(e,t){return Zt({operation:`assertConfidentialBalance`,tokenAddress:this.address,amount:e,signer:this.sdk.signer,provider:this.sdk.provider,readBalance:e=>this.decryptBalance(e,t)})}emit(e){this.sdk.emitEvent(e,this.address)}async submitTransaction(e){let{operation:t,config:n,onSubmitted:r}=e;return Qt({operation:t,signer:this.#e(t),provider:this.sdk.provider,config:n,emit:e=>this.emit(e),onSubmitted:r,logger:this.sdk.logger})}static assertSameSdk(e){let t=e[0].sdk;for(let n=1;n<e.length;n++)if(e[n].sdk!==t)throw new v(`All tokens in a batch operation must share the same ZamaSDK instance`);return t}};function en(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}var tn=class extends _{unwrapTxHash;unwrapRequestId;constructor(e,t,n){super(g.UnshieldAlreadyFinalized,e,n),this.name=`UnshieldAlreadyFinalizedError`,this.unwrapTxHash=t.unwrapTxHash,this.unwrapRequestId=t.unwrapRequestId}},nn=`InvalidUnwrapRequest`,rn=t(n(`${nn}(bytes32)`)).slice(0,10);function an(e){for(let t=e;t instanceof Error;t=t.cause)if(en(t)===nn||t.message.includes(nn)||t.message.includes(rn))return!0;return!1}var on=[{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 sn(e,t,n,r=`0x`){return{address:e,abi:on,functionName:`transferAndCall`,args:[t,n,r]}}function cn(e){return e.startsWith(`0x`)?e:`0x${e}`}function G(e){return t(n(e))}function K(e){return r(cn(e.slice(-40)))}function ln(e){return e}function un(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function dn(e,t){return r(cn(un(e,t).slice(-40)))}function q(e,t){return BigInt(`0x`+un(e,t))}function fn(e,t){return cn(un(e,t))}var J={ConfidentialTransfer:G(`ConfidentialTransfer(address,address,bytes32)`),Wrap:G(`Wrap(address,uint256,bytes32)`),UnwrapRequested:G(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:G(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function pn(e){return e.topics[0]!==J.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:K(e.topics[1]),to:K(e.topics[2]),encryptedAmount:ln(e.topics[3])}}function mn(e){return e.topics[0]!==J.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:K(e.topics[1]),roundedAmount:q(e.data,0),encryptedWrappedAmount:fn(e.data,1)}}function hn(e){return e.topics[0]!==J.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:K(e.topics[1]),unwrapRequestId:ln(e.topics[2]),encryptedAmount:fn(e.data,0)}}function gn(e){return e.topics[0]!==J.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:K(e.topics[1]),unwrapRequestId:ln(e.topics[2]),encryptedAmount:fn(e.data,0),cleartextAmount:q(e.data,1)}}function _n(e){return pn(e)??mn(e)??hn(e)??gn(e)}function vn(e){let t=[];for(let n of e){let e=_n(n);e&&t.push(e)}return t}function yn(e){for(let t of e){let e=hn(t);if(e)return e}return null}function bn(e){for(let t of e){let e=mn(t);if(e)return e}return null}var xn=[J.ConfidentialTransfer,J.Wrap,J.UnwrapRequested,J.UnwrapFinalized],Y={DelegatedForUserDecryption:G(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:G(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function Sn(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:K(e.topics[1]),delegate:K(e.topics[2]),contractAddress:dn(e.data,0),delegationCounter:q(e.data,1),oldExpirationDate:q(e.data,2),newExpirationDate:q(e.data,3)}}function Cn(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:K(e.topics[1]),delegate:K(e.topics[2]),contractAddress:dn(e.data,0),delegationCounter:q(e.data,1),oldExpirationDate:q(e.data,2)}}function wn(e){return Sn(e)??Cn(e)}function Tn(e){let t=[];for(let n of e){let e=wn(n);e&&t.push(e)}return t}function En(e){for(let t of e){let e=Sn(t);if(e)return e}return null}function Dn(e){for(let t of e){let e=Cn(t);if(e)return e}return null}var On=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];function kn(e){return`zama:pending-unshield:${Me(e)}`}var An=me([_e(L,se(e=>({unwrapTxHash:e}))),_e(b({version:C(1),unwrapTxHash:L,unwrapRequestId:w(L)}),se(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function jn(e,t,n,r){if(r===void 0){await e.set(kn(t),n);return}await e.set(kn(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Mn(e,t){let n=kn(t),r=await e.get(n);if(r==null)return null;let i=An.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Nn(e,t){await e.delete(kn(t))}var Pn=class extends $t{#e;#t=null;#n=null;#r(e){try{return Ie(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new Ft(e,{cause:t})}}async underlying(){return this.#f()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#f();this.#n=await this.sdk.provider.readContract(vt(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#f();return this.sdk.provider.readContract(M(t,r(e),this.address))}async shield(e,t){let n=await H(`shield`,this.sdk.signer,this.sdk.provider),i=await this.isPayable(),a=await this.#f(),o=r(n.address),s;try{s=await this.sdk.provider.readContract(He(a,o))}catch(e){throw e instanceof _?e:new z(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:T(e)})}if(s<e)throw new Bt(`Insufficient ERC-20 balance: requested ${e}, available ${s} (token: ${a})`,{requested:e,available:s,token:a});return i?this.#i(e,a,o,t):this.#a(e,o,t)}async#i(e,t,n,i){this.#r(`shield`);let a=i?.to?r(i.to):n,o=a===n?`0x`:a;return this.submitTransaction({operation:`shield:transferAndCall`,config:sn(t,this.address,e,o),onSubmitted:i?.onShieldSubmitted})}async wrap(e,t){this.#r(`wrap`);let n=await H(`wrap`,this.sdk.signer,this.sdk.provider),i=await this.#f(),a=r(n.address),o;try{o=await this.sdk.provider.readContract(He(i,a))}catch(e){throw e instanceof _?e:new z(`Could not read ERC-20 balance for wrap validation (token: ${i})`,{cause:T(e)})}if(o<e)throw new Bt(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${i})`,{requested:e,available:o,token:i});let s;try{s=await this.sdk.provider.readContract(M(i,a,this.address))}catch(e){throw e instanceof _?e:new z(`Could not read ERC-20 allowance for wrap validation (token: ${i})`,{cause:T(e)})}if(s<e)throw new Vt(`Insufficient allowance for wrap: requested ${e}, approved ${s}. Call approveUnderlying() first (token: ${i}).`,{requested:e,available:s,token:i});let c=t?.to?r(t.to):a;return this.submitTransaction({operation:`wrap`,config:E(this.address,c,e),onSubmitted:t?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let i=n?.approvalStrategy??`exact`;i!==`skip`&&await this.#m(e,i===`max`,n);let a=n?.to?r(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:E(this.address,a,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await H(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#f(),i=r(t.address),a=e??2n**256n-1n;return a>0n&&await this.sdk.provider.readContract(M(n,i,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:D(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:D(n,this.address,a)})}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`);return k(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#p(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return k(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#p(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let n;try{n=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof _?e:new A(`Failed to get unwrap receipt`,{cause:e})}let r=this.#c(n.logs);if(await this.#l(r))throw await this.#d(`resumeUnshield`),new tn(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:r});return this.#p(r,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=await Mn(this.sdk.storage,this.address);return e?await this.#u(e)?(await this.#d(`getPendingUnshield`),null):e.unwrapTxHash:null}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t){this.#r(`unwrap`);let n=r((await H(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:n},{operation:t}),[s]=a;if(!s)throw new i(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:It(this.address,n,n,s,o)});return{...c,unwrapRequestId:this.#c(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=r((await H(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),t=await this.readConfidentialBalanceOf(e);if(V(t))throw new a(`Cannot unshield: balance is zero`);let n=await this.submitTransaction({operation:`unwrapAll`,config:Ae(this.address,e,e,t)});return{...n,unwrapRequestId:this.#c(n.receipt.logs)}}async finalizeUnwrap(e){return this.#s(e,`finalize-unwrap`)}async#s(e,t){this.#r(`finalizeUnwrap`),await U(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e],{operation:t}),r=n.clearValues[e];return O(r,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:Fe(this.address,e,r,n.decryptionProof)})}#c(e){let t=yn(e.filter(e=>e.address===void 0||r(e.address)===this.address));if(!t)throw new A(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t.unwrapRequestId}async#l(e){try{return await this.sdk.provider.readContract(qe(this.address,e))===l}catch{return!1}}async#u(e){let t=e.unwrapRequestId;if(t===void 0)try{let n=await this.sdk.provider.waitForTransactionReceipt(e.unwrapTxHash);t=this.#c(n.logs)}catch{return!1}return this.#l(t)}async#d(e){await k(`${e}: clearPendingUnshield`,()=>Nn(this.sdk.storage,this.address),this.sdk.logger)}async#f(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(tt(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#p(e,t,n,r,i){this.emit({type:j.UnshieldPhase1Submitted,txHash:t,operationId:n}),await k(`unshield: savePendingUnshield`,()=>jn(this.sdk.storage,this.address,t,e),this.sdk.logger),this.emit({type:j.UnshieldPhase2Started,operationId:n}),k(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#s(e,i)}catch(n){throw an(n)?(await this.#d(`unshield`),new tn(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:j.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),k(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#d(`unshield`),a}async#m(e,t,n){this.#r(`approveUnderlying`);let i=await this.#f(),a=r((await H(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),o=await this.sdk.provider.readContract(M(i,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:D(i,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:D(i,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};function Fn(e){return{type:`cleartext`,createRelayer:(t,n)=>{if(!t.executorAddress)throw new v(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new o({chain:t,options:e,cleartext:!0,logger:n})}}}function In(e,t){if(e instanceof _){let n=t[e.code];if(n)return n(e)}return t._?.(e)}var Ln=class extends _{encryptedValue;contractAddress;account;constructor(e,t){super(g.NotEntitled,`Account ${e.account} is not entitled to decrypt encrypted value ${e.encryptedValue} on contract ${e.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,t),this.name=`NotEntitledError`,this.encryptedValue=e.encryptedValue,this.contractAddress=e.contractAddress,this.account=e.account}},Rn=class extends _{constructor(e,t){super(g.DelegationSelfNotAllowed,e,t),this.name=`DelegationSelfNotAllowedError`}},zn=class extends _{constructor(e,t){super(g.DelegationCooldown,e,t),this.name=`DelegationCooldownError`}},X=class extends _{constructor(e,t){super(g.DelegationNotFound,e,t),this.name=`DelegationNotFoundError`}},Bn=class extends _{constructor(e,t){super(g.DelegationExpired,e,t),this.name=`DelegationExpiredError`}},Vn=class extends _{constructor(e,t){super(g.DelegationExpiryUnchanged,e,t),this.name=`DelegationExpiryUnchangedError`}},Hn=class extends _{constructor(e,t){super(g.DelegationDelegateEqualsContract,e,t),this.name=`DelegationDelegateEqualsContractError`}},Un=class extends _{constructor(e,t){super(g.DelegationDelegateCannotBeWildcard,e,t),this.name=`DelegationDelegateCannotBeWildcardError`}},Wn=class extends _{constructor(e,t){super(g.DelegationContractIsSelf,e,t),this.name=`DelegationContractIsSelfError`}},Gn=class extends _{constructor(e,t){super(g.AclPaused,e,t),this.name=`AclPausedError`}},Kn=class extends _{constructor(e,t){super(g.DelegationExpirationTooSoon,e,t),this.name=`DelegationExpirationTooSoonError`}},Z=class extends _{constructor(e,t){super(g.DelegationNotPropagated,e,t),this.name=`DelegationNotPropagatedError`}},qn=[a,ct,h,Z,Dt,P,Ln,R,Ue,F];function Q(e,t,n={}){if(qn.some(t=>e instanceof t))return e;let r=e instanceof Error?e.message:t;if(e instanceof Error&&ge(e.message))return new Ue(e.message,{cause:e});if(be(e))return new F(`The permit's KMS context has been revoked on-chain, so the permit is no longer usable. The SDK evicts the permit and re-grants automatically; if this error surfaced, the retry failed the same way. The on-chain validity check is cached for up to 15 minutes, so a just-revoked context can keep failing across that window. Retry after the window; the SDK re-runs the recovery on the next decrypt, no manual cleanup is needed.`,{cause:e});if(e instanceof Error&&De(e.message))return n.isDelegated?new Z(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:e}):new Ln({encryptedValue:oe(e.message)??``,contractAddress:n.contractAddress??``,account:n.account??``},{cause:e});if(ye(e))return new R(r,{cause:e,retryAfter:y(e)});let i=he(e);return i===void 0&&fe(e)?new R(r,{cause:e,retryAfter:y(e)}):i===400?new ct(e instanceof Error?e.message:`No ciphertext for this account`,{cause:e}):n.isDelegated&&i===500?new Z(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:e}):le(e)||i!==void 0?new h(r,i,{cause:e,retryAfter:y(e),retryable:de(e)||void 0}):new a(t,{cause:e})}function Jn(e,t){if(e instanceof _)return e;let n=he(e),r=de(e);return n!==void 0||le(e)?new h(e instanceof Error?e.message:t,n,{cause:e,retryAfter:y(e),retryable:r||void 0}):new i(t,{cause:e})}var Yn=[{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 Xn(e,t,n,r){return{address:e,abi:Yn,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function Zn(e,t,n){return{address:e,abi:Yn,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function Qn(e,t,n,r){return{address:e,abi:Yn,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function $n(e,t,n,r,i){return{address:e,abi:Yn,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}var $=2n**64n-1n,er=`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`;function tr(e){return it(e.signer,e.provider,e)}var nr=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 N(this.#r,e)}#s(e,t){throw this.#a({type:j.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 U(`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 U(`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=r((await H(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#c(n)}}async clear(){let e=this.#o(`clear`),t=r((await H(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#c(t)}}async#c(e){await k(`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)}},rr=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return N(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let r=this.#r(`delegateDecryption`),i=await H(`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 H(`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)}},ir=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 N(this.#r,e)}async decryptValues(e,t){let n=this.#i(`decryptValues`),r=await H(`decryptValues`,this.#e,this.#t);return n.decryptValues(e,r.address,c(t,`decrypt-values`))}async delegatedDecryptValues(e,t,n=t,r){let i=this.#i(`delegatedDecryptValues`),a=await H(`delegatedDecryptValues`,this.#e,this.#t);return i.delegatedDecryptValues(e,t,a.address,n,c(r,`delegated-decrypt-values`))}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};let n=c(t,`decrypt-public-values`);try{let t=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:n}),r={};return t.checkSignaturesArgs.handlesList.forEach((e,n)=>{Ie(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 Q(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 H(`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`})}},ar=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)}},or=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)}},sr=new or,cr=me([x(),Ee(),I]),lr=Se(ce()),ur=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=cr.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=r(e),n=`${this.#n}:${t}:`,i=await this.#l(),a=[],o=[];for(let e of i)e.startsWith(n)?a.push(e):o.push(e);await Promise.all(a.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,o)}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}:${r(e)}:${r(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=lr.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 dr(e,t){let n=fr(e,t);if(!n)throw new a(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:n.serializedPermit}}function fr(e,t){let n=Me(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}var pr=e=>new Promise(t=>setTimeout(t,e)),mr=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 i=r(t);return this.#s(e,{requesterAddress:i,errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,i,a){let o=r(t),s=r(n),c={spent:!1};return this.#a(a?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:r(i),delegator:o,validate:e=>this.#m(e,{delegatorAddress:o,delegateAddress:s}),errorMessage:`Failed to decrypt delegated encrypted values`},{operation:a?.operation},c))}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 Z))throw t;await pr(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:i,maxConcurrency:a=5,waitForPropagation:o=!0,operation:s}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:r(e.contractAddress)}));if(c.length===0)return{items:c};let l=r(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,l,{waitForPropagation:o,operation:s});for(let t of c)this.#d(t,e);return{items:c}}catch(e){if(B(e))throw e;if(c.length===1){let[n=this.#p()]=c;return n.error=this.#f(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:r(t)}),{items:c}}}let u=!1,d;if(await W(c.map(e=>async()=>{if(!u)try{let r=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,l,{waitForPropagation:!1,operation:s});this.#d(e,r)}catch(n){if(B(n)){u=!0,d??=n;return}e.error=this.#f(n,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:r(t)})}}),a),d!==void 0)throw d;return{items:c}}async#o(e,t,n,r){let i=dr(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&&ge(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,i={spent:!1}){if(e.length===0)return{};let a=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:r(e.contractAddress)})),o={},s=[];for(let e of a)V(e.encryptedValue)?o[e.encryptedValue]=0n:s.push(e);if(s.length===0)return o;let c=Array.from(new Set(a.map(e=>e.contractAddress))),l=Array.from(new Set(s.map(e=>e.contractAddress)));if(t.validate)try{await t.validate(l)}catch(e){throw fe(e)?this.#u(e,`the delegation pre-check`):e}let u=[];for(let e of s){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?u.push(e):o[e.encryptedValue]=n}if(u.length===0)return o;let d=await this.#t.grantPermit(c,t.delegator),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.encryptedValue):f.set(e.contractAddress,[e.encryptedValue])}let p=[];for(let[e,t]of f)for(let n of Xt(t))p.push({contractAddress:e,encryptedValues:n});let ee=Date.now(),m=u.map(e=>e.encryptedValue);try{this.#i({type:j.DecryptStart,encryptedValues:m});try{await this.#c(t,d,p,o,n)}catch(e){if(!(e instanceof F)||i.spent)throw e;let r=d.permissions.map(e=>e.serializedPermit.signature);i.spent=!0;try{d=await this.#t.recoverPermits(c,t.delegator,r)}catch(e){throw e instanceof P?new F(`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,d,p.filter(({encryptedValues:e})=>e.some(e=>o[e]===void 0)),o,n)}let e={};for(let t of m){let n=o[t];n!==void 0&&(e[t]=n)}return this.#i({type:j.DecryptEnd,durationMs:Date.now()-ee,encryptedValues:m,result:e}),o}catch(e){let n=e instanceof _&&e.cause instanceof Error?e.cause:e;throw this.#i({type:j.DecryptError,error:T(n),durationMs:Date.now()-ee,encryptedValues:m}),Q(e,t.errorMessage,{isDelegated:t.delegator!==void 0})}}async#c(e,t,n,r,i){let a=(await W(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 F)??a[0]}async#l(e,t,n,r,i,o){let s;try{s=await this.#o(t,n,r,o)}catch(t){throw Q(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],o=s[t]?.value;a!==void 0&&o!==void 0&&(i[a]=o,await this.#e.set(e.requesterAddress,n,a,o))}let c=r.filter(e=>i[e]===void 0);if(c.length>0)throw new a(`${e.errorMessage}: relayer returned no clear value for ${c.length} of ${r.length} handle(s) on ${n}`,{cause:AggregateError(c.map(e=>new a(`No clear value for handle ${e} on ${n}`)),`${c.length} handle(s) missing a clear value on ${n}`)})}#u(e,t){return new R(`RPC provider rate-limited ${t}; retry with backoff.`,{cause:e,retryAfter:y(e)})}#d(e,t){let n=t[e.encryptedValue];if(n===void 0){e.error=new a(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=n}#f(e,t,n){return e instanceof _?e:Q(e,t,n)}#p(){throw new a(`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}},hr={AlreadyDelegatedOrRevokedInSameBlock:e=>new zn(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new Wn(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new Gn(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new Rn(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new Hn(`Delegate address cannot be the same as the contract address.`,{cause:e}),DelegateCannotBeWildcard:e=>new Un(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new Kn(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new Vn(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new X(`Cannot revoke: no active delegation exists.`,{cause:e})};function gr(e){return Object.hasOwn(hr,e)}function _r(e,t){let n=en(e);if(n&&gr(n))return hr[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(hr))if(r.includes(e))return n(t);return null}var vr=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:i,expirationDate:a}){if(a&&a.getTime()<Date.now()+36e5)throw new Kn(`Expiration date must be at least 1 hour in the future`);let o=r(t),s=r(n),c=r(i);if(s===c)throw new Rn(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===r(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`))throw new Un(`Delegate address cannot be the wildcard address; it can only be used as the contract address.`);if(s===o)throw new Hn(`Delegate address cannot be the same as the contract address (${o}).`);let l=this.#e.relayer.chain.aclContractAddress,u=a?BigInt(Math.floor(a.getTime()/1e3)):$,d;try{d=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),d=-1n}if(d===u)throw new Vn(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return o!==r(`0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF`)&&await this.#i({contractAddress:o,delegatorAddress:c,delegateAddress:s}),this.#s({operation:`delegateDecryption`,signer:e,contractAddress:o,config:Xn(l,s,o,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i}){let a=r(t),o=r(n),s=r(i),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new X(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#s({operation:`revokeDelegation`,signer:e,contractAddress:a,config:Zn(c,o,a)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=r(e.contractAddress)===er,[n,i]=await Promise.all([this.getDelegationExpiry(e),t?Promise.resolve(0n):this.getDelegationExpiry({...e,contractAddress:er})]),a=this.#a(n)||this.#a(i)?await this.#t.getBlockTimestamp():void 0,o=this.#o(n,a);if(o.isActive)return o;let s=this.#o(i,a);return s.isActive?s:n>=i?o:s}async#i(e){try{let{isActive:t}=await this.getStatus({...e,contractAddress:er});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!==$}#o(e,t){return e===0n?{isActive:!1,expiryTimestamp:e}:e===$?{isActive:!0,expiryTimestamp:e}:{isActive:t!==void 0&&e>t,expiryTimestamp:e}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let i=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(Qn(i,r(t),r(n),r(e)))}async#s({operation:e,signer:t,contractAddress:n,config:r}){try{return await Qt({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 A))return;let t=_r(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let i=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof X||t instanceof Bn){let n=r(e);i.set(n,t);return}throw t}})),i}async assertDelegationActive(e,t,n){let i=r(e),a=r(t),o=r(n),{isActive:s,expiryTimestamp:c}=await this.getStatus({contractAddress:i,delegatorAddress:a,delegateAddress:o});if(!s)throw c===0n?new X(`No active delegation from ${a} to ${o} for ${i}`):new Bn(`Delegation from ${a} to ${o} for ${i} has expired`)}},yr=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(e,t){let n=Date.now(),i=r(e.contractAddress);try{this.#t({type:j.EncryptStart},i);let r=await this.#e.relayer.encryptValues({...e,options:t});return this.#t({type:j.EncryptEnd,durationMs:Date.now()-n},i),r}catch(e){throw this.#t({type:j.EncryptError,error:T(e),durationMs:Date.now()-n},i),Jn(e,`Encryption failed`)}}},br=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let t=e.previous,n=e.next,r=n?.chainId;r!==void 0&&await k(`switch relayer chain`,()=>this.#t.switchChain(r),this.#i);let i=this.#r;i&&await k(`credential wallet account change`,()=>i.handleWalletAccountChange(t,n),this.#i),t&&await k(`clear decrypt cache`,()=>this.#n.clearForRequester(t.address),this.#i),await Promise.all(Array.from(this.#a,t=>k(`wallet account listener`,()=>t(e),this.#i)))}},xr=b({kind:C(`ConfidentialTransfer`),from:I,token:I,to:I,amount:x()}),Sr=b({kind:C(`ConfidentialTransferFrom`),from:I,token:I,owner:I,to:I,amount:x()}),Cr=b({kind:C(`SetOperator`),from:I,token:I,operator:I,until:Ge}),wr=b({kind:C(`Unwrap`),from:I,token:I,to:I,amount:x()}),Tr=b({kind:C(`UnwrapAll`),from:I,token:I,to:I}),Er=b({kind:C(`FinalizeUnwrap`),from:I,wrapper:I,unwrapRequestIdOrAmount:L}),Dr=b({kind:C(`ApproveUnderlying`),from:I,underlying:I,spender:I,amount:x()}),Or=b({kind:C(`Wrap`),from:I,wrapper:I,to:I,amount:x()}),kr=L.check(Oe(t=>t===`0x`||e(t)===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`)),Ar=b({kind:C(`TransferAndCall`),from:I,underlying:I,wrapper:I,amount:x(),recipientData:w(kr)}),jr=b({kind:C(`DelegateDecryption`),from:I,contractAddress:I,delegateAddress:I,expirationDate:w(we())}),Mr=b({kind:C(`RevokeDelegation`),from:I,contractAddress:I,delegateAddress:I}),Nr=ve({maxFeePerGas:x(),maxPriorityFeePerGas:x()}),Pr=b({nonce:w(xe().check(Lt())),gasLimit:w(x()),fees:w(Nr)}),Fr=b({address:I,abi:Se(Te()),functionName:ce(),args:Se(Te()),value:w(x()),gas:w(x())}),Ir=Ce(Pr,{from:I,calldata:Fr}),Lr=class{#e;#t;#n;constructor(e){this.#e=e.provider,this.#t=e.router,this.#n=e.encryption}async prepare(e,t){t&&=S(Pr,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=S(Ir,{calldata:await this.#r(e),from:e.from,nonce:t?.nonce,gasLimit:t?.gasLimit,fees:t?.fees}),a=await this.#e.prepareTransaction(i);return{kind:e.kind,unsignedTx:a,from:i.from}}async#r(e){switch(e.kind){case`ConfidentialTransfer`:return this.#i(e);case`ConfidentialTransferFrom`:return this.#a(e);case`SetOperator`:return this.#o(e);case`Unwrap`:return this.#s(e);case`UnwrapAll`:return this.#c(e);case`FinalizeUnwrap`:return this.#l(e);case`ApproveUnderlying`:return this.#u(e);case`Wrap`:return this.#d(e);case`TransferAndCall`:return this.#f(e);case`DelegateDecryption`:return this.#p(e);case`RevokeDelegation`:return this.#m(e);default:throw new v(`OfflineService.prepare: unsupported transaction kind '${e.kind}'.`)}}async#i(e){e=S(xr,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 i(`Encryption returned no handles for ConfidentialTransfer`);return We(e.token,e.to,r,n)}async#a(e){e=S(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-from`}),r=t[0];if(!r)throw new i(`Encryption returned no handles for ConfidentialTransferFrom`);return $e(e.token,e.owner,e.to,r,n)}#o(e){return e=S(Cr,e),Be(e.token,e.operator,e.until)}async#s(e){e=S(wr,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 i(`Encryption returned no handles for Unwrap`);return It(e.token,e.from,e.to,r,n)}async#c(e){e=S(Tr,e);let t=await this.#e.readContract(mt(e.token,e.from));return Ae(e.token,e.from,e.to,t)}async#l(e){e=S(Er,e);let t=await this.#t.relayer.decryptPublicValuesWithSignatures({encryptedValues:[e.unwrapRequestIdOrAmount],options:{operation:`offline-finalize-unwrap`}}).catch(e=>{throw Q(e,`Public decryption failed during FinalizeUnwrap`)}),n=t.clearValues[0]?.value;return O(n,`FinalizeUnwrap: decryptPublicValuesWithSignatures(handle).clearValue`),Fe(e.wrapper,e.unwrapRequestIdOrAmount,n,t.checkSignaturesArgs.decryptionProof)}#u(e){return e=S(Dr,e),D(e.underlying,e.spender,e.amount)}#d(e){return e=S(Or,e),E(e.wrapper,e.to,e.amount)}#f(e){return e=S(Ar,e),sn(e.underlying,e.wrapper,e.amount,e.recipientData)}#p(e){if(e=S(jr,e),e.expirationDate&&e.expirationDate.getTime()<Date.now()+36e5)throw new Kn(`Expiration date must be at least 1 hour in the future`);if(e.delegateAddress===e.from)throw new Rn(`Cannot delegate to yourself (delegate === msg.sender).`);if(e.delegateAddress===e.contractAddress)throw new Hn(`Delegate address cannot be the same as the contract address (${e.contractAddress}).`);let t=e.expirationDate?BigInt(Math.floor(e.expirationDate.getTime()/1e3)):$;return Xn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress,t)}#m(e){return e=S(Mr,e),Zn(this.#t.chain.aclContractAddress,e.delegateAddress,e.contractAddress)}};function Rr(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 zr(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 Br(e){if(e===void 0)return;let t=S(wt,e);return new xt(typeof t==`string`?t:new Uint8Array(t))}var Vr=class{#e;provider;signer;storage;registry;permits;delegations;decryption;offline;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t={}){Rr(t),zr(t.transportKeyPairDerivationSecret);let n=Br(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 ur(e.storage,this.#i),this.#u=new vr({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 Qe({provider:this.provider,registryAddresses:r,registryTTL:e.registryTTL}),this.#n=r,this.#t=e.registryTTL,this.#l=new ot({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 mr({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new yr({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new br({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.#d=new Lr({provider:this.provider,router:e.router,encryption:this.#s,emitEvent:(e,t)=>this.emitEvent(e,t)}),this.permits=new nr({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i,emitEvent:this.emitEvent.bind(this)}),this.delegations=new rr({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new ir({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c}),this.offline=new ar(this.#d,this.#l)}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new Qe({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,c(t,`encrypt`))}createToken(e){return new $t(this,e)}createWrappedToken(e){return new Pn(this,e)}dispose(){this.#o.dispose(),this.#e.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};export{On as ACL_TOPICS,Gn as AclPausedError,Y as AclTopics,Ht as BalanceCheckUnavailableError,bt as BaseSigner,Rt as ChainMismatchError,or as ChromeSessionStorage,v as ConfigurationError,ir as Decryption,a as DecryptionFailedError,ht as DefaultRegistryAddresses,Wn as DelegationContractIsSelfError,zn as DelegationCooldownError,Un as DelegationDelegateCannotBeWildcardError,Hn as DelegationDelegateEqualsContractError,Kn as DelegationExpirationTooSoonError,Bn as DelegationExpiredError,Vn as DelegationExpiryUnchangedError,X as DelegationNotFoundError,Z as DelegationNotPropagatedError,Rn as DelegationSelfNotAllowedError,rr as Delegations,je as ERC1363_INTERFACE_ID,z as ERC20ReadFailedError,Ct as ERC7984_INTERFACE_ID,Re as ERC7984_WRAPPER_INTERFACE_ID,s as EncryptOffloadUnavailableError,i as EncryptionFailedError,dt as IndexedDBStorage,Vt as InsufficientAllowanceError,zt as InsufficientConfidentialBalanceError,Bt as InsufficientERC20BalanceError,Ue as InvalidTransportKeyPairError,ke as KeyWrappingError,$ as MAX_UINT64,yt as MemoryStorage,Ot as MutableWalletAccountStore,ct as NoCiphertextError,Ln as NotEntitledError,ar as Offline,nr as Permits,jt as PreparedPermitChainMismatchError,at as PreparedPermitExpiredError,h as RelayerRequestFailedError,F as RevokedKmsContextError,R as RpcRateLimitError,Ft as SignerNotConfiguredError,Ze as SignerRequiredError,P as SigningFailedError,Dt as SigningRejectedError,xn as TOKEN_TOPICS,$t as Token,J as Topics,A as TransactionRevertedError,kt as TransportKeyPairChangedError,St as TransportKeyPairExpiredError,tn as UnshieldAlreadyFinalizedError,er as WILDCARD_CONTRACT,rt as WalletAccountNotReadyError,ut as WalletNotConnectedError,Pn as WrappedToken,Qe as WrappersRegistry,Jt as ZERO_ENCRYPTED_VALUE,_ as ZamaError,g as ZamaErrorCode,Vr as ZamaSDK,j as ZamaSDKEvents,M as allowanceContract,u as anvil,D as approveContract,He as balanceOfContract,ee as bscTestnet,f as chains,sr as chromeSessionStorage,Fn as cleartext,mt as confidentialBalanceOfContract,Tt as confidentialTotalSupplyContract,We as confidentialTransferContract,$e as confidentialTransferFromContract,tr as createConfig,nt as createWalletAccountStore,ze as decimalsContract,wn as decodeAclEvent,Tn as decodeAclEvents,pn as decodeConfidentialTransfer,Sn as decodeDelegatedForUserDecryption,_n as decodeOnChainEvent,vn as decodeOnChainEvents,Cn as decodeRevokedDelegationForUserDecryption,gn as decodeUnwrapFinalized,hn as decodeUnwrapRequested,mn as decodeWrap,Xn as delegateForUserDecryptionContract,Fe as finalizeUnwrapContract,En as findDelegatedForUserDecryption,Dn as findRevokedDelegationForUserDecryption,yn as findUnwrapRequested,bn as findWrap,_t as getConfidentialTokenAddressContract,Qn as getDelegationExpiryContract,Xe as getTokenAddressContract,lt as getTokenPairContract,et as getTokenPairsContract,st as getTokenPairsLengthContract,Mt as getTokenPairsSliceContract,m as hardhat,p as hoodi,At as indexedDBStorage,Ne as inferredTotalSupplyContract,ie as ingenTestnet,Ye as isConfidentialTokenContract,Pt as isConfidentialTokenValidContract,gt as isConfidentialWrapperContract,V as isEncryptedValueZero,$n as isHandleDelegatedContract,Le as isOperatorContract,pe as isRetryable,ne as mainnet,In as matchZamaError,Et as memoryStorage,pt as nameContract,ae as polygon,d as polygonAmoy,Ve as rateContract,ue as retryAfterSeconds,Zn as revokeDelegationContract,te as sepolia,Be as setOperatorContract,Ke as supportsInterfaceContract,Je as symbolContract,sn as transferAndCallContract,tt as underlyingContract,It as unwrapContract,Ae as unwrapFromBalanceContract,qe as unwrapRequesterContract,E as wrapContract,re as zenithTrexTestnet};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-BcKkbAw3.js";var t=e(((e,t)=>{var n=typeof Reflect==`object`?Reflect:null,r=n&&typeof n.apply==`function`?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},i=n&&typeof n.ownKeys==`function`?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function a(e){console&&console.warn&&console.warn(e)}var o=Number.isNaN||function(e){return e!==e};function s(){s.init.call(this)}t.exports=s,t.exports.once=y,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var c=10;function l(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);c=e}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||o(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function u(e){return e._maxListeners===void 0?s.defaultMaxListeners:e._maxListeners}s.prototype.getMaxListeners=function(){return u(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)r(c,this,t);else for(var l=c.length,u=g(c,l),n=0;n<l;++n)r(u[n],this,t);return!0};function d(e,t,n,r){var i,o,s;if(l(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),s=o[t]),s===void 0)s=o[t]=n,++e._eventsCount;else if(typeof s==`function`?s=o[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=u(e),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=Error(`Possible EventEmitter memory leak detected. `+s.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);c.name=`MaxListenersExceededWarning`,c.emitter=e,c.type=t,c.count=s.length,a(c)}return e}s.prototype.addListener=function(e,t){return d(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return d(this,e,t,!0)};function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=f.bind(r);return i.listener=n,r.wrapFn=i,i}s.prototype.once=function(e,t){return l(t),this.on(e,p(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return l(t),this.prependListener(e,p(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,a,o;if(l(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():_(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function m(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?v(i):g(i,i.length)}s.prototype.listeners=function(e){return m(this,e,!0)},s.prototype.rawListeners=function(e){return m(this,e,!1)},s.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):h.call(e,t)},s.prototype.listenerCount=h;function h(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?i(this._events):[]};function g(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function _(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function v(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function y(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}x(e,t,a,{once:!0}),t!==`error`&&b(e,i,{once:!0})})}function b(e,t,n){typeof e.on==`function`&&x(e,`error`,t,n)}function x(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}}));export{t};
|
package/dist/website/assets/{extrinsic-encoding-B3zynq2U.js → extrinsic-encoding-BIj1XBpl.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./registry-
|
|
1
|
+
import{t as e}from"./registry-BgQw-qJW.js";import{n as t}from"./blake2b-BMPujwy0.js";var n=({metadataRpc:n,signature:r,tx:i})=>{let a=new e;a.setMetadata(a.createType(`Metadata`,n));let o=a.createType(`Extrinsic`,{method:i.method},{version:i.version});return o.addSignature(i.address,r,i),t(o.toU8a())};export{n as encodeSignedExtrinsic};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{H as e,O as t,V as n,d as r,n as i,x as a}from"./ModalController-
|
|
1
|
+
import{H as e,O as t,V as n,d as r,n as i,x as a}from"./ModalController-BhWRBcfd.js";import{n as o,r as s}from"./NetworkUtil-DsIkz0Dz.js";var c=class{constructor(e){this.getNonce=e.getNonce}async createMessage(e){let t={accountAddress:e.accountAddress,chainId:e.chainId,version:`1`,domain:typeof document>`u`?`Unknown Domain`:document.location.host,uri:typeof document>`u`?`Unknown URI`:document.location.href,resources:this.resources,nonce:await this.getNonce(e),issuedAt:this.stringifyDate(new Date),statement:void 0,expirationTime:void 0,notBefore:void 0};return Object.assign(t,{toString:()=>this.stringify(t)})}stringify(e){let t=this.getNetworkName(e.chainId);return[`${e.domain} wants you to sign in with your ${t} account:`,e.accountAddress,e.statement?`\n${e.statement}\n`:``,`URI: ${e.uri}`,`Version: ${e.version}`,`Chain ID: ${e.chainId}`,`Nonce: ${e.nonce}`,e.issuedAt&&`Issued At: ${e.issuedAt}`,e.expirationTime&&`Expiration Time: ${e.expirationTime}`,e.notBefore&&`Not Before: ${e.notBefore}`,e.requestId&&`Request ID: ${e.requestId}`,e.resources?.length&&e.resources.reduce((e,t)=>`${e}\n- ${t}`,`Resources:`)].filter(e=>typeof e==`string`).join(`
|
|
2
2
|
`).trim()}getNetworkName(e){let t=i.getAllRequestedCaipNetworks();return o.getNetworkNameByCaipNetworkId(t,e)}stringifyDate(e){return e.toISOString()}},l=class{constructor(t={}){this.otpUuid=null,this.listeners={sessionChanged:[]},this.localAuthStorageKey=t.localAuthStorageKey||e.SIWX_AUTH_TOKEN,this.localNonceStorageKey=t.localNonceStorageKey||e.SIWX_NONCE_TOKEN,this.required=t.required??!0,this.messenger=new c({getNonce:this.getNonce.bind(this)})}async createMessage(e){return this.messenger.createMessage(e)}async addSession(e){let t=await this.request({method:`POST`,key:`authenticate`,body:{data:e.data,message:e.message,signature:e.signature,clientId:this.getClientId(),walletInfo:this.getWalletInfo()},headers:[`nonce`,`otp`]});this.setStorageToken(t.token,this.localAuthStorageKey),this.emit(`sessionChanged`,e),this.setAppKitAccountUser(u(t.token)),this.otpUuid=null}async getSessions(e,t){try{if(!this.getStorageToken(this.localAuthStorageKey))return[];let n=await this.request({method:`GET`,key:`me`,query:{},headers:[`auth`]});if(!n)return[];let r=n.address.toLowerCase()===t.toLowerCase(),i=n.caip2Network===e;if(!r||!i)return[];let a={data:{accountAddress:n.address,chainId:n.caip2Network},message:``,signature:``};return this.emit(`sessionChanged`,a),this.setAppKitAccountUser(n),[a]}catch{return[]}}async revokeSession(e,t){return Promise.resolve(this.clearStorageTokens())}async setSessions(e){if(e.length===0)this.clearStorageTokens();else{let t=e.find(e=>e.data.chainId===r()?.caipNetworkId)||e[0];await this.addSession(t)}}getRequired(){return this.required}async getSessionAccount(){if(!this.getStorageToken(this.localAuthStorageKey))throw Error(`Not authenticated`);return this.request({method:`GET`,key:`me`,body:void 0,query:{includeAppKitAccount:!0},headers:[`auth`]})}async setSessionAccountMetadata(e=null){if(!this.getStorageToken(this.localAuthStorageKey))throw Error(`Not authenticated`);return this.request({method:`PUT`,key:`account-metadata`,body:{metadata:e},headers:[`auth`]})}on(e,t){return this.listeners[e].push(t),()=>{this.listeners[e]=this.listeners[e].filter(e=>e!==t)}}removeAllListeners(){Object.keys(this.listeners).forEach(e=>{this.listeners[e]=[]})}async requestEmailOtp({email:e,account:t}){let n=await this.request({method:`POST`,key:`otp`,body:{email:e,account:t}});return this.otpUuid=n.uuid,this.messenger.resources=[`email:${e}`],n}confirmEmailOtp({code:e}){return this.request({method:`PUT`,key:`otp`,body:{code:e},headers:[`otp`]})}async request({method:e,key:t,query:n,body:r,headers:i}){let{projectId:a,st:o,sv:c}=this.getSDKProperties(),l=new URL(`${s.W3M_API_URL}/auth/v1/${String(t)}`);l.searchParams.set(`projectId`,a),l.searchParams.set(`st`,o),l.searchParams.set(`sv`,c),n&&Object.entries(n).forEach(([e,t])=>l.searchParams.set(e,String(t)));let u=await fetch(l,{method:e,body:r?JSON.stringify(r):void 0,headers:Array.isArray(i)?i.reduce((e,t)=>{switch(t){case`nonce`:e[`x-nonce-jwt`]=`Bearer ${this.getStorageToken(this.localNonceStorageKey)}`;break;case`auth`:e.Authorization=`Bearer ${this.getStorageToken(this.localAuthStorageKey)}`;break;case`otp`:this.otpUuid&&(e[`x-otp`]=this.otpUuid)}return e},{}):void 0});if(!u.ok)throw Error(await u.text());return u.headers.get(`content-type`)?.includes(`application/json`)?u.json():null}getStorageToken(e){return n.getItem(e)}setStorageToken(e,t){n.setItem(t,e)}clearStorageTokens(){this.otpUuid=null,n.removeItem(this.localAuthStorageKey),n.removeItem(this.localNonceStorageKey),this.emit(`sessionChanged`,void 0)}async getNonce(){let{nonce:e,token:t}=await this.request({method:`GET`,key:`nonce`});return this.setStorageToken(t,this.localNonceStorageKey),e}getClientId(){return t.state.clientId}getWalletInfo(){let e=i.getAccountData()?.connectedWalletInfo;if(!e)return;if(`social`in e&&`identifier`in e)return{type:`social`,social:e.social,identifier:e.identifier};let{name:t,icon:n}=e,r=`unknown`;switch(e.type){case`EXTERNAL`:case`INJECTED`:case`ANNOUNCED`:r=`extension`;break;case`WALLET_CONNECT`:r=`walletconnect`;break;default:r=`unknown`}return{type:r,name:t,icon:n}}getSDKProperties(){return a._getSdkProperties()}emit(e,t){this.listeners[e].forEach(e=>e(t))}setAppKitAccountUser(e){let{email:t}=e;t&&Object.values(s.CHAIN).forEach(e=>{i.setAccountProp(`user`,{email:t},e)})}};function u(e){let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=t[1];if(typeof n!=`string`)throw Error(`Invalid token`);let r=n.replace(/-/gu,`+`).replace(/_/gu,`/`),i=r.padEnd(r.length+(4-r.length%4)%4,`=`);return JSON.parse(atob(i))}export{l as ReownAuthentication};
|