@dcl-regenesislabs/mobile-hub 1.0.0-20601593503.commit-26e252e

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.
Files changed (69) hide show
  1. package/assets/PhArrowCircleDown-BtlNV0TZ.js +14 -0
  2. package/assets/PhArrowClockwise-mOiWYLMV.js +14 -0
  3. package/assets/PhArrowDown-CkoOD89h.js +14 -0
  4. package/assets/PhArrowLeft-C0jlxVhM.js +14 -0
  5. package/assets/PhArrowRight-BI-V03Xf.js +14 -0
  6. package/assets/PhArrowSquareOut-DnQ7n_B4.js +14 -0
  7. package/assets/PhArrowUp-izKvURUW.js +14 -0
  8. package/assets/PhArrowUpRight-Bn-JhHsY.js +14 -0
  9. package/assets/PhArrowsClockwise-Brtx2Re-.js +14 -0
  10. package/assets/PhArrowsDownUp-PZosTqZG.js +14 -0
  11. package/assets/PhArrowsLeftRight-CYsRQ2qh.js +14 -0
  12. package/assets/PhBank-hhPAIPVb.js +14 -0
  13. package/assets/PhBrowser-BjzAmrHO.js +14 -0
  14. package/assets/PhCaretDown-ddSjwcwm.js +14 -0
  15. package/assets/PhCaretLeft-B7YLoNEF.js +14 -0
  16. package/assets/PhCaretRight-BY8D5MIg.js +14 -0
  17. package/assets/PhCaretUp-BG10nSut.js +14 -0
  18. package/assets/PhCheck-DrKd7pBC.js +14 -0
  19. package/assets/PhCircleHalf-Bk9C4DvT.js +14 -0
  20. package/assets/PhClock-Sj17weCB.js +14 -0
  21. package/assets/PhCompass-Df1ugFO-.js +14 -0
  22. package/assets/PhCopy-rgttky8E.js +14 -0
  23. package/assets/PhCreditCard-CZpdid2n.js +14 -0
  24. package/assets/PhCurrencyDollar-B6IKKjue.js +14 -0
  25. package/assets/PhDesktop-BuCDXYJj.js +14 -0
  26. package/assets/PhDeviceMobile-CnybhXY-.js +14 -0
  27. package/assets/PhDotsThree-CSAEcba1.js +14 -0
  28. package/assets/PhEnvelope-SmaNeXoQ.js +14 -0
  29. package/assets/PhFunnelSimple-DKx35ITq.js +14 -0
  30. package/assets/PhGlobe-q1mqj65V.js +14 -0
  31. package/assets/PhIdentificationCard-BeLXJpfZ.js +14 -0
  32. package/assets/PhImage-BYrKfN9k.js +14 -0
  33. package/assets/PhInfo-X33f06Ej.js +14 -0
  34. package/assets/PhLightbulb-DMZJsowR.js +14 -0
  35. package/assets/PhMagnifyingGlass-B6D0sWFL.js +14 -0
  36. package/assets/PhPaperPlaneRight-Dvo-nXr9.js +14 -0
  37. package/assets/PhPlus-CBvZvLax.js +14 -0
  38. package/assets/PhPower-D8-AcNM6.js +14 -0
  39. package/assets/PhPuzzlePiece-C-7mYqGO.js +14 -0
  40. package/assets/PhQrCode-uIXlI5ER.js +14 -0
  41. package/assets/PhQuestion-rUoqC2sC.js +14 -0
  42. package/assets/PhQuestionMark-W55Txvvb.js +14 -0
  43. package/assets/PhSealCheck-BeVLq9PH.js +14 -0
  44. package/assets/PhSignOut-Cq2PivQ6.js +14 -0
  45. package/assets/PhSpinner-CZMtAFdX.js +14 -0
  46. package/assets/PhTrash-BamrmMsN.js +14 -0
  47. package/assets/PhUser-A2fxqIV0.js +14 -0
  48. package/assets/PhVault-B8m1usHw.js +14 -0
  49. package/assets/PhWarning-CpkID9oi.js +14 -0
  50. package/assets/PhWarningCircle-Cm58gXb9.js +14 -0
  51. package/assets/PhX-C3b4cCEy.js +14 -0
  52. package/assets/basic-BqNJI8_e.js +1423 -0
  53. package/assets/core-CHil1RFh.js +217 -0
  54. package/assets/features-C-ekZReg.js +5 -0
  55. package/assets/fortmatic-Fv2dqlKd.js +13 -0
  56. package/assets/index-8e4wv-tH.js +1 -0
  57. package/assets/index-B06SWXYS.js +36 -0
  58. package/assets/index-BH66FyTx.js +23 -0
  59. package/assets/index-Bxs-jmhN.js +15 -0
  60. package/assets/index-CcyN_bjy.css +1 -0
  61. package/assets/index-DoQzB8-2.js +5 -0
  62. package/assets/index-Nz_EXiLp.js +7 -0
  63. package/assets/index-QHMvomuf.js +1 -0
  64. package/assets/index-r-E8-KUv.js +1298 -0
  65. package/assets/property-CnFDNXw5.js +3 -0
  66. package/assets/w3m-modal-DV77a3rm.js +1209 -0
  67. package/index.html +14 -0
  68. package/package.json +22 -0
  69. package/vite.svg +1 -0
@@ -0,0 +1,217 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-B06SWXYS.js","assets/index-BH66FyTx.js","assets/index-CcyN_bjy.css","assets/index-Bxs-jmhN.js","assets/features-C-ekZReg.js","assets/basic-BqNJI8_e.js","assets/index-r-E8-KUv.js","assets/w3m-modal-DV77a3rm.js"])))=>i.map(i=>d[i]);
2
+ import{_ as fo,a as hf,e as Un,x as kc}from"./index-BH66FyTx.js";import{d as Ri,s as go,a as On,c as pf,b as ff,k as gf,e as mf,f as wf,g as hl,I as hr,h as yf,i as qt,t as Et,j as W,l as Us,C as bf,m as vf,n as Ur,o as Fa,p as pr,q as Ef,r as Cf,u as If,v as Af,w as Nf,x as _f,y as Sf,z as us,A as fr,B as Pc,D as Tf,E as Rc,F as xc,G as Wr,P as pl,Q as Of,H as kf,J as bn,K as Vd,L as Es,M as ls,N as Ls,O as Kd}from"./index-Bxs-jmhN.js";var fl={};const D={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos",sui:"Sui",stacks:"Stacks"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],SOLANA_SPL_TOKEN_ADDRESSES:{SOL:"So11111111111111111111111111111111111111112"},HTTP_STATUS_CODES:{SERVER_ERROR:500,TOO_MANY_REQUESTS:429,SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof process<"u"&&typeof fl<"u"?fl.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",REMOTE_FEATURES_ALERTS:{MULTI_WALLET_NOT_ENABLED:{DEFAULT:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com."},CONNECTIONS_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnections hook."},CONNECTION_HOOK:{displayMessage:"Multi-Wallet Not Enabled",debugMessage:"Multi-wallet support is not enabled. Please enable it in your AppKit configuration at cloud.reown.com to use the useAppKitConnection hook."}}},IS_DEVELOPMENT:typeof process<"u"&&!1,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://localhost:*","http://127.0.0.1:*","https://127.0.0.1:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]},zd={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(s=>s.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const s=t.find(r=>r.caipNetworkId===e);if(s)return s.name;const[n]=e.split(":");return D.CHAIN_NAME_MAP?.[n]||void 0}},Gd=["eip155","solana","polkadot","bip122","cosmos","sui","stacks"];var Pf=20,Rf=1,kn=1e6,gl=1e6,xf=-7,$f=21,Uf=!1,vi="[big.js] ",Dn=vi+"Invalid ",Lo=Dn+"decimal places",Df=Dn+"rounding mode",Yd=vi+"Division by zero",Se={},gs=void 0,Lf=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Jd(){function t(e){var s=this;if(!(s instanceof t))return e===gs?Jd():new t(e);if(e instanceof t)s.s=e.s,s.e=e.e,s.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(Dn+"value");e=e===0&&1/e<0?"-0":String(e)}Mf(s,e)}s.constructor=t}return t.prototype=Se,t.DP=Pf,t.RM=Rf,t.NE=xf,t.PE=$f,t.strict=Uf,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function Mf(t,e){var s,n,r;if(!Lf.test(e))throw Error(Dn+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(s=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(s<0&&(s=n),s+=+e.slice(n+1),e=e.substring(0,n)):s<0&&(s=e.length),r=e.length,n=0;n<r&&e.charAt(n)=="0";)++n;if(n==r)t.c=[t.e=0];else{for(;r>0&&e.charAt(--r)=="0";);for(t.e=s-n-1,t.c=[],s=0;n<=r;)t.c[s++]=+e.charAt(n++)}return t}function Ln(t,e,s,n){var r=t.c;if(s===gs&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(Df);if(e<1)n=s===3&&(n||!!r[0])||e===0&&(s===1&&r[0]>=5||s===2&&(r[0]>5||r[0]===5&&(n||r[1]!==gs))),r.length=1,n?(t.e=t.e-e+1,r[0]=1):r[0]=t.e=0;else if(e<r.length){if(n=s===1&&r[e]>=5||s===2&&(r[e]>5||r[e]===5&&(n||r[e+1]!==gs||r[e-1]&1))||s===3&&(n||!!r[0]),r.length=e,n){for(;++r[--e]>9;)if(r[e]=0,e===0){++t.e,r.unshift(1);break}}for(e=r.length;!r[--e];)r.pop()}return t}function Mn(t,e,s){var n=t.e,r=t.c.join(""),i=r.length;if(e)r=r.charAt(0)+(i>1?"."+r.slice(1):"")+(n<0?"e":"e+")+n;else if(n<0){for(;++n;)r="0"+r;r="0."+r}else if(n>0)if(++n>i)for(n-=i;n--;)r+="0";else n<i&&(r=r.slice(0,n)+"."+r.slice(n));else i>1&&(r=r.charAt(0)+"."+r.slice(1));return t.s<0&&s?"-"+r:r}Se.abs=function(){var t=new this.constructor(this);return t.s=1,t};Se.cmp=function(t){var e,s=this,n=s.c,r=(t=new s.constructor(t)).c,i=s.s,o=t.s,a=s.e,c=t.e;if(!n[0]||!r[0])return n[0]?i:r[0]?-o:0;if(i!=o)return i;if(e=i<0,a!=c)return a>c^e?1:-1;for(o=(a=n.length)<(c=r.length)?a:c,i=-1;++i<o;)if(n[i]!=r[i])return n[i]>r[i]^e?1:-1;return a==c?0:a>c^e?1:-1};Se.div=function(t){var e=this,s=e.constructor,n=e.c,r=(t=new s(t)).c,i=e.s==t.s?1:-1,o=s.DP;if(o!==~~o||o<0||o>kn)throw Error(Lo);if(!r[0])throw Error(Yd);if(!n[0])return t.s=i,t.c=[t.e=0],t;var a,c,l,u,d,h=r.slice(),p=a=r.length,f=n.length,g=n.slice(0,a),w=g.length,C=t,v=C.c=[],_=0,L=o+(C.e=e.e-t.e)+1;for(C.s=i,i=L<0?0:L,h.unshift(0);w++<a;)g.push(0);do{for(l=0;l<10;l++){if(a!=(w=g.length))u=a>w?1:-1;else for(d=-1,u=0;++d<a;)if(r[d]!=g[d]){u=r[d]>g[d]?1:-1;break}if(u<0){for(c=w==a?r:h;w;){if(g[--w]<c[w]){for(d=w;d&&!g[--d];)g[d]=9;--g[d],g[w]+=10}g[w]-=c[w]}for(;!g[0];)g.shift()}else break}v[_++]=u?l:++l,g[0]&&u?g[w]=n[p]||0:g=[n[p]]}while((p++<f||g[0]!==gs)&&i--);return!v[0]&&_!=1&&(v.shift(),C.e--,L--),_>L&&Ln(C,L,s.RM,g[0]!==gs),C};Se.eq=function(t){return this.cmp(t)===0};Se.gt=function(t){return this.cmp(t)>0};Se.gte=function(t){return this.cmp(t)>-1};Se.lt=function(t){return this.cmp(t)<0};Se.lte=function(t){return this.cmp(t)<1};Se.minus=Se.sub=function(t){var e,s,n,r,i=this,o=i.constructor,a=i.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,i.plus(t);var l=i.c.slice(),u=i.e,d=t.c,h=t.e;if(!l[0]||!d[0])return d[0]?t.s=-c:l[0]?t=new o(i):t.s=1,t;if(a=u-h){for((r=a<0)?(a=-a,n=l):(h=u,n=d),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(s=((r=l.length<d.length)?l:d).length,a=c=0;c<s;c++)if(l[c]!=d[c]){r=l[c]<d[c];break}if(r&&(n=l,l=d,d=n,t.s=-t.s),(c=(s=d.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;s>a;){if(l[--s]<d[s]){for(e=s;e&&!l[--e];)l[e]=9;--l[e],l[s]+=10}l[s]-=d[s]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--h;return l[0]||(t.s=1,l=[h=0]),t.c=l,t.e=h,t};Se.mod=function(t){var e,s=this,n=s.constructor,r=s.s,i=(t=new n(t)).s;if(!t.c[0])throw Error(Yd);return s.s=t.s=1,e=t.cmp(s)==1,s.s=r,t.s=i,e?new n(s):(r=n.DP,i=n.RM,n.DP=n.RM=0,s=s.div(t),n.DP=r,n.RM=i,this.minus(s.times(t)))};Se.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};Se.plus=Se.add=function(t){var e,s,n,r=this,i=r.constructor;if(t=new i(t),r.s!=t.s)return t.s=-t.s,r.minus(t);var o=r.e,a=r.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new i(r):t.s=r.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,n=l):(e=-e,n=a),n.reverse();e--;)n.push(0);n.reverse()}for(a.length-l.length<0&&(n=l,l=a,a=n),e=l.length,s=0;e;a[e]%=10)s=(a[--e]=a[e]+l[e]+s)/10|0;for(s&&(a.unshift(s),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t};Se.pow=function(t){var e=this,s=new e.constructor("1"),n=s,r=t<0;if(t!==~~t||t<-gl||t>gl)throw Error(Dn+"exponent");for(r&&(t=-t);t&1&&(n=n.times(e)),t>>=1,!!t;)e=e.times(e);return r?s.div(n):n};Se.prec=function(t,e){if(t!==~~t||t<1||t>kn)throw Error(Dn+"precision");return Ln(new this.constructor(this),t,e)};Se.round=function(t,e){if(t===gs)t=0;else if(t!==~~t||t<-kn||t>kn)throw Error(Lo);return Ln(new this.constructor(this),t+this.e+1,e)};Se.sqrt=function(){var t,e,s,n=this,r=n.constructor,i=n.s,o=n.e,a=new r("0.5");if(!n.c[0])return new r(n);if(i<0)throw Error(vi+"No square root");i=Math.sqrt(+Mn(n,!0,!0)),i===0||i===1/0?(e=n.c.join(""),e.length+o&1||(e+="0"),i=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new r((i==1/0?"5e":(i=i.toExponential()).slice(0,i.indexOf("e")+1))+o)):t=new r(i+""),o=t.e+(r.DP+=4);do s=t,t=a.times(s.plus(n.div(s)));while(s.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return Ln(t,(r.DP-=4)+t.e+1,r.RM)};Se.times=Se.mul=function(t){var e,s=this,n=s.constructor,r=s.c,i=(t=new n(t)).c,o=r.length,a=i.length,c=s.e,l=t.e;if(t.s=s.s==t.s?1:-1,!r[0]||!i[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=r,r=i,i=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+i[c]*r[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t};Se.toExponential=function(t,e){var s=this,n=s.c[0];if(t!==gs){if(t!==~~t||t<0||t>kn)throw Error(Lo);for(s=Ln(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return Mn(s,!0,!!n)};Se.toFixed=function(t,e){var s=this,n=s.c[0];if(t!==gs){if(t!==~~t||t<0||t>kn)throw Error(Lo);for(s=Ln(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return Mn(s,!1,!!n)};Se[Symbol.for("nodejs.util.inspect.custom")]=Se.toJSON=Se.toString=function(){var t=this,e=t.constructor;return Mn(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};Se.toNumber=function(){var t=+Mn(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(vi+"Imprecise conversion");return t};Se.toPrecision=function(t,e){var s=this,n=s.constructor,r=s.c[0];if(t!==gs){if(t!==~~t||t<1||t>kn)throw Error(Dn+"precision");for(s=Ln(new n(s),t,e);s.c.length<t;)s.c.push(0)}return Mn(s,t<=s.e||s.e<=n.NE||s.e>=n.PE,!!r)};Se.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(vi+"valueOf disallowed");return Mn(t,t.e<=e.NE||t.e>=e.PE,!0)};var Ms=Jd();const Bf={bigNumber(t){return t?new Ms(t):new Ms(0)},multiply(t,e){if(t===void 0||e===void 0)return new Ms(0);const s=new Ms(t),n=new Ms(e);return s.times(n)},toFixed(t,e=2){return t===void 0||t===""?new Ms(0).toFixed(e):new Ms(t).toFixed(e)},formatNumberToLocalString(t,e=2){return t===void 0||t===""?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e,roundingMode:"floor"})},parseLocalStringToNumber(t){if(t===void 0||t==="")return 0;const e=t.replace(/,/gu,"");return new Ms(e).toNumber()}},jf=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],Ff=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],qf=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],Wf={getERC20Abi:t=>D.USDT_CONTRACT_ADDRESSES.includes(t)?qf:jf,getSwapAbi:()=>Ff},Ze={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,n,r]=e;if(!s||!n||!r)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:n,address:r}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,n]=e;if(!s||!n)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:n}}},Ts={RPC_ERROR_CODE:{USER_REJECTED_REQUEST:4001,USER_REJECTED_METHODS:5002,USER_REJECTED:5e3},PROVIDER_RPC_ERROR_NAME:{PROVIDER_RPC:"ProviderRpcError",USER_REJECTED_REQUEST:"UserRejectedRequestError"},isRpcProviderError(t){try{if(typeof t=="object"&&t!==null){const e=t,s=typeof e.message=="string",n=typeof e.code=="number";return s&&n}return!1}catch{return!1}},isUserRejectedMessage(t){return t.toLowerCase().includes("user rejected")||t.toLowerCase().includes("user cancelled")||t.toLowerCase().includes("user canceled")},isUserRejectedRequestError(t){if(Ts.isRpcProviderError(t)){const e=t.code===Ts.RPC_ERROR_CODE.USER_REJECTED_REQUEST,s=t.code===Ts.RPC_ERROR_CODE.USER_REJECTED_METHODS;return e||s||Ts.isUserRejectedMessage(t.message)}return t instanceof Error?Ts.isUserRejectedMessage(t.message):!1}};let Hf=class extends Error{constructor(e,s){super(s.message,{cause:e}),this.name=Ts.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=s.code}},Xd=class extends Hf{constructor(e){super(e,{code:Ts.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=Ts.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}};const ee={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",RECENT_WALLET:"@appkit/recent_wallet",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections",DISCONNECTED_CONNECTOR_IDS:"@appkit/disconnected_connector_ids",HISTORY_TRANSACTIONS_CACHE:"@appkit/history_transactions_cache",TOKEN_PRICE_CACHE:"@appkit/token_price_cache",RECENT_EMAILS:"@appkit/recent_emails",LATEST_APPKIT_VERSION:"@appkit/latest_version"};function ea(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const X={setItem(t,e){kr()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(kr())return localStorage.getItem(t)||void 0},removeItem(t){kr()&&localStorage.removeItem(t)},clear(){kr()&&localStorage.clear()}};function kr(){return typeof window<"u"&&typeof localStorage<"u"}function mo(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const Vf=Symbol(),ml=Object.getPrototypeOf,qa=new WeakMap,Kf=t=>t&&(qa.has(t)?qa.get(t):ml(t)===Object.prototype||ml(t)===Array.prototype),zf=t=>Kf(t)&&t[Vf]||null,wl=(t,e=!0)=>{qa.set(t,e)},wo={},$c=t=>typeof t=="object"&&t!==null,Gf=t=>$c(t)&&!Ei.has(t)&&(Array.isArray(t)||!(Symbol.iterator in t))&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!(t instanceof Error)&&!(t instanceof Number)&&!(t instanceof Date)&&!(t instanceof String)&&!(t instanceof RegExp)&&!(t instanceof ArrayBuffer)&&!(t instanceof Promise),Zd=(t,e)=>{const s=Wa.get(t);if(s?.[0]===e)return s[1];const n=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return wl(n,!0),Wa.set(t,[e,n]),Reflect.ownKeys(t).forEach(r=>{if(Object.getOwnPropertyDescriptor(n,r))return;const i=Reflect.get(t,r),{enumerable:o}=Reflect.getOwnPropertyDescriptor(t,r),a={value:i,enumerable:o,configurable:!0};if(Ei.has(i))wl(i,!1);else if(nn.has(i)){const[c,l]=nn.get(i);a.value=Zd(c,l())}Object.defineProperty(n,r,a)}),Object.preventExtensions(n)},Yf=(t,e,s,n)=>({deleteProperty(r,i){const o=Reflect.get(r,i);s(i);const a=Reflect.deleteProperty(r,i);return a&&n(["delete",[i],o]),a},set(r,i,o,a){const c=!t()&&Reflect.has(r,i),l=Reflect.get(r,i,a);if(c&&(yl(l,o)||Hr.has(o)&&yl(l,Hr.get(o))))return!0;s(i),$c(o)&&(o=zf(o)||o);const u=!nn.has(o)&&Xf(o)?Re(o):o;return e(i,u),Reflect.set(r,i,u,a),n(["set",[i],o,l]),!0}}),nn=new WeakMap,Ei=new WeakSet,Wa=new WeakMap,so=[1],Hr=new WeakMap;let yl=Object.is,Jf=(t,e)=>new Proxy(t,e),Xf=Gf,Zf=Zd,Qf=Yf;function Re(t={}){if(!$c(t))throw new Error("object required");const e=Hr.get(t);if(e)return e;let s=so[0];const n=new Set,r=(w,C=++so[0])=>{s!==C&&(i=s=C,n.forEach(v=>v(w,C)))};let i=s;const o=(w=so[0])=>(i!==w&&(i=w,c.forEach(([C])=>{const v=C[1](w);v>s&&(s=v)})),s),a=w=>(C,v)=>{const _=[...C];_[1]=[w,..._[1]],r(_,v)},c=new Map,l=(w,C)=>{const v=!Ei.has(C)&&nn.get(C);if(v){if((wo?"production":void 0)!=="production"&&c.has(w))throw new Error("prop listener already exists");if(n.size){const _=v[2](a(w));c.set(w,[v,_])}else c.set(w,[v])}},u=w=>{var C;const v=c.get(w);v&&(c.delete(w),(C=v[1])==null||C.call(v))},d=w=>(n.add(w),n.size===1&&c.forEach(([v,_],L)=>{if((wo?"production":void 0)!=="production"&&_)throw new Error("remove already exists");const B=v[2](a(L));c.set(L,[v,B])}),()=>{n.delete(w),n.size===0&&c.forEach(([v,_],L)=>{_&&(_(),c.set(L,[v]))})});let h=!0;const p=Qf(()=>h,l,u,r),f=Jf(t,p);Hr.set(t,f);const g=[t,o,d];return nn.set(f,g),Reflect.ownKeys(t).forEach(w=>{const C=Object.getOwnPropertyDescriptor(t,w);"value"in C&&C.writable&&(f[w]=t[w])}),h=!1,f}function Qe(t,e,s){const n=nn.get(t);(wo?"production":void 0)!=="production"&&!n&&console.warn("Please use proxy object");let r;const i=[],o=n[2];let a=!1;const l=o(u=>{i.push(u),r||(r=Promise.resolve().then(()=>{r=void 0,a&&e(i.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Vr(t){const e=nn.get(t);(wo?"production":void 0)!=="production"&&!e&&console.warn("Please use proxy object");const[s,n]=e;return Zf(s,n())}function Kr(t){return Ei.add(t),t}function eg(){return{proxyStateMap:nn,refSet:Ei,snapCache:Wa,versionHolder:so,proxyCache:Hr}}function et(t,e,s,n){let r=t[e];return Qe(t,()=>{const i=t[e];Object.is(r,i)||s(r=i)})}const{proxyStateMap:tg,snapCache:sg}=eg(),xi=t=>tg.has(t);function ng(t){const e=[];let s=0;const n=new Map,r=new WeakMap,i=()=>{const l=sg.get(a),u=l?.[1];if(u&&!r.has(u)){const d=new Map(n);r.set(u,d)}},o=l=>r.get(l)||n,a={data:e,index:s,epoch:0,get size(){return xi(this)||i(),o(this).size},get(l){const d=o(this).get(l);if(d===void 0){this.epoch;return}return this.data[d]},has(l){const u=o(this);return this.epoch,u.has(l)},set(l,u){if(!xi(this))throw new Error("Cannot perform mutations on a snapshot");const d=n.get(l);return d===void 0?(n.set(l,this.index),this.data[this.index++]=u):this.data[d]=u,this.epoch++,this},delete(l){if(!xi(this))throw new Error("Cannot perform mutations on a snapshot");const u=n.get(l);return u===void 0?!1:(delete this.data[u],n.delete(l),this.epoch++,!0)},clear(){if(!xi(this))throw new Error("Cannot perform mutations on a snapshot");this.data.length=0,this.index=0,this.epoch++,n.clear()},forEach(l){this.epoch,o(this).forEach((d,h)=>{l(this.data[d],h,this)})},*entries(){this.epoch;const l=o(this);for(const[u,d]of l)yield[u,this.data[d]]},*keys(){this.epoch;const l=o(this);for(const u of l.keys())yield u},*values(){this.epoch;const l=o(this);for(const u of l.values())yield this.data[u]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=Re(a);return Object.defineProperties(c,{size:{enumerable:!1},index:{enumerable:!1},epoch:{enumerable:!1},data:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(c),c}var bl={};const ta=(typeof process<"u"&&typeof bl<"u"?bl.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",Qd=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],rg="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",we={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:ta,SECURE_SITE_DASHBOARD:`${ta}/dashboard`,SECURE_SITE_FAVICON:`${ta}/images/favicon.png`,SOLANA_NATIVE_TOKEN_ADDRESS:"So11111111111111111111111111111111111111111",RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],SUGGESTED_TOKENS_BY_CHAIN:{"eip155:42161":["USD₮0"]},BALANCE_SUPPORTED_CHAINS:[D.CHAIN.EVM,D.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[D.CHAIN.EVM],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:[D.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[D.CHAIN.EVM,D.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[D.CHAIN.EVM,D.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[D.CHAIN.EVM],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:[D.CHAIN.EVM,D.CHAIN.SOLANA],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0,multiWallet:!1,emailCapture:!1,payWithExchange:!1,payments:!1,reownAuthentication:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1,reownAuthentication:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0}},x={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=x.getActiveNamespace(),e=x.getActiveCaipNetworkId(),s=e?e.split(":")[1]:void 0,n=s?isNaN(Number(s))?s:Number(s):void 0;return{namespace:t,caipNetworkId:e,chainId:n}},setWalletConnectDeepLink({name:t,href:e}){try{X.setItem(ee.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=X.getItem(ee.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{X.removeItem(ee.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{X.setItem(ee.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{X.setItem(ee.ACTIVE_CAIP_NETWORK_ID,t),x.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return X.getItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{X.removeItem(ee.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=ea(t);X.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=x.getRecentWallets();e.find(n=>n.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),X.setItem(ee.RECENT_WALLETS,JSON.stringify(e)),X.setItem(ee.RECENT_WALLET,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=X.getItem(ee.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const t=X.getItem(ee.RECENT_WALLET);return t?JSON.parse(t):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{X.removeItem(ee.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(t,e){try{const s=ea(t);X.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return X.getItem(ee.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=ea(t);return X.getItem(e)}catch{console.info("Unable to get connected connector id in namespace",t)}},setConnectedSocialProvider(t){try{X.setItem(ee.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return X.getItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{X.removeItem(ee.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return X.getItem(ee.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return X.getItem(ee.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{X.setItem(ee.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return X.getItem(ee.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=X.getItem(ee.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));X.setItem(ee.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=x.getConnectedNamespaces();e.includes(t)||(e.push(t),x.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=x.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),x.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return X.getItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{X.setItem(ee.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{X.removeItem(ee.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=X.getItem(ee.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=x.getBalanceCache();X.setItem(ee.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=x.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;x.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=x.getBalanceCache();e[t.caipAddress]=t,X.setItem(ee.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=X.getItem(ee.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=x.getBalanceCache();X.setItem(ee.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const s=x.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),x.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=x.getNativeBalanceCache();e[t.caipAddress]=t,X.setItem(ee.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=X.getItem(ee.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const s=x.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;x.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=x.getEnsCache();e[t.address]=t,X.setItem(ee.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=x.getEnsCache();X.setItem(ee.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=X.getItem(ee.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=x.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;x.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=x.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},X.setItem(ee.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=x.getIdentityCache();X.setItem(ee.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{X.removeItem(ee.PORTFOLIO_CACHE),X.removeItem(ee.NATIVE_BALANCE_CACHE),X.removeItem(ee.ENS_CACHE),X.removeItem(ee.IDENTITY_CACHE),X.removeItem(ee.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{X.setItem(ee.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=X.getItem(ee.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s=x.getConnections(),n=s[e]??[],r=new Map;for(const o of n)r.set(o.connectorId,{...o});for(const o of t){const a=r.get(o.connectorId),c=o.connectorId===D.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(d=>d.address.toLowerCase())),u=o.accounts.filter(d=>!l.has(d.address.toLowerCase()));a.accounts.push(...u)}else r.set(o.connectorId,{...o})}const i={...s,[e]:Array.from(r.values())};X.setItem(ee.CONNECTIONS,JSON.stringify(i))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=X.getItem(ee.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}},deleteAddressFromConnection({connectorId:t,address:e,namespace:s}){try{const n=x.getConnections(),r=n[s]??[],i=new Map(r.map(a=>[a.connectorId,a])),o=i.get(t);o&&(o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase()).length===0?i.delete(t):i.set(t,{...o,accounts:o.accounts.filter(c=>c.address.toLowerCase()!==e.toLowerCase())})),X.setItem(ee.CONNECTIONS,JSON.stringify({...n,[s]:Array.from(i.values())}))}catch{console.error(`Unable to remove address "${e}" from connector "${t}" in namespace "${s}"`)}},getDisconnectedConnectorIds(){try{const t=X.getItem(ee.DISCONNECTED_CONNECTOR_IDS);return t?JSON.parse(t):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(t,e){try{const s=x.getDisconnectedConnectorIds(),n=s[e]??[];n.push(t),X.setItem(ee.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[e]:Array.from(new Set(n))}))}catch{console.error(`Unable to set disconnected connector id "${t}" for namespace "${e}"`)}},removeDisconnectedConnectorId(t,e){try{const s=x.getDisconnectedConnectorIds();let n=s[e]??[];n=n.filter(r=>r.toLowerCase()!==t.toLowerCase()),X.setItem(ee.DISCONNECTED_CONNECTOR_IDS,JSON.stringify({...s,[e]:Array.from(new Set(n))}))}catch{console.error(`Unable to remove disconnected connector id "${t}" for namespace "${e}"`)}},isConnectorDisconnected(t,e){try{return(x.getDisconnectedConnectorIds()[e]??[]).some(r=>r.toLowerCase()===t.toLowerCase())}catch{console.info(`Unable to get disconnected connector id "${t}" for namespace "${e}"`)}return!1},getTransactionsCache(){try{const t=X.getItem(ee.HISTORY_TRANSACTIONS_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:t,chainId:e=""}){try{const n=x.getTransactionsCache()[t]?.[e];if(n&&!this.isCacheExpired(n.timestamp,this.cacheExpiry.transactionsHistory))return n.transactions;x.removeTransactionsCache({address:t,chainId:e})}catch{console.info("Unable to get transactions cache")}},updateTransactionsCache({address:t,chainId:e="",timestamp:s,transactions:n}){try{const r=x.getTransactionsCache();r[t]={...r[t],[e]:{timestamp:s,transactions:n}},X.setItem(ee.HISTORY_TRANSACTIONS_CACHE,JSON.stringify(r))}catch{console.info("Unable to update transactions cache",{address:t,chainId:e,timestamp:s,transactions:n})}},removeTransactionsCache({address:t,chainId:e}){try{const s=x.getTransactionsCache(),n=s?.[t]||{},{[e]:r,...i}=n;X.setItem(ee.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...s,[t]:i}))}catch{console.info("Unable to remove transactions cache",{address:t,chainId:e})}},getTokenPriceCache(){try{const t=X.getItem(ee.TOKEN_PRICE_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(t){try{const s=x.getTokenPriceCache()[t.join(",")];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.tokenPrice))return s.tokenPrice;x.removeTokenPriceCache(t)}catch{console.info("Unable to get token price cache for addresses",t)}},updateTokenPriceCache(t){try{const e=x.getTokenPriceCache();e[t.addresses.join(",")]={timestamp:t.timestamp,tokenPrice:t.tokenPrice},X.setItem(ee.TOKEN_PRICE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update token price cache",t)}},removeTokenPriceCache(t){try{const e=x.getTokenPriceCache();X.setItem(ee.TOKEN_PRICE_CACHE,JSON.stringify({...e,[t.join(",")]:void 0}))}catch{console.info("Unable to remove token price cache",t)}},getLatestAppKitVersion(){try{const t=this.getLatestAppKitVersionCache(),e=t?.version;return e&&!this.isCacheExpired(t.timestamp,this.cacheExpiry.latestAppKitVersion)?e:void 0}catch{console.info("Unable to get latest AppKit version")}},getLatestAppKitVersionCache(){try{const t=X.getItem(ee.LATEST_APPKIT_VERSION);return t?JSON.parse(t):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(t){try{const e=x.getLatestAppKitVersionCache();e.timestamp=t.timestamp,e.version=t.version,X.setItem(ee.LATEST_APPKIT_VERSION,JSON.stringify(e))}catch{console.info("Unable to update latest AppKit version on local storage",t)}}},G={isMobile(){return this.isClient()?!!(window?.matchMedia&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return G.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=we.TEN_SEC_MS:!0},isAllowedRetry(t,e=we.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(G.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const s=new URL(t),n=new URL(e);return s.hostname===n.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+we.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let s;return(...n)=>{function r(){t(...n)}s&&clearTimeout(s),s=setTimeout(r,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(G.isHttpUrl(t))return this.formatUniversalUrl(t,e);let n=t,r=s;n.includes("://")||(n=t.replaceAll("/","").replaceAll(":",""),n=`${n}://`),n.endsWith("/")||(n=`${n}/`),r&&!r?.endsWith("/")&&(r=`${r}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const i=encodeURIComponent(e);return{redirect:`${n}wc?uri=${i}`,redirectUniversalLink:r?`${r}wc?uri=${i}`:void 0,href:n}},formatUniversalUrl(t,e){if(!G.isHttpUrl(t))return this.formatNativeUrl(t,e);let s=t;s.endsWith("/")||(s=`${s}/`);const n=encodeURIComponent(e);return{redirect:`${s}wc?uri=${n}`,href:s}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?x.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window?.matchMedia&&typeof window.matchMedia=="function"?window.matchMedia("(display-mode: standalone)")?.matches:!1,e=window?.navigator?.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,n)=>{const r=new Image;r.onload=s,r.onerror=n,r.crossOrigin="anonymous",r.src=t});return Promise.race([e,G.wait(2e3)])},parseBalance(t,e){let s="0.000";if(typeof t=="string"){const c=Number(t);if(!isNaN(c)){const l=(Math.floor(c*1e3)/1e3).toFixed(3);l&&(s=l)}}const[n,r]=s.split("."),i=n||"0",o=r||"000";return{formattedText:`${i}.${o}${e?` ${e}`:""}`,value:i,decimals:o,symbol:e}},getApiUrl(){return D.W3M_API_URL},getBlockchainApiUrl(){return D.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return D.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const s={};return e&&t&&(t.forEach((n,r)=>{s[n]=r}),e.sort((n,r)=>{const i=s[n.id],o=s[r.id];return i!==void 0&&o!==void 0?i-o:i!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const s of t)e+=s.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[s,n]=e.split(".");return{dollars:s,pennies:n}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const s=new Set;return t.filter(n=>{const r=n[e];return s.has(r)?!1:(s.add(r),!0)})},generateSdkVersion(t,e,s){const r=t.length===0?we.ADAPTER_TYPES.UNIVERSAL:t.map(i=>i.adapterType).join(",");return`${e}-${r}-${s}`},createAccount(t,e,s,n,r){return{namespace:t,address:e,type:s,publicKey:n,path:r}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),s=e[0];return e.filter(Boolean).length===3&&s in D.CHAIN_NAME_MAP},getAccount(t){return t?typeof t=="string"?{address:t,chainId:void 0}:{address:t.address,chainId:t.chainId}:{address:void 0,chainId:void 0}},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const r="provider_authorization_url=",i=t.substring(t.indexOf(r)+r.length),o=this.injectIntoUrl(decodeURIComponent(i),s,e);return t.replace(i,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const n=t.indexOf(e);if(n===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const r=t.indexOf("&",n),i=e.length,o=r!==-1?r:t.length,a=t.substring(0,n+i),c=t.substring(n+i,o),l=t.substring(r),u=c+s;return a+u+l}},no={STORAGE_KEY:"@appkit-wallet/",SMART_ACCOUNT_ENABLED_NETWORKS:"SMART_ACCOUNT_ENABLED_NETWORKS"},Os={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},ig={set(t,e){sa.isClient&&localStorage.setItem(`${no.STORAGE_KEY}${t}`,e)},get(t){return sa.isClient?localStorage.getItem(`${no.STORAGE_KEY}${t}`):null},delete(t,e){sa.isClient&&(e?localStorage.removeItem(t):localStorage.removeItem(`${no.STORAGE_KEY}${t}`))}},sa={isClient:typeof window<"u"};function og(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function vl(t){return og(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const eh="2.43.3";let na={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${eh}`};class Te extends Error{constructor(e,s={}){const n=s.cause instanceof Te?s.cause.details:s.cause?.message?s.cause.message:s.details,r=s.cause instanceof Te&&s.cause.docsPath||s.docsPath,i=na.getDocsUrl?.({...s,docsPath:r}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...na.version?[`Version: ${na.version}`]:[]].join(`
3
+ `);super(o,s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=r,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=eh}walk(e){return th(this,e)}}function th(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?th(t.cause,e):e?null:t}class dS extends Te{constructor({offset:e,position:s,size:n}){super(`Slice ${s==="start"?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}class sh extends Te{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}}class hS extends Te{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} is expected to be ${s} ${n} long, but is ${e} ${n} long.`,{name:"InvalidBytesLengthError"})}}function Uc(t,{dir:e,size:s=32}={}){return typeof t=="string"?ag(t,{dir:e,size:s}):cg(t,{dir:e,size:s})}function ag(t,{dir:e,size:s=32}={}){if(s===null)return t;const n=t.replace("0x","");if(n.length>s*2)throw new sh({size:Math.ceil(n.length/2),targetSize:s,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function cg(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new sh({size:t.length,targetSize:s,type:"bytes"});const n=new Uint8Array(s);for(let r=0;r<s;r++){const i=e==="right";n[i?r:s-r-1]=t[i?r:t.length-r-1]}return n}class lg extends Te{constructor({max:e,min:s,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${r*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${s} to ${e})`:`(above ${s})`}`,{name:"IntegerOutOfRangeError"})}}class pS extends Te{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class ug extends Te{constructor(e){super(`Hex value "${e}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`,{name:"InvalidHexBooleanError"})}}class dg extends Te{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ra(t,{dir:e="left"}={}){let s=typeof t=="string"?t.replace("0x",""):t,n=0;for(let r=0;r<s.length-1&&s[e==="left"?r:s.length-r-1].toString()==="0";r++)n++;return s=e==="left"?s.slice(n):s.slice(0,s.length-n),typeof t=="string"?(s.length===1&&e==="right"&&(s=`${s}0`),`0x${s.length%2===1?`0${s}`:s}`):s}function Mo(t,{size:e}){if(vl(t)>e)throw new dg({givenSize:vl(t),maxSize:e})}function hg(t,e={}){const{signed:s}=e;e.size&&Mo(t,{size:e.size});const n=BigInt(t);if(!s)return n;const r=(t.length-2)/2,i=(1n<<BigInt(r)*8n-1n)-1n;return n<=i?n:n-BigInt(`0x${"f".padStart(r*2,"f")}`)-1n}function fS(t,e={}){let s=t;if(e.size&&(Mo(s,{size:e.size}),s=ra(s)),ra(s)==="0x00")return!1;if(ra(s)==="0x01")return!0;throw new ug(s)}function gS(t,e={}){return Number(hg(t,e))}const pg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function El(t,e={}){return typeof t=="number"||typeof t=="bigint"?gg(t,e):typeof t=="string"?rh(t,e):typeof t=="boolean"?fg(t,e):nh(t,e)}function fg(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(Mo(s,{size:e.size}),Uc(s,{size:e.size})):s}function nh(t,e={}){let s="";for(let r=0;r<t.length;r++)s+=pg[t[r]];const n=`0x${s}`;return typeof e.size=="number"?(Mo(n,{size:e.size}),Uc(n,{dir:"right",size:e.size})):n}function gg(t,e={}){const{signed:s,size:n}=e,r=BigInt(t);let i;n?s?i=(1n<<BigInt(n)*8n-1n)-1n:i=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&s?-i-1n:0;if(i&&r>i||r<o){const c=typeof t=="bigint"?"n":"";throw new lg({max:i?`${i}${c}`:void 0,min:`${o}${c}`,signed:s,size:n,value:`${t}${c}`})}const a=`0x${(s&&r<0?(1n<<BigInt(n*8))+BigInt(r):r).toString(16)}`;return n?Uc(a,{size:n}):a}const mg=new TextEncoder;function rh(t,e={}){const s=mg.encode(t);return nh(s,e)}class wg extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const s=super.get(e);return super.has(e)&&s!==void 0&&(this.delete(e),super.set(e,s)),s}set(e,s){if(super.set(e,s),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const Sn=(t,e,s)=>JSON.stringify(t,(n,r)=>typeof r=="bigint"?r.toString():r,s),mS={gwei:9,wei:18},yg={ether:-9,wei:9};function Dc(t,e){let s=t.toString();const n=s.startsWith("-");n&&(s=s.slice(1)),s=s.padStart(e,"0");let[r,i]=[s.slice(0,s.length-e),s.slice(s.length-e)];return i=i.replace(/(0+)$/,""),`${n?"-":""}${r||"0"}${i?`.${i}`:""}`}function yo(t,e="wei"){return Dc(t,yg[e])}const wS=t=>t,Lc=t=>t;class Dr extends Te{constructor({body:e,cause:s,details:n,headers:r,status:i,url:o}){super("HTTP request failed.",{cause:s,details:n,metaMessages:[i&&`Status: ${i}`,`URL: ${Lc(o)}`,e&&`Request body: ${Sn(e)}`].filter(Boolean),name:"HttpRequestError"}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.body=e,this.headers=r,this.status=i,this.url=o}}class ih extends Te{constructor({body:e,error:s,url:n}){super("RPC Request failed.",{cause:s,details:s.message,metaMessages:[`URL: ${Lc(n)}`,`Request body: ${Sn(e)}`],name:"RpcRequestError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.code=s.code,this.data=s.data,this.url=n}}class Cl extends Te{constructor({body:e,url:s}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Lc(s)}`,`Request body: ${Sn(e)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=s}}const bg=-1;class Ct extends Te{constructor(e,{code:s,docsPath:n,metaMessages:r,name:i,shortMessage:o}){super(o,{cause:e,docsPath:n,metaMessages:r||e?.metaMessages,name:i||"RpcError"}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i||e.name,this.code=e instanceof ih?e.code:s??bg}}class Pt extends Ct{constructor(e,s){super(e,s),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=s.data}}class zr extends Ct{constructor(e){super(e,{code:zr.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(zr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Gr extends Ct{constructor(e){super(e,{code:Gr.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Gr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class Yr extends Ct{constructor(e,{method:s}={}){super(e,{code:Yr.code,name:"MethodNotFoundRpcError",shortMessage:`The method${s?` "${s}"`:""} does not exist / is not available.`})}}Object.defineProperty(Yr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class Jr extends Ct{constructor(e){super(e,{code:Jr.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
4
+ `)})}}Object.defineProperty(Jr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class ir extends Ct{constructor(e){super(e,{code:ir.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(ir,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class Xr extends Ct{constructor(e){super(e,{code:Xr.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
5
+ `)})}}Object.defineProperty(Xr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class Zr extends Ct{constructor(e){super(e,{code:Zr.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty(Zr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Qr extends Ct{constructor(e){super(e,{code:Qr.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Qr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class or extends Ct{constructor(e){super(e,{code:or.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(or,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class vn extends Ct{constructor(e,{method:s}={}){super(e,{code:vn.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${s?` "${s}"`:""} is not supported.`})}}Object.defineProperty(vn,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class ar extends Ct{constructor(e){super(e,{code:ar.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(ar,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class ei extends Ct{constructor(e){super(e,{code:ei.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(ei,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Tn extends Pt{constructor(e){super(e,{code:Tn.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Tn,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class ti extends Pt{constructor(e){super(e,{code:ti.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(ti,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class si extends Pt{constructor(e,{method:s}={}){super(e,{code:si.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${s?` " ${s}"`:""}.`})}}Object.defineProperty(si,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class ni extends Pt{constructor(e){super(e,{code:ni.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(ni,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class ri extends Pt{constructor(e){super(e,{code:ri.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(ri,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class ii extends Pt{constructor(e){super(e,{code:ii.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(ii,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class oi extends Pt{constructor(e){super(e,{code:oi.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(oi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class ai extends Pt{constructor(e){super(e,{code:ai.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(ai,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class ci extends Pt{constructor(e){super(e,{code:ci.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(ci,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class li extends Pt{constructor(e){super(e,{code:li.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(li,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class ui extends Pt{constructor(e){super(e,{code:ui.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(ui,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class di extends Pt{constructor(e){super(e,{code:di.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(di,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class hi extends Pt{constructor(e){super(e,{code:hi.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(hi,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class vg extends Ct{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}class Mc extends Te{constructor({cause:e,message:s}={}){const n=s?.replace("execution reverted: ","")?.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(Mc,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(Mc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});class Eg extends Te{constructor({cause:e,maxFeePerGas:s}={}){super(`The fee cap (\`maxFeePerGas\`${s?` = ${yo(s)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(Eg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class Cg extends Te{constructor({cause:e,maxFeePerGas:s}={}){super(`The fee cap (\`maxFeePerGas\`${s?` = ${yo(s)}`:""} gwei) cannot be lower than the block base fee.`,{cause:e,name:"FeeCapTooLowError"})}}Object.defineProperty(Cg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/});class Ig extends Te{constructor({cause:e,nonce:s}={}){super(`Nonce provided for the transaction ${s?`(${s}) `:""}is higher than the next one expected.`,{cause:e,name:"NonceTooHighError"})}}Object.defineProperty(Ig,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too high/});class Ag extends Te{constructor({cause:e,nonce:s}={}){super([`Nonce provided for the transaction ${s?`(${s}) `:""}is lower than the current nonce of the account.`,"Try increasing the nonce or find the latest nonce with `getTransactionCount`."].join(`
6
+ `),{cause:e,name:"NonceTooLowError"})}}Object.defineProperty(Ag,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce too low|transaction already imported|already known/});class Ng extends Te{constructor({cause:e,nonce:s}={}){super(`Nonce provided for the transaction ${s?`(${s}) `:""}exceeds the maximum allowed nonce.`,{cause:e,name:"NonceMaxValueError"})}}Object.defineProperty(Ng,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/nonce has max value/});class _g extends Te{constructor({cause:e}={}){super(["The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."].join(`
7
+ `),{cause:e,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(_g,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class Sg extends Te{constructor({cause:e,gas:s}={}){super(`The amount of gas ${s?`(${s}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:e,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(Sg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Tg extends Te{constructor({cause:e,gas:s}={}){super(`The amount of gas ${s?`(${s}) `:""}provided for the transaction is too low.`,{cause:e,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(Tg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class Og extends Te{constructor({cause:e}){super("The transaction type is not supported for this chain.",{cause:e,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(Og,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class kg extends Te{constructor({cause:e,maxPriorityFeePerGas:s,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${s?` = ${yo(s)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${yo(n)} gwei`:""}).`].join(`
8
+ `),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(kg,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class yS extends Te{constructor({cause:e}){super(`An error occurred while executing: ${e?.shortMessage}`,{cause:e,name:"UnknownNodeError"})}}const bS=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],vS=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],oh=[{inputs:[{name:"dns",type:"bytes"}],name:"DNSDecodingFailed",type:"error"},{inputs:[{name:"ens",type:"string"}],name:"DNSEncodingFailed",type:"error"},{inputs:[],name:"EmptyAddress",type:"error"},{inputs:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"HttpError",type:"error"},{inputs:[],name:"InvalidBatchGatewayResponse",type:"error"},{inputs:[{name:"errorData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{name:"name",type:"bytes"},{name:"resolver",type:"address"}],name:"ResolverNotContract",type:"error"},{inputs:[{name:"name",type:"bytes"}],name:"ResolverNotFound",type:"error"},{inputs:[{name:"primary",type:"string"},{name:"primaryAddress",type:"bytes"}],name:"ReverseAddressMismatch",type:"error"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"}],name:"UnsupportedResolverProfile",type:"error"}],ES=[...oh,{name:"resolveWithGateways",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],CS=[...oh,{name:"reverseWithGateways",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"uint256",name:"coinType"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolver"},{type:"address",name:"reverseResolver"}]}],IS=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],AS=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],NS=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],_S=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],$i=[{type:"event",name:"Approval",inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"event",name:"Transfer",inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{type:"uint256"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{type:"uint8"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{type:"uint256"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}];function Pg(){let t=()=>{},e=()=>{};return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}}const ia=new Map;function Rg({fn:t,id:e,shouldSplitBatch:s,wait:n=0,sort:r}){const i=async()=>{const u=c();o();const d=u.map(({args:h})=>h);d.length!==0&&t(d).then(h=>{r&&Array.isArray(h)&&h.sort(r);for(let p=0;p<u.length;p++){const{resolve:f}=u[p];f?.([h[p],h])}}).catch(h=>{for(let p=0;p<u.length;p++){const{reject:f}=u[p];f?.(h)}})},o=()=>ia.delete(e),a=()=>c().map(({args:u})=>u),c=()=>ia.get(e)||[],l=u=>ia.set(e,[...c(),u]);return{flush:o,async schedule(u){const{promise:d,resolve:h,reject:p}=Pg();return s?.([...a(),u])&&i(),c().length>0?(l({args:u,resolve:h,reject:p}),d):(l({args:u,resolve:h,reject:p}),setTimeout(i,n),d)}}}async function ah(t){return new Promise(e=>setTimeout(e,t))}function xg(t,{delay:e=100,retryCount:s=2,shouldRetry:n=()=>!0}={}){return new Promise((r,i)=>{const o=async({count:a=0}={})=>{const c=async({error:l})=>{const u=typeof e=="function"?e({count:a,error:l}):e;u&&await ah(u),o({count:a+1})};try{const l=await t();r(l)}catch(l){if(a<s&&await n({count:a,error:l}))return c({error:l});i(l)}};o()})}const Ha=256;let Ui=Ha,Di;function $g(t=11){if(!Di||Ui+t>Ha*2){Di="",Ui=0;for(let e=0;e<Ha;e++)Di+=(256+Math.random()*256|0).toString(16).substring(1)}return Di.substring(Ui,Ui+++t)}const Li=new wg(8192);function Ug(t,{enabled:e=!0,id:s}){if(!e||!s)return t();if(Li.get(s))return Li.get(s);const n=t().finally(()=>Li.delete(s));return Li.set(s,n),n}function Dg(t,e={}){return async(s,n={})=>{const{dedupe:r=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...n},{method:l}=s;if(i?.exclude?.includes(l))throw new vn(new Error("method not supported"),{method:l});if(i?.include&&!i.include.includes(l))throw new vn(new Error("method not supported"),{method:l});const u=r?rh(`${c}.${Sn(s)}`):void 0;return Ug(()=>xg(async()=>{try{return await t(s)}catch(d){const h=d;switch(h.code){case zr.code:throw new zr(h);case Gr.code:throw new Gr(h);case Yr.code:throw new Yr(h,{method:s.method});case Jr.code:throw new Jr(h);case ir.code:throw new ir(h);case Xr.code:throw new Xr(h);case Zr.code:throw new Zr(h);case Qr.code:throw new Qr(h);case or.code:throw new or(h);case vn.code:throw new vn(h,{method:s.method});case ar.code:throw new ar(h);case ei.code:throw new ei(h);case Tn.code:throw new Tn(h);case ti.code:throw new ti(h);case si.code:throw new si(h);case ni.code:throw new ni(h);case ri.code:throw new ri(h);case ii.code:throw new ii(h);case oi.code:throw new oi(h);case ai.code:throw new ai(h);case ci.code:throw new ci(h);case li.code:throw new li(h);case ui.code:throw new ui(h);case di.code:throw new di(h);case hi.code:throw new hi(h);case 5e3:throw new Tn(h);default:throw d instanceof Te?d:new vg(h)}}},{delay:({count:d,error:h})=>{if(h&&h instanceof Dr){const p=h?.headers?.get("Retry-After");if(p?.match(/\d/))return Number.parseInt(p,10)*1e3}return~~(1<<d)*o},retryCount:a,shouldRetry:({error:d})=>Lg(d)}),{enabled:r,id:u})}}function Lg(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===ar.code||t.code===ir.code:t instanceof Dr&&t.status?t.status===403||t.status===408||t.status===413||t.status===429||t.status===500||t.status===502||t.status===503||t.status===504:!0}function Mg(t,{errorInstance:e=new Error("timed out"),timeout:s,signal:n}){return new Promise((r,i)=>{(async()=>{let o;try{const a=new AbortController;s>0&&(o=setTimeout(()=>{n&&a.abort()},s)),r(await t({signal:a?.signal||null}))}catch(a){a?.name==="AbortError"&&i(e),i(a)}finally{clearTimeout(o)}})()})}function Bg(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const Il=Bg();function jg(t,e={}){return{async request(s){const{body:n,fetchFn:r=e.fetchFn??fetch,onRequest:i=e.onRequest,onResponse:o=e.onResponse,timeout:a=e.timeout??1e4}=s,c={...e.fetchOptions??{},...s.fetchOptions??{}},{headers:l,method:u,signal:d}=c;try{const h=await Mg(async({signal:f})=>{const g={...c,body:Array.isArray(n)?Sn(n.map(_=>({jsonrpc:"2.0",id:_.id??Il.take(),..._}))):Sn({jsonrpc:"2.0",id:n.id??Il.take(),...n}),headers:{"Content-Type":"application/json",...l},method:u||"POST",signal:d||(a>0?f:null)},w=new Request(t,g),C=await i?.(w,g)??{...g,url:t};return await r(C.url??t,C)},{errorInstance:new Cl({body:n,url:t}),timeout:a,signal:!0});o&&await o(h);let p;if(h.headers.get("Content-Type")?.startsWith("application/json"))p=await h.json();else{p=await h.text();try{p=JSON.parse(p||"{}")}catch(f){if(h.ok)throw f;p={error:p}}}if(!h.ok)throw new Dr({body:n,details:Sn(p.error)||h.statusText,headers:h.headers,status:h.status,url:t});return p}catch(h){throw h instanceof Dr||h instanceof Cl?h:new Dr({body:n,cause:h,url:t})}}}}function ch({key:t,methods:e,name:s,request:n,retryCount:r=3,retryDelay:i=150,timeout:o,type:a},c){const l=$g();return{config:{key:t,methods:e,name:s,request:n,retryCount:r,retryDelay:i,timeout:o,type:a},request:Dg(n,{methods:e,retryCount:r,retryDelay:i,uid:l}),value:c}}function Al(t,e={}){const{key:s="fallback",name:n="Fallback",rank:r=!1,shouldThrow:i=Fg,retryCount:o,retryDelay:a}=e;return(({chain:c,pollingInterval:l=4e3,timeout:u,...d})=>{let h=t,p=()=>{};const f=ch({key:s,name:n,async request({method:g,params:w}){let C;const v=async(_=0)=>{const L=h[_]({...d,chain:c,retryCount:0,timeout:u});try{const B=await L.request({method:g,params:w});return p({method:g,params:w,response:B,transport:L,status:"success"}),B}catch(B){if(p({error:B,method:g,params:w,transport:L,status:"error"}),i(B)||_===h.length-1||(C??=h.slice(_+1).some(j=>{const{include:K,exclude:Y}=j({chain:c}).config.methods||{};return K?K.includes(g):Y?!Y.includes(g):!0}),!C))throw B;return v(_+1)}};return v()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:g=>p=g,transports:h.map(g=>g({chain:c,retryCount:0}))});if(r){const g=typeof r=="object"?r:{};qg({chain:c,interval:g.interval??l,onTransports:w=>h=w,ping:g.ping,sampleCount:g.sampleCount,timeout:g.timeout,transports:h,weights:g.weights})}return f})}function Fg(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===or.code||t.code===Tn.code||Mc.nodeMessage.test(t.message)||t.code===5e3))}function qg({chain:t,interval:e=4e3,onTransports:s,ping:n,sampleCount:r=10,timeout:i=1e3,transports:o,weights:a={}}){const{stability:c=.7,latency:l=.3}=a,u=[],d=async()=>{const h=await Promise.all(o.map(async g=>{const w=g({chain:t,retryCount:0,timeout:i}),C=Date.now();let v,_;try{await(n?n({transport:w}):w.request({method:"net_listening"})),_=1}catch{_=0}finally{v=Date.now()}return{latency:v-C,success:_}}));u.push(h),u.length>r&&u.shift();const p=Math.max(...u.map(g=>Math.max(...g.map(({latency:w})=>w)))),f=o.map((g,w)=>{const C=u.map(j=>j[w].latency),_=1-C.reduce((j,K)=>j+K,0)/C.length/p,L=u.map(j=>j[w].success),B=L.reduce((j,K)=>j+K,0)/L.length;return B===0?[0,w]:[l*_+c*B,w]}).sort((g,w)=>w[0]-g[0]);s(f.map(([,g])=>o[g])),await ah(e),d()};d()}class Wg extends Te{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function Mi(t,e={}){const{batch:s,fetchFn:n,fetchOptions:r,key:i="http",methods:o,name:a="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:l,retryDelay:u,raw:d}=e;return({chain:h,retryCount:p,timeout:f})=>{const{batchSize:g=1e3,wait:w=0}=typeof s=="object"?s:{},C=e.retryCount??p,v=f??e.timeout??1e4,_=t||h?.rpcUrls.default.http[0];if(!_)throw new Wg;const L=jg(_,{fetchFn:n,fetchOptions:r,onRequest:c,onResponse:l,timeout:v});return ch({key:i,methods:o,name:a,async request({method:B,params:j}){const K={method:B,params:j},{schedule:Y}=Rg({id:_,wait:w,shouldSplitBatch(P){return P.length>g},fn:P=>L.request({body:P}),sort:(P,I)=>P.id-I.id}),k=async P=>s?Y(P):[await L.request({body:P})],[{error:te,result:ne}]=await k(K);if(d)return{error:te,result:ne};if(te)throw new ih({body:K,error:te,url:_});return ne},retryCount:C,retryDelay:u,timeout:v,type:"http"},{fetchOptions:r,url:_})}}async function yr(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class Ci{constructor({baseUrl:e,clientId:s}){this.baseUrl=e,this.clientId=s}async get({headers:e,signal:s,cache:n,...r}){const i=this.createUrl(r);return(await yr(i,{method:"GET",headers:e,signal:s,cache:n})).json()}async getBlob({headers:e,signal:s,...n}){const r=this.createUrl(n);return(await yr(r,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await yr(i,{method:"POST",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}async put({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await yr(i,{method:"PUT",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}async delete({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await yr(i,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:n})).json()}createUrl({path:e,params:s}){const n=new URL(e,this.baseUrl);return s&&Object.entries(s).forEach(([r,i])=>{i&&n.searchParams.append(r,i)}),this.clientId&&n.searchParams.append("clientId",this.clientId),n}sendBeacon({body:e,...s}){const n=this.createUrl(s);return navigator.sendBeacon(n.toString(),e?JSON.stringify(e):void 0)}}const Va={getFeatureValue(t,e){const s=e?.[t];return s===void 0?we.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;let e=t;return G.isTelegram()&&(G.isIos()&&(e=e.filter(s=>s!=="google")),G.isMac()&&(e=e.filter(s=>s!=="x")),G.isAndroid()&&(e=e.filter(s=>!["facebook","x"].includes(s)))),G.isMobile()&&(e=e.filter(s=>s!=="facebook")),e},isSocialsEnabled(){return Array.isArray(S.state.features?.socials)&&S.state.features?.socials.length>0||Array.isArray(S.state.remoteFeatures?.socials)&&S.state.remoteFeatures?.socials.length>0},isEmailEnabled(){return!!(S.state.features?.email||S.state.remoteFeatures?.email)}},Q=Re({features:we.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:we.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1,coinbasePreference:"all"}),S={state:Q,subscribeKey(t,e){return et(Q,t,e)},setOptions(t){Object.assign(Q,t)},setRemoteFeatures(t){if(!t)return;const e={...Q.remoteFeatures,...t};Q.remoteFeatures=e,Q.remoteFeatures?.socials&&(Q.remoteFeatures.socials=Va.filterSocialsByPlatform(Q.remoteFeatures.socials)),Q.features?.pay&&(Q.remoteFeatures.email=!1,Q.remoteFeatures.socials=!1)},setFeatures(t){if(!t)return;Q.features||(Q.features=we.DEFAULT_FEATURES);const e={...Q.features,...t};Q.features=e,Q.features?.pay&&Q.remoteFeatures&&(Q.remoteFeatures.email=!1,Q.remoteFeatures.socials=!1)},setProjectId(t){Q.projectId=t},setCustomRpcUrls(t){Q.customRpcUrls=t},setAllWallets(t){Q.allWallets=t},setIncludeWalletIds(t){Q.includeWalletIds=t},setExcludeWalletIds(t){Q.excludeWalletIds=t},setFeaturedWalletIds(t){Q.featuredWalletIds=t},setTokens(t){Q.tokens=t},setTermsConditionsUrl(t){Q.termsConditionsUrl=t},setPrivacyPolicyUrl(t){Q.privacyPolicyUrl=t},setCustomWallets(t){Q.customWallets=t},setIsSiweEnabled(t){Q.isSiweEnabled=t},setIsUniversalProvider(t){Q.isUniversalProvider=t},setSdkVersion(t){Q.sdkVersion=t},setMetadata(t){Q.metadata=t},setDisableAppend(t){Q.disableAppend=t},setEIP6963Enabled(t){Q.enableEIP6963=t},setDebug(t){Q.debug=t},setEnableWalletGuide(t){Q.enableWalletGuide=t},setEnableAuthLogger(t){Q.enableAuthLogger=t},setEnableWallets(t){Q.enableWallets=t},setPreferUniversalLinks(t){Q.experimental_preferUniversalLinks=t},setSIWX(t){if(t)for(const[e,s]of Object.entries(we.SIWX_DEFAULTS))t[e]??=s;Q.siwx=t},setConnectMethodsOrder(t){Q.features={...Q.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){Q.features={...Q.features,walletFeaturesOrder:t}},setSocialsOrder(t){Q.remoteFeatures={...Q.remoteFeatures,socials:t}},setCollapseWallets(t){Q.features={...Q.features,collapseWallets:t}},setEnableEmbedded(t){Q.enableEmbedded=t},setAllowUnsupportedChain(t){Q.allowUnsupportedChain=t},setManualWCControl(t){Q.manualWCControl=t},setEnableNetworkSwitch(t){Q.enableNetworkSwitch=t},setEnableMobileFullScreen(t){Q.enableMobileFullScreen=G.isMobile()&&t},setEnableReconnect(t){Q.enableReconnect=t},setCoinbasePreference(t){Q.coinbasePreference=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(Q.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){Q.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return Q.universalProviderConfigOverride},getSnapshot(){return Vr(Q)}},fn=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),qe=Re({...fn}),Hg={state:qe,subscribeKey(t,e){return et(qe,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=G.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){qe.message=fn.message,qe.variant=fn.variant,qe.svg=fn.svg,qe.open=fn.open,qe.autoClose=fn.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:n=fn.autoClose}){qe.open?(qe.open=!1,setTimeout(()=>{qe.message=t,qe.variant=s,qe.svg=e,qe.open=!0,qe.autoClose=n},150)):(qe.message=t,qe.variant=s,qe.svg=e,qe.open=!0,qe.autoClose=n)}},hs=Hg,Vg={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},lh=G.getBlockchainApiUrl(),ht=Re({clientId:null,api:new Ci({baseUrl:lh,clientId:null}),supportedChains:{http:[],ws:[]}}),ie={state:ht,async get(t){const{st:e,sv:s}=ie.getSdkProperties(),n=S.state.projectId,r={...t.params||{},st:e,sv:s,projectId:n};return ht.api.get({...t,params:r})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=S.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{ht.supportedChains.http.length||await ie.getSupportedNetworks()}catch{return!1}return ht.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await ie.get({path:"v1/supported-chains"});return ht.supportedChains=t,t}catch{return ht.supportedChains}},async fetchIdentity({address:t}){const e=x.getIdentityFromCacheForAddress(t);if(e)return e;const s=await ie.get({path:`/v1/identity/${t}`,params:{sender:m.state.activeCaipAddress?G.getPlainAddress(m.state.activeCaipAddress):void 0}});return x.updateIdentityCache({address:t,identity:s,timestamp:Date.now()}),s},async fetchTransactions({account:t,cursor:e,signal:s,cache:n,chainId:r}){if(!await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))return{data:[],next:void 0};const o=x.getTransactionsCacheForAddress({address:t,chainId:r});if(o)return o;const a=await ie.get({path:`/v1/account/${t}/history`,params:{cursor:e,chainId:r},signal:s,cache:n});return x.updateTransactionsCache({address:t,chainId:r,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:n,gasPrice:r}){return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ie.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:s,to:n,gasPrice:r}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ie.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){if(!await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))return{fungibles:[]};const s=x.getTokenPriceCacheForAddresses(t);if(s)return s;const n=await ht.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:S.state.projectId},headers:{"Content-Type":"application/json"}});return x.updateTokenPriceCache({addresses:t,timestamp:Date.now(),tokenPrice:n}),n},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ie.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){const{st:e,sv:s}=ie.getSdkProperties();if(!await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return ie.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:s}})},async generateSwapCalldata({amount:t,from:e,to:s,userAddress:n,disableEstimate:r}){if(!await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ht.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:we.CONVERT_SLIPPAGE_TOLERANCE},projectId:S.state.projectId,from:e,to:s,userAddress:n,disableEstimate:r}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){const{st:n,sv:r}=ie.getSdkProperties();if(!await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ie.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:t,to:e,st:n,sv:r}})},async getBalance(t,e,s){const{st:n,sv:r}=ie.getSdkProperties();if(!await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))return hs.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=x.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await ie.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:n,sv:r}});return x.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ie.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){if(!await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))return[];const s=m.getAccountData()?.address;return ie.get({path:`/v1/profile/reverse/${t}`,params:{sender:s,apiVersion:"2"}})},async getEnsNameSuggestions(t){return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ie.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:n}){return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ht.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:s,signature:n},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:s,purchaseAmount:n,paymentAmount:r}){return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?(await ht.api.post({path:"/v1/generators/onrampurl",params:{projectId:S.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:r}})).url:""},async getOnrampOptions(){if(!await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await ie.get({path:"/v1/onramp/options"})}catch{return Vg}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}){try{return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?await ht.api.post({path:"/v1/onramp/quote",params:{projectId:S.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}}):null}catch{return{networkFee:{amount:s,currency:e.id},paymentSubtotal:{amount:s,currency:e.id},paymentTotal:{amount:s,currency:e.id},purchaseAmount:{amount:s,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ie.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){return await ie.isNetworkSupported(m.state.activeCaipNetwork?.caipNetworkId)?ht.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:S.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){ht.clientId=t,ht.api=new Ci({baseUrl:lh,clientId:t})}},Mt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"},BINANCE:{id:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25",appId:"yFK5FCqYprrXDiVFbhyRx7",deeplink:"bnc://app.binance.com/mp/app",url:"https://app.binance.com/en/download"}},Kg={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,n=encodeURIComponent(s);if(t===Mt.PHANTOM.id&&!("phantom"in window)){const r=s.startsWith("https")?"https":"http",i=s.split("/")[2],o=encodeURIComponent(`${r}://${i}`);window.location.href=`${Mt.PHANTOM.url}/ul/browse/${n}?ref=${o}`}if(t===Mt.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Mt.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),e===D.CHAIN.SOLANA&&t===Mt.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Mt.COINBASE.url}/dapp?cb_url=${n}`),e===D.CHAIN.BITCOIN&&t===Mt.BINANCE.id&&!("binancew3w"in window)){const r=m.state.activeCaipNetwork,i=window.btoa("/pages/browser/index"),o=window.btoa(`url=${n}&defaultChainId=${r?.id??1}`),a=new URL(Mt.BINANCE.deeplink);a.searchParams.set("appId",Mt.BINANCE.appId),a.searchParams.set("startPagePath",i),a.searchParams.set("startPageQuery",o);const c=new URL(Mt.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}},zg=Object.freeze({enabled:!0,events:[]}),Gg=new Ci({baseUrl:G.getAnalyticsUrl(),clientId:null}),Yg=5,Jg=60*1e3,Bs=Re({...zg}),Xg={state:Bs,subscribeKey(t,e){return et(Bs,t,e)},async sendError(t,e){if(!Bs.enabled)return;const s=Date.now();if(Bs.events.filter(i=>{const o=new Date(i.properties.timestamp||"").getTime();return s-o<Jg}).length>=Yg)return;const r={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Bs.events.push(r);try{if(typeof window>"u")return;const{projectId:i,sdkType:o,sdkVersion:a}=S.state;await Gg.post({path:"/e",params:{projectId:i,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:G.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){Bs.enabled=!0},disable(){Bs.enabled=!1},clearEvents(){Bs.events=[]}};class Pn extends Error{constructor(e,s,n){super(e),this.originalName="AppKitError",this.name="AppKitError",this.category=s,this.originalError=n,n&&n instanceof Error&&(this.originalName=n.name),Object.setPrototypeOf(this,Pn.prototype);let r=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){const i=n.stack,o=i.indexOf(`
9
+ `);if(o>-1){const a=i.substring(o+1);this.stack=`${this.name}: ${this.message}
10
+ ${a}`,r=!0}}r||(Error.captureStackTrace?Error.captureStackTrace(this,Pn):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Nl(t,e){let s="";try{t instanceof Error?s=t.message:typeof t=="string"?s=t:typeof t=="object"&&t!==null?Object.keys(t).length===0?s="Unknown error":s=t?.message||JSON.stringify(t):s=String(t)}catch(r){s="Unknown error",console.error("Error parsing error message",r)}const n=t instanceof Pn?t:new Pn(s,e,t);throw Xg.sendError(n,n.category),n}function Vt(t,e="INTERNAL_SDK_ERROR"){const s={};return Object.keys(t).forEach(n=>{const r=t[n];if(typeof r=="function"){let i=r;r.constructor.name==="AsyncFunction"?i=async(...o)=>{try{return await r(...o)}catch(a){return Nl(a,e)}}:i=(...o)=>{try{return r(...o)}catch(a){return Nl(a,e)}},s[n]=i}else s[n]=r}),s}const At=Re({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Zg={state:At,subscribeNetworkImages(t){return Qe(At.networkImages,()=>t(At.networkImages))},subscribeKey(t,e){return et(At,t,e)},subscribe(t){return Qe(At,()=>t(At))},setWalletImage(t,e){At.walletImages[t]=e},setNetworkImage(t,e){At.networkImages[t]=e},setChainImage(t,e){At.chainImages[t]=e},setConnectorImage(t,e){At.connectorImages={...At.connectorImages,[t]:e}},setTokenImage(t,e){At.tokenImages[t]=e},setCurrencyImage(t,e){At.currencyImages[t]=e}},Ft=Vt(Zg),Qg={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:""},oa=Re({networkImagePromises:{}}),uh={async fetchWalletImage(t){if(t)return await Z._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(oa.networkImagePromises[t]||(oa.networkImagePromises[t]=Z._fetchNetworkImage(t)),await oa.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return Ft.state.walletImages[t]},getWalletImage(t){if(t?.image_url)return t?.image_url;if(t?.image_id)return Ft.state.walletImages[t.image_id]},getNetworkImage(t){if(t?.assets?.imageUrl)return t?.assets?.imageUrl;if(t?.assets?.imageId)return Ft.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return Ft.state.networkImages[t]},getConnectorImage(t){if(t?.imageUrl)return t.imageUrl;if(t?.info?.icon)return t.info.icon;if(t?.imageId)return Ft.state.connectorImages[t.imageId]},getChainImage(t){return Ft.state.networkImages[Qg[t]]},getTokenImage(t){if(t)return Ft.state.tokenImages[t]}},em=G.getAnalyticsUrl(),tm=new Ci({baseUrl:em,clientId:null}),sm=["MODAL_CREATED"],nm=45,_l=1e3*10,De=Re({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),de={state:De,subscribe(t){return Qe(De,()=>t(De))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=S.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},shouldFlushEvents(){const t=JSON.stringify(De.pendingEvents).length/1024>nm,e=De.lastFlush+_l<Date.now();return t||e},_setPendingEvent(t){try{let e=m.getAccountData()?.address;if("address"in t.data&&t.data.address&&(e=t.data.address),sm.includes(t.data.event)||typeof window>"u")return;const s=m.getActiveCaipNetwork()?.caipNetworkId;this.state.pendingEvents.push({eventId:G.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e,properties:{..."properties"in t.data?t.data.properties:{},caipNetworkId:s}}}),De.reportedErrors.FORBIDDEN=!1,de.shouldFlushEvents()&&de._submitPendingEvents()}catch(e){console.warn("_setPendingEvent",e)}},sendEvent(t){De.timestamp=Date.now(),De.data=t;const e=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];(S.state.features?.analytics||e.includes(t.event))&&de._setPendingEvent(De),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(t){De.walletImpressions.push(t)},_transformPendingEventsForBatch(t){try{return t.filter(e=>e.props.event!=="WALLET_IMPRESSION_V2")}catch{return t}},_submitPendingEvents(){if(De.lastFlush=Date.now(),!(De.pendingEvents.length===0&&De.walletImpressions.length===0))try{const t=de._transformPendingEventsForBatch(De.pendingEvents);De.walletImpressions.length&&t.push({eventId:G.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION_V2",items:[...De.walletImpressions]}}),tm.sendBeacon({path:"/batch",params:de.getSdkProperties(),body:t}),De.reportedErrors.FORBIDDEN=!1,De.pendingEvents=[],De.walletImpressions=[]}catch{De.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){De.subscribedToVisibilityChange||typeof document>"u"||(De.subscribedToVisibilityChange=!0,document?.addEventListener?.("visibilitychange",()=>{document.visibilityState==="hidden"&&de._submitPendingEvents()}),document?.addEventListener?.("freeze",()=>{de._submitPendingEvents()}),window?.addEventListener?.("pagehide",()=>{de._submitPendingEvents()}),setInterval(()=>{de._submitPendingEvents()},_l))}},rm=G.getApiUrl(),ct=new Ci({baseUrl:rm,clientId:null}),im=40,Sl=4,om=20,ae=Re({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1,explorerWallets:[],explorerFilteredWallets:[],plan:{tier:"none",hasExceededUsageLimit:!1,limits:{isAboveRpcLimit:!1,isAboveMauLimit:!1}}}),Z={state:ae,subscribeKey(t,e){return et(ae,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=S.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return S.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${ct.baseUrl}/getWalletImage/${t}`,s=await ct.getBlob({path:e,params:Z._getSdkProperties()});Ft.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${ct.baseUrl}/public/getAssetImage/${t}`,s=await ct.getBlob({path:e,params:Z._getSdkProperties()});Ft.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${ct.baseUrl}/public/getAssetImage/${t}`,s=await ct.getBlob({path:e,params:Z._getSdkProperties()});Ft.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${ct.baseUrl}/public/getCurrencyImage/${t}`,s=await ct.getBlob({path:e,params:Z._getSdkProperties()});Ft.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${ct.baseUrl}/public/getTokenImage/${t}`,s=await ct.getBlob({path:e,params:Z._getSdkProperties()});Ft.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){const e=t.length,s=G.isMobile()?t?.filter(r=>r.mobile_link||r.webapp_link?!0:Object.values(Mt).map(o=>o.id).includes(r.id)):t,n=e-s.length;return{filteredWallets:s,mobileFilteredOutWalletsLength:n}},async fetchProjectConfig(){return(await ct.get({path:"/appkit/v1/config",params:Z._getSdkProperties()})).features},async fetchUsage(){try{const t=await ct.get({path:"/appkit/v1/project-limits",params:Z._getSdkProperties()}),{tier:e,isAboveMauLimit:s,isAboveRpcLimit:n}=t.planLimits,r=e==="starter",i=s||n;Z.state.plan={tier:e,hasExceededUsageLimit:r&&i,limits:{isAboveRpcLimit:n,isAboveMauLimit:s}}}catch(t){console.warn("Failed to fetch usage",t)}},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await ct.get({path:"/projects/v1/origins",params:Z._getSdkProperties()});return t}catch(t){if(t instanceof Error&&t.cause instanceof Response){const e=t.cause.status;if(e===D.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:t});if(e>=D.HTTP_STATUS_CODES.SERVER_ERROR&&e<600)throw new Error("SERVER_ERROR",{cause:t});return[]}return[]}},async fetchNetworkImages(){const e=m.getAllRequestedCaipNetworks()?.map(({assets:s})=>s?.imageId).filter(Boolean).filter(s=>!uh.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>Z._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=M.state,e=t.map(({imageId:s})=>s).filter(Boolean);await Promise.allSettled(e.map(s=>Z._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>Z._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>Z._fetchTokenImage(e)))},async fetchWallets(t){const e=t.exclude??[];Z._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Mt).map(o=>o.id));const n=await ct.get({path:"/getWallets",params:{...Z._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:t.include?.join(","),exclude:e.join(",")}}),{filteredWallets:r,mobileFilteredOutWalletsLength:i}=Z._filterWalletsByPlatform(n?.data);return{data:r||[],count:n?.count,mobileFilteredOutWalletsLength:i}},async prefetchWalletRanks(){const t=M.state.connectors;if(!t?.length)return;const e={page:1,entries:20,badge:"certified"};if(e.names=t.map(r=>r.name).join(","),m.state.activeChain===D.CHAIN.EVM){const r=[...t.flatMap(i=>i.connectors?.map(o=>o.info?.rdns)||[]),...t.map(i=>i.info?.rdns)].filter(i=>typeof i=="string"&&i.length>0);r.length&&(e.rdns=r.join(","))}const{data:s}=await Z.fetchWallets(e);ae.explorerWallets=s;const n=m.getRequestedCaipNetworkIds().join(",");ae.explorerFilteredWallets=s.filter(r=>r.chains?.some(i=>n.includes(i)))},async fetchFeaturedWallets(){const{featuredWalletIds:t}=S.state;if(t?.length){const e={...Z._getSdkProperties(),page:1,entries:t?.length??Sl,include:t},{data:s}=await Z.fetchWallets(e),n=[...s].sort((i,o)=>t.indexOf(i.id)-t.indexOf(o.id)),r=n.map(i=>i.image_id).filter(Boolean);await Promise.allSettled(r.map(i=>Z._fetchWalletImage(i))),ae.featured=n,ae.allFeatured=n}},async fetchRecommendedWallets(){try{ae.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=S.state,n=[...e??[],...s??[]].filter(Boolean),r=m.getRequestedCaipNetworkIds().join(","),i={page:1,entries:Sl,include:t,exclude:n,chains:r},{data:o,count:a}=await Z.fetchWallets(i),c=x.getRecentWallets(),l=o.map(d=>d.image_id).filter(Boolean),u=c.map(d=>d.image_id).filter(Boolean);await Promise.allSettled([...l,...u].map(d=>Z._fetchWalletImage(d))),ae.recommended=o,ae.allRecommended=o,ae.count=a??0}catch{}finally{ae.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:n}=S.state,r=m.getRequestedCaipNetworkIds().join(","),i=[...ae.recommended.map(({id:d})=>d),...s??[],...n??[]].filter(Boolean),o={page:t,entries:im,include:e,exclude:i,chains:r},{data:a,count:c,mobileFilteredOutWalletsLength:l}=await Z.fetchWallets(o);ae.mobileFilteredOutWalletsLength=l+(ae.mobileFilteredOutWalletsLength??0);const u=a.slice(0,om).map(d=>d.image_id).filter(Boolean);await Promise.allSettled(u.map(d=>Z._fetchWalletImage(d))),ae.wallets=G.uniqueBy([...ae.wallets,...Z._filterOutExtensions(a)],"id").filter(d=>d.chains?.some(h=>r.includes(h))),ae.count=c>ae.count?c:ae.count,ae.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await Z.fetchWallets(e);s&&s.forEach(n=>{ae.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:n}=S.state,r=m.getRequestedCaipNetworkIds().join(",");ae.search=[];const i={page:1,entries:100,search:t?.trim(),badge_type:e,include:s,exclude:n,chains:r},{data:o}=await Z.fetchWallets(i);de.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:t??""}});const a=o.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>Z._fetchWalletImage(c)),G.wait(300)]),ae.search=Z._filterOutExtensions(o)},initPromise(t,e){const s=ae.promises[t];return s||(ae.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:n=!0,fetchWalletRanks:r=!0}={}){const i=[t&&Z.initPromise("connectorImages",Z.fetchConnectorImages),e&&Z.initPromise("featuredWallets",Z.fetchFeaturedWallets),s&&Z.initPromise("recommendedWallets",Z.fetchRecommendedWallets),n&&Z.initPromise("networkImages",Z.fetchNetworkImages),r&&Z.initPromise("walletRanks",Z.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){S.state.features?.analytics&&Z.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await ct.get({path:"/getAnalyticsConfig",params:Z._getSdkProperties()});S.setFeatures({analytics:t})}catch{S.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!t?.length){ae.featured=ae.allFeatured,ae.recommended=ae.allRecommended;return}const e=m.getRequestedCaipNetworkIds().join(",");ae.featured=ae.allFeatured.filter(s=>s.chains?.some(n=>e.includes(n))),ae.recommended=ae.allRecommended.filter(s=>s.chains?.some(n=>e.includes(n))),ae.filteredWallets=ae.wallets.filter(s=>s.chains?.some(n=>e.includes(n)))},clearFilterByNamespaces(){ae.filteredWallets=[]},setFilterByNamespace(t){if(!t){ae.featured=ae.allFeatured,ae.recommended=ae.allRecommended;return}const e=m.getRequestedCaipNetworkIds().join(",");ae.featured=ae.allFeatured.filter(s=>s.chains?.some(n=>e.includes(n))),ae.recommended=ae.allRecommended.filter(s=>s.chains?.some(n=>e.includes(n))),ae.filteredWallets=ae.wallets.filter(s=>s.chains?.some(n=>e.includes(n)))}},am=["ConnectingExternal","ConnectingMultiChain","ConnectingSocial","ConnectingFarcaster"],Ae=Re({view:"Connect",history:["Connect"],transactionStack:[]}),cm={state:Ae,subscribeKey(t,e){return et(Ae,t,e)},pushTransactionStack(t){Ae.transactionStack.push(t)},popTransactionStack(t){const e=Ae.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:n,onCancel:r}=e;switch(t){case"success":s?.();break;case"error":n?.(),se.goBack();break;case"cancel":r?.(),se.goBack();break}},push(t,e){let s=t,n=e;Z.state.plan.hasExceededUsageLimit&&am.includes(t)&&(s="UsageExceeded",n=void 0),s!==Ae.view&&(Ae.view=s,Ae.history.push(s),Ae.data=n)},reset(t,e){Ae.view=t,Ae.history=[t],Ae.data=e},replace(t,e){Ae.history.at(-1)===t||(Ae.view=t,Ae.history[Ae.history.length-1]=t,Ae.data=e)},goBack(){const t=m.state.activeCaipAddress,e=se.state.view==="ConnectingFarcaster",s=!t&&e;if(Ae.history.length>1){Ae.history.pop();const[n]=Ae.history.slice(-1);n&&(t&&n==="Connect"?Ae.view="Account":Ae.view=n)}else pe.close();Ae.data?.wallet&&(Ae.data.wallet=void 0),Ae.data?.redirectView&&(Ae.data.redirectView=void 0),setTimeout(()=>{if(s){m.setAccountProp("farcasterUrl",void 0,m.state.activeChain);const n=M.getAuthConnector();n?.provider?.reload();const r=Vr(S.state);n?.provider?.syncDappData?.({metadata:r.metadata,sdkVersion:r.sdkVersion,projectId:r.projectId,sdkType:r.sdkType})}},100)},goBackToIndex(t){if(Ae.history.length>1){Ae.history=Ae.history.slice(0,t+1);const[e]=Ae.history.slice(-1);e&&(Ae.view=e)}},goBackOrCloseModal(){se.state.history.length>1?se.goBack():pe.close()}},se=Vt(cm),bs=Re({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Ka={state:bs,subscribe(t){return Qe(bs,()=>t(bs))},setThemeMode(t){bs.themeMode=t;try{const e=M.getAuthConnector();if(e){const s=Ka.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:mo(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){bs.themeVariables={...bs.themeVariables,...t};try{const e=M.getAuthConnector();if(e){const s=Ka.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:mo(bs.themeVariables,bs.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Vr(bs)}},Tt=Vt(Ka),dh=Object.fromEntries(Gd.map(t=>[t,void 0])),lm=Object.fromEntries(Gd.map(t=>[t,!0])),be=Re({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:dh,filterByNamespaceMap:lm}),um={state:be,subscribe(t){return Qe(be,()=>{t(be)})},subscribeKey(t,e){return et(be,t,e)},initialize(t){t.forEach(e=>{const s=x.getConnectedConnectorId(e);s&&M.setConnectorId(s,e)})},setActiveConnector(t){t&&(be.activeConnector=Kr(t))},setConnectors(t){t.filter(r=>!be.allConnectors.some(i=>i.id===r.id&&M.getConnectorName(i.name)===M.getConnectorName(r.name)&&i.chain===r.chain)).forEach(r=>{r.type!=="MULTI_CHAIN"&&be.allConnectors.push(Kr(r))});const s=M.getEnabledNamespaces(),n=M.getEnabledConnectors(s);be.connectors=M.mergeMultiChainConnectors(n)},filterByNamespaces(t){Object.keys(be.filterByNamespaceMap).forEach(e=>{be.filterByNamespaceMap[e]=!1}),t.forEach(e=>{be.filterByNamespaceMap[e]=!0}),M.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){be.filterByNamespaceMap[t]=e,M.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=M.getEnabledNamespaces(),e=M.getEnabledConnectors(t),s=M.areAllNamespacesEnabled();be.connectors=M.mergeMultiChainConnectors(e),s?Z.clearFilterByNamespaces():Z.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(be.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return be.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(be.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=M.generateConnectorMapByName(t),s=[];return e.forEach(n=>{const r=n[0],i=r?.id===D.CONNECTOR_ID.AUTH;n.length>1&&r?s.push({name:r.name,imageUrl:r.imageUrl,imageId:r.imageId,connectors:[...n],type:i?"AUTH":"MULTI_CHAIN",chain:"eip155",id:r?.id||""}):r&&s.push(r)}),s},generateConnectorMapByName(t){const e=new Map;return t.forEach(s=>{const{name:n}=s,r=M.getConnectorName(n);if(!r)return;const i=e.get(r)||[];i.find(a=>a.chain===s.chain)||i.push(s),e.set(r,i)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(s=>{e.find(n=>n.chain===s.chain)||e.push(s)}),e},addConnector(t){if(t.id===D.CONNECTOR_ID.AUTH){const e=t,s=Vr(S.state),n=Tt.getSnapshot().themeMode,r=Tt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,projectId:s.projectId,sdkType:s.sdkType}),e?.provider?.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:mo(r,n)}),M.setConnectors([t])}else M.setConnectors([t])},getAuthConnector(t){const e=t||m.state.activeChain,s=be.connectors.find(n=>n.id===D.CONNECTOR_ID.AUTH);if(s)return s?.connectors?.length?s.connectors.find(r=>r.chain===e):s},getAnnouncedConnectorRdns(){return be.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>t.info?.rdns)},getConnectorById(t){return be.allConnectors.find(e=>e.id===t)},getConnector({id:t,rdns:e,namespace:s}){const n=s||m.state.activeChain;return be.allConnectors.filter(i=>i.chain===n).find(i=>i.explorerId===t||i.info?.rdns===e)},syncIfAuthConnector(t){if(t.id!=="AUTH")return;const e=t,s=Vr(S.state),n=Tt.getSnapshot().themeMode,r=Tt.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:mo(r,n)})},getConnectorsByNamespace(t){const e=be.allConnectors.filter(s=>s.chain===t);return M.mergeMultiChainConnectors(e)},canSwitchToSmartAccount(t){return m.checkIfSmartAccountEnabled()&&Wt(t)===Os.ACCOUNT_TYPES.EOA},selectWalletConnector(t){const e=se.state.data?.redirectView,s=M.getConnector({id:t.id,rdns:t.rdns});Kg.handleMobileDeeplinkRedirect(s?.explorerId||t.id,m.state.activeChain),s?se.push("ConnectingExternal",{connector:s,wallet:t,redirectView:e}):se.push("ConnectingWalletConnect",{wallet:t,redirectView:e})},getConnectors(t){return t?M.getConnectorsByNamespace(t):M.mergeMultiChainConnectors(be.allConnectors)},setFilterByNamespace(t){be.filterByNamespace=t,be.connectors=M.getConnectors(t),Z.setFilterByNamespace(t)},setConnectorId(t,e){t&&(be.activeConnectorIds={...be.activeConnectorIds,[e]:t},x.setConnectedConnectorId(e,t))},removeConnectorId(t){be.activeConnectorIds={...be.activeConnectorIds,[t]:void 0},x.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return be.activeConnectorIds[t]},isConnected(t){return t?!!be.activeConnectorIds[t]:Object.values(be.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){be.activeConnectorIds={...dh}}},M=Vt(um),dm=1e3,br={checkNamespaceConnectorId(t,e){return M.getConnectorId(t)===e},isSocialProvider(t){return we.DEFAULT_REMOTE_FEATURES.socials.includes(t)},connectWalletConnect({walletConnect:t,connector:e,closeModalOnConnect:s=!0,redirectViewOnModalClose:n="Connect",onOpen:r,onConnect:i}){return new Promise((o,a)=>{if(t&&M.setActiveConnector(e),r?.(G.isMobile()&&t),n){const l=pe.subscribeKey("open",u=>{u||(se.state.view!==n&&se.replace(n),l(),a(new Error("Modal closed")))})}const c=m.subscribeKey("activeCaipAddress",l=>{l&&(i?.(),s&&pe.close(),c(),o(Ze.parseCaipAddress(l)))})})},connectExternal(t){return new Promise((e,s)=>{const n=m.subscribeKey("activeCaipAddress",r=>{r&&(pe.close(),n(),e(Ze.parseCaipAddress(r)))});H.connectExternal(t,t.chain).catch(()=>{n(),s(new Error("Connection rejected"))})})},connectSocial({social:t,namespace:e,closeModalOnConnect:s=!0,onOpenFarcaster:n,onConnect:r}){let i,o=!1,a=null;const c=e||m.state.activeChain,l=m.subscribeKey("activeCaipAddress",u=>{u&&(s&&pe.close(),l())});return new Promise((u,d)=>{async function h(f){if(f.data?.resultUri)if(f.origin===D.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",h,!1);try{const g=M.getAuthConnector(c);if(g&&!o){i&&i.close(),o=!0;const w=f.data.resultUri;de.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:t}}),x.setConnectedSocialProvider(t),await H.connectExternal({id:g.id,type:g.type,socialUri:w},g.chain);const C=m.state.activeCaipAddress;if(!C){d(new Error("Failed to connect"));return}u(Ze.parseCaipAddress(C)),de.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:t}})}}catch(g){de.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:t,message:G.parseError(g)}}),d(new Error("Failed to connect"))}}else de.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:t,message:"Untrusted Origin"}})}async function p(){if(de.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:t}}),t==="farcaster"){n?.();const f=pe.subscribeKey("open",w=>{!w&&t==="farcaster"&&(d(new Error("Popup closed")),r?.(),f())}),g=M.getAuthConnector();if(g&&!m.getAccountData(c)?.farcasterUrl)try{const{url:C}=await g.provider.getFarcasterUri();m.setAccountProp("farcasterUrl",C,c)}catch{d(new Error("Failed to connect to farcaster"))}}else{const f=M.getAuthConnector();a=G.returnOpenHref(`${D.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(f){const{uri:g}=await f.provider.getSocialRedirectUri({provider:t});if(a&&g){a.location.href=g,i=a;const w=setInterval(()=>{i?.closed&&!o&&(d(new Error("Popup closed")),clearInterval(w))},1e3);window.addEventListener("message",h,!1)}else a?.close(),d(new Error("Failed to initiate social connection"))}}catch{d(new Error("Failed to initiate social connection")),a?.close()}}}p()})},connectEmail({closeModalOnConnect:t=!0,redirectViewOnModalClose:e="Connect",onOpen:s,onConnect:n}){return new Promise((r,i)=>{if(s?.(),e){const a=pe.subscribeKey("open",c=>{c||(se.state.view!==e&&se.replace(e),a(),i(new Error("Modal closed")))})}const o=m.subscribeKey("activeCaipAddress",a=>{a&&(n?.(),t&&pe.close(),o(),r(Ze.parseCaipAddress(a)))})})},async updateEmail(){const t=x.getConnectedConnectorId(m.state.activeChain),e=M.getAuthConnector();if(!e)throw new Error("No auth connector found");if(t!==D.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");const s=e.provider.getEmail()??"";return await pe.open({view:"UpdateEmailWallet",data:{email:s,redirectView:void 0}}),new Promise((n,r)=>{const i=setInterval(()=>{const a=e.provider.getEmail()??"";a!==s&&(pe.close(),clearInterval(i),o(),n({email:a}))},dm),o=pe.subscribeKey("open",a=>{a||(se.state.view!=="Connect"&&se.push("Connect"),clearInterval(i),o(),r(new Error("Modal closed")))})})},canSwitchToSmartAccount(t){return m.checkIfSmartAccountEnabled()&&Wt(t)===Os.ACCOUNT_TYPES.EOA}};function hh(){const t=m.state.activeCaipNetwork?.chainNamespace||"eip155",e=m.state.activeCaipNetwork?.id||1,s=we.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`}function Wt(t){return m.getAccountData(t)?.preferredAccountType}function Bi(t){return m.state.activeCaipNetwork}const bo={getConnectionStatus(t,e){const s=M.state.activeConnectorIds[e],n=H.getConnections(e);return!!s&&t.connectorId===s?"connected":n.some(o=>o.connectorId.toLowerCase()===t.connectorId.toLowerCase())?"active":"disconnected"},excludeConnectorAddressFromConnections({connections:t,connectorId:e,addresses:s}){return t.map(n=>{if((e?n.connectorId.toLowerCase()===e.toLowerCase():!1)&&s){const i=n.accounts.filter(o=>!s.some(c=>c.toLowerCase()===o.address.toLowerCase()));return{...n,accounts:i}}return n})},excludeExistingConnections(t,e){const s=new Set(t);return e.filter(n=>!s.has(n.connectorId))},getConnectionsByConnectorId(t,e){return t.filter(s=>s.connectorId.toLowerCase()===e.toLowerCase())},getConnectionsData(t){const e=!!S.state.remoteFeatures?.multiWallet,s=M.state.activeConnectorIds[t],n=H.getConnections(t),i=(H.state.recentConnections.get(t)??[]).filter(a=>M.getConnectorById(a.connectorId)),o=bo.excludeExistingConnections([...n.map(a=>a.connectorId),...s?[s]:[]],i);return e?{connections:n,recentConnections:o}:{connections:n.filter(a=>a.connectorId.toLowerCase()===s?.toLowerCase()),recentConnections:[]}}},xe=Re({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),hm={state:xe,subscribe(t){return Qe(xe,()=>t(xe))},setLastNetworkInView(t){xe.lastNetworkInView=t},async fetchTransactions(t){if(!t)throw new Error("Transactions can't be fetched without an accountAddress");xe.loading=!0;try{const e=await ie.fetchTransactions({account:t,cursor:xe.next,chainId:m.state.activeCaipNetwork?.caipNetworkId}),s=ro.filterSpamTransactions(e.data),n=ro.filterByConnectedChain(s),r=[...xe.transactions,...n];xe.loading=!1,xe.transactions=r,xe.transactionsByYear=ro.groupTransactionsByYearAndMonth(xe.transactionsByYear,n),xe.empty=r.length===0,xe.next=e.next?e.next:void 0}catch{const s=m.state.activeChain;de.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:S.state.projectId,cursor:xe.next,isSmartAccount:Wt(s)===Os.ACCOUNT_TYPES.SMART_ACCOUNT}}),hs.showError("Failed to fetch transactions"),xe.loading=!1,xe.empty=!0,xe.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const s=t;return e.forEach(n=>{const r=new Date(n.metadata.minedAt).getFullYear(),i=new Date(n.metadata.minedAt).getMonth(),o=s[r]??{},c=(o[i]??[]).filter(l=>l.id!==n.id);s[r]={...o,[i]:[...c,n].sort((l,u)=>new Date(u.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),s},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(n=>n.nft_info?.flags.is_spam===!0))},filterByConnectedChain(t){const e=m.state.activeCaipNetwork?.caipNetworkId;return t.filter(n=>n.metadata.chain===e)},clearCursor(){xe.next=void 0},resetTransactions(){xe.transactions=[],xe.transactionsByYear={},xe.lastNetworkInView=void 0,xe.loading=!1,xe.empty=!1,xe.next=void 0}},ro=Vt(hm,"API_ERROR"),ve=Re({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,buffering:!1,status:"disconnected"});let cn;const pm={state:ve,subscribe(t){return Qe(ve,()=>t(ve))},subscribeKey(t,e){return et(ve,t,e)},_getClient(){return ve._client},setClient(t){ve._client=Kr(t)},initialize(t){const e=t.filter(s=>!!s.namespace).map(s=>s.namespace);H.syncStorageConnections(e)},syncStorageConnections(t){const e=x.getConnections(),s=t??Array.from(m.state.chains.keys());for(const n of s){const r=e[n]??[],i=new Map(ve.recentConnections);i.set(n,r),ve.recentConnections=i}},getConnections(t){return t?ve.connections.get(t)??[]:[]},hasAnyConnection(t){const e=H.state.connections;return Array.from(e.values()).flatMap(s=>s).some(({connectorId:s})=>s===t)},async connectWalletConnect({cache:t="auto"}={}){const e=G.isTelegram()||G.isSafari()&&G.isIos();if(t==="always"||t==="auto"&&e){if(cn){await cn,cn=void 0;return}if(!G.isPairingExpired(ve?.wcPairingExpiry)){const s=ve.wcUri;ve.wcUri=s;return}cn=H._getClient()?.connectWalletConnect?.().catch(()=>{}),H.state.status="connecting",await cn,cn=void 0,ve.wcPairingExpiry=void 0,H.state.status="connected"}else await H._getClient()?.connectWalletConnect?.()},async connectExternal(t,e,s=!0){const n=await H._getClient()?.connectExternal?.(t);return s&&m.setActiveNamespace(e),n},async reconnectExternal(t){await H._getClient()?.reconnectExternal?.(t);const e=t.chain||m.state.activeChain;e&&M.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){if(!e)return;pe.setLoading(!0,m.state.activeChain);const s=M.getAuthConnector();s&&(m.setAccountProp("preferredAccountType",t,e),await s.provider.setPreferredAccount(t),x.setPreferredAccountTypes(Object.entries(m.state.chains).reduce((n,[r,i])=>{const o=r,a=Wt(o);return a!==void 0&&(n[o]=a),n},{})),await H.reconnectExternal(s),pe.setLoading(!1,m.state.activeChain),de.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:m.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(t){return H._getClient()?.signMessage(t)},parseUnits(t,e){return H._getClient()?.parseUnits(t,e)},formatUnits(t,e){return H._getClient()?.formatUnits(t,e)},updateBalance(t){return H._getClient()?.updateBalance(t)},async sendTransaction(t){return H._getClient()?.sendTransaction(t)},async getCapabilities(t){return H._getClient()?.getCapabilities(t)},async grantPermissions(t){return H._getClient()?.grantPermissions(t)},async walletGetAssets(t){return H._getClient()?.walletGetAssets(t)??{}},async estimateGas(t){return H._getClient()?.estimateGas(t)},async writeContract(t){return H._getClient()?.writeContract(t)},async getEnsAddress(t){return H._getClient()?.getEnsAddress(t)},async getEnsAvatar(t){return H._getClient()?.getEnsAvatar(t)},checkInstalled(t){return H._getClient()?.checkInstalled?.(t)||!1},resetWcConnection(){ve.wcUri=void 0,ve.wcPairingExpiry=void 0,ve.wcLinking=void 0,ve.recentWallet=void 0,ve.status="disconnected",ro.resetTransactions(),x.deleteWalletConnectDeepLink(),x.deleteRecentWallet()},resetUri(){ve.wcUri=void 0,ve.wcPairingExpiry=void 0,cn=void 0},finalizeWcConnection(t){const{wcLinking:e,recentWallet:s}=H.state;e&&x.setWalletConnectDeepLink(e),s&&x.setAppKitRecent(s),t&&de.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:t,properties:{method:e?"mobile":"qrcode",name:se.state.data?.wallet?.name||"Unknown",view:se.state.view,walletRank:s?.order}})},setWcBasic(t){ve.wcBasic=t},setUri(t){ve.wcUri=t,ve.wcPairingExpiry=G.getPairingExpiry()},setWcLinking(t){ve.wcLinking=t},setWcError(t){ve.wcError=t,ve.buffering=!1},setRecentWallet(t){ve.recentWallet=t},setBuffering(t){ve.buffering=t},setStatus(t){ve.status=t},setIsSwitchingConnection(t){ve.isSwitchingConnection=t},async disconnect({id:t,namespace:e,initialDisconnect:s}={}){try{await H._getClient()?.disconnect({id:t,chainNamespace:e,initialDisconnect:s})}catch(n){throw new Pn("Failed to disconnect","INTERNAL_SDK_ERROR",n)}},async disconnectConnector({id:t,namespace:e}){try{await H._getClient()?.disconnectConnector({id:t,namespace:e})}catch(s){throw new Pn("Failed to disconnect connector","INTERNAL_SDK_ERROR",s)}},setConnections(t,e){const s=new Map(ve.connections);s.set(e,t),ve.connections=s},async handleAuthAccountSwitch({address:t,namespace:e}){const n=m.getAccountData(e)?.user?.accounts?.find(i=>i.type==="smartAccount"),r=n&&n.address.toLowerCase()===t.toLowerCase()&&br.canSwitchToSmartAccount(e)?"smartAccount":"eoa";await H.setPreferredAccountType(r,e)},async handleActiveConnection({connection:t,namespace:e,address:s}){const n=M.getConnectorById(t.connectorId),r=t.connectorId===D.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${t.connectorId}`);if(r)s&&await H.handleAuthAccountSwitch({address:s,namespace:e});else return(await H.connectExternal({id:n.id,type:n.type,provider:n.provider,address:s,chain:e},e))?.address;return s},async handleDisconnectedConnection({connection:t,namespace:e,address:s,closeModalOnConnect:n}){const r=M.getConnectorById(t.connectorId),i=t.auth?.name?.toLowerCase(),o=t.connectorId===D.CONNECTOR_ID.AUTH,a=t.connectorId===D.CONNECTOR_ID.WALLET_CONNECT;if(!r)throw new Error(`No connector found for connection: ${t.connectorId}`);let c;if(o)if(i&&br.isSocialProvider(i)){const{address:l}=await br.connectSocial({social:i,closeModalOnConnect:n,onOpenFarcaster(){pe.open({view:"ConnectingFarcaster"})},onConnect(){se.replace("ProfileWallets")}});c=l}else{const{address:l}=await br.connectEmail({closeModalOnConnect:n,onOpen(){pe.open({view:"EmailLogin"})},onConnect(){se.replace("ProfileWallets")}});c=l}else if(a){const{address:l}=await br.connectWalletConnect({walletConnect:!0,connector:r,closeModalOnConnect:n,onOpen(u){const d=u?"AllWallets":"ConnectingWalletConnect";pe.state.open?se.push(d):pe.open({view:d})},onConnect(){se.replace("ProfileWallets")}});c=l}else{const l=await H.connectExternal({id:r.id,type:r.type,provider:r.provider,chain:e},e);l&&(c=l.address)}return o&&s&&await H.handleAuthAccountSwitch({address:s,namespace:e}),c},async switchConnection({connection:t,address:e,namespace:s,closeModalOnConnect:n,onChange:r}){let i;const o=m.getAccountData(s)?.caipAddress;if(o){const{address:c}=Ze.parseCaipAddress(o);i=c}const a=bo.getConnectionStatus(t,s);switch(a){case"connected":case"active":{const c=await H.handleActiveConnection({connection:t,namespace:s,address:e});if(i&&c){const l=c.toLowerCase()!==i.toLowerCase();r?.({address:c,namespace:s,hasSwitchedAccount:l,hasSwitchedWallet:a==="active"})}break}case"disconnected":{const c=await H.handleDisconnectedConnection({connection:t,namespace:s,address:e,closeModalOnConnect:n});c&&r?.({address:c,namespace:s,hasSwitchedAccount:!0,hasSwitchedWallet:!0});break}default:throw new Error(`Invalid connection status: ${a}`)}}},H=Vt(pm),aa={createBalance(t,e){const s={name:t.metadata.name||"",symbol:t.metadata.symbol||"",decimals:t.metadata.decimals||0,value:t.metadata.value||0,price:t.metadata.price||0,iconUrl:t.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:e,address:t.address==="native"?void 0:this.convertAddressToCAIP10Address(t.address,e),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:t.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance({hex:t,decimals:e}){return Dc(BigInt(t),e)},convertAddressToCAIP10Address(t,e){return`${e}:${t}`},createCAIP2ChainId(t,e){return`${e}:${parseInt(t,16)}`},getChainIdHexFromCAIP2ChainId(t){const e=t.split(":");if(e.length<2||!e[1])return"0x0";const s=e[1],n=parseInt(s,10);return isNaN(n)?"0x0":`0x${n.toString(16)}`},isWalletGetAssetsResponse(t){return typeof t!="object"||t===null?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(s=>this.isValidAsset(s)))},isValidAsset(t){return typeof t=="object"&&t!==null&&typeof t.address=="string"&&typeof t.balance=="string"&&(t.type==="ERC20"||t.type==="NATIVE")&&typeof t.metadata=="object"&&t.metadata!==null&&typeof t.metadata.name=="string"&&typeof t.metadata.symbol=="string"&&typeof t.metadata.decimals=="number"&&typeof t.metadata.price=="number"&&typeof t.metadata.iconUrl=="string"}};let ca;async function Tl(){if(!ca){const{createPublicClient:t,http:e,defineChain:s}=await fo(async()=>{const{createPublicClient:n,http:r,defineChain:i}=await import("./index-B06SWXYS.js");return{createPublicClient:n,http:r,defineChain:i}},__vite__mapDeps([0,1,2,3]));ca={createPublicClient:t,http:e,defineChain:s}}return ca}const za={getBlockchainApiRpcUrl(t,e){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",t),s.searchParams.set("projectId",e),s.toString()},async getViemChain(t){const{defineChain:e}=await Tl(),{chainId:s}=Ze.parseCaipNetworkId(t.caipNetworkId);return e({...t,id:Number(s)})},async createViemPublicClient(t){const{createPublicClient:e,http:s}=await Tl(),n=S.state.projectId,r=await za.getViemChain(t);if(!r)throw new Error(`Chain ${t.caipNetworkId} not found in viem/chains`);return e({chain:r,transport:s(za.getBlockchainApiRpcUrl(t.caipNetworkId,n))})}},Bc={async getMyTokensWithBalance(t){const e=m.getAccountData()?.address,s=m.state.activeCaipNetwork,n=M.getConnectorId("eip155")===D.CONNECTOR_ID.AUTH;if(!e||!s)return[];const r=`${s.caipNetworkId}:${e}`,i=x.getBalanceCacheForCaipAddress(r);if(i)return i.balances;if(s.chainNamespace===D.CHAIN.EVM&&n){const a=await this.getEIP155Balances(e,s);if(a)return this.filterLowQualityTokens(a)}const o=await ie.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(t,e){try{const s=aa.getChainIdHexFromCAIP2ChainId(e.caipNetworkId);if(!(await H.getCapabilities(t))?.[s]?.assetDiscovery?.supported)return null;const r=await H.walletGetAssets({account:t,chainFilter:[s]});if(!aa.isWalletGetAssetsResponse(r))return null;const o=(r[s]||[]).map(a=>aa.createBalance(a,e.caipNetworkId));return x.updateBalanceCache({caipAddress:`${e.caipNetworkId}:${t}`,balance:{balances:o},timestamp:Date.now()}),o}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:t,assetAddress:e,caipNetwork:s}){const n=await za.createViemPublicClient(s),{address:r}=Ze.parseCaipAddress(t),[{result:i},{result:o},{result:a},{result:c}]=await n.multicall({contracts:[{address:e,functionName:"name",args:[],abi:$i},{address:e,functionName:"symbol",args:[],abi:$i},{address:e,functionName:"balanceOf",args:[r],abi:$i},{address:e,functionName:"decimals",args:[],abi:$i}]});return{name:i,symbol:o,decimals:c,balance:a&&c?Dc(a,c):"0"}}},la={adapters:{}},ph={state:la,initialize(t){la.adapters={...t}},get(t){return la.adapters[t]}},vo={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0},pt=Re({providers:{...vo},providerIds:{...vo}}),$e={state:pt,subscribeKey(t,e){return et(pt,t,e)},subscribe(t){return Qe(pt,()=>{t(pt)})},subscribeProviders(t){return Qe(pt.providers,()=>t(pt.providers))},setProvider(t,e){t&&e&&(pt.providers[t]=Kr(e))},getProvider(t){if(t)return pt.providers[t]},setProviderId(t,e){e&&(pt.providerIds[t]=e)},getProviderId(t){if(t)return pt.providerIds[t]},reset(){pt.providers={...vo},pt.providerIds={...vo}},resetChain(t){pt.providers[t]=void 0,pt.providerIds[t]=void 0}},Fn=Re({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),ks={state:Fn,subscribe(t){return Qe(Fn,()=>t(Fn))},subscribeOpen(t){return et(Fn,"open",t)},set(t){Object.assign(Fn,{...Fn,...t})}},fm={async getTokenList(t){return(await ie.fetchSwapTokens({chainId:t}))?.tokens?.map(n=>({...n,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0}))||[]},async fetchGasPrice(){const t=m.state.activeCaipNetwork;if(!t)return null;try{if(t.chainNamespace==="solana"){const e=(await H?.estimateGas({chainNamespace:"solana"}))?.toString();return{standard:e,fast:e,instant:e}}else return await ie.fetchGasPrice({chainId:t.caipNetworkId})}catch{return null}},async fetchSwapAllowance({tokenAddress:t,userAddress:e,sourceTokenAmount:s,sourceTokenDecimals:n}){const r=await ie.fetchSwapAllowance({tokenAddress:t,userAddress:e});if(r?.allowance&&s&&n){const i=H.parseUnits(s,n)||0;return BigInt(r.allowance)>=i}return!1},async getMyTokensWithBalance(t){const e=await Bc.getMyTokensWithBalance(t);return m.setAccountProp("tokenBalance",e,m.state.activeChain),this.mapBalancesToSwapTokens(e)},mapBalancesToSwapTokens(t){return t?.map(e=>({...e,address:e?.address?e.address:hh(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]},async handleSwapError(t){try{const e=t?.cause;return e?.json&&(await e.json())?.reasons?.[0]?.description?.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}},me=Re({tokenBalances:[],loading:!1}),gm={state:me,subscribe(t){return Qe(me,()=>t(me))},subscribeKey(t,e){return et(me,t,e)},setToken(t){t&&(me.token=Kr(t))},setTokenAmount(t){me.sendTokenAmount=t},setReceiverAddress(t){me.receiverAddress=t},setReceiverProfileImageUrl(t){me.receiverProfileImageUrl=t},setReceiverProfileName(t){me.receiverProfileName=t},setNetworkBalanceInUsd(t){me.networkBalanceInUSD=t},setLoading(t){me.loading=t},getSdkEventProperties(t){return{message:G.parseError(t),isSmartAccount:Wt(m.state.activeChain)===Os.ACCOUNT_TYPES.SMART_ACCOUNT,token:me.token?.symbol||"",amount:me.sendTokenAmount??0,network:m.state.activeCaipNetwork?.caipNetworkId||""}},async sendToken(){try{switch(ue.setLoading(!0),m.state.activeCaipNetwork?.chainNamespace){case"eip155":await ue.sendEvmToken();return;case"solana":await ue.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(t){throw Ts.isUserRejectedRequestError(t)?new Xd(t):t}finally{ue.setLoading(!1)}},async sendEvmToken(){const t=m.state.activeChain;if(!t)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const e=Wt(t);if(!ue.state.sendTokenAmount||!ue.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!ue.state.token)throw new Error("A token is required");if(ue.state.token?.address){de.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Os.ACCOUNT_TYPES.SMART_ACCOUNT,token:ue.state.token.address,amount:ue.state.sendTokenAmount,network:m.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:s}=await ue.sendERC20Token({receiverAddress:ue.state.receiverAddress,tokenAddress:ue.state.token.address,sendTokenAmount:ue.state.sendTokenAmount,decimals:ue.state.token.quantity.decimals});s&&(me.hash=s)}else{de.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Os.ACCOUNT_TYPES.SMART_ACCOUNT,token:ue.state.token.symbol||"",amount:ue.state.sendTokenAmount,network:m.state.activeCaipNetwork?.caipNetworkId||""}});const{hash:s}=await ue.sendNativeToken({receiverAddress:ue.state.receiverAddress,sendTokenAmount:ue.state.sendTokenAmount,decimals:ue.state.token.quantity.decimals});s&&(me.hash=s)}},async fetchTokenBalance(t){me.loading=!0;const e=m.state.activeChain,s=m.state.activeCaipNetwork?.caipNetworkId,n=m.state.activeCaipNetwork?.chainNamespace,r=m.getAccountData(e)?.caipAddress??m.state.activeCaipAddress,i=r?G.getPlainAddress(r):void 0;if(me.lastRetry&&!G.isAllowedRetry(me.lastRetry,30*we.ONE_SEC_MS))return me.loading=!1,[];try{if(i&&s&&n){const o=await Bc.getMyTokensWithBalance();return me.tokenBalances=o,me.lastRetry=void 0,o}}catch(o){me.lastRetry=Date.now(),t?.(o),hs.showError("Token Balance Unavailable")}finally{me.loading=!1}return[]},fetchNetworkBalance(){if(me.tokenBalances.length===0)return;const t=fm.mapBalancesToSwapTokens(me.tokenBalances);if(!t)return;const e=t.find(s=>s.address===hh());e&&(me.networkBalanceInUSD=e?Bf.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){se.pushTransactionStack({});const e=t.receiverAddress,s=m.getAccountData()?.address,n=H.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),i=await H.sendTransaction({chainNamespace:D.CHAIN.EVM,to:e,address:s,data:"0x",value:n??BigInt(0)});return de.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Wt("eip155")===Os.ACCOUNT_TYPES.SMART_ACCOUNT,token:ue.state.token?.symbol||"",amount:t.sendTokenAmount,network:m.state.activeCaipNetwork?.caipNetworkId||"",hash:i||""}}),H._getClient()?.updateBalance("eip155"),ue.resetSend(),{hash:i}},async sendERC20Token(t){se.pushTransactionStack({onSuccess(){se.replace("Account")}});const e=H.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),s=m.getAccountData()?.address;if(s&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const n=G.getPlainAddress(t.tokenAddress);if(!n)throw new Error("SendController:sendERC20Token - tokenAddress is required");const r=await H.writeContract({fromAddress:s,tokenAddress:n,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:Wf.getERC20Abi(n),chainNamespace:D.CHAIN.EVM});return de.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:Wt("eip155")===Os.ACCOUNT_TYPES.SMART_ACCOUNT,token:ue.state.token?.symbol||"",amount:t.sendTokenAmount,network:m.state.activeCaipNetwork?.caipNetworkId||"",hash:r||""}}),ue.resetSend(),{hash:r}}return{hash:void 0}},async sendSolanaToken(){if(!ue.state.sendTokenAmount||!ue.state.receiverAddress)throw new Error("An amount and receiver address are required");se.pushTransactionStack({onSuccess(){se.replace("Account")}});let t;ue.state.token&&ue.state.token.address!==we.SOLANA_NATIVE_TOKEN_ADDRESS&&(G.isCaipAddress(ue.state.token.address)?t=G.getPlainAddress(ue.state.token.address):t=ue.state.token.address);const e=await H.sendTransaction({chainNamespace:"solana",tokenMint:t,to:ue.state.receiverAddress,value:ue.state.sendTokenAmount});e&&(me.hash=e),H._getClient()?.updateBalance("solana"),de.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:!1,token:ue.state.token?.symbol||"",amount:ue.state.sendTokenAmount,network:m.state.activeCaipNetwork?.caipNetworkId||"",hash:e||""}}),ue.resetSend()},resetSend(){me.token=void 0,me.sendTokenAmount=void 0,me.receiverAddress=void 0,me.receiverProfileImageUrl=void 0,me.receiverProfileName=void 0,me.loading=!1,me.tokenBalances=[]}},ue=Vt(gm),ua={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},ji={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},V=Re({chains:ng(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{connectionControllerClient:void 0},isSwitchingNamespace:!1}),fh={state:V,subscribe(t){return Qe(V,()=>{t(V)})},subscribeKey(t,e){return et(V,t,e)},subscribeAccountStateProp(t,e,s){const n=s||V.activeChain;return n?et(V.chains.get(n)?.accountState||{},t,e):()=>{}},subscribeChainProp(t,e,s){let n;return Qe(V.chains,()=>{const r=s||V.activeChain;if(r){const i=V.chains.get(r)?.[t];n!==i&&(n=i,e(i))}})},initialize(t,e,s){const{chainId:n,namespace:r}=x.getActiveNetworkProps(),i=e?.find(u=>u.id.toString()===n?.toString()),a=t.find(u=>u?.namespace===r)||t?.[0],c=t.map(u=>u.namespace).filter(u=>u!==void 0),l=S.state.enableEmbedded?new Set([...c]):new Set([...e?.map(u=>u.chainNamespace)??[]]);(t?.length===0||!a)&&(V.noAdapters=!0),V.noAdapters||(V.activeChain=a?.namespace,V.activeCaipNetwork=i,m.setChainNetworkData(a?.namespace,{caipNetwork:i}),V.activeChain&&ks.set({activeChain:a?.namespace})),l.forEach(u=>{const d=e?.filter(f=>f.chainNamespace===u),h=x.getPreferredAccountTypes()||{},p={...S.state.defaultAccountTypes,...h};m.state.chains.set(u,{namespace:u,networkState:Re({...ji,caipNetwork:d?.[0]}),accountState:Re({...ua,preferredAccountType:p[u]}),caipNetworks:d??[],...s}),m.setRequestedCaipNetworks(d??[],u)})},removeAdapter(t){if(V.activeChain===t){const e=Array.from(V.chains.entries()).find(([s])=>s!==t);if(e){const s=e[1]?.caipNetworks?.[0];s&&m.setActiveCaipNetwork(s)}}V.chains.delete(t)},addAdapter(t,{connectionControllerClient:e},s){if(!t.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");V.chains.set(t.namespace,{namespace:t.namespace,networkState:{...ji,caipNetwork:s[0]},accountState:{...ua},caipNetworks:s,connectionControllerClient:e}),m.setRequestedCaipNetworks(s?.filter(n=>n.chainNamespace===t.namespace)??[],t.namespace)},addNetwork(t){const e=V.chains.get(t.chainNamespace);if(e){const s=[...e.caipNetworks||[]];e.caipNetworks?.find(n=>n.id===t.id)||s.push(t),V.chains.set(t.chainNamespace,{...e,caipNetworks:s}),m.setRequestedCaipNetworks(s,t.chainNamespace),M.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){const s=V.chains.get(t);if(s){const n=V.activeCaipNetwork?.id===e,r=[...s.caipNetworks?.filter(i=>i.id!==e)||[]];n&&s?.caipNetworks?.[0]&&m.setActiveCaipNetwork(s.caipNetworks[0]),V.chains.set(t,{...s,caipNetworks:r}),m.setRequestedCaipNetworks(r||[],t),r.length===0&&M.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=V.chains.get(t);s&&(s.networkState={...s.networkState||ji,...e},V.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const n=V.chains.get(t);if(n){const r={...n.accountState||ua,...e};V.chains.set(t,{...n,accountState:r}),(V.chains.size===1||V.activeChain===t)&&e.caipAddress&&(V.activeCaipAddress=e.caipAddress)}},setChainNetworkData(t,e){if(!t)return;const s=V.chains.get(t);if(s){const n={...s.networkState||ji,...e};V.chains.set(t,{...s,networkState:n})}},setAccountProp(t,e,s,n=!0){m.setChainAccountData(s,{[t]:e},n)},setActiveNamespace(t){V.activeChain=t;const e=t?V.chains.get(t):void 0,s=e?.networkState?.caipNetwork;s?.id&&t&&(V.activeCaipAddress=e?.accountState?.caipAddress,V.activeCaipNetwork=s,m.setChainNetworkData(t,{caipNetwork:s}),x.setActiveCaipNetworkId(s?.caipNetworkId),ks.set({activeChain:t,selectedNetworkId:s?.caipNetworkId}))},setActiveCaipNetwork(t){if(!t)return;const e=V.activeChain===t.chainNamespace;e||m.setIsSwitchingNamespace(!0);const s=V.chains.get(t.chainNamespace);V.activeChain=t.chainNamespace,V.activeCaipNetwork=t,m.setChainNetworkData(t.chainNamespace,{caipNetwork:t});let n=s?.accountState?.address;if(n)V.activeCaipAddress=`${t.chainNamespace}:${t.id}:${n}`;else if(e&&V.activeCaipAddress){const{address:i}=Ze.parseCaipAddress(V.activeCaipAddress);n=i,V.activeCaipAddress=`${t.caipNetworkId}:${n}`}else V.activeCaipAddress=void 0;m.setChainAccountData(t.chainNamespace,{address:n,caipAddress:V.activeCaipAddress}),ue.resetSend(),ks.set({activeChain:V.activeChain,selectedNetworkId:V.activeCaipNetwork?.caipNetworkId}),x.setActiveCaipNetworkId(t.caipNetworkId),!m.checkIfSupportedNetwork(t.chainNamespace)&&S.state.enableNetworkSwitch&&!S.state.allowUnsupportedChain&&!H.state.wcBasic&&m.showUnsupportedChainUI()},addCaipNetwork(t){if(!t)return;const e=V.chains.get(t.chainNamespace);e&&e?.caipNetworks?.push(t)},async switchActiveNamespace(t){if(!t)return;const e=t!==m.state.activeChain,s=m.getNetworkData(t)?.caipNetwork,n=m.getCaipNetworkByNamespace(t,s?.id);e&&n&&await m.switchActiveNetwork(n)},async switchActiveNetwork(t,{throwOnFailure:e=!1}={}){const s=m.state.activeChain;if(!s)throw new Error("ChainController:switchActiveNetwork - namespace is required");const n=$e.getProviderId(V.activeChain)==="AUTH",r=m.getAccountData(s)?.address,i=D.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(t.chainNamespace);try{if(r&&t.chainNamespace===s||n&&i){const o=ph.get(t.chainNamespace);if(!o)throw new Error("Adapter not found");await o.switchNetwork({caipNetwork:t})}m.setActiveCaipNetwork(t)}catch(o){if(e)throw o}de.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})},getConnectionControllerClient(t){const e=t||V.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=V.chains.get(e);if(!s?.connectionControllerClient)throw new Error("ConnectionController client not set");return s.connectionControllerClient},getNetworkProp(t,e){const s=V.chains.get(e)?.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=V.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:n=[]}=e?.networkState||{};return G.sortRequestedNetworks(s,n).filter(o=>o?.id)},getAllRequestedCaipNetworks(){const t=[];return V.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const s=m.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){m.setAdapterNetworkState(e,{requestedCaipNetworks:t});const n=m.getAllRequestedCaipNetworks().map(i=>i.chainNamespace),r=Array.from(new Set(n));M.filterByNamespaces(r)},getAllApprovedCaipNetworkIds(){const t=[];return V.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const s=m.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(t){return t?V.chains.get(t)?.networkState?.caipNetwork:V.activeCaipNetwork},getActiveCaipAddress(){return V.activeCaipAddress},getApprovedCaipNetworkIds(t){return V.chains.get(t)?.networkState?.approvedCaipNetworkIds||[]},setApprovedCaipNetworksData(t,e){m.setAdapterNetworkState(t,e)},checkIfSupportedNetwork(t,e){const s=e||V.activeCaipNetwork?.caipNetworkId,n=m.getRequestedCaipNetworks(t);return n.length?n?.some(r=>r.caipNetworkId===s):!0},checkIfSupportedChainId(t){return V.activeChain?m.getRequestedCaipNetworks(V.activeChain)?.some(s=>s.id===t):!0},checkIfSmartAccountEnabled(){const t=zd.caipNetworkIdToNumber(V.activeCaipNetwork?.caipNetworkId);return!V.activeChain||!t?!1:!!(ig.get(no.SMART_ACCOUNT_ENABLED_NETWORKS)?.split(",")||[])?.includes(t.toString())},showUnsupportedChainUI(){pe.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=V.activeCaipNetwork;return!!(t?.chainNamespace&&we.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){m.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(t){const e=t;if(!e)throw new Error("Chain is required to set account prop");const s=m.state.chains.get(e)?.accountState?.preferredAccountType,n=S.state.defaultAccountTypes[e];V.activeCaipAddress=void 0,m.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountType:n||s,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,user:void 0,status:"disconnected"}),M.removeConnectorId(e)},setIsSwitchingNamespace(t){V.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){const t=[];let e;if(V.chains.forEach(s=>{D.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(n=>n===s.namespace)&&s.namespace&&t.push(s.namespace)}),t.length>0){const s=t[0];return e=s?V.chains.get(s)?.caipNetworks?.[0]:void 0,e}},getAccountData(t){const e=t||V.activeChain;if(e)return m.state.chains.get(e)?.accountState},getNetworkData(t){const e=t||V.activeChain;if(e)return m.state.chains.get(e)?.networkState},getCaipNetworkByNamespace(t,e){if(!t)return;const s=m.state.chains.get(t),n=s?.caipNetworks?.find(r=>r.id.toString()===e?.toString());return n||s?.networkState?.caipNetwork||s?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const t=M.state.filterByNamespace;return(t?[V.chains.get(t)]:Array.from(V.chains.values())).flatMap(s=>s?.caipNetworks||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?m.getRequestedCaipNetworks(t):m.getAllRequestedCaipNetworks()},getCaipNetworkById(t,e){return fh.getCaipNetworks(e).find(s=>s.id.toString()===t.toString()||s.caipNetworkId.toString()===t.toString())},setLastConnectedSIWECaipNetwork(t){V.lastConnectedSIWECaipNetwork=t},getLastConnectedSIWECaipNetwork(){return V.lastConnectedSIWECaipNetwork},async fetchTokenBalance(t){const e=m.getAccountData();if(!e)return[];const s=m.state.activeCaipNetwork?.caipNetworkId,n=m.state.activeCaipNetwork?.chainNamespace,r=m.state.activeCaipAddress,i=r?G.getPlainAddress(r):void 0;if(m.setAccountProp("balanceLoading",!0,n),e.lastRetry&&!G.isAllowedRetry(e.lastRetry,30*we.ONE_SEC_MS))return m.setAccountProp("balanceLoading",!1,n),[];try{if(i&&s&&n){const o=await Bc.getMyTokensWithBalance();return m.setAccountProp("tokenBalance",o,n),m.setAccountProp("lastRetry",void 0,n),m.setAccountProp("balanceLoading",!1,n),o}}catch(o){m.setAccountProp("lastRetry",Date.now(),n),t?.(o),hs.showError("Token Balance Unavailable")}finally{m.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(t){const e=t.chainNamespace,s=!!m.getAccountData(e)?.caipAddress,n=m.getAllApprovedCaipNetworkIds(),r=m.getNetworkProp("supportsAllNetworks",e)!==!1,i=M.getConnectorId(e),o=M.getAuthConnector(),a=i===D.CONNECTOR_ID.AUTH&&o;return!s||r||a?!1:!n?.includes(t.caipNetworkId)}},m=Vt(fh),mm={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const s=m.state.activeCaipNetwork,n=m.state.activeChain,r=se.state.data;if(t.id===s?.id)return;const o=!!m.getAccountData(n)?.address,a=!!m.getAccountData(t.chainNamespace)?.address,c=t.chainNamespace!==n,u=M.getConnectorId(n)===D.CONNECTOR_ID.AUTH,d=D.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(h=>h===t.chainNamespace);e||u&&d?se.push("SwitchNetwork",{...r,network:t}):o&&c&&!a?se.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):se.push("SwitchNetwork",{...r,network:t})}},ft=Re({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),wm={state:ft,subscribe(t){return Qe(ft,()=>t(ft))},subscribeKey(t,e){return et(ft,t,e)},async open(t){const e=t?.namespace,s=m.state.activeChain,n=e&&e!==s,r=m.getAccountData(t?.namespace)?.caipAddress,i=m.state.noAdapters;if(H.state.wcBasic?Z.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await Z.prefetch(),M.setFilterByNamespace(t?.namespace),pe.setLoading(!0,e),e&&n){const o=m.getNetworkData(e)?.caipNetwork||m.getRequestedCaipNetworks(e)[0];o&&(i?(await m.switchActiveNetwork(o),se.push("ConnectingWalletConnectBasic")):mm.onSwitchNetwork({network:o,ignoreSwitchConfirmation:!0}))}else S.state.manualWCControl||i&&!r?G.isMobile()?se.reset("AllWallets"):se.reset("ConnectingWalletConnectBasic"):t?.view?se.reset(t.view,t.data):r?se.reset("Account"):se.reset("Connect");ft.open=!0,ks.set({open:!0}),de.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!r}})},close(){const t=S.state.enableEmbedded,e=!!m.state.activeCaipAddress;ft.open&&de.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),ft.open=!1,se.reset("Connect"),pe.clearLoading(),t?e?se.replace("Account"):se.push("Connect"):ks.set({open:!1}),H.resetUri()},setLoading(t,e){e&&ft.loadingNamespaceMap.set(e,t),ft.loading=t,ks.set({loading:t})},clearLoading(){ft.loadingNamespaceMap.clear(),ft.loading=!1,ks.set({loading:!1})},shake(){ft.shake||(ft.shake=!0,setTimeout(()=>{ft.shake=!1},500))}},pe=Vt(wm),Lr={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},Ga={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},ym={providers:Qd,selectedProvider:null,error:null,purchaseCurrency:Lr,paymentCurrency:Ga,purchaseCurrencies:[Lr],paymentCurrencies:[],quotesLoading:!1},ye=Re(ym),bm={state:ye,subscribe(t){return Qe(ye,()=>t(ye))},subscribeKey(t,e){return et(ye,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=m.state.activeChain,s=e===D.CHAIN.SOLANA?"SOL":"USDC",n=e?m.state.chains.get(e)?.accountState?.address??"":"",r=new URL(t.url);r.searchParams.append("publicKey",rg),r.searchParams.append("destinationCurrencyCode",s),r.searchParams.append("walletAddress",n),r.searchParams.append("externalCustomerId",S.state.projectId),ye.selectedProvider={...t,url:r.toString()}}else ye.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=Qd.filter(n=>e.includes(n.name));ye.providers=s}else ye.providers=[]},setPurchaseCurrency(t){ye.purchaseCurrency=t},setPaymentCurrency(t){ye.paymentCurrency=t},setPurchaseAmount(t){Ya.state.purchaseAmount=t},setPaymentAmount(t){Ya.state.paymentAmount=t},async getAvailableCurrencies(){const t=await ie.getOnrampOptions();ye.purchaseCurrencies=t.purchaseCurrencies,ye.paymentCurrencies=t.paymentCurrencies,ye.paymentCurrency=t.paymentCurrencies[0]||Ga,ye.purchaseCurrency=t.purchaseCurrencies[0]||Lr,await Z.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await Z.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){ye.quotesLoading=!0;try{const t=await ie.getOnrampQuote({purchaseCurrency:ye.purchaseCurrency,paymentCurrency:ye.paymentCurrency,amount:ye.paymentAmount?.toString()||"0",network:ye.purchaseCurrency?.symbol});return ye.quotesLoading=!1,ye.purchaseAmount=Number(t?.purchaseAmount.amount),t}catch(t){return ye.error=t.message,ye.quotesLoading=!1,null}finally{ye.quotesLoading=!1}},resetState(){ye.selectedProvider=null,ye.error=null,ye.purchaseCurrency=Lr,ye.paymentCurrency=Ga,ye.purchaseCurrencies=[Lr],ye.paymentCurrencies=[],ye.paymentAmount=void 0,ye.purchaseAmount=void 0,ye.quotesLoading=!1}},Ya=Vt(bm);var vr={exports:{}},da,Ol;function vm(){if(Ol)return da;Ol=1;function t(s){try{return JSON.stringify(s)}catch{return'"[Circular]"'}}da=e;function e(s,n,r){var i=r&&r.stringify||t,o=1;if(typeof s=="object"&&s!==null){var a=n.length+o;if(a===1)return s;var c=new Array(a);c[0]=i(s);for(var l=1;l<a;l++)c[l]=i(n[l]);return c.join(" ")}if(typeof s!="string")return s;var u=n.length;if(u===0)return s;for(var d="",h=1-o,p=-1,f=s&&s.length||0,g=0;g<f;){if(s.charCodeAt(g)===37&&g+1<f){switch(p=p>-1?p:0,s.charCodeAt(g+1)){case 100:case 102:if(h>=u||n[h]==null)break;p<g&&(d+=s.slice(p,g)),d+=Number(n[h]),p=g+2,g++;break;case 105:if(h>=u||n[h]==null)break;p<g&&(d+=s.slice(p,g)),d+=Math.floor(Number(n[h])),p=g+2,g++;break;case 79:case 111:case 106:if(h>=u||n[h]===void 0)break;p<g&&(d+=s.slice(p,g));var w=typeof n[h];if(w==="string"){d+="'"+n[h]+"'",p=g+2,g++;break}if(w==="function"){d+=n[h].name||"<anonymous>",p=g+2,g++;break}d+=i(n[h]),p=g+2,g++;break;case 115:if(h>=u)break;p<g&&(d+=s.slice(p,g)),d+=String(n[h]),p=g+2,g++;break;case 37:p<g&&(d+=s.slice(p,g)),d+="%",p=g+2,g++,h--;break}++h}++g}return p===-1?s:(p<f&&(d+=s.slice(p)),d)}return da}var kl;function Em(){if(kl)return vr.exports;kl=1;const t=vm();vr.exports=u;const e=A().console||{},s={mapHttpRequest:K,mapHttpResponse:K,wrapRequestSerializer:Y,wrapResponseSerializer:Y,wrapErrorSerializer:Y,req:K,res:K,err:B,errWithCause:B};function n(y,b){return y==="silent"?1/0:b.levels.values[y]}const r=Symbol("pino.logFuncs"),i=Symbol("pino.hierarchy"),o={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function a(y,b){const N={logger:b,parent:y[i]};b[i]=N}function c(y,b,N){const T={};b.forEach(E=>{T[E]=N[E]?N[E]:e[E]||e[o[E]||"log"]||k}),y[r]=T}function l(y,b){return Array.isArray(y)?y.filter(function(T){return T!=="!stdSerializers.err"}):y===!0?Object.keys(b):!1}function u(y){y=y||{},y.browser=y.browser||{};const b=y.browser.transmit;if(b&&typeof b.send!="function")throw Error("pino: transmit option must have a send function");const N=y.browser.write||e;y.browser.write&&(y.browser.asObject=!0);const T=y.serializers||{},E=l(y.browser.serialize,T);let O=y.browser.serialize;Array.isArray(y.browser.serialize)&&y.browser.serialize.indexOf("!stdSerializers.err")>-1&&(O=!1);const F=Object.keys(y.customLevels||{}),$=["error","fatal","warn","info","debug","trace"].concat(F);typeof N=="function"&&$.forEach(function(he){N[he]=N}),(y.enabled===!1||y.browser.disabled)&&(y.level="silent");const re=y.level||"info",U=Object.create(N);U.log||(U.log=k),c(U,$,N),a({},U),Object.defineProperty(U,"levelVal",{get:oe}),Object.defineProperty(U,"level",{get:ce,set:Ie});const J={transmit:b,serialize:E,asObject:y.browser.asObject,asObjectBindingsOnly:y.browser.asObjectBindingsOnly,formatters:y.browser.formatters,levels:$,timestamp:j(y),messageKey:y.messageKey||"msg",onChild:y.onChild||k};U.levels=d(y),U.level=re,U.isLevelEnabled=function(he){return this.levels.values[he]?this.levels.values[he]>=this.levels.values[this.level]:!1},U.setMaxListeners=U.getMaxListeners=U.emit=U.addListener=U.on=U.prependListener=U.once=U.prependOnceListener=U.removeListener=U.removeAllListeners=U.listeners=U.listenerCount=U.eventNames=U.write=U.flush=k,U.serializers=T,U._serialize=E,U._stdErrSerialize=O,U.child=function(...he){return le.call(this,J,...he)},b&&(U._logEvent=L());function oe(){return n(this.level,this)}function ce(){return this._level}function Ie(he){if(he!=="silent"&&!this.levels.values[he])throw Error("unknown level "+he);this._level=he,f(this,J,U,"error"),f(this,J,U,"fatal"),f(this,J,U,"warn"),f(this,J,U,"info"),f(this,J,U,"debug"),f(this,J,U,"trace"),F.forEach(Le=>{f(this,J,U,Le)})}function le(he,Le,dt){if(!Le)throw new Error("missing bindings for child Pino");dt=dt||{},E&&Le.serializers&&(dt.serializers=Le.serializers);const rs=dt.serializers;if(E&&rs){var Kt=Object.assign({},T,rs),ki=y.browser.serialize===!0?Object.keys(Kt):E;delete Le.serializers,v([Le],ki,Kt,this._stdErrSerialize)}function dl(Pi){this._childLevel=(Pi._childLevel|0)+1,this.bindings=Le,Kt&&(this.serializers=Kt,this._serialize=ki),b&&(this._logEvent=L([].concat(Pi._logEvent.bindings,Le)))}dl.prototype=this;const wr=new dl(this);return a(this,wr),wr.child=function(...Pi){return le.call(this,he,...Pi)},wr.level=dt.level||this.level,he.onChild(wr),wr}return U}function d(y){const b=y.customLevels||{},N=Object.assign({},u.levels.values,b),T=Object.assign({},u.levels.labels,h(b));return{values:N,labels:T}}function h(y){const b={};return Object.keys(y).forEach(function(N){b[y[N]]=N}),b}u.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},u.stdSerializers=s,u.stdTimeFunctions=Object.assign({},{nullTime:te,epochTime:ne,unixTime:P,isoTime:I});function p(y){const b=[];y.bindings&&b.push(y.bindings);let N=y[i];for(;N.parent;)N=N.parent,N.logger.bindings&&b.push(N.logger.bindings);return b.reverse()}function f(y,b,N,T){if(Object.defineProperty(y,T,{value:n(y.level,N)>n(T,N)?k:N[r][T],writable:!0,enumerable:!0,configurable:!0}),y[T]===k){if(!b.transmit)return;const O=b.transmit.level||y.level,F=n(O,N);if(n(T,N)<F)return}y[T]=w(y,b,N,T);const E=p(y);E.length!==0&&(y[T]=g(E,y[T]))}function g(y,b){return function(){return b.apply(this,[...y,...arguments])}}function w(y,b,N,T){return(function(E){return function(){const F=b.timestamp(),$=new Array(arguments.length),re=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var U=0;U<$.length;U++)$[U]=arguments[U];var J=!1;if(b.serialize&&(v($,this._serialize,this.serializers,this._stdErrSerialize),J=!0),b.asObject||b.formatters?E.call(re,...C(this,T,$,F,b)):E.apply(re,$),b.transmit){const oe=b.transmit.level||y._level,ce=n(oe,N),Ie=n(T,N);if(Ie<ce)return;_(this,{ts:F,methodLevel:T,methodValue:Ie,transmitValue:N.levels.values[b.transmit.level||y._level],send:b.transmit.send,val:n(y._level,N)},$,J)}}})(y[r][T])}function C(y,b,N,T,E){const{level:O,log:F=oe=>oe}=E.formatters||{},$=N.slice();let re=$[0];const U={};let J=(y._childLevel|0)+1;if(J<1&&(J=1),T&&(U.time=T),O){const oe=O(b,y.levels.values[b]);Object.assign(U,oe)}else U.level=y.levels.values[b];if(E.asObjectBindingsOnly){if(re!==null&&typeof re=="object")for(;J--&&typeof $[0]=="object";)Object.assign(U,$.shift());return[F(U),...$]}else{if(re!==null&&typeof re=="object"){for(;J--&&typeof $[0]=="object";)Object.assign(U,$.shift());re=$.length?t($.shift(),$):void 0}else typeof re=="string"&&(re=t($.shift(),$));return re!==void 0&&(U[E.messageKey]=re),[F(U)]}}function v(y,b,N,T){for(const E in y)if(T&&y[E]instanceof Error)y[E]=u.stdSerializers.err(y[E]);else if(typeof y[E]=="object"&&!Array.isArray(y[E])&&b)for(const O in y[E])b.indexOf(O)>-1&&O in N&&(y[E][O]=N[O](y[E][O]))}function _(y,b,N,T=!1){const E=b.send,O=b.ts,F=b.methodLevel,$=b.methodValue,re=b.val,U=y._logEvent.bindings;T||v(N,y._serialize||Object.keys(y.serializers),y.serializers,y._stdErrSerialize===void 0?!0:y._stdErrSerialize),y._logEvent.ts=O,y._logEvent.messages=N.filter(function(J){return U.indexOf(J)===-1}),y._logEvent.level.label=F,y._logEvent.level.value=$,E(F,y._logEvent,re),y._logEvent=L(U)}function L(y){return{ts:0,messages:[],bindings:y||[],level:{label:"",value:0}}}function B(y){const b={type:y.constructor.name,msg:y.message,stack:y.stack};for(const N in y)b[N]===void 0&&(b[N]=y[N]);return b}function j(y){return typeof y.timestamp=="function"?y.timestamp:y.timestamp===!1?te:ne}function K(){return{}}function Y(y){return y}function k(){}function te(){return!1}function ne(){return Date.now()}function P(){return Math.round(Date.now()/1e3)}function I(){return new Date(Date.now()).toISOString()}function A(){function y(b){return typeof b<"u"&&b}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return y(self)||y(window)||y(this)||{}}}return vr.exports.default=u,vr.exports.pino=u,vr.exports}var es=Em();const Bo=hf(es),Pl=2147483648,Cm={convertEVMChainIdToCoinType(t){if(t>=Pl)throw new Error("Invalid chainId");return(Pl|t)>>>0}},xt=Re({suggestions:[],loading:!1}),Im={state:xt,subscribe(t){return Qe(xt,()=>t(xt))},subscribeKey(t,e){return et(xt,t,e)},async resolveName(t){try{return await ie.lookupEnsName(t)}catch(e){const s=e;throw new Error(s?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(t){try{return await ie.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{xt.loading=!0,xt.suggestions=[];const e=await ie.getEnsNameSuggestions(t);return xt.suggestions=e.suggestions||[],xt.suggestions}catch(e){const s=Mr.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{xt.loading=!1}},async getNamesForAddress(t){try{if(!m.state.activeCaipNetwork)return[];const s=x.getEnsFromCacheForAddress(t);if(s)return s;const n=await ie.reverseLookupEnsName({address:t});return x.updateEnsCache({address:t,ens:n,timestamp:Date.now()}),n}catch(e){const s=Mr.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){const e=m.state.activeCaipNetwork,s=m.getAccountData(e?.chainNamespace)?.address,n=M.getAuthConnector();if(!e)throw new Error("Network not found");if(!s||!n)throw new Error("Address or auth connector not found");xt.loading=!0;try{const r=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});se.pushTransactionStack({onCancel(){se.replace("RegisterAccountName")}});const i=await H.signMessage(r);xt.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=Cm.convertEVMChainIdToCoinType(Number(o));await ie.registerEnsName({coinType:a,address:s,signature:i,message:r}),m.setAccountProp("profileName",t,e.chainNamespace),x.updateEnsCache({address:s,ens:[{name:t,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),se.replace("RegisterAccountNameSuccess")}catch(r){const i=Mr.parseEnsApiError(r,`Error registering name ${t}`);throw se.replace("RegisterAccountName"),new Error(i)}finally{xt.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){return t?.reasons?.[0]?.description||e}},Mr=Vt(Im),Am={solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},tn={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace(t){return Am[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const s={...t},n=new Set;if(e.methods&&Object.keys(e.methods).forEach(r=>n.add(r)),e.chains&&Object.keys(e.chains).forEach(r=>n.add(r)),e.events&&Object.keys(e.events).forEach(r=>n.add(r)),e.rpcMap&&Object.keys(e.rpcMap).forEach(r=>{const[i]=r.split(":");i&&n.add(i)}),n.forEach(r=>{s[r]||(s[r]=this.createDefaultNamespace(r))}),e.methods&&Object.entries(e.methods).forEach(([r,i])=>{s[r]&&(s[r].methods=i)}),e.chains&&Object.entries(e.chains).forEach(([r,i])=>{s[r]&&(s[r].chains=i)}),e.events&&Object.entries(e.events).forEach(([r,i])=>{s[r]&&(s[r].events=i)}),e.rpcMap){const r=new Set;Object.entries(e.rpcMap).forEach(([i,o])=>{const[a,c]=i.split(":");!a||!c||!s[a]||(s[a].rpcMap||(s[a].rpcMap={}),r.has(a)||(s[a].rpcMap={},r.add(a)),s[a].rpcMap[c]=o)})}return s},createNamespaces(t,e){const s=t.reduce((n,r)=>{const{id:i,chainNamespace:o,rpcUrls:a}=r,c=a.default.http[0];n[o]||(n[o]=this.createDefaultNamespace(o));const l=`${o}:${i}`,u=n[o];switch(u.chains.push(l),l){case"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":u.chains.push("solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ");break;case"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":u.chains.push("solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K");break}return u?.rpcMap&&c&&(u.rpcMap[i]=c),n},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{const e=await Mr.resolveName(t);return(Object.values(e?.addresses)||[])[0]?.address||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],n=e.accounts.map(r=>{const[i,o]=r.split(":");return`${i}:${o}`});return Array.from(new Set([...s,...n]))})},isSessionEventData(t){return typeof t=="object"&&t!==null&&"id"in t&&"topic"in t&&"params"in t&&typeof t.params=="object"&&t.params!==null&&"chainId"in t.params&&"event"in t.params&&typeof t.params.event=="object"&&t.params.event!==null},isUserRejectedRequestError(t){try{if(typeof t=="object"&&t!==null){const e=t,s=typeof e.code=="number",n=s&&e.code===tn.RPC_ERROR_CODE.USER_REJECTED_METHODS,r=s&&e.code===tn.RPC_ERROR_CODE.USER_REJECTED;return n||r}return!1}catch{return!1}},isOriginAllowed(t,e,s){for(const n of[...e,...s])if(n.includes("*")){const i=`^${n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(i,"u").test(t))return!0}else try{if(new URL(n).origin===t)return!0}catch{if(n===t)return!0}return!1},listenWcProvider({universalProvider:t,namespace:e,onConnect:s,onDisconnect:n,onAccountsChanged:r,onChainChanged:i,onDisplayUri:o}){s&&t.on("connect",()=>{const a=tn.getWalletConnectAccounts(t,e);s(a)}),n&&t.on("disconnect",()=>{n()}),r&&t.on("accountsChanged",a=>{try{const c=t.session?.namespaces?.[e]?.accounts||[],l=t.rpcProviders?.[e]?.getDefaultChain(),u=a.map(d=>{const h=c.find(g=>g.includes(`${e}:${l}:${d}`));if(!h)return;const{chainId:p,chainNamespace:f}=Ze.parseCaipAddress(h);return{address:d,chainId:p,chainNamespace:f}}).filter(d=>d!==void 0);u.length>0&&r(u)}catch(c){console.warn("Failed to parse accounts for namespace on accountsChanged event",e,a,c)}}),i&&t.on("chainChanged",a=>{i(a)}),o&&t.on("display_uri",a=>{o(a)})},getWalletConnectAccounts(t,e){const s=new Set,n=t?.session?.namespaces?.[e]?.accounts?.map(r=>Ze.parseCaipAddress(r)).filter(({address:r})=>s.has(r.toLowerCase())?!1:(s.add(r.toLowerCase()),!0));return n&&n.length>0?n:[]}},Nm=[D.CONNECTOR_ID.AUTH,D.CONNECTOR_ID.WALLET_CONNECT];class _m{constructor(e){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=s=>m.getCaipNetworks(s),this.getConnectorId=s=>M.getConnectorId(s),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get connections(){return this.availableConnections}get networks(){return this.getCaipNetworks(this.namespace)}onAuthConnected({accounts:e,chainId:s}){const n=this.getCaipNetworks().filter(r=>r.chainNamespace===this.namespace).find(r=>r.id.toString()===s?.toString());e&&n&&this.addConnection({connectorId:D.CONNECTOR_ID.AUTH,accounts:e,caipNetwork:n})}setAuthProvider(e){e.onConnect(this.onAuthConnected.bind(this)),e.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:D.CONNECTOR_ID.AUTH,type:"AUTH",name:D.CONNECTOR_NAMES.AUTH,provider:e,imageId:void 0,chain:this.namespace,chains:[]})}addConnector(...e){const s=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(n=>s.has(n.id)?!1:(s.add(n.id),!0)),this.emit("connectors",this.availableConnectors)}addConnection(...e){const s=new Set;this.availableConnections=[...e,...this.availableConnections].filter(n=>s.has(n.connectorId.toLowerCase())?!1:(s.add(n.connectorId.toLowerCase()),!0)),this.emit("connections",this.availableConnections)}deleteConnection(e){this.availableConnections=this.availableConnections.filter(s=>s.connectorId.toLowerCase()!==e.toLowerCase()),this.emit("connections",this.availableConnections)}clearConnections(e=!1){this.availableConnections=[],e&&this.emit("connections",this.availableConnections)}setStatus(e,s){m.setAccountProp("status",e,s)}on(e,s){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(s)}off(e,s){const n=this.eventListeners.get(e);n&&n.delete(s)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const n=this.eventListeners.get(e);n&&n.forEach(r=>r(s))}async connectWalletConnect(e){try{return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}catch(s){throw tn.isUserRejectedRequestError(s)?new Xd(s):s}}async switchNetwork(e){const{caipNetwork:s}=e,n=$e.getProviderId(s.chainNamespace),r=$e.getProvider(s.chainNamespace);if(!r)throw new Error("Provider not found");if(n==="WALLET_CONNECT"){r.setDefaultChain(s.caipNetworkId);return}if(n==="AUTH"){const i=M.getAuthConnector()?.provider;if(!i)throw new Error("Auth provider not found");const o=Wt(s.chainNamespace);await i.switchNetwork({chainId:s.caipNetworkId});const a=await i.getUser({chainId:s.caipNetworkId,preferredAccountType:o});this.emit("switchNetwork",a)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s.id==="walletConnect");if(!e)throw new Error("WalletConnectConnector not found");return e}onConnect(e,s){if(e.length>0){const{address:n,chainId:r}=G.getAccount(e[0]),i=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===r?.toString()),o=this.connectors.find(a=>a.id===s);n&&(this.emit("accountChanged",{address:n,chainId:r,connector:o}),this.addConnection({connectorId:s,accounts:e.map(a=>{const{address:c}=G.getAccount(a);return{address:c}}),caipNetwork:i}))}}onAccountsChanged(e,s,n=!0){if(e.length>0){const{address:r}=G.getAccount(e[0]),i=this.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors});r&&this.getConnectorId(D.CHAIN.EVM)?.toLowerCase()===s.toLowerCase()&&this.emit("accountChanged",{address:r,chainId:i?.caipNetwork?.id,connector:i?.connector}),this.addConnection({connectorId:s,accounts:e.map(o=>{const{address:a}=G.getAccount(o);return{address:a}}),caipNetwork:i?.caipNetwork})}else n&&this.onDisconnect(s)}onDisconnect(e){this.removeProviderListeners(e),this.deleteConnection(e),this.getConnectorId(D.CHAIN.EVM)?.toLowerCase()===e.toLowerCase()&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(e,s){const n=typeof e=="string"&&e.startsWith("0x")?parseInt(e,16).toString():e.toString(),r=this.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors}),i=this.getCaipNetworks().filter(o=>o.chainNamespace===this.namespace).find(o=>o.id.toString()===n);r&&this.addConnection({connectorId:s,accounts:r.accounts,caipNetwork:i}),this.getConnectorId(D.CHAIN.EVM)?.toLowerCase()===s.toLowerCase()&&this.emit("switchNetwork",{chainId:n})}listenProviderEvents(e,s){if(Nm.includes(e))return;const n=o=>this.onAccountsChanged(o,e),r=o=>this.onChainChanged(o,e),i=()=>this.onDisconnect(e);this.providerHandlers[e]||(s.on("disconnect",i),s.on("accountsChanged",n),s.on("chainChanged",r),this.providerHandlers[e]={provider:s,disconnect:i,accountsChanged:n,chainChanged:r})}removeProviderListeners(e){if(this.providerHandlers[e]){const{provider:s,disconnect:n,accountsChanged:r,chainChanged:i}=this.providerHandlers[e];s.removeListener("disconnect",n),s.removeListener("accountsChanged",r),s.removeListener("chainChanged",i),this.providerHandlers[e]=null}}emitFirstAvailableConnection(){const e=this.getConnection({connections:this.connections,connectors:this.connectors});if(e){const[s]=e.accounts;this.emit("accountChanged",{address:s?.address,chainId:e.caipNetwork?.id,connector:e.connector})}}getConnection({address:e,connectorId:s,connections:n,connectors:r}){if(s){const o=n.find(l=>l.connectorId.toLowerCase()===s.toLowerCase());if(!o)return null;const a=r.find(l=>l.id.toLowerCase()===o.connectorId.toLowerCase()),c=e?o.accounts.find(l=>l.address.toLowerCase()===e.toLowerCase()):o.accounts[0];return{...o,account:c,connector:a}}const i=n.find(o=>o.accounts.length>0&&r.some(a=>a.id.toLowerCase()===o.connectorId.toLowerCase()));if(i){const[o]=i.accounts,a=r.find(c=>c.id.toLowerCase()===i.connectorId.toLowerCase());return{...i,account:o,connector:a}}return null}}let ln=null;const Qt={getSIWX(){return S.state.siwx},async initializeIfEnabled(t=m.getActiveCaipAddress()){const e=S.state.siwx;if(!(e&&t))return;const[s,n,r]=t.split(":");if(m.checkIfSupportedNetwork(s,`${s}:${n}`))try{if(S.state.remoteFeatures?.emailCapture){const o=m.getAccountData(s)?.user;await pe.open({view:"DataCapture",data:{email:o?.email??void 0}});return}if(ln&&await ln,(await e.getSessions(`${s}:${n}`,r)).length)return;await pe.open({view:"SIWXSignMessage"})}catch(i){console.error("SIWXUtil:initializeIfEnabled",i),de.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(i)}),await H._getClient()?.disconnect().catch(console.error),se.reset("Connect"),hs.showError("A problem occurred while trying initialize authentication")}},async isAuthenticated(t=m.getActiveCaipAddress()){if(!S.state.siwx||!t)return!0;const{chainNamespace:s,chainId:n,address:r}=Ze.parseCaipAddress(t),i=`${s}:${n}`;return(await Qt.getSessions({address:r,caipNetworkId:i})).length>0},async requestSignMessage(){const t=S.state.siwx,e=G.getPlainAddress(m.getActiveCaipAddress()),s=Bi(),n=H._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!n)throw new Error("No ConnectionController client found");try{const r=await t.createMessage({chainId:s.caipNetworkId,accountAddress:e}),i=r.toString();M.getConnectorId(s.chainNamespace)===D.CONNECTOR_ID.AUTH&&se.pushTransactionStack({});const a=await n.signMessage(i);await t.addSession({data:r,message:i,signature:a}),m.setLastConnectedSIWECaipNetwork(s),pe.close(),de.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(r){(!pe.state.open||se.state.view==="ApproveTransaction")&&await pe.open({view:"SIWXSignMessage"}),hs.showError("Error signing message"),de.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(r)}),console.error("SWIXUtil:requestSignMessage",r)}},async cancelSignMessage(){try{const t=this.getSIWX();if(t?.getRequired?.()){const s=m.getLastConnectedSIWECaipNetwork();if(s){const n=await t?.getSessions(s?.caipNetworkId,G.getPlainAddress(m.getActiveCaipAddress())||"");n&&n.length>0?await m.switchActiveNetwork(s):await H.disconnect()}else await H.disconnect()}else pe.close();pe.close(),de.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){console.error("SIWXUtil:cancelSignMessage",t)}},async getAllSessions(){const t=this.getSIWX(),e=m.getAllRequestedCaipNetworks(),s=[];return await Promise.all(e.map(async n=>{const r=await t?.getSessions(n.caipNetworkId,G.getPlainAddress(m.getActiveCaipAddress())||"");r&&s.push(...r)})),s},async getSessions(t){const e=S.state.siwx;let s=t?.address;if(!s){const r=m.getActiveCaipAddress();s=G.getPlainAddress(r)}let n=t?.caipNetworkId;return n||(n=m.getActiveCaipNetwork()?.caipNetworkId),e&&s&&n?e.getSessions(n,s):[]},async isSIWXCloseDisabled(){const t=this.getSIWX();if(t){const e=se.state.view==="ApproveTransaction",s=se.state.view==="SIWXSignMessage";if(e||s)return t.getRequired?.()&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:t,chainId:e,socialUri:s,preferredAccountType:n,chainNamespace:r}){const i=Qt.getSIWX(),o=Bi();if(!i||!r.includes(D.CHAIN.EVM)||S.state.remoteFeatures?.emailCapture){const d=await t.connect({chainId:e,socialUri:s,preferredAccountType:n});return{address:d.address,chainId:d.chainId,accounts:d.accounts}}const a=`${r}:${e}`,c=await i.createMessage({chainId:a,accountAddress:"<<AccountAddress>>"}),l={accountAddress:c.accountAddress,chainId:c.chainId,domain:c.domain,uri:c.uri,version:c.version,nonce:c.nonce,notBefore:c.notBefore,statement:c.statement,resources:c.resources,requestId:c.requestId,issuedAt:c.issuedAt,expirationTime:c.expirationTime,serializedMessage:c.toString()},u=await t.connect({chainId:e,socialUri:s,siwxMessage:l,preferredAccountType:n});return l.accountAddress=u.address,l.serializedMessage=u.message||"",u.signature&&u.message&&await Qt.addEmbeddedWalletSession(l,u.message,u.signature),m.setLastConnectedSIWECaipNetwork(o),{address:u.address,chainId:u.chainId,accounts:u.accounts}},async addEmbeddedWalletSession(t,e,s){if(ln)return ln;const n=Qt.getSIWX();return n?(ln=n.addSession({data:t,message:e,signature:s}).finally(()=>{ln=null}),ln):Promise.resolve()},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){const n=Qt.getSIWX(),r=Bi(),i=new Set(e.map(l=>l.split(":")[0]));if(!n||i.size!==1||!i.has("eip155"))return!1;const o=await n.createMessage({chainId:Bi()?.caipNetworkId||"",accountAddress:""}),a=await t.authenticate({nonce:o.nonce,domain:o.domain,uri:o.uri,exp:o.expirationTime,iat:o.issuedAt,nbf:o.notBefore,requestId:o.requestId,version:o.version,resources:o.resources,statement:o.statement,chainId:o.chainId,methods:s,chains:[o.chainId,...e.filter(l=>l!==o.chainId)]});hs.showLoading("Authenticating...",{autoClose:!1});const c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:a.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"};if(m.setAccountProp("connectedWalletInfo",c,Array.from(i)[0]),a?.auths?.length){const l=a.auths.map(u=>{const d=t.client.formatAuthMessage({request:u.p,iss:u.p.iss});return{data:{...u.p,accountAddress:u.p.iss.split(":").slice(-1).join(""),chainId:u.p.iss.split(":").slice(2,4).join(":"),uri:u.p.aud,version:u.p.version||o.version,expirationTime:u.p.exp,issuedAt:u.p.iat,notBefore:u.p.nbf},message:d,signature:u.s.s,cacao:u}});try{await n.setSessions(l),r&&m.setLastConnectedSIWECaipNetwork(r),de.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:Qt.getSIWXEventProperties()})}catch(u){throw console.error("SIWX:universalProviderAuth - failed to set sessions",u),de.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:Qt.getSIWXEventProperties(u)}),await t.disconnect().catch(console.error),u}finally{hs.hide()}}return!0},getSIWXEventProperties(t){const e=m.state.activeChain;if(!e)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:m.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:Wt(e)===Os.ACCOUNT_TYPES.SMART_ACCOUNT,message:t?G.parseError(t):void 0}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};class Sm{constructor({provider:e,namespace:s}){this.id=D.CONNECTOR_ID.WALLET_CONNECT,this.name="WalletConnect",this.type="WALLET_CONNECT",this.imageId="ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",this.getCaipNetworks=m.getCaipNetworks.bind(m),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=s}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const s=this.getCaipNetworks(),n=S.state.universalProviderConfigOverride,r=tn.createNamespaces(s,n);await this.provider.connect({optionalNamespaces:r})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(s=>s.caipNetworkId);return Qt.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:Tm})}}const Tm=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],zt=Re({message:"",variant:"info",open:!1}),Om={state:zt,subscribeKey(t,e){return et(zt,t,e)},open(t,e){const{debug:s}=S.state,{code:n,displayMessage:r,debugMessage:i}=t;r&&s&&(zt.message=r,zt.variant=e,zt.open=!0),i&&console.error(typeof i=="function"?i():i,n?{code:n}:void 0)},warn(t,e,s){zt.open=!0,zt.message=t,zt.variant="warning",e&&console.warn(e,s)},close(){zt.open=!1,zt.message="",zt.variant="info"}},_t=Vt(Om),km={asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"},Pm={asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"};function Rm(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function ze(t,...e){try{return Rm(t(...e))}catch(s){return Promise.reject(s)}}function xm(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function $m(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function io(t){if(xm(t))return String(t);if($m(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return io(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ja="base64:";function Um(t){return typeof t=="string"?t:Ja+Mm(t)}function Dm(t){return typeof t!="string"||!t.startsWith(Ja)?t:Lm(t.slice(Ja.length))}function Lm(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function Mm(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function mt(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Bm(...t){return mt(t.join(":"))}function Fi(t){return t=mt(t),t?t+":":""}function jm(t,e){if(e===void 0)return!0;let s=0,n=t.indexOf(":");for(;n>-1;)s++,n=t.indexOf(":",n+1);return s<=e}function Fm(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const qm="memory",Wm=()=>{const t=new Map;return{name:qm,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,s){t.set(e,s)},setItemRaw(e,s){t.set(e,s)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Hm(t={}){const e={mounts:{"":t.driver||Wm()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},s=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},n=(l,u)=>e.mountpoints.filter(d=>d.startsWith(l)||u&&l.startsWith(d)).map(d=>({relativeBase:l.length>d.length?l.slice(d.length):void 0,mountpoint:d,driver:e.mounts[d]})),r=(l,u)=>{if(e.watching){u=mt(u);for(const d of e.watchListeners)d(l,u)}},i=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await Rl(e.mounts[l],r,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,d)=>{const h=new Map,p=f=>{let g=h.get(f.base);return g||(g={driver:f.driver,base:f.base,items:[]},h.set(f.base,g)),g};for(const f of l){const g=typeof f=="string",w=mt(g?f:f.key),C=g?void 0:f.value,v=g||!f.options?u:{...u,...f.options},_=s(w);p(_).items.push({key:w,value:C,relativeKey:_.relativeKey,options:v})}return Promise.all([...h.values()].map(f=>d(f))).then(f=>f.flat())},c={hasItem(l,u={}){l=mt(l);const{relativeKey:d,driver:h}=s(l);return ze(h.hasItem,d,u)},getItem(l,u={}){l=mt(l);const{relativeKey:d,driver:h}=s(l);return ze(h.getItem,d,u).then(p=>Ri(p))},getItems(l,u={}){return a(l,u,d=>d.driver.getItems?ze(d.driver.getItems,d.items.map(h=>({key:h.relativeKey,options:h.options})),u).then(h=>h.map(p=>({key:Bm(d.base,p.key),value:Ri(p.value)}))):Promise.all(d.items.map(h=>ze(d.driver.getItem,h.relativeKey,h.options).then(p=>({key:h.key,value:Ri(p)})))))},getItemRaw(l,u={}){l=mt(l);const{relativeKey:d,driver:h}=s(l);return h.getItemRaw?ze(h.getItemRaw,d,u):ze(h.getItem,d,u).then(p=>Dm(p))},async setItem(l,u,d={}){if(u===void 0)return c.removeItem(l);l=mt(l);const{relativeKey:h,driver:p}=s(l);p.setItem&&(await ze(p.setItem,h,io(u),d),p.watch||r("update",l))},async setItems(l,u){await a(l,u,async d=>{if(d.driver.setItems)return ze(d.driver.setItems,d.items.map(h=>({key:h.relativeKey,value:io(h.value),options:h.options})),u);d.driver.setItem&&await Promise.all(d.items.map(h=>ze(d.driver.setItem,h.relativeKey,io(h.value),h.options)))})},async setItemRaw(l,u,d={}){if(u===void 0)return c.removeItem(l,d);l=mt(l);const{relativeKey:h,driver:p}=s(l);if(p.setItemRaw)await ze(p.setItemRaw,h,u,d);else if(p.setItem)await ze(p.setItem,h,Um(u),d);else return;p.watch||r("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=mt(l);const{relativeKey:d,driver:h}=s(l);h.removeItem&&(await ze(h.removeItem,d,u),(u.removeMeta||u.removeMata)&&await ze(h.removeItem,d+"$",u),h.watch||r("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=mt(l);const{relativeKey:d,driver:h}=s(l),p=Object.create(null);if(h.getMeta&&Object.assign(p,await ze(h.getMeta,d,u)),!u.nativeOnly){const f=await ze(h.getItem,d+"$",u).then(g=>Ri(g));f&&typeof f=="object"&&(typeof f.atime=="string"&&(f.atime=new Date(f.atime)),typeof f.mtime=="string"&&(f.mtime=new Date(f.mtime)),Object.assign(p,f))}return p},setMeta(l,u,d={}){return this.setItem(l+"$",u,d)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){l=Fi(l);const d=n(l,!0);let h=[];const p=[];let f=!0;for(const w of d){w.driver.flags?.maxDepth||(f=!1);const C=await ze(w.driver.getKeys,w.relativeBase,u);for(const v of C){const _=w.mountpoint+mt(v);h.some(L=>_.startsWith(L))||p.push(_)}h=[w.mountpoint,...h.filter(v=>!v.startsWith(w.mountpoint))]}const g=u.maxDepth!==void 0&&!f;return p.filter(w=>(!g||jm(w,u.maxDepth))&&Fm(w,l))},async clear(l,u={}){l=Fi(l),await Promise.all(n(l,!1).map(async d=>{if(d.driver.clear)return ze(d.driver.clear,d.relativeBase,u);if(d.driver.removeItem){const h=await d.driver.getKeys(d.relativeBase||"",u);return Promise.all(h.map(p=>d.driver.removeItem(p,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>xl(l)))},async watch(l){return await i(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=Fi(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((d,h)=>h.length-d.length)),e.mounts[l]=u,e.watching&&Promise.resolve(Rl(u,r,l)).then(d=>{e.unwatch[l]=d}).catch(console.error),c},async unmount(l,u=!0){l=Fi(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&(e.unwatch[l]?.(),delete e.unwatch[l]),u&&await xl(e.mounts[l]),e.mountpoints=e.mountpoints.filter(d=>d!==l),delete e.mounts[l])},getMount(l=""){l=mt(l)+":";const u=s(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=mt(l),n(l,u.parents).map(h=>({driver:h.driver,base:h.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,d={})=>c.setItem(l,u,d),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function Rl(t,e,s){return t.watch?t.watch((n,r)=>e(n,s+r)):()=>{}}async function xl(t){typeof t.dispose=="function"&&await ze(t.dispose)}const Vm="idb-keyval";var Km=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",s=r=>e+r;let n;return t.dbName&&t.storeName&&(n=pf(t.dbName,t.storeName)),{name:Vm,options:t,async hasItem(r){return!(typeof await hl(s(r),n)>"u")},async getItem(r){return await hl(s(r),n)??null},setItem(r,i){return wf(s(r),i,n)},removeItem(r){return mf(s(r),n)},getKeys(){return gf(n)},clear(){return ff(n)}}};const zm="WALLET_CONNECT_V2_INDEXED_DB",Gm="keyvaluestorage";let Ym=class{constructor(){this.indexedDb=Hm({driver:Km({dbName:zm,storeName:Gm})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const s=await this.indexedDb.getItem(e);if(s!==null)return s}async setItem(e,s){await this.indexedDb.setItem(e,On(s))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ha=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},oo={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(s){return this.hasOwnProperty(s)?String(this[s]):null},t.prototype.setItem=function(s,n){this[s]=String(n)},t.prototype.removeItem=function(s){delete this[s]},t.prototype.clear=function(){const s=this;Object.keys(s).forEach(function(n){s[n]=void 0,delete s[n]})},t.prototype.key=function(s){return s=s||0,Object.keys(this)[s]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ha<"u"&&ha.localStorage?oo.exports=ha.localStorage:typeof window<"u"&&window.localStorage?oo.exports=window.localStorage:oo.exports=new e})();function Jm(t){var e;return[t[0],go((e=t[1])!=null?e:"")]}let Xm=class{constructor(){this.localStorage=oo.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Jm)}async getItem(e){const s=this.localStorage.getItem(e);if(s!==null)return go(s)}async setItem(e,s){this.localStorage.setItem(e,On(s))}async removeItem(e){this.localStorage.removeItem(e)}};const Zm="wc_storage_version",$l=1,Qm=async(t,e,s)=>{const n=Zm,r=await e.getItem(n);if(r&&r>=$l){s(e);return}const i=await t.getKeys();if(!i.length){s(e);return}const o=[];for(;i.length;){const a=i.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(n,$l),s(e),ew(t,o)},ew=async(t,e)=>{e.length&&e.forEach(async s=>{await t.removeItem(s)})};let tw=class{constructor(){this.initialized=!1,this.setInitialized=s=>{this.storage=s,this.initialized=!0};const e=new Xm;this.storage=e;try{const s=new Ym;Qm(e,s,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,s){return await this.initialize(),this.storage.setItem(e,s)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const s=setInterval(()=>{this.initialized&&(clearInterval(s),e())},20)})}};const sw={level:"info"},jo="custom_context",jc=1e3*1024;var nw=Object.defineProperty,rw=(t,e,s)=>e in t?nw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ys=(t,e,s)=>rw(t,typeof e!="symbol"?e+"":e,s);let iw=class{constructor(e){Ys(this,"nodeValue"),Ys(this,"sizeInBytes"),Ys(this,"next"),this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Ul=class{constructor(e){Ys(this,"lengthInNodes"),Ys(this,"sizeInBytes"),Ys(this,"head"),Ys(this,"tail"),Ys(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const s=new iw(e);if(s.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${s.size}`);for(;this.size+s.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=s),this.tail=s):(this.head=s,this.tail=s),this.lengthInNodes++,this.sizeInBytes+=s.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let s=this.head;for(;s!==null;)e.push(s.value),s=s.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const s=e.value;return e=e.next,{done:!1,value:s}}}}};var ow=Object.defineProperty,aw=(t,e,s)=>e in t?ow(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qi=(t,e,s)=>aw(t,typeof e!="symbol"?e+"":e,s);let gh=class{constructor(e,s=jc){qi(this,"logs"),qi(this,"level"),qi(this,"levelValue"),qi(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=es.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=s,this.logs=new Ul(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,s){s===es.levels.values.error?console.error(e):s===es.levels.values.warn?console.warn(e):s===es.levels.values.debug?console.debug(e):s===es.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(On({timestamp:new Date().toISOString(),log:e}));const s=typeof e=="string"?JSON.parse(e).level:e.level;s>=this.levelValue&&this.forwardToConsole(e,s)}getLogs(){return this.logs}clearLogs(){this.logs=new Ul(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const s=this.getLogArray();return s.push(On({extraMetadata:e})),new Blob(s,{type:"application/json"})}};var cw=Object.defineProperty,lw=(t,e,s)=>e in t?cw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,uw=(t,e,s)=>lw(t,e+"",s);let dw=class{constructor(e,s=jc){uw(this,"baseChunkLogger"),this.baseChunkLogger=new gh(e,s)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const s=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=s,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}};var hw=Object.defineProperty,pw=(t,e,s)=>e in t?hw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fw=(t,e,s)=>pw(t,e+"",s);let gw=class{constructor(e,s=jc){fw(this,"baseChunkLogger"),this.baseChunkLogger=new gh(e,s)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var mw=Object.defineProperty,ww=Object.defineProperties,yw=Object.getOwnPropertyDescriptors,Dl=Object.getOwnPropertySymbols,bw=Object.prototype.hasOwnProperty,vw=Object.prototype.propertyIsEnumerable,Ll=(t,e,s)=>e in t?mw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Eo=(t,e)=>{for(var s in e||(e={}))bw.call(e,s)&&Ll(t,s,e[s]);if(Dl)for(var s of Dl(e))vw.call(e,s)&&Ll(t,s,e[s]);return t},Co=(t,e)=>ww(t,yw(e));function Ew(t){return Co(Eo({},t),{level:t?.level||sw.level})}function Cw(t,e,s=jo){return t[s]=e,t}function It(t,e=jo){return t[e]||""}function Iw(t,e,s=jo){const n=It(t,s);return n.trim()?`${n}/${e}`:e}function Rt(t,e,s=jo){const n=Iw(t,e,s),r=t.child({context:n});return Cw(r,n,s)}function Aw(t){var e,s;const n=new dw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Bo(Co(Eo({},t.opts),{level:"trace",browser:Co(Eo({},(s=t.opts)==null?void 0:s.browser),{write:r=>n.write(r)})})),chunkLoggerController:n}}function Nw(t){var e;const s=new gw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Bo(Co(Eo({},t.opts),{level:"trace"}),s),chunkLoggerController:s}}function mh(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Aw(t):Nw(t)}var _w=Object.defineProperty,Sw=(t,e,s)=>e in t?_w(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ml=(t,e,s)=>Sw(t,typeof e!="symbol"?e+"":e,s);let Tw=class extends hr{constructor(e){super(),this.opts=e,Ml(this,"protocol","wc"),Ml(this,"version",2)}};var Ow=Object.defineProperty,kw=(t,e,s)=>e in t?Ow(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Pw=(t,e,s)=>kw(t,e+"",s);let Rw=class extends hr{constructor(e,s){super(),this.core=e,this.logger=s,Pw(this,"records",new Map)}},xw=class{constructor(e,s){this.logger=e,this.core=s}},$w=class extends hr{constructor(e,s){super(),this.relayer=e,this.logger=s}},Uw=class extends hr{constructor(e){super()}},Dw=class{constructor(e,s,n,r){this.core=e,this.logger=s,this.name=n}},Lw=class extends hr{constructor(e,s){super(),this.relayer=e,this.logger=s}},Mw=class extends hr{constructor(e,s){super(),this.core=e,this.logger=s}},Bw=class{constructor(e,s,n){this.core=e,this.logger=s,this.store=n}},jw=class{constructor(e,s){this.projectId=e,this.logger=s}},Fw=class{constructor(e,s,n){this.core=e,this.logger=s,this.telemetryEnabled=n}};var qw=Object.defineProperty,Ww=(t,e,s)=>e in t?qw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Bl=(t,e,s)=>Ww(t,typeof e!="symbol"?e+"":e,s);let Hw=class{constructor(e){this.opts=e,Bl(this,"protocol","wc"),Bl(this,"version",2)}},Vw=class{constructor(e){this.client=e}};var Kw={};const zw=":";function Rs(t){const[e,s]=t.split(zw);return{namespace:e,reference:s}}function wh(t,e){return t.includes(":")?[t]:e.chains||[]}var Gw=Object.defineProperty,Yw=Object.defineProperties,Jw=Object.getOwnPropertyDescriptors,jl=Object.getOwnPropertySymbols,Xw=Object.prototype.hasOwnProperty,Zw=Object.prototype.propertyIsEnumerable,Xa=(t,e,s)=>e in t?Gw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Fl=(t,e)=>{for(var s in e||(e={}))Xw.call(e,s)&&Xa(t,s,e[s]);if(jl)for(var s of jl(e))Zw.call(e,s)&&Xa(t,s,e[s]);return t},Qw=(t,e)=>Yw(t,Jw(e)),ql=(t,e,s)=>Xa(t,typeof e!="symbol"?e+"":e,s);const ey="ReactNative",kt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},ty="js";function Io(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function on(){return!Us.getDocument()&&!!Us.getNavigator()&&navigator.product===ey}function sy(){return on()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function ny(){return on()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function gr(){return!Io()&&!!Us.getNavigator()&&!!Us.getDocument()}function Ii(){return on()?kt.reactNative:Io()?kt.node:gr()?kt.browser:kt.unknown}function Wl(){var t;try{return on()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function ry(t,e){const s=new URLSearchParams(t);return Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!=null&&s.set(n,String(r))}),s.toString()}function iy(t){var e,s;const n=yh();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(r=>r!=="")),Qw(Fl(Fl({},n),t),{url:t?.url||n.url,name:t?.name||n.name,description:t?.description||n.description,icons:(s=t?.icons)!=null&&s.length&&t.icons.length>0?t.icons:n.icons})}catch(r){return console.warn("Error populating app metadata",r),t||n}}function yh(){return yf.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function oy(){if(Ii()===kt.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:s,Version:n}=global.Platform;return[s,n].join("-")}const t=vf();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function ay(){var t;const e=Ii();return e===kt.browser?[e,((t=Us.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function bh(t,e,s){const n=oy(),r=ay();return[[t,e].join("-"),[ty,s].join("-"),n,r].join("/")}function cy({protocol:t,version:e,relayUrl:s,sdkVersion:n,auth:r,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),u=bh(t,e,n),d={auth:r,ua:u,projectId:i,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=ry(l[1]||"",d);return l[0]+"?"+h}function En(t,e){return t.filter(s=>e.includes(s)).length===t.length}function Za(t){return Object.fromEntries(t.entries())}function Qa(t){return new Map(Object.entries(t))}function gn(t=W.FIVE_MINUTES,e){const s=W.toMiliseconds(t||W.FIVE_MINUTES);let n,r,i,o;return{resolve:a=>{i&&n&&(clearTimeout(i),n(a),o=Promise.resolve(a))},reject:a=>{i&&r&&(clearTimeout(i),r(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);i=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),n=a,r=c})}}function ps(t,e,s){return new Promise(async(n,r)=>{const i=setTimeout(()=>r(new Error(s)),e);try{const o=await t;n(o)}catch(o){r(o)}clearTimeout(i)})}function vh(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function ly(t){return vh("topic",t)}function uy(t){return vh("id",t)}function Eh(t){const[e,s]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")n.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))n.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return n}function je(t,e){return W.fromMiliseconds(Date.now()+W.toMiliseconds(t))}function ds(t){return Date.now()>=W.toMiliseconds(t)}function Ne(t,e){return`${t}${e?`:${e}`:""}`}function ms(t=[],e=[]){return[...new Set([...t,...e])]}async function dy({id:t,topic:e,wcDeepLink:s}){var n;try{if(!s)return;const r=typeof s=="string"?JSON.parse(s):s,i=r?.href;if(typeof i!="string")return;const o=hy(i,t,e),a=Ii();if(a===kt.browser){if(!((n=Us.getDocument())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}py(o)}else a===kt.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(r){console.error(r)}}function hy(t,e,s){const n=`requestId=${e}&sessionTopic=${s}`;t.endsWith("/")&&(t=t.slice(0,-1));let r=`${t}`;if(t.startsWith("https://t.me")){const i=t.includes("?")?"&startapp=":"?startapp=";r=`${r}${i}${wy(n,!0)}`}else r=`${r}/wc?${n}`;return r}function py(t){let e="_self";my()?e="_top":(gy()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function fy(t,e){let s="";try{if(gr()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(n){console.error(n)}return s}function Hl(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),n=s.indexOf(e);return s[n+2]}function Vl(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Fc(){return typeof process<"u"&&Kw.IS_VITEST==="true"}function gy(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function my(){try{return window.self!==window.top}catch{return!1}}function wy(t,e=!1){const s=Buffer.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function Ch(t){return Buffer.from(t,"base64").toString("utf-8")}function yy(t){return new Promise(e=>setTimeout(e,t))}let by=class{constructor({limit:e}){ql(this,"limit"),ql(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const s=this.set.values().next().value;s&&this.set.delete(s)}this.set.add(e)}}has(e){return this.set.has(e)}};const Wi=BigInt(2**32-1),Kl=BigInt(32);function Ih(t,e=!1){return e?{h:Number(t&Wi),l:Number(t>>Kl&Wi)}:{h:Number(t>>Kl&Wi)|0,l:Number(t&Wi)|0}}function Ah(t,e=!1){const s=t.length;let n=new Uint32Array(s),r=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=Ih(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const zl=(t,e,s)=>t>>>s,Gl=(t,e,s)=>t<<32-s|e>>>s,Ks=(t,e,s)=>t>>>s|e<<32-s,zs=(t,e,s)=>t<<32-s|e>>>s,Pr=(t,e,s)=>t<<64-s|e>>>s-32,Rr=(t,e,s)=>t>>>s-32|e<<64-s,vy=(t,e)=>e,Ey=(t,e)=>t,Cy=(t,e,s)=>t<<s|e>>>32-s,Iy=(t,e,s)=>e<<s|t>>>32-s,Ay=(t,e,s)=>e<<s-32|t>>>64-s,Ny=(t,e,s)=>t<<s-32|e>>>64-s;function Xt(t,e,s,n){const r=(e>>>0)+(n>>>0);return{h:t+s+(r/2**32|0)|0,l:r|0}}const qc=(t,e,s)=>(t>>>0)+(e>>>0)+(s>>>0),Wc=(t,e,s,n)=>e+s+n+(t/2**32|0)|0,_y=(t,e,s,n)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0),Sy=(t,e,s,n,r)=>e+s+n+r+(t/2**32|0)|0,Ty=(t,e,s,n,r)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0)+(r>>>0),Oy=(t,e,s,n,r,i)=>e+s+n+r+i+(t/2**32|0)|0,qn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Fo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ds(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ns(t,...e){if(!Fo(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function qo(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Ds(t.outputLen),Ds(t.blockLen)}function rn(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Hc(t,e){ns(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function pi(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ht(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function pa(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function is(t,e){return t<<32-e|t>>>e}const Nh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function _h(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Cs=Nh?t=>t:t=>_h(t);function ky(t){for(let e=0;e<t.length;e++)t[e]=_h(t[e]);return t}const Gs=Nh?t=>t:ky,Sh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Py=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function er(t){if(ns(t),Sh)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=Py[t[s]];return e}const vs={_0:48,_9:57,A:65,F:70,a:97,f:102};function Yl(t){if(t>=vs._0&&t<=vs._9)return t-vs._0;if(t>=vs.A&&t<=vs.F)return t-(vs.A-10);if(t>=vs.a&&t<=vs.f)return t-(vs.a-10)}function Ao(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Sh)return Uint8Array.fromHex(t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(s);for(let r=0,i=0;r<s;r++,i+=2){const o=Yl(t.charCodeAt(i)),a=Yl(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[r]=o*16+a}return n}function Th(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ss(t){return typeof t=="string"&&(t=Th(t)),ns(t),t}function Js(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];ns(r),e+=r.length}const s=new Uint8Array(e);for(let n=0,r=0;n<t.length;n++){const i=t[n];s.set(i,r),r+=i.length}return s}class Wo{}function Ai(t){const e=n=>t().update(ss(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function Ry(t){const e=(n,r)=>t(r).update(ss(n)).digest(),s=t({});return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}function Bn(t=32){if(qn&&typeof qn.getRandomValues=="function")return qn.getRandomValues(new Uint8Array(t));if(qn&&typeof qn.randomBytes=="function")return Uint8Array.from(qn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const xy=BigInt(0),Er=BigInt(1),$y=BigInt(2),Uy=BigInt(7),Dy=BigInt(256),Ly=BigInt(113),Oh=[],kh=[],Ph=[];for(let t=0,e=Er,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],Oh.push(2*(5*n+s)),kh.push((t+1)*(t+2)/2%64);let r=xy;for(let i=0;i<7;i++)e=(e<<Er^(e>>Uy)*Ly)%Dy,e&$y&&(r^=Er<<(Er<<BigInt(i))-Er);Ph.push(r)}const Rh=Ah(Ph,!0),My=Rh[0],By=Rh[1],Jl=(t,e,s)=>s>32?Ay(t,e,s):Cy(t,e,s),Xl=(t,e,s)=>s>32?Ny(t,e,s):Iy(t,e,s);function jy(t,e=24){const s=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],d=Jl(l,u,1)^s[a],h=Xl(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=d,t[o+p+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=kh[o],c=Jl(r,i,a),l=Xl(r,i,a),u=Oh[o];r=t[u],i=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=My[n],t[1]^=By[n]}Ht(s)}let Fy=class xh extends Wo{constructor(e,s,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=s,this.outputLen=n,this.enableXOF=r,this.rounds=i,Ds(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=pi(this.state)}clone(){return this._cloneInto()}keccak(){Gs(this.state32),jy(this.state32,this.rounds),Gs(this.state32),this.posOut=0,this.pos=0}update(e){rn(this),e=ss(e),ns(e);const{blockLen:s,state:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);for(let a=0;a<o;a++)n[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:n,blockLen:r}=this;e[n]^=s,(s&128)!==0&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){rn(this,!1),ns(e),this.finish();const s=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(s.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ds(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Hc(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ht(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new xh(s,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}};const qy=(t,e,s)=>Ai(()=>new Fy(e,t,s)),Wy=qy(1,136,256/8);function Hy(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i),c=n?4:0,l=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+l,a,n)}function Vy(t,e,s){return t&e^~t&s}function Ky(t,e,s){return t&e^t&s^e&s}let $h=class extends Wo{constructor(e,s,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=s,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=pa(this.buffer)}update(e){rn(this),e=ss(e),ns(e);const{view:s,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(r-this.pos,i-o);if(a===r){const c=pa(e);for(;r<=i-o;o+=r)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===r&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){rn(this),Hc(e,this),this.finished=!0;const{buffer:s,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,Ht(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let d=o;d<r;d++)s[d]=0;Hy(n,r-8,BigInt(this.length*8),i),this.process(n,0);const a=pa(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)a.setUint32(4*d,u[d],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=r,e.pos=a,r%s&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const js=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),st=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),nt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),zy=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Fs=new Uint32Array(64);class Gy extends $h{constructor(e=32){super(64,e,8,!1),this.A=js[0]|0,this.B=js[1]|0,this.C=js[2]|0,this.D=js[3]|0,this.E=js[4]|0,this.F=js[5]|0,this.G=js[6]|0,this.H=js[7]|0}get(){const{A:e,B:s,C:n,D:r,E:i,F:o,G:a,H:c}=this;return[e,s,n,r,i,o,a,c]}set(e,s,n,r,i,o,a,c){this.A=e|0,this.B=s|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let d=0;d<16;d++,s+=4)Fs[d]=e.getUint32(s,!1);for(let d=16;d<64;d++){const h=Fs[d-15],p=Fs[d-2],f=is(h,7)^is(h,18)^h>>>3,g=is(p,17)^is(p,19)^p>>>10;Fs[d]=g+Fs[d-7]+f+Fs[d-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){const h=is(a,6)^is(a,11)^is(a,25),p=u+h+Vy(a,c,l)+zy[d]+Fs[d]|0,f=(is(n,2)^is(n,13)^is(n,22))+Ky(n,r,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=r,r=n,n=p+f|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,r,i,o,a,c,l,u)}roundClean(){Ht(Fs)}destroy(){this.set(0,0,0,0,0,0,0,0),Ht(this.buffer)}}const Uh=Ah(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Yy=Uh[0],Jy=Uh[1],qs=new Uint32Array(80),Ws=new Uint32Array(80);let Vc=class extends $h{constructor(e=64){super(128,e,16,!1),this.Ah=nt[0]|0,this.Al=nt[1]|0,this.Bh=nt[2]|0,this.Bl=nt[3]|0,this.Ch=nt[4]|0,this.Cl=nt[5]|0,this.Dh=nt[6]|0,this.Dl=nt[7]|0,this.Eh=nt[8]|0,this.El=nt[9]|0,this.Fh=nt[10]|0,this.Fl=nt[11]|0,this.Gh=nt[12]|0,this.Gl=nt[13]|0,this.Hh=nt[14]|0,this.Hl=nt[15]|0}get(){const{Ah:e,Al:s,Bh:n,Bl:r,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:h,Gh:p,Gl:f,Hh:g,Hl:w}=this;return[e,s,n,r,i,o,a,c,l,u,d,h,p,f,g,w]}set(e,s,n,r,i,o,a,c,l,u,d,h,p,f,g,w){this.Ah=e|0,this.Al=s|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=h|0,this.Gh=p|0,this.Gl=f|0,this.Hh=g|0,this.Hl=w|0}process(e,s){for(let _=0;_<16;_++,s+=4)qs[_]=e.getUint32(s),Ws[_]=e.getUint32(s+=4);for(let _=16;_<80;_++){const L=qs[_-15]|0,B=Ws[_-15]|0,j=Ks(L,B,1)^Ks(L,B,8)^zl(L,B,7),K=zs(L,B,1)^zs(L,B,8)^Gl(L,B,7),Y=qs[_-2]|0,k=Ws[_-2]|0,te=Ks(Y,k,19)^Pr(Y,k,61)^zl(Y,k,6),ne=zs(Y,k,19)^Rr(Y,k,61)^Gl(Y,k,6),P=_y(K,ne,Ws[_-7],Ws[_-16]),I=Sy(P,j,te,qs[_-7],qs[_-16]);qs[_]=I|0,Ws[_]=P|0}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:h,Fh:p,Fl:f,Gh:g,Gl:w,Hh:C,Hl:v}=this;for(let _=0;_<80;_++){const L=Ks(d,h,14)^Ks(d,h,18)^Pr(d,h,41),B=zs(d,h,14)^zs(d,h,18)^Rr(d,h,41),j=d&p^~d&g,K=h&f^~h&w,Y=Ty(v,B,K,Jy[_],Ws[_]),k=Oy(Y,C,L,j,Yy[_],qs[_]),te=Y|0,ne=Ks(n,r,28)^Pr(n,r,34)^Pr(n,r,39),P=zs(n,r,28)^Rr(n,r,34)^Rr(n,r,39),I=n&i^n&a^i&a,A=r&o^r&c^o&c;C=g|0,v=w|0,g=p|0,w=f|0,p=d|0,f=h|0,{h:d,l:h}=Xt(l|0,u|0,k|0,te|0),l=a|0,u=c|0,a=i|0,c=o|0,i=n|0,o=r|0;const y=qc(te,P,A);n=Wc(y,k,ne,I),r=y|0}({h:n,l:r}=Xt(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:o}=Xt(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Xt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Xt(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:h}=Xt(this.Eh|0,this.El|0,d|0,h|0),{h:p,l:f}=Xt(this.Fh|0,this.Fl|0,p|0,f|0),{h:g,l:w}=Xt(this.Gh|0,this.Gl|0,g|0,w|0),{h:C,l:v}=Xt(this.Hh|0,this.Hl|0,C|0,v|0),this.set(n,r,i,o,a,c,l,u,d,h,p,f,g,w,C,v)}roundClean(){Ht(qs,Ws)}destroy(){Ht(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class Xy extends Vc{constructor(){super(48),this.Ah=st[0]|0,this.Al=st[1]|0,this.Bh=st[2]|0,this.Bl=st[3]|0,this.Ch=st[4]|0,this.Cl=st[5]|0,this.Dh=st[6]|0,this.Dl=st[7]|0,this.Eh=st[8]|0,this.El=st[9]|0,this.Fh=st[10]|0,this.Fl=st[11]|0,this.Gh=st[12]|0,this.Gl=st[13]|0,this.Hh=st[14]|0,this.Hl=st[15]|0}}const rt=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Zy extends Vc{constructor(){super(32),this.Ah=rt[0]|0,this.Al=rt[1]|0,this.Bh=rt[2]|0,this.Bl=rt[3]|0,this.Ch=rt[4]|0,this.Cl=rt[5]|0,this.Dh=rt[6]|0,this.Dl=rt[7]|0,this.Eh=rt[8]|0,this.El=rt[9]|0,this.Fh=rt[10]|0,this.Fl=rt[11]|0,this.Gh=rt[12]|0,this.Gl=rt[13]|0,this.Hh=rt[14]|0,this.Hl=rt[15]|0}}const Ho=Ai(()=>new Gy),Qy=Ai(()=>new Vc),eb=Ai(()=>new Xy),tb=Ai(()=>new Zy),sb=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),We=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),z=new Uint32Array(32);function Hs(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=z[2*t],l=z[2*t+1],u=z[2*e],d=z[2*e+1],h=z[2*s],p=z[2*s+1],f=z[2*n],g=z[2*n+1],w=qc(c,u,o);l=Wc(w,l,d,a),c=w|0,{Dh:g,Dl:f}={Dh:g^l,Dl:f^c},{Dh:g,Dl:f}={Dh:vy(g,f),Dl:Ey(g)},{h:p,l:h}=Xt(p,h,g,f),{Bh:d,Bl:u}={Bh:d^p,Bl:u^h},{Bh:d,Bl:u}={Bh:Ks(d,u,24),Bl:zs(d,u,24)},z[2*t]=c,z[2*t+1]=l,z[2*e]=u,z[2*e+1]=d,z[2*s]=h,z[2*s+1]=p,z[2*n]=f,z[2*n+1]=g}function Vs(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=z[2*t],l=z[2*t+1],u=z[2*e],d=z[2*e+1],h=z[2*s],p=z[2*s+1],f=z[2*n],g=z[2*n+1],w=qc(c,u,o);l=Wc(w,l,d,a),c=w|0,{Dh:g,Dl:f}={Dh:g^l,Dl:f^c},{Dh:g,Dl:f}={Dh:Ks(g,f,16),Dl:zs(g,f,16)},{h:p,l:h}=Xt(p,h,g,f),{Bh:d,Bl:u}={Bh:d^p,Bl:u^h},{Bh:d,Bl:u}={Bh:Pr(d,u,63),Bl:Rr(d,u,63)},z[2*t]=c,z[2*t+1]=l,z[2*e]=u,z[2*e+1]=d,z[2*s]=h,z[2*s+1]=p,z[2*n]=f,z[2*n+1]=g}function nb(t,e={},s,n,r){if(Ds(s),t<0||t>s)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.length>s))throw new Error("key length must be undefined or 1.."+s);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==r)throw new Error("personalization must be undefined or "+r)}class rb extends Wo{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Ds(e),Ds(s),this.blockLen=e,this.outputLen=s,this.buffer=new Uint8Array(e),this.buffer32=pi(this.buffer)}update(e){rn(this),e=ss(e),ns(e);const{blockLen:s,buffer:n,buffer32:r}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===s&&(Gs(r),this.compress(r,0,!1),Gs(r),this.pos=0);const l=Math.min(s-this.pos,i-c),u=o+c;if(l===s&&!(u%4)&&c+l<i){const d=new Uint32Array(a,u,Math.floor((i-c)/4));Gs(d);for(let h=0;c+s<i;h+=r.length,c+=s)this.length+=s,this.compress(d,h,!1);Gs(d);continue}n.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){rn(this),Hc(e,this);const{pos:s,buffer32:n}=this;this.finished=!0,Ht(this.buffer.subarray(s)),Gs(n),this.compress(n,0,!0),Gs(n);const r=pi(e);this.get().forEach((i,o)=>r[o]=Cs(i))}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}_cloneInto(e){const{buffer:s,length:n,finished:r,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(s),e.destroyed=i,e.finished=r,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class ib extends rb{constructor(e={}){const s=e.dkLen===void 0?64:e.dkLen;super(128,s),this.v0l=We[0]|0,this.v0h=We[1]|0,this.v1l=We[2]|0,this.v1h=We[3]|0,this.v2l=We[4]|0,this.v2h=We[5]|0,this.v3l=We[6]|0,this.v3h=We[7]|0,this.v4l=We[8]|0,this.v4h=We[9]|0,this.v5l=We[10]|0,this.v5h=We[11]|0,this.v6l=We[12]|0,this.v6h=We[13]|0,this.v7l=We[14]|0,this.v7h=We[15]|0,nb(s,e,64,16,16);let{key:n,personalization:r,salt:i}=e,o=0;if(n!==void 0&&(n=ss(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=ss(i);const a=pi(i);this.v4l^=Cs(a[0]),this.v4h^=Cs(a[1]),this.v5l^=Cs(a[2]),this.v5h^=Cs(a[3])}if(r!==void 0){r=ss(r);const a=pi(r);this.v6l^=Cs(a[0]),this.v6h^=Cs(a[1]),this.v7l^=Cs(a[2]),this.v7h^=Cs(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:s,v1l:n,v1h:r,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:d,v5h:h,v6l:p,v6h:f,v7l:g,v7h:w}=this;return[e,s,n,r,i,o,a,c,l,u,d,h,p,f,g,w]}set(e,s,n,r,i,o,a,c,l,u,d,h,p,f,g,w){this.v0l=e|0,this.v0h=s|0,this.v1l=n|0,this.v1h=r|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=d|0,this.v5h=h|0,this.v6l=p|0,this.v6h=f|0,this.v7l=g|0,this.v7h=w|0}compress(e,s,n){this.get().forEach((c,l)=>z[l]=c),z.set(We,16);let{h:r,l:i}=Ih(BigInt(this.length));z[24]=We[8]^i,z[25]=We[9]^r,n&&(z[28]=~z[28],z[29]=~z[29]);let o=0;const a=sb;for(let c=0;c<12;c++)Hs(0,4,8,12,e,s+2*a[o++]),Vs(0,4,8,12,e,s+2*a[o++]),Hs(1,5,9,13,e,s+2*a[o++]),Vs(1,5,9,13,e,s+2*a[o++]),Hs(2,6,10,14,e,s+2*a[o++]),Vs(2,6,10,14,e,s+2*a[o++]),Hs(3,7,11,15,e,s+2*a[o++]),Vs(3,7,11,15,e,s+2*a[o++]),Hs(0,5,10,15,e,s+2*a[o++]),Vs(0,5,10,15,e,s+2*a[o++]),Hs(1,6,11,12,e,s+2*a[o++]),Vs(1,6,11,12,e,s+2*a[o++]),Hs(2,7,8,13,e,s+2*a[o++]),Vs(2,7,8,13,e,s+2*a[o++]),Hs(3,4,9,14,e,s+2*a[o++]),Vs(3,4,9,14,e,s+2*a[o++]);this.v0l^=z[0]^z[16],this.v0h^=z[1]^z[17],this.v1l^=z[2]^z[18],this.v1h^=z[3]^z[19],this.v2l^=z[4]^z[20],this.v2h^=z[5]^z[21],this.v3l^=z[6]^z[22],this.v3h^=z[7]^z[23],this.v4l^=z[8]^z[24],this.v4h^=z[9]^z[25],this.v5l^=z[10]^z[26],this.v5h^=z[11]^z[27],this.v6l^=z[12]^z[28],this.v6h^=z[13]^z[29],this.v7l^=z[14]^z[30],this.v7h^=z[15]^z[31],Ht(z)}destroy(){this.destroyed=!0,Ht(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const ob=Ry(t=>new ib(t)),ab="https://rpc.walletconnect.org/v1";function Dh(t){const e=`Ethereum Signed Message:
11
+ ${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Wy(s)).toString("hex")}async function cb(t,e,s,n,r,i){switch(s.t){case"eip191":return await lb(t,e,s.s);case"eip1271":return await ub(t,e,s.s,n,r,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}function lb(t,e,s){const n=Nf(s);return _f({payload:Dh(e),signature:n}).toLowerCase()===t.toLowerCase()}async function ub(t,e,s,n,r,i){const o=Rs(n);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l=s.substring(2),u=(l.length/2).toString(16).padStart(64,"0"),d=(e.startsWith("0x")?e:Dh(e)).substring(2),h=a+d+c+u+l,p=await fetch(`${i||ab}/?chainId=${n}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:db(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:f}=await p.json();return f?f.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function db(){return Date.now()+Math.floor(Math.random()*1e3)}function hb(t){const e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);const n=s[0];if(n===0)throw new Error("No signatures found");const r=1+n*64;if(s.length<r)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const i=Buffer.from(t,"base64").slice(1,65);return pr.encode(i)}function pb(t){const e=new Uint8Array(Buffer.from(t,"base64")),s=Array.from("TransactionData::").map(i=>i.charCodeAt(0)),n=new Uint8Array(s.length+e.length);n.set(s),n.set(e,s.length);const r=ob(n,{dkLen:32});return pr.encode(r)}function Zl(t){const e=new Uint8Array(Ho(fb(t)));return pr.encode(e)}function fb(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function Ql(t){const e=Buffer.from(t,"base64"),s=Ef(e).txn;if(!s)throw new Error("Invalid signed transaction: missing 'txn' field");const n=Cf(s),r=Buffer.from("TX"),i=Buffer.concat([r,Buffer.from(n)]),o=tb(i);return If.encode(o).replace(/=+$/,"")}function fa(t){const e=[];let s=BigInt(t);for(;s>=BigInt(128);)e.push(Number(s&BigInt(127)|BigInt(128))),s>>=BigInt(7);return e.push(Number(s)),Buffer.from(e)}function gb(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),s=Buffer.from(t.signed.authInfoBytes,"base64"),n=Buffer.from(t.signature.signature,"base64"),r=[];r.push(Buffer.from([10])),r.push(fa(e.length)),r.push(e),r.push(Buffer.from([18])),r.push(fa(s.length)),r.push(s),r.push(Buffer.from([26])),r.push(fa(n.length)),r.push(n);const i=Buffer.concat(r),o=Ho(i);return Buffer.from(o).toString("hex").toUpperCase()}function mb(t){var e,s;const n=[];try{if(typeof t=="string")return n.push(t),n;if(typeof t!="object")return n;t!=null&&t.id&&n.push(t.id);const r=(s=(e=t?.capabilities)==null?void 0:e.caip345)==null?void 0:s.transactionHashes;r&&n.push(...r)}catch(r){console.warn("getWalletSendCallsHashes failed: ",r)}return n}var wb=Object.defineProperty,yb=Object.defineProperties,bb=Object.getOwnPropertyDescriptors,eu=Object.getOwnPropertySymbols,vb=Object.prototype.hasOwnProperty,Eb=Object.prototype.propertyIsEnumerable,tu=(t,e,s)=>e in t?wb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Cb=(t,e)=>{for(var s in e||(e={}))vb.call(e,s)&&tu(t,s,e[s]);if(eu)for(var s of eu(e))Eb.call(e,s)&&tu(t,s,e[s]);return t},Ib=(t,e)=>yb(t,bb(e));const Ab="did:pkh:",Kc=t=>t?.split(":"),Nb=t=>{const e=t&&Kc(t);if(e)return t.includes(Ab)?e[3]:e[1]},ec=t=>{const e=t&&Kc(t);if(e)return e[2]+":"+e[3]},No=t=>{const e=t&&Kc(t);if(e)return e.pop()};async function su(t){const{cacao:e,projectId:s}=t,{s:n,p:r}=e,i=Lh(r,r.iss),o=No(r.iss);return await cb(o,i,n,ec(r.iss),s)}const Lh=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,n=No(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let r=t.statement||void 0;const i=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${Nb(e)}`,c=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,u=t.exp?`Expiration Time: ${t.exp}`:void 0,d=t.nbf?`Not Before: ${t.nbf}`:void 0,h=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(g=>`
12
+ - ${g}`).join("")}`:void 0,f=ao(t.resources);if(f){const g=fi(f);r=$b(r,g)}return[s,n,"",r,"",i,o,a,c,l,u,d,h,p].filter(g=>g!=null).join(`
13
+ `)};function _b(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function Sb(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function Rn(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(s=>{const n=t.att[s];if(Array.isArray(n))throw new Error(`Resource must be an object: ${s}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${s}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${s}`);Object.keys(n).forEach(r=>{const i=n[r];if(!Array.isArray(i))throw new Error(`Ability limits ${r} must be an array of objects, found: ${i}`);if(!i.length)throw new Error(`Value of ${r} is empty array, must be an array with objects`);i.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${r}) must be an array of objects, found: ${o}`)})})})}function Tb(t,e,s,n={}){return s?.sort((r,i)=>r.localeCompare(i)),{att:{[t]:Ob(e,s,n)}}}function Ob(t,e,s={}){e=e?.sort((r,i)=>r.localeCompare(i));const n=e.map(r=>({[`${t}/${r}`]:[s]}));return Object.assign({},...n)}function Mh(t){return Rn(t),`urn:recap:${_b(t).replace(/=/g,"")}`}function fi(t){const e=Sb(t.replace("urn:recap:",""));return Rn(e),e}function kb(t,e,s){const n=Tb(t,e,s);return Mh(n)}function Pb(t){return t&&t.includes("urn:recap:")}function Rb(t,e){const s=fi(t),n=fi(e),r=xb(s,n);return Mh(r)}function xb(t,e){Rn(t),Rn(e);const s=Object.keys(t.att).concat(Object.keys(e.att)).sort((r,i)=>r.localeCompare(i)),n={att:{}};return s.forEach(r=>{var i,o;Object.keys(((i=t.att)==null?void 0:i[r])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[r])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;n.att[r]=Ib(Cb({},n.att[r]),{[a]:((c=t.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),n}function $b(t="",e){Rn(e);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(s))return t;const n=[];let r=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(d=>({ability:d.split("/")[0],action:d.split("/")[1]}));c.sort((d,h)=>d.action.localeCompare(h.action));const l={};c.forEach(d=>{l[d.ability]||(l[d.ability]=[]),l[d.ability].push(d.action)});const u=Object.keys(l).map(d=>(r++,`(${r}) '${d}': '${l[d].join("', '")}' for '${a}'.`));n.push(u.join(", ").replace(".,","."))});const i=n.join(" "),o=`${s}${i}`;return`${t?t+" ":""}${o}`}function nu(t){var e;const s=fi(t);Rn(s);const n=(e=s.att)==null?void 0:e.eip155;return n?Object.keys(n).map(r=>r.split("/")[1]):[]}function ru(t){const e=fi(t);Rn(e);const s=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(r=>{var i;(i=r?.[0])!=null&&i.chains&&s.push(r[0].chains)})}),[...new Set(s.flat())]}function ao(t){if(!t)return;const e=t?.[t.length-1];return Pb(e)?e:void 0}function Bh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function tc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function ga(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function yt(t,...e){if(!Bh(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function iu(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ub(t,e){yt(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function sn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function cr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Db(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Lb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Mb(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function sc(t){if(typeof t=="string")t=Mb(t);else if(Bh(t))t=nc(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Bb(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function jb(t,e){if(t.length!==e.length)return!1;let s=0;for(let n=0;n<t.length;n++)s|=t[n]^e[n];return s===0}const Fb=(t,e)=>{function s(n,...r){if(yt(n),!Lb)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const l=r[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?yt(l):yt(l,t.nonceLength)}const i=t.tagLength;i&&r[1]!==void 0&&yt(r[1]);const o=e(n,...r),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");yt(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,yt(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(yt(l),i&&l.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(s,t),s};function ou(t,e,s=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(s&&!Wb(e))throw new Error("invalid output, must be aligned");return e}function au(t,e,s,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,n);const r=BigInt(32),i=BigInt(4294967295),o=Number(s>>r&i),a=Number(s&i);t.setUint32(e+4,o,n),t.setUint32(e+0,a,n)}function qb(t,e,s){tc(s);const n=new Uint8Array(16),r=Db(n);return au(r,0,BigInt(e),s),au(r,8,BigInt(t),s),n}function Wb(t){return t.byteOffset%4===0}function nc(t){return Uint8Array.from(t)}const jh=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),Hb=jh("expand 16-byte k"),Vb=jh("expand 32-byte k"),Kb=sn(Hb),zb=sn(Vb);function Ee(t,e){return t<<e|t>>>32-e}function rc(t){return t.byteOffset%4===0}const Hi=64,Gb=16,Fh=2**32-1,cu=new Uint32Array;function Yb(t,e,s,n,r,i,o,a){const c=r.length,l=new Uint8Array(Hi),u=sn(l),d=rc(r)&&rc(i),h=d?sn(r):cu,p=d?sn(i):cu;for(let f=0;f<c;o++){if(t(e,s,n,u,o,a),o>=Fh)throw new Error("arx: counter overflow");const g=Math.min(Hi,c-f);if(d&&g===Hi){const w=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let C=0,v;C<Gb;C++)v=w+C,p[v]=h[v]^u[C];f+=Hi;continue}for(let w=0,C;w<g;w++)C=f+w,i[C]=r[C]^l[w];f+=g}}function Jb(t,e){const{allowShortKeys:s,extendNonceFn:n,counterLength:r,counterRight:i,rounds:o}=Bb({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return ga(r),ga(o),tc(i),tc(s),(a,c,l,u,d=0)=>{yt(a),yt(c),yt(l);const h=l.length;if(u===void 0&&(u=new Uint8Array(h)),yt(u),ga(d),d<0||d>=Fh)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);const p=[];let f=a.length,g,w;if(f===32)p.push(g=nc(a)),w=zb;else if(f===16&&s)g=new Uint8Array(32),g.set(a),g.set(a,16),w=Kb,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${f}`);rc(c)||p.push(c=nc(c));const C=sn(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(w,C,sn(c.subarray(0,16)),C),c=c.subarray(16)}const v=16-r;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){const L=new Uint8Array(12);L.set(c,i?0:12-c.length),c=L,p.push(c)}const _=sn(c);return Yb(t,w,C,_,l,u,d,o),cr(...p),u}}const Ye=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class Xb{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=sc(e),yt(e,32);const s=Ye(e,0),n=Ye(e,2),r=Ye(e,4),i=Ye(e,6),o=Ye(e,8),a=Ye(e,10),c=Ye(e,12),l=Ye(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ye(e,16+2*u)}process(e,s,n=!1){const r=n?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],d=o[4],h=o[5],p=o[6],f=o[7],g=o[8],w=o[9],C=Ye(e,s+0),v=Ye(e,s+2),_=Ye(e,s+4),L=Ye(e,s+6),B=Ye(e,s+8),j=Ye(e,s+10),K=Ye(e,s+12),Y=Ye(e,s+14);let k=i[0]+(C&8191),te=i[1]+((C>>>13|v<<3)&8191),ne=i[2]+((v>>>10|_<<6)&8191),P=i[3]+((_>>>7|L<<9)&8191),I=i[4]+((L>>>4|B<<12)&8191),A=i[5]+(B>>>1&8191),y=i[6]+((B>>>14|j<<2)&8191),b=i[7]+((j>>>11|K<<5)&8191),N=i[8]+((K>>>8|Y<<8)&8191),T=i[9]+(Y>>>5|r),E=0,O=E+k*a+te*(5*w)+ne*(5*g)+P*(5*f)+I*(5*p);E=O>>>13,O&=8191,O+=A*(5*h)+y*(5*d)+b*(5*u)+N*(5*l)+T*(5*c),E+=O>>>13,O&=8191;let F=E+k*c+te*a+ne*(5*w)+P*(5*g)+I*(5*f);E=F>>>13,F&=8191,F+=A*(5*p)+y*(5*h)+b*(5*d)+N*(5*u)+T*(5*l),E+=F>>>13,F&=8191;let $=E+k*l+te*c+ne*a+P*(5*w)+I*(5*g);E=$>>>13,$&=8191,$+=A*(5*f)+y*(5*p)+b*(5*h)+N*(5*d)+T*(5*u),E+=$>>>13,$&=8191;let re=E+k*u+te*l+ne*c+P*a+I*(5*w);E=re>>>13,re&=8191,re+=A*(5*g)+y*(5*f)+b*(5*p)+N*(5*h)+T*(5*d),E+=re>>>13,re&=8191;let U=E+k*d+te*u+ne*l+P*c+I*a;E=U>>>13,U&=8191,U+=A*(5*w)+y*(5*g)+b*(5*f)+N*(5*p)+T*(5*h),E+=U>>>13,U&=8191;let J=E+k*h+te*d+ne*u+P*l+I*c;E=J>>>13,J&=8191,J+=A*a+y*(5*w)+b*(5*g)+N*(5*f)+T*(5*p),E+=J>>>13,J&=8191;let oe=E+k*p+te*h+ne*d+P*u+I*l;E=oe>>>13,oe&=8191,oe+=A*c+y*a+b*(5*w)+N*(5*g)+T*(5*f),E+=oe>>>13,oe&=8191;let ce=E+k*f+te*p+ne*h+P*d+I*u;E=ce>>>13,ce&=8191,ce+=A*l+y*c+b*a+N*(5*w)+T*(5*g),E+=ce>>>13,ce&=8191;let Ie=E+k*g+te*f+ne*p+P*h+I*d;E=Ie>>>13,Ie&=8191,Ie+=A*u+y*l+b*c+N*a+T*(5*w),E+=Ie>>>13,Ie&=8191;let le=E+k*w+te*g+ne*f+P*p+I*h;E=le>>>13,le&=8191,le+=A*d+y*u+b*l+N*c+T*a,E+=le>>>13,le&=8191,E=(E<<2)+E|0,E=E+O|0,O=E&8191,E=E>>>13,F+=E,i[0]=O,i[1]=F,i[2]=$,i[3]=re,i[4]=U,i[5]=J,i[6]=oe,i[7]=ce,i[8]=Ie,i[9]=le}finalize(){const{h:e,pad:s}=this,n=new Uint16Array(10);let r=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=r,r=e[a]>>>13,e[a]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+r,r=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(r^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+s[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+s[a]|0)+(o>>>16)|0,e[a]=o&65535;cr(n)}update(e){iu(this),e=sc(e),yt(e);const{buffer:s,blockLen:n}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(n-this.pos,r-i);if(o===n){for(;n<=r-i;i+=n)this.process(e,i);continue}s.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===n&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){cr(this.h,this.r,this.buffer,this.pad)}digestInto(e){iu(this),Ub(e,this),this.finished=!0;const{buffer:s,h:n}=this;let{pos:r}=this;if(r){for(s[r++]=1;r<16;r++)s[r]=0;this.process(s,0,!0)}this.finalize();let i=0;for(let o=0;o<8;o++)e[i++]=n[o]>>>0,e[i++]=n[o]>>>8;return e}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const n=e.slice(0,s);return this.destroy(),n}}function Zb(t){const e=(n,r)=>t(r).update(sc(n)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}const Qb=Zb(t=>new Xb(t));function ev(t,e,s,n,r,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],d=e[1],h=e[2],p=e[3],f=e[4],g=e[5],w=e[6],C=e[7],v=r,_=s[0],L=s[1],B=s[2],j=o,K=a,Y=c,k=l,te=u,ne=d,P=h,I=p,A=f,y=g,b=w,N=C,T=v,E=_,O=L,F=B;for(let re=0;re<i;re+=2)j=j+te|0,T=Ee(T^j,16),A=A+T|0,te=Ee(te^A,12),j=j+te|0,T=Ee(T^j,8),A=A+T|0,te=Ee(te^A,7),K=K+ne|0,E=Ee(E^K,16),y=y+E|0,ne=Ee(ne^y,12),K=K+ne|0,E=Ee(E^K,8),y=y+E|0,ne=Ee(ne^y,7),Y=Y+P|0,O=Ee(O^Y,16),b=b+O|0,P=Ee(P^b,12),Y=Y+P|0,O=Ee(O^Y,8),b=b+O|0,P=Ee(P^b,7),k=k+I|0,F=Ee(F^k,16),N=N+F|0,I=Ee(I^N,12),k=k+I|0,F=Ee(F^k,8),N=N+F|0,I=Ee(I^N,7),j=j+ne|0,F=Ee(F^j,16),b=b+F|0,ne=Ee(ne^b,12),j=j+ne|0,F=Ee(F^j,8),b=b+F|0,ne=Ee(ne^b,7),K=K+P|0,T=Ee(T^K,16),N=N+T|0,P=Ee(P^N,12),K=K+P|0,T=Ee(T^K,8),N=N+T|0,P=Ee(P^N,7),Y=Y+I|0,E=Ee(E^Y,16),A=A+E|0,I=Ee(I^A,12),Y=Y+I|0,E=Ee(E^Y,8),A=A+E|0,I=Ee(I^A,7),k=k+te|0,O=Ee(O^k,16),y=y+O|0,te=Ee(te^y,12),k=k+te|0,O=Ee(O^k,8),y=y+O|0,te=Ee(te^y,7);let $=0;n[$++]=o+j|0,n[$++]=a+K|0,n[$++]=c+Y|0,n[$++]=l+k|0,n[$++]=u+te|0,n[$++]=d+ne|0,n[$++]=h+P|0,n[$++]=p+I|0,n[$++]=f+A|0,n[$++]=g+y|0,n[$++]=w+b|0,n[$++]=C+N|0,n[$++]=v+T|0,n[$++]=_+E|0,n[$++]=L+O|0,n[$++]=B+F|0}const tv=Jb(ev,{counterRight:!1,counterLength:4,allowShortKeys:!1}),sv=new Uint8Array(16),lu=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(sv.subarray(s))},nv=new Uint8Array(32);function uu(t,e,s,n,r){const i=t(e,s,nv),o=Qb.create(i);r&&lu(o,r),lu(o,n);const a=qb(n.length,r?r.length:0,!0);o.update(a);const c=o.digest();return cr(i,a),c}const rv=t=>(e,s,n)=>({encrypt(r,i){const o=r.length;i=ou(o+16,i,!1),i.set(r);const a=i.subarray(0,-16);t(e,s,a,a,1);const c=uu(t,e,s,a,n);return i.set(c,o),cr(c),i},decrypt(r,i){i=ou(r.length-16,i,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=uu(t,e,s,o,n);if(!jb(a,c))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),t(e,s,i,i,1),cr(c),i}}),qh=Fb({blockSize:64,nonceLength:12,tagLength:16},rv(tv));let Wh=class extends Wo{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,qo(e);const n=ss(s);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Ht(i)}update(e){return rn(this),this.iHash.update(e),this}digestInto(e){rn(this),ns(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Vo=(t,e,s)=>new Wh(t,e).update(s).digest();Vo.create=(t,e)=>new Wh(t,e);function iv(t,e,s){return qo(t),s===void 0&&(s=new Uint8Array(t.outputLen)),Vo(t,ss(s),ss(e))}const ma=Uint8Array.from([0]),du=Uint8Array.of();function ov(t,e,s,n=32){qo(t),Ds(n);const r=t.outputLen;if(n>255*r)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/r);s===void 0&&(s=du);const o=new Uint8Array(i*r),a=Vo.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<i;u++)ma[0]=u+1,c.update(u===0?du:l).update(s).update(ma).digestInto(l),o.set(l,r*u),a._cloneInto(c);return a.destroy(),c.destroy(),Ht(l,ma),o.slice(0,n)}const av=(t,e,s,n,r)=>ov(t,iv(t,e,s),n,r),Ko=Ho,zc=BigInt(0),ic=BigInt(1);function _o(t,e=""){if(typeof t!="boolean"){const s=e&&`"${e}"`;throw new Error(s+"expected boolean, got type="+typeof t)}return t}function Cn(t,e,s=""){const n=Fo(t),r=t?.length,i=e!==void 0;if(!n||i&&r!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=n?`length=${r}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Vi(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Hh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?zc:BigInt("0x"+t)}function zo(t){return Hh(er(t))}function So(t){return ns(t),Hh(er(Uint8Array.from(t).reverse()))}function Gc(t,e){return Ao(t.toString(16).padStart(e*2,"0"))}function Yc(t,e){return Gc(t,e).reverse()}function at(t,e,s){let n;if(typeof e=="string")try{n=Ao(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(Fo(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const r=n.length;if(typeof s=="number"&&r!==s)throw new Error(t+" of length "+s+" expected, got "+r);return n}const wa=t=>typeof t=="bigint"&&zc<=t;function cv(t,e,s){return wa(t)&&wa(e)&&wa(s)&&e<=t&&t<s}function oc(t,e,s,n){if(!cv(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function Vh(t){let e;for(e=0;t>zc;t>>=ic,e+=1);return e}const Ni=t=>(ic<<BigInt(t))-ic;function lv(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),r=h=>Uint8Array.of(h);let i=n(t),o=n(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...h)=>s(o,i,...h),u=(h=n(0))=>{o=l(r(0),h),i=l(),h.length!==0&&(o=l(r(1),h),i=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const p=[];for(;h<e;){i=l();const f=i.slice();p.push(f),h+=i.length}return Js(...p)};return(h,p)=>{c(),u(h);let f;for(;!(f=p(d()));)u();return c(),f}}function Go(t,e,s={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(r,i,o){const a=t[r];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${r}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([r,i])=>n(r,i,!1)),Object.entries(s).forEach(([r,i])=>n(r,i,!0))}function hu(t){const e=new WeakMap;return(s,...n)=>{const r=e.get(s);if(r!==void 0)return r;const i=t(s,...n);return e.set(s,i),i}}const vt=BigInt(0),lt=BigInt(1),In=BigInt(2),Kh=BigInt(3),zh=BigInt(4),Gh=BigInt(5),uv=BigInt(7),Yh=BigInt(8),dv=BigInt(9),Jh=BigInt(16);function Ot(t,e){const s=t%e;return s>=vt?s:e+s}function Jt(t,e,s){let n=t;for(;e-- >vt;)n*=n,n%=s;return n}function pu(t,e){if(t===vt)throw new Error("invert: expected non-zero number");if(e<=vt)throw new Error("invert: expected positive modulus, got "+e);let s=Ot(t,e),n=e,r=vt,i=lt;for(;s!==vt;){const o=n/s,a=n%s,c=r-i*o;n=s,s=a,r=i,i=c}if(n!==lt)throw new Error("invert: does not exist");return Ot(r,e)}function Jc(t,e,s){if(!t.eql(t.sqr(e),s))throw new Error("Cannot find square root")}function Xh(t,e){const s=(t.ORDER+lt)/zh,n=t.pow(e,s);return Jc(t,n,e),n}function hv(t,e){const s=(t.ORDER-Gh)/Yh,n=t.mul(e,In),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,In),r),a=t.mul(i,t.sub(o,t.ONE));return Jc(t,a,e),a}function pv(t){const e=an(t),s=Zh(t),n=s(e,e.neg(e.ONE)),r=s(e,n),i=s(e,e.neg(n)),o=(t+uv)/Jh;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,n);const d=a.mul(l,r),h=a.mul(l,i),p=a.eql(a.sqr(u),c),f=a.eql(a.sqr(d),c);l=a.cmov(l,u,p),u=a.cmov(h,d,f);const g=a.eql(a.sqr(u),c),w=a.cmov(l,u,g);return Jc(a,w,c),w}}function Zh(t){if(t<Kh)throw new Error("sqrt is not defined for small field");let e=t-lt,s=0;for(;e%In===vt;)e/=In,s++;let n=In;const r=an(t);for(;fu(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Xh;let i=r.pow(n,e);const o=(e+lt)/In;return function(a,c){if(a.is0(c))return c;if(fu(a,c)!==1)throw new Error("Cannot find square root");let l=s,u=a.mul(a.ONE,i),d=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(d,a.ONE);){if(a.is0(d))return a.ZERO;let p=1,f=a.sqr(d);for(;!a.eql(f,a.ONE);)if(p++,f=a.sqr(f),p===l)throw new Error("Cannot find square root");const g=lt<<BigInt(l-p-1),w=a.pow(u,g);l=p,u=a.sqr(w),d=a.mul(d,u),h=a.mul(h,w)}return h}}function fv(t){return t%zh===Kh?Xh:t%Yh===Gh?hv:t%Jh===dv?pv(t):Zh(t)}const gv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function mv(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},s=gv.reduce((n,r)=>(n[r]="function",n),e);return Go(t,s),t}function wv(t,e,s){if(s<vt)throw new Error("invalid exponent, negatives unsupported");if(s===vt)return t.ONE;if(s===lt)return e;let n=t.ONE,r=e;for(;s>vt;)s&lt&&(n=t.mul(n,r)),r=t.sqr(r),s>>=lt;return n}function Qh(t,e,s=!1){const n=new Array(e.length).fill(s?t.ZERO:void 0),r=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),i=t.inv(r);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),i),n}function fu(t,e){const s=(t.ORDER-lt)/In,n=t.pow(e,s),r=t.eql(n,t.ONE),i=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function ep(t,e){e!==void 0&&Ds(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function an(t,e,s=!1,n={}){if(t<=vt)throw new Error("invalid field: expected ORDER > 0, got "+t);let r,i,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||s)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(r=h.BITS),h.sqrt&&(i=h.sqrt),typeof h.isLE=="boolean"&&(s=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(r=e),n.sqrt&&(i=n.sqrt);const{nBitLength:c,nByteLength:l}=ep(t,r);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:t,isLE:s,BITS:c,BYTES:l,MASK:Ni(c),ZERO:vt,ONE:lt,allowedLengths:a,create:h=>Ot(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return vt<=h&&h<t},is0:h=>h===vt,isValidNot0:h=>!d.is0(h)&&d.isValid(h),isOdd:h=>(h&lt)===lt,neg:h=>Ot(-h,t),eql:(h,p)=>h===p,sqr:h=>Ot(h*h,t),add:(h,p)=>Ot(h+p,t),sub:(h,p)=>Ot(h-p,t),mul:(h,p)=>Ot(h*p,t),pow:(h,p)=>wv(d,h,p),div:(h,p)=>Ot(h*pu(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>pu(h,t),sqrt:i||(h=>(u||(u=fv(t)),u(d,h))),toBytes:h=>s?Yc(h,l):Gc(h,l),fromBytes:(h,p=!0)=>{if(a){if(!a.includes(h.length)||h.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(l);g.set(h,s?0:g.length-h.length),h=g}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let f=s?So(h):zo(h);if(o&&(f=Ot(f,t)),!p&&!d.isValid(f))throw new Error("invalid field element: outside of range 0..ORDER");return f},invertBatch:h=>Qh(d,h),cmov:(h,p,f)=>f?p:h});return Object.freeze(d)}function tp(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function sp(t){const e=tp(t);return e+Math.ceil(e/2)}function yv(t,e,s=!1){const n=t.length,r=tp(e),i=sp(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?So(t):zo(t),a=Ot(o,e-lt)+lt;return s?Yc(a,r):Gc(a,r)}const lr=BigInt(0),An=BigInt(1);function To(t,e){const s=e.negate();return t?s:e}function ya(t,e){const s=Qh(t.Fp,e.map(n=>n.Z));return e.map((n,r)=>t.fromAffine(n.toAffine(s[r])))}function np(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ba(t,e){np(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=Ni(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function gu(t,e,s){const{windowSize:n,mask:r,maxNumber:i,shiftBy:o}=s;let a=Number(t&r),c=t>>o;a>n&&(a-=i,c+=An);const l=e*n,u=l+Math.abs(a)-1,d=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:p,offsetF:l}}function bv(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,n)=>{if(!(s instanceof e))throw new Error("invalid point at index "+n)})}function vv(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,n)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+n)})}const va=new WeakMap,rp=new WeakMap;function Ea(t){return rp.get(t)||1}function mu(t){if(t!==lr)throw new Error("invalid wNAF")}class Ev{constructor(e,s){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,n=this.ZERO){let r=e;for(;s>lr;)s&An&&(n=n.add(r)),r=r.double(),s>>=An;return n}precomputeWindow(e,s){const{windows:n,windowSize:r}=ba(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<n;c++){a=o,i.push(a);for(let l=1;l<r;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=ba(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:h,offsetF:p}=gu(n,a,o);n=c,u?i=i.add(To(h,s[p])):r=r.add(To(d,s[l]))}return mu(n),{p:r,f:i}}wNAFUnsafe(e,s,n,r=this.ZERO){const i=ba(e,this.bits);for(let o=0;o<i.windows&&n!==lr;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=gu(n,o,i);if(n=a,!l){const d=s[c];r=r.add(u?d.negate():d)}}return mu(n),r}getPrecomputes(e,s,n){let r=va.get(s);return r||(r=this.precomputeWindow(s,e),e!==1&&(typeof n=="function"&&(r=n(r)),va.set(s,r))),r}cached(e,s,n){const r=Ea(e);return this.wNAF(r,this.getPrecomputes(r,e,n),s)}unsafe(e,s,n,r){const i=Ea(e);return i===1?this._unsafeLadder(e,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),s,r)}createCache(e,s){np(s,this.bits),rp.set(e,s),va.delete(e)}hasCache(e){return Ea(e)!==1}}function Cv(t,e,s,n){let r=e,i=t.ZERO,o=t.ZERO;for(;s>lr||n>lr;)s&An&&(i=i.add(r)),n&An&&(o=o.add(r)),r=r.double(),s>>=An,n>>=An;return{p1:i,p2:o}}function Iv(t,e,s,n){bv(s,t),vv(n,e);const r=s.length,i=n.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Vh(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Ni(c),u=new Array(Number(l)+1).fill(o),d=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=d;p>=0;p-=c){u.fill(o);for(let g=0;g<i;g++){const w=n[g],C=Number(w>>BigInt(p)&l);u[C]=u[C].add(s[g])}let f=o;for(let g=u.length-1,w=o;g>0;g--)w=w.add(u[g]),f=f.add(w);if(h=h.add(f),p!==0)for(let g=0;g<c;g++)h=h.double()}return h}function wu(t,e,s){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return mv(e),e}else return an(t,{isLE:s})}function Av(t,e,s={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>lr))throw new Error(`CURVE.${a} must be positive bigint`)}const r=wu(e.p,s.Fp,n),i=wu(e.n,s.Fn,n),o=["Gx","Gy","a","b"];for(const a of o)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:i}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Th("HashToScalar-");const Cr=BigInt(0),Wn=BigInt(1),Ki=BigInt(2);function Nv(t){return Go(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function _v(t){const e=Nv(t),{P:s,type:n,adjustScalarBytes:r,powPminus2:i,randomBytes:o}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");const c=o||Bn,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?Ki**BigInt(254):Ki**BigInt(447),f=a?BigInt(8)*Ki**BigInt(251)-Wn:BigInt(4)*Ki**BigInt(445)-Wn,g=p+f+Wn,w=P=>Ot(P,s),C=v(d);function v(P){return Yc(w(P),u)}function _(P){const I=at("u coordinate",P,u);return a&&(I[31]&=127),w(So(I))}function L(P){return So(r(at("scalar",P,u)))}function B(P,I){const A=Y(_(I),L(P));if(A===Cr)throw new Error("invalid private or public key received");return v(A)}function j(P){return B(P,C)}function K(P,I,A){const y=w(P*(I-A));return I=w(I-y),A=w(A+y),{x_2:I,x_3:A}}function Y(P,I){oc("u",P,Cr,s),oc("scalar",I,p,g);const A=I,y=P;let b=Wn,N=Cr,T=P,E=Wn,O=Cr;for(let $=BigInt(l-1);$>=Cr;$--){const re=A>>$&Wn;O^=re,{x_2:b,x_3:T}=K(O,b,T),{x_2:N,x_3:E}=K(O,N,E),O=re;const U=b+N,J=w(U*U),oe=b-N,ce=w(oe*oe),Ie=J-ce,le=T+E,he=T-E,Le=w(he*U),dt=w(le*oe),rs=Le+dt,Kt=Le-dt;T=w(rs*rs),E=w(y*w(Kt*Kt)),b=w(J*ce),N=w(Ie*(J+w(h*Ie)))}({x_2:b,x_3:T}=K(O,b,T)),{x_2:N,x_3:E}=K(O,N,E);const F=i(N);return w(b*F)}const k={secretKey:u,publicKey:u,seed:u},te=(P=c(u))=>(ns(P,k.seed),P);function ne(P){const I=te(P);return{secretKey:I,publicKey:j(I)}}return{keygen:ne,getSharedSecret:(P,I)=>B(P,I),getPublicKey:P=>j(P),scalarMult:B,scalarMultBase:j,utils:{randomSecretKey:te,randomPrivateKey:te},GuBytes:C.slice(),lengths:k}}const Sv=BigInt(1),yu=BigInt(2),Tv=BigInt(3),Ov=BigInt(5);BigInt(8);const ip=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),kv={p:ip,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Pv(t){const e=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=ip,o=t*t%i*t%i,a=Jt(o,yu,i)*o%i,c=Jt(a,Sv,i)*t%i,l=Jt(c,Ov,i)*c%i,u=Jt(l,e,i)*l%i,d=Jt(u,s,i)*u%i,h=Jt(d,n,i)*d%i,p=Jt(h,r,i)*h%i,f=Jt(p,r,i)*h%i,g=Jt(f,e,i)*l%i;return{pow_p_5_8:Jt(g,yu,i)*t%i,b2:o}}function Rv(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const xv=an(kv.p,{isLE:!0}),ac=(()=>{const t=xv.ORDER;return _v({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:s,b2:n}=Pv(e);return Ot(Jt(s,Tv,t)*n,t)},adjustScalarBytes:Rv})})(),bu=(t,e)=>(t+(t>=0?e:-e)/op)/e;function $v(t,e,s){const[[n,r],[i,o]]=e,a=bu(o*t,s),c=bu(-r*t,s);let l=t-a*n-c*i,u=-a*r-c*o;const d=l<Ps,h=u<Ps;d&&(l=-l),h&&(u=-u);const p=Ni(Math.ceil(Vh(s)/2))+tr;if(l<Ps||l>=p||u<Ps||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:d,k1:l,k2neg:h,k2:u}}function cc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ca(t,e){const s={};for(let n of Object.keys(e))s[n]=t[n]===void 0?e[n]:t[n];return _o(s.lowS,"lowS"),_o(s.prehash,"prehash"),s.format!==void 0&&cc(s.format),s}class Uv extends Error{constructor(e=""){super(e)}}const Ss={Err:Uv,_tlv:{encode:(t,e)=>{const{Err:s}=Ss;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const n=e.length/2,r=Vi(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?Vi(r.length/2|128):"";return Vi(t)+i+r+e},decode(t,e){const{Err:s}=Ss;let n=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new s("tlv.decode: wrong tlv");const r=e[n++],i=!!(r&128);let o=0;if(!i)o=r;else{const c=r&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(n,n+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(n+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=Ss;if(t<Ps)throw new e("integer: negative integers are not allowed");let s=Vi(t);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(t){const{Err:e}=Ss;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return zo(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=Ss,r=at("signature",t),{v:i,l:o}=n.decode(48,r);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,i),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=Ss,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}},Ps=BigInt(0),tr=BigInt(1),op=BigInt(2),zi=BigInt(3),Dv=BigInt(4);function Jn(t,e){const{BYTES:s}=t;let n;if(typeof e=="bigint")n=e;else{let r=at("private key",e);try{n=t.fromBytes(r)}catch{throw new Error(`invalid private key: expected ui8a of size ${s}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Lv(t,e={}){const s=Av("weierstrass",t,e),{Fp:n,Fn:r}=s;let i=s.CURVE;const{h:o,n:a}=i;Go(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=cp(n,r);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(P,I,A){const{x:y,y:b}=I.toAffine(),N=n.toBytes(y);if(_o(A,"isCompressed"),A){u();const T=!n.isOdd(b);return Js(ap(T),N)}else return Js(Uint8Array.of(4),N,n.toBytes(b))}function h(P){Cn(P,void 0,"Point");const{publicKey:I,publicKeyUncompressed:A}=l,y=P.length,b=P[0],N=P.subarray(1);if(y===I&&(b===2||b===3)){const T=n.fromBytes(N);if(!n.isValid(T))throw new Error("bad point: is not on curve, wrong x");const E=g(T);let O;try{O=n.sqrt(E)}catch($){const re=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+re)}u();const F=n.isOdd(O);return(b&1)===1!==F&&(O=n.neg(O)),{x:T,y:O}}else if(y===A&&b===4){const T=n.BYTES,E=n.fromBytes(N.subarray(0,T)),O=n.fromBytes(N.subarray(T,T*2));if(!w(E,O))throw new Error("bad point: is not on curve");return{x:E,y:O}}else throw new Error(`bad point: got length ${y}, expected compressed=${I} or uncompressed=${A}`)}const p=e.toBytes||d,f=e.fromBytes||h;function g(P){const I=n.sqr(P),A=n.mul(I,P);return n.add(n.add(A,n.mul(P,i.a)),i.b)}function w(P,I){const A=n.sqr(I),y=g(P);return n.eql(A,y)}if(!w(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const C=n.mul(n.pow(i.a,zi),Dv),v=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(C,v)))throw new Error("bad curve params: a or b");function _(P,I,A=!1){if(!n.isValid(I)||A&&n.is0(I))throw new Error(`bad point coordinate ${P}`);return I}function L(P){if(!(P instanceof k))throw new Error("ProjectivePoint expected")}function B(P){if(!c||!c.basises)throw new Error("no endo");return $v(P,c.basises,r.ORDER)}const j=hu((P,I)=>{const{X:A,Y:y,Z:b}=P;if(n.eql(b,n.ONE))return{x:A,y};const N=P.is0();I==null&&(I=N?n.ONE:n.inv(b));const T=n.mul(A,I),E=n.mul(y,I),O=n.mul(b,I);if(N)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:T,y:E}}),K=hu(P=>{if(P.is0()){if(e.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:I,y:A}=P.toAffine();if(!n.isValid(I)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!w(I,A))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Y(P,I,A,y,b){return A=new k(n.mul(A.X,P),A.Y,A.Z),I=To(y,I),A=To(b,A),I.add(A)}class k{constructor(I,A,y){this.X=_("x",I),this.Y=_("y",A,!0),this.Z=_("z",y),Object.freeze(this)}static CURVE(){return i}static fromAffine(I){const{x:A,y}=I||{};if(!I||!n.isValid(A)||!n.isValid(y))throw new Error("invalid affine point");if(I instanceof k)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(y)?k.ZERO:new k(A,y,n.ONE)}static fromBytes(I){const A=k.fromAffine(f(Cn(I,void 0,"point")));return A.assertValidity(),A}static fromHex(I){return k.fromBytes(at("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,A=!0){return ne.createCache(this,I),A||this.multiply(zi),this}assertValidity(){K(this)}hasEvenY(){const{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){L(I);const{X:A,Y:y,Z:b}=this,{X:N,Y:T,Z:E}=I,O=n.eql(n.mul(A,E),n.mul(N,b)),F=n.eql(n.mul(y,E),n.mul(T,b));return O&&F}negate(){return new k(this.X,n.neg(this.Y),this.Z)}double(){const{a:I,b:A}=i,y=n.mul(A,zi),{X:b,Y:N,Z:T}=this;let E=n.ZERO,O=n.ZERO,F=n.ZERO,$=n.mul(b,b),re=n.mul(N,N),U=n.mul(T,T),J=n.mul(b,N);return J=n.add(J,J),F=n.mul(b,T),F=n.add(F,F),E=n.mul(I,F),O=n.mul(y,U),O=n.add(E,O),E=n.sub(re,O),O=n.add(re,O),O=n.mul(E,O),E=n.mul(J,E),F=n.mul(y,F),U=n.mul(I,U),J=n.sub($,U),J=n.mul(I,J),J=n.add(J,F),F=n.add($,$),$=n.add(F,$),$=n.add($,U),$=n.mul($,J),O=n.add(O,$),U=n.mul(N,T),U=n.add(U,U),$=n.mul(U,J),E=n.sub(E,$),F=n.mul(U,re),F=n.add(F,F),F=n.add(F,F),new k(E,O,F)}add(I){L(I);const{X:A,Y:y,Z:b}=this,{X:N,Y:T,Z:E}=I;let O=n.ZERO,F=n.ZERO,$=n.ZERO;const re=i.a,U=n.mul(i.b,zi);let J=n.mul(A,N),oe=n.mul(y,T),ce=n.mul(b,E),Ie=n.add(A,y),le=n.add(N,T);Ie=n.mul(Ie,le),le=n.add(J,oe),Ie=n.sub(Ie,le),le=n.add(A,b);let he=n.add(N,E);return le=n.mul(le,he),he=n.add(J,ce),le=n.sub(le,he),he=n.add(y,b),O=n.add(T,E),he=n.mul(he,O),O=n.add(oe,ce),he=n.sub(he,O),$=n.mul(re,le),O=n.mul(U,ce),$=n.add(O,$),O=n.sub(oe,$),$=n.add(oe,$),F=n.mul(O,$),oe=n.add(J,J),oe=n.add(oe,J),ce=n.mul(re,ce),le=n.mul(U,le),oe=n.add(oe,ce),ce=n.sub(J,ce),ce=n.mul(re,ce),le=n.add(le,ce),J=n.mul(oe,le),F=n.add(F,J),J=n.mul(he,le),O=n.mul(Ie,O),O=n.sub(O,J),J=n.mul(Ie,oe),$=n.mul(he,$),$=n.add($,J),new k(O,F,$)}subtract(I){return this.add(I.negate())}is0(){return this.equals(k.ZERO)}multiply(I){const{endo:A}=e;if(!r.isValidNot0(I))throw new Error("invalid scalar: out of range");let y,b;const N=T=>ne.cached(this,T,E=>ya(k,E));if(A){const{k1neg:T,k1:E,k2neg:O,k2:F}=B(I),{p:$,f:re}=N(E),{p:U,f:J}=N(F);b=re.add(J),y=Y(A.beta,$,U,T,O)}else{const{p:T,f:E}=N(I);y=T,b=E}return ya(k,[y,b])[0]}multiplyUnsafe(I){const{endo:A}=e,y=this;if(!r.isValid(I))throw new Error("invalid scalar: out of range");if(I===Ps||y.is0())return k.ZERO;if(I===tr)return y;if(ne.hasCache(this))return this.multiply(I);if(A){const{k1neg:b,k1:N,k2neg:T,k2:E}=B(I),{p1:O,p2:F}=Cv(k,y,N,E);return Y(A.beta,O,F,b,T)}else return ne.unsafe(y,I)}multiplyAndAddUnsafe(I,A,y){const b=this.multiplyUnsafe(A).add(I.multiplyUnsafe(y));return b.is0()?void 0:b}toAffine(I){return j(this,I)}isTorsionFree(){const{isTorsionFree:I}=e;return o===tr?!0:I?I(k,this):ne.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:I}=e;return o===tr?this:I?I(k,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(I=!0){return _o(I,"isCompressed"),this.assertValidity(),p(k,this,I)}toHex(I=!0){return er(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return ya(k,I)}static msm(I,A){return Iv(k,r,I,A)}static fromPrivateKey(I){return k.BASE.multiply(Jn(r,I))}}k.BASE=new k(i.Gx,i.Gy,n.ONE),k.ZERO=new k(n.ZERO,n.ONE,n.ZERO),k.Fp=n,k.Fn=r;const te=r.BITS,ne=new Ev(k,e.endo?Math.ceil(te/2):te);return k.BASE.precompute(8),k}function ap(t){return Uint8Array.of(t?2:3)}function cp(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Mv(t,e={}){const{Fn:s}=t,n=e.randomBytes||Bn,r=Object.assign(cp(t.Fp,s),{seed:sp(s.ORDER)});function i(h){try{return!!Jn(s,h)}catch{return!1}}function o(h,p){const{publicKey:f,publicKeyUncompressed:g}=r;try{const w=h.length;return p===!0&&w!==f||p===!1&&w!==g?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(r.seed)){return yv(Cn(h,r.seed,"seed"),s.ORDER)}function c(h,p=!0){return t.BASE.multiply(Jn(s,h)).toBytes(p)}function l(h){const p=a(h);return{secretKey:p,publicKey:c(p)}}function u(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:p,publicKey:f,publicKeyUncompressed:g}=r;if(s.allowedLengths||p===f)return;const w=at("key",h).length;return w===f||w===g}function d(h,p,f=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");const g=Jn(s,h);return t.fromHex(p).multiply(g).toBytes(f)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>Jn(s,h),precompute(h=8,p=t.BASE){return p.precompute(h,!1)}},lengths:r})}function Bv(t,e,s={}){qo(e),Go(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=s.randomBytes||Bn,r=s.hmac||((A,...y)=>Vo(e,A,Js(...y))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p}=Mv(t,s),f={prehash:!1,lowS:typeof s.lowS=="boolean"?s.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function w(A){const y=a>>tr;return A>y}function C(A,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return y}function v(A,y){cc(y);const b=p.signature,N=y==="compact"?b:y==="recovered"?b+1:void 0;return Cn(A,N,`${y} signature`)}class _{constructor(y,b,N){this.r=C("r",y),this.s=C("s",b),N!=null&&(this.recovery=N),Object.freeze(this)}static fromBytes(y,b=g){v(y,b);let N;if(b==="der"){const{r:F,s:$}=Ss.toSig(Cn(y));return new _(F,$)}b==="recovered"&&(N=y[0],b="compact",y=y.subarray(1));const T=o.BYTES,E=y.subarray(0,T),O=y.subarray(T,T*2);return new _(o.fromBytes(E),o.fromBytes(O),N)}static fromHex(y,b){return this.fromBytes(Ao(y),b)}addRecoveryBit(y){return new _(this.r,this.s,y)}recoverPublicKey(y){const b=i.ORDER,{r:N,s:T,recovery:E}=this;if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");if(a*op<b&&E>1)throw new Error("recovery id is ambiguous for h>1 curve");const O=E===2||E===3?N+a:N;if(!i.isValid(O))throw new Error("recovery id 2 or 3 invalid");const F=i.toBytes(O),$=t.fromBytes(Js(ap((E&1)===0),F)),re=o.inv(O),U=B(at("msgHash",y)),J=o.create(-U*re),oe=o.create(T*re),ce=t.BASE.multiplyUnsafe(J).add($.multiplyUnsafe(oe));if(ce.is0())throw new Error("point at infinify");return ce.assertValidity(),ce}hasHighS(){return w(this.s)}toBytes(y=g){if(cc(y),y==="der")return Ao(Ss.hexFromSig(this));const b=o.toBytes(this.r),N=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Js(Uint8Array.of(this.recovery),b,N)}return Js(b,N)}toHex(y){return er(this.toBytes(y))}assertValidity(){}static fromCompact(y){return _.fromBytes(at("sig",y),"compact")}static fromDER(y){return _.fromBytes(at("sig",y),"der")}normalizeS(){return this.hasHighS()?new _(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return er(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return er(this.toBytes("compact"))}}const L=s.bits2int||function(A){if(A.length>8192)throw new Error("input is too large");const y=zo(A),b=A.length*8-c;return b>0?y>>BigInt(b):y},B=s.bits2int_modN||function(A){return o.create(L(A))},j=Ni(c);function K(A){return oc("num < 2^"+c,A,Ps,j),o.toBytes(A)}function Y(A,y){return Cn(A,void 0,"message"),y?Cn(e(A),void 0,"prehashed message"):A}function k(A,y,b){if(["recovered","canonical"].some(oe=>oe in b))throw new Error("sign() legacy options not supported");const{lowS:N,prehash:T,extraEntropy:E}=Ca(b,f);A=Y(A,T);const O=B(A),F=Jn(o,y),$=[K(F),K(O)];if(E!=null&&E!==!1){const oe=E===!0?n(p.secretKey):E;$.push(at("extraEntropy",oe))}const re=Js(...$),U=O;function J(oe){const ce=L(oe);if(!o.isValidNot0(ce))return;const Ie=o.inv(ce),le=t.BASE.multiply(ce).toAffine(),he=o.create(le.x);if(he===Ps)return;const Le=o.create(Ie*o.create(U+he*F));if(Le===Ps)return;let dt=(le.x===he?0:2)|Number(le.y&tr),rs=Le;return N&&w(Le)&&(rs=o.neg(Le),dt^=1),new _(he,rs,dt)}return{seed:re,k2sig:J}}function te(A,y,b={}){A=at("message",A);const{seed:N,k2sig:T}=k(A,y,b);return lv(e.outputLen,o.BYTES,r)(N,T)}function ne(A){let y;const b=typeof A=="string"||Fo(A),N=!b&&A!==null&&typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!b&&!N)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(N)y=new _(A.r,A.s);else if(b){try{y=_.fromBytes(at("sig",A),"der")}catch(T){if(!(T instanceof Ss.Err))throw T}if(!y)try{y=_.fromBytes(at("sig",A),"compact")}catch{return!1}}return y||!1}function P(A,y,b,N={}){const{lowS:T,prehash:E,format:O}=Ca(N,f);if(b=at("publicKey",b),y=Y(at("message",y),E),"strict"in N)throw new Error("options.strict was renamed to lowS");const F=O===void 0?ne(A):_.fromBytes(at("sig",A),O);if(F===!1)return!1;try{const $=t.fromBytes(b);if(T&&F.hasHighS())return!1;const{r:re,s:U}=F,J=B(y),oe=o.inv(U),ce=o.create(J*oe),Ie=o.create(re*oe),le=t.BASE.multiplyUnsafe(ce).add($.multiplyUnsafe(Ie));return le.is0()?!1:o.create(le.x)===re}catch{return!1}}function I(A,y,b={}){const{prehash:N}=Ca(b,f);return y=Y(y,N),_.fromBytes(A,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p,Point:t,sign:te,verify:P,recoverPublicKey:I,Signature:_,hash:e})}function jv(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},s=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const r=an(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),i={Fp:s,Fn:r,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function Fv(t){const{CURVE:e,curveOpts:s}=jv(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:s,hash:t.hash,ecdsaOpts:n}}function qv(t,e){const s=e.Point;return Object.assign({},e,{ProjectivePoint:s,CURVE:Object.assign({},t,ep(s.Fn.ORDER,s.Fn.BITS))})}function Wv(t){const{CURVE:e,curveOpts:s,hash:n,ecdsaOpts:r}=Fv(t),i=Lv(e,s),o=Bv(i,n,r);return qv(t,o)}function lc(t,e){const s=n=>Wv({...t,hash:n});return{...s(e),create:s}}const lp={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},up={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},dp={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Hv=an(lp.p),Vv=an(up.p),Kv=an(dp.p),zv=lc({...lp,Fp:Hv,lowS:!1},Ho);lc({...up,Fp:Vv,lowS:!1},eb),lc({...dp,Fp:Kv,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Qy);const Gv=zv,hp="base10",ut="base16",bt="base64pad",Xs="base64url",_i="utf8",pp=0,xs=1,Si=2,Yv=0,vu=1,Br=12,Xc=32;function Jv(){const t=ac.utils.randomPrivateKey(),e=ac.getPublicKey(t);return{privateKey:Et(t,ut),publicKey:Et(e,ut)}}function uc(){const t=Bn(Xc);return Et(t,ut)}function Xv(t,e){const s=ac.getSharedSecret(qt(t,ut),qt(e,ut)),n=av(Ko,s,void 0,void 0,Xc);return Et(n,ut)}function co(t){const e=Ko(qt(t,ut));return Et(e,ut)}function jt(t){const e=Ko(qt(t,_i));return Et(e,ut)}function fp(t){return qt(`${t}`,hp)}function xn(t){return Number(Et(t,hp))}function gp(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function mp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function Zv(t){const e=fp(typeof t.type<"u"?t.type:pp);if(xn(e)===xs&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?qt(t.senderPublicKey,ut):void 0,n=typeof t.iv<"u"?qt(t.iv,ut):Bn(Br),r=qt(t.symKey,ut),i=qh(r,n).encrypt(qt(t.message,_i)),o=wp({type:e,sealed:i,iv:n,senderPublicKey:s});return t.encoding===Xs?gp(o):o}function Qv(t){const e=qt(t.symKey,ut),{sealed:s,iv:n}=gi({encoded:t.encoded,encoding:t.encoding}),r=qh(e,n).decrypt(s);if(r===null)throw new Error("Failed to decrypt");return Et(r,_i)}function e0(t,e){const s=fp(Si),n=Bn(Br),r=qt(t,_i),i=wp({type:s,sealed:r,iv:n});return e===Xs?gp(i):i}function t0(t,e){const{sealed:s}=gi({encoded:t,encoding:e});return Et(s,_i)}function wp(t){if(xn(t.type)===Si)return Et(Ur([t.type,t.sealed]),bt);if(xn(t.type)===xs){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Et(Ur([t.type,t.senderPublicKey,t.iv,t.sealed]),bt)}return Et(Ur([t.type,t.iv,t.sealed]),bt)}function gi(t){const e=(t.encoding||bt)===Xs?mp(t.encoded):t.encoded,s=qt(e,bt),n=s.slice(Yv,vu),r=vu;if(xn(n)===xs){const c=r+Xc,l=c+Br,u=s.slice(r,c),d=s.slice(c,l),h=s.slice(l);return{type:n,sealed:h,iv:d,senderPublicKey:u}}if(xn(n)===Si){const c=s.slice(r),l=Bn(Br);return{type:n,sealed:c,iv:l}}const i=r+Br,o=s.slice(r,i),a=s.slice(i);return{type:n,sealed:a,iv:o}}function s0(t,e){const s=gi({encoded:t,encoding:e?.encoding});return yp({type:xn(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?Et(s.senderPublicKey,ut):void 0,receiverPublicKey:e?.receiverPublicKey})}function yp(t){const e=t?.type||pp;if(e===xs){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function Eu(t){return t.type===xs&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Cu(t){return t.type===Si}function n0(t){const e=Buffer.from(t.x,"base64"),s=Buffer.from(t.y,"base64");return Ur([new Uint8Array([4]),e,s])}function r0(t,e){const[s,n,r]=t.split("."),i=Buffer.from(mp(r),"base64");if(i.length!==64)throw new Error("Invalid signature length");const o=i.slice(0,32),a=i.slice(32,64),c=`${s}.${n}`,l=Ko(c),u=n0(e);if(!Gv.verify(Ur([o,a]),l,u))throw new Error("Invalid signature");return Fa(t).payload}const i0="irn";function Oo(t){return t?.relay||{protocol:i0}}function Xn(t){const e=bf[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var o0=Object.defineProperty,a0=Object.defineProperties,c0=Object.getOwnPropertyDescriptors,Iu=Object.getOwnPropertySymbols,l0=Object.prototype.hasOwnProperty,u0=Object.prototype.propertyIsEnumerable,Au=(t,e,s)=>e in t?o0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ia=(t,e)=>{for(var s in e||(e={}))l0.call(e,s)&&Au(t,s,e[s]);if(Iu)for(var s of Iu(e))u0.call(e,s)&&Au(t,s,e[s]);return t},d0=(t,e)=>a0(t,c0(e));function h0(t,e="-"){const s={},n="relay"+e;return Object.keys(t).forEach(r=>{if(r.startsWith(n)){const i=r.replace(n,""),o=t[r];s[i]=o}}),s}function Nu(t){if(!t.includes("wc:")){const l=Ch(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),s=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),r=t.substring(e+1,s).split("@"),i=typeof s<"u"?t.substring(s):"",o=new URLSearchParams(i),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:p0(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:h0(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function p0(t){return t.startsWith("//")?t.substring(2):t}function f0(t,e="-"){const s="relay",n={};return Object.keys(t).forEach(r=>{const i=r,o=s+e+i;t[i]&&(n[o]=t[i])}),n}function _u(t){const e=new URLSearchParams,s=Ia(Ia(d0(Ia({},f0(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(s).sort(([n],[r])=>n.localeCompare(r)).forEach(([n,r])=>{r!==void 0&&e.append(n,String(r))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function Gi(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var g0=Object.defineProperty,m0=Object.defineProperties,w0=Object.getOwnPropertyDescriptors,Su=Object.getOwnPropertySymbols,y0=Object.prototype.hasOwnProperty,b0=Object.prototype.propertyIsEnumerable,Tu=(t,e,s)=>e in t?g0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,v0=(t,e)=>{for(var s in e||(e={}))y0.call(e,s)&&Tu(t,s,e[s]);if(Su)for(var s of Su(e))b0.call(e,s)&&Tu(t,s,e[s]);return t},E0=(t,e)=>m0(t,w0(e));function mr(t){const e=[];return t.forEach(s=>{const[n,r]=s.split(":");e.push(`${n}:${r}`)}),e}function C0(t){const e=[];return Object.values(t).forEach(s=>{e.push(...mr(s.accounts))}),e}function I0(t,e){const s=[];return Object.values(t).forEach(n=>{mr(n.accounts).includes(e)&&s.push(...n.methods)}),s}function A0(t,e){const s=[];return Object.values(t).forEach(n=>{mr(n.accounts).includes(e)&&s.push(...n.events)}),s}function Yo(t){return t.includes(":")}function Zn(t){return Yo(t)?t.split(":")[0]:t}function Ou(t){var e,s,n;const r={};if(!ws(t))return r;for(const[i,o]of Object.entries(t)){const a=Yo(i)?[i]:o.chains,c=o.methods||[],l=o.events||[],u=Zn(i);r[u]=E0(v0({},r[u]),{chains:ms(a,(e=r[u])==null?void 0:e.chains),methods:ms(c,(s=r[u])==null?void 0:s.methods),events:ms(l,(n=r[u])==null?void 0:n.events)})}return r}function N0(t){const e={};return t?.forEach(s=>{var n;const[r,i]=s.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(s),(n=e[r].chains)==null||n.push(`${r}:${i}`)}),e}function ku(t,e){e=e.map(n=>n.replace("did:pkh:",""));const s=N0(e);for(const[n,r]of Object.entries(s))r.methods?r.methods=ms(r.methods,t):r.methods=t,r.events=["chainChanged","accountsChanged"];return s}function _0(t,e){var s,n,r,i,o,a;const c=Ou(t),l=Ou(e),u={},d=Object.keys(c).concat(Object.keys(l));for(const h of d)u[h]={chains:ms((s=c[h])==null?void 0:s.chains,(n=l[h])==null?void 0:n.chains),methods:ms((r=c[h])==null?void 0:r.methods,(i=l[h])==null?void 0:i.methods),events:ms((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return u}const S0={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},T0={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function q(t,e){const{message:s,code:n}=T0[t];return{message:e?`${s} ${e}`:s,code:n}}function Ue(t,e){const{message:s,code:n}=S0[t];return{message:e?`${s} ${e}`:s,code:n}}function $s(t,e){return!!Array.isArray(t)}function ws(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function He(t){return typeof t>"u"}function Fe(t,e){return e&&He(t)?!0:typeof t=="string"&&!!t.trim().length}function Zc(t,e){return e&&He(t)?!0:typeof t=="number"&&!isNaN(t)}function O0(t,e){const{requiredNamespaces:s}=e,n=Object.keys(t.namespaces),r=Object.keys(s);let i=!0;return En(r,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=mr(a),d=s[o];(!En(wh(o,d),u)||!En(d.methods,c)||!En(d.events,l))&&(i=!1)}),i):!1}function ko(t){return Fe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function k0(t){if(Fe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&ko(s)}}return!1}function P0(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(Fe(t,!1)){if(e(t))return!0;const s=Ch(t);return e(s)}}catch{}return!1}function R0(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function x0(t){return t?.topic}function $0(t,e){let s=null;return Fe(t?.publicKey,!1)||(s=q("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function Pu(t){let e=!0;return $s(t)?t.length&&(e=t.every(s=>Fe(s,!1))):e=!1,e}function U0(t,e,s){let n=null;return $s(e)&&e.length?e.forEach(r=>{n||ko(r)||(n=Ue("UNSUPPORTED_CHAINS",`${s}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):ko(t)||(n=Ue("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),n}function D0(t,e,s){let n=null;return Object.entries(t).forEach(([r,i])=>{if(n)return;const o=U0(r,wh(r,i),`${e} ${s}`);o&&(n=o)}),n}function L0(t,e){let s=null;return $s(t)?t.forEach(n=>{s||k0(n)||(s=Ue("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):s=Ue("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function M0(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=L0(n?.accounts,`${e} namespace`);r&&(s=r)}),s}function B0(t,e){let s=null;return Pu(t?.methods)?Pu(t?.events)||(s=Ue("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=Ue("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function bp(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=B0(n,`${e}, namespace`);r&&(s=r)}),s}function j0(t,e,s){let n=null;if(t&&ws(t)){const r=bp(t,e);r&&(n=r);const i=D0(t,e,s);i&&(n=i)}else n=q("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return n}function Aa(t,e){let s=null;if(t&&ws(t)){const n=bp(t,e);n&&(s=n);const r=M0(t,e);r&&(s=r)}else s=q("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function vp(t){return Fe(t.protocol,!0)}function F0(t,e){let s=!1;return t?t&&$s(t)&&t.length&&t.forEach(n=>{s=vp(n)}):s=!0,s}function q0(t){return typeof t=="number"}function wt(t){return typeof t<"u"&&typeof t!==null}function W0(t){return!(!t||typeof t!="object"||!t.code||!Zc(t.code,!1)||!t.message||!Fe(t.message,!1))}function H0(t){return!(He(t)||!Fe(t.method,!1))}function V0(t){return!(He(t)||He(t.result)&&He(t.error)||!Zc(t.id,!1)||!Fe(t.jsonrpc,!1))}function K0(t){return!(He(t)||!Fe(t.name,!1))}function Ru(t,e){return!(!ko(e)||!C0(t).includes(e))}function z0(t,e,s){return Fe(s,!1)?I0(t,e).includes(s):!1}function G0(t,e,s){return Fe(s,!1)?A0(t,e).includes(s):!1}function xu(t,e,s){let n=null;const r=Y0(t),i=J0(e),o=Object.keys(r),a=Object.keys(i),c=$u(Object.keys(t)),l=$u(Object.keys(e)),u=c.filter(d=>!l.includes(d));return u.length&&(n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
14
+ Required: ${u.toString()}
15
+ Received: ${Object.keys(e).toString()}`)),En(o,a)||(n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.
16
+ Required: ${o.toString()}
17
+ Approved: ${a.toString()}`)),Object.keys(e).forEach(d=>{if(!d.includes(":")||n)return;const h=mr(e[d].accounts);h.includes(d)||(n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${d}
18
+ Required: ${d}
19
+ Approved: ${h.toString()}`))}),o.forEach(d=>{n||(En(r[d].methods,i[d].methods)?En(r[d].events,i[d].events)||(n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${d}`)):n=q("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${d}`))}),n}function Y0(t){const e={};return Object.keys(t).forEach(s=>{var n;s.includes(":")?e[s]=t[s]:(n=t[s].chains)==null||n.forEach(r=>{e[r]={methods:t[s].methods,events:t[s].events}})}),e}function $u(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function J0(t){const e={};return Object.keys(t).forEach(s=>{s.includes(":")?e[s]=t[s]:mr(t[s].accounts)?.forEach(r=>{e[r]={accounts:t[s].accounts.filter(i=>i.includes(`${r}:`)),methods:t[s].methods,events:t[s].events}})}),e}function X0(t,e){return Zc(t,!1)&&t<=e.max&&t>=e.min}function Uu(){const t=Ii();return new Promise(e=>{switch(t){case kt.browser:e(Z0());break;case kt.reactNative:e(Q0());break;case kt.node:e(eE());break;default:e(!0)}})}function Z0(){return gr()&&navigator?.onLine}async function Q0(){return on()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function eE(){return!0}function tE(t){switch(Ii()){case kt.browser:sE(t);break;case kt.reactNative:nE(t);break}}function sE(t){!on()&&gr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function nE(t){on()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function rE(){var t;return gr()&&Us.getDocument()?((t=Us.getDocument())==null?void 0:t.visibilityState)==="visible":!0}const Na={};class Ir{static get(e){return Na[e]}static set(e,s){Na[e]=s}static delete(e){delete Na[e]}}function iE(t){const e=pr.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function oE({publicKey:t,signature:e,payload:s}){var n;const r=dc(s.method),i=128|parseInt(((n=s.version)==null?void 0:n.toString())||"4"),o=lE(s.address),a=s.era==="00"?new Uint8Array([0]):dc(s.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(s.nonce,16),l=new Uint8Array([c&255,c>>8&255]),u=BigInt(`0x${cE(s.tip)}`),d=dE(u),h=new Uint8Array([0,...t,o,...e,...a,...l,...d,...r]),p=uE(h.length+1);return new Uint8Array([...p,i,...h])}function aE(t){const e=dc(t),s=Af.blake2b(e,void 0,32);return"0x"+Buffer.from(s).toString("hex")}function dc(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function cE(t){return t.startsWith("0x")?t.slice(2):t}function lE(t){const e=pr.decode(t)[0];return e===42?0:e===60?2:1}function uE(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function dE(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function hE(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),s=iE(t.transaction.address),n=oE({publicKey:s,signature:e,payload:t.transaction}),r=Buffer.from(n).toString("hex");return aE(r)}function Qc({logger:t,name:e}){const s=typeof t=="string"?mh({opts:{level:t,name:e}}).logger:t;return s.level=typeof t=="string"?t:t.level,s}var pE={};const Ep="wc",Cp=2,hc="core",ys=`${Ep}@2:${hc}:`,fE={logger:"error"},gE={database:":memory:"},mE="crypto",Du="client_ed25519_seed",wE=W.ONE_DAY,yE="keychain",bE="0.3",vE="messages",EE="0.3",CE=W.SIX_HOURS,IE="publisher",Ip="irn",AE="error",Ap="wss://relay.walletconnect.org",NE="relayer",Me={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},_E="_subscription",$t={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},SE=.1,pc="2.22.4",Pe={link_mode:"link_mode",relay:"relay"},lo={inbound:"inbound",outbound:"outbound"},TE="0.3",OE="WALLETCONNECT_CLIENT_ID",Lu="WALLETCONNECT_LINK_MODE_APPS",St={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},kE="subscription",PE="0.3",RE="pairing",xE="0.3",Ar={wc_pairingDelete:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:W.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:W.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:W.ONE_DAY,prompt:!1,tag:0},res:{ttl:W.ONE_DAY,prompt:!1,tag:0}}},mn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Gt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},$E="history",UE="0.3",DE="expirer",Bt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},LE="0.3",ME="verify-api",BE="https://verify.walletconnect.com",Np="https://verify.walletconnect.org",jr=Np,jE=`${jr}/v3`,FE=[BE,Np],qE="echo",WE="https://echo.walletconnect.com",cs={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Is={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Yt={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},un={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},dn={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},Nr={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},HE=.1,VE="event-client",KE=86400,zE="https://pulse.walletconnect.org/batch";function GE(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),n=0;n<s.length;n++)s[n]=255;for(var r=0;r<t.length;r++){var i=t.charAt(r),o=i.charCodeAt(0);if(s[o]!==255)throw new TypeError(i+" is ambiguous");s[o]=r}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,w=0,C=0,v=f.length;C!==v&&f[C]===0;)C++,g++;for(var _=(v-C)*u+1>>>0,L=new Uint8Array(_);C!==v;){for(var B=f[C],j=0,K=_-1;(B!==0||j<w)&&K!==-1;K--,j++)B+=256*L[K]>>>0,L[K]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");w=j,C++}for(var Y=_-w;Y!==_&&L[Y]===0;)Y++;for(var k=c.repeat(g);Y<_;++Y)k+=t.charAt(L[Y]);return k}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var w=0,C=0;f[g]===c;)w++,g++;for(var v=(f.length-g)*l+1>>>0,_=new Uint8Array(v);f[g];){var L=s[f.charCodeAt(g)];if(L===255)return;for(var B=0,j=v-1;(L!==0||B<C)&&j!==-1;j--,B++)L+=a*_[j]>>>0,_[j]=L%256>>>0,L=L/256>>>0;if(L!==0)throw new Error("Non-zero carry");C=B,g++}if(f[g]!==" "){for(var K=v-C;K!==v&&_[K]===0;)K++;for(var Y=new Uint8Array(w+(v-K)),k=w;K!==v;)Y[k++]=_[K++];return Y}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var YE=GE,JE=YE;const _p=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},XE=t=>new TextEncoder().encode(t),ZE=t=>new TextDecoder().decode(t);class QE{constructor(e,s,n){this.name=e,this.prefix=s,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class eC{constructor(e,s,n){if(this.name=e,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Sp(this,e)}}class tC{constructor(e){this.decoders=e}or(e){return Sp(this,e)}decode(e){const s=e[0],n=this.decoders[s];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Sp=(t,e)=>new tC({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class sC{constructor(e,s,n,r){this.name=e,this.prefix=s,this.baseEncode=n,this.baseDecode=r,this.encoder=new QE(e,s,n),this.decoder=new eC(e,s,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Jo=({name:t,prefix:e,encode:s,decode:n})=>new sC(t,e,s,n),Ti=({prefix:t,name:e,alphabet:s})=>{const{encode:n,decode:r}=JE(s,e);return Jo({prefix:t,name:e,encode:n,decode:i=>_p(r(i))})},nC=(t,e,s,n)=>{const r={};for(let u=0;u<e.length;++u)r[e[u]]=u;let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*s/8|0);let a=0,c=0,l=0;for(let u=0;u<i;++u){const d=r[t[u]];if(d===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<s|d,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},rC=(t,e,s)=>{const n=e[e.length-1]==="=",r=(1<<s)-1;let i="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,i+=e[r&a>>o];if(o&&(i+=e[r&a<<s-o]),n)for(;i.length*s&7;)i+="=";return i},tt=({name:t,prefix:e,bitsPerChar:s,alphabet:n})=>Jo({prefix:e,name:t,encode(r){return rC(r,n,s)},decode(r){return nC(r,n,s,t)}}),iC=Jo({prefix:"\0",name:"identity",encode:t=>ZE(t),decode:t=>XE(t)});var oC=Object.freeze({__proto__:null,identity:iC});const aC=tt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cC=Object.freeze({__proto__:null,base2:aC});const lC=tt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var uC=Object.freeze({__proto__:null,base8:lC});const dC=Ti({prefix:"9",name:"base10",alphabet:"0123456789"});var hC=Object.freeze({__proto__:null,base10:dC});const pC=tt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),fC=tt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var gC=Object.freeze({__proto__:null,base16:pC,base16upper:fC});const mC=tt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),wC=tt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),yC=tt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),bC=tt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vC=tt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),EC=tt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),CC=tt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),IC=tt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),AC=tt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var NC=Object.freeze({__proto__:null,base32:mC,base32upper:wC,base32pad:yC,base32padupper:bC,base32hex:vC,base32hexupper:EC,base32hexpad:CC,base32hexpadupper:IC,base32z:AC});const _C=Ti({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),SC=Ti({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var TC=Object.freeze({__proto__:null,base36:_C,base36upper:SC});const OC=Ti({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kC=Ti({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var PC=Object.freeze({__proto__:null,base58btc:OC,base58flickr:kC});const RC=tt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),xC=tt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$C=tt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),UC=tt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var DC=Object.freeze({__proto__:null,base64:RC,base64pad:xC,base64url:$C,base64urlpad:UC});const Tp=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),LC=Tp.reduce((t,e,s)=>(t[s]=e,t),[]),MC=Tp.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function BC(t){return t.reduce((e,s)=>(e+=LC[s],e),"")}function jC(t){const e=[];for(const s of t){const n=MC[s.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(n)}return new Uint8Array(e)}const FC=Jo({prefix:"🚀",name:"base256emoji",encode:BC,decode:jC});var qC=Object.freeze({__proto__:null,base256emoji:FC}),WC=Op,Mu=128,HC=-128,VC=Math.pow(2,31);function Op(t,e,s){e=e||[],s=s||0;for(var n=s;t>=VC;)e[s++]=t&255|Mu,t/=128;for(;t&HC;)e[s++]=t&255|Mu,t>>>=7;return e[s]=t|0,Op.bytes=s-n+1,e}var KC=fc,zC=128,Bu=127;function fc(t,n){var s=0,n=n||0,r=0,i=n,o,a=t.length;do{if(i>=a)throw fc.bytes=0,new RangeError("Could not decode varint");o=t[i++],s+=r<28?(o&Bu)<<r:(o&Bu)*Math.pow(2,r),r+=7}while(o>=zC);return fc.bytes=i-n,s}var GC=Math.pow(2,7),YC=Math.pow(2,14),JC=Math.pow(2,21),XC=Math.pow(2,28),ZC=Math.pow(2,35),QC=Math.pow(2,42),eI=Math.pow(2,49),tI=Math.pow(2,56),sI=Math.pow(2,63),nI=function(t){return t<GC?1:t<YC?2:t<JC?3:t<XC?4:t<ZC?5:t<QC?6:t<eI?7:t<tI?8:t<sI?9:10},rI={encode:WC,decode:KC,encodingLength:nI},kp=rI;const ju=(t,e,s=0)=>(kp.encode(t,e,s),e),Fu=t=>kp.encodingLength(t),gc=(t,e)=>{const s=e.byteLength,n=Fu(t),r=n+Fu(s),i=new Uint8Array(r+s);return ju(t,i,0),ju(s,i,n),i.set(e,r),new iI(t,s,e,i)};class iI{constructor(e,s,n,r){this.code=e,this.size=s,this.digest=n,this.bytes=r}}const Pp=({name:t,code:e,encode:s})=>new oI(t,e,s);class oI{constructor(e,s,n){this.name=e,this.code=s,this.encode=n}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?gc(this.code,s):s.then(n=>gc(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Rp=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),aI=Pp({name:"sha2-256",code:18,encode:Rp("SHA-256")}),cI=Pp({name:"sha2-512",code:19,encode:Rp("SHA-512")});var lI=Object.freeze({__proto__:null,sha256:aI,sha512:cI});const xp=0,uI="identity",$p=_p,dI=t=>gc(xp,$p(t)),hI={code:xp,name:uI,encode:$p,digest:dI};var pI=Object.freeze({__proto__:null,identity:hI});new TextEncoder,new TextDecoder;const qu={...oC,...cC,...uC,...hC,...gC,...NC,...TC,...PC,...DC,...qC};({...lI,...pI});function Up(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function fI(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Up(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Dp(t,e,s,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:n}}}const Wu=Dp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),_a=Dp("ascii","a",t=>{let e="a";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return e},t=>{t=t.substring(1);const e=fI(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),gI={utf8:Wu,"utf-8":Wu,hex:qu.base16,latin1:_a,ascii:_a,binary:_a,...qu};function mI(t,e="utf8"){const s=gI[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Up(globalThis.Buffer.from(t,"utf-8")):s.decoder.decode(`${s.prefix}${t}`)}var wI=Object.defineProperty,yI=(t,e,s)=>e in t?wI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,os=(t,e,s)=>yI(t,typeof e!="symbol"?e+"":e,s);class bI{constructor(e,s){this.core=e,this.logger=s,os(this,"keychain",new Map),os(this,"name",yE),os(this,"version",bE),os(this,"initialized",!1),os(this,"storagePrefix",ys),os(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),os(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),os(this,"set",async(n,r)=>{this.isInitialized(),this.keychain.set(n,r),await this.persist()}),os(this,"get",n=>{this.isInitialized();const r=this.keychain.get(n);if(typeof r>"u"){const{message:i}=q("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(i)}return r}),os(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=Rt(s,this.name)}get context(){return It(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Za(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Qa(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var vI=Object.defineProperty,EI=(t,e,s)=>e in t?vI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ve=(t,e,s)=>EI(t,typeof e!="symbol"?e+"":e,s);class CI{constructor(e,s,n){this.core=e,this.logger=s,Ve(this,"name",mE),Ve(this,"keychain"),Ve(this,"randomSessionIdentifier",uc()),Ve(this,"initialized",!1),Ve(this,"clientId"),Ve(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ve(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),Ve(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const r=await this.getClientSeed(),i=pl(r),o=Of(i.publicKey);return this.clientId=o,o}),Ve(this,"generateKeyPair",()=>{this.isInitialized();const r=Jv();return this.setPrivateKey(r.publicKey,r.privateKey)}),Ve(this,"signJWT",async r=>{this.isInitialized();const i=await this.getClientSeed(),o=pl(i),a=this.randomSessionIdentifier;return await kf(a,r,wE,o)}),Ve(this,"generateSharedKey",(r,i,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=Xv(a,i);return this.setSymKey(c,o)}),Ve(this,"setSymKey",async(r,i)=>{this.isInitialized();const o=i||co(r);return await this.keychain.set(o,r),o}),Ve(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),Ve(this,"encode",async(r,i,o)=>{this.isInitialized();const a=yp(o),c=On(i);if(Cu(a))return e0(c,o?.encoding);if(Eu(a)){const h=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(h,p)}const l=this.getSymKey(r),{type:u,senderPublicKey:d}=a;return Zv({type:u,symKey:l,message:c,senderPublicKey:d,encoding:o?.encoding})}),Ve(this,"decode",async(r,i,o)=>{this.isInitialized();const a=s0(i,o);if(Cu(a)){const c=t0(i,o?.encoding);return go(c)}if(Eu(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=Qv({symKey:c,encoded:i,encoding:o?.encoding});return go(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ve(this,"getPayloadType",(r,i=bt)=>{const o=gi({encoded:r,encoding:i});return xn(o.type)}),Ve(this,"getPayloadSenderPublicKey",(r,i=bt)=>{const o=gi({encoded:r,encoding:i});return o.senderPublicKey?Et(o.senderPublicKey,ut):void 0}),this.core=e,this.logger=Rt(s,this.name),this.keychain=n||new bI(this.core,this.logger)}get context(){return It(this.logger)}async setPrivateKey(e,s){return await this.keychain.set(e,s),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Du)}catch{e=uc(),await this.keychain.set(Du,e)}return mI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var II=Object.defineProperty,AI=Object.defineProperties,NI=Object.getOwnPropertyDescriptors,Hu=Object.getOwnPropertySymbols,_I=Object.prototype.hasOwnProperty,SI=Object.prototype.propertyIsEnumerable,mc=(t,e,s)=>e in t?II(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,TI=(t,e)=>{for(var s in e||(e={}))_I.call(e,s)&&mc(t,s,e[s]);if(Hu)for(var s of Hu(e))SI.call(e,s)&&mc(t,s,e[s]);return t},OI=(t,e)=>AI(t,NI(e)),Nt=(t,e,s)=>mc(t,typeof e!="symbol"?e+"":e,s);class kI extends xw{constructor(e,s){super(e,s),this.logger=e,this.core=s,Nt(this,"messages",new Map),Nt(this,"messagesWithoutClientAck",new Map),Nt(this,"name",vE),Nt(this,"version",EE),Nt(this,"initialized",!1),Nt(this,"storagePrefix",ys),Nt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const r=await this.getRelayerMessagesWithoutClientAck();typeof r<"u"&&(this.messagesWithoutClientAck=r),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),Nt(this,"set",async(n,r,i)=>{this.isInitialized();const o=jt(r);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=r,this.messages.set(n,a),i===lo.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,OI(TI({},c),{[o]:r}))}return await this.persist(),o}),Nt(this,"get",n=>{this.isInitialized();let r=this.messages.get(n);return typeof r>"u"&&(r={}),r}),Nt(this,"getWithoutAck",n=>{this.isInitialized();const r={};for(const i of n){const o=this.messagesWithoutClientAck.get(i)||{};r[i]=Object.values(o)}return r}),Nt(this,"has",(n,r)=>{this.isInitialized();const i=this.get(n),o=jt(r);return typeof i[o]<"u"}),Nt(this,"ack",async(n,r)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(n);if(typeof i>"u")return;const o=jt(r);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,i),await this.persist()}),Nt(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Rt(e,this.name),this.core=s}get context(){return It(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,Za(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Za(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Qa(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Qa(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var PI=Object.defineProperty,RI=Object.defineProperties,xI=Object.getOwnPropertyDescriptors,Vu=Object.getOwnPropertySymbols,$I=Object.prototype.hasOwnProperty,UI=Object.prototype.propertyIsEnumerable,wc=(t,e,s)=>e in t?PI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Hn=(t,e)=>{for(var s in e||(e={}))$I.call(e,s)&&wc(t,s,e[s]);if(Vu)for(var s of Vu(e))UI.call(e,s)&&wc(t,s,e[s]);return t},Ku=(t,e)=>RI(t,xI(e)),Ut=(t,e,s)=>wc(t,typeof e!="symbol"?e+"":e,s);class DI extends $w{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Ut(this,"events",new Un.EventEmitter),Ut(this,"name",IE),Ut(this,"queue",new Map),Ut(this,"publishTimeout",W.toMiliseconds(W.ONE_MINUTE)),Ut(this,"initialPublishTimeout",W.toMiliseconds(W.ONE_SECOND*15)),Ut(this,"needsTransportRestart",!1),Ut(this,"publish",async(n,r,i)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:r,opts:i}});const d=i?.ttl||CE,h=i?.prompt||!1,p=i?.tag||0,f=i?.id||bn().toString(),g=Xn(Oo().protocol),w={id:f,method:i?.publishMethod||g.publish,params:Hn({topic:n,message:r,ttl:d,prompt:h,tag:p,attestation:i?.attestation},i?.tvf)},C=`Failed to publish payload, please try again. id:${f} tag:${p}`;try{He((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),He((c=w.params)==null?void 0:c.tag)&&((l=w.params)==null||delete l.tag);const v=new Promise(async _=>{const L=({id:j})=>{var K;((K=w.id)==null?void 0:K.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(Me.publish,L),_())};this.relayer.events.on(Me.publish,L);const B=ps(new Promise((j,K)=>{this.rpcPublish(w,i).then(j).catch(Y=>{this.logger.warn(Y,Y?.message),K(Y)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${f} tag:${p}`);try{await B,this.events.removeListener(Me.publish,L)}catch(j){this.queue.set(f,{request:w,opts:i,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:f,topic:n,message:r,opts:i}}),await ps(v,this.publishTimeout,C)}catch(v){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(v),(u=i?.internal)!=null&&u.throwOnFailedPublish)throw v}finally{this.queue.delete(f)}}),Ut(this,"publishCustom",async n=>{var r,i,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:l,opts:u={}}=n,{attestation:d,tvf:h,publishMethod:p,prompt:f,tag:g,ttl:w=W.FIVE_MINUTES}=u,C=u.id||bn().toString(),v=Xn(Oo().protocol),_=p||v.publish,L={id:C,method:_,params:Hn(Ku(Hn({},l),{ttl:w,prompt:f,tag:g,attestation:d}),h)},B=`Failed to publish custom payload, please try again. id:${C} tag:${g}`;try{He((r=L.params)==null?void 0:r.prompt)&&((i=L.params)==null||delete i.prompt),He((o=L.params)==null?void 0:o.tag)&&((a=L.params)==null||delete a.tag);const j=new Promise(async K=>{const Y=({id:te})=>{var ne;((ne=L.id)==null?void 0:ne.toString())===te.toString()&&(this.removeRequestFromQueue(te),this.relayer.events.removeListener(Me.publish,Y),K())};this.relayer.events.on(Me.publish,Y);const k=ps(new Promise((te,ne)=>{this.rpcPublish(L,u).then(te).catch(P=>{this.logger.warn(P,P?.message),ne(P)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${_} id:${C} tag:${g}`);try{await k,this.events.removeListener(Me.publish,Y)}catch(te){this.queue.set(C,{request:L,opts:u,attempt:1}),this.logger.warn(te,te?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:C,payload:l,opts:u}}),await ps(j,this.publishTimeout,B)}catch(j){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(j),(c=u?.internal)!=null&&c.throwOnFailedPublish)throw j}finally{this.queue.delete(C)}}),Ut(this,"on",(n,r)=>{this.events.on(n,r)}),Ut(this,"once",(n,r)=>{this.events.once(n,r)}),Ut(this,"off",(n,r)=>{this.events.off(n,r)}),Ut(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.relayer=e,this.logger=Rt(s,this.name),this.registerEventListeners()}get context(){return It(this.logger)}async rpcPublish(e,s){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(Me.publish,Hn(Hn({},e),s)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{var n;const r=e.attempt+1;this.queue.set(s,Ku(Hn({},e),{attempt:r})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${r}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(fr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Me.connection_stalled);return}this.checkQueue()}),this.relayer.on(Me.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var LI=Object.defineProperty,MI=(t,e,s)=>e in t?LI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Vn=(t,e,s)=>MI(t,typeof e!="symbol"?e+"":e,s);class BI{constructor(){Vn(this,"map",new Map),Vn(this,"set",(e,s)=>{const n=this.get(e);this.exists(e,s)||this.map.set(e,[...n,s])}),Vn(this,"get",e=>this.map.get(e)||[]),Vn(this,"exists",(e,s)=>this.get(e).includes(s)),Vn(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,s))return;const r=n.filter(i=>i!==s);if(!r.length){this.map.delete(e);return}this.map.set(e,r)}),Vn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var jI=Object.defineProperty,FI=Object.defineProperties,qI=Object.getOwnPropertyDescriptors,zu=Object.getOwnPropertySymbols,WI=Object.prototype.hasOwnProperty,HI=Object.prototype.propertyIsEnumerable,yc=(t,e,s)=>e in t?jI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_r=(t,e)=>{for(var s in e||(e={}))WI.call(e,s)&&yc(t,s,e[s]);if(zu)for(var s of zu(e))HI.call(e,s)&&yc(t,s,e[s]);return t},Sa=(t,e)=>FI(t,qI(e)),Oe=(t,e,s)=>yc(t,typeof e!="symbol"?e+"":e,s);class VI extends Lw{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Oe(this,"subscriptions",new Map),Oe(this,"topicMap",new BI),Oe(this,"events",new Un.EventEmitter),Oe(this,"name",kE),Oe(this,"version",PE),Oe(this,"pending",new Map),Oe(this,"cached",[]),Oe(this,"initialized",!1),Oe(this,"storagePrefix",ys),Oe(this,"subscribeTimeout",W.toMiliseconds(W.ONE_MINUTE)),Oe(this,"initialSubscribeTimeout",W.toMiliseconds(W.ONE_SECOND*15)),Oe(this,"clientId"),Oe(this,"batchSubscribeTopicsLimit",500),Oe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Oe(this,"subscribe",async(n,r)=>{var i;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}});try{const o=Oo(r),a={topic:n,relay:o,transportType:r?.transportType};(i=r?.internal)!=null&&i.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,r);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:r}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),Oe(this,"unsubscribe",async(n,r)=>{this.isInitialized(),typeof r?.id<"u"?await this.unsubscribeById(n,r.id,r):await this.unsubscribeByTopic(n,r)}),Oe(this,"isSubscribed",n=>new Promise(r=>{r(this.topicMap.topics.includes(n))})),Oe(this,"isKnownTopic",n=>new Promise(r=>{r(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(i=>i.topic===n))})),Oe(this,"on",(n,r)=>{this.events.on(n,r)}),Oe(this,"once",(n,r)=>{this.events.once(n,r)}),Oe(this,"off",(n,r)=>{this.events.off(n,r)}),Oe(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),Oe(this,"start",async()=>{await this.onConnect()}),Oe(this,"stop",async()=>{await this.onDisconnect()}),Oe(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Oe(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(r=>{n.push(r)}),await this.batchSubscribe(n)}),Oe(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(fr.pulse,async()=>{await this.checkPending()}),this.events.on(St.created,async n=>{const r=St.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()}),this.events.on(St.deleted,async n=>{const r=St.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()})}),this.relayer=e,this.logger=Rt(s,this.name),this.clientId=""}get context(){return It(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,s){let n=!1;try{n=this.getSubscription(e).topic===s}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,s){const n=this.topicMap.get(e);await Promise.all(n.map(async r=>await this.unsubscribeById(e,r,s)))}async unsubscribeById(e,s,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}});try{const r=Oo(n);await this.restartToComplete({topic:e,id:s,relay:r}),await this.rpcUnsubscribe(e,s,r);const i=Ue("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:n}})}catch(r){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(r),r}}async rpcSubscribe(e,s,n){var r,i;const o=await this.getSubscriptionId(e);if((r=n?.internal)!=null&&r.skipSubscribe)return o;(!n||n?.transportType===Pe.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const a={method:Xn(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{if(n?.transportType===Pe.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(d=>this.logger.warn(d))},W.toMiliseconds(W.ONE_SECOND)),o;const l=new Promise(async d=>{const h=p=>{p.topic===e&&(this.events.removeListener(St.created,h),d(p.id))};this.events.on(St.created,h);try{const p=await ps(new Promise((f,g)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w?.message),g(w)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(St.created,h),d(p)}catch{}}),u=await ps(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Me.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,n={method:Xn(s.protocol).batchSubscribe,params:{topics:e.map(r=>r.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await ps(new Promise(r=>{this.relayer.request(n).catch(i=>this.logger.warn(i)).then(r)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Me.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,n={method:Xn(s.protocol).batchFetchMessages,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let r;try{r=await await ps(new Promise((i,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Me.connection_stalled)}return r}rpcUnsubscribe(e,s,n){const r={method:Xn(n.protocol).unsubscribe,params:{topic:e,id:s}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r}),this.relayer.request(r)}onSubscribe(e,s){this.setSubscription(e,Sa(_r({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,_r({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,n){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,s){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:s}),this.addSubscription(e,s)}addSubscription(e,s){this.subscriptions.set(e,_r({},s)),this.topicMap.set(s.topic,e),this.events.emit(St.created,s)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const s=this.subscriptions.get(e);if(!s){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(St.deleted,Sa(_r({},n),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(St.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<s;n++){const r=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(r)}}this.events.emit(St.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(s=>{var n;return s.topic===((n=this.subscriptions.get(s.id))==null?void 0:n.topic)})){const{message:s}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async s=>Sa(_r({},s),{id:await this.getSubscriptionId(s.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const s=await this.rpcBatchFetchMessages(e);s&&s.messages&&(await yy(W.toMiliseconds(W.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(s.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return jt(e+await this.getClientId())}}var KI=Object.defineProperty,Gu=Object.getOwnPropertySymbols,zI=Object.prototype.hasOwnProperty,GI=Object.prototype.propertyIsEnumerable,bc=(t,e,s)=>e in t?KI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Yu=(t,e)=>{for(var s in e||(e={}))zI.call(e,s)&&bc(t,s,e[s]);if(Gu)for(var s of Gu(e))GI.call(e,s)&&bc(t,s,e[s]);return t},Ce=(t,e,s)=>bc(t,typeof e!="symbol"?e+"":e,s);class YI extends Uw{constructor(e){var s;super(e),Ce(this,"protocol","wc"),Ce(this,"version",2),Ce(this,"core"),Ce(this,"logger"),Ce(this,"events",new Un.EventEmitter),Ce(this,"provider"),Ce(this,"messages"),Ce(this,"subscriber"),Ce(this,"publisher"),Ce(this,"name",NE),Ce(this,"transportExplicitlyClosed",!1),Ce(this,"initialized",!1),Ce(this,"connectionAttemptInProgress",!1),Ce(this,"relayUrl"),Ce(this,"projectId"),Ce(this,"packageName"),Ce(this,"bundleId"),Ce(this,"hasExperiencedNetworkDisruption",!1),Ce(this,"pingTimeout"),Ce(this,"heartBeatTimeout",W.toMiliseconds(W.THIRTY_SECONDS+W.FIVE_SECONDS)),Ce(this,"reconnectTimeout"),Ce(this,"connectPromise"),Ce(this,"reconnectInProgress",!1),Ce(this,"requestsInFlight",[]),Ce(this,"connectTimeout",W.toMiliseconds(W.ONE_SECOND*15)),Ce(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const o=n.id||bn().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const a=`${o}:${((i=n.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),Ce(this,"resetPingTimeout",()=>{Io()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,i,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||o.call(i)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),Ce(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),Ce(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Me.connect)}),Ce(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Ce(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(Me.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Ce(this,"registerProviderListeners",()=>{this.provider.on($t.payload,this.onPayloadHandler),this.provider.on($t.connect,this.onConnectHandler),this.provider.on($t.disconnect,this.onDisconnectHandler),this.provider.on($t.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Qc({logger:(s=e.logger)!=null?s:AE,name:this.name}),this.messages=new kI(this.logger,e.core),this.subscriber=new VI(this,this.logger),this.publisher=new DI(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ap,sy()?this.packageName=Wl():ny()&&(this.bundleId=Wl()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return It(this.logger)}get connected(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,s,n;return((n=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,n){this.isInitialized(),await this.publisher.publish(e,s,n),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:Pe.relay},lo.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,s){var n,r,i;this.isInitialized(),(!(s!=null&&s.transportType)||s?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=s?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(r=s?.internal)==null?void 0:r.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(St.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(St.created,l)}),new Promise(async(u,d)=>{a=await this.subscriber.subscribe(e,Yu({internal:{throwOnFailedPublish:o}},s)).catch(h=>{o&&d(h)})||a,u()})]),a}async unsubscribe(e,s){this.isInitialized(),await this.subscriber.unsubscribe(e,s)}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}off(e,s){this.events.off(e,s)}removeListener(e,s){this.events.removeListener(e,s)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await ps(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(s,n)=>{await this.connect(e).then(s).catch(n).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Uu())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const s=e.sort((n,r)=>n.publishedAt-r.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const n of s)try{await this.onMessageEvent(n)}catch(r){this.logger.warn(r,"Error while processing batch message event: "+r?.message)}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:n}=e;if(!s.sessionExists){const r=je(W.FIVE_MINUTES),i={topic:n,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,i)}this.events.emit(Me.message,e),await this.recordMessageEvent(e,lo.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let s=1;for(;s<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${s}...`),await this.createProvider(),await new Promise(async(n,r)=>{const i=()=>{r(new Error("Connection interrupted while trying to connect"))};this.provider.once($t.disconnect,i),await ps(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{r(o)}).finally(()=>{this.provider.off($t.disconnect,i),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{r(new Error("Connection interrupted while trying to subscribe"))};this.provider.once($t.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off($t.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const r=n;this.logger.warn({},r.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${s}`);break}await new Promise(n=>setTimeout(n,W.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,n,r,i;if(Io())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null||i.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Pc(new Tf(cy({sdkVersion:pc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,s){const{topic:n,message:r}=e;await this.messages.set(n,r,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const r=this.messages.has(s,n);return r&&this.logger.warn(`Ignoring duplicate message: ${n}`),r}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Rc(e)){if(!e.method.endsWith(_E))return;const s=e.params,{topic:n,message:r,publishedAt:i,attestation:o}=s.data,a={topic:n,message:r,publishedAt:i,transportType:Pe.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Yu({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else xc(e)&&this.events.emit(Me.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,lo.inbound),this.events.emit(Me.message,e))}async acknowledgePayload(e){const s=Wr(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off($t.payload,this.onPayloadHandler),this.provider.off($t.connect,this.onConnectHandler),this.provider.off($t.disconnect,this.onDisconnectHandler),this.provider.off($t.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Uu();tE(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(fr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&rE())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Me.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},W.toMiliseconds(SE)))))}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function JI(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Ju(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Xu(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const XI="[object RegExp]",ZI="[object String]",QI="[object Number]",eA="[object Boolean]",Zu="[object Arguments]",tA="[object Symbol]",sA="[object Date]",nA="[object Map]",rA="[object Set]",iA="[object Array]",oA="[object Function]",aA="[object ArrayBuffer]",Ta="[object Object]",cA="[object Error]",lA="[object DataView]",uA="[object Uint8Array]",dA="[object Uint8ClampedArray]",hA="[object Uint16Array]",pA="[object Uint32Array]",fA="[object BigUint64Array]",gA="[object Int8Array]",mA="[object Int16Array]",wA="[object Int32Array]",yA="[object BigInt64Array]",bA="[object Float32Array]",vA="[object Float64Array]";function EA(){}function Qu(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function CA(t,e,s){return xr(t,e,void 0,void 0,void 0,void 0,s)}function xr(t,e,s,n,r,i,o){const a=o(t,e,s,n,r,i);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Fr(t,e,i,o)}return Fr(t,e,i,o)}function Fr(t,e,s,n){if(Object.is(t,e))return!0;let r=Xu(t),i=Xu(e);if(r===Zu&&(r=Ta),i===Zu&&(i=Ta),r!==i)return!1;switch(r){case ZI:return t.toString()===e.toString();case QI:{const c=t.valueOf(),l=e.valueOf();return JI(c,l)}case eA:case sA:case tA:return Object.is(t.valueOf(),e.valueOf());case XI:return t.source===e.source&&t.flags===e.flags;case oA:return t===e}s=s??new Map;const o=s.get(t),a=s.get(e);if(o!=null&&a!=null)return o===e;s.set(t,e),s.set(e,t);try{switch(r){case nA:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!xr(l,e.get(c),c,t,e,s,n))return!1;return!0}case rA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const d=c[u],h=l.findIndex(p=>xr(d,p,void 0,t,e,s,n));if(h===-1)return!1;l.splice(h,1)}return!0}case iA:case uA:case dA:case hA:case pA:case fA:case gA:case mA:case wA:case yA:case bA:case vA:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!xr(t[c],e[c],c,t,e,s,n))return!1;return!0}case aA:return t.byteLength!==e.byteLength?!1:Fr(new Uint8Array(t),new Uint8Array(e),s,n);case lA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Fr(new Uint8Array(t),new Uint8Array(e),s,n);case cA:return t.name===e.name&&t.message===e.message;case Ta:{if(!(Fr(t.constructor,e.constructor,s,n)||Qu(t)&&Qu(e)))return!1;const c=[...Object.keys(t),...Ju(t)],l=[...Object.keys(e),...Ju(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const d=c[u],h=t[d];if(!Object.hasOwn(e,d))return!1;const p=e[d];if(!xr(h,p,d,t,e,s,n))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function IA(t,e){return CA(t,e,EA)}var AA=Object.defineProperty,ed=Object.getOwnPropertySymbols,NA=Object.prototype.hasOwnProperty,_A=Object.prototype.propertyIsEnumerable,vc=(t,e,s)=>e in t?AA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,td=(t,e)=>{for(var s in e||(e={}))NA.call(e,s)&&vc(t,s,e[s]);if(ed)for(var s of ed(e))_A.call(e,s)&&vc(t,s,e[s]);return t},gt=(t,e,s)=>vc(t,typeof e!="symbol"?e+"":e,s);class jn extends Dw{constructor(e,s,n,r=ys,i=void 0){super(e,s,n,r),this.core=e,this.logger=s,this.name=n,gt(this,"map",new Map),gt(this,"version",TE),gt(this,"cached",[]),gt(this,"initialized",!1),gt(this,"getKey"),gt(this,"storagePrefix",ys),gt(this,"recentlyDeleted",[]),gt(this,"recentlyDeletedLimit",200),gt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!He(o)?this.map.set(this.getKey(o),o):R0(o)?this.map.set(o.id,o):x0(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),gt(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),gt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),gt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>IA(a[c],o[c]))):this.values)),gt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=td(td({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),gt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Rt(s,this.name),this.storagePrefix=r,this.getKey=i}get context(){return It(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const s=this.map.get(e);if(!s){if(this.recentlyDeleted.includes(e)){const{message:r}=q("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return s}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:s}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var SA=Object.defineProperty,TA=(t,e,s)=>e in t?SA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,fe=(t,e,s)=>TA(t,typeof e!="symbol"?e+"":e,s);class OA{constructor(e,s){this.core=e,this.logger=s,fe(this,"name",RE),fe(this,"version",xE),fe(this,"events",new kc),fe(this,"pairings"),fe(this,"initialized",!1),fe(this,"storagePrefix",ys),fe(this,"ignoredPayloadTypes",[xs]),fe(this,"registeredMethods",[]),fe(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),fe(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),fe(this,"create",async n=>{this.isInitialized();const r=uc(),i=await this.core.crypto.setSymKey(r),o=je(W.FIVE_MINUTES),a={protocol:Ip},c={topic:i,expiry:o,relay:a,active:!1,methods:n?.methods},l=_u({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:r,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(mn.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:n?.transportType,internal:n?.internal}),{topic:i,uri:l}}),fe(this,"pair",async n=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[cs.pairing_started]}});this.isValidPair(n,r);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Nu(n.uri);r.props.properties.topic=i,r.addTrace(cs.pairing_uri_validation_success),r.addTrace(cs.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(i)){if(u=this.pairings.get(i),r.addTrace(cs.existing_pairing),u.active)throw r.setError(Is.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);r.addTrace(cs.pairing_not_expired)}const d=c||je(W.FIVE_MINUTES),h={topic:i,relay:a,expiry:d,active:!1,methods:l};this.core.expirer.set(i,d),await this.pairings.set(i,h),r.addTrace(cs.store_new_pairing),n.activatePairing&&await this.activate({topic:i}),this.events.emit(mn.create,h),r.addTrace(cs.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),r.addTrace(cs.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(Is.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(p){throw r.setError(Is.subscribe_pairing_topic_failure),p}return r.addTrace(cs.subscribe_pairing_topic_success),h}),fe(this,"activate",async({topic:n})=>{this.isInitialized();const r=je(W.FIVE_MINUTES);this.core.expirer.set(n,r),await this.pairings.update(n,{active:!0,expiry:r})}),fe(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:r}=n;if(this.pairings.keys.includes(r)){const i=await this.sendRequest(r,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=gn();this.events.once(Ne("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}}),fe(this,"updateExpiry",async({topic:n,expiry:r})=>{this.isInitialized(),await this.pairings.update(n,{expiry:r})}),fe(this,"updateMetadata",async({topic:n,metadata:r})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:r})}),fe(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),fe(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:r}=n;this.pairings.keys.includes(r)&&(await this.sendRequest(r,"wc_pairingDelete",Ue("USER_DISCONNECTED")),await this.deletePairing(r))}),fe(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:r,relay:i,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(r);return _u({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:i,expiryTimestamp:o,methods:a})}),fe(this,"sendRequest",async(n,r,i)=>{const o=us(r,i),a=await this.core.crypto.encode(n,o),c=Ar[r].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),fe(this,"sendResult",async(n,r,i)=>{const o=Wr(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=Ar[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"sendError",async(n,r,i)=>{const o=Vd(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=Ar[c]?Ar[c].res:Ar.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),fe(this,"deletePairing",async(n,r)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Ue("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),r?Promise.resolve():this.core.expirer.del(n)])}),fe(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(r=>ds(r.expiry));await Promise.all(n.map(r=>this.deletePairing(r.topic)))}),fe(this,"onRelayEventRequest",async n=>{const{topic:r,payload:i}=n;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(r,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(r,i);default:return await this.onUnknownRpcMethodRequest(r,i)}}),fe(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i}=n,o=(await this.core.history.get(r,i.id)).request.method;return o==="wc_pairingPing"?this.onPairingPingResponse(r,i):this.onUnknownRpcMethodResponse(o)}),fe(this,"onPairingPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult(i,n,!0),this.events.emit(mn.ping,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),fe(this,"onPairingPingResponse",(n,r)=>{const{id:i}=r;setTimeout(()=>{Es(r)?this.events.emit(Ne("pairing_ping",i),{}):ls(r)&&this.events.emit(Ne("pairing_ping",i),{error:r.error})},500)}),fe(this,"onPairingDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(mn.delete,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),fe(this,"onUnknownRpcMethodRequest",async(n,r)=>{const{id:i,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Ue("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,n,a),this.logger.error(a)}catch(a){await this.sendError(i,n,a),this.logger.error(a)}}),fe(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(Ue("WC_METHOD_UNSUPPORTED",n))}),fe(this,"isValidPair",(n,r)=>{var i;if(!wt(n)){const{message:a}=q("MISSING_OR_INVALID",`pair() params: ${n}`);throw r.setError(Is.malformed_pairing_uri),new Error(a)}if(!P0(n.uri)){const{message:a}=q("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw r.setError(Is.malformed_pairing_uri),new Error(a)}const o=Nu(n?.uri);if(!((i=o?.relay)!=null&&i.protocol)){const{message:a}=q("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(Is.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=q("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(Is.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&W.toMiliseconds(o?.expiryTimestamp)<Date.now()){r.setError(Is.pairing_expired);const{message:a}=q("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),fe(this,"isValidPing",async n=>{if(!wt(n)){const{message:i}=q("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),fe(this,"isValidDisconnect",async n=>{if(!wt(n)){const{message:i}=q("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),fe(this,"isValidPairingTopic",async n=>{if(!Fe(n,!1)){const{message:r}=q("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(r)}if(!this.pairings.keys.includes(n)){const{message:r}=q("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(r)}if(ds(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:r}=q("EXPIRED",`pairing topic: ${n}`);throw new Error(r)}}),this.core=e,this.logger=Rt(s,this.name),this.pairings=new jn(this.core,this.logger,this.name,this.storagePrefix)}get context(){return It(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Me.message,async e=>{const{topic:s,message:n,transportType:r}=e;if(this.pairings.keys.includes(s)&&r!==Pe.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const i=await this.core.crypto.decode(s,n);Rc(i)?(this.core.history.set(s,i),await this.onRelayEventRequest({topic:s,payload:i})):xc(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:s,payload:i}),this.core.history.delete(s,i.id)),await this.core.relayer.messages.ack(s,n)}catch(i){this.logger.error(i)}})}registerExpirerEvents(){this.core.expirer.on(Bt.expired,async e=>{const{topic:s}=Eh(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(mn.expire,{topic:s}))})}}var kA=Object.defineProperty,PA=(t,e,s)=>e in t?kA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Je=(t,e,s)=>PA(t,typeof e!="symbol"?e+"":e,s);class RA extends Rw{constructor(e,s){super(e,s),this.core=e,this.logger=s,Je(this,"records",new Map),Je(this,"events",new Un.EventEmitter),Je(this,"name",$E),Je(this,"version",UE),Je(this,"cached",[]),Je(this,"initialized",!1),Je(this,"storagePrefix",ys),Je(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Je(this,"set",(n,r,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:r,chainId:i}),this.records.has(r.id))return;const o={id:r.id,topic:n,request:{method:r.method,params:r.params||null},chainId:i,expiry:je(W.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Gt.created,o)}),Je(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const r=await this.getRecord(n.id);typeof r.response>"u"&&(r.response=ls(n)?{error:n.error}:{result:n.result},this.records.set(r.id,r),this.persist(),this.events.emit(Gt.updated,r))}),Je(this,"get",async(n,r)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:r}),await this.getRecord(r))),Je(this,"delete",(n,r)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:r}),this.values.forEach(i=>{if(i.topic===n){if(typeof r<"u"&&i.id!==r)return;this.records.delete(i.id),this.events.emit(Gt.deleted,i)}}),this.persist()}),Je(this,"exists",async(n,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===n:!1)),Je(this,"on",(n,r)=>{this.events.on(n,r)}),Je(this,"once",(n,r)=>{this.events.once(n,r)}),Je(this,"off",(n,r)=>{this.events.off(n,r)}),Je(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=Rt(s,this.name)}get context(){return It(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(s=>{if(typeof s.response<"u")return;const n={topic:s.topic,request:us(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const s=this.records.get(e);if(!s){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Gt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Gt.created,e=>{const s=Gt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Gt.updated,e=>{const s=Gt.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Gt.deleted,e=>{const s=Gt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(fr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{W.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(Gt.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xA=Object.defineProperty,$A=(t,e,s)=>e in t?xA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,it=(t,e,s)=>$A(t,typeof e!="symbol"?e+"":e,s);class UA extends Mw{constructor(e,s){super(e,s),this.core=e,this.logger=s,it(this,"expirations",new Map),it(this,"events",new Un.EventEmitter),it(this,"name",DE),it(this,"version",LE),it(this,"cached",[]),it(this,"initialized",!1),it(this,"storagePrefix",ys),it(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),it(this,"has",n=>{try{const r=this.formatTarget(n);return typeof this.getExpiration(r)<"u"}catch{return!1}}),it(this,"set",(n,r)=>{this.isInitialized();const i=this.formatTarget(n),o={target:i,expiry:r};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(Bt.created,{target:i,expiration:o})}),it(this,"get",n=>{this.isInitialized();const r=this.formatTarget(n);return this.getExpiration(r)}),it(this,"del",n=>{if(this.isInitialized(),this.has(n)){const r=this.formatTarget(n),i=this.getExpiration(r);this.expirations.delete(r),this.events.emit(Bt.deleted,{target:r,expiration:i})}}),it(this,"on",(n,r)=>{this.events.on(n,r)}),it(this,"once",(n,r)=>{this.events.once(n,r)}),it(this,"off",(n,r)=>{this.events.off(n,r)}),it(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=Rt(s,this.name)}get context(){return It(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return ly(e);if(typeof e=="number")return uy(e);const{message:s}=q("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(s)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Bt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const s=this.expirations.get(e);if(!s){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return s}checkExpiry(e,s){const{expiry:n}=s;W.toMiliseconds(n)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(Bt.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(fr.pulse,()=>this.checkExpirations()),this.events.on(Bt.created,e=>{const s=Bt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Bt.expired,e=>{const s=Bt.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Bt.deleted,e=>{const s=Bt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var DA=Object.defineProperty,LA=(t,e,s)=>e in t?DA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Be=(t,e,s)=>LA(t,typeof e!="symbol"?e+"":e,s);class MA extends Bw{constructor(e,s,n){super(e,s,n),this.core=e,this.logger=s,this.store=n,Be(this,"name",ME),Be(this,"abortController"),Be(this,"isDevEnv"),Be(this,"verifyUrlV3",jE),Be(this,"storagePrefix",ys),Be(this,"version",Cp),Be(this,"publicKey"),Be(this,"fetchPromise"),Be(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&W.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Be(this,"register",async r=>{if(!gr()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=r,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=Us.getDocument(),u=this.startAbortTimer(W.ONE_SECOND*5),d=await new Promise((h,p)=>{const f=()=>{window.removeEventListener("message",w),l.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",f,{signal:this.abortController.signal});const w=C=>{if(C.data&&typeof C.data=="string")try{const v=JSON.parse(C.data);if(v.type==="verify_attestation"){if(Fa(v.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",w),h(v.attestation===null?"":v.attestation)}}catch(v){this.logger.warn(v)}};l.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(d,"jwt attestation"),d}catch(l){this.logger.warn(l)}return""}),Be(this,"resolve",async r=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=r;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(Fa(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(r?.verifyUrl);return this.fetchAttestation(o,c)}),Be(this,"fetchAttestation",async(r,i)=>{this.logger.debug(`resolving attestation: ${r} from url: ${i}`);const o=this.startAbortTimer(W.ONE_SECOND*5),a=await fetch(`${i}/attestation/${r}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),Be(this,"getVerifyUrl",r=>{let i=r||jr;return FE.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${jr}`),i=jr),i}),Be(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(W.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(r),await i.json()}catch(r){this.logger.warn(r)}}),Be(this,"persistPublicKey",async r=>{this.logger.debug(r,"persisting public key to local storage"),await this.store.setItem(this.storeKey,r),this.publicKey=r}),Be(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Be(this,"isValidJwtAttestation",async r=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(r,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(r,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Be(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Be(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const r=await this.fetchPromise;return this.fetchPromise=void 0,r}),Be(this,"validateAttestation",(r,i)=>{const o=r0(r,i.publicKey),a={hasExpired:W.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Rt(s,this.name),this.abortController=new AbortController,this.isDevEnv=Fc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return It(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),W.toMiliseconds(e))}}var BA=Object.defineProperty,jA=(t,e,s)=>e in t?BA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,sd=(t,e,s)=>jA(t,typeof e!="symbol"?e+"":e,s);class FA extends jw{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,sd(this,"context",qE),sd(this,"registerDeviceToken",async n=>{const{clientId:r,token:i,notificationType:o,enableEncrypted:a=!1}=n,c=`${WE}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:r,type:o,token:i,always_raw:a})})}),this.logger=Rt(s,this.context)}}var qA=Object.defineProperty,nd=Object.getOwnPropertySymbols,WA=Object.prototype.hasOwnProperty,HA=Object.prototype.propertyIsEnumerable,Ec=(t,e,s)=>e in t?qA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Sr=(t,e)=>{for(var s in e||(e={}))WA.call(e,s)&&Ec(t,s,e[s]);if(nd)for(var s of nd(e))HA.call(e,s)&&Ec(t,s,e[s]);return t},Ke=(t,e,s)=>Ec(t,typeof e!="symbol"?e+"":e,s);class VA extends Fw{constructor(e,s,n=!0){super(e,s,n),this.core=e,this.logger=s,Ke(this,"context",VE),Ke(this,"storagePrefix",ys),Ke(this,"storageVersion",HE),Ke(this,"events",new Map),Ke(this,"shouldPersist",!1),Ke(this,"init",async()=>{if(!Fc())try{const r={eventId:Vl(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:bh(this.core.relayer.protocol,this.core.relayer.version,pc)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),Ke(this,"createEvent",r=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=Vl(),u=this.core.projectId||"",d=Date.now(),h=Sr({eventId:l,timestamp:d,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),Ke(this,"getEvent",r=>{const{eventId:i,topic:o}=r;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Sr(Sr({},a),this.setMethods(a.eventId))}),Ke(this,"deleteEvent",r=>{const{eventId:i}=r;this.events.delete(i),this.shouldPersist=!0}),Ke(this,"setEventListeners",()=>{this.core.heartbeat.on(fr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{W.fromMiliseconds(Date.now())-W.fromMiliseconds(r.timestamp)>KE&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),Ke(this,"setMethods",r=>({addTrace:i=>this.addTrace(r,i),setError:i=>this.setError(r,i)})),Ke(this,"addTrace",(r,i)=>{const o=this.events.get(r);o&&(o.props.properties.trace.push(i),this.events.set(r,o),this.shouldPersist=!0)}),Ke(this,"setError",(r,i)=>{const o=this.events.get(r);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(r,o),this.shouldPersist=!0)}),Ke(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ke(this,"restore",async()=>{try{const r=await this.core.storage.getItem(this.storageKey)||[];if(!r.length)return;r.forEach(i=>{this.events.set(i.eventId,Sr(Sr({},i),this.setMethods(i.eventId)))})}catch(r){this.logger.warn(r)}}),Ke(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const r=[];for(const[i,o]of this.events)o.props.type&&r.push(o);if(r.length!==0)try{if((await this.sendEvent(r)).ok)for(const i of r)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}}),Ke(this,"sendEvent",async r=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${zE}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${pc}${i}`,{method:"POST",body:JSON.stringify(r)})}),Ke(this,"getAppDomain",()=>yh().url),this.logger=Rt(s,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var KA=Object.defineProperty,rd=Object.getOwnPropertySymbols,zA=Object.prototype.hasOwnProperty,GA=Object.prototype.propertyIsEnumerable,Cc=(t,e,s)=>e in t?KA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,id=(t,e)=>{for(var s in e||(e={}))zA.call(e,s)&&Cc(t,s,e[s]);if(rd)for(var s of rd(e))GA.call(e,s)&&Cc(t,s,e[s]);return t},ke=(t,e,s)=>Cc(t,typeof e!="symbol"?e+"":e,s);let YA=class Lp extends Tw{constructor(e){var s;super(e),ke(this,"protocol",Ep),ke(this,"version",Cp),ke(this,"name",hc),ke(this,"relayUrl"),ke(this,"projectId"),ke(this,"customStoragePrefix"),ke(this,"events",new Un.EventEmitter),ke(this,"logger"),ke(this,"heartbeat"),ke(this,"relayer"),ke(this,"crypto"),ke(this,"storage"),ke(this,"history"),ke(this,"expirer"),ke(this,"pairing"),ke(this,"verify"),ke(this,"echoClient"),ke(this,"linkModeSupportedApps"),ke(this,"eventClient"),ke(this,"initialized",!1),ke(this,"logChunkController"),ke(this,"on",(a,c)=>this.events.on(a,c)),ke(this,"once",(a,c)=>this.events.once(a,c)),ke(this,"off",(a,c)=>this.events.off(a,c)),ke(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ke(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Pe.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ap,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Ew({level:typeof e?.logger=="string"&&e.logger?e.logger:fE.logger,name:hc}),{logger:i,chunkLoggerController:o}=mh({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(s=this.logChunkController)!=null&&s.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Rt(i,this.name),this.heartbeat=new Sf,this.crypto=new CI(this,this.logger,e?.keychain),this.history=new RA(this,this.logger),this.expirer=new UA(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new tw(id(id({},gE),e?.storageOptions)),this.relayer=new YI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new OA(this,this.logger),this.verify=new MA(this,this.logger,this.storage),this.echoClient=new FA(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new VA(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new Lp(e);await s.initialize();const n=await s.crypto.getClientId();return await s.storage.setItem(OE,n),s}get context(){return It(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Lu,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(Lu)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${e}`,n=`${s}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[s]}catch(s){console.warn("Failed to get global WalletConnect core",s);return}}setGlobalCore(e){var s;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&pE.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const JA=YA,Mp="wc",Bp=2,jp="client",el=`${Mp}@${Bp}:${jp}:`,Oa={name:jp,logger:"error"},od="WALLETCONNECT_DEEPLINK_CHOICE",XA="proposal",ad="Proposal expired",ZA="session",Kn=W.SEVEN_DAYS,QA="engine",Xe={wc_sessionPropose:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1104},res:{ttl:W.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1106},res:{ttl:W.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:W.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1112},res:{ttl:W.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:W.ONE_DAY,prompt:!1,tag:1114},res:{ttl:W.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:W.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:W.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:W.FIVE_MINUTES,prompt:!1,tag:1119}}},ka={min:W.FIVE_MINUTES,max:W.SEVEN_DAYS},as={idle:"IDLE",active:"ACTIVE"},e1={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},t1="request",s1=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],n1="wc",r1="auth",i1="authKeys",o1="pairingTopics",a1="requests",Xo=`${n1}@${1.5}:${r1}:`,uo=`${Xo}:PUB_KEY`;var c1=Object.defineProperty,l1=Object.defineProperties,u1=Object.getOwnPropertyDescriptors,cd=Object.getOwnPropertySymbols,d1=Object.prototype.hasOwnProperty,h1=Object.prototype.propertyIsEnumerable,Ic=(t,e,s)=>e in t?c1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_e=(t,e)=>{for(var s in e||(e={}))d1.call(e,s)&&Ic(t,s,e[s]);if(cd)for(var s of cd(e))h1.call(e,s)&&Ic(t,s,e[s]);return t},ot=(t,e)=>l1(t,u1(e)),R=(t,e,s)=>Ic(t,typeof e!="symbol"?e+"":e,s);class p1 extends Vw{constructor(e){super(e),R(this,"name",QA),R(this,"events",new kc),R(this,"initialized",!1),R(this,"requestQueue",{state:as.idle,queue:[]}),R(this,"sessionRequestQueue",{state:as.idle,queue:[]}),R(this,"emittedSessionRequests",new by({limit:500})),R(this,"requestQueueDelay",W.ONE_SECOND),R(this,"expectedPairingMethodMap",new Map),R(this,"recentlyDeletedMap",new Map),R(this,"recentlyDeletedLimit",200),R(this,"relayMessageCache",[]),R(this,"pendingSessions",new Map),R(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Xe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},W.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=ot(_e({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=_0(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=n;let u=r,d,h=!1;try{if(u){const j=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=j.active}}catch(j){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),j}if(!u||!h){const{topic:j,uri:K}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});u=j,d=K}if(!u){const{message:j}=q("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(j)}const p=await this.client.core.crypto.generateKeyPair(),f=Xe.wc_sessionPropose.req.ttl||W.FIVE_MINUTES,g=je(f),w=ot(_e(_e({requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:Ip}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:Ls()}),C=Ne("session_connect",w.id),{reject:v,resolve:_,done:L}=gn(f,ad),B=({id:j})=>{j===w.id&&(this.client.events.off("proposal_expire",B),this.pendingSessions.delete(w.id),this.events.emit(C,{error:{message:ad,code:0}}))};return this.client.events.on("proposal_expire",B),this.events.once(C,({error:j,session:K})=>{this.client.events.off("proposal_expire",B),j?v(j):K&&_(K)}),await this.sendProposeSession({proposal:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:w.id}}}),await this.setProposal(w.id,w),{uri:d,approval:L}}),R(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(n){throw this.client.logger.error("pair() failed"),n}}),R(this,"approve",async s=>{var n,r,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=s?.id)==null?void 0:n.toString(),trace:[Yt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(k){throw o.setError(un.no_internet_connection),k}try{await this.isValidProposalId(s?.id)}catch(k){throw this.client.logger.error(`approve() -> proposal.get(${s?.id}) failed`),o.setError(un.proposal_not_found),k}try{await this.isValidApprove(s)}catch(k){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(un.session_approve_namespace_validation_failure),k}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=s,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:g,requiredNamespaces:w,optionalNamespaces:C}=p;let v=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});v||(v=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:Yt.session_approve_started,properties:{topic:f,trace:[Yt.session_approve_started,Yt.session_namespaces_validation_success]}}));const _=await this.client.core.crypto.generateKeyPair(),L=g.publicKey,B=await this.client.core.crypto.generateSharedKey(_,L),j=_e(_e(_e({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:_,metadata:this.client.metadata},expiry:je(Kn)},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),K=Pe.relay;v.addTrace(Yt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(B,{transportType:K,internal:{skipSubscribe:!0}})}catch(k){throw v.setError(un.subscribe_session_topic_failure),k}v.addTrace(Yt.subscribe_session_topic_success);const Y=ot(_e({},j),{topic:B,requiredNamespaces:w,optionalNamespaces:C,pairingTopic:f,acknowledged:!1,self:j.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:_,transportType:Pe.relay});await this.client.session.set(B,Y),v.addTrace(Yt.store_session);try{await this.sendApproveSession({sessionTopic:B,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:_},sessionSettleRequest:j,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),v.addTrace(Yt.session_approve_publish_success)}catch(k){throw this.client.logger.error(k),this.client.session.delete(B,Ue("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(B),k}return this.client.core.eventClient.deleteEvent({eventId:v.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(B,je(Kn)),{topic:B,acknowledged:()=>Promise.resolve(this.client.session.get(B))}}),R(this,"reject",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(s)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:r}=s;let i;try{i=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}i&&await this.sendError({id:n,topic:i,error:r,rpcOpts:Xe.wc_sessionPropose.reject}),await this.deleteProposal(n)}),R(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(d){throw this.client.logger.error("update() -> isValidUpdate() failed"),d}const{topic:n,namespaces:r}=s,{done:i,resolve:o,reject:a}=gn(),c=Ls(),l=bn().toString(),u=this.client.session.get(n).namespaces;return this.events.once(Ne("session_update",c),({error:d})=>{d?a(d):o()}),await this.client.session.update(n,{namespaces:r}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:r},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(d=>{this.client.logger.error(d),this.client.session.update(n,{namespaces:u}),a(d)}),{acknowledged:i}}),R(this,"extend",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(s)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=s,r=Ls(),{done:i,resolve:o,reject:a}=gn();return this.events.once(Ne("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,je(Kn)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),R(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:r,topic:i,expiry:o=Xe.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(i);a?.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const c=Ls(),l=bn().toString(),{done:u,resolve:d,reject:h}=gn(o,"Request expired. Please try again.");this.events.once(Ne("session_request",c),({error:w,result:C})=>{w?h(w):d(C)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:{request:ot(_e({},r),{expiryTimestamp:je(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(w=>h(w)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),await u();const g={request:ot(_e({},r),{expiryTimestamp:je(o)}),chainId:n};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(C=>h(C)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),w()}),new Promise(async w=>{var C;if(!((C=a.sessionConfig)!=null&&C.disableDeepLink)){const v=await fy(this.client.core.storage,od);await dy({id:c,topic:i,wcDeepLink:v})}w()}),u()]).then(w=>w[2])}),R(this,"respond",async s=>{var n,r;this.isInitialized();const i=this.client.core.eventClient.createEvent({properties:{topic:s?.topic||((r=(n=s?.response)==null?void 0:n.id)==null?void 0:r.toString()),trace:[Yt.session_request_response_started]}});try{await this.isValidRespond(s)}catch(d){throw i.addTrace(d?.message),i.setError(un.session_request_response_validation_failure),d}i.addTrace(Yt.session_request_response_validation_success);const{topic:o,response:a}=s,{id:c}=a,l=this.client.session.get(o);l.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{i.addTrace(Yt.session_request_response_publish_started),Es(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):ls(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(s)}catch(d){throw i.addTrace(d?.message),i.setError(un.session_request_response_publish_failure),d}}),R(this,"ping",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(s)}catch(r){throw this.client.logger.error("ping() -> isValidPing() failed"),r}const{topic:n}=s;if(this.client.session.keys.includes(n)){const r=Ls(),i=bn().toString(),{done:o,resolve:a,reject:c}=gn();this.events.once(Ne("session_ping",r),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:r,relayRpcId:i}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:n}))}),R(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:n,event:r,chainId:i}=s,o=bn().toString(),a=Ls();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:r,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:n}=s;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:Ue("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:r}=q("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(r)}}),R(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(n=>O0(n,s)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(this,"authenticate",async(s,n)=>{var r;this.isInitialized(),this.isValidAuthenticate(s);const i=n&&this.client.core.linkModeSupportedApps.includes(n)&&((r=this.client.metadata.redirect)==null?void 0:r.linkMode),o=i?Pe.link_mode:Pe.relay;o===Pe.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:d,type:h,exp:p,nbf:f,methods:g=[],expiry:w}=s,C=[...s.resources||[]],{topic:v,uri:_}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:v,uri:_}});const L=await this.client.core.crypto.generateKeyPair(),B=co(L);if(await Promise.all([this.client.auth.authKeys.set(uo,{responseTopic:B,publicKey:L}),this.client.auth.pairingTopics.set(B,{topic:B,pairingTopic:v})]),await this.client.core.relayer.subscribe(B,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${v}`),g.length>0){const{namespace:E}=Rs(a[0]);let O=kb(E,"request",g);ao(C)&&(O=Rb(O,C.pop())),C.push(O)}const j=w&&w>Xe.wc_sessionAuthenticate.req.ttl?w:Xe.wc_sessionAuthenticate.req.ttl,K={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:d,iat:new Date().toISOString(),exp:p,nbf:f,resources:C},requester:{publicKey:L,metadata:this.client.metadata},expiryTimestamp:je(j)},Y={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},k={requiredNamespaces:{},optionalNamespaces:Y,relays:[{protocol:"irn"}],pairingTopic:v,proposer:{publicKey:L,metadata:this.client.metadata},expiryTimestamp:je(Xe.wc_sessionPropose.req.ttl),id:Ls()},{done:te,resolve:ne,reject:P}=gn(j,"Request expired"),I=Ls(),A=Ne("session_connect",k.id),y=Ne("session_request",I),b=async({error:E,session:O})=>{this.events.off(y,N),E?P(E):O&&ne({session:O})},N=async E=>{var O,F,$;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),E.error){const le=Ue("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return E.error.code===le.code?void 0:(this.events.off(A,b),P(E.error.message))}await this.deleteProposal(k.id),this.events.off(A,b);const{cacaos:re,responder:U}=E.result,J=[],oe=[];for(const le of re){await su({cacao:le,projectId:this.client.core.projectId})||(this.client.logger.error(le,"Signature verification failed"),P(Ue("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:he}=le,Le=ao(he.resources),dt=[ec(he.iss)],rs=No(he.iss);if(Le){const Kt=nu(Le),ki=ru(Le);J.push(...Kt),dt.push(...ki)}for(const Kt of dt)oe.push(`${Kt}:${rs}`)}const ce=await this.client.core.crypto.generateSharedKey(L,U.publicKey);let Ie;J.length>0&&(Ie={topic:ce,acknowledged:!0,self:{publicKey:L,metadata:this.client.metadata},peer:U,controller:U.publicKey,expiry:je(Kn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:v,namespaces:ku([...new Set(J)],[...new Set(oe)]),transportType:o},await this.client.core.relayer.subscribe(ce,{transportType:o}),await this.client.session.set(ce,Ie),v&&await this.client.core.pairing.updateMetadata({topic:v,metadata:U.metadata}),Ie=this.client.session.get(ce)),(O=this.client.metadata.redirect)!=null&&O.linkMode&&(F=U.metadata.redirect)!=null&&F.linkMode&&($=U.metadata.redirect)!=null&&$.universal&&n&&(this.client.core.addLinkModeSupportedApp(U.metadata.redirect.universal),this.client.session.update(ce,{transportType:Pe.link_mode})),ne({auths:re,session:Ie})};this.events.once(A,b),this.events.once(y,N);let T;try{if(i){const E=us("wc_sessionAuthenticate",K,I);this.client.core.history.set(v,E);const O=await this.client.core.crypto.encode("",E,{type:Si,encoding:Xs});T=Gi(n,v,O)}else await Promise.all([this.sendRequest({topic:v,method:"wc_sessionAuthenticate",params:K,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:v,method:"wc_sessionPropose",params:k,expiry:Xe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:k.id})])}catch(E){throw this.events.off(A,b),this.events.off(y,N),E}return await this.setProposal(k.id,k),await this.setAuthRequest(I,{request:ot(_e({},K),{verifyContext:{}}),pairingTopic:v,transportType:o}),{uri:T??_,response:te}}),R(this,"approveSessionAuthenticate",async s=>{const{id:n,auths:r}=s,i=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[dn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw i.setError(Nr.no_internet_connection),w}const o=this.getPendingAuthRequest(n);if(!o)throw i.setError(Nr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||Pe.relay;a===Pe.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=co(c),d={type:xs,receiverPublicKey:c,senderPublicKey:l},h=[],p=[];for(const w of r){if(!await su({cacao:w,projectId:this.client.core.projectId})){i.setError(Nr.invalid_cacao);const B=Ue("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:u,error:B,encodeOpts:d}),new Error(B.message)}i.addTrace(dn.cacaos_verified);const{p:C}=w,v=ao(C.resources),_=[ec(C.iss)],L=No(C.iss);if(v){const B=nu(v),j=ru(v);h.push(...B),_.push(...j)}for(const B of _)p.push(`${B}:${L}`)}const f=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(dn.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:f,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:je(Kn),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:ku([...new Set(h)],[...new Set(p)]),transportType:a},i.addTrace(dn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(w){throw i.setError(Nr.subscribe_authenticated_session_topic_failure),w}i.addTrace(dn.subscribe_authenticated_session_topic_success),await this.client.session.set(f,g),i.addTrace(dn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(dn.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:n,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:d,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw i.setError(Nr.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:i.eventId}),{session:g}}),R(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:n,reason:r}=s,i=this.getPendingAuthRequest(n);if(!i)throw new Error(`Could not find pending auth request with id ${n}`);i.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=co(o),l={type:xs,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:r,encodeOpts:l,rpcOpts:Xe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),R(this,"formatAuthMessage",s=>{this.isInitialized();const{request:n,iss:r}=s;return Lh(n,r)}),R(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const s=this.relayMessageCache.shift();s&&await this.onRelayMessage(s)}catch(s){this.client.logger.error(s)}},50)}),R(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const n=this.client.core.pairing.pairings.get(s.pairingTopic),r=this.client.core.pairing.pairings.getAll().filter(i=>{var o,a;return((o=i.peerMetadata)==null?void 0:o.url)&&((a=i.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&i.topic&&i.topic!==n.topic});if(r.length===0)return;this.client.logger.info(`Cleaning up ${r.length} duplicate pairing(s)`),await Promise.all(r.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),R(this,"deleteSession",async s=>{var n;const{topic:r,expirerHasDeleted:i=!1,emitEvent:o=!0,id:a=0}=s,{self:c}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,Ue("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),i||this.client.core.expirer.del(r),this.client.core.storage.removeItem(od).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===r&&this.deletePendingSessionRequest(l.id,Ue("USER_DISCONNECTED"))}),r===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=as.idle),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),R(this,"deleteProposal",async(s,n)=>{if(n)try{const r=this.client.proposal.get(s);this.client.core.eventClient.getEvent({topic:r.pairingTopic})?.setError(un.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,Ue("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),R(this,"deletePendingSessionRequest",async(s,n,r=!1)=>{await Promise.all([this.client.pendingRequest.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==s),r&&(this.sessionRequestQueue.state=as.idle,this.client.events.emit("session_request_expire",{id:s}))}),R(this,"deletePendingAuthRequest",async(s,n,r=!1)=>{await Promise.all([this.client.auth.requests.delete(s,n),r?Promise.resolve():this.client.core.expirer.del(s)])}),R(this,"setExpiry",async(s,n)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,n),await this.client.session.update(s,{expiry:n}))}),R(this,"setProposal",async(s,n)=>{this.client.core.expirer.set(s,je(Xe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,n)}),R(this,"setAuthRequest",async(s,n)=>{const{request:r,pairingTopic:i,transportType:o=Pe.relay}=n;this.client.core.expirer.set(s,r.expiryTimestamp),await this.client.auth.requests.set(s,{authPayload:r.authPayload,requester:r.requester,expiryTimestamp:r.expiryTimestamp,id:s,pairingTopic:i,verifyContext:r.verifyContext,transportType:o})}),R(this,"setPendingSessionRequest",async s=>{const{id:n,topic:r,params:i,verifyContext:o}=s,a=i.request.expiryTimestamp||je(Xe.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:r,params:i,verifyContext:o})}),R(this,"sendRequest",async s=>{const{topic:n,method:r,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:d,publishOpts:h={}}=s,p=us(r,i,c);let f;const g=!!u;try{const v=g?Xs:bt;f=await this.client.core.crypto.encode(n,p,{encoding:v})}catch(v){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),v}let w;if(s1.includes(r)){const v=jt(JSON.stringify(p)),_=jt(f);w=await this.client.core.verify.register({id:_,decryptedId:v})}const C=_e(_e({},Xe[r].req),h);if(C.attestation=w,o&&(C.ttl=o),a&&(C.id=a),this.client.core.history.set(n,p),g){const v=Gi(u,n,f);await global.Linking.openURL(v,this.client.name)}else C.tvf=ot(_e({},d),{correlationId:p.id}),l?(C.internal=ot(_e({},C.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,f,C)):this.client.core.relayer.publish(n,f,C).catch(v=>this.client.logger.error(v));return p.id}),R(this,"sendProposeSession",async s=>{const{proposal:n,publishOpts:r}=s,i=us("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,i);const o=await this.client.core.crypto.encode(n.pairingTopic,i,{encoding:bt}),a=jt(JSON.stringify(i)),c=jt(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:o},opts:ot(_e({},r),{publishMethod:"wc_proposeSession",attestation:l})})}),R(this,"sendApproveSession",async s=>{const{sessionTopic:n,pairingProposalResponse:r,proposal:i,sessionSettleRequest:o,publishOpts:a}=s,c=Wr(i.id,r),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:bt}),u=us("wc_sessionSettle",o,a?.id),d=await this.client.core.crypto.encode(n,u,{encoding:bt});this.client.core.history.set(n,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:d},opts:ot(_e({},a),{publishMethod:"wc_approveSession"})})}),R(this,"sendResult",async s=>{const{id:n,topic:r,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=Wr(n,i);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=d?Xs:bt;u=await this.client.core.crypto.encode(r,l,ot(_e({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),f}let h,p;try{h=await this.client.core.history.get(r,n);const f=h.request;try{p=this.getTVFParams(n,f.params,i)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${n}) failed`),f}if(d){const f=Gi(c,r,u);await global.Linking.openURL(f,this.client.name)}else{const f=h.request.method,g=Xe[f].res;g.tvf=ot(_e({},p),{correlationId:n}),o?(g.internal=ot(_e({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,u,g)):this.client.core.relayer.publish(r,u,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(l)}),R(this,"sendError",async s=>{const{id:n,topic:r,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=Vd(n,i);let u;const d=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=d?Xs:bt;u=await this.client.core.crypto.encode(r,l,ot(_e({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${r} failed`),p}let h;try{h=await this.client.core.history.get(r,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${r}, ${n}) failed`),p}if(d){const p=Gi(c,r,u);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,f=a||Xe[p].res;this.client.core.relayer.publish(r,u,f)}await this.client.core.history.resolve(l)}),R(this,"cleanup",async()=>{const s=[],n=[];this.client.session.getAll().forEach(r=>{let i=!1;ds(r.expiry)&&(i=!0),this.client.core.crypto.keychain.has(r.topic)||(i=!0),i&&s.push(r.topic)}),this.client.proposal.getAll().forEach(r=>{ds(r.expiryTimestamp)&&n.push(r.id)}),await Promise.all([...s.map(r=>this.deleteSession({topic:r})),...n.map(r=>this.deleteProposal(r))])}),R(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),R(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===as.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=as.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=as.idle}),R(this,"processRequest",async s=>{const{topic:n,payload:r,attestation:i,transportType:o,encryptedId:a}=s,c=r.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:r,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,r);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,r);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,r);case"wc_sessionPing":return await this.onSessionPingRequest(n,r);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,r);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,r);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:r,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),R(this,"onRelayEventResponse",async s=>{const{topic:n,payload:r,transportType:i}=s,o=(await this.client.core.history.get(n,r.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,r,i);case"wc_sessionSettle":return this.onSessionSettleResponse(n,r);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,r);case"wc_sessionExtend":return this.onSessionExtendResponse(n,r);case"wc_sessionPing":return this.onSessionPingResponse(n,r);case"wc_sessionRequest":return this.onSessionRequestResponse(n,r);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,r);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),R(this,"onRelayEventUnknownPayload",s=>{const{topic:n}=s,{message:r}=q("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),R(this,"shouldIgnorePairingRequest",s=>{const{topic:n,requestMethod:r}=s,i=this.expectedPairingMethodMap.get(n);return!i||i.includes(r)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),R(this,"onSessionProposeRequest",async s=>{const{topic:n,payload:r,attestation:i,encryptedId:o}=s,{params:a,id:c}=r;try{const l=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(Is.proposal_listener_not_found)),this.isValidConnect(_e({},r.params));const u=a.expiryTimestamp||je(Xe.wc_sessionPropose.req.ttl),d=_e({id:c,pairingTopic:n,expiryTimestamp:u,attestation:i,encryptedId:o},a);await this.setProposal(c,d);const h=await this.getVerifyContext({attestationId:i,hash:jt(JSON.stringify(r)),encryptedId:o,metadata:d.proposer.metadata});l?.addTrace(cs.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:d,verifyContext:h})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:Xe.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),R(this,"onSessionProposeResponse",async(s,n,r)=>{const{id:i}=n;if(Es(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(i,{sessionTopic:u,pairingTopic:s,proposalId:i,publicKey:c});const d=await this.client.core.relayer.subscribe(u,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:d}),await this.client.core.pairing.activate({topic:s})}else if(ls(n)){await this.deleteProposal(i);const o=Ne("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),R(this,"onSessionSettleRequest",async(s,n)=>{const{id:r,params:i}=n;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:d,sessionConfig:h}=n.params,p=[...this.pendingSessions.values()].find(w=>w.sessionTopic===s);if(!p)return this.client.logger.error(`Pending session not found for topic ${s}`);const f=this.client.proposal.get(p.proposalId),g=ot(_e(_e(_e({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),d&&{scopedProperties:d}),h&&{sessionConfig:h}),{transportType:Pe.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(Ne("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:n.id,topic:s,result:!0})}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(s,n)=>{const{id:r}=n;Es(n)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(Ne("session_approve",r),{})):ls(n)&&(await this.client.session.delete(s,Ue("USER_DISCONNECTED")),this.events.emit(Ne("session_approve",r),{error:n.error}))}),R(this,"onSessionUpdateRequest",async(s,n)=>{const{params:r,id:i}=n;try{const o=`${s}_session_update`,a=Ir.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:s,error:Ue("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(_e({topic:s},r));try{Ir.set(o,i),await this.client.session.update(s,{namespaces:r.namespaces}),await this.sendResult({id:i,topic:s,result:!0})}catch(c){throw Ir.delete(o),c}this.client.events.emit("session_update",{id:i,topic:s,params:r})}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),R(this,"isRequestOutOfSync",(s,n)=>n.toString().slice(0,-3)<s.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(s,n)=>{const{id:r}=n,i=Ne("session_update",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);Es(n)?this.events.emit(Ne("session_update",r),{}):ls(n)&&this.events.emit(Ne("session_update",r),{error:n.error})}),R(this,"onSessionExtendRequest",async(s,n)=>{const{id:r}=n;try{this.isValidExtend({topic:s}),await this.setExpiry(s,je(Kn)),await this.sendResult({id:r,topic:s,result:!0}),this.client.events.emit("session_extend",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),R(this,"onSessionExtendResponse",(s,n)=>{const{id:r}=n,i=Ne("session_extend",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);Es(n)?this.events.emit(Ne("session_extend",r),{}):ls(n)&&this.events.emit(Ne("session_extend",r),{error:n.error})}),R(this,"onSessionPingRequest",async(s,n)=>{const{id:r}=n;try{this.isValidPing({topic:s}),await this.sendResult({id:r,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:r,topic:s})}catch(i){await this.sendError({id:r,topic:s,error:i}),this.client.logger.error(i)}}),R(this,"onSessionPingResponse",(s,n)=>{const{id:r}=n,i=Ne("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);Es(n)?this.events.emit(Ne("session_ping",r),{}):ls(n)&&this.events.emit(Ne("session_ping",r),{error:n.error})},500)}),R(this,"onSessionDeleteRequest",async(s,n)=>{const{id:r}=n;try{this.isValidDisconnect({topic:s,reason:n.params}),await Promise.all([new Promise(i=>{this.client.core.relayer.once(Me.publish,async()=>{i(await this.deleteSession({topic:s,id:r}))})}),this.sendResult({id:r,topic:s,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:Ue("USER_DISCONNECTED")})]).catch(i=>this.client.logger.error(i))}catch(i){this.client.logger.error(i)}}),R(this,"onSessionRequest",async s=>{var n,r,i;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=s,{id:d,params:h}=a;try{await this.isValidRequest(_e({topic:o},h));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:jt(JSON.stringify(us("wc_sessionRequest",h,d))),encryptedId:l,metadata:p.peer.metadata,transportType:u}),g={id:d,topic:o,params:h,verifyContext:f};await this.setPendingSessionRequest(g),u===Pe.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((r=p.peer.metadata.redirect)==null?void 0:r.universal),(i=this.client.signConfig)!=null&&i.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(p){await this.sendError({id:d,topic:o,error:p}),this.client.logger.error(p)}}),R(this,"onSessionRequestResponse",(s,n)=>{const{id:r}=n,i=Ne("session_request",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);Es(n)?this.events.emit(Ne("session_request",r),{result:n.result}):ls(n)&&this.events.emit(Ne("session_request",r),{error:n.error})}),R(this,"onSessionEventRequest",async(s,n)=>{const{id:r,params:i}=n;try{const o=`${s}_session_event_${i.event.name}`,a=Ir.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(_e({topic:s},i)),this.client.events.emit("session_event",{id:r,topic:s,params:i}),Ir.set(o,r)}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(s,n)=>{const{id:r}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:n}),Es(n)?this.events.emit(Ne("session_request",r),{result:n.result}):ls(n)&&this.events.emit(Ne("session_request",r),{error:n.error})}),R(this,"onSessionAuthenticateRequest",async s=>{var n;const{topic:r,payload:i,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:u,expiryTimestamp:d}=i.params,h=await this.getVerifyContext({attestationId:o,hash:jt(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:r,id:i.id,authPayload:u,verifyContext:h,expiryTimestamp:d};await this.setAuthRequest(i.id,{request:p,pairingTopic:r,transportType:c}),c===Pe.link_mode&&(n=l.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:i.params,id:i.id,verifyContext:h})}catch(l){this.client.logger.error(l);const u=i.params.requester.publicKey,d=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(i.params.requester.metadata,c),p={type:xs,receiverPublicKey:u,senderPublicKey:d};await this.sendError({id:i.id,topic:r,error:l,encodeOpts:p,rpcOpts:Xe.wc_sessionAuthenticate.autoReject,appLink:h})}}),R(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),R(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=as.idle,this.processSessionRequestQueue()},W.toMiliseconds(this.requestQueueDelay))}),R(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:n})=>{const r=this.client.core.history.pending;r.length>0&&r.filter(i=>i.topic===s&&i.request.method==="wc_sessionRequest").forEach(i=>{const o=i.request.id,a=Ne("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Ne("session_request",i.request.id),{error:n})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===as.active){this.client.logger.info("session request queue is already active.");return}const s=this.sessionRequestQueue.queue[0];if(!s){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(s)}catch(n){this.client.logger.error(n)}}),R(this,"emitSessionRequest",s=>{if(this.emittedSessionRequests.has(s.id)){this.client.logger.warn({id:s.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${s.id}`);return}this.sessionRequestQueue.state=as.active,this.emittedSessionRequests.add(s.id),this.client.events.emit("session_request",s)}),R(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const n=this.client.proposal.getAll().find(r=>r.pairingTopic===s.topic);n&&this.onSessionProposeRequest({topic:s.topic,payload:us("wc_sessionPropose",ot(_e({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),R(this,"isValidConnect",async s=>{if(!wt(s)){const{message:l}=q("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:n,requiredNamespaces:r,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=s;if(He(n)||await this.isValidPairingTopic(n),!F0(c)){const{message:l}=q("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(r&&!He(r)&&ws(r)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(r,"requiredNamespaces")}if(i&&!He(i)&&ws(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),o&&!He(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!He(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(r||{}).concat(Object.keys(i||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),R(this,"validateNamespaces",(s,n)=>{const r=j0(s,"connect()",n);if(r)throw new Error(r.message)}),R(this,"isValidApprove",async s=>{if(!wt(s))throw new Error(q("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:n,namespaces:r,relayProtocol:i,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),l=Aa(r,"approve()");if(l)throw new Error(l.message);const u=xu(c.requiredNamespaces,r,"approve()");if(u)throw new Error(u.message);if(!Fe(i,!0)){const{message:d}=q("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(d)}if(o&&!He(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!He(a)){this.validateSessionProps(a,"scopedProperties");const d=new Set(Object.keys(r));if(!Object.keys(a).every(h=>d.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(d).join(", ")}`)}}),R(this,"isValidReject",async s=>{if(!wt(s)){const{message:i}=q("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(i)}const{id:n,reason:r}=s;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!W0(r)){const{message:i}=q("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(i)}}),R(this,"isValidSessionSettleRequest",s=>{if(!wt(s)){const{message:l}=q("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:n,controller:r,namespaces:i,expiry:o}=s;if(!vp(n)){const{message:l}=q("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=$0(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Aa(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ds(o)){const{message:l}=q("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),R(this,"isValidUpdate",async s=>{if(!wt(s)){const{message:c}=q("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:n,namespaces:r}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const i=this.client.session.get(n),o=Aa(r,"update()");if(o)throw new Error(o.message);const a=xu(i.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async s=>{if(!wt(s)){const{message:r}=q("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(r)}const{topic:n}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),R(this,"isValidRequest",async s=>{if(!wt(s)){const{message:c}=q("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:n,request:r,chainId:i,expiry:o}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!Ru(a,i)){const{message:c}=q("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!H0(r)){const{message:c}=q("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!z0(a,i,r.method)){const{message:c}=q("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}if(o&&!X0(o,ka)){const{message:c}=q("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${ka.min} and ${ka.max}`);throw new Error(c)}}),R(this,"isValidRespond",async s=>{var n;if(!wt(s)){const{message:a}=q("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(a)}const{topic:r,response:i}=s;try{await this.isValidSessionTopic(r)}catch(a){throw(n=s?.response)!=null&&n.id&&this.cleanupAfterResponse(s),a}if(!V0(i)){const{message:a}=q("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(a)}const o=this.client.pendingRequest.get(i.id);if(o.topic!==r){const{message:a}=q("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${i.id}, expected topic: ${o.topic}, received topic: ${r}`);throw new Error(a)}}),R(this,"isValidPing",async s=>{if(!wt(s)){const{message:r}=q("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidEmit",async s=>{if(!wt(s)){const{message:a}=q("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}const{topic:n,event:r,chainId:i}=s;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!Ru(o,i)){const{message:a}=q("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!K0(r)){const{message:a}=q("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!G0(o,i,r.name)){const{message:a}=q("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async s=>{if(!wt(s)){const{message:r}=q("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidAuthenticate",s=>{const{chains:n,uri:r,domain:i,nonce:o}=s;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!Fe(r,!1))throw new Error("uri is required parameter");if(!Fe(i,!1))throw new Error("domain is required parameter");if(!Fe(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Rs(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Rs(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),R(this,"getVerifyContext",async s=>{const{attestationId:n,hash:r,encryptedId:i,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||jr,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Pe.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:n,hash:r,encryptedId:i,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),R(this,"validateSessionProps",(s,n)=>{Object.values(s).forEach((r,i)=>{if(r==null){const{message:o}=q("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${r} for key ${Object.keys(s)[i]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",s=>{const n=this.client.auth.requests.get(s);return typeof n=="object"?n:void 0}),R(this,"addToRecentlyDeleted",(s,n)=>{if(this.recentlyDeletedMap.set(s,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let r=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(r++>=i)break;this.recentlyDeletedMap.delete(o)}}}),R(this,"checkRecentlyDeleted",s=>{const n=this.recentlyDeletedMap.get(s);if(n){const{message:r}=q("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${s}`);throw new Error(r)}}),R(this,"isLinkModeEnabled",(s,n)=>{var r,i,o,a,c,l,u,d,h;return!s||n!==Pe.link_mode?!1:((i=(r=this.client.metadata)==null?void 0:r.redirect)==null?void 0:i.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=s?.redirect)==null?void 0:u.universal)!==void 0&&((d=s?.redirect)==null?void 0:d.universal)!==""&&((h=s?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(s,n)=>{var r;return this.isLinkModeEnabled(s,n)?(r=s?.redirect)==null?void 0:r.universal:void 0}),R(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const n=Hl(s,"topic")||"",r=decodeURIComponent(Hl(s,"wc_ev")||""),i=this.client.session.keys.includes(n);i&&this.client.session.update(n,{transportType:Pe.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:r,sessionExists:i})}),R(this,"registerLinkModeListeners",async()=>{var s;if(Fc()||on()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await n.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}}),R(this,"getTVFParams",(s,n,r)=>{var i,o,a;if(!((i=n.request)!=null&&i.method))return{};const c={correlationId:s,rpcMethods:[n.request.method],chainId:n.chainId};try{const l=this.extractTxHashesFromResult(n.request,r);c.txHashes=l,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(o=n.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),R(this,"isValidContractData",s=>{var n;if(!s)return!1;try{const r=s?.data||((n=s?.[0])==null?void 0:n.data);if(!r.startsWith("0x"))return!1;const i=r.slice(2);return/^[0-9a-fA-F]*$/.test(i)?i.length%2===0:!1}catch{}return!1}),R(this,"extractTxHashesFromResult",(s,n)=>{var r;try{if(!n)return[];const i=s.method,o=e1[i];if(i==="sui_signTransaction")return[pb(n.transactionBytes)];if(i==="near_signTransaction")return[Zl(n)];if(i==="near_signTransactions")return n.map(c=>Zl(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(r=n.tx_json)==null?void 0:r.hash];if(i==="polkadot_signTransaction")return[hE({transaction:s.params.transactionPayload,signature:n.signature})];if(i==="algo_signTxn")return $s(n)?n.map(c=>Ql(c)):[Ql(n)];if(i==="cosmos_signDirect")return[gb(n)];if(i==="wallet_sendCalls")return mb(n);if(typeof n=="string")return[n];const a=n[o.key];if($s(a))return i==="solana_signAllTransactions"?a.map(c=>hb(c)):a;if(typeof a=="string")return[a]}catch(i){this.client.logger.warn(i,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,s=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,r]of Object.entries(s))for(const i of r)try{await this.onProviderMessageEvent({topic:n,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${i}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Me.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:n,attestation:r,transportType:i}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(uo)?this.client.auth.authKeys.get(uo):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,n,{receiverPublicKey:o,encoding:i===Pe.link_mode?Xs:bt});Rc(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:r,transportType:i,encryptedId:jt(n)})):xc(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:i}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:i}),await this.client.core.relayer.messages.ack(s,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Bt.expired,async e=>{const{topic:s,id:n}=Eh(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,q("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,q("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(mn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(mn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Fe(e,!1)){const{message:s}=q("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(s)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:s}=q("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(ds(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=q("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!Fe(e,!1)){const{message:s}=q("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(s)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:s}=q("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(ds(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=q("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=q("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(s)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(Fe(e,!1)){const{message:s}=q("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=q("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!q0(e)){const{message:s}=q("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=q("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(ds(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=q("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class f1 extends jn{constructor(e,s){super(e,s,XA,el),this.core=e,this.logger=s}}let g1=class extends jn{constructor(e,s){super(e,s,ZA,el),this.core=e,this.logger=s}};class m1 extends jn{constructor(e,s){super(e,s,t1,el,n=>n.id),this.core=e,this.logger=s}}class w1 extends jn{constructor(e,s){super(e,s,i1,Xo,()=>uo),this.core=e,this.logger=s}}class y1 extends jn{constructor(e,s){super(e,s,o1,Xo),this.core=e,this.logger=s}}class b1 extends jn{constructor(e,s){super(e,s,a1,Xo,n=>n.id),this.core=e,this.logger=s}}var v1=Object.defineProperty,E1=(t,e,s)=>e in t?v1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Pa=(t,e,s)=>E1(t,typeof e!="symbol"?e+"":e,s);class C1{constructor(e,s){this.core=e,this.logger=s,Pa(this,"authKeys"),Pa(this,"pairingTopics"),Pa(this,"requests"),this.authKeys=new w1(this.core,this.logger),this.pairingTopics=new y1(this.core,this.logger),this.requests=new b1(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var I1=Object.defineProperty,A1=(t,e,s)=>e in t?I1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ge=(t,e,s)=>A1(t,typeof e!="symbol"?e+"":e,s);let N1=class Fp extends Hw{constructor(e){super(e),ge(this,"protocol",Mp),ge(this,"version",Bp),ge(this,"name",Oa.name),ge(this,"metadata"),ge(this,"core"),ge(this,"logger"),ge(this,"events",new Un.EventEmitter),ge(this,"engine"),ge(this,"session"),ge(this,"proposal"),ge(this,"pendingRequest"),ge(this,"auth"),ge(this,"signConfig"),ge(this,"on",(n,r)=>this.events.on(n,r)),ge(this,"once",(n,r)=>this.events.once(n,r)),ge(this,"off",(n,r)=>this.events.off(n,r)),ge(this,"removeListener",(n,r)=>this.events.removeListener(n,r)),ge(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),ge(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"update",async n=>{try{return await this.engine.update(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"request",async n=>{try{return await this.engine.request(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"find",n=>{try{return this.engine.find(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),ge(this,"authenticate",async(n,r)=>{try{return await this.engine.authenticate(n,r)}catch(i){throw this.logger.error(i.message),i}}),ge(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),ge(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),this.name=e?.name||Oa.name,this.metadata=iy(e?.metadata),this.signConfig=e?.signConfig;const s=Qc({logger:e?.logger||Oa.logger,name:this.name});this.logger=s,this.core=e?.core||new JA(e),this.session=new g1(this.core,this.logger),this.proposal=new f1(this.core,this.logger),this.pendingRequest=new m1(this.core,this.logger),this.engine=new p1(this),this.auth=new C1(this.core,this.logger)}static async init(e){const s=new Fp(e);return await s.initialize(),s}get context(){return It(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const _1=N1;function tl(t){return t==null||typeof t!="object"&&typeof t!="function"}function qp(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Wp(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const S1="[object RegExp]",Hp="[object String]",Vp="[object Number]",Kp="[object Boolean]",zp="[object Arguments]",T1="[object Symbol]",O1="[object Date]",k1="[object Map]",P1="[object Set]",R1="[object Array]",x1="[object ArrayBuffer]",$1="[object Object]",U1="[object DataView]",D1="[object Uint8Array]",L1="[object Uint8ClampedArray]",M1="[object Uint16Array]",B1="[object Uint32Array]",j1="[object Int8Array]",F1="[object Int16Array]",q1="[object Int32Array]",W1="[object Float32Array]",H1="[object Float64Array]";function sl(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function V1(t,e){return Qn(t,void 0,t,new Map,e)}function Qn(t,e,s,n=new Map,r=void 0){const i=r?.(t,e,s,n);if(i!=null)return i;if(tl(t))return t;if(n.has(t))return n.get(t);if(Array.isArray(t)){const o=new Array(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=Qn(t[a],a,s,n,r);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;n.set(t,o);for(const[a,c]of t)o.set(a,Qn(c,a,s,n,r));return o}if(t instanceof Set){const o=new Set;n.set(t,o);for(const a of t)o.add(Qn(a,void 0,s,n,r));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(sl(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=Qn(t[a],a,s,n,r);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return n.set(t,o),wn(o,t,s,n,r),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return n.set(t,o),wn(o,t,s,n,r),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),wn(o,t,s,n,r),o}if(t instanceof Error){const o=new t.constructor;return n.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,wn(o,t,s,n,r),o}if(typeof t=="object"&&K1(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),wn(o,t,s,n,r),o}return t}function wn(t,e,s=t,n,r){const i=[...Object.keys(e),...qp(e)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Qn(e[a],a,s,n,r))}}function K1(t){switch(Wp(t)){case zp:case R1:case x1:case U1:case Kp:case O1:case W1:case H1:case j1:case F1:case q1:case k1:case Vp:case $1:case S1:case P1:case Hp:case T1:case D1:case L1:case M1:case B1:return!0;default:return!1}}function z1(t,e){return V1(t,(s,n,r,i)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Vp:case Hp:case Kp:{const o=new t.constructor(t?.valueOf());return wn(o,t),o}case zp:{const o={};return wn(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function ld(t){return z1(t)}function ud(t){return t!==null&&typeof t=="object"&&Wp(t)==="[object Arguments]"}function dd(t){return typeof t=="object"&&t!==null}function G1(){}function Y1(t){return sl(t)}function J1(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const s=t[Symbol.toStringTag];return s==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${s}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function X1(t){if(tl(t))return t;if(Array.isArray(t)||sl(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),s=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new s(t);if(t instanceof RegExp){const n=new s(t);return n.lastIndex=t.lastIndex,n}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const n=new s(t.message);return n.stack=t.stack,n.name=t.name,n.cause=t.cause,n}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const n=Object.create(e);return Object.assign(n,t)}return t}function Z1(t,...e){const s=e.slice(0,-1),n=e[e.length-1];let r=t;for(let i=0;i<s.length;i++){const o=s[i];r=Ac(r,o,n,new Map)}return r}function Ac(t,e,s,n){if(tl(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return X1(n.get(e));if(n.set(e,t),Array.isArray(e)){e=e.slice();for(let i=0;i<e.length;i++)e[i]=e[i]??void 0}const r=[...Object.keys(e),...qp(e)];for(let i=0;i<r.length;i++){const o=r[i];let a=e[o],c=t[o];if(ud(a)&&(a={...a}),ud(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=ld(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],d=Reflect.ownKeys(c);for(let h=0;h<d.length;h++){const p=d[h];u[p]=c[p]}c=u}else c=[];const l=s(c,a,o,t,e,n);l!=null?t[o]=l:Array.isArray(a)||dd(c)&&dd(a)?t[o]=Ac(c,a,s,n):c==null&&J1(a)?t[o]=Ac({},a,s,n):c==null&&Y1(a)?t[o]=ld(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function Q1(t,...e){return Z1(t,...e,G1)}const hd="error",eN="wss://relay.walletconnect.org",tN="wc",Gp="universal_provider",Yi=`${tN}@2:${Gp}:`,Yp="https://rpc.walletconnect.org/v1/",Jp="generic",sN=`${Yp}bundler`,sr="call_status",nN=86400,nl={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var rN=Object.defineProperty,iN=Object.defineProperties,oN=Object.getOwnPropertyDescriptors,pd=Object.getOwnPropertySymbols,aN=Object.prototype.hasOwnProperty,cN=Object.prototype.propertyIsEnumerable,fd=(t,e,s)=>e in t?rN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ji=(t,e)=>{for(var s in e||(e={}))aN.call(e,s)&&fd(t,s,e[s]);if(pd)for(var s of pd(e))cN.call(e,s)&&fd(t,s,e[s]);return t},lN=(t,e)=>iN(t,oN(e));function Xp(t,e,s){var n;const r=Rs(t);return((n=e.rpcMap)==null?void 0:n[r.reference])||`${Yp}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function uN(t){return t.includes(":")?t.split(":")[1]:t}function Zp(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function dN(t,e){const s=Object.keys(e.namespaces).filter(r=>r.includes(t));if(!s.length)return[];const n=[];return s.forEach(r=>{const i=e.namespaces[r].accounts;n.push(...i)}),n}function gd(t){return Object.fromEntries(Object.entries(t).filter(([e,s])=>{var n,r;return((n=s?.chains)==null?void 0:n.length)&&((r=s?.chains)==null?void 0:r.length)>0}))}function Xi(t={},e={}){const s=gd(md(t)),n=gd(md(e));return Q1(s,n)}function md(t){var e,s,n,r,i;const o={};if(!ws(t))return o;for(const[a,c]of Object.entries(t)){const l=Yo(a)?[a]:c.chains,u=c.methods||[],d=c.events||[],h=c.rpcMap||{},p=Zn(a);o[p]=lN(Ji(Ji({},o[p]),c),{chains:ms(l,(e=o[p])==null?void 0:e.chains),methods:ms(u,(s=o[p])==null?void 0:s.methods),events:ms(d,(n=o[p])==null?void 0:n.events)}),(ws(h)||ws(((r=o[p])==null?void 0:r.rpcMap)||{}))&&(o[p].rpcMap=Ji(Ji({},h),(i=o[p])==null?void 0:i.rpcMap))}return o}function wd(t){return t.includes(":")?t.split(":")[2]:t}function yd(t){const e={};for(const[s,n]of Object.entries(t)){const r=n.methods||[],i=n.events||[],o=n.accounts||[],a=Yo(s)?[s]:n.chains?n.chains:Zp(n.accounts);e[s]={chains:a,methods:r,events:i,accounts:o}}return e}function Ra(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function hN(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const Qp={},nr=t=>Qp[t],xa=(t,e)=>{Qp[t]=e};var pN=Object.defineProperty,bd=Object.getOwnPropertySymbols,fN=Object.prototype.hasOwnProperty,gN=Object.prototype.propertyIsEnumerable,vd=(t,e,s)=>e in t?pN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ed=(t,e)=>{for(var s in e||(e={}))fN.call(e,s)&&vd(t,s,e[s]);if(bd)for(var s of bd(e))gN.call(e,s)&&vd(t,s,e[s]);return t};const Cd="eip155",mN=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],wN=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,$a=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Id=t=>Object.keys(t).filter(e=>mN.includes(e)).reduce((e,s)=>(e[s]=yN(t[s]),e),{}),yN=t=>typeof t=="string"&&hN(t)?JSON.parse(t):t,bN=(t,e,s)=>{const{sessionProperties:n={},scopedProperties:r={}}=t,i={};if(!ws(r)&&!ws(n))return;const o=Id(n);for(const a of s){const c=wN(a);if(!c)continue;i[$a(c)]=o;const l=r?.[`${Cd}:${c}`];if(l){const u=l?.[`${Cd}:${c}:${e}`];i[$a(c)]=Ed(Ed({},i[$a(c)]),Id(u||l))}}for(const[a,c]of Object.entries(i))Object.keys(c).length===0&&delete i[a];return Object.keys(i).length>0?i:void 0};var vN=Object.defineProperty,EN=(t,e,s)=>e in t?vN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,CN=(t,e,s)=>EN(t,e+"",s);let Ua;class rl{constructor(e){CN(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,s){return await this.storage.setItem(e,s)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return Ua||(Ua=new rl(e)),Ua}}var IN=Object.defineProperty,AN=Object.defineProperties,NN=Object.getOwnPropertyDescriptors,Ad=Object.getOwnPropertySymbols,_N=Object.prototype.hasOwnProperty,SN=Object.prototype.propertyIsEnumerable,Nd=(t,e,s)=>e in t?IN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,TN=(t,e)=>{for(var s in e||(e={}))_N.call(e,s)&&Nd(t,s,e[s]);if(Ad)for(var s of Ad(e))SN.call(e,s)&&Nd(t,s,e[s]);return t},ON=(t,e)=>AN(t,NN(e));async function kN(t,e){const s=Rs(t.result.capabilities.caip345.caip2),n=t.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(n.map(d=>PN(s.reference,d,e))),i=r.filter(d=>d.status==="fulfilled").map(d=>d.value).filter(d=>d);r.filter(d=>d.status==="rejected").forEach(d=>console.warn("Failed to fetch transaction receipt:",d.reason));const o=!i.length||i.some(d=>!d),a=i.every(d=>d?.status==="0x1"),c=i.every(d=>d?.status==="0x0"),l=i.some(d=>d?.status==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:i,status:u}}async function PN(t,e,s){return await s(parseInt(t)).request(us("eth_getTransactionReceipt",[e]))}async function RN({sendCalls:t,storage:e}){const s=await e.getItem(sr);await e.setItem(sr,ON(TN({},s),{[t.result.id]:{request:t.request,result:t.result,expiry:je(nN)}}))}async function xN({resultId:t,storage:e}){const s=await e.getItem(sr);if(s){delete s[t],await e.setItem(sr,s);for(const n in s)ds(s[n].expiry)&&delete s[n];await e.setItem(sr,s)}}async function $N({resultId:t,storage:e}){const s=await e.getItem(sr),n=s?.[t];if(n&&!ds(n.expiry))return n;await xN({resultId:t,storage:e})}var UN=Object.defineProperty,DN=Object.defineProperties,LN=Object.getOwnPropertyDescriptors,_d=Object.getOwnPropertySymbols,MN=Object.prototype.hasOwnProperty,BN=Object.prototype.propertyIsEnumerable,Nc=(t,e,s)=>e in t?UN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Da=(t,e)=>{for(var s in e||(e={}))MN.call(e,s)&&Nc(t,s,e[s]);if(_d)for(var s of _d(e))BN.call(e,s)&&Nc(t,s,e[s]);return t},La=(t,e)=>DN(t,LN(e)),hn=(t,e,s)=>Nc(t,typeof e!="symbol"?e+"":e,s);class jN{constructor(e){hn(this,"name","eip155"),hn(this,"client"),hn(this,"chainId"),hn(this,"namespace"),hn(this,"httpProviders"),hn(this,"events"),hn(this,"storage"),this.namespace=e.namespace,this.events=nr("events"),this.client=nr("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=rl.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s);const n=this.chainId;this.chainId=parseInt(e),this.events.emit(nl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,s){const n=s||Xp(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Pc(new Kd(n,nr("disableProviderPing")))}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var n;const r=parseInt(uN(s));e[r]=this.createHttpProvider(r,(n=this.namespace.rpcMap)==null?void 0:n[s])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}getHttpProvider(e){const s=e||this.chainId;return this.httpProviders[s]||(this.httpProviders=La(Da({},this.httpProviders),{[s]:this.createHttpProvider(s)}),this.httpProviders[s])}async handleSwitchChain(e){var s,n;let r=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";r=r.startsWith("0x")?r:`0x${r}`;const i=parseInt(r,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:r}]},chainId:(n=this.namespace.chains)==null?void 0:n[0]}),this.setDefaultChain(`${i}`);else throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,n,r,i,o;const a=(n=(s=e.request)==null?void 0:s.params)==null?void 0:n[0],c=((i=(r=e.request)==null?void 0:r.params)==null?void 0:i[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l?.sessionProperties)==null?void 0:o.capabilities)||{},d=`${a}${c.join(",")}`,h=u?.[d];if(h)return h;let p;try{p=bN(l,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(p)return p;const f=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:La(Da({},l.sessionProperties||{}),{capabilities:La(Da({},u||{}),{[d]:f})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return f}async getCallStatus(e){var s,n,r;const i=this.client.session.get(e.topic),o=(s=i.sessionProperties)==null?void 0:s.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(n=i.sessionProperties)==null?void 0:n.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await $N({resultId:(r=e.request.params)==null?void 0:r[0],storage:this.storage});if(c)try{return await kN(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,s){var n;const r=new URL(e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(us("eth_getUserOperationReceipt",[(n=s.request.params)==null?void 0:n[0]]))});if(!i.ok)throw new Error(`Failed to fetch user operation receipt - ${i.status}`);return await i.json()}getBundlerUrl(e,s){return`${sN}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}async sendCalls(e){var s,n,r;const i=await this.client.request(e),o=(s=e.request.params)==null?void 0:s[0],a=i?.id,c=i?.capabilities||{},l=(n=c?.caip345)==null?void 0:n.caip2,u=(r=c?.caip345)==null?void 0:r.transactionHashes;return!a||!l||!(u!=null&&u.length)||await RN({sendCalls:{request:o,result:i},storage:this.storage}),i}}var FN=Object.defineProperty,qN=(t,e,s)=>e in t?FN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,zn=(t,e,s)=>qN(t,typeof e!="symbol"?e+"":e,s);class WN{constructor(e){zn(this,"name",Jp),zn(this,"client"),zn(this,"httpProviders"),zn(this,"events"),zn(this,"namespace"),zn(this,"chainId"),this.namespace=e.namespace,this.events=nr("events"),this.client=nr("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s);const n=this.chainId;this.chainId=e,this.events.emit(nl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${n}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return Rs(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){var e,s;const n={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(r=>{var i,o;const a=Rs(r),c=(o=(i=this.namespace)==null?void 0:i.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];n[a.reference]=this.createHttpProvider(r,c)}),n}getHttpProvider(e){const s=Rs(e).reference,n=this.httpProviders[s];if(typeof n>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return n}setHttpProvider(e,s){const n=this.createHttpProvider(e,s);n&&(this.httpProviders[e]=n)}createHttpProvider(e,s){const n=s||Xp(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Pc(new Kd(n,nr("disableProviderPing")))}}var HN=Object.defineProperty,VN=Object.defineProperties,KN=Object.getOwnPropertyDescriptors,Sd=Object.getOwnPropertySymbols,zN=Object.prototype.hasOwnProperty,GN=Object.prototype.propertyIsEnumerable,_c=(t,e,s)=>e in t?HN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Tr=(t,e)=>{for(var s in e||(e={}))zN.call(e,s)&&_c(t,s,e[s]);if(Sd)for(var s of Sd(e))GN.call(e,s)&&_c(t,s,e[s]);return t},Zi=(t,e)=>VN(t,KN(e)),Dt=(t,e,s)=>_c(t,typeof e!="symbol"?e+"":e,s);let YN=class ef{constructor(e){Dt(this,"client"),Dt(this,"namespaces"),Dt(this,"optionalNamespaces"),Dt(this,"sessionProperties"),Dt(this,"scopedProperties"),Dt(this,"events",new kc),Dt(this,"rpcProviders",{}),Dt(this,"session"),Dt(this,"providerOpts"),Dt(this,"logger"),Dt(this,"uri"),Dt(this,"disableProviderPing",!1);var s,n;this.providerOpts=e,this.logger=Qc({logger:(s=e.logger)!=null?s:hd,name:(n=this.providerOpts.name)!=null?n:Gp}),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const s=new ef(e);return await s.initialize(),s}async request(e,s,n){const[r,i]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(r).request({request:Tr({},e),chainId:`${r}:${i}`,topic:this.session.topic,expiry:n})}sendAsync(e,s,n,r){const i=new Date().getTime();this.request(e,n,r).then(o=>s(null,Wr(i,o))).catch(o=>s(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:Ue("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,s){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:n,response:r}=await this.client.authenticate(e,s);n&&(this.uri=n,this.events.emit("display_uri",n));const i=await r();if(this.session=i.session,this.session){const o=yd(this.session.namespaces);this.namespaces=Xi(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return i}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}removeListener(e,s){this.events.removeListener(e,s)}off(e,s){this.events.off(e,s)}get isWalletConnect(){return!0}async pair(e){const{uri:s,approval:n}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});s&&(this.uri=s,this.events.emit("display_uri",s));const r=await n();this.session=r;const i=yd(r.namespaces);return this.namespaces=Xi(this.namespaces,i),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,s){try{if(!this.session)return;const[n,r]=this.validateChain(e);this.getProvider(n).setDefaultChain(r,s)}catch(n){if(!/Please call connect/.test(n.message))throw n}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(!$s(s))return;for(const n of s)e.deletePairings?this.client.core.expirer.set(n.topic,0):await this.client.core.relayer.subscriber.unsubscribe(n.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}catch(s){this.logger.warn(s,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,s;if(this.client=this.providerOpts.client||await _1.init({core:this.providerOpts.core,logger:this.providerOpts.logger||hd,relayUrl:this.providerOpts.relayUrl||eN,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(n){throw this.logger.error(n,"Failed to get session"),new Error(`The provided session: ${(s=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:s.topic} doesn't exist in the Sign client`)}else{const n=this.client.session.getAll();this.session=n[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(s=>Zn(s)))];xa("client",this.client),xa("events",this.events),xa("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const n=dN(s,this.session);if(n?.length===0)return;const r=Zp(n),i=Xi(this.namespaces,this.optionalNamespaces),o=Zi(Tr({},i[s]),{accounts:n,chains:r});s==="eip155"?this.rpcProviders[s]=new jN({namespace:o}):this.rpcProviders[s]=new WN({namespace:o})})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var s;const{topic:n}=e;n===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:n,topic:r}=e;if(r!==((s=this.session)==null?void 0:s.topic))return;const{event:i}=n;if(i.name==="accountsChanged"){const o=i.data;o&&$s(o)&&this.events.emit("accountsChanged",o.map(wd))}else if(i.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=Zn(o),l=Ra(o)!==Ra(a)?`${c}:${Ra(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(i.name,i.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var n,r;if(e!==((n=this.session)==null?void 0:n.topic))return;const{namespaces:i}=s,o=(r=this.client)==null?void 0:r.session.get(e);this.session=Zi(Tr({},o),{namespaces:i}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:s})}),this.client.on("session_delete",async e=>{var s;e.topic===((s=this.session)==null?void 0:s.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Zi(Tr({},Ue("USER_DISCONNECTED")),{data:e.topic})))}),this.on(nl.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(Zi(Tr({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Jp]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var s;this.getProvider(e).updateNamespace((s=this.session)==null?void 0:s.namespaces[e])})}setNamespaces(e){const{namespaces:s={},optionalNamespaces:n={},sessionProperties:r,scopedProperties:i}=e;this.optionalNamespaces=Xi(s,n),this.sessionProperties=r,this.scopedProperties=i}validateChain(e){const[s,n]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,n];if(s&&!Object.keys(this.namespaces||{}).map(o=>Zn(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&n)return[s,n];const r=Zn(Object.keys(this.namespaces)[0]),i=this.rpcProviders[r].getDefaultChain();return[r,i]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:s,internal:n=!1}){if(!this.namespaces)return;const[r,i]=this.validateChain(e);i&&(this.updateNamespaceChain(r,i),n?(this.events.emit("chainChanged",i),this.emitAccountsChangedOnChainChange({namespace:r,currentCaipChainId:e,previousCaipChainId:s})):this.getProvider(r).setDefaultChain(i),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:s,previousCaipChainId:n}){var r,i;try{if(n===s)return;const o=(i=(r=this.session)==null?void 0:r.namespaces[e])==null?void 0:i.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${s}:`)).map(wd);if(!$s(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,s){if(!this.namespaces)return;const n=this.namespaces[e]?e:`${e}:${s}`,r={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[n]?this.namespaces[n]&&(this.namespaces[n].defaultChain=s):this.namespaces[n]=r}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,s){var n;const r=((n=this.session)==null?void 0:n.topic)||"";await this.client.core.storage.setItem(`${Yi}/${e}${r}`,s)}async getFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${Yi}/${e}${n}`)}async deleteFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${Yi}/${e}${n}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const s=await this.client.core.storage.getKeys();for(const n of s)n.startsWith(Yi)&&await this.client.core.storage.removeItem(n)}catch(s){this.logger.warn(s,"Failed to cleanup storage")}}};const As={EIP155:D.CHAIN.EVM,CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH"},JN={NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200","00000008819873e925422c1ff0f99f7c":"b3406e4a-bbfc-44fb-e3a6-89673c78b700"}},mi={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,n])=>{e[`${As.EIP155}:${s}`]=n}),e},isLowerCaseMatch(t,e){return t?.toLowerCase()===e?.toLowerCase()},getActiveNamespaceConnectedToAuth(){const t=m.state.activeChain;return D.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(e=>M.getConnectorId(e)===D.CONNECTOR_ID.AUTH&&e===t)},withRetry({conditionFn:t,intervalMs:e,maxRetries:s}){let n=0;return new Promise(r=>{async function i(){return n+=1,await t()?r(!0):n>=s?r(!1):(setTimeout(i,e),null)}i()})},userChainIdToChainNamespace(t){if(typeof t=="number")return D.CHAIN.EVM;const[e]=t.split(":");return e},getOtherAuthNamespaces(t){return t?D.AUTH_CONNECTOR_SUPPORTED_CHAINS.filter(n=>n!==t):[]},getConnectorStorageInfo(t,e){const n=x.getConnections()[e]??[];return{hasDisconnected:x.isConnectorDisconnected(t,e),hasConnected:n.some(r=>mi.isLowerCaseMatch(r.connectorId,t))}}},XN=new AbortController,Lt={EmbeddedWalletAbortController:XN,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"ORIGIN_NOT_ALLOWED"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{code:"APKT001",displayMessage:"Network Not Found",debugMessage:"The specified network is not recognized. Please ensure it is included in the `networks` array of your `createAppKit` configuration."},ORIGIN_NOT_ALLOWED:{code:"APKT002",displayMessage:"Invalid App Configuration",debugMessage:()=>`The origin ${kr()?window.origin:"unknown"} is not in your allow list. Please update your allowed domains at https://dashboard.reown.com. [PID: ${S.state.projectId}]`},IFRAME_LOAD_FAILED:{code:"APKT003",displayMessage:"Network Error: Wallet Load Failed",debugMessage:()=>"Failed to load the embedded wallet. This may be due to network issues or server downtime. Please check your network connection and try again shortly. Contact support if the issue persists."},IFRAME_REQUEST_TIMEOUT:{code:"APKT004",displayMessage:"Wallet Request Timeout",debugMessage:()=>"The request to the embedded wallet timed out. Please check your network connection and try again shortly. Contact support if the issue persists."},UNVERIFIED_DOMAIN:{code:"APKT005",displayMessage:"Unverified Domain",debugMessage:()=>"Embedded wallet load failed. Ensure your domain is verified in https://dashboard.reown.com."},JWT_TOKEN_NOT_VALID:{code:"APKT006",displayMessage:"Session Expired",debugMessage:"Your session is invalid or expired. Please check your system’s date and time settings, then reconnect."},INVALID_PROJECT_ID:{code:"APKT007",displayMessage:"Invalid Project ID",debugMessage:"The specified project ID is invalid. Please visit https://dashboard.reown.com to obtain a valid project ID."},PROJECT_ID_NOT_CONFIGURED:{code:"APKT008",displayMessage:"Project ID Missing",debugMessage:"No project ID is configured. You can create and configure a project ID at https://dashboard.reown.com."},SERVER_ERROR_APP_CONFIGURATION:{code:"APKT009",displayMessage:"Server Error",debugMessage:t=>`Unable to fetch App Configuration. ${t}. Please check your network connection and try again shortly. Contact support if the issue persists.`},RATE_LIMITED_APP_CONFIGURATION:{code:"APKT010",displayMessage:"Rate Limited",debugMessage:"You have been rate limited while retrieving App Configuration. Please wait a few minutes and try again. Contact support if the issue persists."}},ALERT_WARNINGS:{LOCAL_CONFIGURATION_IGNORED:{debugMessage:t=>`[Reown Config Notice] ${t}`},INACTIVE_NAMESPACE_NOT_CONNECTED:{code:"APKTW001",displayMessage:"Inactive Namespace Not Connected",debugMessage:(t,e)=>`An error occurred while connecting an inactive namespace ${t}: "${e}"`},INVALID_EMAIL:{code:"APKTW002",displayMessage:"Invalid Email Address",debugMessage:"Please enter a valid email address"}}},tf={TOKEN_ADDRESSES_BY_SYMBOL:{USDC:{8453:km.asset,84532:Pm.asset}},getTokenSymbolByAddress(t){if(!t)return;const[e]=Object.entries(tf.TOKEN_ADDRESSES_BY_SYMBOL).find(([s,n])=>Object.values(n).includes(t))??[];return e}},ZN={level:"info"},il=1e3*1024;var QN=Object.defineProperty,e_=(t,e,s)=>e in t?QN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Zs=(t,e,s)=>e_(t,typeof e!="symbol"?e+"":e,s);let t_=class{constructor(e){Zs(this,"nodeValue"),Zs(this,"sizeInBytes"),Zs(this,"next"),this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Td=class{constructor(e){Zs(this,"lengthInNodes"),Zs(this,"sizeInBytes"),Zs(this,"head"),Zs(this,"tail"),Zs(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const s=new t_(e);if(s.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${s.size}`);for(;this.size+s.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=s),this.tail=s):(this.head=s,this.tail=s),this.lengthInNodes++,this.sizeInBytes+=s.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let s=this.head;for(;s!==null;)e.push(s.value),s=s.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const s=e.value;return e=e.next,{done:!1,value:s}}}}};var s_=Object.defineProperty,n_=(t,e,s)=>e in t?s_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qi=(t,e,s)=>n_(t,typeof e!="symbol"?e+"":e,s);let sf=class{constructor(e,s=il){Qi(this,"logs"),Qi(this,"level"),Qi(this,"levelValue"),Qi(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=es.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=s,this.logs=new Td(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,s){s===es.levels.values.error?console.error(e):s===es.levels.values.warn?console.warn(e):s===es.levels.values.debug?console.debug(e):s===es.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(On({timestamp:new Date().toISOString(),log:e}));const s=typeof e=="string"?JSON.parse(e).level:e.level;s>=this.levelValue&&this.forwardToConsole(e,s)}getLogs(){return this.logs}clearLogs(){this.logs=new Td(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const s=this.getLogArray();return s.push(On({extraMetadata:e})),new Blob(s,{type:"application/json"})}};var r_=Object.defineProperty,i_=(t,e,s)=>e in t?r_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,o_=(t,e,s)=>i_(t,e+"",s);let a_=class{constructor(e,s=il){o_(this,"baseChunkLogger"),this.baseChunkLogger=new sf(e,s)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const s=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=s,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(s)}};var c_=Object.defineProperty,l_=(t,e,s)=>e in t?c_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,u_=(t,e,s)=>l_(t,e+"",s);class d_{constructor(e,s=il){u_(this,"baseChunkLogger"),this.baseChunkLogger=new sf(e,s)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var h_=Object.defineProperty,p_=Object.defineProperties,f_=Object.getOwnPropertyDescriptors,Od=Object.getOwnPropertySymbols,g_=Object.prototype.hasOwnProperty,m_=Object.prototype.propertyIsEnumerable,kd=(t,e,s)=>e in t?h_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Po=(t,e)=>{for(var s in e||(e={}))g_.call(e,s)&&kd(t,s,e[s]);if(Od)for(var s of Od(e))m_.call(e,s)&&kd(t,s,e[s]);return t},Ro=(t,e)=>p_(t,f_(e));function w_(t){return Ro(Po({},t),{level:t?.level||ZN.level})}function y_(t){var e,s;const n=new a_((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Bo(Ro(Po({},t.opts),{level:"trace",browser:Ro(Po({},(s=t.opts)==null?void 0:s.browser),{write:r=>n.write(r)})})),chunkLoggerController:n}}function b_(t){var e;const s=new d_((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Bo(Ro(Po({},t.opts),{level:"trace"}),s),chunkLoggerController:s}}function v_(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?y_(t):b_(t)}const E_={createLogger(t,e="error"){const s=w_({level:e}),{logger:n}=v_({opts:s});return n.error=(...r)=>{for(const i of r)if(i instanceof Error){t(i,...r);return}t(void 0,...r)},n}},C_="rpc.walletconnect.org";function Pd(t,e){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",t),s.searchParams.set("projectId",e),s.toString()}const Ma=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","eip155:80094","eip155:80069","eip155:560048","eip155:31","eip155:2818","eip155:57054","eip155:911867","eip155:534351","eip155:1112","eip155:534352","eip155:1111","eip155:146","eip155:130","eip155:1284","eip155:30","eip155:2810","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],Gn={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===C_}catch{s=!1}if(s){const n=new URL(t);return n.searchParams.has("projectId")||n.searchParams.set("projectId",e),n.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:D.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${D.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){const n=t.rpcUrls?.default?.http?.[0];return Ma.includes(e)?Pd(e,s):n||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){const r=this.getChainNamespace(t),i=this.getCaipNetworkId(t),o=t.rpcUrls?.default?.http?.[0],a=this.getDefaultRpcUrl(t,i,s),c=t?.rpcUrls?.chainDefault?.http?.[0]||o,l=n?.[i]?.map(h=>h.url)||[],u=[...l,...a?[a]:[]],d=[...l];return c&&!d.includes(c)&&d.push(c),{...t,chainNamespace:r,caipNetworkId:i,assets:{imageId:JN.NetworkImageIds[t.id],imageUrl:e?.[t.id]},rpcUrls:{...t.rpcUrls,default:{http:u},chainDefault:{http:d}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){return t.map(r=>Gn.extendCaipNetwork(r,{customNetworkImageUrls:e,customRpcUrls:n,projectId:s}))},getViemTransport(t,e,s){const n=[];return s?.forEach(r=>{n.push(Mi(r.url,r.config))}),Ma.includes(t.caipNetworkId)&&n.push(Mi(Pd(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),t?.rpcUrls?.default?.http?.forEach(r=>{n.push(Mi(r))}),Al(n)},extendWagmiTransports(t,e,s){if(Ma.includes(t.caipNetworkId)){const n=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return Al([s,Mi(n)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:D.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){const e=x.getActiveCaipNetworkId(),s=m.getAllRequestedCaipNetworks(),n=Array.from(m.state.chains?.keys()||[]),r=e?.split(":")[0],i=r?n.includes(r):!1,o=s?.find(c=>c.caipNetworkId===e);return i&&!o&&e?this.getUnsupportedNetwork(e):o||t||s?.[0]}},I_={ACCOUNT_TABS:[{label:"Tokens"},{label:"Activity"}],VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120},VIEWS_WITH_LEGAL_FOOTER:["Connect","ConnectWallets","OnRampTokenSelect","OnRampFiatSelect","OnRampProviders"],VIEWS_WITH_DEFAULT_FOOTER:["Networks"]},$r={filterOutDuplicatesByRDNS(t){const e=S.state.enableEIP6963?M.state.connectors:[],s=x.getRecentWallets(),n=e.map(a=>a.info?.rdns).filter(Boolean),r=s.map(a=>a.rdns).filter(Boolean),i=n.concat(r);if(i.includes("io.metamask.mobile")&&G.isMobile()){const a=i.indexOf("io.metamask.mobile");i[a]="io.metamask"}return t.filter(a=>!(a?.rdns&&i.includes(String(a.rdns))||!a?.rdns&&e.some(l=>l.name===a.name)))},filterOutDuplicatesByIds(t){const e=M.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=x.getRecentWallets(),n=e.map(a=>a.explorerId),r=s.map(a=>a.id),i=n.concat(r);return t.filter(a=>!i.includes(a?.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=M.state,{featuredWalletIds:s}=S.state,n=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>(a.info?.rdns&&(o[a.info.rdns]=!0),o),{});return t.map(o=>({...o,installed:!!o.rdns&&!!n[o.rdns??""]})).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(s?.length){const l=s.indexOf(o.id),u=s.indexOf(a.id);if(l!==-1&&u!==-1)return l-u;if(l!==-1)return-1;if(u!==-1)return 1}return 0})},getConnectOrderMethod(t,e){const s=t?.connectMethodsOrder||S.state.features?.connectMethodsOrder,n=e||M.state.connectors;if(s)return s;const{injected:r,announced:i}=Ba.getConnectorsByType(n,Z.state.recommended,Z.state.featured),o=r.filter(Ba.showConnector),a=i.filter(Ba.showConnector);return o.length||a.length?["wallet","email","social"]:I_.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&Z.state.excludedWallets.some(n=>n.rdns===t.rdns),s=!!t.name&&Z.state.excludedWallets.some(n=>mi.isLowerCaseMatch(n.name,t.name));return e||s},markWalletsWithDisplayIndex(t){return t.map((e,s)=>({...e,display_index:s}))}},Ba={getConnectorsByType(t,e,s){const{customWallets:n}=S.state,r=x.getRecentWallets(),i=$r.filterOutDuplicateWallets(e),o=$r.filterOutDuplicateWallets(s),a=t.filter(d=>d.type==="MULTI_CHAIN"),c=t.filter(d=>d.type==="ANNOUNCED"),l=t.filter(d=>d.type==="INJECTED"),u=t.filter(d=>d.type==="EXTERNAL");return{custom:n,recent:r,external:u,multiChain:a,announced:c,injected:l,recommended:i,featured:o}},showConnector(t){const e=t.info?.rdns,s=!!e&&Z.state.excludedWallets.some(r=>!!r.rdns&&r.rdns===e),n=!!t.name&&Z.state.excludedWallets.some(r=>mi.isLowerCaseMatch(r.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!G.isMobile()||G.isMobile()&&!e&&!H.checkInstalled())||s||n)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||n))},getIsConnectedWithWC(){return Array.from(m.state.chains.values()).some(s=>M.getConnectorId(s.namespace)===D.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:n,announced:r,injected:i,multiChain:o,external:a,overriddenConnectors:c=S.state.features?.connectorTypeOrder??[]}){const u=[{type:"walletConnect",isEnabled:!0},{type:"recent",isEnabled:n.length>0},{type:"injected",isEnabled:[...i,...r,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(f=>f.isEnabled),d=new Set(u.map(f=>f.type)),h=c.filter(f=>d.has(f)).map(f=>({type:f,isEnabled:!0})),p=u.filter(({type:f})=>!h.some(({type:w})=>w===f));return Array.from(new Set([...h,...p].map(({type:f})=>f)))},sortConnectorsByExplorerWallet(t){return[...t].sort((e,s)=>e.explorerWallet&&s.explorerWallet?(e.explorerWallet.order??0)-(s.explorerWallet.order??0):e.explorerWallet?-1:s.explorerWallet?1:0)},getAuthName({email:t,socialUsername:e,socialProvider:s}){return e?s&&s==="discord"&&e.endsWith("0")?e.slice(0,-1):e:t.length>30?`${t.slice(0,-3)}...`:t},async fetchProviderData(t){try{if(t.name==="Browser Wallet"&&!G.isMobile())return{accounts:[],chainId:void 0};if(t.id===D.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};const[e,s]=await Promise.all([t.provider?.request({method:"eth_accounts"}),t.provider?.request({method:"eth_chainId"}).then(n=>Number(n))]);return{accounts:e,chainId:s}}catch(e){return console.warn(`Failed to fetch provider data for ${t.name}`,e),{accounts:[],chainId:void 0}}},getFilteredCustomWallets(t){const e=x.getRecentWallets(),s=M.state.connectors.map(o=>o.info?.rdns).filter(Boolean),n=e.map(o=>o.rdns).filter(Boolean),r=s.concat(n);if(r.includes("io.metamask.mobile")&&G.isMobile()){const o=r.indexOf("io.metamask.mobile");r[o]="io.metamask"}return t.filter(o=>!r.includes(String(o?.rdns)))},hasWalletConnector(t){return M.state.connectors.some(e=>e.id===t.id||e.name===t.name)},isWalletCompatibleWithCurrentChain(t){const e=m.state.activeChain;return e&&t.chains?t.chains.some(s=>{const n=s.split(":")[0];return e===n}):!0},getFilteredRecentWallets(){return x.getRecentWallets().filter(s=>!$r.isExcluded(s)).filter(s=>!this.hasWalletConnector(s)).filter(s=>this.isWalletCompatibleWithCurrentChain(s))},getCappedRecommendedWallets(t){const{connectors:e}=M.state,{customWallets:s,featuredWalletIds:n}=S.state,r=e.find(v=>v.id==="walletConnect"),i=e.filter(v=>v.type==="INJECTED"||v.type==="ANNOUNCED"||v.type==="MULTI_CHAIN");if(!r&&!i.length&&!s?.length)return[];const o=Va.isEmailEnabled(),a=Va.isSocialsEnabled(),c=i.filter(v=>v.name!=="Browser Wallet"),l=n?.length||0,u=s?.length||0,d=c.length||0,h=o?1:0,p=a?1:0,f=l+u+d+h+p,w=Math.max(0,4-f);return w<=0?[]:$r.filterOutDuplicateWallets(t).slice(0,w)}};const ho=globalThis,ol=ho.ShadowRoot&&(ho.ShadyCSS===void 0||ho.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,al=Symbol(),Rd=new WeakMap;let nf=class{constructor(e,s,n){if(this._$cssResult$=!0,n!==al)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=s}get styleSheet(){let e=this.o;const s=this.t;if(ol&&e===void 0){const n=s!==void 0&&s.length===1;n&&(e=Rd.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&Rd.set(s,e))}return e}toString(){return this.cssText}};const Zt=t=>new nf(typeof t=="string"?t:t+"",void 0,al),Qs=(t,...e)=>{const s=t.length===1?t[0]:e.reduce((n,r,i)=>n+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+t[i+1],t[0]);return new nf(s,t,al)},A_=(t,e)=>{if(ol)t.adoptedStyleSheets=e.map(s=>s instanceof CSSStyleSheet?s:s.styleSheet);else for(const s of e){const n=document.createElement("style"),r=ho.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=s.cssText,t.appendChild(n)}},xd=ol?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const n of e.cssRules)s+=n.cssText;return Zt(s)})(t):t;const{is:N_,defineProperty:__,getOwnPropertyDescriptor:S_,getOwnPropertyNames:T_,getOwnPropertySymbols:O_,getPrototypeOf:k_}=Object,Zo=globalThis,$d=Zo.trustedTypes,P_=$d?$d.emptyScript:"",R_=Zo.reactiveElementPolyfillSupport,qr=(t,e)=>t,Sc={toAttribute(t,e){switch(e){case Boolean:t=t?P_:null;break;case Object:case Array:t=t==null?t:JSON.stringify(t)}return t},fromAttribute(t,e){let s=t;switch(e){case Boolean:s=t!==null;break;case Number:s=t===null?null:Number(t);break;case Object:case Array:try{s=JSON.parse(t)}catch{s=null}}return s}},rf=(t,e)=>!N_(t,e),Ud={attribute:!0,type:String,converter:Sc,reflect:!1,useDefault:!1,hasChanged:rf};Symbol.metadata??=Symbol("metadata"),Zo.litPropertyMetadata??=new WeakMap;let Yn=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,s=Ud){if(s.state&&(s.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((s=Object.create(s)).wrapped=!0),this.elementProperties.set(e,s),!s.noAccessor){const n=Symbol(),r=this.getPropertyDescriptor(e,n,s);r!==void 0&&__(this.prototype,e,r)}}static getPropertyDescriptor(e,s,n){const{get:r,set:i}=S_(this.prototype,e)??{get(){return this[s]},set(o){this[s]=o}};return{get:r,set(o){const a=r?.call(this);i?.call(this,o),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Ud}static _$Ei(){if(this.hasOwnProperty(qr("elementProperties")))return;const e=k_(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(qr("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(qr("properties"))){const s=this.properties,n=[...T_(s),...O_(s)];for(const r of n)this.createProperty(r,s[r])}const e=this[Symbol.metadata];if(e!==null){const s=litPropertyMetadata.get(e);if(s!==void 0)for(const[n,r]of s)this.elementProperties.set(n,r)}this._$Eh=new Map;for(const[s,n]of this.elementProperties){const r=this._$Eu(s,n);r!==void 0&&this._$Eh.set(r,s)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const s=[];if(Array.isArray(e)){const n=new Set(e.flat(1/0).reverse());for(const r of n)s.unshift(xd(r))}else e!==void 0&&s.push(xd(e));return s}static _$Eu(e,s){const n=s.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,s=this.constructor.elementProperties;for(const n of s.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return A_(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,s,n){this._$AK(e,n)}_$ET(e,s){const n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&n.reflect===!0){const i=(n.converter?.toAttribute!==void 0?n.converter:Sc).toAttribute(s,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,s){const n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const i=n.getPropertyOptions(r),o=typeof i.converter=="function"?{fromAttribute:i.converter}:i.converter?.fromAttribute!==void 0?i.converter:Sc;this._$Em=r;const a=o.fromAttribute(s,i.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,s,n,r=!1,i){if(e!==void 0){const o=this.constructor;if(r===!1&&(i=this[e]),n??=o.getPropertyOptions(e),!((n.hasChanged??rf)(i,s)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(o._$Eu(e,n))))return;this.C(e,s,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,s,{useDefault:n,reflect:r,wrapped:i},o){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,o??s??this[e]),i!==!0||o!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(s=void 0),this._$AL.set(e,s)),r===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(s){Promise.reject(s)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[r,i]of this._$Ep)this[r]=i;this._$Ep=void 0}const n=this.constructor.elementProperties;if(n.size>0)for(const[r,i]of n){const{wrapped:o}=i,a=this[r];o!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,i,a)}}let e=!1;const s=this._$AL;try{e=this.shouldUpdate(s),e?(this.willUpdate(s),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(s)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(s)}willUpdate(e){}_$AE(e){this._$EO?.forEach(s=>s.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(s=>this._$ET(s,this[s])),this._$EM()}updated(e){}firstUpdated(e){}};Yn.elementStyles=[],Yn.shadowRootOptions={mode:"open"},Yn[qr("elementProperties")]=new Map,Yn[qr("finalized")]=new Map,R_?.({ReactiveElement:Yn}),(Zo.reactiveElementVersions??=[]).push("2.1.2");const cl=globalThis,Dd=t=>t,xo=cl.trustedTypes,Ld=xo?xo.createPolicy("lit-html",{createHTML:t=>t}):void 0,of="$lit$",en=`lit$${Math.random().toFixed(9).slice(2)}$`,af="?"+en,x_=`<${af}>`,$n=document,wi=()=>$n.createComment(""),yi=t=>t===null||typeof t!="object"&&typeof t!="function",ll=Array.isArray,$_=t=>ll(t)||typeof t?.[Symbol.iterator]=="function",ja=`[
20
+ \f\r]`,Or=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Md=/-->/g,Bd=/>/g,pn=RegExp(`>|${ja}(?:([^\\s"'>=/]+)(${ja}*=${ja}*(?:[^
21
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),jd=/'/g,Fd=/"/g,cf=/^(?:script|style|textarea|title)$/i,lf=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),iT=lf(1),oT=lf(2),ur=Symbol.for("lit-noChange"),Ge=Symbol.for("lit-nothing"),qd=new WeakMap,Nn=$n.createTreeWalker($n,129);function uf(t,e){if(!ll(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ld!==void 0?Ld.createHTML(e):e}const U_=(t,e)=>{const s=t.length-1,n=[];let r,i=e===2?"<svg>":e===3?"<math>":"",o=Or;for(let a=0;a<s;a++){const c=t[a];let l,u,d=-1,h=0;for(;h<c.length&&(o.lastIndex=h,u=o.exec(c),u!==null);)h=o.lastIndex,o===Or?u[1]==="!--"?o=Md:u[1]!==void 0?o=Bd:u[2]!==void 0?(cf.test(u[2])&&(r=RegExp("</"+u[2],"g")),o=pn):u[3]!==void 0&&(o=pn):o===pn?u[0]===">"?(o=r??Or,d=-1):u[1]===void 0?d=-2:(d=o.lastIndex-u[2].length,l=u[1],o=u[3]===void 0?pn:u[3]==='"'?Fd:jd):o===Fd||o===jd?o=pn:o===Md||o===Bd?o=Or:(o=pn,r=void 0);const p=o===pn&&t[a+1].startsWith("/>")?" ":"";i+=o===Or?c+x_:d>=0?(n.push(l),c.slice(0,d)+of+c.slice(d)+en+p):c+en+(d===-2?a:p)}return[uf(t,i+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class bi{constructor({strings:e,_$litType$:s},n){let r;this.parts=[];let i=0,o=0;const a=e.length-1,c=this.parts,[l,u]=U_(e,s);if(this.el=bi.createElement(l,n),Nn.currentNode=this.el.content,s===2||s===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=Nn.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(of)){const h=u[o++],p=r.getAttribute(d).split(en),f=/([.?@])?(.*)/.exec(h);c.push({type:1,index:i,name:f[2],strings:p,ctor:f[1]==="."?L_:f[1]==="?"?M_:f[1]==="@"?B_:Qo}),r.removeAttribute(d)}else d.startsWith(en)&&(c.push({type:6,index:i}),r.removeAttribute(d));if(cf.test(r.tagName)){const d=r.textContent.split(en),h=d.length-1;if(h>0){r.textContent=xo?xo.emptyScript:"";for(let p=0;p<h;p++)r.append(d[p],wi()),Nn.nextNode(),c.push({type:2,index:++i});r.append(d[h],wi())}}}else if(r.nodeType===8)if(r.data===af)c.push({type:2,index:i});else{let d=-1;for(;(d=r.data.indexOf(en,d+1))!==-1;)c.push({type:7,index:i}),d+=en.length-1}i++}}static createElement(e,s){const n=$n.createElement("template");return n.innerHTML=e,n}}function dr(t,e,s=t,n){if(e===ur)return e;let r=n!==void 0?s._$Co?.[n]:s._$Cl;const i=yi(e)?void 0:e._$litDirective$;return r?.constructor!==i&&(r?._$AO?.(!1),i===void 0?r=void 0:(r=new i(t),r._$AT(t,s,n)),n!==void 0?(s._$Co??=[])[n]=r:s._$Cl=r),r!==void 0&&(e=dr(t,r._$AS(t,e.values),r,n)),e}class D_{constructor(e,s){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=s}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:s},parts:n}=this._$AD,r=(e?.creationScope??$n).importNode(s,!0);Nn.currentNode=r;let i=Nn.nextNode(),o=0,a=0,c=n[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new Oi(i,i.nextSibling,this,e):c.type===1?l=new c.ctor(i,c.name,c.strings,this,e):c.type===6&&(l=new j_(i,this,e)),this._$AV.push(l),c=n[++a]}o!==c?.index&&(i=Nn.nextNode(),o++)}return Nn.currentNode=$n,r}p(e){let s=0;for(const n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,s),s+=n.strings.length-2):n._$AI(e[s])),s++}}class Oi{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,s,n,r){this.type=2,this._$AH=Ge,this._$AN=void 0,this._$AA=e,this._$AB=s,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const s=this._$AM;return s!==void 0&&e?.nodeType===11&&(e=s.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,s=this){e=dr(this,e,s),yi(e)?e===Ge||e==null||e===""?(this._$AH!==Ge&&this._$AR(),this._$AH=Ge):e!==this._$AH&&e!==ur&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):$_(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==Ge&&yi(this._$AH)?this._$AA.nextSibling.data=e:this.T($n.createTextNode(e)),this._$AH=e}$(e){const{values:s,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=bi.createElement(uf(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(s);else{const i=new D_(r,this),o=i.u(this.options);i.p(s),this.T(o),this._$AH=i}}_$AC(e){let s=qd.get(e.strings);return s===void 0&&qd.set(e.strings,s=new bi(e)),s}k(e){ll(this._$AH)||(this._$AH=[],this._$AR());const s=this._$AH;let n,r=0;for(const i of e)r===s.length?s.push(n=new Oi(this.O(wi()),this.O(wi()),this,this.options)):n=s[r],n._$AI(i),r++;r<s.length&&(this._$AR(n&&n._$AB.nextSibling,r),s.length=r)}_$AR(e=this._$AA.nextSibling,s){for(this._$AP?.(!1,!0,s);e!==this._$AB;){const n=Dd(e).nextSibling;Dd(e).remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}}class Qo{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,n,r,i){this.type=1,this._$AH=Ge,this._$AN=void 0,this.element=e,this.name=s,this._$AM=r,this.options=i,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=Ge}_$AI(e,s=this,n,r){const i=this.strings;let o=!1;if(i===void 0)e=dr(this,e,s,0),o=!yi(e)||e!==this._$AH&&e!==ur,o&&(this._$AH=e);else{const a=e;let c,l;for(e=i[0],c=0;c<i.length-1;c++)l=dr(this,a[n+c],s,c),l===ur&&(l=this._$AH[c]),o||=!yi(l)||l!==this._$AH[c],l===Ge?e=Ge:e!==Ge&&(e+=(l??"")+i[c+1]),this._$AH[c]=l}o&&!r&&this.j(e)}j(e){e===Ge?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class L_ extends Qo{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===Ge?void 0:e}}class M_ extends Qo{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==Ge)}}class B_ extends Qo{constructor(e,s,n,r,i){super(e,s,n,r,i),this.type=5}_$AI(e,s=this){if((e=dr(this,e,s,0)??Ge)===ur)return;const n=this._$AH,r=e===Ge&&n!==Ge||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==Ge&&(n===Ge||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}}class j_{constructor(e,s,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=s,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){dr(this,e)}}const F_=cl.litHtmlPolyfillSupport;F_?.(bi,Oi),(cl.litHtmlVersions??=[]).push("3.3.2");const q_=(t,e,s)=>{const n=s?.renderBefore??e;let r=n._$litPart$;if(r===void 0){const i=s?.renderBefore??null;n._$litPart$=r=new Oi(e.insertBefore(wi(),i),i,void 0,s??{})}return r._$AI(t),r};const ul=globalThis;class po extends Yn{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=q_(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ur}}po._$litElement$=!0,po.finalized=!0,ul.litElementHydrateSupport?.({LitElement:po});const W_=ul.litElementPolyfillSupport;W_?.({LitElement:po});(ul.litElementVersions??=[]).push("4.2.2");const H_={black:"#202020",white:"#FFFFFF",white010:"rgba(255, 255, 255, 0.1)",accent010:"rgba(9, 136, 240, 0.1)",accent020:"rgba(9, 136, 240, 0.2)",accent030:"rgba(9, 136, 240, 0.3)",accent040:"rgba(9, 136, 240, 0.4)",accent050:"rgba(9, 136, 240, 0.5)",accent060:"rgba(9, 136, 240, 0.6)",accent070:"rgba(9, 136, 240, 0.7)",accent080:"rgba(9, 136, 240, 0.8)",accent090:"rgba(9, 136, 240, 0.9)",accent100:"rgba(9, 136, 240, 1.0)",accentSecondary010:"rgba(199, 185, 148, 0.1)",accentSecondary020:"rgba(199, 185, 148, 0.2)",accentSecondary030:"rgba(199, 185, 148, 0.3)",accentSecondary040:"rgba(199, 185, 148, 0.4)",accentSecondary050:"rgba(199, 185, 148, 0.5)",accentSecondary060:"rgba(199, 185, 148, 0.6)",accentSecondary070:"rgba(199, 185, 148, 0.7)",accentSecondary080:"rgba(199, 185, 148, 0.8)",accentSecondary090:"rgba(199, 185, 148, 0.9)",accentSecondary100:"rgba(199, 185, 148, 1.0)",productWalletKit:"#FFB800",productAppKit:"#FF573B",productCloud:"#0988F0",productDocumentation:"#008847",neutrals050:"#F6F6F6",neutrals100:"#F3F3F3",neutrals200:"#E9E9E9",neutrals300:"#D0D0D0",neutrals400:"#BBB",neutrals500:"#9A9A9A",neutrals600:"#6C6C6C",neutrals700:"#4F4F4F",neutrals800:"#363636",neutrals900:"#2A2A2A",neutrals1000:"#252525",semanticSuccess010:"rgba(48, 164, 107, 0.1)",semanticSuccess020:"rgba(48, 164, 107, 0.2)",semanticSuccess030:"rgba(48, 164, 107, 0.3)",semanticSuccess040:"rgba(48, 164, 107, 0.4)",semanticSuccess050:"rgba(48, 164, 107, 0.5)",semanticSuccess060:"rgba(48, 164, 107, 0.6)",semanticSuccess070:"rgba(48, 164, 107, 0.7)",semanticSuccess080:"rgba(48, 164, 107, 0.8)",semanticSuccess090:"rgba(48, 164, 107, 0.9)",semanticSuccess100:"rgba(48, 164, 107, 1.0)",semanticError010:"rgba(223, 74, 52, 0.1)",semanticError020:"rgba(223, 74, 52, 0.2)",semanticError030:"rgba(223, 74, 52, 0.3)",semanticError040:"rgba(223, 74, 52, 0.4)",semanticError050:"rgba(223, 74, 52, 0.5)",semanticError060:"rgba(223, 74, 52, 0.6)",semanticError070:"rgba(223, 74, 52, 0.7)",semanticError080:"rgba(223, 74, 52, 0.8)",semanticError090:"rgba(223, 74, 52, 0.9)",semanticError100:"rgba(223, 74, 52, 1.0)",semanticWarning010:"rgba(243, 161, 63, 0.1)",semanticWarning020:"rgba(243, 161, 63, 0.2)",semanticWarning030:"rgba(243, 161, 63, 0.3)",semanticWarning040:"rgba(243, 161, 63, 0.4)",semanticWarning050:"rgba(243, 161, 63, 0.5)",semanticWarning060:"rgba(243, 161, 63, 0.6)",semanticWarning070:"rgba(243, 161, 63, 0.7)",semanticWarning080:"rgba(243, 161, 63, 0.8)",semanticWarning090:"rgba(243, 161, 63, 0.9)",semanticWarning100:"rgba(243, 161, 63, 1.0)"},$o={core:{backgroundAccentPrimary:"#0988F0",backgroundAccentCertified:"#C7B994",backgroundWalletKit:"#FFB800",backgroundAppKit:"#FF573B",backgroundCloud:"#0988F0",backgroundDocumentation:"#008847",backgroundSuccess:"rgba(48, 164, 107, 0.20)",backgroundError:"rgba(223, 74, 52, 0.20)",backgroundWarning:"rgba(243, 161, 63, 0.20)",textAccentPrimary:"#0988F0",textAccentCertified:"#C7B994",textWalletKit:"#FFB800",textAppKit:"#FF573B",textCloud:"#0988F0",textDocumentation:"#008847",textSuccess:"#30A46B",textError:"#DF4A34",textWarning:"#F3A13F",borderAccentPrimary:"#0988F0",borderSecondary:"#C7B994",borderSuccess:"#30A46B",borderError:"#DF4A34",borderWarning:"#F3A13F",foregroundAccent010:"rgba(9, 136, 240, 0.1)",foregroundAccent020:"rgba(9, 136, 240, 0.2)",foregroundAccent040:"rgba(9, 136, 240, 0.4)",foregroundAccent060:"rgba(9, 136, 240, 0.6)",foregroundSecondary020:"rgba(199, 185, 148, 0.2)",foregroundSecondary040:"rgba(199, 185, 148, 0.4)",foregroundSecondary060:"rgba(199, 185, 148, 0.6)",iconAccentPrimary:"#0988F0",iconAccentCertified:"#C7B994",iconSuccess:"#30A46B",iconError:"#DF4A34",iconWarning:"#F3A13F",glass010:"rgba(255, 255, 255, 0.1)",zIndex:"9999"},dark:{overlay:"rgba(0, 0, 0, 0.50)",backgroundPrimary:"#202020",backgroundInvert:"#FFFFFF",textPrimary:"#FFFFFF",textSecondary:"#9A9A9A",textTertiary:"#BBBBBB",textInvert:"#202020",borderPrimary:"#2A2A2A",borderPrimaryDark:"#363636",borderSecondary:"#4F4F4F",foregroundPrimary:"#252525",foregroundSecondary:"#2A2A2A",foregroundTertiary:"#363636",iconDefault:"#9A9A9A",iconInverse:"#FFFFFF"},light:{overlay:"rgba(230 , 230, 230, 0.5)",backgroundPrimary:"#FFFFFF",borderPrimaryDark:"#E9E9E9",backgroundInvert:"#202020",textPrimary:"#202020",textSecondary:"#9A9A9A",textTertiary:"#6C6C6C",textInvert:"#FFFFFF",borderPrimary:"#E9E9E9",borderSecondary:"#D0D0D0",foregroundPrimary:"#F3F3F3",foregroundSecondary:"#E9E9E9",foregroundTertiary:"#D0D0D0",iconDefault:"#9A9A9A",iconInverse:"#202020"}},V_={1:"4px",2:"8px",10:"10px",3:"12px",4:"16px",6:"24px",5:"20px",8:"32px",16:"64px",20:"80px",32:"128px",64:"256px",128:"512px",round:"9999px"},K_={0:"0px","01":"2px",1:"4px",2:"8px",3:"12px",4:"16px",5:"20px",6:"24px",7:"28px",8:"32px",9:"36px",10:"40px",12:"48px",14:"56px",16:"64px",20:"80px",32:"128px",64:"256px"},z_={regular:"KHTeka",mono:"KHTekaMono"},G_={regular:"400",medium:"500"},Y_={h1:"50px",h2:"44px",h3:"38px",h4:"32px",h5:"26px",h6:"20px",large:"16px",medium:"14px",small:"12px"},J_={"h1-regular-mono":{lineHeight:"50px",letterSpacing:"-3px"},"h1-regular":{lineHeight:"50px",letterSpacing:"-1px"},"h1-medium":{lineHeight:"50px",letterSpacing:"-0.84px"},"h2-regular-mono":{lineHeight:"44px",letterSpacing:"-2.64px"},"h2-regular":{lineHeight:"44px",letterSpacing:"-0.88px"},"h2-medium":{lineHeight:"44px",letterSpacing:"-0.88px"},"h3-regular-mono":{lineHeight:"38px",letterSpacing:"-2.28px"},"h3-regular":{lineHeight:"38px",letterSpacing:"-0.76px"},"h3-medium":{lineHeight:"38px",letterSpacing:"-0.76px"},"h4-regular-mono":{lineHeight:"32px",letterSpacing:"-1.92px"},"h4-regular":{lineHeight:"32px",letterSpacing:"-0.32px"},"h4-medium":{lineHeight:"32px",letterSpacing:"-0.32px"},"h5-regular-mono":{lineHeight:"26px",letterSpacing:"-1.56px"},"h5-regular":{lineHeight:"26px",letterSpacing:"-0.26px"},"h5-medium":{lineHeight:"26px",letterSpacing:"-0.26px"},"h6-regular-mono":{lineHeight:"20px",letterSpacing:"-1.2px"},"h6-regular":{lineHeight:"20px",letterSpacing:"-0.6px"},"h6-medium":{lineHeight:"20px",letterSpacing:"-0.6px"},"lg-regular-mono":{lineHeight:"16px",letterSpacing:"-0.96px"},"lg-regular":{lineHeight:"18px",letterSpacing:"-0.16px"},"lg-medium":{lineHeight:"18px",letterSpacing:"-0.16px"},"md-regular-mono":{lineHeight:"14px",letterSpacing:"-0.84px"},"md-regular":{lineHeight:"16px",letterSpacing:"-0.14px"},"md-medium":{lineHeight:"16px",letterSpacing:"-0.14px"},"sm-regular-mono":{lineHeight:"12px",letterSpacing:"-0.72px"},"sm-regular":{lineHeight:"14px",letterSpacing:"-0.12px"},"sm-medium":{lineHeight:"14px",letterSpacing:"-0.12px"}},X_={"ease-out-power-2":"cubic-bezier(0.23, 0.09, 0.08, 1.13)","ease-out-power-1":"cubic-bezier(0.12, 0.04, 0.2, 1.06)","ease-in-power-2":"cubic-bezier(0.92, -0.13, 0.77, 0.91)","ease-in-power-1":"cubic-bezier(0.88, -0.06, 0.8, 0.96)","ease-inout-power-2":"cubic-bezier(0.77, 0.09, 0.23, 1.13)","ease-inout-power-1":"cubic-bezier(0.88, 0.04, 0.12, 1.06)"},Z_={xl:"400ms",lg:"200ms",md:"125ms",sm:"75ms"},Tc={colors:H_,fontFamily:z_,fontWeight:G_,textSize:Y_,typography:J_,tokens:{core:$o.core,theme:$o.dark},borderRadius:V_,spacing:K_,durations:Z_,easings:X_},Wd="--apkt",_s={createCSSVariables(t){const e={},s={};function n(i,o,a=""){for(const[c,l]of Object.entries(i)){const u=a?`${a}-${c}`:c;l&&typeof l=="object"&&Object.keys(l).length?(o[c]={},n(l,o[c],u)):typeof l=="string"&&(o[c]=`${Wd}-${u}`)}}function r(i,o){for(const[a,c]of Object.entries(i))c&&typeof c=="object"?(o[a]={},r(c,o[a])):typeof c=="string"&&(o[a]=`var(${c})`)}return n(t,e),r(e,s),{cssVariables:e,cssVariablesVarPrefix:s}},assignCSSVariables(t,e){const s={};function n(r,i,o){for(const[a,c]of Object.entries(r)){const l=o?`${o}-${a}`:a,u=i[a];c&&typeof c=="object"?n(c,u,l):typeof u=="string"&&(s[`${Wd}-${l}`]=u)}}return n(t,e),s},createRootStyles(t,e){const s={...Tc,tokens:{...Tc.tokens,theme:t==="light"?$o.light:$o.dark}},{cssVariables:n}=_s.createCSSVariables(s),r=_s.assignCSSVariables(n,s),i=_s.generateW3MVariables(e),o=_s.generateW3MOverrides(e),a=_s.generateScaledVariables(e),c=_s.generateBaseVariables(r),l={...r,...c,...i,...o,...a},u=_s.applyColorMixToVariables(e,l),d={...l,...u};return`:root {${Object.entries(d).map(([p,f])=>`${p}:${f.replace("/[:;{}</>]/g","")};`).join("")}}`},generateW3MVariables(t){if(!t)return{};const e={};return e["--w3m-font-family"]=t["--w3m-font-family"]||"KHTeka",e["--w3m-accent"]=t["--w3m-accent"]||"#0988F0",e["--w3m-color-mix"]=t["--w3m-color-mix"]||"#000",e["--w3m-color-mix-strength"]=`${t["--w3m-color-mix-strength"]||0}%`,e["--w3m-font-size-master"]=t["--w3m-font-size-master"]||"10px",e["--w3m-border-radius-master"]=t["--w3m-border-radius-master"]||"4px",e},generateW3MOverrides(t){if(!t)return{};const e={};if(t["--w3m-accent"]){const s=t["--w3m-accent"];e["--apkt-tokens-core-iconAccentPrimary"]=s,e["--apkt-tokens-core-borderAccentPrimary"]=s,e["--apkt-tokens-core-textAccentPrimary"]=s,e["--apkt-tokens-core-backgroundAccentPrimary"]=s}return t["--w3m-font-family"]&&(e["--apkt-fontFamily-regular"]=t["--w3m-font-family"]),t["--w3m-z-index"]&&(e["--apkt-tokens-core-zIndex"]=`${t["--w3m-z-index"]}`),e},generateScaledVariables(t){if(!t)return{};const e={};if(t["--w3m-font-size-master"]){const s=parseFloat(t["--w3m-font-size-master"].replace("px",""));e["--apkt-textSize-h1"]=`${Number(s)*5}px`,e["--apkt-textSize-h2"]=`${Number(s)*4.4}px`,e["--apkt-textSize-h3"]=`${Number(s)*3.8}px`,e["--apkt-textSize-h4"]=`${Number(s)*3.2}px`,e["--apkt-textSize-h5"]=`${Number(s)*2.6}px`,e["--apkt-textSize-h6"]=`${Number(s)*2}px`,e["--apkt-textSize-large"]=`${Number(s)*1.6}px`,e["--apkt-textSize-medium"]=`${Number(s)*1.4}px`,e["--apkt-textSize-small"]=`${Number(s)*1.2}px`}if(t["--w3m-border-radius-master"]){const s=parseFloat(t["--w3m-border-radius-master"].replace("px",""));e["--apkt-borderRadius-1"]=`${Number(s)}px`,e["--apkt-borderRadius-2"]=`${Number(s)*2}px`,e["--apkt-borderRadius-3"]=`${Number(s)*3}px`,e["--apkt-borderRadius-4"]=`${Number(s)*4}px`,e["--apkt-borderRadius-5"]=`${Number(s)*5}px`,e["--apkt-borderRadius-6"]=`${Number(s)*6}px`,e["--apkt-borderRadius-8"]=`${Number(s)*8}px`,e["--apkt-borderRadius-16"]=`${Number(s)*16}px`,e["--apkt-borderRadius-20"]=`${Number(s)*20}px`,e["--apkt-borderRadius-32"]=`${Number(s)*32}px`,e["--apkt-borderRadius-64"]=`${Number(s)*64}px`,e["--apkt-borderRadius-128"]=`${Number(s)*128}px`}return e},generateColorMixCSS(t,e){if(!t?.["--w3m-color-mix"]||!t["--w3m-color-mix-strength"])return"";const s=t["--w3m-color-mix"],n=t["--w3m-color-mix-strength"];if(!n||n===0)return"";const r=Object.keys(e||{}).filter(o=>{const a=o.includes("-tokens-core-background")||o.includes("-tokens-core-text")||o.includes("-tokens-core-border")||o.includes("-tokens-core-foreground")||o.includes("-tokens-core-icon")||o.includes("-tokens-theme-background")||o.includes("-tokens-theme-text")||o.includes("-tokens-theme-border")||o.includes("-tokens-theme-foreground")||o.includes("-tokens-theme-icon"),c=o.includes("-borderRadius-")||o.includes("-spacing-")||o.includes("-textSize-")||o.includes("-fontFamily-")||o.includes("-fontWeight-")||o.includes("-typography-")||o.includes("-duration-")||o.includes("-ease-")||o.includes("-path-")||o.includes("-width-")||o.includes("-height-")||o.includes("-visual-size-")||o.includes("-modal-width")||o.includes("-cover");return a&&!c});return r.length===0?"":` @supports (background: color-mix(in srgb, white 50%, black)) {
22
+ :root {
23
+ ${r.map(o=>{const a=e?.[o]||"";return a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?`${o}: color-mix(in srgb, ${s} ${n}%, ${a});`:`${o}: color-mix(in srgb, ${s} ${n}%, var(${o}-base, ${a}));`}).join("")}
24
+ }
25
+ }`},generateBaseVariables(t){const e={},s=t["--apkt-tokens-theme-backgroundPrimary"];s&&(e["--apkt-tokens-theme-backgroundPrimary-base"]=s);const n=t["--apkt-tokens-core-backgroundAccentPrimary"];return n&&(e["--apkt-tokens-core-backgroundAccentPrimary-base"]=n),e},applyColorMixToVariables(t,e){const s={};if(e?.["--apkt-tokens-theme-backgroundPrimary"]&&(s["--apkt-tokens-theme-backgroundPrimary"]="var(--apkt-tokens-theme-backgroundPrimary-base)"),e?.["--apkt-tokens-core-backgroundAccentPrimary"]&&(s["--apkt-tokens-core-backgroundAccentPrimary"]="var(--apkt-tokens-core-backgroundAccentPrimary-base)"),!t?.["--w3m-color-mix"]||!t["--w3m-color-mix-strength"])return s;const n=t["--w3m-color-mix"],r=t["--w3m-color-mix-strength"];if(!r||r===0)return s;const i=Object.keys(e||{}).filter(o=>{const a=o.includes("-tokens-core-background")||o.includes("-tokens-core-text")||o.includes("-tokens-core-border")||o.includes("-tokens-core-foreground")||o.includes("-tokens-core-icon")||o.includes("-tokens-theme-background")||o.includes("-tokens-theme-text")||o.includes("-tokens-theme-border")||o.includes("-tokens-theme-foreground")||o.includes("-tokens-theme-icon")||o.includes("-tokens-theme-overlay"),c=o.includes("-borderRadius-")||o.includes("-spacing-")||o.includes("-textSize-")||o.includes("-fontFamily-")||o.includes("-fontWeight-")||o.includes("-typography-")||o.includes("-duration-")||o.includes("-ease-")||o.includes("-path-")||o.includes("-width-")||o.includes("-height-")||o.includes("-visual-size-")||o.includes("-modal-width")||o.includes("-cover");return a&&!c});return i.length===0||i.forEach(o=>{const a=e?.[o]||"";o.endsWith("-base")||(o==="--apkt-tokens-theme-backgroundPrimary"||o==="--apkt-tokens-core-backgroundAccentPrimary"?s[o]=`color-mix(in srgb, ${n} ${r}%, var(${o}-base))`:a.includes("color-mix")||a.startsWith("#")||a.startsWith("rgb")?s[o]=`color-mix(in srgb, ${n} ${r}%, ${a})`:s[o]=`color-mix(in srgb, ${n} ${r}%, var(${o}-base, ${a}))`)}),s}},{cssVariablesVarPrefix:Q_}=_s.createCSSVariables(Tc);function aT(t,...e){return Qs(t,...e.map(s=>Zt(typeof s=="function"?s(Q_):s)))}let yn,_n,fs,ts,Uo;const Ns={"KHTeka-500-woff2":"https://fonts.reown.com/KHTeka-Medium.woff2","KHTeka-400-woff2":"https://fonts.reown.com/KHTeka-Regular.woff2","KHTeka-300-woff2":"https://fonts.reown.com/KHTeka-Light.woff2","KHTekaMono-400-woff2":"https://fonts.reown.com/KHTekaMono-Regular.woff2","KHTeka-500-woff":"https://fonts.reown.com/KHTeka-Light.woff","KHTeka-400-woff":"https://fonts.reown.com/KHTeka-Regular.woff","KHTeka-300-woff":"https://fonts.reown.com/KHTeka-Light.woff","KHTekaMono-400-woff":"https://fonts.reown.com/KHTekaMono-Regular.woff"};function Do(t,e="dark"){yn&&document.head.removeChild(yn),yn=document.createElement("style"),yn.textContent=_s.createRootStyles(e,t),document.head.appendChild(yn)}function cT(t,e="dark"){if(Uo=t,_n=document.createElement("style"),fs=document.createElement("style"),ts=document.createElement("style"),_n.textContent=rr(t).core.cssText,fs.textContent=rr(t).dark.cssText,ts.textContent=rr(t).light.cssText,document.head.appendChild(_n),document.head.appendChild(fs),document.head.appendChild(ts),Do(t,e),Oc(e),!t?.["--w3m-font-family"])for(const[s,n]of Object.entries(Ns)){const r=document.createElement("link");r.rel="preload",r.href=n,r.as="font",r.type=s.includes("woff2")?"font/woff2":"font/woff",r.crossOrigin="anonymous",document.head.appendChild(r)}Oc(e)}function Oc(t="dark"){fs&&ts&&yn&&(t==="light"?(Do(Uo,t),fs.removeAttribute("media"),ts.media="enabled"):(Do(Uo,t),ts.removeAttribute("media"),fs.media="enabled"))}function eS(t){if(Uo=t,_n&&fs&&ts&&(_n.textContent=rr(t).core.cssText,fs.textContent=rr(t).dark.cssText,ts.textContent=rr(t).light.cssText,t?.["--w3m-font-family"])){const e=t["--w3m-font-family"];_n.textContent=_n.textContent?.replace("font-family: KHTeka",`font-family: ${e}`),fs.textContent=fs.textContent?.replace("font-family: KHTeka",`font-family: ${e}`),ts.textContent=ts.textContent?.replace("font-family: KHTeka",`font-family: ${e}`)}if(yn){const e=ts?.media==="enabled"?"light":"dark";Do(t,e)}}function rr(t){const e=!!t?.["--w3m-font-family"];return{core:Qs`
26
+ ${e?Qs``:Qs`
27
+ @font-face {
28
+ font-family: 'KHTeka';
29
+ src:
30
+ url(${Zt(Ns["KHTeka-400-woff2"])}) format('woff2'),
31
+ url(${Zt(Ns["KHTeka-400-woff"])}) format('woff');
32
+ font-weight: 400;
33
+ font-style: normal;
34
+ font-display: swap;
35
+ }
36
+
37
+ @font-face {
38
+ font-family: 'KHTeka';
39
+ src:
40
+ url(${Zt(Ns["KHTeka-300-woff2"])}) format('woff2'),
41
+ url(${Zt(Ns["KHTeka-300-woff"])}) format('woff');
42
+ font-weight: 300;
43
+ font-style: normal;
44
+ }
45
+
46
+ @font-face {
47
+ font-family: 'KHTekaMono';
48
+ src:
49
+ url(${Zt(Ns["KHTekaMono-400-woff2"])}) format('woff2'),
50
+ url(${Zt(Ns["KHTekaMono-400-woff"])}) format('woff');
51
+ font-weight: 400;
52
+ font-style: normal;
53
+ }
54
+
55
+ @font-face {
56
+ font-family: 'KHTeka';
57
+ src:
58
+ url(${Zt(Ns["KHTeka-400-woff2"])}) format('woff2'),
59
+ url(${Zt(Ns["KHTeka-400-woff"])}) format('woff');
60
+ font-weight: 400;
61
+ font-style: normal;
62
+ }
63
+ `}
64
+
65
+ @keyframes w3m-shake {
66
+ 0% {
67
+ transform: scale(1) rotate(0deg);
68
+ }
69
+ 20% {
70
+ transform: scale(1) rotate(-1deg);
71
+ }
72
+ 40% {
73
+ transform: scale(1) rotate(1.5deg);
74
+ }
75
+ 60% {
76
+ transform: scale(1) rotate(-1.5deg);
77
+ }
78
+ 80% {
79
+ transform: scale(1) rotate(1deg);
80
+ }
81
+ 100% {
82
+ transform: scale(1) rotate(0deg);
83
+ }
84
+ }
85
+ @keyframes w3m-iframe-fade-out {
86
+ 0% {
87
+ opacity: 1;
88
+ }
89
+ 100% {
90
+ opacity: 0;
91
+ }
92
+ }
93
+ @keyframes w3m-iframe-zoom-in {
94
+ 0% {
95
+ transform: translateY(50px);
96
+ opacity: 0;
97
+ }
98
+ 100% {
99
+ transform: translateY(0px);
100
+ opacity: 1;
101
+ }
102
+ }
103
+ @keyframes w3m-iframe-zoom-in-mobile {
104
+ 0% {
105
+ transform: scale(0.95);
106
+ opacity: 0;
107
+ }
108
+ 100% {
109
+ transform: scale(1);
110
+ opacity: 1;
111
+ }
112
+ }
113
+ :root {
114
+ --apkt-modal-width: 370px;
115
+
116
+ --apkt-visual-size-inherit: inherit;
117
+ --apkt-visual-size-sm: 40px;
118
+ --apkt-visual-size-md: 55px;
119
+ --apkt-visual-size-lg: 80px;
120
+
121
+ --apkt-path-network-sm: path(
122
+ 'M15.4 2.1a5.21 5.21 0 0 1 5.2 0l11.61 6.7a5.21 5.21 0 0 1 2.61 4.52v13.4c0 1.87-1 3.59-2.6 4.52l-11.61 6.7c-1.62.93-3.6.93-5.22 0l-11.6-6.7a5.21 5.21 0 0 1-2.61-4.51v-13.4c0-1.87 1-3.6 2.6-4.52L15.4 2.1Z'
123
+ );
124
+
125
+ --apkt-path-network-md: path(
126
+ 'M43.4605 10.7248L28.0485 1.61089C25.5438 0.129705 22.4562 0.129705 19.9515 1.61088L4.53951 10.7248C2.03626 12.2051 0.5 14.9365 0.5 17.886V36.1139C0.5 39.0635 2.03626 41.7949 4.53951 43.2752L19.9515 52.3891C22.4562 53.8703 25.5438 53.8703 28.0485 52.3891L43.4605 43.2752C45.9637 41.7949 47.5 39.0635 47.5 36.114V17.8861C47.5 14.9365 45.9637 12.2051 43.4605 10.7248Z'
127
+ );
128
+
129
+ --apkt-path-network-lg: path(
130
+ 'M78.3244 18.926L50.1808 2.45078C45.7376 -0.150261 40.2624 -0.150262 35.8192 2.45078L7.6756 18.926C3.23322 21.5266 0.5 26.3301 0.5 31.5248V64.4752C0.5 69.6699 3.23322 74.4734 7.6756 77.074L35.8192 93.5492C40.2624 96.1503 45.7376 96.1503 50.1808 93.5492L78.3244 77.074C82.7668 74.4734 85.5 69.6699 85.5 64.4752V31.5248C85.5 26.3301 82.7668 21.5266 78.3244 18.926Z'
131
+ );
132
+
133
+ --apkt-width-network-sm: 36px;
134
+ --apkt-width-network-md: 48px;
135
+ --apkt-width-network-lg: 86px;
136
+
137
+ --apkt-duration-dynamic: 0ms;
138
+ --apkt-height-network-sm: 40px;
139
+ --apkt-height-network-md: 54px;
140
+ --apkt-height-network-lg: 96px;
141
+ }
142
+ `,dark:Qs`
143
+ :root {
144
+ }
145
+ `,light:Qs`
146
+ :root {
147
+ }
148
+ `}}const lT=Qs`
149
+ div,
150
+ span,
151
+ iframe,
152
+ a,
153
+ img,
154
+ form,
155
+ button,
156
+ label,
157
+ *::after,
158
+ *::before {
159
+ margin: 0;
160
+ padding: 0;
161
+ box-sizing: border-box;
162
+ font-style: normal;
163
+ text-rendering: optimizeSpeed;
164
+ -webkit-font-smoothing: antialiased;
165
+ -moz-osx-font-smoothing: grayscale;
166
+ -webkit-tap-highlight-color: transparent;
167
+ backface-visibility: hidden;
168
+ }
169
+
170
+ :host {
171
+ font-family: var(--apkt-fontFamily-regular);
172
+ }
173
+ `,uT=Qs`
174
+ button,
175
+ a {
176
+ cursor: pointer;
177
+ display: flex;
178
+ justify-content: center;
179
+ align-items: center;
180
+ position: relative;
181
+
182
+ will-change: background-color, color, border, box-shadow, width, height, transform, opacity;
183
+ outline: none;
184
+ border: none;
185
+ text-decoration: none;
186
+ transition:
187
+ background-color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
188
+ color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
189
+ border var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
190
+ box-shadow var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
191
+ width var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
192
+ height var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
193
+ transform var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
194
+ opacity var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
195
+ scale var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
196
+ border-radius var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2);
197
+ will-change:
198
+ background-color, color, border, box-shadow, width, height, transform, opacity, scale,
199
+ border-radius;
200
+ }
201
+
202
+ a:active:not([disabled]),
203
+ button:active:not([disabled]) {
204
+ scale: 0.975;
205
+ transform-origin: center;
206
+ }
207
+
208
+ button:disabled {
209
+ cursor: default;
210
+ }
211
+
212
+ input {
213
+ border: none;
214
+ outline: none;
215
+ appearance: none;
216
+ }
217
+ `,eo={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};class tS extends _m{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new Sm({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace})),Promise.resolve()}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect(),this.emit("disconnect")}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}return{connections:[]}}syncConnections(){return Promise.resolve()}async getAccounts({namespace:e}){const n=this.provider?.session?.namespaces?.[e]?.accounts?.map(r=>{const[,,i]=r.split(":");return i}).filter((r,i,o)=>o.indexOf(r)===i)||[];return Promise.resolve({accounts:n.map(r=>G.createAccount(e,r,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&we.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};const n=m.getAccountData();if(n?.balanceLoading&&e.chainId===m.state.activeCaipNetwork?.id)return{balance:n?.balance||"0.00",symbol:n?.balanceSymbol||""};const i=(await m.fetchTokenBalance()).find(o=>o.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&o.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:i?.quantity.numeric||"0.00",symbol:i?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:s,message:n,address:r}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let i="";return m.state.activeCaipNetwork?.chainNamespace===D.CHAIN.SOLANA?i=(await s.request({method:"solana_signMessage",params:{message:pr.encode(new TextEncoder().encode(n)),pubkey:r}},m.state.activeCaipNetwork?.caipNetworkId)).signature:i=await s.request({method:"personal_sign",params:[n,r]},m.state.activeCaipNetwork?.caipNetworkId),{signature:i}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}emitFirstAvailableConnection(){}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:s}=e,n=this.getWalletConnectConnector();if(s.chainNamespace===D.CHAIN.EVM)try{await n.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:El(s.id)}]})}catch(r){if(r.code===eo.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||r.code===eo.ERROR_INVALID_CHAIN_ID||r.code===eo.ERROR_CODE_DEFAULT||r?.data?.originalError?.code===eo.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await n.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:El(s.id),rpcUrls:[s?.rpcUrls.chainDefault?.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[s.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}n.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(n=>n.type==="WALLET_CONNECT")?.provider}}const sS=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication"],to={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?we.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(s=>s!=="email"):!1},processFallback:t=>t===void 0?we.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?we.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?we.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?we.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?we.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?we.DEFAULT_REMOTE_FEATURES.onramp:!1:t},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?we.DEFAULT_REMOTE_FEATURES.activity:!!t},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?we.DEFAULT_REMOTE_FEATURES.reownBranding:!!t},emailCapture:{apiFeatureName:"email_capture",localFeatureName:"emailCapture",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>t.isEnabled&&(t.config??[]),processFallback:t=>!1},multiWallet:{apiFeatureName:"multi_wallet",localFeatureName:"multiWallet",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>we.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>we.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>we.DEFAULT_REMOTE_FEATURES.payments},reownAuthentication:{apiFeatureName:"reown_authentication",localFeatureName:"reownAuthentication",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>typeof t>"u"?we.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!t}},nS={localSettingsOverridden:new Set,getApiConfig(t,e){return e?.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=to[e],n=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(n)}},processFeature(t,e,s,n,r){const i=to[t],o=e[i.localFeatureName];if(r&&!i.isAvailableOnBasic)return!1;if(n){const a=this.getApiConfig(i.apiFeatureName,s);return a?.config===null?this.processFallbackFeature(t,o):a?.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return to[t].processApi(e)},processFallbackFeature(t,e){return to[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let n=null,r=!1;try{n=await Z.fetchProjectConfig(),r=n!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const i=r&&!e?we.DEFAULT_REMOTE_FEATURES:we.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of sS){const a=this.processFeature(o,s,n,r,e);Object.assign(i,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),we.DEFAULT_REMOTE_FEATURES}if(r&&this.localSettingsOverridden.size>0){const o=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;_t.open({debugMessage:Lt.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(o)},"warning")}return i}};class rS{constructor(e){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,n)=>{if(s){const r=m.getCaipNetworks(s)?.find(a=>a.id===n);if(r)return r;const i=m.getNetworkData(s)?.caipNetwork;return i||m.getRequestedCaipNetworks(s).filter(a=>a.chainNamespace===s)?.[0]}return m.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>m.getCaipNetworks(s),this.getActiveChainNamespace=()=>m.state.activeChain,this.setRequestedCaipNetworks=(s,n)=>{m.setRequestedCaipNetworks(s,n)},this.getApprovedCaipNetworkIds=()=>m.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>m.state.activeChain===s||!s?m.state.activeCaipAddress:m.state.chains.get(s)?.accountState?.caipAddress,this.setClientId=s=>{ie.setClientId(s)},this.getProvider=s=>$e.getProvider(s),this.getProviderType=s=>$e.getProviderId(s),this.getPreferredAccountType=s=>Wt(s),this.setCaipAddress=(s,n,r=!1)=>{m.setAccountProp("caipAddress",s,n,r),m.setAccountProp("address",G.getPlainAddress(s),n,r)},this.setBalance=(s,n,r)=>{m.setAccountProp("balance",s,r),m.setAccountProp("balanceSymbol",n,r)},this.setProfileName=(s,n)=>{m.setAccountProp("profileName",s,n)},this.setProfileImage=(s,n)=>{m.setAccountProp("profileImage",s,n)},this.setUser=(s,n)=>{m.setAccountProp("user",s,n)},this.resetAccount=s=>{m.resetAccount(s)},this.setCaipNetwork=s=>{m.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,n)=>{m.setChainNetworkData(n,{caipNetwork:s})},this.setStatus=(s,n)=>{m.setAccountProp("status",s,n),M.isConnected()?x.setConnectionStatus("connected"):x.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>m.getAccountData(s)?.address,this.setConnectors=s=>{const n=[...M.state.allConnectors,...s];M.setConnectors(n)},this.setConnections=(s,n)=>{x.setConnections(s,n),H.setConnections(s,n)},this.fetchIdentity=s=>ie.fetchIdentity(s),this.getReownName=s=>Mr.getNamesForAddress(s),this.getConnectors=()=>M.getConnectors(),this.getConnectorImage=s=>uh.getConnectorImage(s),this.getConnections=s=>this.remoteFeatures.multiWallet?bo.getConnectionsData(s).connections:(_t.open(D.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=s=>this.remoteFeatures.multiWallet?bo.getConnectionsData(s).recentConnections:(_t.open(D.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async s=>{if(!this.remoteFeatures.multiWallet){_t.open(D.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await H.switchConnection(s)},this.deleteConnection=s=>{if(!this.remoteFeatures.multiWallet){_t.open(D.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}x.deleteAddressFromConnection(s),H.syncStorageConnections()},this.setConnectedWalletInfo=(s,n)=>{const r=$e.getProviderId(n),i=s?{...s,type:r}:void 0;m.setAccountProp("connectedWalletInfo",i,n)},this.getIsConnectedState=()=>!!m.state.activeCaipAddress,this.addAddressLabel=(s,n,r)=>{const i=m.getAccountData(r)?.addressLabels||{};m.setAccountProp("addressLabels",{...i,[s]:n},r)},this.removeAddressLabel=(s,n)=>{const r=m.getAccountData(n)?.addressLabels||{};m.setAccountProp("addressLabels",{...r,[s]:void 0},n)},this.getAddress=s=>{const n=s||m.state.activeChain;return m.getAccountData(n)?.address},this.resetNetwork=s=>{m.resetNetwork(s)},this.addConnector=s=>{M.addConnector(s)},this.resetWcConnection=()=>{H.resetWcConnection()},this.setAddressExplorerUrl=(s,n)=>{m.setAccountProp("addressExplorerUrl",s,n)},this.setSmartAccountDeployed=(s,n)=>{m.setAccountProp("smartAccountDeployed",s,n)},this.setPreferredAccountType=(s,n)=>{m.setAccountProp("preferredAccountType",s,n)},this.setEIP6963Enabled=s=>{S.setEIP6963Enabled(s)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,s){const n=e?.map(i=>i.namespace).filter(i=>!!i);if(n?.length)return[...new Set(n)];const r=s?.map(i=>i.chainNamespace);return[...new Set(r)]}async initialize(e){if(this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),S.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),this.remoteFeatures=await nS.fetchRemoteFeatures(e),await Z.fetchUsage(),S.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&Ya.setOnrampProviders(this.remoteFeatures.onramp),(S.state.remoteFeatures?.email||Array.isArray(S.state.remoteFeatures?.socials)&&S.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins(),S.state.features?.reownAuthentication||S.state.remoteFeatures?.reownAuthentication){const{ReownAuthentication:s}=await fo(async()=>{const{ReownAuthentication:r}=await import("./features-C-ekZReg.js");return{ReownAuthentication:r}},__vite__mapDeps([4,1,2,3])),n=S.state.siwx;n instanceof s||(n&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),S.setSIWX(new s))}}async openSend(e){const s=e.namespace||m.state.activeChain,n=this.getCaipAddress(s),r=this.getCaipNetwork(s)?.id;if(!n)throw new Error("openSend: caipAddress not found");if(r?.toString()!==e.chainId.toString()){const i=m.getCaipNetworkById(e.chainId,s);if(!i)throw new Error(`openSend: caipNetwork with chainId ${e.chainId} not found`);await this.switchNetwork(i,{throwOnFailure:!0})}try{const i=tf.getTokenSymbolByAddress(e.assetAddress);i&&await Z.fetchTokenImages([i])}catch{}return await pe.open({view:"WalletSend",data:{send:e}}),new Promise((i,o)=>{const a=ue.subscribeKey("hash",u=>{u&&(l(),i({hash:u}))}),c=pe.subscribe(u=>{u.open||(l(),o(new Error("Modal closed")))}),l=this.createCleanupHandler([a,c])})}toModalOptions(){function e(n){return n?.view==="Swap"}function s(n){return n?.view==="WalletSend"}return{isSwap:e,isSend:s}}async checkAllowedOrigins(){try{const e=await Z.fetchAllowedOrigins();if(!G.isClient())return;const s=window.location.origin;tn.isOriginAllowed(s,e,D.DEFAULT_ALLOWED_ANCESTORS)||_t.open(Lt.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error))return;switch(e.message){case"RATE_LIMITED":_t.open(Lt.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const s=e.cause instanceof Error?e.cause:e;_t.open({displayMessage:Lt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:Lt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(s.message)},"error");break}}}}createCleanupHandler(e){return()=>{e.forEach(s=>{try{s()}catch{}})}}sendInitializeEvent(e){const{...s}=e;delete s.adapters,delete s.universalProvider,de.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(n=>n.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initAdapterController(){ph.initialize(this.chainAdapters)}initializeThemeController(e){e.themeMode&&Tt.setThemeMode(e.themeMode),e.themeVariables&&Tt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");m.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});const s=this.getDefaultNetwork();s&&m.setActiveCaipNetwork(s)}initializeConnectionController(e){H.initialize(e.adapters??[]),H.setWcBasic(e.basic??!1)}initializeConnectorController(){M.initialize(this.chainNamespaces)}initializeProjectSettings(e){S.setProjectId(e.projectId),S.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){S.setDebug(e.debug!==!1),S.setEnableWalletGuide(e.enableWalletGuide!==!1),S.setEnableWallets(e.enableWallets!==!1),S.setEIP6963Enabled(e.enableEIP6963!==!1),S.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),S.setEnableReconnect(e.enableReconnect!==!1),S.setEnableMobileFullScreen(e.enableMobileFullScreen===!0),S.setCoinbasePreference(e.coinbasePreference),S.setEnableAuthLogger(e.enableAuthLogger!==!1),S.setCustomRpcUrls(e.customRpcUrls),S.setEnableEmbedded(e.enableEmbedded),S.setAllWallets(e.allWallets),S.setIncludeWalletIds(e.includeWalletIds),S.setExcludeWalletIds(e.excludeWalletIds),S.setFeaturedWalletIds(e.featuredWalletIds),S.setTokens(e.tokens),S.setTermsConditionsUrl(e.termsConditionsUrl),S.setPrivacyPolicyUrl(e.privacyPolicyUrl),S.setCustomWallets(e.customWallets),S.setFeatures(e.features),S.setAllowUnsupportedChain(e.allowUnsupportedChain),S.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),S.setPreferUniversalLinks(e.experimental_preferUniversalLinks),S.setDefaultAccountTypes(e.defaultAccountTypes);const s=this.getDefaultMetaData();if(!e.metadata&&s&&(e.metadata=s),S.setMetadata(e.metadata),S.setDisableAppend(e.disableAppend),S.setEnableEmbedded(e.enableEmbedded),S.setSIWX(e.siwx),this.features=S.state.features??{},!e.projectId){_t.open(Lt.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(r=>r.namespace===D.CHAIN.EVM)&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");S.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return G.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const n=Gn.getUnsupportedNetwork(`${s}:${e}`);m.setActiveCaipNetwork(n)}}getDefaultNetwork(){return Gn.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,s){return Gn.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return Gn.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(r=>r.id===e.defaultNetwork?.id);return s?Gn.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectConnector(e,s){try{this.setLoading(!0,e);let n={connections:[]};const r=this.getAdapter(e);return(m.state.chains.get(e)?.accountState?.caipAddress||!S.state.enableReconnect)&&r?.disconnect&&(n=await r.disconnect({id:s})),this.setLoading(!1,e),n}catch(n){throw this.setLoading(!1,e),new Error(`Failed to disconnect chains: ${n.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=m.state.activeChain,s=this.getAdapter(e),n=this.getCaipNetwork(e)?.id,r=H.getConnections(e),i=this.remoteFeatures.multiWallet,o=r.length>0;if(!s)throw new Error("Adapter not found");const a=await s.connectWalletConnect(n);(!o||!i)&&this.close(),this.setClientId(a?.clientId||null),x.setConnectedNamespaces([...m.state.chains.keys()]),await this.syncWalletConnectAccount(),await Qt.initializeIfEnabled()},connectExternal:async e=>{const s=await this.onConnectExternal(e);return await this.connectInactiveNamespaces(e,s),s?{address:s.address}:void 0},reconnectExternal:async({id:e,info:s,type:n,provider:r})=>{const i=m.state.activeChain,o=this.getAdapter(i);if(!i)throw new Error("reconnectExternal: namespace not found");if(!o)throw new Error("reconnectExternal: adapter not found");o?.reconnect&&(await o?.reconnect({id:e,info:s,type:n,provider:r,chainId:this.getCaipNetwork()?.id}),x.addConnectedNamespace(i),this.syncConnectedWalletInfo(i))},disconnectConnector:async e=>{await this.disconnectConnector(e.namespace,e.id)},disconnect:async e=>{const{id:s,chainNamespace:n,initialDisconnect:r}=e||{},i=n||m.state.activeChain,o=M.getConnectorId(i),a=s===D.CONNECTOR_ID.AUTH||o===D.CONNECTOR_ID.AUTH,c=s===D.CONNECTOR_ID.WALLET_CONNECT||o===D.CONNECTOR_ID.WALLET_CONNECT;try{const l=Array.from(m.state.chains.keys());let u=n?[n]:l;(c||a)&&(u=l);const d=u.map(async f=>{const g=M.getConnectorId(f),w=s||g,C=await this.disconnectConnector(f,w);C&&(a&&x.deleteConnectedSocialProvider(),C.connections.forEach(v=>{x.addDisconnectedConnectorId(v.connectorId,f)})),r&&this.onDisconnectNamespace({chainNamespace:f,closeModal:!1})}),h=await Promise.allSettled(d);ue.resetSend(),H.resetWcConnection(),Qt.getSIWX()?.signOutOnDisconnect&&await Qt.clearSessions(),M.setFilterByNamespace(void 0),H.syncStorageConnections();const p=h.filter(f=>f.status==="rejected");if(p.length>0)throw new Error(p.map(f=>f.reason.message).join(", "));de.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:n||"all"}})}catch(l){throw new Error(`Failed to disconnect chains: ${l.message}`)}},checkInstalled:e=>e?e.some(s=>!!window.ethereum?.[String(s)]):!!window.ethereum,signMessage:async e=>{const s=m.state.activeChain,n=this.getAdapter(m.state.activeChain);if(!s)throw new Error("signMessage: namespace not found");if(!n)throw new Error("signMessage: adapter not found");const r=this.getAddress(s);if(!r)throw new Error("signMessage: address not found");return(await n?.signMessage({message:e,address:r,provider:$e.getProvider(s)}))?.signature||""},sendTransaction:async e=>{const s=e.chainNamespace;if(!s)throw new Error("sendTransaction: namespace not found");if(we.SEND_SUPPORTED_NAMESPACES.includes(s)){const n=this.getAdapter(s);if(!n)throw new Error("sendTransaction: adapter not found");const r=$e.getProvider(s);return(await n?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:r}))?.hash||""}return""},estimateGas:async e=>{const s=e.chainNamespace;if(s===D.CHAIN.EVM){const n=this.getAdapter(s);if(!n)throw new Error("estimateGas: adapter is required but got undefined");const r=$e.getProvider(s),i=this.getCaipNetwork();if(!i)throw new Error("estimateGas: caipNetwork is required but got undefined");return(await n?.estimateGas({...e,provider:r,caipNetwork:i}))?.gas||0n}return 0n},getEnsAvatar:async()=>{const e=m.state.activeChain;if(!e)throw new Error("getEnsAvatar: namespace is required but got undefined");const s=this.getAddress(e);if(!s)throw new Error("getEnsAvatar: address not found");return await this.syncIdentity({address:s,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:e}),m.getAccountData()?.profileImage||!1},getEnsAddress:async e=>await tn.resolveReownName(e),writeContract:async e=>{const s=m.state.activeChain,n=this.getAdapter(s);if(!s)throw new Error("writeContract: namespace is required but got undefined");if(!n)throw new Error("writeContract: adapter is required but got undefined");const r=this.getCaipNetwork(),i=this.getCaipAddress(),o=$e.getProvider(s);if(!r||!i)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");return(await n?.writeContract({...e,caipNetwork:r,provider:o,caipAddress:i}))?.hash},parseUnits:(e,s)=>{const n=this.getAdapter(m.state.activeChain);if(!n)throw new Error("parseUnits: adapter is required but got undefined");return n?.parseUnits({value:e,decimals:s})??0n},formatUnits:(e,s)=>{const n=this.getAdapter(m.state.activeChain);if(!n)throw new Error("formatUnits: adapter is required but got undefined");return n?.formatUnits({value:e,decimals:s})??"0"},getCapabilities:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("getCapabilities: adapter is required but got undefined");return await s?.getCapabilities(e)},grantPermissions:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("grantPermissions: adapter is required but got undefined");return await s?.grantPermissions(e)},revokePermissions:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("revokePermissions: adapter is required but got undefined");return s?.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(m.state.activeChain);if(!s)throw new Error("walletGetAssets: adapter is required but got undefined");return await s?.walletGetAssets(e)??{}},updateBalance:e=>{const s=this.getAddress(e),n=this.getCaipNetwork(e);!n||!s||this.updateNativeBalance(s,n?.id,e)}},H.setClient(this.connectionControllerClient)}async onConnectExternal(e){const s=m.state.activeChain,n=e.chain||s,r=this.getAdapter(n);let i=!0;if(e.type===As.CONNECTOR_TYPE_AUTH&&D.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(d=>M.getConnectorId(d)===D.CONNECTOR_ID.AUTH)&&e.chain!==s&&(i=!1),e.chain&&e.chain!==s&&!e.caipNetwork){const l=this.getCaipNetworks().find(u=>u.chainNamespace===e.chain);l&&i&&this.setCaipNetwork(l)}if(!n)throw new Error("connectExternal: namespace not found");if(!r)throw new Error("connectExternal: adapter not found");const o=this.getCaipNetwork(n),a=e.caipNetwork||o,c=await r.connect({id:e.id,address:e.address,info:e.info,type:e.type,provider:e.provider,socialUri:e.socialUri,chainId:e.caipNetwork?.id||o?.id,rpcUrl:e.caipNetwork?.rpcUrls?.default?.http?.[0]||o?.rpcUrls?.default?.http?.[0]});if(c)return x.addConnectedNamespace(n),this.syncProvider({...c,chainNamespace:n}),this.setStatus("connected",n),this.syncConnectedWalletInfo(n),x.removeDisconnectedConnectorId(e.id,n),{address:c.address,connectedCaipNetwork:a}}async connectInactiveNamespaces(e,s){const n=e.type===As.CONNECTOR_TYPE_AUTH,r=mi.getOtherAuthNamespaces(s?.connectedCaipNetwork?.chainNamespace),i=m.state.activeCaipNetwork,o=this.getAdapter(i?.chainNamespace);n&&(await Promise.all(r.map(async a=>{try{const c=$e.getProvider(a),l=this.getCaipNetwork(a);await this.getAdapter(a)?.connect({...e,provider:c,socialUri:void 0,chainId:l?.id,rpcUrl:l?.rpcUrls?.default?.http?.[0]})&&(x.addConnectedNamespace(a),x.removeDisconnectedConnectorId(e.id,a),this.setStatus("connected",a),this.syncConnectedWalletInfo(a))}catch(c){_t.warn(Lt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,Lt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(a,c instanceof Error?c.message:void 0),Lt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),i&&await o?.switchNetwork({caipNetwork:i}))}getApprovedCaipNetworksData(){if($e.getProviderId(m.state.activeChain)===As.CONNECTOR_TYPE_WALLET_CONNECT){const s=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(s)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=$e.getProviderId(s);if(e.chainNamespace===m.state.activeChain)await this.getAdapter(s)?.switchNetwork({caipNetwork:e});else if(this.setCaipNetwork(e),r===As.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const i=this.getAddressByChainNamespace(s);i&&this.syncAccount({address:i,chainId:e.id,chainNamespace:s})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(s=>{const n=s.chains||[],r=s.accounts.map(i=>{const{chainId:o,chainNamespace:a}=Ze.parseCaipAddress(i);return`${a}:${o}`});return Array.from(new Set([...n,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,n)=>{const r=e?.find(i=>i.namespace===n);return r?(r.construct({namespace:n,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:i})=>i===n)}),s[n]=r):s[n]=new tS({namespace:n,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e);const s=this.getAdapter(e);if(!s)throw new Error("adapter not found");await s.syncConnectors(),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)})),this.initAdapterController()}onConnectors(e){this.getAdapter(e)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const n=x.getConnectionStatus();S.state.enableReconnect===!1?this.setStatus("disconnected",e):n==="connected"?this.setStatus("connecting",e):n==="disconnected"?(x.clearAddressCache(),this.setStatus(n,e)):this.setStatus(n,e),s.on("switchNetwork",({address:r,chainId:i})=>{const o=this.getCaipNetworks().find(l=>l.id.toString()===i.toString()||l.caipNetworkId.toString()===i.toString()),a=m.state.activeChain===e,c=m.state.chains.get(e)?.accountState?.address;if(o){const l=a&&r?r:c;l&&this.syncAccount({address:l,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(i)}),s.on("disconnect",()=>{const r=this.remoteFeatures.multiWallet,i=Array.from(H.state.connections.values()).flat();this.onDisconnectNamespace({chainNamespace:e,closeModal:!r||i.length===0})}),s.on("connections",r=>{this.setConnections(r,e)}),s.on("pendingTransactions",()=>{const r=this.getAddress(e),i=m.state.activeCaipNetwork;!r||!i?.id||this.updateNativeBalance(r,i.id,i.chainNamespace)}),s.on("accountChanged",({address:r,chainId:i,connector:o})=>{this.handlePreviousConnectorConnection(o);const a=m.state.activeChain===e;o?.provider&&(this.syncProvider({id:o.id,type:o.type,provider:o?.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e));const c=m.getNetworkData(e)?.caipNetwork?.id,l=i||c;a&&l?this.syncAccount({address:r,chainId:l,chainNamespace:e}):!a&&l?(this.syncAccountInfo(r,l,e),this.syncBalance({address:r,chainId:l,chainNamespace:e})):this.syncAccountInfo(r,i,e),x.addConnectedNamespace(e)})}async handlePreviousConnectorConnection(e){const s=e?.chain,n=e?.id,r=M.getConnectorId(s),i=S.state.remoteFeatures?.multiWallet,a=s&&n&&r&&r!==n&&!i;try{a&&await H.disconnect({id:r,namespace:s})}catch(c){console.warn("Error disconnecting previous connector",c)}}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&await this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(e=>H.disconnect({namespace:e,initialDisconnect:!0})))}catch(e){console.error("Error disconnecting existing connections:",e)}}async reconnectWalletConnect(){await this.syncWalletConnectAccount();const e=this.getAddress();this.getCaipAddress()||x.deleteRecentWallet();const s=x.getRecentWallet();de.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:G.isMobile()?"mobile":"qrcode",name:s?.name||"Unknown",reconnect:!0,view:se.state.view,walletRank:s?.order}})}async syncNamespaceConnection(e){try{e===D.CHAIN.EVM&&G.isSafeApp()&&M.setConnectorId(D.CONNECTOR_ID.SAFE,e);const s=M.getConnectorId(e);switch(this.setStatus("connecting",e),s){case D.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case D.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}onDisconnectNamespace(e){const{chainNamespace:s,closeModal:n}=e||{};m.resetAccount(s),m.resetNetwork(s),x.removeConnectedNamespace(s);const r=Array.from(m.state.chains.keys());(s?[s]:r).forEach(o=>x.addDisconnectedConnectorId(M.getConnectorId(o)||"",o)),M.removeConnectorId(s),$e.resetChain(s),this.setUser(null,s),this.setStatus("disconnected",s),this.setConnectedWalletInfo(null,s),n!==!1&&pe.close()}async syncAdapterConnections(){await Promise.allSettled(this.chainNamespaces.map(e=>{const s=this.getAdapter(e),n=this.getCaipAddress(e),r=this.getCaipNetwork(e);return s?.syncConnections({connectToFirstConnector:!n,caipNetwork:r})}))}async syncAdapterConnection(e){const s=this.getAdapter(e),n=this.getCaipNetwork(e),r=M.getConnectorId(e),o=M.getConnectors(e).find(a=>a.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!n?.id)throw new Error("CaipNetwork not found");const a=await s?.syncConnection({namespace:e,id:o.id,chainId:n.id,rpcUrl:n?.rpcUrls?.default?.http?.[0]});a?(this.syncProvider({...a,chainNamespace:e}),await this.syncAccount({...a,chainNamespace:e}),this.setStatus("connected",e),de.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:a.address,properties:{method:"browser",name:o.info?.name||o.name||"Unknown",reconnect:!0,view:se.state.view,walletRank:void 0}})):this.setStatus("disconnected",e)}catch{this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})}}async syncWalletConnectAccount(){const e=Object.keys(this.universalProvider?.session?.namespaces||{}),s=this.chainNamespaces.map(async n=>{const r=this.getAdapter(n);if(!r)return;const i=this.universalProvider?.session?.namespaces?.[n]?.accounts||[],o=m.state.activeCaipNetwork?.id,a=i.find(l=>{const{chainId:u}=Ze.parseCaipAddress(l);return u===o?.toString()})||i[0];if(a){const l=Ze.validateCaipAddress(a),{chainId:u,address:d}=Ze.parseCaipAddress(l);if($e.setProviderId(n,As.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&m.state.activeCaipNetwork&&r.namespace!==D.CHAIN.EVM){const h=r.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:m.state.activeCaipNetwork});$e.setProvider(n,h)}else $e.setProvider(n,this.universalProvider);M.setConnectorId(D.CONNECTOR_ID.WALLET_CONNECT,n),x.addConnectedNamespace(n),await this.syncAccount({address:d,chainId:u,chainNamespace:n})}else e.includes(n)&&this.setStatus("disconnected",n);const c=this.getApprovedCaipNetworksData();this.syncConnectedWalletInfo(n),m.setApprovedCaipNetworksData(n,{approvedCaipNetworkIds:c.approvedCaipNetworkIds,supportsAllNetworks:c.supportsAllNetworks})});await Promise.all(s)}syncProvider({type:e,provider:s,id:n,chainNamespace:r}){$e.setProviderId(r,e),$e.setProvider(r,s),M.setConnectorId(n,r)}async syncAccount(e){const s=e.chainNamespace===m.state.activeChain,n=m.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:i,chainNamespace:o}=e,{chainId:a}=x.getActiveNetworkProps(),c=n?.id||a,l=m.state.activeCaipNetwork?.name===D.UNSUPPORTED_NETWORK_NAME,u=m.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!u)&&c){let d=this.getCaipNetworks().find(g=>g.id.toString()===c.toString()),h=this.getCaipNetworks().find(g=>g.chainNamespace===o);if(!u&&!d&&!h){const g=this.getApprovedCaipNetworkIds()||[],w=g.find(v=>Ze.parseCaipNetworkId(v)?.chainId===c.toString()),C=g.find(v=>Ze.parseCaipNetworkId(v)?.chainNamespace===o);d=this.getCaipNetworks().find(v=>v.caipNetworkId===w),h=this.getCaipNetworks().find(v=>v.caipNetworkId===C||"deprecatedCaipNetworkId"in v&&v.deprecatedCaipNetworkId===C)}const p=d||h;p?.chainNamespace===m.state.activeChain?S.state.enableNetworkSwitch&&!S.state.allowUnsupportedChain&&m.state.activeCaipNetwork?.name===D.UNSUPPORTED_NETWORK_NAME?m.showUnsupportedChainUI():this.setCaipNetwork(p):s||n&&this.setCaipNetworkOfNamespace(n,o),this.syncConnectedWalletInfo(o);const f=this.getAddress(o);mi.isLowerCaseMatch(r,f)||this.syncAccountInfo(r,p?.id,o),s?await this.syncBalance({address:r,chainId:p?.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:n?.id,chainNamespace:o}),this.syncIdentity({address:r,chainId:i,chainNamespace:o})}}async syncAccountInfo(e,s,n){const r=this.getCaipAddress(n),i=s||r?.split(":")[1];if(!i)return;const o=`${n}:${i}:${e}`;this.setCaipAddress(o,n,!0),await this.syncIdentity({address:e,chainId:i,chainNamespace:n})}async syncReownName(e,s){try{const n=await this.getReownName(e);if(n[0]){const r=n[0];this.setProfileName(r.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){const s=M.getConnectorId(e),n=$e.getProviderId(e);if(n===As.CONNECTOR_TYPE_ANNOUNCED||n===As.CONNECTOR_TYPE_INJECTED){if(s){const i=this.getConnectors().find(o=>{const a=o.id===s,c=o.info?.rdns===s,l=o.connectors?.some(u=>u.id===s||u.info?.rdns===s);return a||c||!!l});if(i){const{info:o,name:a,imageUrl:c}=i,l=c||this.getConnectorImage(i);this.setConnectedWalletInfo({name:a,icon:l,...o},e)}}}else if(n===As.CONNECTOR_TYPE_WALLET_CONNECT){const r=$e.getProvider(e);r?.session&&this.setConnectedWalletInfo({...r.session.peer.metadata,name:r.session.peer.metadata.name,icon:r.session.peer.metadata.icons?.[0]},e)}else if(s&&(s===D.CONNECTOR_ID.COINBASE_SDK||s===D.CONNECTOR_ID.COINBASE)){const r=this.getConnectors().find(c=>c.id===s),i=r?.name||"Coinbase Wallet",o=r?.imageUrl||this.getConnectorImage(r),a=r?.info;this.setConnectedWalletInfo({...a,name:i,icon:o},e)}}async syncBalance(e){!zd.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(n=>n.id.toString()===e.chainId?.toString())||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,n){const r=this.getAdapter(n),i=m.getCaipNetworkByNamespace(n,s);if(r){const o=await r.getBalance({address:e,chainId:s,caipNetwork:i,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,n),o}}async initializeUniversalAdapter(){const e=E_.createLogger((n,...r)=>{n&&this.handleAlertError(n),console.error(...r)}),s={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};S.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await YN.init(s),S.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(e=>{tn.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:s=>{H.setUri(s)},onConnect:s=>{const{address:n}=G.getAccount(s[0]);H.finalizeWcConnection(n)},onDisconnect:()=>{m.state.noAdapters&&this.resetAccount(e),H.resetWcConnection()},onChainChanged:s=>{const n=m.state.activeChain,r=n&&M.state.activeConnectorIds[n]===D.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(m.state.noAdapters||r)){const i=this.getCaipNetworks().find(a=>a.id.toString()===s.toString()||a.caipNetworkId.toString()===s.toString()),o=this.getCaipNetwork();if(!i){this.setUnsupportedNetwork(s);return}o?.id.toString()!==i?.id.toString()&&o?.chainNamespace===i?.chainNamespace&&this.setCaipNetwork(i)}},onAccountsChanged:s=>{const n=m.state.activeChain,r=n&&M.state.activeConnectorIds[n]===D.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(m.state.noAdapters||r)){const i=s?.[0];i&&this.syncAccount({address:i.address,chainId:i.chainId,chainNamespace:i.chainNamespace})}}})})}createUniversalProvider(){return!this.universalProviderInitPromise&&G.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){de.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}getDisabledCaipNetworks(){const e=m.getAllApprovedCaipNetworkIds(),s=m.getAllRequestedCaipNetworks();return G.sortRequestedNetworks(e,s).filter(r=>m.isCaipNetworkDisabled(r))}handleAlertError(e){const s=Object.entries(Lt.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[n,r]=s??[],{message:i,alertErrorKey:o}=r??{};if(n&&i&&!this.reportedAlertErrors[n]){const a=Lt.ALERT_ERRORS[o];a&&(_t.open(a,"error"),this.reportedAlertErrors[n]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const n=e;n.namespace=s,n.construct({namespace:s,projectId:this.options?.projectId,networks:this.caipNetworks?.filter(({chainNamespace:r})=>r===s)}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=n)}async open(e){await this.injectModalUi(),e?.uri&&H.setUri(e.uri);const{isSwap:s,isSend:n}=this.toModalOptions();return s(e)?pe.open({...e,data:{swap:e.arguments}}):n(e)&&e.arguments?this.openSend(e.arguments):pe.open(e)}async close(){await this.injectModalUi(),pe.close()}setLoading(e,s){pe.setLoading(e,s)}async disconnect(e){await H.disconnect({namespace:e})}getSIWX(){return S.state.siwx}getError(){return""}getChainId(){return m.state.activeCaipNetwork?.id}async switchNetwork(e,{throwOnFailure:s=!1}={}){const n=this.getCaipNetworks().find(r=>r.id===e.id);if(!n){_t.open(Lt.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await m.switchActiveNetwork(n,{throwOnFailure:s})}getWalletProvider(){return m.state.activeChain?$e.state.providers[m.state.activeChain]:null}getWalletProviderType(){return $e.getProviderId(m.state.activeChain)}subscribeProviders(e){return $e.subscribeProviders(e)}getThemeMode(){return Tt.state.themeMode}getThemeVariables(){return Tt.state.themeVariables}setThemeMode(e){Tt.setThemeMode(e),Oc(Tt.state.themeMode)}setTermsConditionsUrl(e){S.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){S.setPrivacyPolicyUrl(e)}setThemeVariables(e){Tt.setThemeVariables(e),eS(Tt.state.themeVariables)}subscribeTheme(e){return Tt.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?H.subscribe(e):(_t.open(D.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){return e?m.state.chains.get(e)?.accountState?.connectedWalletInfo:m.getAccountData()?.connectedWalletInfo}getAccount(e){const s=e||m.state.activeChain,n=M.getAuthConnector(s),r=m.getAccountData(s),i=x.getConnectedConnectorId(m.state.activeChain),o=H.getConnections(s);if(!s)throw new Error("AppKit:getAccount - namespace is required");const a=o.flatMap(c=>c.accounts.map(({address:l,type:u,publicKey:d})=>G.createAccount(s,l,u||"eoa",d)));if(r)return{allAccounts:a,caipAddress:r.caipAddress,address:G.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:n&&i===D.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:x.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:Wt(s),isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const n=()=>{const r=this.getAccount(s);r&&e(r)};s?m.subscribeChainProp("accountState",n,s):m.subscribe(n),M.subscribe(n)}subscribeNetwork(e){return m.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s?.id,caipNetworkId:s?.caipNetworkId})})}subscribeWalletInfo(e,s){return s?m.subscribeChainProp("accountState",n=>e(n?.connectedWalletInfo),s):m.subscribeChainProp("accountState",n=>e(n?.connectedWalletInfo))}subscribeShouldUpdateToAddress(e){m.subscribeChainProp("accountState",s=>e(s?.shouldUpdateToAddress))}subscribeCaipNetworkChange(e){m.subscribeKey("activeCaipNetwork",e)}getState(){return ks.state}getRemoteFeatures(){return S.state.remoteFeatures}subscribeState(e){return ks.subscribe(e)}subscribeRemoteFeatures(e){return S.subscribeKey("remoteFeatures",e)}showErrorMessage(e){hs.showError(e)}showSuccessMessage(e){hs.showSuccess(e)}getEvent(){return{...de.state}}subscribeEvents(e){return de.subscribe(e)}replace(e){se.replace(e)}redirect(e){se.push(e)}popTransactionStack(e){se.popTransactionStack(e)}isOpen(){return pe.state.open}isTransactionStackEmpty(){return se.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){S.setFeatures(e)}updateRemoteFeatures(e){S.setRemoteFeatures(e)}updateOptions(e){const n={...S.state||{},...e};S.setOptions(n)}setConnectMethodsOrder(e){S.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){S.setWalletFeaturesOrder(e)}setCollapseWallets(e){S.setCollapseWallets(e)}setSocialsOrder(e){S.setSocialsOrder(e)}getConnectMethodsOrder(){return $r.getConnectOrderMethod(S.state.features,M.getConnectors())}addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const n=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(r=>r.id===n.id)||m.addNetwork(n)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(r=>r.id===s)&&m.removeNetwork(e,s)}}let Hd=!1;class df extends rS{async open(e){M.isConnected()||await super.open(e)}async close(){if(await super.close(),this.options.manualWCControl){const e=m.getAccountData(this.activeChainNamespace)?.address;H.finalizeWcConnection(e)}}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!Hd&&G.isClient()){if(await fo(()=>import("./basic-BqNJI8_e.js"),__vite__mapDeps([5,6,1,2,3])),await fo(()=>import("./w3m-modal-DV77a3rm.js"),__vite__mapDeps([7,6,1,2,3])),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!S.state.disableAppend&&!S.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}Hd=!0}}}const iS="1.8.11";function oS(t){return new df({...t,basic:!0,sdkVersion:`html-core-${iS}`})}const dT=Object.freeze(Object.defineProperty({__proto__:null,AppKit:df,createAppKit:oS},Symbol.toStringTag,{value:"Module"}));export{Te as $,Z as A,ie as B,M as C,Bc as D,de as E,hh as F,et as G,mi as H,Qe as I,Qt as J,Q_ as K,I_ as L,pe as M,Bf as N,S as O,cT as P,rf as Q,se as R,hs as S,Tt as T,Sc as U,ur as V,$r as W,zd as X,ee as Y,Bi as Z,X as _,G as a,Cl as a$,vl as a0,Mo as a1,Uc as a2,og as a3,gg as a4,El as a5,wg as a6,dS as a7,ag as a8,fg as a9,yS as aA,hS as aB,Rg as aC,bS as aD,ah as aE,$g as aF,vS as aG,AS as aH,ES as aI,IS as aJ,CS as aK,Lc as aL,Dr as aM,fS as aN,NS as aO,_S as aP,Pg as aQ,xg as aR,ch as aS,Al as aT,Fg as aU,Mi as aV,$i as aW,yg as aX,sh as aY,ug as aZ,dg as a_,lg as aa,rh as ab,nh as ac,gS as ad,ra as ae,pS as af,hg as ag,Sn as ah,Dc as ai,mS as aj,yo as ak,wS as al,ir as am,Xr as an,ih as ao,Mc as ap,Eg as aq,Cg as ar,Ig as as,Ag as at,Ng as au,_g as av,Sg as aw,Tg as ax,Og as ay,kg as az,H as b,hi as b0,di as b1,ui as b2,ri as b3,ci as b4,Jr as b5,Gr as b6,ei as b7,ar as b8,Yr as b9,vn as ba,zr as bb,ni as bc,Pt as bd,Zr as be,Qr as bf,Ct as bg,ii as bh,or as bi,ti as bj,li as bk,vg as bl,ai as bm,oi as bn,si as bo,Tn as bp,Wg as bq,cg as br,Mg as bs,dT as bt,D as c,iT as d,aT as e,Ft as f,Ba as g,uh as h,po as i,uT as j,Pn as k,Ts as l,we as m,m as n,Gn as o,x as p,Ge as q,lT as r,Qs as s,Vt as t,Re as u,Wt as v,oT as w,Os as x,fm as y,_t as z};