@dcl/auth-site 4.11.8-22578122545.commit-e9eeb71 → 4.11.8-22595822532.commit-afd96dd

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 (101) hide show
  1. package/assets/{ConstantsUtil-Beb771Re.js → ConstantsUtil-IDdlcd1R.js} +1 -1
  2. package/assets/{ContentfulRichText-BT_jiRkj.js → ContentfulRichText-D4aBlOCS.js} +1 -1
  3. package/assets/{ExchangeController-CZUQfoIt.js → ExchangeController-CdNMWCFY.js} +1 -1
  4. package/assets/{HelpersUtil-C11O2AAO.js → HelpersUtil-C-tF-mFe.js} +1 -1
  5. package/assets/NetworkUtil-B_5naIJv.js +2 -0
  6. package/assets/{SwapController-DMXY5k5Q.js → SwapController-C22Z0wcW.js} +1 -1
  7. package/assets/{biconomy-dpT8cHxB.js → biconomy-CsbeHKGc.js} +1 -1
  8. package/assets/ccip-Ck_6HlbQ.js +1 -0
  9. package/assets/{data-capture-CpiGUgey.js → data-capture-CsxiqOap.js} +1 -1
  10. package/assets/{email-oX_m7Aa-.js → email-fUFAiT2-.js} +1 -1
  11. package/assets/{embedded-wallet-Bl5i1CVx.js → embedded-wallet-ByhNQW_m.js} +1 -1
  12. package/assets/{engine-Di0gkU--.js → engine-D-Ovp2TM.js} +1 -1
  13. package/assets/extractIPFS-CLKrpjwD.js +1 -0
  14. package/assets/{features-BazuRuhR.js → features-CWGDlAbL.js} +2 -2
  15. package/assets/fortmatic-dqMA7imt.js +13 -0
  16. package/assets/{getInstalledModules-4RtkG0t3.js → getInstalledModules-I7ouqKHk.js} +1 -1
  17. package/assets/{if-defined-abRe-w5Z.js → if-defined-CX592d7e.js} +1 -1
  18. package/assets/in-app-wallet-calls-BojXfO-N.js +1 -0
  19. package/assets/index-889I9oIL.js +4 -0
  20. package/assets/{index-BlqsQpQi.js → index-B-_eFHsW.js} +159 -135
  21. package/assets/index-B5bQO_5Q.js +2 -0
  22. package/assets/{index-CqzZX9DL.js → index-BC8kwCHT.js} +1 -1
  23. package/assets/{index-PGvg6u0E.js → index-BFxczUld.js} +1 -1
  24. package/assets/{index-9QU7SDcQ.css → index-BLCMf4Dl.css} +1 -1
  25. package/assets/{index-CtjRZuR4.js → index-BQomJqTo.js} +1 -1
  26. package/assets/{index-B0_tUN9P.js → index-BSjmiClU.js} +1 -1
  27. package/assets/index-BWLwEJXK.js +42 -0
  28. package/assets/{index-DouYiF09.js → index-BZVL4XGs.js} +1 -1
  29. package/assets/{index-a1X8Ebvm.js → index-BmFli_oI.js} +1 -1
  30. package/assets/{index-CeEwMUyg.js → index-Bqa3GYNx.js} +1 -1
  31. package/assets/{index-DqO1Z0lD.js → index-CGtyOtb5.js} +1 -1
  32. package/assets/{index-D0RY8YDZ.js → index-CIdBLhTD.js} +1 -1
  33. package/assets/{index-89tjUcEb.js → index-Cb7OJiUx.js} +1 -1
  34. package/assets/{index-vqOTS2d-.js → index-CfV4oumQ.js} +1 -1
  35. package/assets/{index-CyzXlQ91.js → index-Cu7g55gd.js} +1 -1
  36. package/assets/{index-BWIXvCB5.js → index-CwgUmhAO.js} +1 -1
  37. package/assets/{index-BwvA90bd.js → index-CxrHy176.js} +1 -1
  38. package/assets/{index-B6TdJyIm.js → index-CyQsNS2n.js} +1 -1
  39. package/assets/{index-DeOIg2Dk.js → index-D2Kun0LZ.js} +1 -1
  40. package/assets/{index-DNzCjATa.js → index-D4mhVfJ7.js} +1 -1
  41. package/assets/{index-CAlOjqpf.js → index-D756ZP2E.js} +1 -1
  42. package/assets/{index-DV--vmXV.js → index-DGiPcc80.js} +1 -1
  43. package/assets/{index-BLzSiw0W.js → index-DYhRHUaQ.js} +1 -1
  44. package/assets/index-DbFP4sQZ.js +14 -0
  45. package/assets/{index-2TE95rJd.js → index-DrVuM1V8.js} +1 -1
  46. package/assets/{index-BZ3jIFM2.js → index-DsAAirdR.js} +1 -1
  47. package/assets/{index-BVZ_AL9I.js → index-DtYhmtF7.js} +1 -1
  48. package/assets/{index-DQNENbqo.js → index-Dv-Wyp9h.js} +1 -1
  49. package/assets/{index-BoXw98h4.js → index-Dz4wl94s.js} +1 -1
  50. package/assets/{index-VAkQawUc.js → index-GhwyMHy6.js} +1 -1
  51. package/assets/index-IPnwlwFJ.js +251 -0
  52. package/assets/{index-Dz4T9To4.js → index-Ptgsp97-.js} +1 -1
  53. package/assets/{index-CapZ79aD.js → index-VteGn-Hg.js} +1 -1
  54. package/assets/index-WkSlxog0.js +7 -0
  55. package/assets/{index-Dpr_P0ct.js → index-_oohqe1q.js} +1 -1
  56. package/assets/{index-Cj4wfhJc.js → index-oScHGSy6.js} +1 -1
  57. package/assets/{index-D5H4cP2T.js → index-rdqbhPin.js} +1 -1
  58. package/assets/{index-D4mhlXGJ.js → index-s8aUs3iQ.js} +1 -1
  59. package/assets/{index-1VtD7CLy.js → index-uVpOzjx_.js} +1 -1
  60. package/assets/networks-w0_eLt2M.js +38 -0
  61. package/assets/{onramp-D3_7ZL82.js → onramp-DNtmpA6Y.js} +1 -1
  62. package/assets/{openzeppelin-tu2wkN5F.js → openzeppelin-BVmZw860.js} +1 -1
  63. package/assets/{parse-typed-data-DrWxA1Px.js → parse-typed-data-Bz7EM74g.js} +1 -1
  64. package/assets/{passkeys-Bd71fvAp.js → passkeys-DNsQ_KOr.js} +1 -1
  65. package/assets/{pay-with-exchange-S8VsI0Gz.js → pay-with-exchange-COuzct72.js} +1 -1
  66. package/assets/{receive-CssfsmCg.js → receive-DJ-kCiiX.js} +1 -1
  67. package/assets/{ref-CpaAsnTm.js → ref-4FoIik5B.js} +1 -1
  68. package/assets/{resolveImplementation-ChAPi7Ai.js → resolveImplementation-CWTRQlvf.js} +1 -1
  69. package/assets/{secp256k1-D2tq2LcV.js → secp256k1-j5B89ek6.js} +1 -1
  70. package/assets/{send-Dn_R4Z4B.js → send-BGQ3IUrv.js} +1 -1
  71. package/assets/send-eip712-transaction-b1J3Gfv4.js +1 -0
  72. package/assets/{send-gasless-transaction-D2BATGmB.js → send-gasless-transaction-CG-7Oc6z.js} +2 -2
  73. package/assets/sha256-D6ei3Af4.js +1 -0
  74. package/assets/{socials-4QsnsTEq.js → socials-Cx5_uD8B.js} +1 -1
  75. package/assets/{swaps-wkdldL9M.js → swaps-BQNZs4oR.js} +1 -1
  76. package/assets/thirdweb-CozZI4bW.js +20 -0
  77. package/assets/{transactions-On-0hU_2.js → transactions-4STPUm57.js} +1 -1
  78. package/assets/ui-CqQlCpnD.js +762 -0
  79. package/assets/vendor-CE6cyrlI.js +59 -0
  80. package/assets/{w3m-modal-CXj2S6eL.js → w3m-modal-HqHeH3Ma.js} +1 -1
  81. package/assets/web-connector-Dc49-8eH.js +9 -0
  82. package/index.html +5 -5
  83. package/package.json +7 -7
  84. package/assets/NetworkUtil-BR1fA1nY.js +0 -7
  85. package/assets/ccip-sVcQHIcW.js +0 -1
  86. package/assets/extractIPFS-1dJDs4wc.js +0 -1
  87. package/assets/fortmatic-GmT951Dh.js +0 -13
  88. package/assets/in-app-wallet-calls-CwNOCAlj.js +0 -1
  89. package/assets/index-666qfDL3.js +0 -14
  90. package/assets/index-DmglfVgc.js +0 -7
  91. package/assets/index-XCBP3gpR.js +0 -3
  92. package/assets/index-kL5rdP6y.js +0 -248
  93. package/assets/index-lj-K-ZzU.js +0 -4
  94. package/assets/index-uhBF7NYr.js +0 -2
  95. package/assets/networks-i3C3SWYo.js +0 -4
  96. package/assets/send-eip712-transaction-B28ux6z7.js +0 -1
  97. package/assets/thirdweb--fgBAAk6.js +0 -20
  98. package/assets/ui-BgRic9u_.js +0 -762
  99. package/assets/vendor-Cd_4SrvV.js +0 -59
  100. package/assets/verifyHash-mxdlcflY.js +0 -35
  101. package/assets/web-connector-DX5MbV8B.js +0 -9
@@ -0,0 +1,251 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BWLwEJXK.js","assets/NetworkUtil-B_5naIJv.js","assets/thirdweb-CozZI4bW.js","assets/sha256-D6ei3Af4.js","assets/index-B-_eFHsW.js","assets/ui-CqQlCpnD.js","assets/vendor-CE6cyrlI.js","assets/index-BLCMf4Dl.css","assets/features-CWGDlAbL.js","assets/embedded-wallet-ByhNQW_m.js","assets/index-GhwyMHy6.js","assets/index-DtYhmtF7.js","assets/if-defined-CX592d7e.js","assets/ref-4FoIik5B.js","assets/index-rdqbhPin.js","assets/HelpersUtil-C-tF-mFe.js","assets/ConstantsUtil-IDdlcd1R.js","assets/index-Dz4wl94s.js","assets/index-CGtyOtb5.js","assets/index-DrVuM1V8.js","assets/index-DsAAirdR.js","assets/index-CIdBLhTD.js","assets/NavigationUtil-DmfK5sOV.js","assets/email-fUFAiT2-.js","assets/index-BQomJqTo.js","assets/index-CwgUmhAO.js","assets/socials-Cx5_uD8B.js","assets/index-oScHGSy6.js","assets/index-BZVL4XGs.js","assets/index-DYhRHUaQ.js","assets/index-uVpOzjx_.js","assets/index-VteGn-Hg.js","assets/swaps-BQNZs4oR.js","assets/index-D2Kun0LZ.js","assets/index-BFxczUld.js","assets/SwapController-C22Z0wcW.js","assets/index-D4mhVfJ7.js","assets/send-BGQ3IUrv.js","assets/index-CyQsNS2n.js","assets/index-CxrHy176.js","assets/index-Bqa3GYNx.js","assets/index-Ptgsp97-.js","assets/receive-DJ-kCiiX.js","assets/onramp-DNtmpA6Y.js","assets/index-BmFli_oI.js","assets/index-BSjmiClU.js","assets/index-D756ZP2E.js","assets/pay-with-exchange-COuzct72.js","assets/ExchangeController-CdNMWCFY.js","assets/transactions-4STPUm57.js","assets/index-CfV4oumQ.js","assets/index-DGiPcc80.js","assets/index-Cu7g55gd.js","assets/index-BC8kwCHT.js","assets/index-_oohqe1q.js","assets/data-capture-CsxiqOap.js","assets/index-Cb7OJiUx.js","assets/index-s8aUs3iQ.js","assets/w3m-modal-HqHeH3Ma.js"])))=>i.map(i=>d[i]);
2
+ import{p as vn,g as Sy,_ as Dt,an as Iy}from"./thirdweb-CozZI4bW.js";import{C as $,A as Af,N as Sf,k as Ny,a as Ty,r as Ry,h as Oy,c as Py,s as xy,t as Nu}from"./NetworkUtil-B_5naIJv.js";import{z as ky,A as io,B as pa,E as Ya,F as Uy,G as $y,J as Dy,K as Ly,L as My,M as Tu,N as Ai,O as By,P as As,Q as Qt,U as Z,V as In,X as jy,Y as Fy,Z as Yi,_ as Wl,$ as Si,a0 as qy,a1 as Wy,a2 as Hy,a3 as Mr,a4 as zy,a5 as Ks,a6 as Ii,a7 as Wd,a8 as Vy,a9 as Hd,aa as zd,ab as oo,ac as Vd,ad as Ru,ae as Ky,af as Gy,ag as mr,ah as If,ai as dn,aj as Vs,ak as Rn,al as Nf}from"./index-B-_eFHsW.js";import{a as Pe,g as Ce}from"./ui-CqQlCpnD.js";const Tf={isLowerCaseMatch(t,e){return(t==null?void 0:t.toLowerCase())===(e==null?void 0:e.toLowerCase())}};var Yy=20,Zy=1,Or=1e6,Ou=1e6,Jy=-7,Xy=21,Qy=!1,Qo="[big.js] ",Br=Qo+"Invalid ",Sc=Br+"decimal places",ew=Br+"rounding mode",Rf=Qo+"Division by zero",qe={},Xs=void 0,tw=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Of(){function t(e){var s=this;if(!(s instanceof t))return e===Xs?Of():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(Br+"value");e=e===0&&1/e<0?"-0":String(e)}sw(s,e)}s.constructor=t}return t.prototype=qe,t.DP=Yy,t.RM=Zy,t.NE=Jy,t.PE=Xy,t.strict=Qy,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function sw(t,e){var s,n,r;if(!tw.test(e))throw Error(Br+"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 jr(t,e,s,n){var r=t.c;if(s===Xs&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(ew);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]!==Xs))),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]!==Xs||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 Fr(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}qe.abs=function(){var t=new this.constructor(this);return t.s=1,t};qe.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};qe.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>Or)throw Error(Sc);if(!r[0])throw Error(Rf);if(!n[0])return t.s=i,t.c=[t.e=0],t;var a,c,l,d,u,h=r.slice(),p=a=r.length,g=n.length,f=n.slice(0,a),w=f.length,v=t,N=v.c=[],A=0,_=o+(v.e=e.e-t.e)+1;for(v.s=i,i=_<0?0:_,h.unshift(0);w++<a;)f.push(0);do{for(l=0;l<10;l++){if(a!=(w=f.length))d=a>w?1:-1;else for(u=-1,d=0;++u<a;)if(r[u]!=f[u]){d=r[u]>f[u]?1:-1;break}if(d<0){for(c=w==a?r:h;w;){if(f[--w]<c[w]){for(u=w;u&&!f[--u];)f[u]=9;--f[u],f[w]+=10}f[w]-=c[w]}for(;!f[0];)f.shift()}else break}N[A++]=d?l:++l,f[0]&&d?f[w]=n[p]||0:f=[n[p]]}while((p++<g||f[0]!==Xs)&&i--);return!N[0]&&A!=1&&(N.shift(),v.e--,_--),A>_&&jr(v,_,s.RM,f[0]!==Xs),v};qe.eq=function(t){return this.cmp(t)===0};qe.gt=function(t){return this.cmp(t)>0};qe.gte=function(t){return this.cmp(t)>-1};qe.lt=function(t){return this.cmp(t)<0};qe.lte=function(t){return this.cmp(t)<1};qe.minus=qe.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(),d=i.e,u=t.c,h=t.e;if(!l[0]||!u[0])return u[0]?t.s=-c:l[0]?t=new o(i):t.s=1,t;if(a=d-h){for((r=a<0)?(a=-a,n=l):(h=d,n=u),n.reverse(),c=a;c--;)n.push(0);n.reverse()}else for(s=((r=l.length<u.length)?l:u).length,a=c=0;c<s;c++)if(l[c]!=u[c]){r=l[c]<u[c];break}if(r&&(n=l,l=u,u=n,t.s=-t.s),(c=(s=u.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;s>a;){if(l[--s]<u[s]){for(e=s;e&&!l[--e];)l[e]=9;--l[e],l[s]+=10}l[s]-=u[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};qe.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(Rf);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)))};qe.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};qe.plus=qe.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};qe.pow=function(t){var e=this,s=new e.constructor("1"),n=s,r=t<0;if(t!==~~t||t<-Ou||t>Ou)throw Error(Br+"exponent");for(r&&(t=-t);t&1&&(n=n.times(e)),t>>=1,!!t;)e=e.times(e);return r?s.div(n):n};qe.prec=function(t,e){if(t!==~~t||t<1||t>Or)throw Error(Br+"precision");return jr(new this.constructor(this),t,e)};qe.round=function(t,e){if(t===Xs)t=0;else if(t!==~~t||t<-Or||t>Or)throw Error(Sc);return jr(new this.constructor(this),t+this.e+1,e)};qe.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(Qo+"No square root");i=Math.sqrt(+Fr(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 jr(t,(r.DP-=4)+t.e+1,r.RM)};qe.times=qe.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};qe.toExponential=function(t,e){var s=this,n=s.c[0];if(t!==Xs){if(t!==~~t||t<0||t>Or)throw Error(Sc);for(s=jr(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return Fr(s,!0,!!n)};qe.toFixed=function(t,e){var s=this,n=s.c[0];if(t!==Xs){if(t!==~~t||t<0||t>Or)throw Error(Sc);for(s=jr(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return Fr(s,!1,!!n)};qe[Symbol.for("nodejs.util.inspect.custom")]=qe.toJSON=qe.toString=function(){var t=this,e=t.constructor;return Fr(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};qe.toNumber=function(){var t=+Fr(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(Qo+"Imprecise conversion");return t};qe.toPrecision=function(t,e){var s=this,n=s.constructor,r=s.c[0];if(t!==Xs){if(t!==~~t||t<1||t>Or)throw Error(Br+"precision");for(s=jr(new n(s),t,e);s.c.length<t;)s.c.push(0)}return Fr(s,t<=s.e||s.e<=n.NE||s.e>=n.PE,!!r)};qe.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(Qo+"valueOf disallowed");return Fr(t,t.e<=e.NE||t.e>=e.PE,!0)};var On=Of();const nw={bigNumber(t){return t?new On(t):new On(0)},multiply(t,e){if(t===void 0||e===void 0)return new On(0);const s=new On(t),n=new On(e);return s.times(n)},toFixed(t,e=2){return t===void 0||t===""?new On(0).toFixed(e):new On(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 On(e).toNumber()}},rw=[{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"}]}],iw=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],ow=[{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"}]}],aw={getERC20Abi:t=>$.USDT_CONTRACT_ADDRESSES.includes(t)?ow:rw,getSwapAbi:()=>iw},Hr={ConnectorExplorerIds:{[$.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[$.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[$.CONNECTOR_ID.BASE_ACCOUNT]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[$.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[$.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[$.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[$.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[$.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[$.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[$.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[$.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[$.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[$.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[$.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[$.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[$.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[$.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13",[$.OKX_CONNECTOR_NAME]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[$.BINANCE_CONNECTOR_NAME]:"2fafea35bb471d22889ccb49c08d99dd0a18a37982602c33f696a5723934ba25"}},dt={validateCaipAddress(t){var e;if(((e=t.split(":"))==null?void 0:e.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}}},wn={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(wn.isRpcProviderError(t)){const e=t.code===wn.RPC_ERROR_CODE.USER_REJECTED_REQUEST,s=t.code===wn.RPC_ERROR_CODE.USER_REJECTED_METHODS;return e||s||wn.isUserRejectedMessage(t.message)}return t instanceof Error?wn.isUserRejectedMessage(t.message):!1}};let cw=class extends Error{constructor(e,s){super(s.message,{cause:e}),this.name=wn.PROVIDER_RPC_ERROR_NAME.PROVIDER_RPC,this.code=s.code}},Pf=class extends cw{constructor(e){super(e,{code:wn.RPC_ERROR_CODE.USER_REJECTED_REQUEST,message:"User rejected the request"}),this.name=wn.PROVIDER_RPC_ERROR_NAME.USER_REJECTED_REQUEST}};const le={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",TON_WALLETS_CACHE:"@appkit/ton_wallets_cache"};function zc(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const ae={setItem(t,e){Wi()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(Wi())return localStorage.getItem(t)||void 0},removeItem(t){Wi()&&localStorage.removeItem(t)},clear(){Wi()&&localStorage.clear()}};function Wi(){return typeof window<"u"&&typeof localStorage<"u"}function ao(t,e){const s=(t==null?void 0:t["--apkt-accent"])??(t==null?void 0:t["--w3m-accent"]);return e==="light"?{"--w3m-accent":s||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":s||"hsla(230, 100%, 67%, 1)","--w3m-background":"#202020"}}const lw=Symbol(),Pu=Object.getPrototypeOf,Hl=new WeakMap,dw=t=>t&&(Hl.has(t)?Hl.get(t):Pu(t)===Object.prototype||Pu(t)===Array.prototype),uw=t=>dw(t)&&t[lw]||null,xu=(t,e=!0)=>{Hl.set(t,e)},Za={},Kd=t=>typeof t=="object"&&t!==null,hw=t=>Kd(t)&&!ea.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),xf=(t,e)=>{const s=zl.get(t);if((s==null?void 0:s[0])===e)return s[1];const n=Array.isArray(t)?[]:Object.create(Object.getPrototypeOf(t));return xu(n,!0),zl.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(ea.has(i))xu(i,!1);else if(Jn.has(i)){const[c,l]=Jn.get(i);a.value=xf(c,l())}Object.defineProperty(n,r,a)}),Object.preventExtensions(n)},pw=(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&&(ku(l,o)||co.has(o)&&ku(l,co.get(o))))return!0;s(i),Kd(o)&&(o=uw(o)||o);const d=!Jn.has(o)&&gw(o)?Ge(o):o;return e(i,d),Reflect.set(r,i,d,a),n(["set",[i],o,l]),!0}}),Jn=new WeakMap,ea=new WeakSet,zl=new WeakMap,Ma=[1],co=new WeakMap;let ku=Object.is,fw=(t,e)=>new Proxy(t,e),gw=hw,mw=xf,yw=pw;function Ge(t={}){if(!Kd(t))throw new Error("object required");const e=co.get(t);if(e)return e;let s=Ma[0];const n=new Set,r=(w,v=++Ma[0])=>{s!==v&&(i=s=v,n.forEach(N=>N(w,v)))};let i=s;const o=(w=Ma[0])=>(i!==w&&(i=w,c.forEach(([v])=>{const N=v[1](w);N>s&&(s=N)})),s),a=w=>(v,N)=>{const A=[...v];A[1]=[w,...A[1]],r(A,N)},c=new Map,l=(w,v)=>{const N=!ea.has(v)&&Jn.get(v);if(N){if((Za?"production":void 0)!=="production"&&c.has(w))throw new Error("prop listener already exists");if(n.size){const A=N[2](a(w));c.set(w,[N,A])}else c.set(w,[N])}},d=w=>{var v;const N=c.get(w);N&&(c.delete(w),(v=N[1])==null||v.call(N))},u=w=>(n.add(w),n.size===1&&c.forEach(([N,A],_)=>{if((Za?"production":void 0)!=="production"&&A)throw new Error("remove already exists");const P=N[2](a(_));c.set(_,[N,P])}),()=>{n.delete(w),n.size===0&&c.forEach(([N,A],_)=>{A&&(A(),c.set(_,[N]))})});let h=!0;const p=yw(()=>h,l,d,r),g=fw(t,p);co.set(t,g);const f=[t,o,u];return Jn.set(g,f),Reflect.ownKeys(t).forEach(w=>{const v=Object.getOwnPropertyDescriptor(t,w);"value"in v&&v.writable&&(g[w]=t[w])}),h=!1,g}function _t(t,e,s){const n=Jn.get(t);(Za?"production":void 0)!=="production"&&!n&&console.warn("Please use proxy object");let r;const i=[],o=n[2];let a=!1;const l=o(d=>{i.push(d),r||(r=Promise.resolve().then(()=>{r=void 0,a&&e(i.splice(0))}))});return a=!0,()=>{a=!1,l()}}function lo(t){const e=Jn.get(t);(Za?"production":void 0)!=="production"&&!e&&console.warn("Please use proxy object");const[s,n]=e;return mw(s,n())}function uo(t){return ea.add(t),t}function ww(){return{proxyStateMap:Jn,refSet:ea,snapCache:zl,versionHolder:Ma,proxyCache:co}}function At(t,e,s,n){let r=t[e];return _t(t,()=>{const i=t[e];Object.is(r,i)||s(r=i)})}const{proxyStateMap:Ew,snapCache:bw}=ww(),fa=t=>Ew.has(t);function vw(t){const e=[];let s=0;const n=new Map,r=new WeakMap,i=()=>{const l=bw.get(a),d=l==null?void 0:l[1];if(d&&!r.has(d)){const u=new Map(n);r.set(d,u)}},o=l=>r.get(l)||n,a={data:e,index:s,epoch:0,get size(){return fa(this)||i(),o(this).size},get(l){const u=o(this).get(l);if(u===void 0){this.epoch;return}return this.data[u]},has(l){const d=o(this);return this.epoch,d.has(l)},set(l,d){if(!fa(this))throw new Error("Cannot perform mutations on a snapshot");const u=n.get(l);return u===void 0?(n.set(l,this.index),this.data[this.index++]=d):this.data[u]=d,this.epoch++,this},delete(l){if(!fa(this))throw new Error("Cannot perform mutations on a snapshot");const d=n.get(l);return d===void 0?!1:(delete this.data[d],n.delete(l),this.epoch++,!0)},clear(){if(!fa(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((u,h)=>{l(this.data[u],h,this)})},*entries(){this.epoch;const l=o(this);for(const[d,u]of l)yield[d,this.data[u]]},*keys(){this.epoch;const l=o(this);for(const d of l.keys())yield d},*values(){this.epoch;const l=o(this);for(const d of l.values())yield this.data[d]},[Symbol.iterator](){return this.entries()},get[Symbol.toStringTag](){return"Map"},toJSON(){return new Map(this.entries())}},c=Ge(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 Uu={};const Vc=(typeof vn<"u"&&typeof Uu<"u"?Uu.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",kf=[{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],Cw="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",Ne={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:Vc,SECURE_SITE_DASHBOARD:`${Vc}/dashboard`,SECURE_SITE_FAVICON:`${Vc}/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:[$.CHAIN.EVM,$.CHAIN.SOLANA],SEND_PARAMS_SUPPORTED_CHAINS:[$.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:[$.CHAIN.EVM],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:[$.CHAIN.EVM,$.CHAIN.SOLANA],PAY_WITH_EXCHANGE_SUPPORTED_CHAIN_NAMESPACES:[$.CHAIN.EVM,$.CHAIN.SOLANA],ACTIVITY_ENABLED_CHAIN_NAMESPACES:[$.CHAIN.EVM,$.CHAIN.TON],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x",sui:"0x",stacks:"0x",ton:"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:[$.CHAIN.EVM,$.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,headless:!1},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1,emailCapture:!1,reownAuthentication:!1,headless:!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,headless:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa",ton:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"},SIWX_DEFAULTS:{signOutOnDisconnect:!0},MANDATORY_WALLET_IDS_ON_MOBILE:[Hr.ConnectorExplorerIds[$.CONNECTOR_ID.COINBASE],Hr.ConnectorExplorerIds[$.CONNECTOR_ID.COINBASE_SDK],Hr.ConnectorExplorerIds[$.CONNECTOR_ID.BASE_ACCOUNT],Hr.ConnectorExplorerIds[$.SOLFLARE_CONNECTOR_NAME],Hr.ConnectorExplorerIds[$.PHANTOM_CONNECTOR_NAME],Hr.ConnectorExplorerIds[$.BINANCE_CONNECTOR_NAME]],DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"]},F={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5,transactionsHistory:15e3,tokenPrice:15e3,latestAppKitVersion:6048e5,tonWallets:864e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=F.getActiveNamespace(),e=F.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{ae.setItem(le.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=ae.getItem(le.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{ae.removeItem(le.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{ae.setItem(le.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{ae.setItem(le.ACTIVE_CAIP_NETWORK_ID,t),F.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return ae.getItem(le.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{ae.removeItem(le.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=zc(t);ae.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=F.getRecentWallets();e.find(n=>n.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),ae.setItem(le.RECENT_WALLETS,JSON.stringify(e)),ae.setItem(le.RECENT_WALLET,JSON.stringify(t)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=ae.getItem(le.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},getRecentWallet(){try{const t=ae.getItem(le.RECENT_WALLET);return t?JSON.parse(t):null}catch{console.info("Unable to get AppKit recent")}return null},deleteRecentWallet(){try{ae.removeItem(le.RECENT_WALLET)}catch{console.info("Unable to delete AppKit recent")}},setConnectedConnectorId(t,e){try{const s=zc(t);ae.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return ae.getItem(le.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=zc(t);return ae.getItem(e)}catch{console.info("Unable to get connected connector id in namespace",t)}},setConnectedSocialProvider(t){try{ae.setItem(le.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return ae.getItem(le.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{ae.removeItem(le.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return ae.getItem(le.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){var s;const t=ae.getItem(le.ACTIVE_CAIP_NETWORK_ID);return(s=t==null?void 0:t.split(":"))==null?void 0:s[1]},setConnectionStatus(t){try{ae.setItem(le.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return ae.getItem(le.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=ae.getItem(le.CONNECTED_NAMESPACES);return t!=null&&t.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));ae.setItem(le.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=F.getConnectedNamespaces();e.includes(t)||(e.push(t),F.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=F.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),F.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return ae.getItem(le.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{ae.setItem(le.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{ae.removeItem(le.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=ae.getItem(le.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=F.getBalanceCache();ae.setItem(le.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=F.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;F.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=F.getBalanceCache();e[t.caipAddress]=t,ae.setItem(le.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=ae.getItem(le.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=F.getBalanceCache();ae.setItem(le.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=F.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),F.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=F.getNativeBalanceCache();e[t.caipAddress]=t,ae.setItem(le.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=ae.getItem(le.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const s=F.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;F.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=F.getEnsCache();e[t.address]=t,ae.setItem(le.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=F.getEnsCache();ae.setItem(le.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=ae.getItem(le.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=F.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;F.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=F.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},ae.setItem(le.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=F.getIdentityCache();ae.setItem(le.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},getTonWalletsCache(){try{const t=ae.getItem(le.TON_WALLETS_CACHE),e=t?JSON.parse(t):void 0;if(e&&!this.isCacheExpired(e.timestamp,this.cacheExpiry.tonWallets))return e;F.removeTonWalletsCache()}catch{console.info("Unable to get ton wallets cache")}},updateTonWalletsCache(t){try{const e=F.getTonWalletsCache()||{timestamp:0,wallets:[]};e.timestamp=new Date().getTime(),e.wallets=t,ae.setItem(le.TON_WALLETS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ton wallets cache",t)}},removeTonWalletsCache(){try{ae.removeItem(le.TON_WALLETS_CACHE)}catch{console.info("Unable to remove ton wallets cache")}},clearAddressCache(){try{ae.removeItem(le.PORTFOLIO_CACHE),ae.removeItem(le.NATIVE_BALANCE_CACHE),ae.removeItem(le.ENS_CACHE),ae.removeItem(le.IDENTITY_CACHE),ae.removeItem(le.HISTORY_TRANSACTIONS_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{ae.setItem(le.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=ae.getItem(le.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s=F.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===$.CONNECTOR_ID.AUTH;if(a&&!c){const l=new Set(a.accounts.map(u=>u.address.toLowerCase())),d=o.accounts.filter(u=>!l.has(u.address.toLowerCase()));a.accounts.push(...d)}else r.set(o.connectorId,{...o})}const i={...s,[e]:Array.from(r.values())};ae.setItem(le.CONNECTIONS,JSON.stringify(i))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=ae.getItem(le.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=F.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())})),ae.setItem(le.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=ae.getItem(le.DISCONNECTED_CONNECTOR_IDS);return t?JSON.parse(t):{}}catch{console.info("Unable to get disconnected connector ids")}return{}},addDisconnectedConnectorId(t,e){try{const s=F.getDisconnectedConnectorIds(),n=s[e]??[];n.push(t),ae.setItem(le.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=F.getDisconnectedConnectorIds();let n=s[e]??[];n=n.filter(r=>r.toLowerCase()!==t.toLowerCase()),ae.setItem(le.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(F.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=ae.getItem(le.HISTORY_TRANSACTIONS_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get transactions cache")}return{}},getTransactionsCacheForAddress({address:t,chainId:e=""}){var s;try{const r=(s=F.getTransactionsCache()[t])==null?void 0:s[e];if(r&&!this.isCacheExpired(r.timestamp,this.cacheExpiry.transactionsHistory))return r.transactions;F.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=F.getTransactionsCache();r[t]={...r[t],[e]:{timestamp:s,transactions:n}},ae.setItem(le.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=F.getTransactionsCache(),n=(s==null?void 0:s[t])||{},{[e]:r,...i}=n;ae.setItem(le.HISTORY_TRANSACTIONS_CACHE,JSON.stringify({...s,[t]:i}))}catch{console.info("Unable to remove transactions cache",{address:t,chainId:e})}},getTokenPriceCache(){try{const t=ae.getItem(le.TOKEN_PRICE_CACHE);return t?JSON.parse(t):{}}catch{console.info("Unable to get token price cache")}return{}},getTokenPriceCacheForAddresses(t){try{const s=F.getTokenPriceCache()[t.join(",")];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.tokenPrice))return s.tokenPrice;F.removeTokenPriceCache(t)}catch{console.info("Unable to get token price cache for addresses",t)}},updateTokenPriceCache(t){try{const e=F.getTokenPriceCache();e[t.addresses.join(",")]={timestamp:t.timestamp,tokenPrice:t.tokenPrice},ae.setItem(le.TOKEN_PRICE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update token price cache",t)}},removeTokenPriceCache(t){try{const e=F.getTokenPriceCache();ae.setItem(le.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==null?void 0: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=ae.getItem(le.LATEST_APPKIT_VERSION);return t?JSON.parse(t):{}}catch{console.info("Unable to get latest AppKit version cache")}return{}},updateLatestAppKitVersion(t){try{const e=F.getLatestAppKitVersionCache();e.timestamp=t.timestamp,e.version=t.version,ae.setItem(le.LATEST_APPKIT_VERSION,JSON.stringify(e))}catch{console.info("Unable to update latest AppKit version on local storage",t)}}},X={getWindow(){if(!(typeof window>"u"))return window},isMobile(){var t;return this.isClient()?!!(window!=null&&window.matchMedia&&typeof window.matchMedia=="function"&&((t=window.matchMedia("(pointer:coarse)"))!=null&&t.matches)||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t==null?void 0:t.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return X.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window==null?void 0:window.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=Ne.TEN_SEC_MS:!0},isAllowedRetry(t,e=Ne.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return(window==null?void 0:window.self)!==(window==null?void 0:window.top)}catch{return!1}},isSafeApp(){var t,e;if(X.isClient()&&window.self!==window.top)try{const s=(e=(t=window==null?void 0:window.location)==null?void 0:t.ancestorOrigins)==null?void 0:e[0],n="https://app.safe.global";if(s){const r=new URL(s),i=new URL(n);return r.hostname===i.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Ne.FOUR_MINUTES_MS},getNetworkId(t){return t==null?void 0:t.split(":")[1]},getPlainAddress(t){return t==null?void 0: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(X.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!=null&&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(!X.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()?F.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window==null||window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window==null?void 0:window.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){var s,n;if(typeof window>"u")return!1;const t=window!=null&&window.matchMedia&&typeof window.matchMedia=="function"?(s=window.matchMedia("(display-mode: standalone)"))==null?void 0:s.matches:!1,e=(n=window==null?void 0:window.navigator)==null?void 0:n.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,X.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 $.W3M_API_URL},getBlockchainApiUrl(){return $.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return $.PULSE_API_URL},getUUID(){return 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)})},parseError(t){var e,s;return typeof t=="string"?t:typeof((s=(e=t==null?void 0:t.issues)==null?void 0:e[0])==null?void 0:s.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?Ne.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 $.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==null?void 0:window.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window==null?void 0: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),d=c+s;return a+d+l}};var pi={};const _w="https://secure.walletconnect.org/sdk",Aw=(typeof vn<"u"&&typeof pi<"u"?pi.NEXT_PUBLIC_SECURE_SITE_SDK_URL:void 0)||_w,Sw=(typeof vn<"u"&&typeof pi<"u"?pi.NEXT_PUBLIC_DEFAULT_LOG_LEVEL:void 0)||"error",Iw=(typeof vn<"u"&&typeof pi<"u"?pi.NEXT_PUBLIC_SECURE_SITE_SDK_VERSION:void 0)||"4",oe={APP_EVENT_KEY:"@w3m-app/",FRAME_EVENT_KEY:"@w3m-frame/",RPC_METHOD_KEY:"RPC_",STORAGE_KEY:"@appkit-wallet/",SESSION_TOKEN_KEY:"SESSION_TOKEN_KEY",EMAIL_LOGIN_USED_KEY:"EMAIL_LOGIN_USED_KEY",LAST_USED_CHAIN_KEY:"LAST_USED_CHAIN_KEY",LAST_EMAIL_LOGIN_TIME:"LAST_EMAIL_LOGIN_TIME",EMAIL:"EMAIL",PREFERRED_ACCOUNT_TYPE:"PREFERRED_ACCOUNT_TYPE",SMART_ACCOUNT_ENABLED:"SMART_ACCOUNT_ENABLED",SMART_ACCOUNT_ENABLED_NETWORKS:"SMART_ACCOUNT_ENABLED_NETWORKS",SOCIAL_USERNAME:"SOCIAL_USERNAME",APP_SWITCH_NETWORK:"@w3m-app/SWITCH_NETWORK",APP_CONNECT_EMAIL:"@w3m-app/CONNECT_EMAIL",APP_CONNECT_DEVICE:"@w3m-app/CONNECT_DEVICE",APP_CONNECT_OTP:"@w3m-app/CONNECT_OTP",APP_CONNECT_SOCIAL:"@w3m-app/CONNECT_SOCIAL",APP_GET_SOCIAL_REDIRECT_URI:"@w3m-app/GET_SOCIAL_REDIRECT_URI",APP_GET_USER:"@w3m-app/GET_USER",APP_SIGN_OUT:"@w3m-app/SIGN_OUT",APP_IS_CONNECTED:"@w3m-app/IS_CONNECTED",APP_GET_CHAIN_ID:"@w3m-app/GET_CHAIN_ID",APP_RPC_REQUEST:"@w3m-app/RPC_REQUEST",APP_UPDATE_EMAIL:"@w3m-app/UPDATE_EMAIL",APP_UPDATE_EMAIL_PRIMARY_OTP:"@w3m-app/UPDATE_EMAIL_PRIMARY_OTP",APP_UPDATE_EMAIL_SECONDARY_OTP:"@w3m-app/UPDATE_EMAIL_SECONDARY_OTP",APP_AWAIT_UPDATE_EMAIL:"@w3m-app/AWAIT_UPDATE_EMAIL",APP_SYNC_THEME:"@w3m-app/SYNC_THEME",APP_SYNC_DAPP_DATA:"@w3m-app/SYNC_DAPP_DATA",APP_GET_SMART_ACCOUNT_ENABLED_NETWORKS:"@w3m-app/GET_SMART_ACCOUNT_ENABLED_NETWORKS",APP_INIT_SMART_ACCOUNT:"@w3m-app/INIT_SMART_ACCOUNT",APP_SET_PREFERRED_ACCOUNT:"@w3m-app/SET_PREFERRED_ACCOUNT",APP_CONNECT_FARCASTER:"@w3m-app/CONNECT_FARCASTER",APP_GET_FARCASTER_URI:"@w3m-app/GET_FARCASTER_URI",APP_RELOAD:"@w3m-app/RELOAD",APP_RPC_ABORT:"@w3m-app/RPC_ABORT",FRAME_SWITCH_NETWORK_ERROR:"@w3m-frame/SWITCH_NETWORK_ERROR",FRAME_SWITCH_NETWORK_SUCCESS:"@w3m-frame/SWITCH_NETWORK_SUCCESS",FRAME_CONNECT_EMAIL_ERROR:"@w3m-frame/CONNECT_EMAIL_ERROR",FRAME_CONNECT_EMAIL_SUCCESS:"@w3m-frame/CONNECT_EMAIL_SUCCESS",FRAME_CONNECT_DEVICE_ERROR:"@w3m-frame/CONNECT_DEVICE_ERROR",FRAME_CONNECT_DEVICE_SUCCESS:"@w3m-frame/CONNECT_DEVICE_SUCCESS",FRAME_CONNECT_OTP_SUCCESS:"@w3m-frame/CONNECT_OTP_SUCCESS",FRAME_CONNECT_OTP_ERROR:"@w3m-frame/CONNECT_OTP_ERROR",FRAME_CONNECT_SOCIAL_SUCCESS:"@w3m-frame/CONNECT_SOCIAL_SUCCESS",FRAME_CONNECT_SOCIAL_ERROR:"@w3m-frame/CONNECT_SOCIAL_ERROR",FRAME_CONNECT_FARCASTER_SUCCESS:"@w3m-frame/CONNECT_FARCASTER_SUCCESS",FRAME_CONNECT_FARCASTER_ERROR:"@w3m-frame/CONNECT_FARCASTER_ERROR",FRAME_GET_FARCASTER_URI_SUCCESS:"@w3m-frame/GET_FARCASTER_URI_SUCCESS",FRAME_GET_FARCASTER_URI_ERROR:"@w3m-frame/GET_FARCASTER_URI_ERROR",FRAME_GET_SOCIAL_REDIRECT_URI_SUCCESS:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_SUCCESS",FRAME_GET_SOCIAL_REDIRECT_URI_ERROR:"@w3m-frame/GET_SOCIAL_REDIRECT_URI_ERROR",FRAME_GET_USER_SUCCESS:"@w3m-frame/GET_USER_SUCCESS",FRAME_GET_USER_ERROR:"@w3m-frame/GET_USER_ERROR",FRAME_SIGN_OUT_SUCCESS:"@w3m-frame/SIGN_OUT_SUCCESS",FRAME_SIGN_OUT_ERROR:"@w3m-frame/SIGN_OUT_ERROR",FRAME_IS_CONNECTED_SUCCESS:"@w3m-frame/IS_CONNECTED_SUCCESS",FRAME_IS_CONNECTED_ERROR:"@w3m-frame/IS_CONNECTED_ERROR",FRAME_GET_CHAIN_ID_SUCCESS:"@w3m-frame/GET_CHAIN_ID_SUCCESS",FRAME_GET_CHAIN_ID_ERROR:"@w3m-frame/GET_CHAIN_ID_ERROR",FRAME_RPC_REQUEST_SUCCESS:"@w3m-frame/RPC_REQUEST_SUCCESS",FRAME_RPC_REQUEST_ERROR:"@w3m-frame/RPC_REQUEST_ERROR",FRAME_SESSION_UPDATE:"@w3m-frame/SESSION_UPDATE",FRAME_UPDATE_EMAIL_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SUCCESS",FRAME_UPDATE_EMAIL_ERROR:"@w3m-frame/UPDATE_EMAIL_ERROR",FRAME_UPDATE_EMAIL_PRIMARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_PRIMARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_PRIMARY_OTP_ERROR",FRAME_UPDATE_EMAIL_SECONDARY_OTP_SUCCESS:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_SUCCESS",FRAME_UPDATE_EMAIL_SECONDARY_OTP_ERROR:"@w3m-frame/UPDATE_EMAIL_SECONDARY_OTP_ERROR",FRAME_SYNC_THEME_SUCCESS:"@w3m-frame/SYNC_THEME_SUCCESS",FRAME_SYNC_THEME_ERROR:"@w3m-frame/SYNC_THEME_ERROR",FRAME_SYNC_DAPP_DATA_SUCCESS:"@w3m-frame/SYNC_DAPP_DATA_SUCCESS",FRAME_SYNC_DAPP_DATA_ERROR:"@w3m-frame/SYNC_DAPP_DATA_ERROR",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS",FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR:"@w3m-frame/GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR",FRAME_INIT_SMART_ACCOUNT_SUCCESS:"@w3m-frame/INIT_SMART_ACCOUNT_SUCCESS",FRAME_INIT_SMART_ACCOUNT_ERROR:"@w3m-frame/INIT_SMART_ACCOUNT_ERROR",FRAME_SET_PREFERRED_ACCOUNT_SUCCESS:"@w3m-frame/SET_PREFERRED_ACCOUNT_SUCCESS",FRAME_SET_PREFERRED_ACCOUNT_ERROR:"@w3m-frame/SET_PREFERRED_ACCOUNT_ERROR",FRAME_READY:"@w3m-frame/READY",FRAME_RELOAD_SUCCESS:"@w3m-frame/RELOAD_SUCCESS",FRAME_RELOAD_ERROR:"@w3m-frame/RELOAD_ERROR",FRAME_RPC_ABORT_SUCCESS:"@w3m-frame/RPC_ABORT_SUCCESS",FRAME_RPC_ABORT_ERROR:"@w3m-frame/RPC_ABORT_ERROR",RPC_RESPONSE_TYPE_ERROR:"RPC_RESPONSE_ERROR",RPC_RESPONSE_TYPE_TX:"RPC_RESPONSE_TRANSACTION_HASH",RPC_RESPONSE_TYPE_OBJECT:"RPC_RESPONSE_OBJECT"},et={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"}},$u={transactionHash:/^0x(?:[A-Fa-f0-9]{64})$/u,signedMessage:/^0x(?:[a-fA-F0-9]{62,})$/u},lt={set(t,e){ds.isClient&&localStorage.setItem(`${oe.STORAGE_KEY}${t}`,e)},get(t){return ds.isClient?localStorage.getItem(`${oe.STORAGE_KEY}${t}`):null},delete(t,e){ds.isClient&&(e?localStorage.removeItem(t):localStorage.removeItem(`${oe.STORAGE_KEY}${t}`))}},ga=30*1e3,ds={checkIfAllowedToTriggerEmail(){const t=lt.get(oe.LAST_EMAIL_LOGIN_TIME);if(t){const e=Date.now()-Number(t);if(e<ga){const s=Math.ceil((ga-e)/1e3);throw new Error(`Please try again after ${s} seconds`)}}},getTimeToNextEmailLogin(){const t=lt.get(oe.LAST_EMAIL_LOGIN_TIME);if(t){const e=Date.now()-Number(t);if(e<ga)return Math.ceil((ga-e)/1e3)}return 0},checkIfRequestExists(t){return et.NOT_SAFE_RPC_METHODS.includes(t.method)||et.SAFE_RPC_METHODS.includes(t.method)},getResponseType(t){return typeof t=="string"&&((t==null?void 0:t.match($u.transactionHash))||(t==null?void 0:t.match($u.signedMessage)))?oe.RPC_RESPONSE_TYPE_TX:oe.RPC_RESPONSE_TYPE_OBJECT},checkIfRequestIsSafe(t){return et.SAFE_RPC_METHODS.includes(t.method)},isClient:typeof window<"u"};var Me;(function(t){t.assertEqual=r=>r;function e(r){}t.assertIs=e;function s(r){throw new Error}t.assertNever=s,t.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return t.objectValues(o)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},t.find=(r,i)=>{for(const o of r)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&isFinite(r)&&Math.floor(r)===r;function n(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(Me||(Me={}));var Vl;(function(t){t.mergeShapes=(e,s)=>({...e,...s})})(Vl||(Vl={}));const se=Me.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Fn=t=>{switch(typeof t){case"undefined":return se.undefined;case"string":return se.string;case"number":return isNaN(t)?se.nan:se.number;case"boolean":return se.boolean;case"function":return se.function;case"bigint":return se.bigint;case"symbol":return se.symbol;case"object":return Array.isArray(t)?se.array:t===null?se.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?se.promise:typeof Map<"u"&&t instanceof Map?se.map:typeof Set<"u"&&t instanceof Set?se.set:typeof Date<"u"&&t instanceof Date?se.date:se.object;default:return se.unknown}},K=Me.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Nw=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class Ds extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const s=e||function(i){return i.message},n={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)n._errors.push(s(o));else{let a=n,c=0;for(;c<o.path.length;){const l=o.path[c];c===o.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(s(o))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return r(this),n}toString(){return this.message}get message(){return JSON.stringify(this.issues,Me.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=s=>s.message){const s={},n=[];for(const r of this.issues)r.path.length>0?(s[r.path[0]]=s[r.path[0]]||[],s[r.path[0]].push(e(r))):n.push(e(r));return{formErrors:n,fieldErrors:s}}get formErrors(){return this.flatten()}}Ds.create=t=>new Ds(t);const ho=(t,e)=>{let s;switch(t.code){case K.invalid_type:t.received===se.undefined?s="Required":s=`Expected ${t.expected}, received ${t.received}`;break;case K.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,Me.jsonStringifyReplacer)}`;break;case K.unrecognized_keys:s=`Unrecognized key(s) in object: ${Me.joinValues(t.keys,", ")}`;break;case K.invalid_union:s="Invalid input";break;case K.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${Me.joinValues(t.options)}`;break;case K.invalid_enum_value:s=`Invalid enum value. Expected ${Me.joinValues(t.options)}, received '${t.received}'`;break;case K.invalid_arguments:s="Invalid function arguments";break;case K.invalid_return_type:s="Invalid function return type";break;case K.invalid_date:s="Invalid date";break;case K.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?s=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?s=`Invalid input: must end with "${t.validation.endsWith}"`:Me.assertNever(t.validation):t.validation!=="regex"?s=`Invalid ${t.validation}`:s="Invalid";break;case K.too_small:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:s="Invalid input";break;case K.too_big:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:s="Invalid input";break;case K.custom:s="Invalid input";break;case K.invalid_intersection_types:s="Intersection results could not be merged";break;case K.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case K.not_finite:s="Number must be finite";break;default:s=e.defaultError,Me.assertNever(t)}return{message:s}};let Uf=ho;function Tw(t){Uf=t}function Ja(){return Uf}const Xa=t=>{const{data:e,path:s,errorMaps:n,issueData:r}=t,i=[...s,...r.path||[]],o={...r,path:i};let a="";const c=n.filter(l=>!!l).slice().reverse();for(const l of c)a=l(o,{data:e,defaultError:a}).message;return{...r,path:i,message:r.message||a}},Rw=[];function ie(t,e){const s=Xa({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ja(),ho].filter(n=>!!n)});t.common.issues.push(s)}class kt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,s){const n=[];for(const r of s){if(r.status==="aborted")return be;r.status==="dirty"&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,s){const n=[];for(const r of s)n.push({key:await r.key,value:await r.value});return kt.mergeObjectSync(e,n)}static mergeObjectSync(e,s){const n={};for(const r of s){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return be;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}}const be=Object.freeze({status:"aborted"}),$f=t=>({status:"dirty",value:t}),Ft=t=>({status:"valid",value:t}),Kl=t=>t.status==="aborted",Gl=t=>t.status==="dirty",po=t=>t.status==="valid",Qa=t=>typeof Promise<"u"&&t instanceof Promise;var pe;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(pe||(pe={}));class tn{constructor(e,s,n,r){this._cachedPath=[],this.parent=e,this.data=s,this._path=n,this._key=r}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Du=(t,e)=>{if(po(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new Ds(t.common.issues);return this._error=s,this._error}}};function _e(t){if(!t)return{};const{errorMap:e,invalid_type_error:s,required_error:n,description:r}=t;if(e&&(s||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>o.code!=="invalid_type"?{message:a.defaultError}:typeof a.data>"u"?{message:n??a.defaultError}:{message:s??a.defaultError},description:r}}class Se{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Fn(e.data)}_getOrReturnCtx(e,s){return s||{common:e.parent.common,data:e.data,parsedType:Fn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new kt,ctx:{common:e.parent.common,data:e.data,parsedType:Fn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const s=this._parse(e);if(Qa(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(e){const s=this._parse(e);return Promise.resolve(s)}parse(e,s){const n=this.safeParse(e,s);if(n.success)return n.data;throw n.error}safeParse(e,s){var n;const r={common:{issues:[],async:(n=s==null?void 0:s.async)!==null&&n!==void 0?n:!1,contextualErrorMap:s==null?void 0:s.errorMap},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fn(e)},i=this._parseSync({data:e,path:r.path,parent:r});return Du(r,i)}async parseAsync(e,s){const n=await this.safeParseAsync(e,s);if(n.success)return n.data;throw n.error}async safeParseAsync(e,s){const n={common:{issues:[],contextualErrorMap:s==null?void 0:s.errorMap,async:!0},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fn(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(Qa(r)?r:Promise.resolve(r));return Du(n,i)}refine(e,s){const n=r=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(r):s;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:K.custom,...n(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,s){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof s=="function"?s(n,r):s),!1))}_refinement(e){return new Bs({schema:this,typeName:me.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Cn.create(this,this._def)}nullable(){return kr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ls.create(this,this._def)}promise(){return gi.create(this,this._def)}or(e){return yo.create([this,e],this._def)}and(e){return wo.create(this,e,this._def)}transform(e){return new Bs({..._e(this._def),schema:this,typeName:me.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const s=typeof e=="function"?e:()=>e;return new _o({..._e(this._def),innerType:this,defaultValue:s,typeName:me.ZodDefault})}brand(){return new Lf({typeName:me.ZodBranded,type:this,..._e(this._def)})}catch(e){const s=typeof e=="function"?e:()=>e;return new nc({..._e(this._def),innerType:this,catchValue:s,typeName:me.ZodCatch})}describe(e){const s=this.constructor;return new s({...this._def,description:e})}pipe(e){return ta.create(this,e)}readonly(){return ic.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ow=/^c[^\s-]{8,}$/i,Pw=/^[a-z][a-z0-9]*$/,xw=/^[0-9A-HJKMNP-TV-Z]{26}$/,kw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Uw=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$w="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Kc;const Dw=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,Lw=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,Mw=t=>t.precision?t.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${t.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${t.precision}}Z$`):t.precision===0?t.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):t.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function Bw(t,e){return!!((e==="v4"||!e)&&Dw.test(t)||(e==="v6"||!e)&&Lw.test(t))}class $s extends Se{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==se.string){const i=this._getOrReturnCtx(e);return ie(i,{code:K.invalid_type,expected:se.string,received:i.parsedType}),be}const n=new kt;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),ie(r,{code:K.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),ie(r,{code:K.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?ie(r,{code:K.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&ie(r,{code:K.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Uw.test(e.data)||(r=this._getOrReturnCtx(e,r),ie(r,{validation:"email",code:K.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Kc||(Kc=new RegExp($w,"u")),Kc.test(e.data)||(r=this._getOrReturnCtx(e,r),ie(r,{validation:"emoji",code:K.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")kw.test(e.data)||(r=this._getOrReturnCtx(e,r),ie(r,{validation:"uuid",code:K.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Ow.test(e.data)||(r=this._getOrReturnCtx(e,r),ie(r,{validation:"cuid",code:K.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Pw.test(e.data)||(r=this._getOrReturnCtx(e,r),ie(r,{validation:"cuid2",code:K.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")xw.test(e.data)||(r=this._getOrReturnCtx(e,r),ie(r,{validation:"ulid",code:K.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),ie(r,{validation:"url",code:K.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),ie(r,{validation:"regex",code:K.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),ie(r,{code:K.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),ie(r,{code:K.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),ie(r,{code:K.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Mw(i).test(e.data)||(r=this._getOrReturnCtx(e,r),ie(r,{code:K.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="ip"?Bw(e.data,i.version)||(r=this._getOrReturnCtx(e,r),ie(r,{validation:"ip",code:K.invalid_string,message:i.message}),n.dirty()):Me.assertNever(i);return{status:n.value,value:e.data}}_regex(e,s,n){return this.refinement(r=>e.test(r),{validation:s,code:K.invalid_string,...pe.errToObj(n)})}_addCheck(e){return new $s({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...pe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...pe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...pe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...pe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...pe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...pe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...pe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...pe.errToObj(e)})}datetime(e){var s;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(s=e==null?void 0:e.offset)!==null&&s!==void 0?s:!1,...pe.errToObj(e==null?void 0:e.message)})}regex(e,s){return this._addCheck({kind:"regex",regex:e,...pe.errToObj(s)})}includes(e,s){return this._addCheck({kind:"includes",value:e,position:s==null?void 0:s.position,...pe.errToObj(s==null?void 0:s.message)})}startsWith(e,s){return this._addCheck({kind:"startsWith",value:e,...pe.errToObj(s)})}endsWith(e,s){return this._addCheck({kind:"endsWith",value:e,...pe.errToObj(s)})}min(e,s){return this._addCheck({kind:"min",value:e,...pe.errToObj(s)})}max(e,s){return this._addCheck({kind:"max",value:e,...pe.errToObj(s)})}length(e,s){return this._addCheck({kind:"length",value:e,...pe.errToObj(s)})}nonempty(e){return this.min(1,pe.errToObj(e))}trim(){return new $s({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new $s({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new $s({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get minLength(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxLength(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}}$s.create=t=>{var e;return new $s({checks:[],typeName:me.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,..._e(t)})};function jw(t,e){const s=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,r=s>n?s:n,i=parseInt(t.toFixed(r).replace(".","")),o=parseInt(e.toFixed(r).replace(".",""));return i%o/Math.pow(10,r)}class Xn extends Se{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==se.number){const i=this._getOrReturnCtx(e);return ie(i,{code:K.invalid_type,expected:se.number,received:i.parsedType}),be}let n;const r=new kt;for(const i of this._def.checks)i.kind==="int"?Me.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),ie(n,{code:K.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),ie(n,{code:K.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),ie(n,{code:K.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?jw(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),ie(n,{code:K.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),ie(n,{code:K.not_finite,message:i.message}),r.dirty()):Me.assertNever(i);return{status:r.value,value:e.data}}gte(e,s){return this.setLimit("min",e,!0,pe.toString(s))}gt(e,s){return this.setLimit("min",e,!1,pe.toString(s))}lte(e,s){return this.setLimit("max",e,!0,pe.toString(s))}lt(e,s){return this.setLimit("max",e,!1,pe.toString(s))}setLimit(e,s,n,r){return new Xn({...this._def,checks:[...this._def.checks,{kind:e,value:s,inclusive:n,message:pe.toString(r)}]})}_addCheck(e){return new Xn({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:pe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:pe.toString(e)})}multipleOf(e,s){return this._addCheck({kind:"multipleOf",value:e,message:pe.toString(s)})}finite(e){return this._addCheck({kind:"finite",message:pe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:pe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:pe.toString(e)})}get minValue(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxValue(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Me.isInteger(e.value))}get isFinite(){let e=null,s=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(s===null||n.value>s)&&(s=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(s)&&Number.isFinite(e)}}Xn.create=t=>new Xn({checks:[],typeName:me.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,..._e(t)});class Qn extends Se{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==se.bigint){const i=this._getOrReturnCtx(e);return ie(i,{code:K.invalid_type,expected:se.bigint,received:i.parsedType}),be}let n;const r=new kt;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),ie(n,{code:K.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),ie(n,{code:K.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),ie(n,{code:K.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):Me.assertNever(i);return{status:r.value,value:e.data}}gte(e,s){return this.setLimit("min",e,!0,pe.toString(s))}gt(e,s){return this.setLimit("min",e,!1,pe.toString(s))}lte(e,s){return this.setLimit("max",e,!0,pe.toString(s))}lt(e,s){return this.setLimit("max",e,!1,pe.toString(s))}setLimit(e,s,n,r){return new Qn({...this._def,checks:[...this._def.checks,{kind:e,value:s,inclusive:n,message:pe.toString(r)}]})}_addCheck(e){return new Qn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:pe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:pe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:pe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:pe.toString(e)})}multipleOf(e,s){return this._addCheck({kind:"multipleOf",value:e,message:pe.toString(s)})}get minValue(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxValue(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}}Qn.create=t=>{var e;return new Qn({checks:[],typeName:me.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,..._e(t)})};class fo extends Se{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==se.boolean){const n=this._getOrReturnCtx(e);return ie(n,{code:K.invalid_type,expected:se.boolean,received:n.parsedType}),be}return Ft(e.data)}}fo.create=t=>new fo({typeName:me.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,..._e(t)});class Pr extends Se{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==se.date){const i=this._getOrReturnCtx(e);return ie(i,{code:K.invalid_type,expected:se.date,received:i.parsedType}),be}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return ie(i,{code:K.invalid_date}),be}const n=new kt;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),ie(r,{code:K.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),ie(r,{code:K.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Me.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Pr({...this._def,checks:[...this._def.checks,e]})}min(e,s){return this._addCheck({kind:"min",value:e.getTime(),message:pe.toString(s)})}max(e,s){return this._addCheck({kind:"max",value:e.getTime(),message:pe.toString(s)})}get minDate(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e!=null?new Date(e):null}}Pr.create=t=>new Pr({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:me.ZodDate,..._e(t)});class ec extends Se{_parse(e){if(this._getType(e)!==se.symbol){const n=this._getOrReturnCtx(e);return ie(n,{code:K.invalid_type,expected:se.symbol,received:n.parsedType}),be}return Ft(e.data)}}ec.create=t=>new ec({typeName:me.ZodSymbol,..._e(t)});class go extends Se{_parse(e){if(this._getType(e)!==se.undefined){const n=this._getOrReturnCtx(e);return ie(n,{code:K.invalid_type,expected:se.undefined,received:n.parsedType}),be}return Ft(e.data)}}go.create=t=>new go({typeName:me.ZodUndefined,..._e(t)});class mo extends Se{_parse(e){if(this._getType(e)!==se.null){const n=this._getOrReturnCtx(e);return ie(n,{code:K.invalid_type,expected:se.null,received:n.parsedType}),be}return Ft(e.data)}}mo.create=t=>new mo({typeName:me.ZodNull,..._e(t)});class fi extends Se{constructor(){super(...arguments),this._any=!0}_parse(e){return Ft(e.data)}}fi.create=t=>new fi({typeName:me.ZodAny,..._e(t)});class Sr extends Se{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ft(e.data)}}Sr.create=t=>new Sr({typeName:me.ZodUnknown,..._e(t)});class Nn extends Se{_parse(e){const s=this._getOrReturnCtx(e);return ie(s,{code:K.invalid_type,expected:se.never,received:s.parsedType}),be}}Nn.create=t=>new Nn({typeName:me.ZodNever,..._e(t)});class tc extends Se{_parse(e){if(this._getType(e)!==se.undefined){const n=this._getOrReturnCtx(e);return ie(n,{code:K.invalid_type,expected:se.void,received:n.parsedType}),be}return Ft(e.data)}}tc.create=t=>new tc({typeName:me.ZodVoid,..._e(t)});class Ls extends Se{_parse(e){const{ctx:s,status:n}=this._processInputParams(e),r=this._def;if(s.parsedType!==se.array)return ie(s,{code:K.invalid_type,expected:se.array,received:s.parsedType}),be;if(r.exactLength!==null){const o=s.data.length>r.exactLength.value,a=s.data.length<r.exactLength.value;(o||a)&&(ie(s,{code:o?K.too_big:K.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&s.data.length<r.minLength.value&&(ie(s,{code:K.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&s.data.length>r.maxLength.value&&(ie(s,{code:K.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),s.common.async)return Promise.all([...s.data].map((o,a)=>r.type._parseAsync(new tn(s,o,s.path,a)))).then(o=>kt.mergeArray(n,o));const i=[...s.data].map((o,a)=>r.type._parseSync(new tn(s,o,s.path,a)));return kt.mergeArray(n,i)}get element(){return this._def.type}min(e,s){return new Ls({...this._def,minLength:{value:e,message:pe.toString(s)}})}max(e,s){return new Ls({...this._def,maxLength:{value:e,message:pe.toString(s)}})}length(e,s){return new Ls({...this._def,exactLength:{value:e,message:pe.toString(s)}})}nonempty(e){return this.min(1,e)}}Ls.create=(t,e)=>new Ls({type:t,minLength:null,maxLength:null,exactLength:null,typeName:me.ZodArray,..._e(e)});function Xr(t){if(t instanceof Je){const e={};for(const s in t.shape){const n=t.shape[s];e[s]=Cn.create(Xr(n))}return new Je({...t._def,shape:()=>e})}else return t instanceof Ls?new Ls({...t._def,type:Xr(t.element)}):t instanceof Cn?Cn.create(Xr(t.unwrap())):t instanceof kr?kr.create(Xr(t.unwrap())):t instanceof sn?sn.create(t.items.map(e=>Xr(e))):t}class Je extends Se{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),s=Me.objectKeys(e);return this._cached={shape:e,keys:s}}_parse(e){if(this._getType(e)!==se.object){const l=this._getOrReturnCtx(e);return ie(l,{code:K.invalid_type,expected:se.object,received:l.parsedType}),be}const{status:n,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof Nn&&this._def.unknownKeys==="strip"))for(const l in r.data)o.includes(l)||a.push(l);const c=[];for(const l of o){const d=i[l],u=r.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new tn(r,u,r.path,l)),alwaysSet:l in r.data})}if(this._def.catchall instanceof Nn){const l=this._def.unknownKeys;if(l==="passthrough")for(const d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(l==="strict")a.length>0&&(ie(r,{code:K.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const d of a){const u=r.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new tn(r,u,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const l=[];for(const d of c){const u=await d.key;l.push({key:u,value:await d.value,alwaysSet:d.alwaysSet})}return l}).then(l=>kt.mergeObjectSync(n,l)):kt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return pe.errToObj,new Je({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(s,n)=>{var r,i,o,a;const c=(o=(i=(r=this._def).errorMap)===null||i===void 0?void 0:i.call(r,s,n).message)!==null&&o!==void 0?o:n.defaultError;return s.code==="unrecognized_keys"?{message:(a=pe.errToObj(e).message)!==null&&a!==void 0?a:c}:{message:c}}}:{}})}strip(){return new Je({...this._def,unknownKeys:"strip"})}passthrough(){return new Je({...this._def,unknownKeys:"passthrough"})}extend(e){return new Je({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Je({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:me.ZodObject})}setKey(e,s){return this.augment({[e]:s})}catchall(e){return new Je({...this._def,catchall:e})}pick(e){const s={};return Me.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(s[n]=this.shape[n])}),new Je({...this._def,shape:()=>s})}omit(e){const s={};return Me.objectKeys(this.shape).forEach(n=>{e[n]||(s[n]=this.shape[n])}),new Je({...this._def,shape:()=>s})}deepPartial(){return Xr(this)}partial(e){const s={};return Me.objectKeys(this.shape).forEach(n=>{const r=this.shape[n];e&&!e[n]?s[n]=r:s[n]=r.optional()}),new Je({...this._def,shape:()=>s})}required(e){const s={};return Me.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])s[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Cn;)i=i._def.innerType;s[n]=i}}),new Je({...this._def,shape:()=>s})}keyof(){return Df(Me.objectKeys(this.shape))}}Je.create=(t,e)=>new Je({shape:()=>t,unknownKeys:"strip",catchall:Nn.create(),typeName:me.ZodObject,..._e(e)});Je.strictCreate=(t,e)=>new Je({shape:()=>t,unknownKeys:"strict",catchall:Nn.create(),typeName:me.ZodObject,..._e(e)});Je.lazycreate=(t,e)=>new Je({shape:t,unknownKeys:"strip",catchall:Nn.create(),typeName:me.ZodObject,..._e(e)});class yo extends Se{_parse(e){const{ctx:s}=this._processInputParams(e),n=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return s.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Ds(a.ctx.common.issues));return ie(s,{code:K.invalid_union,unionErrors:o}),be}if(s.common.async)return Promise.all(n.map(async i=>{const o={...s,common:{...s.common,issues:[]},parent:null};return{result:await i._parseAsync({data:s.data,path:s.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const c of n){const l={...s,common:{...s.common,issues:[]},parent:null},d=c._parseSync({data:s.data,path:s.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&o.push(l.common.issues)}if(i)return s.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(c=>new Ds(c));return ie(s,{code:K.invalid_union,unionErrors:a}),be}}get options(){return this._def.options}}yo.create=(t,e)=>new yo({options:t,typeName:me.ZodUnion,..._e(e)});const Ba=t=>t instanceof bo?Ba(t.schema):t instanceof Bs?Ba(t.innerType()):t instanceof vo?[t.value]:t instanceof er?t.options:t instanceof Co?Object.keys(t.enum):t instanceof _o?Ba(t._def.innerType):t instanceof go?[void 0]:t instanceof mo?[null]:null;class Ic extends Se{_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==se.object)return ie(s,{code:K.invalid_type,expected:se.object,received:s.parsedType}),be;const n=this.discriminator,r=s.data[n],i=this.optionsMap.get(r);return i?s.common.async?i._parseAsync({data:s.data,path:s.path,parent:s}):i._parseSync({data:s.data,path:s.path,parent:s}):(ie(s,{code:K.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),be)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,s,n){const r=new Map;for(const i of s){const o=Ba(i.shape[e]);if(!o)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of o){if(r.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);r.set(a,i)}}return new Ic({typeName:me.ZodDiscriminatedUnion,discriminator:e,options:s,optionsMap:r,..._e(n)})}}function Yl(t,e){const s=Fn(t),n=Fn(e);if(t===e)return{valid:!0,data:t};if(s===se.object&&n===se.object){const r=Me.objectKeys(e),i=Me.objectKeys(t).filter(a=>r.indexOf(a)!==-1),o={...t,...e};for(const a of i){const c=Yl(t[a],e[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(s===se.array&&n===se.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const o=t[i],a=e[i],c=Yl(o,a);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return s===se.date&&n===se.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class wo extends Se{_parse(e){const{status:s,ctx:n}=this._processInputParams(e),r=(i,o)=>{if(Kl(i)||Kl(o))return be;const a=Yl(i.value,o.value);return a.valid?((Gl(i)||Gl(o))&&s.dirty(),{status:s.value,value:a.data}):(ie(n,{code:K.invalid_intersection_types}),be)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}wo.create=(t,e,s)=>new wo({left:t,right:e,typeName:me.ZodIntersection,..._e(s)});class sn extends Se{_parse(e){const{status:s,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.array)return ie(n,{code:K.invalid_type,expected:se.array,received:n.parsedType}),be;if(n.data.length<this._def.items.length)return ie(n,{code:K.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),be;!this._def.rest&&n.data.length>this._def.items.length&&(ie(n,{code:K.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const i=[...n.data].map((o,a)=>{const c=this._def.items[a]||this._def.rest;return c?c._parse(new tn(n,o,n.path,a)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>kt.mergeArray(s,o)):kt.mergeArray(s,i)}get items(){return this._def.items}rest(e){return new sn({...this._def,rest:e})}}sn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new sn({items:t,typeName:me.ZodTuple,rest:null,..._e(e)})};class Eo extends Se{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:s,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.object)return ie(n,{code:K.invalid_type,expected:se.object,received:n.parsedType}),be;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in n.data)r.push({key:i._parse(new tn(n,a,n.path,a)),value:o._parse(new tn(n,n.data[a],n.path,a))});return n.common.async?kt.mergeObjectAsync(s,r):kt.mergeObjectSync(s,r)}get element(){return this._def.valueType}static create(e,s,n){return s instanceof Se?new Eo({keyType:e,valueType:s,typeName:me.ZodRecord,..._e(n)}):new Eo({keyType:$s.create(),valueType:e,typeName:me.ZodRecord,..._e(s)})}}class sc extends Se{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:s,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.map)return ie(n,{code:K.invalid_type,expected:se.map,received:n.parsedType}),be;const r=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([a,c],l)=>({key:r._parse(new tn(n,a,n.path,[l,"key"])),value:i._parse(new tn(n,c,n.path,[l,"value"]))}));if(n.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const c of o){const l=await c.key,d=await c.value;if(l.status==="aborted"||d.status==="aborted")return be;(l.status==="dirty"||d.status==="dirty")&&s.dirty(),a.set(l.value,d.value)}return{status:s.value,value:a}})}else{const a=new Map;for(const c of o){const l=c.key,d=c.value;if(l.status==="aborted"||d.status==="aborted")return be;(l.status==="dirty"||d.status==="dirty")&&s.dirty(),a.set(l.value,d.value)}return{status:s.value,value:a}}}}sc.create=(t,e,s)=>new sc({valueType:e,keyType:t,typeName:me.ZodMap,..._e(s)});class xr extends Se{_parse(e){const{status:s,ctx:n}=this._processInputParams(e);if(n.parsedType!==se.set)return ie(n,{code:K.invalid_type,expected:se.set,received:n.parsedType}),be;const r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(ie(n,{code:K.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),s.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(ie(n,{code:K.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),s.dirty());const i=this._def.valueType;function o(c){const l=new Set;for(const d of c){if(d.status==="aborted")return be;d.status==="dirty"&&s.dirty(),l.add(d.value)}return{status:s.value,value:l}}const a=[...n.data.values()].map((c,l)=>i._parse(new tn(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>o(c)):o(a)}min(e,s){return new xr({...this._def,minSize:{value:e,message:pe.toString(s)}})}max(e,s){return new xr({...this._def,maxSize:{value:e,message:pe.toString(s)}})}size(e,s){return this.min(e,s).max(e,s)}nonempty(e){return this.min(1,e)}}xr.create=(t,e)=>new xr({valueType:t,minSize:null,maxSize:null,typeName:me.ZodSet,..._e(e)});class oi extends Se{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==se.function)return ie(s,{code:K.invalid_type,expected:se.function,received:s.parsedType}),be;function n(a,c){return Xa({data:a,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,Ja(),ho].filter(l=>!!l),issueData:{code:K.invalid_arguments,argumentsError:c}})}function r(a,c){return Xa({data:a,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,Ja(),ho].filter(l=>!!l),issueData:{code:K.invalid_return_type,returnTypeError:c}})}const i={errorMap:s.common.contextualErrorMap},o=s.data;if(this._def.returns instanceof gi){const a=this;return Ft(async function(...c){const l=new Ds([]),d=await a._def.args.parseAsync(c,i).catch(p=>{throw l.addIssue(n(c,p)),l}),u=await Reflect.apply(o,this,d);return await a._def.returns._def.type.parseAsync(u,i).catch(p=>{throw l.addIssue(r(u,p)),l})})}else{const a=this;return Ft(function(...c){const l=a._def.args.safeParse(c,i);if(!l.success)throw new Ds([n(c,l.error)]);const d=Reflect.apply(o,this,l.data),u=a._def.returns.safeParse(d,i);if(!u.success)throw new Ds([r(d,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new oi({...this._def,args:sn.create(e).rest(Sr.create())})}returns(e){return new oi({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,s,n){return new oi({args:e||sn.create([]).rest(Sr.create()),returns:s||Sr.create(),typeName:me.ZodFunction,..._e(n)})}}class bo extends Se{get schema(){return this._def.getter()}_parse(e){const{ctx:s}=this._processInputParams(e);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}bo.create=(t,e)=>new bo({getter:t,typeName:me.ZodLazy,..._e(e)});class vo extends Se{_parse(e){if(e.data!==this._def.value){const s=this._getOrReturnCtx(e);return ie(s,{received:s.data,code:K.invalid_literal,expected:this._def.value}),be}return{status:"valid",value:e.data}}get value(){return this._def.value}}vo.create=(t,e)=>new vo({value:t,typeName:me.ZodLiteral,..._e(e)});function Df(t,e){return new er({values:t,typeName:me.ZodEnum,..._e(e)})}class er extends Se{_parse(e){if(typeof e.data!="string"){const s=this._getOrReturnCtx(e),n=this._def.values;return ie(s,{expected:Me.joinValues(n),received:s.parsedType,code:K.invalid_type}),be}if(this._def.values.indexOf(e.data)===-1){const s=this._getOrReturnCtx(e),n=this._def.values;return ie(s,{received:s.data,code:K.invalid_enum_value,options:n}),be}return Ft(e.data)}get options(){return this._def.values}get enum(){const e={};for(const s of this._def.values)e[s]=s;return e}get Values(){const e={};for(const s of this._def.values)e[s]=s;return e}get Enum(){const e={};for(const s of this._def.values)e[s]=s;return e}extract(e){return er.create(e)}exclude(e){return er.create(this.options.filter(s=>!e.includes(s)))}}er.create=Df;class Co extends Se{_parse(e){const s=Me.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==se.string&&n.parsedType!==se.number){const r=Me.objectValues(s);return ie(n,{expected:Me.joinValues(r),received:n.parsedType,code:K.invalid_type}),be}if(s.indexOf(e.data)===-1){const r=Me.objectValues(s);return ie(n,{received:n.data,code:K.invalid_enum_value,options:r}),be}return Ft(e.data)}get enum(){return this._def.values}}Co.create=(t,e)=>new Co({values:t,typeName:me.ZodNativeEnum,..._e(e)});class gi extends Se{unwrap(){return this._def.type}_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==se.promise&&s.common.async===!1)return ie(s,{code:K.invalid_type,expected:se.promise,received:s.parsedType}),be;const n=s.parsedType===se.promise?s.data:Promise.resolve(s.data);return Ft(n.then(r=>this._def.type.parseAsync(r,{path:s.path,errorMap:s.common.contextualErrorMap})))}}gi.create=(t,e)=>new gi({type:t,typeName:me.ZodPromise,..._e(e)});class Bs extends Se{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===me.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:s,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{ie(n,o),o.fatal?s.abort():s.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(n.data,i);return n.common.issues.length?{status:"dirty",value:n.data}:n.common.async?Promise.resolve(o).then(a=>this._def.schema._parseAsync({data:a,path:n.path,parent:n})):this._def.schema._parseSync({data:o,path:n.path,parent:n})}if(r.type==="refinement"){const o=a=>{const c=r.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?be:(a.status==="dirty"&&s.dirty(),o(a.value),{status:s.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?be:(a.status==="dirty"&&s.dirty(),o(a.value).then(()=>({status:s.value,value:a.value}))))}if(r.type==="transform")if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!po(o))return o;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>po(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:s.value,value:a})):o);Me.assertNever(r)}}Bs.create=(t,e,s)=>new Bs({schema:t,typeName:me.ZodEffects,effect:e,..._e(s)});Bs.createWithPreprocess=(t,e,s)=>new Bs({schema:e,effect:{type:"preprocess",transform:t},typeName:me.ZodEffects,..._e(s)});class Cn extends Se{_parse(e){return this._getType(e)===se.undefined?Ft(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Cn.create=(t,e)=>new Cn({innerType:t,typeName:me.ZodOptional,..._e(e)});class kr extends Se{_parse(e){return this._getType(e)===se.null?Ft(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}kr.create=(t,e)=>new kr({innerType:t,typeName:me.ZodNullable,..._e(e)});class _o extends Se{_parse(e){const{ctx:s}=this._processInputParams(e);let n=s.data;return s.parsedType===se.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}_o.create=(t,e)=>new _o({innerType:t,typeName:me.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._e(e)});class nc extends Se{_parse(e){const{ctx:s}=this._processInputParams(e),n={...s,common:{...s.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Qa(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ds(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Ds(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}nc.create=(t,e)=>new nc({innerType:t,typeName:me.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._e(e)});class rc extends Se{_parse(e){if(this._getType(e)!==se.nan){const n=this._getOrReturnCtx(e);return ie(n,{code:K.invalid_type,expected:se.nan,received:n.parsedType}),be}return{status:"valid",value:e.data}}}rc.create=t=>new rc({typeName:me.ZodNaN,..._e(t)});const Fw=Symbol("zod_brand");class Lf extends Se{_parse(e){const{ctx:s}=this._processInputParams(e),n=s.data;return this._def.type._parse({data:n,path:s.path,parent:s})}unwrap(){return this._def.type}}class ta extends Se{_parse(e){const{status:s,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?be:i.status==="dirty"?(s.dirty(),$f(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{const r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return r.status==="aborted"?be:r.status==="dirty"?(s.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,s){return new ta({in:e,out:s,typeName:me.ZodPipeline})}}class ic extends Se{_parse(e){const s=this._def.innerType._parse(e);return po(s)&&(s.value=Object.freeze(s.value)),s}}ic.create=(t,e)=>new ic({innerType:t,typeName:me.ZodReadonly,..._e(e)});const Mf=(t,e={},s)=>t?fi.create().superRefine((n,r)=>{var i,o;if(!t(n)){const a=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,c=(o=(i=a.fatal)!==null&&i!==void 0?i:s)!==null&&o!==void 0?o:!0,l=typeof a=="string"?{message:a}:a;r.addIssue({code:"custom",...l,fatal:c})}}):fi.create(),qw={object:Je.lazycreate};var me;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(me||(me={}));const Ww=(t,e={message:`Input not instance of ${t.name}`})=>Mf(s=>s instanceof t,e),Bf=$s.create,jf=Xn.create,Hw=rc.create,zw=Qn.create,Ff=fo.create,Vw=Pr.create,Kw=ec.create,Gw=go.create,Yw=mo.create,Zw=fi.create,Jw=Sr.create,Xw=Nn.create,Qw=tc.create,eE=Ls.create,tE=Je.create,sE=Je.strictCreate,nE=yo.create,rE=Ic.create,iE=wo.create,oE=sn.create,aE=Eo.create,cE=sc.create,lE=xr.create,dE=oi.create,uE=bo.create,hE=vo.create,pE=er.create,fE=Co.create,gE=gi.create,Lu=Bs.create,mE=Cn.create,yE=kr.create,wE=Bs.createWithPreprocess,EE=ta.create,bE=()=>Bf().optional(),vE=()=>jf().optional(),CE=()=>Ff().optional(),_E={string:t=>$s.create({...t,coerce:!0}),number:t=>Xn.create({...t,coerce:!0}),boolean:t=>fo.create({...t,coerce:!0}),bigint:t=>Qn.create({...t,coerce:!0}),date:t=>Pr.create({...t,coerce:!0})},AE=be;var m=Object.freeze({__proto__:null,defaultErrorMap:ho,setErrorMap:Tw,getErrorMap:Ja,makeIssue:Xa,EMPTY_PATH:Rw,addIssueToContext:ie,ParseStatus:kt,INVALID:be,DIRTY:$f,OK:Ft,isAborted:Kl,isDirty:Gl,isValid:po,isAsync:Qa,get util(){return Me},get objectUtil(){return Vl},ZodParsedType:se,getParsedType:Fn,ZodType:Se,ZodString:$s,ZodNumber:Xn,ZodBigInt:Qn,ZodBoolean:fo,ZodDate:Pr,ZodSymbol:ec,ZodUndefined:go,ZodNull:mo,ZodAny:fi,ZodUnknown:Sr,ZodNever:Nn,ZodVoid:tc,ZodArray:Ls,ZodObject:Je,ZodUnion:yo,ZodDiscriminatedUnion:Ic,ZodIntersection:wo,ZodTuple:sn,ZodRecord:Eo,ZodMap:sc,ZodSet:xr,ZodFunction:oi,ZodLazy:bo,ZodLiteral:vo,ZodEnum:er,ZodNativeEnum:Co,ZodPromise:gi,ZodEffects:Bs,ZodTransformer:Bs,ZodOptional:Cn,ZodNullable:kr,ZodDefault:_o,ZodCatch:nc,ZodNaN:rc,BRAND:Fw,ZodBranded:Lf,ZodPipeline:ta,ZodReadonly:ic,custom:Mf,Schema:Se,ZodSchema:Se,late:qw,get ZodFirstPartyTypeKind(){return me},coerce:_E,any:Zw,array:eE,bigint:zw,boolean:Ff,date:Vw,discriminatedUnion:rE,effect:Lu,enum:pE,function:dE,instanceof:Ww,intersection:iE,lazy:uE,literal:hE,map:cE,nan:Hw,nativeEnum:fE,never:Xw,null:Yw,nullable:yE,number:jf,object:tE,oboolean:CE,onumber:vE,optional:mE,ostring:bE,pipeline:EE,preprocess:wE,promise:gE,record:aE,set:lE,strictObject:sE,string:Bf,symbol:Kw,transformer:Lu,tuple:oE,undefined:Gw,union:nE,unknown:Jw,void:Qw,NEVER:AE,ZodIssueCode:K,quotelessJson:Nw,ZodError:Ds});const Xe=m.object({message:m.string()});function ne(t){return m.literal(oe[t])}const Nc=m.object({serializedMessage:m.string().optional(),accountAddress:m.string(),chainId:m.string(),notBefore:m.string().optional(),domain:m.string(),uri:m.string(),version:m.string(),nonce:m.string(),statement:m.string().optional(),resources:m.array(m.string()).optional(),requestId:m.string().optional(),issuedAt:m.string().optional(),expirationTime:m.string().optional()});m.object({accessList:m.array(m.string()),blockHash:m.string().nullable(),blockNumber:m.string().nullable(),chainId:m.string().or(m.number()),from:m.string(),gas:m.string(),hash:m.string(),input:m.string().nullable(),maxFeePerGas:m.string(),maxPriorityFeePerGas:m.string(),nonce:m.string(),r:m.string(),s:m.string(),to:m.string(),transactionIndex:m.string().nullable(),type:m.string(),v:m.string(),value:m.string()});const SE=m.object({chainId:m.string().or(m.number()),rpcUrl:m.optional(m.string())}),IE=m.object({email:m.string().email()}),NE=m.object({otp:m.string()}),TE=m.object({uri:m.string(),preferredAccountType:m.optional(m.string()),chainId:m.optional(m.string().or(m.number())),siwxMessage:m.optional(Nc),rpcUrl:m.optional(m.string())}),RE=m.object({chainId:m.optional(m.string().or(m.number())),preferredAccountType:m.optional(m.string()),socialUri:m.optional(m.string()),siwxMessage:m.optional(Nc),rpcUrl:m.optional(m.string())}),OE=m.object({provider:m.enum(["google","github","apple","facebook","x","discord"])}),PE=m.object({email:m.string().email()}),xE=m.object({otp:m.string()}),kE=m.object({otp:m.string()}),UE=m.object({themeMode:m.optional(m.enum(["light","dark"])),themeVariables:m.optional(m.record(m.string(),m.string().or(m.number()))),w3mThemeVariables:m.optional(m.record(m.string(),m.string()))}),$E=m.object({metadata:m.object({name:m.string(),description:m.string(),url:m.string(),icons:m.array(m.string())}).optional(),sdkVersion:m.string().optional(),sdkType:m.string().optional(),projectId:m.string()}),DE=m.object({type:m.string()}),LE=m.object({action:m.enum(["VERIFY_DEVICE","VERIFY_OTP","CONNECT"])}),ME=m.object({url:m.string()}),BE=m.object({userName:m.string()}),jE=m.object({email:m.string().optional().nullable(),address:m.string(),chainId:m.string().or(m.number()),accounts:m.array(m.object({address:m.string(),type:m.enum([et.ACCOUNT_TYPES.EOA,et.ACCOUNT_TYPES.SMART_ACCOUNT])})).optional(),userName:m.string().optional().nullable(),preferredAccountType:m.optional(m.string()),signature:m.string().optional(),message:m.string().optional(),siwxMessage:m.optional(Nc)}),FE=m.object({action:m.enum(["VERIFY_PRIMARY_OTP","VERIFY_SECONDARY_OTP"])}),qE=m.object({email:m.string().email().optional().nullable(),address:m.string(),chainId:m.string().or(m.number()),smartAccountDeployed:m.optional(m.boolean()),accounts:m.array(m.object({address:m.string(),type:m.enum([et.ACCOUNT_TYPES.EOA,et.ACCOUNT_TYPES.SMART_ACCOUNT])})).optional(),preferredAccountType:m.optional(m.string()),signature:m.string().optional(),message:m.string().optional(),siwxMessage:m.optional(Nc)}),WE=m.object({uri:m.string()}),HE=m.object({isConnected:m.boolean()}),zE=m.object({chainId:m.string().or(m.number())}),VE=m.object({chainId:m.string().or(m.number())}),KE=m.object({newEmail:m.string().email()}),GE=m.object({smartAccountEnabledNetworks:m.array(m.number())});m.object({address:m.string(),isDeployed:m.boolean()});const YE=m.object({version:m.string().optional()}),ZE=m.object({type:m.string(),address:m.string()}),JE=m.any(),XE=m.object({method:m.literal("eth_accounts")}),QE=m.object({method:m.literal("eth_blockNumber")}),eb=m.object({method:m.literal("eth_call"),params:m.array(m.any())}),tb=m.object({method:m.literal("eth_chainId")}),sb=m.object({method:m.literal("eth_estimateGas"),params:m.array(m.any())}),nb=m.object({method:m.literal("eth_feeHistory"),params:m.array(m.any())}),rb=m.object({method:m.literal("eth_gasPrice")}),ib=m.object({method:m.literal("eth_getAccount"),params:m.array(m.any())}),ob=m.object({method:m.literal("eth_getBalance"),params:m.array(m.any())}),ab=m.object({method:m.literal("eth_getBlockByHash"),params:m.array(m.any())}),cb=m.object({method:m.literal("eth_getBlockByNumber"),params:m.array(m.any())}),lb=m.object({method:m.literal("eth_getBlockReceipts"),params:m.array(m.any())}),db=m.object({method:m.literal("eth_getBlockTransactionCountByHash"),params:m.array(m.any())}),ub=m.object({method:m.literal("eth_getBlockTransactionCountByNumber"),params:m.array(m.any())}),hb=m.object({method:m.literal("eth_getCode"),params:m.array(m.any())}),pb=m.object({method:m.literal("eth_getFilterChanges"),params:m.array(m.any())}),fb=m.object({method:m.literal("eth_getFilterLogs"),params:m.array(m.any())}),gb=m.object({method:m.literal("eth_getLogs"),params:m.array(m.any())}),mb=m.object({method:m.literal("eth_getProof"),params:m.array(m.any())}),yb=m.object({method:m.literal("eth_getStorageAt"),params:m.array(m.any())}),wb=m.object({method:m.literal("eth_getTransactionByBlockHashAndIndex"),params:m.array(m.any())}),Eb=m.object({method:m.literal("eth_getTransactionByBlockNumberAndIndex"),params:m.array(m.any())}),bb=m.object({method:m.literal("eth_getTransactionByHash"),params:m.array(m.any())}),vb=m.object({method:m.literal("eth_getTransactionCount"),params:m.array(m.any())}),Cb=m.object({method:m.literal("eth_getTransactionReceipt"),params:m.array(m.any())}),_b=m.object({method:m.literal("eth_getUncleCountByBlockHash"),params:m.array(m.any())}),Ab=m.object({method:m.literal("eth_getUncleCountByBlockNumber"),params:m.array(m.any())}),Sb=m.object({method:m.literal("eth_maxPriorityFeePerGas")}),Ib=m.object({method:m.literal("eth_newBlockFilter")}),Nb=m.object({method:m.literal("eth_newFilter"),params:m.array(m.any())}),Tb=m.object({method:m.literal("eth_newPendingTransactionFilter")}),Rb=m.object({method:m.literal("eth_sendRawTransaction"),params:m.array(m.any())}),Ob=m.object({method:m.literal("eth_syncing"),params:m.array(m.any())}),Pb=m.object({method:m.literal("eth_uninstallFilter"),params:m.array(m.any())}),Mu=m.object({method:m.literal("personal_sign"),params:m.array(m.any())}),xb=m.object({method:m.literal("eth_signTypedData_v4"),params:m.array(m.any())}),kb=m.object({method:m.literal("eth_sendTransaction"),params:m.array(m.any())}),Ub=m.object({method:m.literal("solana_signMessage"),params:m.object({message:m.string(),pubkey:m.string()})}),$b=m.object({method:m.literal("solana_signTransaction"),params:m.object({transaction:m.string()})}),Db=m.object({method:m.literal("solana_signAllTransactions"),params:m.object({transactions:m.array(m.string())})}),Lb=m.object({method:m.literal("solana_signAndSendTransaction"),params:m.object({transaction:m.string(),options:m.object({skipPreflight:m.boolean().optional(),preflightCommitment:m.enum(["processed","confirmed","finalized","recent","single","singleGossip","root","max"]).optional(),maxRetries:m.number().optional(),minContextSlot:m.number().optional()}).optional()})}),Mb=m.object({method:m.literal("wallet_sendCalls"),params:m.array(m.object({chainId:m.string().or(m.number()).optional(),from:m.string().optional(),version:m.string().optional(),capabilities:m.any().optional(),calls:m.array(m.object({to:m.string().startsWith("0x"),data:m.string().startsWith("0x").optional(),value:m.string().optional()}))}))}),Bb=m.object({method:m.literal("wallet_getCallsStatus"),params:m.array(m.string())}),jb=m.object({method:m.literal("wallet_getCapabilities"),params:m.array(m.string().or(m.number()).optional()).optional()}),Fb=m.object({method:m.literal("wallet_grantPermissions"),params:m.array(m.any())}),qb=m.object({method:m.literal("wallet_revokePermissions"),params:m.any()}),Wb=m.object({method:m.literal("wallet_getAssets"),params:m.any()}),Bu=m.object({token:m.string()}),re=m.object({id:m.string().optional()}),Gc={appEvent:re.extend({type:ne("APP_SWITCH_NETWORK"),payload:SE}).or(re.extend({type:ne("APP_CONNECT_EMAIL"),payload:IE})).or(re.extend({type:ne("APP_CONNECT_DEVICE")})).or(re.extend({type:ne("APP_CONNECT_OTP"),payload:NE})).or(re.extend({type:ne("APP_CONNECT_SOCIAL"),payload:TE})).or(re.extend({type:ne("APP_GET_FARCASTER_URI")})).or(re.extend({type:ne("APP_CONNECT_FARCASTER")})).or(re.extend({type:ne("APP_GET_USER"),payload:m.optional(RE)})).or(re.extend({type:ne("APP_GET_SOCIAL_REDIRECT_URI"),payload:OE})).or(re.extend({type:ne("APP_SIGN_OUT")})).or(re.extend({type:ne("APP_IS_CONNECTED"),payload:m.optional(Bu)})).or(re.extend({type:ne("APP_GET_CHAIN_ID")})).or(re.extend({type:ne("APP_GET_SMART_ACCOUNT_ENABLED_NETWORKS")})).or(re.extend({type:ne("APP_INIT_SMART_ACCOUNT")})).or(re.extend({type:ne("APP_SET_PREFERRED_ACCOUNT"),payload:DE})).or(re.extend({type:ne("APP_RPC_REQUEST"),payload:Mu.or(Wb).or(XE).or(QE).or(eb).or(tb).or(sb).or(nb).or(rb).or(ib).or(ob).or(ab).or(cb).or(lb).or(db).or(ub).or(hb).or(pb).or(fb).or(gb).or(mb).or(yb).or(wb).or(Eb).or(bb).or(vb).or(Cb).or(_b).or(Ab).or(Sb).or(Ib).or(Nb).or(Tb).or(Rb).or(Ob).or(Pb).or(Mu).or(xb).or(kb).or(Ub).or($b).or(Db).or(Lb).or(Bb).or(Mb).or(jb).or(Fb).or(qb).and(m.object({chainId:m.string().or(m.number()).optional(),chainNamespace:m.enum(["eip155","solana","polkadot","bip122","cosmos"]).optional(),rpcUrl:m.string().optional()}))})).or(re.extend({type:ne("APP_UPDATE_EMAIL"),payload:PE})).or(re.extend({type:ne("APP_UPDATE_EMAIL_PRIMARY_OTP"),payload:xE})).or(re.extend({type:ne("APP_UPDATE_EMAIL_SECONDARY_OTP"),payload:kE})).or(re.extend({type:ne("APP_SYNC_THEME"),payload:UE})).or(re.extend({type:ne("APP_SYNC_DAPP_DATA"),payload:$E})).or(re.extend({type:ne("APP_RELOAD")})).or(re.extend({type:ne("APP_RPC_ABORT")})),frameEvent:re.extend({type:ne("FRAME_SWITCH_NETWORK_ERROR"),payload:Xe}).or(re.extend({type:ne("FRAME_SWITCH_NETWORK_SUCCESS"),payload:VE})).or(re.extend({type:ne("FRAME_CONNECT_EMAIL_SUCCESS"),payload:LE})).or(re.extend({type:ne("FRAME_CONNECT_EMAIL_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_GET_FARCASTER_URI_SUCCESS"),payload:ME})).or(re.extend({type:ne("FRAME_GET_FARCASTER_URI_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_CONNECT_FARCASTER_SUCCESS"),payload:BE})).or(re.extend({type:ne("FRAME_CONNECT_FARCASTER_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_CONNECT_OTP_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_CONNECT_OTP_SUCCESS")})).or(re.extend({type:ne("FRAME_CONNECT_DEVICE_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_CONNECT_DEVICE_SUCCESS")})).or(re.extend({type:ne("FRAME_CONNECT_SOCIAL_SUCCESS"),payload:jE})).or(re.extend({type:ne("FRAME_CONNECT_SOCIAL_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_GET_USER_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_GET_USER_SUCCESS"),payload:qE})).or(re.extend({type:ne("FRAME_GET_SOCIAL_REDIRECT_URI_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_GET_SOCIAL_REDIRECT_URI_SUCCESS"),payload:WE})).or(re.extend({type:ne("FRAME_SIGN_OUT_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_SIGN_OUT_SUCCESS")})).or(re.extend({type:ne("FRAME_IS_CONNECTED_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_IS_CONNECTED_SUCCESS"),payload:HE})).or(re.extend({type:ne("FRAME_GET_CHAIN_ID_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_GET_CHAIN_ID_SUCCESS"),payload:zE})).or(re.extend({type:ne("FRAME_RPC_REQUEST_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_RPC_REQUEST_SUCCESS"),payload:JE})).or(re.extend({type:ne("FRAME_SESSION_UPDATE"),payload:Bu})).or(re.extend({type:ne("FRAME_UPDATE_EMAIL_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_UPDATE_EMAIL_SUCCESS"),payload:FE})).or(re.extend({type:ne("FRAME_UPDATE_EMAIL_PRIMARY_OTP_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_UPDATE_EMAIL_PRIMARY_OTP_SUCCESS")})).or(re.extend({type:ne("FRAME_UPDATE_EMAIL_SECONDARY_OTP_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_UPDATE_EMAIL_SECONDARY_OTP_SUCCESS"),payload:KE})).or(re.extend({type:ne("FRAME_SYNC_THEME_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_SYNC_THEME_SUCCESS")})).or(re.extend({type:ne("FRAME_SYNC_DAPP_DATA_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_SYNC_DAPP_DATA_SUCCESS")})).or(re.extend({type:ne("FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_SUCCESS"),payload:GE})).or(re.extend({type:ne("FRAME_GET_SMART_ACCOUNT_ENABLED_NETWORKS_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_INIT_SMART_ACCOUNT_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_SET_PREFERRED_ACCOUNT_SUCCESS"),payload:ZE})).or(re.extend({type:ne("FRAME_SET_PREFERRED_ACCOUNT_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_READY"),payload:YE})).or(re.extend({type:ne("FRAME_RELOAD_ERROR"),payload:Xe})).or(re.extend({type:ne("FRAME_RELOAD_SUCCESS")}))};function Yc(t,e={}){var s;return typeof(e==null?void 0:e.type)=="string"&&((s=e==null?void 0:e.type)==null?void 0:s.includes(t))}function Hb({projectId:t,chainId:e,enableLogger:s,rpcUrl:n=$.BLOCKCHAIN_API_RPC_URL,enableCloudAuthAccount:r=!1}){const i=new URL(Aw);i.searchParams.set("projectId",t),i.searchParams.set("chainId",String(e)),i.searchParams.set("version",Iw),i.searchParams.set("enableLogger",String(s)),i.searchParams.set("rpcUrl",n);const o=lt.get("dapp_smart_account_version");return o&&(o==="v6"||o==="v7")&&(console.warn(">> AppKit - Forcing smart account version",o),i.searchParams.set("smartAccountVersion",o)),r&&i.searchParams.set("enableCloudAuthAccount","true"),i.toString()}class zb{constructor({projectId:e,isAppClient:s=!1,chainId:n="eip155:1",enableLogger:r=!0,enableCloudAuthAccount:i=!1,rpcUrl:o=$.BLOCKCHAIN_API_RPC_URL}){if(this.iframe=null,this.iframeIsReady=!1,this.initFrame=()=>{const a=document.getElementById("w3m-iframe");this.iframe&&!a&&document.body.appendChild(this.iframe)},this.events={registerFrameEventHandler:(a,c,l)=>{function d({data:u}){var p;if(!Yc(oe.FRAME_EVENT_KEY,u))return;const h=Gc.frameEvent.safeParse(u);if(!h.success){console.warn("W3mFrame: invalid frame event",h.error.message);return}((p=h.data)==null?void 0:p.id)===a&&(c(h.data),window.removeEventListener("message",d))}ds.isClient&&(window.addEventListener("message",d),l.addEventListener("abort",()=>{window.removeEventListener("message",d)}))},onFrameEvent:a=>{ds.isClient&&window.addEventListener("message",({data:c})=>{if(!Yc(oe.FRAME_EVENT_KEY,c))return;const l=Gc.frameEvent.safeParse(c);l.success?a(l.data):console.warn("W3mFrame: invalid frame event",l.error.message)})},onAppEvent:a=>{ds.isClient&&window.addEventListener("message",({data:c})=>{if(!Yc(oe.APP_EVENT_KEY,c))return;const l=Gc.appEvent.safeParse(c);l.success||console.warn("W3mFrame: invalid app event",l.error.message),a(c)})},postAppEvent:a=>{var c;if(ds.isClient){if(!((c=this.iframe)!=null&&c.contentWindow))throw new Error("W3mFrame: iframe is not set");this.iframe.contentWindow.postMessage(a,"*")}},postFrameEvent:a=>{if(ds.isClient){if(!parent)throw new Error("W3mFrame: parent is not set");parent.postMessage(a,"*")}}},this.projectId=e,this.frameLoadPromise=new Promise((a,c)=>{this.frameLoadPromiseResolver={resolve:a,reject:c}}),this.rpcUrl=o,s&&(this.frameLoadPromise=new Promise((a,c)=>{this.frameLoadPromiseResolver={resolve:a,reject:c}}),ds.isClient)){const a=document.createElement("iframe");a.id="w3m-iframe",a.src=Hb({projectId:e,chainId:n,enableLogger:r,rpcUrl:this.rpcUrl,enableCloudAuthAccount:i}),a.name="w3m-secure-iframe",a.style.position="fixed",a.style.zIndex="999999",a.style.display="none",a.style.border="none",a.style.animationDelay="0s, 50ms",a.style.borderBottomLeftRadius="clamp(0px, var(--apkt-borderRadius-8), 44px)",a.style.borderBottomRightRadius="clamp(0px, var(--apkt-borderRadius-8), 44px)",this.iframe=a,this.iframe.onerror=()=>{var c;(c=this.frameLoadPromiseResolver)==null||c.reject("Unable to load email login dependency")},this.events.onFrameEvent(c=>{var l;c.type==="@w3m-frame/READY"&&(this.iframeIsReady=!0,(l=this.frameLoadPromiseResolver)==null||l.resolve(void 0))})}}get networks(){const e=["eip155:1","eip155:5","eip155:11155111","eip155:10","eip155:420","eip155:42161","eip155:421613","eip155:137","eip155:80001","eip155:42220","eip155:1313161554","eip155:1313161555","eip155:56","eip155:97","eip155:43114","eip155:43113","eip155:324","eip155:280","eip155:100","eip155:8453","eip155:84531","eip155:84532","eip155:7777777","eip155:999","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"].map(s=>({[s]:{rpcUrl:`${this.rpcUrl}/v1/?chainId=${s}&projectId=${this.projectId}`,chainId:s}}));return Object.assign({},...e)}}var Oi={exports:{}},ju;function Vb(){if(ju)return Oi.exports;ju=1;const t=ky();Oi.exports=d;const e=T().console||{},s={mapHttpRequest:L,mapHttpResponse:L,wrapRequestSerializer:W,wrapResponseSerializer:W,wrapErrorSerializer:W,req:L,res:L,err:P,errWithCause:P};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 S={logger:b,parent:y[i]};b[i]=S}function c(y,b,S){const R={};b.forEach(C=>{R[C]=S[C]?S[C]:e[C]||e[o[C]||"log"]||k}),y[r]=R}function l(y,b){return Array.isArray(y)?y.filter(function(R){return R!=="!stdSerializers.err"}):y===!0?Object.keys(b):!1}function d(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 S=y.browser.write||e;y.browser.write&&(y.browser.asObject=!0);const R=y.serializers||{},C=l(y.browser.serialize,R);let O=y.browser.serialize;Array.isArray(y.browser.serialize)&&y.browser.serialize.indexOf("!stdSerializers.err")>-1&&(O=!1);const B=Object.keys(y.customLevels||{}),M=["error","fatal","warn","info","debug","trace"].concat(B);typeof S=="function"&&M.forEach(function(ve){S[ve]=S}),(y.enabled===!1||y.browser.disabled)&&(y.level="silent");const ce=y.level||"info",j=Object.create(S);j.log||(j.log=k),c(j,M,S),a({},j),Object.defineProperty(j,"levelVal",{get:he}),Object.defineProperty(j,"level",{get:ge,set:xe});const J={transmit:b,serialize:C,asObject:y.browser.asObject,asObjectBindingsOnly:y.browser.asObjectBindingsOnly,formatters:y.browser.formatters,levels:M,timestamp:U(y),messageKey:y.messageKey||"msg",onChild:y.onChild||k};j.levels=u(y),j.level=ce,j.isLevelEnabled=function(ve){return this.levels.values[ve]?this.levels.values[ve]>=this.levels.values[this.level]:!1},j.setMaxListeners=j.getMaxListeners=j.emit=j.addListener=j.on=j.prependListener=j.once=j.prependOnceListener=j.removeListener=j.removeAllListeners=j.listeners=j.listenerCount=j.eventNames=j.write=j.flush=k,j.serializers=R,j._serialize=C,j._stdErrSerialize=O,j.child=function(...ve){return ye.call(this,J,...ve)},b&&(j._logEvent=_());function he(){return n(this.level,this)}function ge(){return this._level}function xe(ve){if(ve!=="silent"&&!this.levels.values[ve])throw Error("unknown level "+ve);this._level=ve,g(this,J,j,"error"),g(this,J,j,"fatal"),g(this,J,j,"warn"),g(this,J,j,"info"),g(this,J,j,"debug"),g(this,J,j,"trace"),B.forEach(Ve=>{g(this,J,j,Ve)})}function ye(ve,Ve,st){if(!Ve)throw new Error("missing bindings for child Pino");st=st||{},C&&Ve.serializers&&(st.serializers=Ve.serializers);const ut=st.serializers;if(C&&ut){var wt=Object.assign({},R,ut),Fs=y.browser.serialize===!0?Object.keys(wt):C;delete Ve.serializers,N([Ve],Fs,wt,this._stdErrSerialize)}function rn(ha){this._childLevel=(ha._childLevel|0)+1,this.bindings=Ve,wt&&(this.serializers=wt,this._serialize=Fs),b&&(this._logEvent=_([].concat(ha._logEvent.bindings,Ve)))}rn.prototype=this;const Ri=new rn(this);return a(this,Ri),Ri.child=function(...ha){return ye.call(this,ve,...ha)},Ri.level=st.level||this.level,ve.onChild(Ri),Ri}return j}function u(y){const b=y.customLevels||{},S=Object.assign({},d.levels.values,b),R=Object.assign({},d.levels.labels,h(b));return{values:S,labels:R}}function h(y){const b={};return Object.keys(y).forEach(function(S){b[y[S]]=S}),b}d.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"}},d.stdSerializers=s,d.stdTimeFunctions=Object.assign({},{nullTime:q,epochTime:V,unixTime:x,isoTime:I});function p(y){const b=[];y.bindings&&b.push(y.bindings);let S=y[i];for(;S.parent;)S=S.parent,S.logger.bindings&&b.push(S.logger.bindings);return b.reverse()}function g(y,b,S,R){if(Object.defineProperty(y,R,{value:n(y.level,S)>n(R,S)?k:S[r][R],writable:!0,enumerable:!0,configurable:!0}),y[R]===k){if(!b.transmit)return;const O=b.transmit.level||y.level,B=n(O,S);if(n(R,S)<B)return}y[R]=w(y,b,S,R);const C=p(y);C.length!==0&&(y[R]=f(C,y[R]))}function f(y,b){return function(){return b.apply(this,[...y,...arguments])}}function w(y,b,S,R){return function(C){return function(){const B=b.timestamp(),M=new Array(arguments.length),ce=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var j=0;j<M.length;j++)M[j]=arguments[j];var J=!1;if(b.serialize&&(N(M,this._serialize,this.serializers,this._stdErrSerialize),J=!0),b.asObject||b.formatters?C.call(ce,...v(this,R,M,B,b)):C.apply(ce,M),b.transmit){const he=b.transmit.level||y._level,ge=n(he,S),xe=n(R,S);if(xe<ge)return;A(this,{ts:B,methodLevel:R,methodValue:xe,transmitValue:S.levels.values[b.transmit.level||y._level],send:b.transmit.send,val:n(y._level,S)},M,J)}}}(y[r][R])}function v(y,b,S,R,C){const{level:O,log:B=he=>he}=C.formatters||{},M=S.slice();let ce=M[0];const j={};let J=(y._childLevel|0)+1;if(J<1&&(J=1),R&&(j.time=R),O){const he=O(b,y.levels.values[b]);Object.assign(j,he)}else j.level=y.levels.values[b];if(C.asObjectBindingsOnly){if(ce!==null&&typeof ce=="object")for(;J--&&typeof M[0]=="object";)Object.assign(j,M.shift());return[B(j),...M]}else{if(ce!==null&&typeof ce=="object"){for(;J--&&typeof M[0]=="object";)Object.assign(j,M.shift());ce=M.length?t(M.shift(),M):void 0}else typeof ce=="string"&&(ce=t(M.shift(),M));return ce!==void 0&&(j[C.messageKey]=ce),[B(j)]}}function N(y,b,S,R){for(const C in y)if(R&&y[C]instanceof Error)y[C]=d.stdSerializers.err(y[C]);else if(typeof y[C]=="object"&&!Array.isArray(y[C])&&b)for(const O in y[C])b.indexOf(O)>-1&&O in S&&(y[C][O]=S[O](y[C][O]))}function A(y,b,S,R=!1){const C=b.send,O=b.ts,B=b.methodLevel,M=b.methodValue,ce=b.val,j=y._logEvent.bindings;R||N(S,y._serialize||Object.keys(y.serializers),y.serializers,y._stdErrSerialize===void 0?!0:y._stdErrSerialize),y._logEvent.ts=O,y._logEvent.messages=S.filter(function(J){return j.indexOf(J)===-1}),y._logEvent.level.label=B,y._logEvent.level.value=M,C(B,y._logEvent,ce),y._logEvent=_(j)}function _(y){return{ts:0,messages:[],bindings:y||[],level:{label:"",value:0}}}function P(y){const b={type:y.constructor.name,msg:y.message,stack:y.stack};for(const S in y)b[S]===void 0&&(b[S]=y[S]);return b}function U(y){return typeof y.timestamp=="function"?y.timestamp:y.timestamp===!1?q:V}function L(){return{}}function W(y){return y}function k(){}function q(){return!1}function V(){return Date.now()}function x(){return Math.round(Date.now()/1e3)}function I(){return new Date(Date.now()).toISOString()}function T(){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 Oi.exports.default=d,Oi.exports.pino=d,Oi.exports}var Qr=Vb();const qf=Sy(Qr),Kb={level:"info"},Tc="custom_context",Gd=1e3*1024;var Gb=Object.defineProperty,Yb=(t,e,s)=>e in t?Gb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qn=(t,e,s)=>Yb(t,typeof e!="symbol"?e+"":e,s);let Zb=class{constructor(e){qn(this,"nodeValue"),qn(this,"sizeInBytes"),qn(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}},Fu=class{constructor(e){qn(this,"lengthInNodes"),qn(this,"sizeInBytes"),qn(this,"head"),qn(this,"tail"),qn(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const s=new Zb(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 Jb=Object.defineProperty,Xb=(t,e,s)=>e in t?Jb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ma=(t,e,s)=>Xb(t,typeof e!="symbol"?e+"":e,s);let Wf=class{constructor(e,s=Gd){ma(this,"logs"),ma(this,"level"),ma(this,"levelValue"),ma(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=Qr.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=s,this.logs=new Fu(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,s){s===Qr.levels.values.error?console.error(e):s===Qr.levels.values.warn?console.warn(e):s===Qr.levels.values.debug?console.debug(e):s===Qr.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(io({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 Fu(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const s=this.getLogArray();return s.push(io({extraMetadata:e})),new Blob(s,{type:"application/json"})}};var Qb=Object.defineProperty,ev=(t,e,s)=>e in t?Qb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,tv=(t,e,s)=>ev(t,e+"",s);let sv=class{constructor(e,s=Gd){tv(this,"baseChunkLogger"),this.baseChunkLogger=new Wf(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 nv=Object.defineProperty,rv=(t,e,s)=>e in t?nv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,iv=(t,e,s)=>rv(t,e+"",s);let ov=class{constructor(e,s=Gd){iv(this,"baseChunkLogger"),this.baseChunkLogger=new Wf(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 av=Object.defineProperty,cv=Object.defineProperties,lv=Object.getOwnPropertyDescriptors,qu=Object.getOwnPropertySymbols,dv=Object.prototype.hasOwnProperty,uv=Object.prototype.propertyIsEnumerable,Wu=(t,e,s)=>e in t?av(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oc=(t,e)=>{for(var s in e||(e={}))dv.call(e,s)&&Wu(t,s,e[s]);if(qu)for(var s of qu(e))uv.call(e,s)&&Wu(t,s,e[s]);return t},ac=(t,e)=>cv(t,lv(e));function Yd(t){return ac(oc({},t),{level:(t==null?void 0:t.level)||Kb.level})}function hv(t,e,s=Tc){return t[s]=e,t}function es(t,e=Tc){return t[e]||""}function pv(t,e,s=Tc){const n=es(t,s);return n.trim()?`${n}/${e}`:e}function ts(t,e,s=Tc){const n=pv(t,e,s),r=t.child({context:n});return hv(r,n,s)}function fv(t){var e,s;const n=new sv((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:qf(ac(oc({},t.opts),{level:"trace",browser:ac(oc({},(s=t.opts)==null?void 0:s.browser),{write:r=>n.write(r)})})),chunkLoggerController:n}}function gv(t){var e;const s=new ov((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:qf(ac(oc({},t.opts),{level:"trace"}),s),chunkLoggerController:s}}function Rc(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?fv(t):gv(t)}class mv{constructor(e){var i;const s=Yd({level:Sw}),{logger:n,chunkLoggerController:r}=Rc({opts:s});this.logger=ts(n,this.constructor.name),this.chunkLoggerController=r,typeof window<"u"&&((i=this.chunkLoggerController)!=null&&i.downloadLogsBlobInBrowser)&&(window.downloadAppKitLogsBlob||(window.downloadAppKitLogsBlob={}),window.downloadAppKitLogsBlob.sdk=()=>{var o;(o=this.chunkLoggerController)!=null&&o.downloadLogsBlobInBrowser&&this.chunkLoggerController.downloadLogsBlobInBrowser({projectId:e})})}}class yv{constructor({projectId:e,chainId:s,enableLogger:n=!0,onTimeout:r,abortController:i,getActiveCaipNetwork:o,getCaipNetworks:a,enableCloudAuthAccount:c,metadata:l,sdkVersion:d,sdkType:u}){this.openRpcRequests=new Map,this.isInitialized=!1,n&&(this.w3mLogger=new mv(e)),this.abortController=i,this.getActiveCaipNetwork=o,this.getCaipNetworks=a;const h=this.getRpcUrl(s);this.projectId=e,this.sdkVersion=d,this.sdkType=u,this.metadata=l,this.w3mFrame=new zb({projectId:e,isAppClient:!0,chainId:s,enableLogger:n,rpcUrl:h,enableCloudAuthAccount:c}),this.onTimeout=r,this.getLoginEmailUsed()&&this.createFrame()}async createFrame(){this.w3mFrame.initFrame(),this.initPromise=new Promise(e=>{this.w3mFrame.events.onFrameEvent(s=>{s.type===oe.FRAME_READY&&setTimeout(()=>{e()},500)})}),await this.initPromise,await this.syncDappData({metadata:this.metadata,projectId:this.projectId,sdkVersion:this.sdkVersion,sdkType:this.sdkType}),await this.getSmartAccountEnabledNetworks(),this.isInitialized=!0,this.initPromise=void 0}async init(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}await this.createFrame()}}getLoginEmailUsed(){return!!lt.get(oe.EMAIL_LOGIN_USED_KEY)}getEmail(){return lt.get(oe.EMAIL)}getUsername(){return lt.get(oe.SOCIAL_USERNAME)}async reload(){var e;try{await this.appEvent({type:oe.APP_RELOAD})}catch(s){throw(e=this.w3mLogger)==null||e.logger.error({error:s},"Error reloading iframe"),s}}async connectEmail(e){var s;try{ds.checkIfAllowedToTriggerEmail(),await this.init();const n=await this.appEvent({type:oe.APP_CONNECT_EMAIL,payload:e});return this.setNewLastEmailLoginTime(),n}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error connecting email"),n}}async connectDevice(){var e;try{return this.appEvent({type:oe.APP_CONNECT_DEVICE})}catch(s){throw(e=this.w3mLogger)==null||e.logger.error({error:s},"Error connecting device"),s}}async connectOtp(e){var s;try{return this.appEvent({type:oe.APP_CONNECT_OTP,payload:e})}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error connecting otp"),n}}async isConnected(){var e;try{if(!this.getLoginEmailUsed())return{isConnected:!1};const s=await this.appEvent({type:oe.APP_IS_CONNECTED});return s!=null&&s.isConnected||this.deleteAuthLoginCache(),s}catch(s){throw this.deleteAuthLoginCache(),(e=this.w3mLogger)==null||e.logger.error({error:s},"Error checking connection"),s}}async getChainId(){var e;try{const s=await this.appEvent({type:oe.APP_GET_CHAIN_ID});return this.setLastUsedChainId(s.chainId),s}catch(s){throw(e=this.w3mLogger)==null||e.logger.error({error:s},"Error getting chain id"),s}}async getSocialRedirectUri(e){var s;try{return await this.init(),this.appEvent({type:oe.APP_GET_SOCIAL_REDIRECT_URI,payload:e})}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error getting social redirect uri"),n}}async updateEmail(e){var s;try{const n=await this.appEvent({type:oe.APP_UPDATE_EMAIL,payload:e});return this.setNewLastEmailLoginTime(),n}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error updating email"),n}}async updateEmailPrimaryOtp(e){var s;try{return this.appEvent({type:oe.APP_UPDATE_EMAIL_PRIMARY_OTP,payload:e})}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error updating email primary otp"),n}}async updateEmailSecondaryOtp(e){var s;try{const n=await this.appEvent({type:oe.APP_UPDATE_EMAIL_SECONDARY_OTP,payload:e});return this.setLoginSuccess(n.newEmail),n}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error updating email secondary otp"),n}}async syncTheme(e){var s;try{return this.appEvent({type:oe.APP_SYNC_THEME,payload:e})}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error syncing theme"),n}}async syncDappData(e){var s;try{return this.appEvent({type:oe.APP_SYNC_DAPP_DATA,payload:e})}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error syncing dapp data"),n}}async getSmartAccountEnabledNetworks(){var e;try{const s=await this.appEvent({type:oe.APP_GET_SMART_ACCOUNT_ENABLED_NETWORKS});return this.persistSmartAccountEnabledNetworks(s.smartAccountEnabledNetworks),s}catch(s){throw this.persistSmartAccountEnabledNetworks([]),(e=this.w3mLogger)==null||e.logger.error({error:s},"Error getting smart account enabled networks"),s}}async setPreferredAccount(e){var s;try{return this.appEvent({type:oe.APP_SET_PREFERRED_ACCOUNT,payload:{type:e}})}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error setting preferred account"),n}}async connect(e){var s,n;if(e!=null&&e.socialUri)try{await this.init();const r=this.getRpcUrl(e.chainId),i=await this.appEvent({type:oe.APP_CONNECT_SOCIAL,payload:{uri:e.socialUri,preferredAccountType:e.preferredAccountType,chainId:e.chainId,siwxMessage:e.siwxMessage,rpcUrl:r}});return i.userName&&this.setSocialLoginSuccess(i.userName),this.setLoginSuccess(i.email),this.setLastUsedChainId(i.chainId),this.user=i,i}catch(r){throw(s=this.w3mLogger)==null||s.logger.error({error:r},"Error connecting social"),r}else try{const r=(e==null?void 0:e.chainId)||this.getLastUsedChainId()||1,i=await this.getUser({chainId:r,preferredAccountType:e==null?void 0:e.preferredAccountType,siwxMessage:e==null?void 0:e.siwxMessage,rpcUrl:this.getRpcUrl(r)});return this.setLoginSuccess(i.email),this.setLastUsedChainId(i.chainId),this.user=i,i}catch(r){throw(n=this.w3mLogger)==null||n.logger.error({error:r},"Error connecting"),r}}async getUser(e){var s;try{await this.init();const n=(e==null?void 0:e.chainId)||this.getLastUsedChainId()||1,r=await this.appEvent({type:oe.APP_GET_USER,payload:{...e,chainId:n,rpcUrl:this.getRpcUrl(n)}});return this.user=r,r}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error connecting"),n}}async connectSocial({uri:e,chainId:s,preferredAccountType:n}){var r;try{await this.init();const i=this.getRpcUrl(s),o=await this.appEvent({type:oe.APP_CONNECT_SOCIAL,payload:{uri:e,chainId:s,rpcUrl:i,preferredAccountType:n}});return o.userName&&this.setSocialLoginSuccess(o.userName),o}catch(i){throw(r=this.w3mLogger)==null||r.logger.error({error:i},"Error connecting social"),i}}async getFarcasterUri(){var e;try{return await this.init(),await this.appEvent({type:oe.APP_GET_FARCASTER_URI})}catch(s){throw(e=this.w3mLogger)==null||e.logger.error({error:s},"Error getting farcaster uri"),s}}async connectFarcaster(){var e;try{const s=await this.appEvent({type:oe.APP_CONNECT_FARCASTER});return s.userName&&this.setSocialLoginSuccess(s.userName),s}catch(s){throw(e=this.w3mLogger)==null||e.logger.error({error:s},"Error connecting farcaster"),s}}async switchNetwork({chainId:e}){var s;try{const n=this.getRpcUrl(e),r=await this.appEvent({type:oe.APP_SWITCH_NETWORK,payload:{chainId:e,rpcUrl:n}});return this.setLastUsedChainId(r.chainId),r}catch(n){throw(s=this.w3mLogger)==null||s.logger.error({error:n},"Error switching network"),n}}async disconnect(){var e;try{return this.deleteAuthLoginCache(),await new Promise(async n=>{const r=setTimeout(()=>{n()},3e3);await this.appEvent({type:oe.APP_SIGN_OUT}),clearTimeout(r),n()})}catch(s){throw(e=this.w3mLogger)==null||e.logger.error({error:s},"Error disconnecting"),s}}async request(e){var n,r,i,o,a;const s=e;try{if(et.GET_CHAIN_ID===e.method)return this.getLastUsedChainId();const c=e.chainNamespace||"eip155",l=(n=this.getActiveCaipNetwork(c))==null?void 0:n.id;s.chainNamespace=c,s.chainId=l,s.rpcUrl=this.getRpcUrl(l),(r=this.rpcRequestHandler)==null||r.call(this,e);const d=await this.appEvent({type:oe.APP_RPC_REQUEST,payload:s});return(i=this.rpcSuccessHandler)==null||i.call(this,d,s),d}catch(c){throw(o=this.rpcErrorHandler)==null||o.call(this,c,s),(a=this.w3mLogger)==null||a.logger.error({error:c},"Error requesting"),c}}onRpcRequest(e){this.rpcRequestHandler=e}onRpcSuccess(e){this.rpcSuccessHandler=e}onRpcError(e){this.rpcErrorHandler=e}onIsConnected(e){this.w3mFrame.events.onFrameEvent(s=>{s.type===oe.FRAME_IS_CONNECTED_SUCCESS&&s.payload.isConnected&&e()})}onNotConnected(e){this.w3mFrame.events.onFrameEvent(s=>{s.type===oe.FRAME_IS_CONNECTED_ERROR&&e(),s.type===oe.FRAME_IS_CONNECTED_SUCCESS&&!s.payload.isConnected&&e()})}onConnect(e){this.w3mFrame.events.onFrameEvent(s=>{s.type===oe.FRAME_GET_USER_SUCCESS&&e(s.payload)})}onSocialConnected(e){this.w3mFrame.events.onFrameEvent(s=>{s.type===oe.FRAME_CONNECT_SOCIAL_SUCCESS&&e(s.payload)})}async getCapabilities(){try{return await this.request({method:"wallet_getCapabilities"})||{}}catch{return{}}}onSetPreferredAccount(e){this.w3mFrame.events.onFrameEvent(s=>{s.type===oe.FRAME_SET_PREFERRED_ACCOUNT_SUCCESS?e(s.payload):s.type===oe.FRAME_SET_PREFERRED_ACCOUNT_ERROR&&e({type:et.ACCOUNT_TYPES.EOA})})}getAvailableChainIds(){return Object.keys(this.w3mFrame.networks)}async rejectRpcRequests(){var e;try{await Promise.all(Array.from(this.openRpcRequests.values()).map(async({abortController:s,method:n})=>{et.SAFE_RPC_METHODS.includes(n)||s.abort(),await this.appEvent({type:oe.APP_RPC_ABORT})})),this.openRpcRequests.clear()}catch(s){(e=this.w3mLogger)==null||e.logger.error({error:s},"Error aborting RPC request")}}async appEvent(e){let s,n;function r(c){return c.replace("@w3m-app/","")}const i=[oe.APP_SYNC_DAPP_DATA,oe.APP_SYNC_THEME,oe.APP_SET_PREFERRED_ACCOUNT],o=r(e.type);return!this.w3mFrame.iframeIsReady&&!i.includes(e.type)&&(n=setTimeout(()=>{var c;(c=this.onTimeout)==null||c.call(this,"iframe_load_failed"),this.abortController.abort()},2e4)),await this.w3mFrame.frameLoadPromise,clearTimeout(n),[oe.APP_CONNECT_EMAIL,oe.APP_CONNECT_DEVICE,oe.APP_CONNECT_OTP,oe.APP_CONNECT_SOCIAL,oe.APP_GET_SOCIAL_REDIRECT_URI].map(r).includes(o)&&(s=setTimeout(()=>{var c;(c=this.onTimeout)==null||c.call(this,"iframe_request_timeout"),this.abortController.abort()},12e4)),new Promise((c,l)=>{var p,g,f;const d=Math.random().toString(36).substring(7);(f=(p=this.w3mLogger)==null?void 0:(g=p.logger).info)==null||f.call(g,{event:e,id:d},"Sending app event"),this.w3mFrame.events.postAppEvent({...e,id:d});const u=new AbortController;if(o==="RPC_REQUEST"){const w=e;this.openRpcRequests.set(d,{...w.payload,abortController:u})}u.signal.addEventListener("abort",()=>{o==="RPC_REQUEST"?l(new Error("Request was aborted")):o!=="GET_FARCASTER_URI"&&l(new Error("Something went wrong"))});const h=(w,v)=>{var N,A,_;w.id===d&&((A=v==null?void 0:(N=v.logger).info)==null||A.call(N,{framEvent:w,id:d},"Received frame response"),this.openRpcRequests.delete(w.id),w.type===`@w3m-frame/${o}_SUCCESS`?(s&&clearTimeout(s),n&&clearTimeout(n),"payload"in w&&c(w.payload),c(void 0)):w.type===`@w3m-frame/${o}_ERROR`&&(s&&clearTimeout(s),n&&clearTimeout(n),"payload"in w&&l(new Error(((_=w.payload)==null?void 0:_.message)||"An error occurred")),l(new Error("An error occurred"))))};this.w3mFrame.events.registerFrameEventHandler(d,w=>h(w,this.w3mLogger),this.abortController.signal)})}setNewLastEmailLoginTime(){lt.set(oe.LAST_EMAIL_LOGIN_TIME,Date.now().toString())}setSocialLoginSuccess(e){lt.set(oe.SOCIAL_USERNAME,e)}setLoginSuccess(e){e&&lt.set(oe.EMAIL,e),lt.set(oe.EMAIL_LOGIN_USED_KEY,"true"),lt.delete(oe.LAST_EMAIL_LOGIN_TIME)}deleteAuthLoginCache(){lt.delete(oe.EMAIL_LOGIN_USED_KEY),lt.delete(oe.EMAIL),lt.delete(oe.LAST_USED_CHAIN_KEY),lt.delete(oe.SOCIAL_USERNAME)}setLastUsedChainId(e){e&&lt.set(oe.LAST_USED_CHAIN_KEY,String(e))}getLastUsedChainId(){const e=lt.get(oe.LAST_USED_CHAIN_KEY)??void 0,s=Number(e);return isNaN(s)?e:s}persistSmartAccountEnabledNetworks(e){lt.set(oe.SMART_ACCOUNT_ENABLED_NETWORKS,e.join(","))}getRpcUrl(e){var i,o;let s=e===void 0?void 0:"eip155";typeof e=="string"&&(e.includes(":")?s=(i=dt.parseCaipNetworkId(e))==null?void 0:i.chainNamespace:Number.isInteger(Number(e))?s="eip155":s="solana");const n=this.getCaipNetworks(s),r=e?n.find(a=>String(a.id)===String(e)||a.caipNetworkId===e):n[0];return(o=r==null?void 0:r.rpcUrls.default.http)==null?void 0:o[0]}}function Hf(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}`:""}`}const a2=[{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:"addr",type:"address"}],name:"getEthBalance",outputs:[{name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"}],c2=[{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"}]}],zf=[{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"}],l2=[...zf,{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"}]}],d2=[...zf,{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"}]}],u2=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],h2=[{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"}]}],p2=[{name:"isValidSignature",type:"function",stateMutability:"view",inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],outputs:[{name:"",type:"bytes4"}]}],f2=[{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"}],ya=[{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"}]}];async function Pi(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class sa{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 Pi(i,{method:"GET",headers:e,signal:s,cache:n})).json()}async getBlob({headers:e,signal:s,...n}){const r=this.createUrl(n);return(await Pi(r,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:n,...r}){const i=this.createUrl(r);return(await Pi(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 Pi(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 Pi(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 Zl={getFeatureValue(t,e){const s=e==null?void 0:e[t];return s===void 0?Ne.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;let e=t;return X.isTelegram()&&(X.isIos()&&(e=e.filter(s=>s!=="google")),X.isMac()&&(e=e.filter(s=>s!=="x")),X.isAndroid()&&(e=e.filter(s=>!["facebook","x"].includes(s)))),X.isMobile()&&(e=e.filter(s=>s!=="facebook")),e},isSocialsEnabled(){var t,e,s,n;return Array.isArray((t=D.state.features)==null?void 0:t.socials)&&((e=D.state.features)==null?void 0:e.socials.length)>0||Array.isArray((s=D.state.remoteFeatures)==null?void 0:s.socials)&&((n=D.state.remoteFeatures)==null?void 0:n.socials.length)>0},isEmailEnabled(){var t,e;return!!((t=D.state.features)!=null&&t.email||(e=D.state.remoteFeatures)!=null&&e.email)}},de=Ge({features:Ne.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Ne.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{},enableMobileFullScreen:!1,coinbasePreference:"all"}),D={state:de,subscribeKey(t,e){return At(de,t,e)},setOptions(t){Object.assign(de,t)},setRemoteFeatures(t){var s,n;if(!t)return;const e={...de.remoteFeatures,...t};de.remoteFeatures=e,(s=de.remoteFeatures)!=null&&s.socials&&(de.remoteFeatures.socials=Zl.filterSocialsByPlatform(de.remoteFeatures.socials)),(n=de.features)!=null&&n.pay&&(de.remoteFeatures.email=!1,de.remoteFeatures.socials=!1)},setFeatures(t){var s;if(!t)return;de.features||(de.features=Ne.DEFAULT_FEATURES);const e={...de.features,...t};de.features=e,(s=de.features)!=null&&s.pay&&de.remoteFeatures&&(de.remoteFeatures.email=!1,de.remoteFeatures.socials=!1)},setProjectId(t){de.projectId=t},setCustomRpcUrls(t){de.customRpcUrls=t},setAllWallets(t){de.allWallets=t},setIncludeWalletIds(t){de.includeWalletIds=t},setExcludeWalletIds(t){de.excludeWalletIds=t},setFeaturedWalletIds(t){de.featuredWalletIds=t},setTokens(t){de.tokens=t},setTermsConditionsUrl(t){de.termsConditionsUrl=t},setPrivacyPolicyUrl(t){de.privacyPolicyUrl=t},setCustomWallets(t){de.customWallets=t},setIsSiweEnabled(t){de.isSiweEnabled=t},setIsUniversalProvider(t){de.isUniversalProvider=t},setSdkVersion(t){de.sdkVersion=t},setMetadata(t){de.metadata=t},setDisableAppend(t){de.disableAppend=t},setEIP6963Enabled(t){de.enableEIP6963=t},setDebug(t){de.debug=t},setEnableWalletGuide(t){de.enableWalletGuide=t},setEnableAuthLogger(t){de.enableAuthLogger=t},setEnableWallets(t){de.enableWallets=t},setPreferUniversalLinks(t){de.experimental_preferUniversalLinks=t},setSIWX(t){if(t)for(const[e,s]of Object.entries(Ne.SIWX_DEFAULTS))t[e]??(t[e]=s);de.siwx=t},setConnectMethodsOrder(t){de.features={...de.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){de.features={...de.features,walletFeaturesOrder:t}},setSocialsOrder(t){de.remoteFeatures={...de.remoteFeatures,socials:t}},setCollapseWallets(t){de.features={...de.features,collapseWallets:t}},setEnableEmbedded(t){de.enableEmbedded=t},setAllowUnsupportedChain(t){de.allowUnsupportedChain=t},setManualWCControl(t){de.manualWCControl=t},setEnableNetworkSwitch(t){de.enableNetworkSwitch=t},setEnableMobileFullScreen(t){de.enableMobileFullScreen=X.isMobile()&&t},setEnableReconnect(t){de.enableReconnect=t},setCoinbasePreference(t){de.coinbasePreference=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(de.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){de.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return de.universalProviderConfigOverride},getSnapshot(){return lo(de)}},ur=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),at=Ge({...ur}),wv={state:at,subscribeKey(t,e){return At(at,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=X.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){at.message=ur.message,at.variant=ur.variant,at.svg=ur.svg,at.open=ur.open,at.autoClose=ur.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:n=ur.autoClose}){at.open?(at.open=!1,setTimeout(()=>{at.message=t,at.variant=s,at.svg=e,at.open=!0,at.autoClose=n},150)):(at.message=t,at.variant=s,at.svg=e,at.open=!0,at.autoClose=n)}},Ys=wv,Ev={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"}]}]},Vf=X.getBlockchainApiUrl(),Ut=Ge({clientId:null,api:new sa({baseUrl:Vf,clientId:null}),supportedChains:{http:[],ws:[]}}),fe={state:Ut,async get(t){const{st:e,sv:s}=fe.getSdkProperties(),n=D.state.projectId,r={...t.params||{},st:e,sv:s,projectId:n};return Ut.api.get({...t,params:r})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=D.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{Ut.supportedChains.http.length||await fe.getSupportedNetworks()}catch{return!1}return Ut.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await fe.get({path:"v1/supported-chains"});return Ut.supportedChains=t,t}catch{return Ut.supportedChains}},async fetchIdentity({address:t}){const e=F.getIdentityFromCacheForAddress(t);if(e)return e;const s=await fe.get({path:`/v1/identity/${t}`,params:{sender:E.state.activeCaipAddress?X.getPlainAddress(E.state.activeCaipAddress):void 0}});return F.updateIdentityCache({address:t,identity:s,timestamp:Date.now()}),s},async fetchTransactions({account:t,cursor:e,signal:s,cache:n,chainId:r}){var c;if(!await fe.isNetworkSupported((c=E.state.activeCaipNetwork)==null?void 0:c.caipNetworkId))return{data:[],next:void 0};const o=F.getTransactionsCacheForAddress({address:t,chainId:r});if(o)return o;const a=await fe.get({path:`/v1/account/${t}/history`,params:{cursor:e,chainId:r},signal:s,cache:n});return F.updateTransactionsCache({address:t,chainId:r,timestamp:Date.now(),transactions:a}),a},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:n,gasPrice:r}){var o;return await fe.isNetworkSupported((o=E.state.activeCaipNetwork)==null?void 0:o.caipNetworkId)?fe.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}){var s;return await fe.isNetworkSupported((s=E.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?fe.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async getAddressBalance({caipNetworkId:t,address:e}){return Ut.api.post({path:`/v1?chainId=${t}&projectId=${D.state.projectId}`,body:{id:"1",jsonrpc:"2.0",method:"getAddressBalance",params:{address:e}}}).then(s=>s.result)},async fetchTokenPrice({addresses:t}){var r;if(!await fe.isNetworkSupported((r=E.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))return{fungibles:[]};const s=F.getTokenPriceCacheForAddresses(t);if(s)return s;const n=await Ut.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:D.state.projectId},headers:{"Content-Type":"application/json"}});return F.updateTokenPriceCache({addresses:t,timestamp:Date.now(),tokenPrice:n}),n},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){var n;return await fe.isNetworkSupported((n=E.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)?fe.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){var r;const{st:e,sv:s}=fe.getSdkProperties();if(!await fe.isNetworkSupported((r=E.state.activeCaipNetwork)==null?void 0:r.caipNetworkId))throw new Error("Network not supported for Gas Price");return fe.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}){var o;if(!await fe.isNetworkSupported((o=E.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return Ut.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:Ne.CONVERT_SLIPPAGE_TOLERANCE},projectId:D.state.projectId,from:e,to:s,userAddress:n,disableEstimate:r}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){var o;const{st:n,sv:r}=fe.getSdkProperties();if(!await fe.isNetworkSupported((o=E.state.activeCaipNetwork)==null?void 0:o.caipNetworkId))throw new Error("Network not supported for Swaps");return fe.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){var l;const{st:n,sv:r}=fe.getSdkProperties();if(!await fe.isNetworkSupported((l=E.state.activeCaipNetwork)==null?void 0:l.caipNetworkId))return Ys.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=F.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await fe.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:n,sv:r}});return F.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){var s;return await fe.isNetworkSupported((s=E.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?fe.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){var n,r;if(!await fe.isNetworkSupported((n=E.state.activeCaipNetwork)==null?void 0:n.caipNetworkId))return[];const s=(r=E.getAccountData())==null?void 0:r.address;return fe.get({path:`/v1/profile/reverse/${t}`,params:{sender:s,apiVersion:"2"}})},async getEnsNameSuggestions(t){var s;return await fe.isNetworkSupported((s=E.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?fe.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:n}){var i;return await fe.isNetworkSupported((i=E.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)?Ut.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}){var a;return await fe.isNetworkSupported((a=E.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)?(await Ut.api.post({path:"/v1/generators/onrampurl",params:{projectId:D.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:n,presetFiatAmount:r}})).url:""},async getOnrampOptions(){var e;if(!await fe.isNetworkSupported((e=E.state.activeCaipNetwork)==null?void 0:e.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await fe.get({path:"/v1/onramp/options"})}catch{return Ev}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:n}){var r;try{return await fe.isNetworkSupported((r=E.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?await Ut.api.post({path:"/v1/onramp/quote",params:{projectId:D.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){var s;return await fe.isNetworkSupported((s=E.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)?fe.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){var r;return await fe.isNetworkSupported((r=E.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)?Ut.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:D.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){Ut.clientId=t,Ut.api=new sa({baseUrl:Vf,clientId:t})}},ws={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"}},bv={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,n=encodeURIComponent(s);if(t===ws.PHANTOM.id&&!("phantom"in window)){const r=s.startsWith("https")?"https":"http",i=s.split("/")[2],o=encodeURIComponent(`${r}://${i}`);window.location.href=`${ws.PHANTOM.url}/ul/browse/${n}?ref=${o}`}if(t===ws.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${ws.SOLFLARE.url}/ul/v1/browse/${n}?ref=${n}`),e===$.CHAIN.SOLANA&&t===ws.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${ws.COINBASE.url}/dapp?cb_url=${n}`),e===$.CHAIN.BITCOIN&&t===ws.BINANCE.id&&!("binancew3w"in window)){const r=E.state.activeCaipNetwork,i=window.btoa("/pages/browser/index"),o=window.btoa(`url=${n}&defaultChainId=${(r==null?void 0:r.id)??1}`),a=new URL(ws.BINANCE.deeplink);a.searchParams.set("appId",ws.BINANCE.appId),a.searchParams.set("startPagePath",i),a.searchParams.set("startPageQuery",o);const c=new URL(ws.BINANCE.url);c.searchParams.set("_dp",window.btoa(a.toString())),window.location.href=c.toString()}}},vv=Object.freeze({enabled:!0,events:[]}),Cv=new sa({baseUrl:X.getAnalyticsUrl(),clientId:null}),_v=5,Av=60*1e3,Pn=Ge({...vv}),Sv={state:Pn,subscribeKey(t,e){return At(Pn,t,e)},async sendError(t,e){if(!Pn.enabled)return;const s=Date.now();if(Pn.events.filter(i=>{const o=new Date(i.properties.timestamp||"").getTime();return s-o<Av}).length>=_v)return;const r={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};Pn.events.push(r);try{if(typeof window>"u")return;const{projectId:i,sdkType:o,sdkVersion:a}=D.state;await Cv.post({path:"/e",params:{projectId:i,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:X.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(){Pn.enabled=!0},disable(){Pn.enabled=!1},clearEvents(){Pn.events=[]}};class Ur 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,Ur.prototype);let r=!1;if(n instanceof Error&&typeof n.stack=="string"&&n.stack){const i=n.stack,o=i.indexOf(`
3
+ `);if(o>-1){const a=i.substring(o+1);this.stack=`${this.name}: ${this.message}
4
+ ${a}`,r=!0}}r||(Error.captureStackTrace?Error.captureStackTrace(this,Ur):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Hu(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==null?void 0:t.message)||JSON.stringify(t):s=String(t)}catch(r){s="Unknown error",console.error("Error parsing error message",r)}const n=t instanceof Ur?t:new Ur(s,e,t);throw Sv.sendError(n,n.category),n}function Ns(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 Hu(a,e)}}:i=(...o)=>{try{return r(...o)}catch(a){return Hu(a,e)}},s[n]=i}else s[n]=r}),s}const rs=Ge({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),Iv={state:rs,subscribeNetworkImages(t){return _t(rs.networkImages,()=>t(rs.networkImages))},subscribeKey(t,e){return At(rs,t,e)},subscribe(t){return _t(rs,()=>t(rs))},setWalletImage(t,e){rs.walletImages[t]=e},setNetworkImage(t,e){rs.networkImages[t]=e},setChainImage(t,e){rs.chainImages[t]=e},setConnectorImage(t,e){rs.connectorImages={...rs.connectorImages,[t]:e}},setTokenImage(t,e){rs.tokenImages[t]=e},setCurrencyImage(t,e){rs.currencyImages[t]=e}},Cs=Ns(Iv),zu={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:"",sui:"",stacks:"",ton:"20f673c0-095e-49b2-07cf-eb5049dcf600"},Zc=Ge({networkImagePromises:{}}),Kf={async fetchWalletImage(t){if(t)return await te._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(Zc.networkImagePromises[t]||(Zc.networkImagePromises[t]=te._fetchNetworkImage(t)),await Zc.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return Cs.state.walletImages[t]},getWalletImage(t){if(t!=null&&t.image_url)return t==null?void 0:t.image_url;if(t!=null&&t.image_id)return Cs.state.walletImages[t.image_id]},getNetworkImage(t){var e,s,n;if((e=t==null?void 0:t.assets)!=null&&e.imageUrl)return(s=t==null?void 0:t.assets)==null?void 0:s.imageUrl;if((n=t==null?void 0:t.assets)!=null&&n.imageId)return Cs.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return Cs.state.networkImages[t]},getConnectorImage(t){var e;if(t!=null&&t.imageUrl)return t.imageUrl;if((e=t==null?void 0:t.info)!=null&&e.icon)return t.info.icon;if(t!=null&&t.imageId)return Cs.state.connectorImages[t.imageId]},getChainImage(t){return Cs.state.networkImages[zu[t]]},getTokenImage(t){if(t)return Cs.state.tokenImages[t]},getWalletImageUrl(t){if(!t)return"";const{projectId:e,sdkType:s,sdkVersion:n}=D.state,r=new URL(`${$.W3M_API_URL}/getWalletImage/${t}`);return r.searchParams.set("projectId",e),r.searchParams.set("st",s),r.searchParams.set("sv",n),r.toString()},getAssetImageUrl(t){if(!t)return"";const{projectId:e,sdkType:s,sdkVersion:n}=D.state,r=new URL(`${$.W3M_API_URL}/public/getAssetImage/${t}`);return r.searchParams.set("projectId",e),r.searchParams.set("st",s),r.searchParams.set("sv",n),r.toString()},getChainNamespaceImageUrl(t){return this.getAssetImageUrl(zu[t])}},Nv=X.getAnalyticsUrl(),Tv=new sa({baseUrl:Nv,clientId:null}),Rv=["MODAL_CREATED"],Ov=45,Vu=1e3*10,Qe=Ge({timestamp:Date.now(),lastFlush:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"},pendingEvents:[],subscribedToVisibilityChange:!1,walletImpressions:[]}),Ee={state:Qe,subscribe(t){return _t(Qe,()=>t(Qe))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=D.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},shouldFlushEvents(){const t=JSON.stringify(Qe.pendingEvents).length/1024>Ov,e=Qe.lastFlush+Vu<Date.now();return t||e},_setPendingEvent(t){var e,s;try{let n=(e=E.getAccountData())==null?void 0:e.address;if("address"in t.data&&t.data.address&&(n=t.data.address),Rv.includes(t.data.event)||typeof window>"u")return;const r=(s=E.getActiveCaipNetwork())==null?void 0:s.caipNetworkId;this.state.pendingEvents.push({eventId:X.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:n,properties:{..."properties"in t.data?t.data.properties:{},caipNetworkId:r}}}),Qe.reportedErrors.FORBIDDEN=!1,Ee.shouldFlushEvents()&&Ee._submitPendingEvents()}catch(n){console.warn("_setPendingEvent",n)}},sendEvent(t){var s;Qe.timestamp=Date.now(),Qe.data=t;const e=["INITIALIZE","CONNECT_SUCCESS","SOCIAL_LOGIN_SUCCESS"];((s=D.state.features)!=null&&s.analytics||e.includes(t.event))&&Ee._setPendingEvent(Qe),this.subscribeToFlushTriggers()},sendWalletImpressionEvent(t){Qe.walletImpressions.push(t)},_transformPendingEventsForBatch(t){try{return t.filter(e=>e.props.event!=="WALLET_IMPRESSION_V2")}catch{return t}},_submitPendingEvents(){if(Qe.lastFlush=Date.now(),!(Qe.pendingEvents.length===0&&Qe.walletImpressions.length===0))try{const t=Ee._transformPendingEventsForBatch(Qe.pendingEvents);Qe.walletImpressions.length&&t.push({eventId:X.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:Date.now(),props:{type:"track",event:"WALLET_IMPRESSION_V2",items:[...Qe.walletImpressions]}}),Tv.sendBeacon({path:"/batch",params:Ee.getSdkProperties(),body:t}),Qe.reportedErrors.FORBIDDEN=!1,Qe.pendingEvents=[],Qe.walletImpressions=[]}catch{Qe.reportedErrors.FORBIDDEN=!0}},subscribeToFlushTriggers(){var t,e,s;Qe.subscribedToVisibilityChange||typeof document>"u"||(Qe.subscribedToVisibilityChange=!0,(t=document==null?void 0:document.addEventListener)==null||t.call(document,"visibilitychange",()=>{document.visibilityState==="hidden"&&Ee._submitPendingEvents()}),(e=document==null?void 0:document.addEventListener)==null||e.call(document,"freeze",()=>{Ee._submitPendingEvents()}),(s=window==null?void 0:window.addEventListener)==null||s.call(window,"pagehide",()=>{Ee._submitPendingEvents()}),setInterval(()=>{Ee._submitPendingEvents()},Vu))}},Pv=X.getApiUrl(),$t=new sa({baseUrl:Pv,clientId:null}),xv=40,Ku=4,kv=20,we=Ge({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}}}),te={state:we,subscribeKey(t,e){return At(we,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=D.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return D.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${$t.baseUrl}/getWalletImage/${t}`,s=await $t.getBlob({path:e,params:te._getSdkProperties()});Cs.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${$t.baseUrl}/public/getAssetImage/${t}`,s=await $t.getBlob({path:e,params:te._getSdkProperties()});Cs.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${$t.baseUrl}/public/getAssetImage/${t}`,s=await $t.getBlob({path:e,params:te._getSdkProperties()});Cs.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${$t.baseUrl}/public/getCurrencyImage/${t}`,s=await $t.getBlob({path:e,params:te._getSdkProperties()});Cs.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${$t.baseUrl}/public/getTokenImage/${t}`,s=await $t.getBlob({path:e,params:te._getSdkProperties()});Cs.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){const e=t.length,s=X.isMobile()?t==null?void 0:t.filter(r=>r.mobile_link||r.webapp_link?!0:Object.values(ws).map(o=>o.id).includes(r.id)):t,n=e-s.length;return{filteredWallets:s,mobileFilteredOutWalletsLength:n}},async fetchProjectConfig(){return(await $t.get({path:"/appkit/v1/config",params:te._getSdkProperties()})).features},async fetchUsage(){try{const t=await $t.get({path:"/appkit/v1/project-limits",params:te._getSdkProperties()}),{tier:e,isAboveMauLimit:s,isAboveRpcLimit:n}=t.planLimits,r=e==="starter",i=s||n;te.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 $t.get({path:"/projects/v1/origins",params:te._getSdkProperties()});return t}catch(t){if(t instanceof Error&&t.cause instanceof Response){const e=t.cause.status;if(e===$.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)throw new Error("RATE_LIMITED",{cause:t});if(e>=$.HTTP_STATUS_CODES.SERVER_ERROR&&e<600)throw new Error("SERVER_ERROR",{cause:t});return[]}return[]}},async fetchNetworkImages(){const t=E.getAllRequestedCaipNetworks(),e=t==null?void 0:t.map(({assets:s})=>s==null?void 0:s.imageId).filter(Boolean).filter(s=>!Kf.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>te._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=z.state,e=t.map(({imageId:s})=>s).filter(Boolean);await Promise.allSettled(e.map(s=>te._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>te._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>te._fetchTokenImage(e)))},async fetchWallets(t){var o;const e=t.exclude??[];te._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(ws).map(a=>a.id));const n=await $t.get({path:"/getWallets",params:{...te._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:(o=t.include)==null?void 0:o.join(","),exclude:e.join(",")}}),{filteredWallets:r,mobileFilteredOutWalletsLength:i}=te._filterWalletsByPlatform(n==null?void 0:n.data);return{data:r||[],count:n==null?void 0:n.count,mobileFilteredOutWalletsLength:i}},async prefetchWalletRanks(){const t=z.state.connectors;if(!(t!=null&&t.length))return;const e={page:1,entries:20,badge:"certified"};if(e.names=t.map(r=>r.name).join(","),E.state.activeChain===$.CHAIN.EVM){const r=[...t.flatMap(i=>{var o;return((o=i.connectors)==null?void 0:o.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}))||[]}),...t.map(i=>{var o;return(o=i.info)==null?void 0:o.rdns})].filter(i=>typeof i=="string"&&i.length>0);r.length&&(e.rdns=r.join(","))}const{data:s}=await te.fetchWallets(e);we.explorerWallets=s,z.extendConnectorsWithExplorerWallets(s);const n=E.getRequestedCaipNetworkIds().join(",");we.explorerFilteredWallets=s.filter(r=>{var i;return(i=r.chains)==null?void 0:i.some(o=>n.includes(o))})},async fetchFeaturedWallets(){const{featuredWalletIds:t}=D.state;if(t!=null&&t.length){const e={...te._getSdkProperties(),page:1,entries:(t==null?void 0:t.length)??Ku,include:t},{data:s}=await te.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=>te._fetchWalletImage(i))),we.featured=n,we.allFeatured=n}},async fetchRecommendedWallets(){try{we.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=D.state,n=[...e??[],...s??[]].filter(Boolean),r=E.getRequestedCaipNetworkIds().join(","),i={page:1,entries:Ku,include:t,exclude:n,chains:r},{data:o,count:a}=await te.fetchWallets(i),c=F.getRecentWallets(),l=o.map(u=>u.image_id).filter(Boolean),d=c.map(u=>u.image_id).filter(Boolean);await Promise.allSettled([...l,...d].map(u=>te._fetchWalletImage(u))),we.recommended=o,we.allRecommended=o,we.count=a??0}catch{}finally{we.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:n}=D.state,r=E.getRequestedCaipNetworkIds().join(","),i=[...we.recommended.map(({id:u})=>u),...s??[],...n??[]].filter(Boolean),o={page:t,entries:xv,include:e,exclude:i,chains:r},{data:a,count:c,mobileFilteredOutWalletsLength:l}=await te.fetchWallets(o);we.mobileFilteredOutWalletsLength=l+(we.mobileFilteredOutWalletsLength??0);const d=a.slice(0,kv).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(d.map(u=>te._fetchWalletImage(u))),we.wallets=X.uniqueBy([...we.wallets,...te._filterOutExtensions(a)],"id").filter(u=>{var h;return(h=u.chains)==null?void 0:h.some(p=>r.includes(p))}),we.count=c>we.count?c:we.count,we.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await te.fetchWallets(e);s&&s.forEach(n=>{we.excludedWallets.push({rdns:n.rdns,name:n.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:n}=D.state,r=E.getRequestedCaipNetworkIds().join(",");we.search=[];const i={page:1,entries:100,search:t==null?void 0:t.trim(),badge_type:e,include:s,exclude:n,chains:r},{data:o}=await te.fetchWallets(i);Ee.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=>te._fetchWalletImage(c)),X.wait(300)]),we.search=te._filterOutExtensions(o)},initPromise(t,e){const s=we.promises[t];return s||(we.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:n=!0,fetchWalletRanks:r=!0}={}){const i=[t&&te.initPromise("connectorImages",te.fetchConnectorImages),e&&te.initPromise("featuredWallets",te.fetchFeaturedWallets),s&&te.initPromise("recommendedWallets",te.fetchRecommendedWallets),n&&te.initPromise("networkImages",te.fetchNetworkImages),r&&te.initPromise("walletRanks",te.prefetchWalletRanks)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){var t;(t=D.state.features)!=null&&t.analytics&&te.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await $t.get({path:"/getAnalyticsConfig",params:te._getSdkProperties()});D.setFeatures({analytics:t})}catch{D.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!(t!=null&&t.length)){we.featured=we.allFeatured,we.recommended=we.allRecommended;return}const e=E.getRequestedCaipNetworkIds().join(",");we.featured=we.allFeatured.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),we.recommended=we.allRecommended.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),we.filteredWallets=we.wallets.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))})},clearFilterByNamespaces(){we.filteredWallets=[]},setFilterByNamespace(t){if(!t){we.featured=we.allFeatured,we.recommended=we.allRecommended;return}const e=E.getRequestedCaipNetworkIds().join(",");we.featured=we.allFeatured.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),we.recommended=we.allRecommended.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))}),we.filteredWallets=we.wallets.filter(s=>{var n;return(n=s.chains)==null?void 0:n.some(r=>e.includes(r))})}},Uv=["ConnectingExternal","ConnectingMultiChain","ConnectingSocial","ConnectingFarcaster"],je=Ge({view:"Connect",history:["Connect"],transactionStack:[]}),$v={state:je,subscribeKey(t,e){return At(je,t,e)},pushTransactionStack(t){je.transactionStack.push(t)},popTransactionStack(t){const e=je.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:n,onCancel:r}=e;switch(t){case"success":s==null||s();break;case"error":n==null||n(),ue.goBack();break;case"cancel":r==null||r(),ue.goBack();break}},push(t,e){let s=t,n=e;te.state.plan.hasExceededUsageLimit&&Uv.includes(t)&&(s="UsageExceeded",n=void 0),s!==je.view&&(je.view=s,je.history.push(s),je.data=n)},reset(t,e){je.view=t,je.history=[t],je.data=e},replace(t,e){je.history.at(-1)===t||(je.view=t,je.history[je.history.length-1]=t,je.data=e)},goBack(){var n,r;const t=E.state.activeCaipAddress,e=ue.state.view==="ConnectingFarcaster",s=!t&&e;if(je.history.length>1){je.history.pop();const[i]=je.history.slice(-1);i&&(t&&i==="Connect"?je.view="Account":je.view=i)}else Te.close();(n=je.data)!=null&&n.wallet&&(je.data.wallet=void 0),(r=je.data)!=null&&r.redirectView&&(je.data.redirectView=void 0),setTimeout(()=>{var i,o,a;if(s){E.setAccountProp("farcasterUrl",void 0,E.state.activeChain);const c=z.getAuthConnector();(i=c==null?void 0:c.provider)==null||i.reload();const l=lo(D.state);(a=(o=c==null?void 0:c.provider)==null?void 0:o.syncDappData)==null||a.call(o,{metadata:l.metadata,sdkVersion:l.sdkVersion,projectId:l.projectId,sdkType:l.sdkType})}},100)},goBackToIndex(t){if(je.history.length>1){je.history=je.history.slice(0,t+1);const[e]=je.history.slice(-1);e&&(je.view=e)}},goBackOrCloseModal(){ue.state.history.length>1?ue.goBack():Te.close()}},ue=Ns($v),on=Ge({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Jl={state:on,subscribe(t){return _t(on,()=>t(on))},setThemeMode(t){on.themeMode=t;try{const e=z.getAuthConnector();if(e){const s=Jl.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:ao(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){on.themeVariables={...on.themeVariables,...t};try{const e=z.getAuthConnector();if(e){const s=Jl.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:ao(on.themeVariables,on.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return lo(on)}},Kt=Ns(Jl),Gf=Object.fromEntries(Af.map(t=>[t,void 0])),Dv=Object.fromEntries(Af.map(t=>[t,!0])),ke=Ge({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:Gf,filterByNamespaceMap:Dv}),Lv={state:ke,subscribe(t){return _t(ke,()=>{t(ke)})},subscribeKey(t,e){return At(ke,t,e)},initialize(t){t.forEach(e=>{const s=F.getConnectedConnectorId(e);s&&z.setConnectorId(s,e)})},setActiveConnector(t){t&&(ke.activeConnector=uo(t))},setConnectors(t){t.filter(r=>!ke.allConnectors.some(i=>i.id===r.id&&z.getConnectorName(i.name)===z.getConnectorName(r.name)&&i.chain===r.chain)).forEach(r=>{r.type!=="MULTI_CHAIN"&&ke.allConnectors.push(uo(r))});const s=z.getEnabledNamespaces(),n=z.getEnabledConnectors(s);ke.connectors=z.mergeMultiChainConnectors(n)},filterByNamespaces(t){Object.keys(ke.filterByNamespaceMap).forEach(e=>{ke.filterByNamespaceMap[e]=!1}),t.forEach(e=>{ke.filterByNamespaceMap[e]=!0}),z.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){ke.filterByNamespaceMap[t]=e,z.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=z.getEnabledNamespaces(),e=z.getEnabledConnectors(t),s=z.areAllNamespacesEnabled();ke.connectors=z.mergeMultiChainConnectors(e),s?te.clearFilterByNamespaces():te.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(ke.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return ke.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(ke.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=z.generateConnectorMapByName(t),s=[];return e.forEach(n=>{const r=n[0],i=(r==null?void 0:r.id)===$.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==null?void 0:r.id)||""}):r&&s.push(r)}),s},generateConnectorMapByName(t){const e=new Map;return t.forEach(s=>{const{name:n}=s,r=z.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){var e,s,n;if(t.id===$.CONNECTOR_ID.AUTH){const r=t,i=lo(D.state),o=Kt.getSnapshot().themeMode,a=Kt.getSnapshot().themeVariables;(s=(e=r==null?void 0:r.provider)==null?void 0:e.syncDappData)==null||s.call(e,{metadata:i.metadata,sdkVersion:i.sdkVersion,projectId:i.projectId,sdkType:i.sdkType}),(n=r==null?void 0:r.provider)==null||n.syncTheme({themeMode:o,themeVariables:a,w3mThemeVariables:ao(a,o)}),z.setConnectors([t])}else z.setConnectors([t])},getAuthConnector(t){var n;const e=t||E.state.activeChain,s=ke.connectors.find(r=>r.id===$.CONNECTOR_ID.AUTH);if(s)return(n=s==null?void 0:s.connectors)!=null&&n.length?s.connectors.find(i=>i.chain===e):s},getAnnouncedConnectorRdns(){return ke.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>{var e;return(e=t.info)==null?void 0:e.rdns})},getConnectorById(t){return ke.allConnectors.find(e=>e.id===t)},getConnector({id:t,namespace:e}){const s=e||E.state.activeChain;return ke.allConnectors.filter(i=>i.chain===s).find(i=>i.id===t||i.explorerId===t)},syncIfAuthConnector(t){var i,o;if(t.id!=="AUTH")return;const e=t,s=lo(D.state),n=Kt.getSnapshot().themeMode,r=Kt.getSnapshot().themeVariables;(o=(i=e==null?void 0:e.provider)==null?void 0:i.syncDappData)==null||o.call(i,{metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:n,themeVariables:r,w3mThemeVariables:ao(r,n)})},getConnectorsByNamespace(t){const e=ke.allConnectors.filter(s=>s.chain===t);return z.mergeMultiChainConnectors(e)},canSwitchToSmartAccount(t){return E.checkIfSmartAccountEnabled()&&us(t)===et.ACCOUNT_TYPES.EOA},selectWalletConnector(t){var r;const e=(r=ue.state.data)==null?void 0:r.redirectView,s=E.state.activeChain,n=s?z.getConnector({id:t.id,namespace:s}):void 0;bv.handleMobileDeeplinkRedirect((n==null?void 0:n.explorerId)||t.id,E.state.activeChain),n?ue.push("ConnectingExternal",{connector:n,wallet:t,redirectView:e}):ue.push("ConnectingWalletConnect",{wallet:t,redirectView:e})},getConnectors(t){return t?z.getConnectorsByNamespace(t):z.mergeMultiChainConnectors(ke.allConnectors)},setFilterByNamespace(t){ke.filterByNamespace=t,ke.connectors=z.getConnectors(t),te.setFilterByNamespace(t)},setConnectorId(t,e){t&&(ke.activeConnectorIds={...ke.activeConnectorIds,[e]:t},F.setConnectedConnectorId(e,t))},removeConnectorId(t){ke.activeConnectorIds={...ke.activeConnectorIds,[t]:void 0},F.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return ke.activeConnectorIds[t]},isConnected(t){return t?!!ke.activeConnectorIds[t]:Object.values(ke.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){ke.activeConnectorIds={...Gf}},extendConnectorsWithExplorerWallets(t){ke.allConnectors.forEach(n=>{const r=t.find(i=>{var o;return i.id===n.id||i.rdns&&i.rdns===((o=n.info)==null?void 0:o.rdns)});r&&(n.explorerWallet=r)});const e=z.getEnabledNamespaces(),s=z.getEnabledConnectors(e);ke.connectors=z.mergeMultiChainConnectors(s)}},z=Ns(Lv),Mv=1e3,xi={checkNamespaceConnectorId(t,e){return z.getConnectorId(t)===e},isSocialProvider(t){return Ne.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&&z.setActiveConnector(e),r==null||r(X.isMobile()&&t),n){const l=Te.subscribeKey("open",d=>{d||(ue.state.view!==n&&ue.replace(n),l(),a(new Error("Modal closed")))})}const c=E.subscribeKey("activeCaipAddress",l=>{l&&(i==null||i(),s&&Te.close(),c(),o(dt.parseCaipAddress(l)))})})},connectExternal(t){return new Promise((e,s)=>{const n=E.subscribeKey("activeCaipAddress",r=>{r&&(Te.close(),n(),e(dt.parseCaipAddress(r)))});G.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||E.state.activeChain,l=E.subscribeKey("activeCaipAddress",d=>{d&&(s&&Te.close(),l())});return new Promise((d,u)=>{async function h(g){var f;if((f=g.data)!=null&&f.resultUri)if(g.origin===$.SECURE_SITE_SDK_ORIGIN){window.removeEventListener("message",h,!1);try{const w=z.getAuthConnector(c);if(w&&!o){i&&i.close(),o=!0;const v=g.data.resultUri;Ee.sendEvent({type:"track",event:"SOCIAL_LOGIN_REQUEST_USER_DATA",properties:{provider:t}}),F.setConnectedSocialProvider(t),await G.connectExternal({id:w.id,type:w.type,socialUri:v},w.chain);const N=E.state.activeCaipAddress;if(!N){u(new Error("Failed to connect"));return}d(dt.parseCaipAddress(N)),Ee.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:t}})}}catch(w){Ee.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:t,message:X.parseError(w)}}),u(new Error("Failed to connect"))}}else Ee.sendEvent({type:"track",event:"SOCIAL_LOGIN_ERROR",properties:{provider:t,message:"Untrusted Origin"}})}async function p(){if(Ee.sendEvent({type:"track",event:"SOCIAL_LOGIN_STARTED",properties:{provider:t}}),t==="farcaster"){n==null||n();const g=Te.subscribeKey("open",w=>{!w&&t==="farcaster"&&(u(new Error("Popup closed")),r==null||r(),g())}),f=z.getAuthConnector();if(f){const w=E.getAccountData(c);if(!(w!=null&&w.farcasterUrl))try{const{url:v}=await f.provider.getFarcasterUri();E.setAccountProp("farcasterUrl",v,c)}catch{u(new Error("Failed to connect to farcaster"))}}}else{const g=z.getAuthConnector();a=X.returnOpenHref(`${$.SECURE_SITE_SDK_ORIGIN}/loading`,"popupWindow","width=600,height=800,scrollbars=yes");try{if(g){const{uri:f}=await g.provider.getSocialRedirectUri({provider:t});if(a&&f){a.location.href=f,i=a;const w=setInterval(()=>{i!=null&&i.closed&&!o&&(u(new Error("Popup closed")),clearInterval(w))},1e3);window.addEventListener("message",h,!1)}else a==null||a.close(),u(new Error("Failed to initiate social connection"))}}catch{u(new Error("Failed to initiate social connection")),a==null||a.close()}}}p()})},connectEmail({closeModalOnConnect:t=!0,redirectViewOnModalClose:e="Connect",onOpen:s,onConnect:n}){return new Promise((r,i)=>{if(s==null||s(),e){const a=Te.subscribeKey("open",c=>{c||(ue.state.view!==e&&ue.replace(e),a(),i(new Error("Modal closed")))})}const o=E.subscribeKey("activeCaipAddress",a=>{a&&(n==null||n(),t&&Te.close(),o(),r(dt.parseCaipAddress(a)))})})},async updateEmail(){const t=F.getConnectedConnectorId(E.state.activeChain),e=z.getAuthConnector();if(!e)throw new Error("No auth connector found");if(t!==$.CONNECTOR_ID.AUTH)throw new Error("Not connected to email or social");const s=e.provider.getEmail()??"";return await Te.open({view:"UpdateEmailWallet",data:{email:s,redirectView:void 0}}),new Promise((n,r)=>{const i=setInterval(()=>{const a=e.provider.getEmail()??"";a!==s&&(Te.close(),clearInterval(i),o(),n({email:a}))},Mv),o=Te.subscribeKey("open",a=>{a||(ue.state.view!=="Connect"&&ue.push("Connect"),clearInterval(i),o(),r(new Error("Modal closed")))})})},canSwitchToSmartAccount(t){return E.checkIfSmartAccountEnabled()&&us(t)===et.ACCOUNT_TYPES.EOA}};function Yf(){var n,r;const t=((n=E.state.activeCaipNetwork)==null?void 0:n.chainNamespace)||"eip155",e=((r=E.state.activeCaipNetwork)==null?void 0:r.id)||1,s=Ne.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`}function us(t){var s;return(s=E.getAccountData(t))==null?void 0:s.preferredAccountType}function Hi(t){var e,s;return t?(s=(e=E.state.chains.get(t))==null?void 0:e.networkState)==null?void 0:s.caipNetwork:E.state.activeCaipNetwork}const cc={getConnectionStatus(t,e){const s=z.state.activeConnectorIds[e],n=G.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){var a;const e=!!((a=D.state.remoteFeatures)!=null&&a.multiWallet),s=z.state.activeConnectorIds[t],n=G.getConnections(t),i=(G.state.recentConnections.get(t)??[]).filter(c=>z.getConnectorById(c.connectorId)),o=cc.excludeExistingConnections([...n.map(c=>c.connectorId),...s?[s]:[]],i);return e?{connections:n,recentConnections:o}:{connections:n.filter(c=>c.connectorId.toLowerCase()===(s==null?void 0:s.toLowerCase())),recentConnections:[]}},onConnectMobile(t){const e=G.state.wcUri;if(t!=null&&t.mobile_link&&e)try{G.setWcError(!1);const{mobile_link:s,link_mode:n,name:r}=t,{redirect:i,redirectUniversalLink:o,href:a}=X.formatNativeUrl(s,e,n),c=i,l=o,d=X.isIframe()?"_top":"_self";G.setWcLinking({name:r,href:a}),G.setRecentWallet(t),D.state.experimental_preferUniversalLinks&&l?X.openHref(l,d):X.openHref(c,d)}catch(s){Ee.sendEvent({type:"track",event:"CONNECT_PROXY_ERROR",properties:{message:s instanceof Error?s.message:"Error parsing the deep link",uri:e,mobile_link:t.mobile_link,name:t.name}}),G.setWcError(!0)}}},zr=Ge({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1,connectingWallet:void 0}),hs={state:zr,subscribe(t){return _t(zr,()=>t(zr))},subscribeOpen(t){return At(zr,"open",t)},set(t){Object.assign(zr,{...zr,...t})}},Ye=Ge({transactions:[],transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),Bv={state:Ye,subscribe(t){return _t(Ye,()=>t(Ye))},setLastNetworkInView(t){Ye.lastNetworkInView=t},async fetchTransactions(t){var e;if(!t)throw new Error("Transactions can't be fetched without an accountAddress");Ye.loading=!0;try{const s=await fe.fetchTransactions({account:t,cursor:Ye.next,chainId:(e=E.state.activeCaipNetwork)==null?void 0:e.caipNetworkId}),n=ja.filterSpamTransactions(s.data),r=ja.filterByConnectedChain(n),i=[...Ye.transactions,...r];Ye.loading=!1,Ye.transactions=i,Ye.transactionsByYear=ja.groupTransactionsByYearAndMonth(Ye.transactionsByYear,r),Ye.empty=i.length===0,Ye.next=s.next?s.next:void 0}catch{const n=E.state.activeChain;Ee.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:D.state.projectId,cursor:Ye.next,isSmartAccount:us(n)===et.ACCOUNT_TYPES.SMART_ACCOUNT}}),Ys.showError("Failed to fetch transactions"),Ye.loading=!1,Ye.empty=!0,Ye.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,d)=>new Date(d.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),s},filterSpamTransactions(t){return t.filter(e=>{var n;return!((n=e.transfers)==null?void 0:n.every(r=>{var i;return((i=r.nft_info)==null?void 0:i.flags.is_spam)===!0}))})},filterByConnectedChain(t){var n;const e=(n=E.state.activeCaipNetwork)==null?void 0:n.caipNetworkId;return t.filter(r=>r.metadata.chain===e)},clearCursor(){Ye.next=void 0},resetTransactions(){Ye.transactions=[],Ye.transactionsByYear={},Ye.lastNetworkInView=void 0,Ye.loading=!1,Ye.empty=!1,Ye.next=void 0}},ja=Ns(Bv,"API_ERROR"),Ie=Ge({connections:new Map,recentConnections:new Map,isSwitchingConnection:!1,wcError:!1,wcFetchingUri:!1,buffering:!1,status:"disconnected"});let ir;const jv={state:Ie,subscribe(t){return _t(Ie,()=>t(Ie))},subscribeKey(t,e){return At(Ie,t,e)},_getClient(){return Ie._client},setClient(t){Ie._client=uo(t)},initialize(t){const e=t.filter(s=>!!s.namespace).map(s=>s.namespace);G.syncStorageConnections(e)},syncStorageConnections(t){const e=F.getConnections(),s=t??Array.from(E.state.chains.keys());for(const n of s){const r=e[n]??[],i=new Map(Ie.recentConnections);i.set(n,r),Ie.recentConnections=i}},getConnections(t){return t?Ie.connections.get(t)??[]:[]},hasAnyConnection(t){const e=G.state.connections;return Array.from(e.values()).flatMap(s=>s).some(({connectorId:s})=>s===t)},async connectWalletConnect({cache:t="auto"}={}){var s,n,r,i;Ie.wcFetchingUri=!0;const e=X.isTelegram()||X.isSafari()&&X.isIos();if(t==="always"||t==="auto"&&e){if(ir){await ir,ir=void 0;return}if(!X.isPairingExpired(Ie==null?void 0:Ie.wcPairingExpiry)){const o=Ie.wcUri;Ie.wcUri=o;return}ir=(n=(s=G._getClient())==null?void 0:s.connectWalletConnect)==null?void 0:n.call(s).catch(()=>{}),G.state.status="connecting",await ir,ir=void 0,Ie.wcPairingExpiry=void 0,G.state.status="connected"}else await((i=(r=G._getClient())==null?void 0:r.connectWalletConnect)==null?void 0:i.call(r))},async connectExternal(t,e,s=!0){var o,a,c;const n=await((a=(o=G._getClient())==null?void 0:o.connectExternal)==null?void 0:a.call(o,t));s&&E.setActiveNamespace(e);const r=z.state.allConnectors.find(l=>l.id===(t==null?void 0:t.id)),i=t.type==="AUTH"?"email":"browser";return Ee.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:i,name:(r==null?void 0:r.name)||"Unknown",view:ue.state.view,walletRank:(c=r==null?void 0:r.explorerWallet)==null?void 0:c.order}}),n},async reconnectExternal(t){var s,n;await((n=(s=G._getClient())==null?void 0:s.reconnectExternal)==null?void 0:n.call(s,t));const e=t.chain||E.state.activeChain;e&&z.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){var n;if(!e)return;Te.setLoading(!0,E.state.activeChain);const s=z.getAuthConnector();s&&(E.setAccountProp("preferredAccountType",t,e),await s.provider.setPreferredAccount(t),F.setPreferredAccountTypes(Object.entries(E.state.chains).reduce((r,[i,o])=>{const a=i,c=us(a);return c!==void 0&&(r[a]=c),r},{})),await G.reconnectExternal(s),Te.setLoading(!1,E.state.activeChain),Ee.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:((n=E.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}}))},async signMessage(t){var e;return(e=G._getClient())==null?void 0:e.signMessage(t)},parseUnits(t,e){var s;return(s=G._getClient())==null?void 0:s.parseUnits(t,e)},formatUnits(t,e){var s;return(s=G._getClient())==null?void 0:s.formatUnits(t,e)},updateBalance(t){var e;return(e=G._getClient())==null?void 0:e.updateBalance(t)},async sendTransaction(t){var e;return(e=G._getClient())==null?void 0:e.sendTransaction(t)},async getCapabilities(t){var e;return(e=G._getClient())==null?void 0:e.getCapabilities(t)},async grantPermissions(t){var e;return(e=G._getClient())==null?void 0:e.grantPermissions(t)},async walletGetAssets(t){var e;return((e=G._getClient())==null?void 0:e.walletGetAssets(t))??{}},async estimateGas(t){var e;return(e=G._getClient())==null?void 0:e.estimateGas(t)},async writeContract(t){var e;return(e=G._getClient())==null?void 0:e.writeContract(t)},async getEnsAddress(t){var e;return(e=G._getClient())==null?void 0:e.getEnsAddress(t)},async getEnsAvatar(t){var e;return(e=G._getClient())==null?void 0:e.getEnsAvatar(t)},checkInstalled(t){var e,s;return((s=(e=G._getClient())==null?void 0:e.checkInstalled)==null?void 0:s.call(e,t))||!1},resetWcConnection(){Ie.wcUri=void 0,Ie.wcPairingExpiry=void 0,Ie.wcLinking=void 0,Ie.recentWallet=void 0,Ie.wcFetchingUri=!1,Ie.status="disconnected",ja.resetTransactions(),F.deleteWalletConnectDeepLink(),F.deleteRecentWallet(),hs.set({connectingWallet:void 0})},resetUri(){Ie.wcUri=void 0,Ie.wcPairingExpiry=void 0,ir=void 0,Ie.wcFetchingUri=!1,hs.set({connectingWallet:void 0})},finalizeWcConnection(t){var n,r;const{wcLinking:e,recentWallet:s}=G.state;e&&F.setWalletConnectDeepLink(e),s&&F.setAppKitRecent(s),t&&Ee.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:t,properties:{method:e?"mobile":"qrcode",name:((r=(n=ue.state.data)==null?void 0:n.wallet)==null?void 0:r.name)||"Unknown",view:ue.state.view,walletRank:s==null?void 0:s.order}})},setWcBasic(t){Ie.wcBasic=t},setUri(t){Ie.wcUri=t,Ie.wcFetchingUri=!1,Ie.wcPairingExpiry=X.getPairingExpiry()},setWcLinking(t){Ie.wcLinking=t},setWcError(t){Ie.wcError=t,Ie.wcFetchingUri=!1,Ie.buffering=!1},setRecentWallet(t){Ie.recentWallet=t},setBuffering(t){Ie.buffering=t},setStatus(t){Ie.status=t},setIsSwitchingConnection(t){Ie.isSwitchingConnection=t},async disconnect({id:t,namespace:e,initialDisconnect:s}={}){var n;try{await((n=G._getClient())==null?void 0:n.disconnect({id:t,chainNamespace:e,initialDisconnect:s}))}catch(r){throw new Ur("Failed to disconnect","INTERNAL_SDK_ERROR",r)}},async disconnectConnector({id:t,namespace:e}){var s;try{await((s=G._getClient())==null?void 0:s.disconnectConnector({id:t,namespace:e}))}catch(n){throw new Ur("Failed to disconnect connector","INTERNAL_SDK_ERROR",n)}},setConnections(t,e){const s=new Map(Ie.connections);s.set(e,t),Ie.connections=s},async handleAuthAccountSwitch({address:t,namespace:e}){var i,o;const s=E.getAccountData(e),n=(o=(i=s==null?void 0:s.user)==null?void 0:i.accounts)==null?void 0:o.find(a=>a.type==="smartAccount"),r=n&&n.address.toLowerCase()===t.toLowerCase()&&xi.canSwitchToSmartAccount(e)?"smartAccount":"eoa";await G.setPreferredAccountType(r,e)},async handleActiveConnection({connection:t,namespace:e,address:s}){const n=z.getConnectorById(t.connectorId),r=t.connectorId===$.CONNECTOR_ID.AUTH;if(!n)throw new Error(`No connector found for connection: ${t.connectorId}`);if(r)s&&await G.handleAuthAccountSwitch({address:s,namespace:e});else{const i=await G.connectExternal({id:n.id,type:n.type,provider:n.provider,address:s,chain:e},e);return i==null?void 0:i.address}return s},async handleDisconnectedConnection({connection:t,namespace:e,address:s,closeModalOnConnect:n}){var l,d;const r=z.getConnectorById(t.connectorId),i=(d=(l=t.auth)==null?void 0:l.name)==null?void 0:d.toLowerCase(),o=t.connectorId===$.CONNECTOR_ID.AUTH,a=t.connectorId===$.CONNECTOR_ID.WALLET_CONNECT;if(!r)throw new Error(`No connector found for connection: ${t.connectorId}`);let c;if(o)if(i&&xi.isSocialProvider(i)){const{address:u}=await xi.connectSocial({social:i,closeModalOnConnect:n,onOpenFarcaster(){Te.open({view:"ConnectingFarcaster"})},onConnect(){ue.replace("ProfileWallets")}});c=u}else{const{address:u}=await xi.connectEmail({closeModalOnConnect:n,onOpen(){Te.open({view:"EmailLogin"})},onConnect(){ue.replace("ProfileWallets")}});c=u}else if(a){const{address:u}=await xi.connectWalletConnect({walletConnect:!0,connector:r,closeModalOnConnect:n,onOpen(h){const p=h?"AllWallets":"ConnectingWalletConnect";Te.state.open?ue.push(p):Te.open({view:p})},onConnect(){ue.replace("ProfileWallets")}});c=u}else{const u=await G.connectExternal({id:r.id,type:r.type,provider:r.provider,chain:e},e);u&&(c=u.address)}return o&&s&&await G.handleAuthAccountSwitch({address:s,namespace:e}),c},async switchConnection({connection:t,address:e,namespace:s,closeModalOnConnect:n,onChange:r}){var c;let i;const o=(c=E.getAccountData(s))==null?void 0:c.caipAddress;if(o){const{address:l}=dt.parseCaipAddress(o);i=l}const a=cc.getConnectionStatus(t,s);switch(a){case"connected":case"active":{const l=await G.handleActiveConnection({connection:t,namespace:s,address:e});if(i&&l){const d=l.toLowerCase()!==i.toLowerCase();r==null||r({address:l,namespace:s,hasSwitchedAccount:d,hasSwitchedWallet:a==="active"})}break}case"disconnected":{const l=await G.handleDisconnectedConnection({connection:t,namespace:s,address:e,closeModalOnConnect:n});l&&(r==null||r({address:l,namespace:s,hasSwitchedAccount:!0,hasSwitchedWallet:!0}));break}default:throw new Error(`Invalid connection status: ${a}`)}}},G=Ns(jv),Jc={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 Hf(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 Xc;async function Gu(){if(!Xc){const{createPublicClient:t,http:e,defineChain:s}=await Dt(async()=>{const{createPublicClient:n,http:r,defineChain:i}=await import("./index-BWLwEJXK.js");return{createPublicClient:n,http:r,defineChain:i}},__vite__mapDeps([0,1,2,3,4,5,6,7]));Xc={createPublicClient:t,http:e,defineChain:s}}return Xc}const Xl={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 Gu(),{chainId:s}=dt.parseCaipNetworkId(t.caipNetworkId);return e({...t,id:Number(s)})},async createViemPublicClient(t){const{createPublicClient:e,http:s}=await Gu(),n=D.state.projectId,r=await Xl.getViemChain(t);if(!r)throw new Error(`Chain ${t.caipNetworkId} not found in viem/chains`);return e({chain:r,transport:s(Xl.getBlockchainApiRpcUrl(t.caipNetworkId,n))})}},Zd={async getMyTokensWithBalance(t){var a;const e=(a=E.getAccountData())==null?void 0:a.address,s=E.state.activeCaipNetwork,n=z.getConnectorId("eip155")===$.CONNECTOR_ID.AUTH;if(!e||!s)return[];const r=`${s.caipNetworkId}:${e}`,i=F.getBalanceCacheForCaipAddress(r);if(i)return i.balances;if(s.chainNamespace===$.CHAIN.EVM&&n){const c=await this.getEIP155Balances(e,s);if(c)return this.filterLowQualityTokens(c)}const o=await fe.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(o.balances)},async getEIP155Balances(t,e){var s,n;try{const r=Jc.getChainIdHexFromCAIP2ChainId(e.caipNetworkId),i=await G.getCapabilities(t);if(!((n=(s=i==null?void 0:i[r])==null?void 0:s.assetDiscovery)!=null&&n.supported))return null;const o=await G.walletGetAssets({account:t,chainFilter:[r]});if(!Jc.isWalletGetAssetsResponse(o))return null;const c=(o[r]||[]).map(l=>Jc.createBalance(l,e.caipNetworkId));return F.updateBalanceCache({caipAddress:`${e.caipNetworkId}:${t}`,balance:{balances:c},timestamp:Date.now()}),c}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},async fetchERC20Balance({caipAddress:t,assetAddress:e,caipNetwork:s}){const n=await Xl.createViemPublicClient(s),{address:r}=dt.parseCaipAddress(t),[{result:i},{result:o},{result:a},{result:c}]=await n.multicall({contracts:[{address:e,functionName:"name",args:[],abi:ya},{address:e,functionName:"symbol",args:[],abi:ya},{address:e,functionName:"balanceOf",args:[r],abi:ya},{address:e,functionName:"decimals",args:[],abi:ya}]});return{name:i,symbol:o,decimals:c,balance:a&&c?Hf(a,c):"0"}}},Qc={adapters:{}},Zf={state:Qc,initialize(t){Qc.adapters={...t}},get(t){return Qc.adapters[t]}},lc={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0,sui:void 0,stacks:void 0,ton:void 0},qt=Ge({providers:{...lc},providerIds:{...lc}}),He={state:qt,subscribeKey(t,e){return At(qt,t,e)},subscribe(t){return _t(qt,()=>{t(qt)})},subscribeProviders(t){return _t(qt.providers,()=>t(qt.providers))},setProvider(t,e){t&&e&&(qt.providers[t]=uo(e))},getProvider(t){if(t)return qt.providers[t]},setProviderId(t,e){e&&(qt.providerIds[t]=e)},getProviderId(t){if(t)return qt.providerIds[t]},reset(){qt.providers={...lc},qt.providerIds={...lc}},resetChain(t){qt.providers[t]=void 0,qt.providerIds[t]=void 0}},Fv={async getTokenList(t){var n;const e=await fe.fetchSwapTokens({chainId:t});return((n=e==null?void 0:e.tokens)==null?void 0:n.map(r=>({...r,eip2612:!1,quantity:{decimals:"0",numeric:"0"},price:0,value:0})))||[]},async fetchGasPrice(){var e;const t=E.state.activeCaipNetwork;if(!t)return null;try{switch(t.chainNamespace){case"solana":const s=(e=await(G==null?void 0:G.estimateGas({chainNamespace:"solana"})))==null?void 0:e.toString();return{standard:s,fast:s,instant:s};case"eip155":default:return await fe.fetchGasPrice({chainId:t.caipNetworkId})}}catch{return null}},async fetchSwapAllowance({tokenAddress:t,userAddress:e,sourceTokenAmount:s,sourceTokenDecimals:n}){const r=await fe.fetchSwapAllowance({tokenAddress:t,userAddress:e});if(r!=null&&r.allowance&&s&&n){const i=G.parseUnits(s,n)||0;return BigInt(r.allowance)>=i}return!1},async getMyTokensWithBalance(t){const e=await Zd.getMyTokensWithBalance(t);return E.setAccountProp("tokenBalance",e,E.state.activeChain),this.mapBalancesToSwapTokens(e)},mapBalancesToSwapTokens(t){return(t==null?void 0:t.map(e=>({...e,address:e!=null&&e.address?e.address:Yf(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1})))||[]},async handleSwapError(t){var e,s;try{const n=t==null?void 0:t.cause;if(!(n!=null&&n.json))return;const r=await n.json(),i=(s=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:s.description;return i!=null&&i.includes("insufficient liquidity")?"Insufficient liquidity":void 0}catch{return}}},Ue=Ge({tokenBalances:[],loading:!1}),qv={state:Ue,subscribe(t){return _t(Ue,()=>t(Ue))},subscribeKey(t,e){return At(Ue,t,e)},setToken(t){t&&(Ue.token=uo(t))},setTokenAmount(t){Ue.sendTokenAmount=t},setReceiverAddress(t){Ue.receiverAddress=t},setReceiverProfileImageUrl(t){Ue.receiverProfileImageUrl=t},setReceiverProfileName(t){Ue.receiverProfileName=t},setNetworkBalanceInUsd(t){Ue.networkBalanceInUSD=t},setLoading(t){Ue.loading=t},getSdkEventProperties(t){var e,s;return{message:X.parseError(t),isSmartAccount:us(E.state.activeChain)===et.ACCOUNT_TYPES.SMART_ACCOUNT,token:((e=Ue.token)==null?void 0:e.symbol)||"",amount:Ue.sendTokenAmount??0,network:((s=E.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||""}},async sendToken(){var t;try{switch(Ae.setLoading(!0),(t=E.state.activeCaipNetwork)==null?void 0:t.chainNamespace){case"eip155":await Ae.sendEvmToken();return;case"solana":await Ae.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}catch(e){throw wn.isUserRejectedRequestError(e)?new Pf(e):e}finally{Ae.setLoading(!1)}},async sendEvmToken(){var s,n,r;const t=E.state.activeChain;if(!t)throw new Error("SendController:sendEvmToken - activeChainNamespace is required");const e=us(t);if(!Ae.state.sendTokenAmount||!Ae.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!Ae.state.token)throw new Error("A token is required");if((s=Ae.state.token)!=null&&s.address){Ee.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===et.ACCOUNT_TYPES.SMART_ACCOUNT,token:Ae.state.token.address,amount:Ae.state.sendTokenAmount,network:((n=E.state.activeCaipNetwork)==null?void 0:n.caipNetworkId)||""}});const{hash:i}=await Ae.sendERC20Token({receiverAddress:Ae.state.receiverAddress,tokenAddress:Ae.state.token.address,sendTokenAmount:Ae.state.sendTokenAmount,decimals:Ae.state.token.quantity.decimals});i&&(Ue.hash=i)}else{Ee.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===et.ACCOUNT_TYPES.SMART_ACCOUNT,token:Ae.state.token.symbol||"",amount:Ae.state.sendTokenAmount,network:((r=E.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||""}});const{hash:i}=await Ae.sendNativeToken({receiverAddress:Ae.state.receiverAddress,sendTokenAmount:Ae.state.sendTokenAmount,decimals:Ae.state.token.quantity.decimals});i&&(Ue.hash=i)}},async fetchTokenBalance(t){var o,a,c;Ue.loading=!0;const e=E.state.activeChain,s=(o=E.state.activeCaipNetwork)==null?void 0:o.caipNetworkId,n=(a=E.state.activeCaipNetwork)==null?void 0:a.chainNamespace,r=((c=E.getAccountData(e))==null?void 0:c.caipAddress)??E.state.activeCaipAddress,i=r?X.getPlainAddress(r):void 0;if(Ue.lastRetry&&!X.isAllowedRetry(Ue.lastRetry,30*Ne.ONE_SEC_MS))return Ue.loading=!1,[];try{if(i&&s&&n){const l=await Zd.getMyTokensWithBalance();return Ue.tokenBalances=l,Ue.lastRetry=void 0,l}}catch(l){Ue.lastRetry=Date.now(),t==null||t(l),Ys.showError("Token Balance Unavailable")}finally{Ue.loading=!1}return[]},fetchNetworkBalance(){if(Ue.tokenBalances.length===0)return;const t=Fv.mapBalancesToSwapTokens(Ue.tokenBalances);if(!t)return;const e=t.find(s=>s.address===Yf());e&&(Ue.networkBalanceInUSD=e?nw.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){var o,a,c,l;ue.pushTransactionStack({});const e=t.receiverAddress,s=(o=E.getAccountData())==null?void 0:o.address,n=G.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),i=await G.sendTransaction({chainNamespace:$.CHAIN.EVM,to:e,address:s,data:"0x",value:n??BigInt(0)});return Ee.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:us("eip155")===et.ACCOUNT_TYPES.SMART_ACCOUNT,token:((a=Ae.state.token)==null?void 0:a.symbol)||"",amount:t.sendTokenAmount,network:((c=E.state.activeCaipNetwork)==null?void 0:c.caipNetworkId)||"",hash:i||""}}),(l=G._getClient())==null||l.updateBalance("eip155"),Ae.resetSend(),{hash:i}},async sendERC20Token(t){var n,r,i;ue.pushTransactionStack({onSuccess(){ue.replace("Account")}});const e=G.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals)),s=(n=E.getAccountData())==null?void 0:n.address;if(s&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const o=X.getPlainAddress(t.tokenAddress);if(!o)throw new Error("SendController:sendERC20Token - tokenAddress is required");const a=await G.writeContract({fromAddress:s,tokenAddress:o,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:aw.getERC20Abi(o),chainNamespace:$.CHAIN.EVM});return Ee.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:us("eip155")===et.ACCOUNT_TYPES.SMART_ACCOUNT,token:((r=Ae.state.token)==null?void 0:r.symbol)||"",amount:t.sendTokenAmount,network:((i=E.state.activeCaipNetwork)==null?void 0:i.caipNetworkId)||"",hash:a||""}}),Ae.resetSend(),{hash:a}}return{hash:void 0}},async sendSolanaToken(){var s,n,r;if(!Ae.state.sendTokenAmount||!Ae.state.receiverAddress)throw new Error("An amount and receiver address are required");ue.pushTransactionStack({onSuccess(){ue.replace("Account")}});let t;Ae.state.token&&Ae.state.token.address!==Ne.SOLANA_NATIVE_TOKEN_ADDRESS&&(X.isCaipAddress(Ae.state.token.address)?t=X.getPlainAddress(Ae.state.token.address):t=Ae.state.token.address);const e=await G.sendTransaction({chainNamespace:"solana",tokenMint:t,to:Ae.state.receiverAddress,value:Ae.state.sendTokenAmount});e&&(Ue.hash=e),(s=G._getClient())==null||s.updateBalance("solana"),Ee.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:!1,token:((n=Ae.state.token)==null?void 0:n.symbol)||"",amount:Ae.state.sendTokenAmount,network:((r=E.state.activeCaipNetwork)==null?void 0:r.caipNetworkId)||"",hash:e||""}}),Ae.resetSend()},resetSend(){Ue.token=void 0,Ue.sendTokenAmount=void 0,Ue.receiverAddress=void 0,Ue.receiverProfileImageUrl=void 0,Ue.receiverProfileName=void 0,Ue.loading=!1,Ue.tokenBalances=[]}},Ae=Ns(qv),el={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,user:void 0,preferredAccountType:void 0},wa={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},Q=Ge({chains:vw(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{connectionControllerClient:void 0},isSwitchingNamespace:!1}),Jf={state:Q,subscribe(t){return _t(Q,()=>{t(Q)})},subscribeKey(t,e){return At(Q,t,e)},subscribeAccountStateProp(t,e,s){var r;const n=s||Q.activeChain;return n?At(((r=Q.chains.get(n))==null?void 0:r.accountState)||{},t,e):()=>{}},subscribeChainProp(t,e,s){let n;return _t(Q.chains,()=>{var i;const r=s||Q.activeChain;if(r){const o=(i=Q.chains.get(r))==null?void 0:i[t];n!==o&&(n=o,e(o))}})},initialize(t,e,s){const{chainId:n,namespace:r}=F.getActiveNetworkProps(),i=e==null?void 0:e.find(d=>d.id.toString()===(n==null?void 0:n.toString())),a=t.find(d=>(d==null?void 0:d.namespace)===r)||(t==null?void 0:t[0]),c=t.map(d=>d.namespace).filter(d=>d!==void 0),l=D.state.enableEmbedded?new Set([...c]):new Set([...(e==null?void 0:e.map(d=>d.chainNamespace))??[]]);((t==null?void 0:t.length)===0||!a)&&(Q.noAdapters=!0),Q.noAdapters||(Q.activeChain=a==null?void 0:a.namespace,Q.activeCaipNetwork=i,E.setChainNetworkData(a==null?void 0:a.namespace,{caipNetwork:i}),Q.activeChain&&hs.set({activeChain:a==null?void 0:a.namespace})),l.forEach(d=>{const u=e==null?void 0:e.filter(g=>g.chainNamespace===d),h=F.getPreferredAccountTypes()||{},p={...D.state.defaultAccountTypes,...h};E.state.chains.set(d,{namespace:d,networkState:Ge({...wa,caipNetwork:u==null?void 0:u[0]}),accountState:Ge({...el,preferredAccountType:p[d]}),caipNetworks:u??[],...s}),E.setRequestedCaipNetworks(u??[],d)})},removeAdapter(t){var e,s;if(Q.activeChain===t){const n=Array.from(Q.chains.entries()).find(([r])=>r!==t);if(n){const r=(s=(e=n[1])==null?void 0:e.caipNetworks)==null?void 0:s[0];r&&E.setActiveCaipNetwork(r)}}Q.chains.delete(t)},addAdapter(t,{connectionControllerClient:e},s){if(!t.namespace)throw new Error("ChainController:addAdapter - adapter must have a namespace");Q.chains.set(t.namespace,{namespace:t.namespace,networkState:{...wa,caipNetwork:s[0]},accountState:{...el},caipNetworks:s,connectionControllerClient:e}),E.setRequestedCaipNetworks((s==null?void 0:s.filter(n=>n.chainNamespace===t.namespace))??[],t.namespace)},addNetwork(t){var s;const e=Q.chains.get(t.chainNamespace);if(e){const n=[...e.caipNetworks||[]];(s=e.caipNetworks)!=null&&s.find(r=>r.id===t.id)||n.push(t),Q.chains.set(t.chainNamespace,{...e,caipNetworks:n}),E.setRequestedCaipNetworks(n,t.chainNamespace),z.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){var n,r,i;const s=Q.chains.get(t);if(s){const o=((n=Q.activeCaipNetwork)==null?void 0:n.id)===e,a=[...((r=s.caipNetworks)==null?void 0:r.filter(c=>c.id!==e))||[]];o&&((i=s==null?void 0:s.caipNetworks)!=null&&i[0])&&E.setActiveCaipNetwork(s.caipNetworks[0]),Q.chains.set(t,{...s,caipNetworks:a}),E.setRequestedCaipNetworks(a||[],t),a.length===0&&z.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=Q.chains.get(t);s&&(s.networkState={...s.networkState||wa,...e},Q.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const n=Q.chains.get(t);if(n){const r={...n.accountState||el,...e};Q.chains.set(t,{...n,accountState:r}),(Q.chains.size===1||Q.activeChain===t)&&e.caipAddress&&(Q.activeCaipAddress=e.caipAddress)}},setChainNetworkData(t,e){if(!t)return;const s=Q.chains.get(t);if(s){const n={...s.networkState||wa,...e};Q.chains.set(t,{...s,networkState:n})}},setAccountProp(t,e,s,n=!0){E.setChainAccountData(s,{[t]:e},n)},setActiveNamespace(t){var n,r;Q.activeChain=t;const e=t?Q.chains.get(t):void 0,s=(n=e==null?void 0:e.networkState)==null?void 0:n.caipNetwork;s!=null&&s.id&&t&&(Q.activeCaipAddress=(r=e==null?void 0:e.accountState)==null?void 0:r.caipAddress,Q.activeCaipNetwork=s,E.setChainNetworkData(t,{caipNetwork:s}),F.setActiveCaipNetworkId(s==null?void 0:s.caipNetworkId),hs.set({activeChain:t,selectedNetworkId:s==null?void 0:s.caipNetworkId}))},setActiveCaipNetwork(t){var i,o;if(!t)return;const e=Q.activeChain===t.chainNamespace;e||E.setIsSwitchingNamespace(!0);const s=Q.chains.get(t.chainNamespace);Q.activeChain=t.chainNamespace,Q.activeCaipNetwork=t,E.setChainNetworkData(t.chainNamespace,{caipNetwork:t});let n=(i=s==null?void 0:s.accountState)==null?void 0:i.address;if(n)Q.activeCaipAddress=`${t.chainNamespace}:${t.id}:${n}`;else if(e&&Q.activeCaipAddress){const{address:a}=dt.parseCaipAddress(Q.activeCaipAddress);n=a,Q.activeCaipAddress=`${t.caipNetworkId}:${n}`}else Q.activeCaipAddress=void 0;E.setChainAccountData(t.chainNamespace,{address:n,caipAddress:Q.activeCaipAddress}),Ae.resetSend(),hs.set({activeChain:Q.activeChain,selectedNetworkId:(o=Q.activeCaipNetwork)==null?void 0:o.caipNetworkId}),F.setActiveCaipNetworkId(t.caipNetworkId),!E.checkIfSupportedNetwork(t.chainNamespace)&&D.state.enableNetworkSwitch&&!D.state.allowUnsupportedChain&&!G.state.wcBasic&&E.showUnsupportedChainUI()},addCaipNetwork(t){var s;if(!t)return;const e=Q.chains.get(t.chainNamespace);e&&((s=e==null?void 0:e.caipNetworks)==null||s.push(t))},async switchActiveNamespace(t){var r;if(!t)return;const e=t!==E.state.activeChain,s=(r=E.getNetworkData(t))==null?void 0:r.caipNetwork,n=E.getCaipNetworkByNamespace(t,s==null?void 0:s.id);e&&n&&await E.switchActiveNetwork(n)},async switchActiveNetwork(t,{throwOnFailure:e=!1}={}){var o;const s=E.state.activeChain;if(!s)throw new Error("ChainController:switchActiveNetwork - namespace is required");const n=He.getProviderId(Q.activeChain)==="AUTH",r=(o=E.getAccountData(s))==null?void 0:o.address,i=$.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(t.chainNamespace);try{if(r&&t.chainNamespace===s||n&&i){const a=Zf.get(t.chainNamespace);if(!a)throw new Error("Adapter not found");await a.switchNetwork({caipNetwork:t})}E.setActiveCaipNetwork(t)}catch(a){if(e)throw a}Ee.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})},getConnectionControllerClient(t){const e=t||Q.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=Q.chains.get(e);if(!(s!=null&&s.connectionControllerClient))throw new Error("ConnectionController client not set");return s.connectionControllerClient},getNetworkProp(t,e){var n;const s=(n=Q.chains.get(e))==null?void 0:n.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=Q.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:n=[]}=(e==null?void 0:e.networkState)||{};return X.sortRequestedNetworks(s,n).filter(o=>o==null?void 0:o.id)},getAllRequestedCaipNetworks(){const t=[];return Q.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllRequestedCaipNetworks - chainAdapter must have a namespace");const s=E.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){E.setAdapterNetworkState(e,{requestedCaipNetworks:t});const n=E.getAllRequestedCaipNetworks().map(i=>i.chainNamespace),r=Array.from(new Set(n));z.filterByNamespaces(r)},getAllApprovedCaipNetworkIds(){const t=[];return Q.chains.forEach(e=>{if(!e.namespace)throw new Error("ChainController:getAllApprovedCaipNetworkIds - chainAdapter must have a namespace");const s=E.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(t){var e,s;return t?(s=(e=Q.chains.get(t))==null?void 0:e.networkState)==null?void 0:s.caipNetwork:Q.activeCaipNetwork},getActiveCaipAddress(){return Q.activeCaipAddress},getApprovedCaipNetworkIds(t){var n;const e=Q.chains.get(t);return((n=e==null?void 0:e.networkState)==null?void 0:n.approvedCaipNetworkIds)||[]},setApprovedCaipNetworksData(t,e){E.setAdapterNetworkState(t,e)},checkIfSupportedNetwork(t,e){var r;const s=e||((r=Q.activeCaipNetwork)==null?void 0:r.caipNetworkId),n=E.getRequestedCaipNetworks(t);return n.length?n==null?void 0:n.some(i=>i.caipNetworkId===s):!0},checkIfSupportedChainId(t){if(!Q.activeChain)return!0;const e=E.getRequestedCaipNetworks(Q.activeChain);return e==null?void 0:e.some(s=>s.id===t)},checkIfSmartAccountEnabled(){var n,r;const t=Sf.caipNetworkIdToNumber((n=Q.activeCaipNetwork)==null?void 0:n.caipNetworkId);if(!Q.activeChain||!t)return!1;const s=((r=lt.get(oe.SMART_ACCOUNT_ENABLED_NETWORKS))==null?void 0:r.split(","))||[];return!!(s!=null&&s.includes(t.toString()))},showUnsupportedChainUI(){Te.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=Q.activeCaipNetwork;return!!(t!=null&&t.chainNamespace&&Ne.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){E.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0})},resetAccount(t){var r,i;const e=t;if(!e)throw new Error("Chain is required to set account prop");const s=(i=(r=E.state.chains.get(e))==null?void 0:r.accountState)==null?void 0:i.preferredAccountType,n=D.state.defaultAccountTypes[e];Q.activeCaipAddress=void 0,E.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"}),z.removeConnectorId(e)},setIsSwitchingNamespace(t){Q.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){var s,n;const t=[];let e;if(Q.chains.forEach(r=>{$.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(i=>i===r.namespace)&&r.namespace&&t.push(r.namespace)}),t.length>0){const r=t[0];return e=r?(n=(s=Q.chains.get(r))==null?void 0:s.caipNetworks)==null?void 0:n[0]:void 0,e}},getAccountData(t){var s;const e=t||Q.activeChain;if(e)return(s=E.state.chains.get(e))==null?void 0:s.accountState},getNetworkData(t){var s;const e=t||Q.activeChain;if(e)return(s=E.state.chains.get(e))==null?void 0:s.networkState},getCaipNetworkByNamespace(t,e){var r,i,o;if(!t)return;const s=E.state.chains.get(t),n=(r=s==null?void 0:s.caipNetworks)==null?void 0:r.find(a=>a.id.toString()===(e==null?void 0:e.toString()));return n||((i=s==null?void 0:s.networkState)==null?void 0:i.caipNetwork)||((o=s==null?void 0:s.caipNetworks)==null?void 0:o[0])},getRequestedCaipNetworkIds(){const t=z.state.filterByNamespace;return(t?[Q.chains.get(t)]:Array.from(Q.chains.values())).flatMap(s=>(s==null?void 0:s.caipNetworks)||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?E.getRequestedCaipNetworks(t):E.getAllRequestedCaipNetworks()},getCaipNetworkById(t,e){return Jf.getCaipNetworks(e).find(s=>s.id.toString()===t.toString()||s.caipNetworkId.toString()===t.toString())},setLastConnectedSIWECaipNetwork(t){Q.lastConnectedSIWECaipNetwork=t},getLastConnectedSIWECaipNetwork(){return Q.lastConnectedSIWECaipNetwork},async fetchTokenBalance(t){var o,a;const e=E.getAccountData();if(!e)return[];const s=(o=E.state.activeCaipNetwork)==null?void 0:o.caipNetworkId,n=(a=E.state.activeCaipNetwork)==null?void 0:a.chainNamespace,r=E.state.activeCaipAddress,i=r?X.getPlainAddress(r):void 0;if(E.setAccountProp("balanceLoading",!0,n),e.lastRetry&&!X.isAllowedRetry(e.lastRetry,30*Ne.ONE_SEC_MS))return E.setAccountProp("balanceLoading",!1,n),[];try{if(i&&s&&n){const c=await Zd.getMyTokensWithBalance();return E.setAccountProp("tokenBalance",c,n),E.setAccountProp("lastRetry",void 0,n),E.setAccountProp("balanceLoading",!1,n),c}}catch(c){E.setAccountProp("lastRetry",Date.now(),n),t==null||t(c),Ys.showError("Token Balance Unavailable")}finally{E.setAccountProp("balanceLoading",!1,n)}return[]},isCaipNetworkDisabled(t){var c;const e=t.chainNamespace,s=!!((c=E.getAccountData(e))!=null&&c.caipAddress),n=E.getAllApprovedCaipNetworkIds(),r=E.getNetworkProp("supportsAllNetworks",e)!==!1,i=z.getConnectorId(e),o=z.getAuthConnector(),a=i===$.CONNECTOR_ID.AUTH&&o;return!s||r||a?!1:!(n!=null&&n.includes(t.caipNetworkId))}},E=Ns(Jf),Wv={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){var h,p;const s=E.state.activeCaipNetwork,n=E.state.activeChain,r=ue.state.data;if(t.id===(s==null?void 0:s.id))return;const o=!!((h=E.getAccountData(n))!=null&&h.address),a=!!((p=E.getAccountData(t.chainNamespace))!=null&&p.address),c=t.chainNamespace!==n,d=z.getConnectorId(n)===$.CONNECTOR_ID.AUTH,u=$.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(g=>g===t.chainNamespace);e||d&&u?ue.push("SwitchNetwork",{...r,network:t}):o&&c&&!a?ue.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):ue.push("SwitchNetwork",{...r,network:t})}},Wt=Ge({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),Hv={state:Wt,subscribe(t){return _t(Wt,()=>t(Wt))},subscribeKey(t,e){return At(Wt,t,e)},async open(t){var o,a;const e=t==null?void 0:t.namespace,s=E.state.activeChain,n=e&&e!==s,r=(o=E.getAccountData(t==null?void 0:t.namespace))==null?void 0:o.caipAddress,i=E.state.noAdapters;if(G.state.wcBasic?te.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1}):await te.prefetch(),z.setFilterByNamespace(t==null?void 0:t.namespace),Te.setLoading(!0,e),e&&n){const c=((a=E.getNetworkData(e))==null?void 0:a.caipNetwork)||E.getRequestedCaipNetworks(e)[0];c&&(i?(await E.switchActiveNetwork(c),ue.push("ConnectingWalletConnectBasic")):Wv.onSwitchNetwork({network:c,ignoreSwitchConfirmation:!0}))}else D.state.manualWCControl||i&&!r?X.isMobile()?ue.reset("AllWallets"):ue.reset("ConnectingWalletConnectBasic"):t!=null&&t.view?ue.reset(t.view,t.data):r?ue.reset("Account"):ue.reset("Connect");Wt.open=!0,hs.set({open:!0}),Ee.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!r}})},close(){const t=D.state.enableEmbedded,e=!!E.state.activeCaipAddress;Wt.open&&Ee.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),Wt.open=!1,ue.reset("Connect"),Te.clearLoading(),t?e?ue.replace("Account"):ue.push("Connect"):hs.set({open:!1}),G.resetUri()},setLoading(t,e){e&&Wt.loadingNamespaceMap.set(e,t),Wt.loading=t,hs.set({loading:t})},clearLoading(){Wt.loadingNamespaceMap.clear(),Wt.loading=!1,hs.set({loading:!1})},shake(){Wt.shake||(Wt.shake=!0,setTimeout(()=>{Wt.shake=!1},500))}},Te=Ns(Hv),Zi={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"}]},Ql={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},zv={providers:kf,selectedProvider:null,error:null,purchaseCurrency:Zi,paymentCurrency:Ql,purchaseCurrencies:[Zi],paymentCurrencies:[],quotesLoading:!1},$e=Ge(zv),Vv={state:$e,subscribe(t){return _t($e,()=>t($e))},subscribeKey(t,e){return At($e,t,e)},setSelectedProvider(t){var e,s;if(t&&t.name==="meld"){const n=E.state.activeChain,r=n===$.CHAIN.SOLANA?"SOL":"USDC",i=n?((s=(e=E.state.chains.get(n))==null?void 0:e.accountState)==null?void 0:s.address)??"":"",o=new URL(t.url);o.searchParams.append("publicKey",Cw),o.searchParams.append("destinationCurrencyCode",r),o.searchParams.append("walletAddress",i),o.searchParams.append("externalCustomerId",D.state.projectId),$e.selectedProvider={...t,url:o.toString()}}else $e.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=kf.filter(n=>e.includes(n.name));$e.providers=s}else $e.providers=[]},setPurchaseCurrency(t){$e.purchaseCurrency=t},setPaymentCurrency(t){$e.paymentCurrency=t},setPurchaseAmount(t){ed.state.purchaseAmount=t},setPaymentAmount(t){ed.state.paymentAmount=t},async getAvailableCurrencies(){const t=await fe.getOnrampOptions();$e.purchaseCurrencies=t.purchaseCurrencies,$e.paymentCurrencies=t.paymentCurrencies,$e.paymentCurrency=t.paymentCurrencies[0]||Ql,$e.purchaseCurrency=t.purchaseCurrencies[0]||Zi,await te.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await te.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){var t,e;$e.quotesLoading=!0;try{const s=await fe.getOnrampQuote({purchaseCurrency:$e.purchaseCurrency,paymentCurrency:$e.paymentCurrency,amount:((t=$e.paymentAmount)==null?void 0:t.toString())||"0",network:(e=$e.purchaseCurrency)==null?void 0:e.symbol});return $e.quotesLoading=!1,$e.purchaseAmount=Number(s==null?void 0:s.purchaseAmount.amount),s}catch(s){return $e.error=s.message,$e.quotesLoading=!1,null}finally{$e.quotesLoading=!1}},resetState(){$e.selectedProvider=null,$e.error=null,$e.purchaseCurrency=Zi,$e.paymentCurrency=Ql,$e.purchaseCurrencies=[Zi],$e.paymentCurrencies=[],$e.paymentAmount=void 0,$e.purchaseAmount=void 0,$e.quotesLoading=!1}},ed=Ns(Vv);function Kv(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function ft(t,...e){try{return Kv(t(...e))}catch(s){return Promise.reject(s)}}function Gv(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function Yv(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Fa(t){if(Gv(t))return String(t);if(Yv(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Fa(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const td="base64:";function Zv(t){return typeof t=="string"?t:td+Qv(t)}function Jv(t){return typeof t!="string"||!t.startsWith(td)?t:Xv(t.slice(td.length))}function Xv(t){return globalThis.Buffer?Pe.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function Qv(t){return globalThis.Buffer?Pe.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function zt(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function eC(...t){return zt(t.join(":"))}function Ea(t){return t=zt(t),t?t+":":""}function tC(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 sC(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const nC="memory",rC=()=>{const t=new Map;return{name:nC,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 iC(t={}){const e={mounts:{"":t.driver||rC()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},s=l=>{for(const d of e.mountpoints)if(l.startsWith(d))return{base:d,relativeKey:l.slice(d.length),driver:e.mounts[d]};return{base:"",relativeKey:l,driver:e.mounts[""]}},n=(l,d)=>e.mountpoints.filter(u=>u.startsWith(l)||d&&l.startsWith(u)).map(u=>({relativeBase:l.length>u.length?l.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),r=(l,d)=>{if(e.watching){d=zt(d);for(const u of e.watchListeners)u(l,d)}},i=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await Yu(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,d,u)=>{const h=new Map,p=g=>{let f=h.get(g.base);return f||(f={driver:g.driver,base:g.base,items:[]},h.set(g.base,f)),f};for(const g of l){const f=typeof g=="string",w=zt(f?g:g.key),v=f?void 0:g.value,N=f||!g.options?d:{...d,...g.options},A=s(w);p(A).items.push({key:w,value:v,relativeKey:A.relativeKey,options:N})}return Promise.all([...h.values()].map(g=>u(g))).then(g=>g.flat())},c={hasItem(l,d={}){l=zt(l);const{relativeKey:u,driver:h}=s(l);return ft(h.hasItem,u,d)},getItem(l,d={}){l=zt(l);const{relativeKey:u,driver:h}=s(l);return ft(h.getItem,u,d).then(p=>pa(p))},getItems(l,d={}){return a(l,d,u=>u.driver.getItems?ft(u.driver.getItems,u.items.map(h=>({key:h.relativeKey,options:h.options})),d).then(h=>h.map(p=>({key:eC(u.base,p.key),value:pa(p.value)}))):Promise.all(u.items.map(h=>ft(u.driver.getItem,h.relativeKey,h.options).then(p=>({key:h.key,value:pa(p)})))))},getItemRaw(l,d={}){l=zt(l);const{relativeKey:u,driver:h}=s(l);return h.getItemRaw?ft(h.getItemRaw,u,d):ft(h.getItem,u,d).then(p=>Jv(p))},async setItem(l,d,u={}){if(d===void 0)return c.removeItem(l);l=zt(l);const{relativeKey:h,driver:p}=s(l);p.setItem&&(await ft(p.setItem,h,Fa(d),u),p.watch||r("update",l))},async setItems(l,d){await a(l,d,async u=>{if(u.driver.setItems)return ft(u.driver.setItems,u.items.map(h=>({key:h.relativeKey,value:Fa(h.value),options:h.options})),d);u.driver.setItem&&await Promise.all(u.items.map(h=>ft(u.driver.setItem,h.relativeKey,Fa(h.value),h.options)))})},async setItemRaw(l,d,u={}){if(d===void 0)return c.removeItem(l,u);l=zt(l);const{relativeKey:h,driver:p}=s(l);if(p.setItemRaw)await ft(p.setItemRaw,h,d,u);else if(p.setItem)await ft(p.setItem,h,Zv(d),u);else return;p.watch||r("update",l)},async removeItem(l,d={}){typeof d=="boolean"&&(d={removeMeta:d}),l=zt(l);const{relativeKey:u,driver:h}=s(l);h.removeItem&&(await ft(h.removeItem,u,d),(d.removeMeta||d.removeMata)&&await ft(h.removeItem,u+"$",d),h.watch||r("remove",l))},async getMeta(l,d={}){typeof d=="boolean"&&(d={nativeOnly:d}),l=zt(l);const{relativeKey:u,driver:h}=s(l),p=Object.create(null);if(h.getMeta&&Object.assign(p,await ft(h.getMeta,u,d)),!d.nativeOnly){const g=await ft(h.getItem,u+"$",d).then(f=>pa(f));g&&typeof g=="object"&&(typeof g.atime=="string"&&(g.atime=new Date(g.atime)),typeof g.mtime=="string"&&(g.mtime=new Date(g.mtime)),Object.assign(p,g))}return p},setMeta(l,d,u={}){return this.setItem(l+"$",d,u)},removeMeta(l,d={}){return this.removeItem(l+"$",d)},async getKeys(l,d={}){var w;l=Ea(l);const u=n(l,!0);let h=[];const p=[];let g=!0;for(const v of u){(w=v.driver.flags)!=null&&w.maxDepth||(g=!1);const N=await ft(v.driver.getKeys,v.relativeBase,d);for(const A of N){const _=v.mountpoint+zt(A);h.some(P=>_.startsWith(P))||p.push(_)}h=[v.mountpoint,...h.filter(A=>!A.startsWith(v.mountpoint))]}const f=d.maxDepth!==void 0&&!g;return p.filter(v=>(!f||tC(v,d.maxDepth))&&sC(v,l))},async clear(l,d={}){l=Ea(l),await Promise.all(n(l,!1).map(async u=>{if(u.driver.clear)return ft(u.driver.clear,u.relativeBase,d);if(u.driver.removeItem){const h=await u.driver.getKeys(u.relativeBase||"",d);return Promise.all(h.map(p=>u.driver.removeItem(p,d)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>Zu(l)))},async watch(l){return await i(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(d=>d!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,d){if(l=Ea(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((u,h)=>h.length-u.length)),e.mounts[l]=d,e.watching&&Promise.resolve(Yu(d,r,l)).then(u=>{e.unwatch[l]=u}).catch(console.error),c},async unmount(l,d=!0){var u,h;l=Ea(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&((h=(u=e.unwatch)[l])==null||h.call(u),delete e.unwatch[l]),d&&await Zu(e.mounts[l]),e.mountpoints=e.mountpoints.filter(p=>p!==l),delete e.mounts[l])},getMount(l=""){l=zt(l)+":";const d=s(l);return{driver:d.driver,base:d.base}},getMounts(l="",d={}){return l=zt(l),n(l,d.parents).map(h=>({driver:h.driver,base:h.mountpoint}))},keys:(l,d={})=>c.getKeys(l,d),get:(l,d={})=>c.getItem(l,d),set:(l,d,u={})=>c.setItem(l,d,u),has:(l,d={})=>c.hasItem(l,d),del:(l,d={})=>c.removeItem(l,d),remove:(l,d={})=>c.removeItem(l,d)};return c}function Yu(t,e,s){return t.watch?t.watch((n,r)=>e(n,s+r)):()=>{}}async function Zu(t){typeof t.dispose=="function"&&await ft(t.dispose)}const oC="idb-keyval";var aC=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",s=r=>e+r;let n;return t.dbName&&t.storeName&&(n=Uy(t.dbName,t.storeName)),{name:oC,options:t,async hasItem(r){return!(typeof await Tu(s(r),n)>"u")},async getItem(r){return await Tu(s(r),n)??null},setItem(r,i){return My(s(r),i,n)},removeItem(r){return Ly(s(r),n)},getKeys(){return Dy(n)},clear(){return $y(n)}}};const cC="WALLET_CONNECT_V2_INDEXED_DB",lC="keyvaluestorage";let dC=class{constructor(){this.indexedDb=iC({driver:aC({dbName:cC,storeName:lC})})}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,io(s))}async removeItem(e){await this.indexedDb.removeItem(e)}};var tl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Ce<"u"?Ce:typeof self<"u"?self:{},qa={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 tl<"u"&&tl.localStorage?qa.exports=tl.localStorage:typeof window<"u"&&window.localStorage?qa.exports=window.localStorage:qa.exports=new e})();function uC(t){var e;return[t[0],Ya((e=t[1])!=null?e:"")]}let hC=class{constructor(){this.localStorage=qa.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(uC)}async getItem(e){const s=this.localStorage.getItem(e);if(s!==null)return Ya(s)}async setItem(e,s){this.localStorage.setItem(e,io(s))}async removeItem(e){this.localStorage.removeItem(e)}};const pC="wc_storage_version",Ju=1,fC=async(t,e,s)=>{const n=pC,r=await e.getItem(n);if(r&&r>=Ju){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,Ju),s(e),gC(t,o)},gC=async(t,e)=>{e.length&&e.forEach(async s=>{await t.removeItem(s)})};let mC=class{constructor(){this.initialized=!1,this.setInitialized=s=>{this.storage=s,this.initialized=!0};const e=new hC;this.storage=e;try{const s=new dC;fC(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)})}};var yC=Object.defineProperty,wC=(t,e,s)=>e in t?yC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Xu=(t,e,s)=>wC(t,typeof e!="symbol"?e+"":e,s);let EC=class extends Ai{constructor(e){super(),this.opts=e,Xu(this,"protocol","wc"),Xu(this,"version",2)}};var bC=Object.defineProperty,vC=(t,e,s)=>e in t?bC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,CC=(t,e,s)=>vC(t,e+"",s);let _C=class extends Ai{constructor(e,s){super(),this.core=e,this.logger=s,CC(this,"records",new Map)}},AC=class{constructor(e,s){this.logger=e,this.core=s}},SC=class extends Ai{constructor(e,s){super(),this.relayer=e,this.logger=s}},IC=class extends Ai{constructor(e){super()}},NC=class{constructor(e,s,n,r){this.core=e,this.logger=s,this.name=n}},TC=class extends Ai{constructor(e,s){super(),this.relayer=e,this.logger=s}},RC=class extends Ai{constructor(e,s){super(),this.core=e,this.logger=s}},OC=class{constructor(e,s,n){this.core=e,this.logger=s,this.store=n}};class PC{constructor(e,s){this.projectId=e,this.logger=s}}let xC=class{constructor(e,s,n){this.core=e,this.logger=s,this.telemetryEnabled=n}};var kC=Object.defineProperty,UC=(t,e,s)=>e in t?kC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qu=(t,e,s)=>UC(t,typeof e!="symbol"?e+"":e,s);let $C=class{constructor(e){this.opts=e,Qu(this,"protocol","wc"),Qu(this,"version",2)}},DC=class{constructor(e){this.client=e}};const LC="0.1.1";function MC(){return LC}let tt=class sd extends Error{constructor(e,s={}){const n=(()=>{var c;if(s.cause instanceof sd){if(s.cause.details)return s.cause.details;if(s.cause.shortMessage)return s.cause.shortMessage}return s.cause&&"details"in s.cause&&typeof s.cause.details=="string"?s.cause.details:(c=s.cause)!=null&&c.message?s.cause.message:s.details})(),r=s.cause instanceof sd&&s.cause.docsPath||s.docsPath,o=`https://oxlib.sh${r??""}`,a=[e||"An error occurred.",...s.metaMessages?["",...s.metaMessages]:[],...n||r?["",n?`Details: ${n}`:void 0,r?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
5
+ `);super(a,s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{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,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${MC()}`}),this.cause=s.cause,this.details=n,this.docs=o,this.docsPath=r,this.shortMessage=e}walk(e){return Xf(this,e)}};function Xf(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Xf(t.cause,e):e?null:t}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Jd=BigInt(0),nd=BigInt(1);function na(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Xd(t){if(!na(t))throw new Error("Uint8Array expected")}function Ao(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function ba(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Qf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Jd:BigInt("0x"+t)}const eg=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",BC=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function So(t){if(Xd(t),eg)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=BC[t[s]];return e}const an={_0:48,_9:57,A:65,F:70,a:97,f:102};function eh(t){if(t>=an._0&&t<=an._9)return t-an._0;if(t>=an.A&&t<=an.F)return t-(an.A-10);if(t>=an.a&&t<=an.f)return t-(an.a-10)}function dc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(eg)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=eh(t.charCodeAt(i)),a=eh(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 Ir(t){return Qf(So(t))}function tg(t){return Xd(t),Qf(So(Uint8Array.from(t).reverse()))}function ra(t,e){return dc(t.toString(16).padStart(e*2,"0"))}function sg(t,e){return ra(t,e).reverse()}function bs(t,e,s){let n;if(typeof e=="string")try{n=dc(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(na(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}function uc(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];Xd(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}const sl=t=>typeof t=="bigint"&&Jd<=t;function Qd(t,e,s){return sl(t)&&sl(e)&&sl(s)&&e<=t&&t<s}function ai(t,e,s,n){if(!Qd(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function jC(t){let e;for(e=0;t>Jd;t>>=nd,e+=1);return e}const Oc=t=>(nd<<BigInt(t))-nd,nl=t=>new Uint8Array(t),th=t=>Uint8Array.from(t);function FC(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");let n=nl(t),r=nl(t),i=0;const o=()=>{n.fill(1),r.fill(0),i=0},a=(...u)=>s(r,n,...u),c=(u=nl(0))=>{r=a(th([0]),u),n=a(),u.length!==0&&(r=a(th([1]),u),n=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const h=[];for(;u<e;){n=a();const p=n.slice();h.push(p),u+=n.length}return uc(...h)};return(u,h)=>{o(),c(u);let p;for(;!(p=h(l()));)c();return o(),p}}const qC={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||na(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Pc(t,e,s={}){const n=(r,i,o)=>{const a=qC[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[r];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(r)+" is invalid. Expected "+i+", got "+c)};for(const[r,i]of Object.entries(e))n(r,i,!1);for(const[r,i]of Object.entries(s))n(r,i,!0);return t}function sh(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}}function WC(t,e){if(oh(t)>e)throw new d_({givenSize:oh(t),maxSize:e})}const cn={zero:48,nine:57,A:65,F:70,a:97,f:102};function nh(t){if(t>=cn.zero&&t<=cn.nine)return t-cn.zero;if(t>=cn.A&&t<=cn.F)return t-(cn.A-10);if(t>=cn.a&&t<=cn.f)return t-(cn.a-10)}function HC(t,e={}){const{dir:s,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new u_({size:t.length,targetSize:n,type:"Bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const o=s==="right";r[o?i:n-i-1]=t[o?i:t.length-i-1]}return r}function ng(t,e){if(tr(t)>e)throw new e_({givenSize:tr(t),maxSize:e})}function zC(t,e){if(typeof e=="number"&&e>0&&e>tr(t)-1)throw new og({offset:e,position:"start",size:tr(t)})}function VC(t,e,s){if(typeof e=="number"&&typeof s=="number"&&tr(t)!==s-e)throw new og({offset:s,position:"end",size:tr(t)})}function rg(t,e={}){const{dir:s,size:n=32}=e;if(n===0)return t;const r=t.replace("0x","");if(r.length>n*2)throw new t_({size:Math.ceil(r.length/2),targetSize:n,type:"Hex"});return`0x${r[s==="right"?"padEnd":"padStart"](n*2,"0")}`}const KC="#__bigint";function eu(t,e,s){return JSON.stringify(t,(n,r)=>typeof r=="bigint"?r.toString()+KC:r,s)}const GC=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function YC(t,e={}){const{strict:s=!1}=e;if(!t)throw new rh(t);if(typeof t!="string")throw new rh(t);if(s&&!/^0x[0-9a-fA-F]*$/.test(t))throw new ih(t);if(!t.startsWith("0x"))throw new ih(t)}function ZC(...t){return`0x${t.reduce((e,s)=>e+s.replace("0x",""),"")}`}function tu(t){return t instanceof Uint8Array?hc(t):Array.isArray(t)?hc(new Uint8Array(t)):t}function hc(t,e={}){let s="";for(let r=0;r<t.length;r++)s+=GC[t[r]];const n=`0x${s}`;return typeof e.size=="number"?(ng(n,e.size),ig(n,e.size)):n}function rl(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 l=typeof t=="bigint"?"n":"";throw new QC({max:i?`${i}${l}`:void 0,min:`${o}${l}`,signed:s,size:n,value:`${t}${l}`})}const c=`0x${(s&&r<0?(1n<<BigInt(n*8))+BigInt(r):r).toString(16)}`;return n?JC(c,n):c}function JC(t,e){return rg(t,{dir:"left",size:e})}function ig(t,e){return rg(t,{dir:"right",size:e})}function fn(t,e,s,n={}){const{strict:r}=n;zC(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(s??t.length)*2)}`;return r&&VC(i,e,s),i}function tr(t){return Math.ceil((t.length-2)/2)}function XC(t,e={}){const{strict:s=!1}=e;try{return YC(t,{strict:s}),!0}catch{return!1}}class QC extends tt{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}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class rh extends tt{constructor(e){super(`Value \`${typeof e=="object"?eu(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class ih extends tt{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}let e_=class extends tt{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed \`${s}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class og extends tt{constructor({offset:e,position:s,size:n}){super(`Slice ${s==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let t_=class extends tt{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${s}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const s_=new TextEncoder;function n_(t){if(!(t instanceof Uint8Array)){if(!t)throw new va(t);if(typeof t!="object")throw new va(t);if(!("BYTES_PER_ELEMENT"in t))throw new va(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new va(t)}}function r_(t){return t instanceof Uint8Array?t:typeof t=="string"?o_(t):i_(t)}function i_(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function o_(t,e={}){const{size:s}=e;let n=t;s&&(ng(t,s),n=ig(t,s));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,o=new Uint8Array(i);for(let a=0,c=0;a<i;a++){const l=nh(r.charCodeAt(c++)),d=nh(r.charCodeAt(c++));if(l===void 0||d===void 0)throw new tt(`Invalid byte sequence ("${r[c-2]}${r[c-1]}" in "${r}").`);o[a]=l*16+d}return o}function a_(t,e={}){const{size:s}=e,n=s_.encode(t);return typeof s=="number"?(WC(n,s),c_(n,s)):n}function c_(t,e){return HC(t,{dir:"right",size:e})}function oh(t){return t.length}function l_(t){try{return n_(t),!0}catch{return!1}}class va extends tt{constructor(e){super(`Value \`${typeof e=="object"?eu(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}let d_=class extends tt{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed \`${s}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},u_=class extends tt{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${s}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};function ag(t,e={}){const{as:s=typeof t=="string"?"Hex":"Bytes"}=e,n=Ny(r_(t));return s==="Bytes"?n:hc(n)}let h_=class 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 p_={checksum:new h_(8192)},il=p_.checksum;function cg(t,e={}){const{compressed:s}=e,{prefix:n,x:r,y:i}=t;if(s===!1||typeof r=="bigint"&&typeof i=="bigint"){if(n!==4)throw new ah({prefix:n,cause:new E_});return}if(s===!0||typeof r=="bigint"&&typeof i>"u"){if(n!==3&&n!==2)throw new ah({prefix:n,cause:new w_});return}throw new y_({publicKey:t})}function f_(t){const e=(()=>{if(XC(t))return lg(t);if(l_(t))return g_(t);const{prefix:s,x:n,y:r}=t;return typeof n=="bigint"&&typeof r=="bigint"?{prefix:s??4,x:n,y:r}:{prefix:s,x:n}})();return cg(e),e}function g_(t){return lg(hc(t))}function lg(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new b_({publicKey:t});if(t.length===130){const n=BigInt(fn(t,0,32)),r=BigInt(fn(t,32,64));return{prefix:4,x:n,y:r}}if(t.length===132){const n=Number(fn(t,0,1)),r=BigInt(fn(t,1,33)),i=BigInt(fn(t,33,65));return{prefix:n,x:r,y:i}}const e=Number(fn(t,0,1)),s=BigInt(fn(t,1,33));return{prefix:e,x:s}}function m_(t,e={}){cg(t);const{prefix:s,x:n,y:r}=t,{includePrefix:i=!0}=e;return ZC(i?rl(s,{size:1}):"0x",rl(n,{size:32}),typeof r=="bigint"?rl(r,{size:32}):"0x")}class y_ extends tt{constructor({publicKey:e}){super(`Value \`${eu(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class ah extends tt{constructor({prefix:e,cause:s}){super(`Prefix "${e}" is invalid.`,{cause:s}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class w_ extends tt{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class E_ extends tt{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let b_=class extends tt{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${tr(tu(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const v_=/^0x[a-fA-F0-9]{40}$/;function dg(t,e={}){const{strict:s=!0}=e;if(!v_.test(t))throw new ch({address:t,cause:new A_});if(s){if(t.toLowerCase()===t)return;if(ug(t)!==t)throw new ch({address:t,cause:new S_})}}function ug(t){if(il.has(t))return il.get(t);dg(t,{strict:!1});const e=t.substring(2).toLowerCase(),s=ag(a_(e),{as:"Bytes"}),n=e.split("");for(let i=0;i<40;i+=2)s[i>>1]>>4>=8&&n[i]&&(n[i]=n[i].toUpperCase()),(s[i>>1]&15)>=8&&n[i+1]&&(n[i+1]=n[i+1].toUpperCase());const r=`0x${n.join("")}`;return il.set(t,r),r}function C_(t,e={}){const{checksum:s=!1}=e;return dg(t),s?ug(t):t}function __(t,e={}){const s=ag(`0x${m_(t).slice(4)}`).substring(26);return C_(`0x${s}`,e)}class ch extends tt{constructor({address:e,cause:s}){super(`Address "${e}" is invalid.`,{cause:s}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class A_ extends tt{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class S_ extends tt{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Jt=BigInt(0),Mt=BigInt(1),yr=BigInt(2),I_=BigInt(3),hg=BigInt(4),pg=BigInt(5),fg=BigInt(8);function Gt(t,e){const s=t%e;return s>=Jt?s:e+s}function fs(t,e,s){let n=t;for(;e-- >Jt;)n*=n,n%=s;return n}function rd(t,e){if(t===Jt)throw new Error("invert: expected non-zero number");if(e<=Jt)throw new Error("invert: expected positive modulus, got "+e);let s=Gt(t,e),n=e,r=Jt,i=Mt;for(;s!==Jt;){const a=n/s,c=n%s,l=r-i*a;n=s,s=c,r=i,i=l}if(n!==Mt)throw new Error("invert: does not exist");return Gt(r,e)}function gg(t,e){const s=(t.ORDER+Mt)/hg,n=t.pow(e,s);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function N_(t,e){const s=(t.ORDER-pg)/fg,n=t.mul(e,yr),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,yr),r),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function T_(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Mt,s=0;for(;e%yr===Jt;)e/=yr,s++;let n=yr;const r=su(t);for(;lh(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return gg;let i=r.pow(n,e);const o=(e+Mt)/yr;return function(c,l){if(c.is0(l))return l;if(lh(c,l)!==1)throw new Error("Cannot find square root");let d=s,u=c.mul(c.ONE,i),h=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let g=1,f=c.sqr(h);for(;!c.eql(f,c.ONE);)if(g++,f=c.sqr(f),g===d)throw new Error("Cannot find square root");const w=Mt<<BigInt(d-g-1),v=c.pow(u,w);d=g,u=c.sqr(v),h=c.mul(h,u),p=c.mul(p,v)}return p}}function R_(t){return t%hg===I_?gg:t%fg===pg?N_:T_(t)}const O_=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function P_(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},s=O_.reduce((n,r)=>(n[r]="function",n),e);return Pc(t,s)}function x_(t,e,s){if(s<Jt)throw new Error("invalid exponent, negatives unsupported");if(s===Jt)return t.ONE;if(s===Mt)return e;let n=t.ONE,r=e;for(;s>Jt;)s&Mt&&(n=t.mul(n,r)),r=t.sqr(r),s>>=Mt;return n}function mg(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 lh(t,e){const s=(t.ORDER-Mt)/yr,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 yg(t,e){e!==void 0&&Ty(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function su(t,e,s=!1,n={}){if(t<=Jt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:r,nByteLength:i}=yg(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:s,BITS:r,BYTES:i,MASK:Oc(r),ZERO:Jt,ONE:Mt,create:c=>Gt(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Jt<=c&&c<t},is0:c=>c===Jt,isOdd:c=>(c&Mt)===Mt,neg:c=>Gt(-c,t),eql:(c,l)=>c===l,sqr:c=>Gt(c*c,t),add:(c,l)=>Gt(c+l,t),sub:(c,l)=>Gt(c-l,t),mul:(c,l)=>Gt(c*l,t),pow:(c,l)=>x_(a,c,l),div:(c,l)=>Gt(c*rd(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>rd(c,t),sqrt:n.sqrt||(c=>(o||(o=R_(t)),o(a,c))),toBytes:c=>s?sg(c,i):ra(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return s?tg(c):Ir(c)},invertBatch:c=>mg(a,c),cmov:(c,l,d)=>d?l:c});return Object.freeze(a)}function wg(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 Eg(t){const e=wg(t);return e+Math.ceil(e/2)}function k_(t,e,s=!1){const n=t.length,r=wg(e),i=Eg(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?tg(t):Ir(t),a=Gt(o,e-Mt)+Mt;return s?sg(a,r):ra(a,r)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const dh=BigInt(0),id=BigInt(1);function ol(t,e){const s=e.negate();return t?s:e}function bg(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function al(t,e){bg(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=Oc(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function uh(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+=id);const l=e*n,d=l+Math.abs(a)-1,u=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:l}}function U_(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 $_(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 cl=new WeakMap,vg=new WeakMap;function ll(t){return vg.get(t)||1}function D_(t,e){return{constTimeNegate:ol,hasPrecomputes(s){return ll(s)!==1},unsafeLadder(s,n,r=t.ZERO){let i=s;for(;n>dh;)n&id&&(r=r.add(i)),i=i.double(),n>>=id;return r},precomputeWindow(s,n){const{windows:r,windowSize:i}=al(n,e),o=[];let a=s,c=a;for(let l=0;l<r;l++){c=a,o.push(c);for(let d=1;d<i;d++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(s,n,r){let i=t.ZERO,o=t.BASE;const a=al(s,e);for(let c=0;c<a.windows;c++){const{nextN:l,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:g}=uh(r,c,a);r=l,u?o=o.add(ol(p,n[g])):i=i.add(ol(h,n[d]))}return{p:i,f:o}},wNAFUnsafe(s,n,r,i=t.ZERO){const o=al(s,e);for(let a=0;a<o.windows&&r!==dh;a++){const{nextN:c,offset:l,isZero:d,isNeg:u}=uh(r,a,o);if(r=c,!d){const h=n[l];i=i.add(u?h.negate():h)}}return i},getPrecomputes(s,n,r){let i=cl.get(n);return i||(i=this.precomputeWindow(n,s),s!==1&&cl.set(n,r(i))),i},wNAFCached(s,n,r){const i=ll(s);return this.wNAF(i,this.getPrecomputes(i,s,r),n)},wNAFCachedUnsafe(s,n,r,i){const o=ll(s);return o===1?this.unsafeLadder(s,n,i):this.wNAFUnsafe(o,this.getPrecomputes(o,s,r),n,i)},setWindowSize(s,n){bg(n,e),vg.set(s,n),cl.delete(s)}}}function L_(t,e,s,n){U_(s,t),$_(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=jC(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Oc(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=u;p>=0;p-=c){d.fill(o);for(let f=0;f<i;f++){const w=n[f],v=Number(w>>BigInt(p)&l);d[v]=d[v].add(s[f])}let g=o;for(let f=d.length-1,w=o;f>0;f--)w=w.add(d[f]),g=g.add(w);if(h=h.add(g),p!==0)for(let f=0;f<c;f++)h=h.double()}return h}function Cg(t){return P_(t.Fp),Pc(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yg(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function hh(t){t.lowS!==void 0&&Ao("lowS",t.lowS),t.prehash!==void 0&&Ao("prehash",t.prehash)}function M_(t){const e=Cg(t);Pc(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:s,Fp:n,a:r}=e;if(s){if(!n.eql(r,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof s!="object"||typeof s.beta!="bigint"||typeof s.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class B_ extends Error{constructor(e=""){super(e)}}const mn={Err:B_,_tlv:{encode:(t,e)=>{const{Err:s}=mn;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=ba(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?ba(r.length/2|128):"";return ba(t)+i+r+e},decode(t,e){const{Err:s}=mn;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 d of l)o=o<<8|d;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}=mn;if(t<En)throw new e("integer: negative integers are not allowed");let s=ba(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}=mn;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 Ir(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=mn,r=bs("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:d}=n.decode(2,c);if(d.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}=mn,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}};function dl(t,e){return So(ra(t,e))}const En=BigInt(0),gt=BigInt(1);BigInt(2);const ul=BigInt(3),j_=BigInt(4);function F_(t){const e=M_(t),{Fp:s}=e,n=su(e.n,e.nBitLength),r=e.toBytes||((A,_,P)=>{const U=_.toAffine();return uc(Uint8Array.from([4]),s.toBytes(U.x),s.toBytes(U.y))}),i=e.fromBytes||(A=>{const _=A.subarray(1),P=s.fromBytes(_.subarray(0,s.BYTES)),U=s.fromBytes(_.subarray(s.BYTES,2*s.BYTES));return{x:P,y:U}});function o(A){const{a:_,b:P}=e,U=s.sqr(A),L=s.mul(U,A);return s.add(s.add(L,s.mul(A,_)),P)}function a(A,_){const P=s.sqr(_),U=o(A);return s.eql(P,U)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=s.mul(s.pow(e.a,ul),j_),l=s.mul(s.sqr(e.b),BigInt(27));if(s.is0(s.add(c,l)))throw new Error("bad curve params: a or b");function d(A){return Qd(A,gt,e.n)}function u(A){const{allowedPrivateKeyLengths:_,nByteLength:P,wrapPrivateKey:U,n:L}=e;if(_&&typeof A!="bigint"){if(na(A)&&(A=So(A)),typeof A!="string"||!_.includes(A.length))throw new Error("invalid private key");A=A.padStart(P*2,"0")}let W;try{W=typeof A=="bigint"?A:Ir(bs("private key",A,P))}catch{throw new Error("invalid private key, expected hex or "+P+" bytes, got "+typeof A)}return U&&(W=Gt(W,L)),ai("private key",W,gt,L),W}function h(A){if(!(A instanceof f))throw new Error("ProjectivePoint expected")}const p=sh((A,_)=>{const{px:P,py:U,pz:L}=A;if(s.eql(L,s.ONE))return{x:P,y:U};const W=A.is0();_==null&&(_=W?s.ONE:s.inv(L));const k=s.mul(P,_),q=s.mul(U,_),V=s.mul(L,_);if(W)return{x:s.ZERO,y:s.ZERO};if(!s.eql(V,s.ONE))throw new Error("invZ was invalid");return{x:k,y:q}}),g=sh(A=>{if(A.is0()){if(e.allowInfinityPoint&&!s.is0(A.py))return;throw new Error("bad point: ZERO")}const{x:_,y:P}=A.toAffine();if(!s.isValid(_)||!s.isValid(P))throw new Error("bad point: x or y not FE");if(!a(_,P))throw new Error("bad point: equation left != right");if(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(_,P,U){if(_==null||!s.isValid(_))throw new Error("x required");if(P==null||!s.isValid(P)||s.is0(P))throw new Error("y required");if(U==null||!s.isValid(U))throw new Error("z required");this.px=_,this.py=P,this.pz=U,Object.freeze(this)}static fromAffine(_){const{x:P,y:U}=_||{};if(!_||!s.isValid(P)||!s.isValid(U))throw new Error("invalid affine point");if(_ instanceof f)throw new Error("projective point not allowed");const L=W=>s.eql(W,s.ZERO);return L(P)&&L(U)?f.ZERO:new f(P,U,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(_){const P=mg(s,_.map(U=>U.pz));return _.map((U,L)=>U.toAffine(P[L])).map(f.fromAffine)}static fromHex(_){const P=f.fromAffine(i(bs("pointHex",_)));return P.assertValidity(),P}static fromPrivateKey(_){return f.BASE.multiply(u(_))}static msm(_,P){return L_(f,n,_,P)}_setWindowSize(_){N.setWindowSize(this,_)}assertValidity(){g(this)}hasEvenY(){const{y:_}=this.toAffine();if(s.isOdd)return!s.isOdd(_);throw new Error("Field doesn't support isOdd")}equals(_){h(_);const{px:P,py:U,pz:L}=this,{px:W,py:k,pz:q}=_,V=s.eql(s.mul(P,q),s.mul(W,L)),x=s.eql(s.mul(U,q),s.mul(k,L));return V&&x}negate(){return new f(this.px,s.neg(this.py),this.pz)}double(){const{a:_,b:P}=e,U=s.mul(P,ul),{px:L,py:W,pz:k}=this;let q=s.ZERO,V=s.ZERO,x=s.ZERO,I=s.mul(L,L),T=s.mul(W,W),y=s.mul(k,k),b=s.mul(L,W);return b=s.add(b,b),x=s.mul(L,k),x=s.add(x,x),q=s.mul(_,x),V=s.mul(U,y),V=s.add(q,V),q=s.sub(T,V),V=s.add(T,V),V=s.mul(q,V),q=s.mul(b,q),x=s.mul(U,x),y=s.mul(_,y),b=s.sub(I,y),b=s.mul(_,b),b=s.add(b,x),x=s.add(I,I),I=s.add(x,I),I=s.add(I,y),I=s.mul(I,b),V=s.add(V,I),y=s.mul(W,k),y=s.add(y,y),I=s.mul(y,b),q=s.sub(q,I),x=s.mul(y,T),x=s.add(x,x),x=s.add(x,x),new f(q,V,x)}add(_){h(_);const{px:P,py:U,pz:L}=this,{px:W,py:k,pz:q}=_;let V=s.ZERO,x=s.ZERO,I=s.ZERO;const T=e.a,y=s.mul(e.b,ul);let b=s.mul(P,W),S=s.mul(U,k),R=s.mul(L,q),C=s.add(P,U),O=s.add(W,k);C=s.mul(C,O),O=s.add(b,S),C=s.sub(C,O),O=s.add(P,L);let B=s.add(W,q);return O=s.mul(O,B),B=s.add(b,R),O=s.sub(O,B),B=s.add(U,L),V=s.add(k,q),B=s.mul(B,V),V=s.add(S,R),B=s.sub(B,V),I=s.mul(T,O),V=s.mul(y,R),I=s.add(V,I),V=s.sub(S,I),I=s.add(S,I),x=s.mul(V,I),S=s.add(b,b),S=s.add(S,b),R=s.mul(T,R),O=s.mul(y,O),S=s.add(S,R),R=s.sub(b,R),R=s.mul(T,R),O=s.add(O,R),b=s.mul(S,O),x=s.add(x,b),b=s.mul(B,O),V=s.mul(C,V),V=s.sub(V,b),b=s.mul(C,S),I=s.mul(B,I),I=s.add(I,b),new f(V,x,I)}subtract(_){return this.add(_.negate())}is0(){return this.equals(f.ZERO)}wNAF(_){return N.wNAFCached(this,_,f.normalizeZ)}multiplyUnsafe(_){const{endo:P,n:U}=e;ai("scalar",_,En,U);const L=f.ZERO;if(_===En)return L;if(this.is0()||_===gt)return this;if(!P||N.hasPrecomputes(this))return N.wNAFCachedUnsafe(this,_,f.normalizeZ);let{k1neg:W,k1:k,k2neg:q,k2:V}=P.splitScalar(_),x=L,I=L,T=this;for(;k>En||V>En;)k&gt&&(x=x.add(T)),V&gt&&(I=I.add(T)),T=T.double(),k>>=gt,V>>=gt;return W&&(x=x.negate()),q&&(I=I.negate()),I=new f(s.mul(I.px,P.beta),I.py,I.pz),x.add(I)}multiply(_){const{endo:P,n:U}=e;ai("scalar",_,gt,U);let L,W;if(P){const{k1neg:k,k1:q,k2neg:V,k2:x}=P.splitScalar(_);let{p:I,f:T}=this.wNAF(q),{p:y,f:b}=this.wNAF(x);I=N.constTimeNegate(k,I),y=N.constTimeNegate(V,y),y=new f(s.mul(y.px,P.beta),y.py,y.pz),L=I.add(y),W=T.add(b)}else{const{p:k,f:q}=this.wNAF(_);L=k,W=q}return f.normalizeZ([L,W])[0]}multiplyAndAddUnsafe(_,P,U){const L=f.BASE,W=(q,V)=>V===En||V===gt||!q.equals(L)?q.multiplyUnsafe(V):q.multiply(V),k=W(this,P).add(W(_,U));return k.is0()?void 0:k}toAffine(_){return p(this,_)}isTorsionFree(){const{h:_,isTorsionFree:P}=e;if(_===gt)return!0;if(P)return P(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:_,clearCofactor:P}=e;return _===gt?this:P?P(f,this):this.multiplyUnsafe(e.h)}toRawBytes(_=!0){return Ao("isCompressed",_),this.assertValidity(),r(f,this,_)}toHex(_=!0){return Ao("isCompressed",_),So(this.toRawBytes(_))}}f.BASE=new f(e.Gx,e.Gy,s.ONE),f.ZERO=new f(s.ZERO,s.ONE,s.ZERO);const{endo:w,nBitLength:v}=e,N=D_(f,w?Math.ceil(v/2):v);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:u,weierstrassEquation:o,isWithinCurveOrder:d}}function q_(t){const e=Cg(t);return Pc(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function W_(t){const e=q_(t),{Fp:s,n,nByteLength:r,nBitLength:i}=e,o=s.BYTES+1,a=2*s.BYTES+1;function c(y){return Gt(y,n)}function l(y){return rd(y,n)}const{ProjectivePoint:d,normPrivateKeyToScalar:u,weierstrassEquation:h,isWithinCurveOrder:p}=F_({...e,toBytes(y,b,S){const R=b.toAffine(),C=s.toBytes(R.x),O=uc;return Ao("isCompressed",S),S?O(Uint8Array.from([b.hasEvenY()?2:3]),C):O(Uint8Array.from([4]),C,s.toBytes(R.y))},fromBytes(y){const b=y.length,S=y[0],R=y.subarray(1);if(b===o&&(S===2||S===3)){const C=Ir(R);if(!Qd(C,gt,s.ORDER))throw new Error("Point is not on curve");const O=h(C);let B;try{B=s.sqrt(O)}catch(j){const J=j instanceof Error?": "+j.message:"";throw new Error("Point is not on curve"+J)}const M=(B&gt)===gt;return(S&1)===1!==M&&(B=s.neg(B)),{x:C,y:B}}else if(b===a&&S===4){const C=s.fromBytes(R.subarray(0,s.BYTES)),O=s.fromBytes(R.subarray(s.BYTES,2*s.BYTES));return{x:C,y:O}}else{const C=o,O=a;throw new Error("invalid Point, expected length of "+C+", or uncompressed "+O+", got "+b)}}});function g(y){const b=n>>gt;return y>b}function f(y){return g(y)?c(-y):y}const w=(y,b,S)=>Ir(y.slice(b,S));class v{constructor(b,S,R){ai("r",b,gt,n),ai("s",S,gt,n),this.r=b,this.s=S,R!=null&&(this.recovery=R),Object.freeze(this)}static fromCompact(b){const S=r;return b=bs("compactSignature",b,S*2),new v(w(b,0,S),w(b,S,2*S))}static fromDER(b){const{r:S,s:R}=mn.toSig(bs("DER",b));return new v(S,R)}assertValidity(){}addRecoveryBit(b){return new v(this.r,this.s,b)}recoverPublicKey(b){const{r:S,s:R,recovery:C}=this,O=L(bs("msgHash",b));if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");const B=C===2||C===3?S+e.n:S;if(B>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const M=C&1?"03":"02",ce=d.fromHex(M+dl(B,s.BYTES)),j=l(B),J=c(-O*j),he=c(R*j),ge=d.BASE.multiplyAndAddUnsafe(ce,J,he);if(!ge)throw new Error("point at infinify");return ge.assertValidity(),ge}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return dc(this.toDERHex())}toDERHex(){return mn.hexFromSig(this)}toCompactRawBytes(){return dc(this.toCompactHex())}toCompactHex(){const b=r;return dl(this.r,b)+dl(this.s,b)}}const N={isValidPrivateKey(y){try{return u(y),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const y=Eg(e.n);return k_(e.randomBytes(y),e.n)},precompute(y=8,b=d.BASE){return b._setWindowSize(y),b.multiply(BigInt(3)),b}};function A(y,b=!0){return d.fromPrivateKey(y).toRawBytes(b)}function _(y){if(typeof y=="bigint")return!1;if(y instanceof d)return!0;const S=bs("key",y).length,R=s.BYTES,C=R+1,O=2*R+1;if(!(e.allowedPrivateKeyLengths||r===C))return S===C||S===O}function P(y,b,S=!0){if(_(y)===!0)throw new Error("first arg must be private key");if(_(b)===!1)throw new Error("second arg must be public key");return d.fromHex(b).multiply(u(y)).toRawBytes(S)}const U=e.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const b=Ir(y),S=y.length*8-i;return S>0?b>>BigInt(S):b},L=e.bits2int_modN||function(y){return c(U(y))},W=Oc(i);function k(y){return ai("num < 2^"+i,y,En,W),ra(y,r)}function q(y,b,S=V){if(["recovered","canonical"].some(ye=>ye in S))throw new Error("sign() legacy options not supported");const{hash:R,randomBytes:C}=e;let{lowS:O,prehash:B,extraEntropy:M}=S;O==null&&(O=!0),y=bs("msgHash",y),hh(S),B&&(y=bs("prehashed msgHash",R(y)));const ce=L(y),j=u(b),J=[k(j),k(ce)];if(M!=null&&M!==!1){const ye=M===!0?C(s.BYTES):M;J.push(bs("extraEntropy",ye))}const he=uc(...J),ge=ce;function xe(ye){const ve=U(ye);if(!p(ve))return;const Ve=l(ve),st=d.BASE.multiply(ve).toAffine(),ut=c(st.x);if(ut===En)return;const wt=c(Ve*c(ge+ut*j));if(wt===En)return;let Fs=(st.x===ut?0:2)|Number(st.y&gt),rn=wt;return O&&g(wt)&&(rn=f(wt),Fs^=1),new v(ut,rn,Fs)}return{seed:he,k2sig:xe}}const V={lowS:e.lowS,prehash:!1},x={lowS:e.lowS,prehash:!1};function I(y,b,S=V){const{seed:R,k2sig:C}=q(y,b,S),O=e;return FC(O.hash.outputLen,O.nByteLength,O.hmac)(R,C)}d.BASE._setWindowSize(8);function T(y,b,S,R=x){var Fs;const C=y;b=bs("msgHash",b),S=bs("publicKey",S);const{lowS:O,prehash:B,format:M}=R;if(hh(R),"strict"in R)throw new Error("options.strict was renamed to lowS");if(M!==void 0&&M!=="compact"&&M!=="der")throw new Error("format must be compact or der");const ce=typeof C=="string"||na(C),j=!ce&&!M&&typeof C=="object"&&C!==null&&typeof C.r=="bigint"&&typeof C.s=="bigint";if(!ce&&!j)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let J,he;try{if(j&&(J=new v(C.r,C.s)),ce){try{M!=="compact"&&(J=v.fromDER(C))}catch(rn){if(!(rn instanceof mn.Err))throw rn}!J&&M!=="der"&&(J=v.fromCompact(C))}he=d.fromHex(S)}catch{return!1}if(!J||O&&J.hasHighS())return!1;B&&(b=e.hash(b));const{r:ge,s:xe}=J,ye=L(b),ve=l(xe),Ve=c(ye*ve),st=c(ge*ve),ut=(Fs=d.BASE.multiplyAndAddUnsafe(he,Ve,st))==null?void 0:Fs.toAffine();return ut?c(ut.x)===ge:!1}return{CURVE:e,getPublicKey:A,getSharedSecret:P,sign:I,verify:T,ProjectivePoint:d,Signature:v,utils:N}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function H_(t){return{hash:t,hmac:(e,...s)=>Oy(t,e,Py(...s)),randomBytes:Ry}}function z_(t,e){const s=n=>W_({...t,...H_(n)});return{...s(e),create:s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _g=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ph=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),V_=BigInt(0),K_=BigInt(1),od=BigInt(2),fh=(t,e)=>(t+e/od)/e;function G_(t){const e=_g,s=BigInt(3),n=BigInt(6),r=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,u=fs(d,s,e)*d%e,h=fs(u,s,e)*d%e,p=fs(h,od,e)*l%e,g=fs(p,r,e)*p%e,f=fs(g,i,e)*g%e,w=fs(f,a,e)*f%e,v=fs(w,c,e)*w%e,N=fs(v,a,e)*f%e,A=fs(N,s,e)*d%e,_=fs(A,o,e)*g%e,P=fs(_,n,e)*l%e,U=fs(P,od,e);if(!ad.eql(ad.sqr(U),t))throw new Error("Cannot find square root");return U}const ad=su(_g,void 0,void 0,{sqrt:G_}),Y_=z_({a:V_,b:BigInt(7),Fp:ad,n:ph,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=ph,s=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-K_*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=s,o=BigInt("0x100000000000000000000000000000000"),a=fh(i*t,e),c=fh(-n*t,e);let l=Gt(t-a*s-c*r,e),d=Gt(-a*n-c*i,e);const u=l>o,h=d>o;if(u&&(l=e-l),h&&(d=e-d),l>o||d>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}}},xy);function Z_(t){if(t.length!==130&&t.length!==132)throw new X_({signature:t});const e=BigInt(fn(t,0,32)),s=BigInt(fn(t,32,64)),n=(()=>{const r=+`0x${t.slice(130)}`;if(!Number.isNaN(r))try{return J_(r)}catch{throw new Q_({value:r})}})();return typeof n>"u"?{r:e,s}:{r:e,s,yParity:n}}function J_(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new e0({value:t})}class X_ extends tt{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${tr(tu(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class Q_ extends tt{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class e0 extends tt{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function t0(t){return __(s0(t))}function s0(t){const{payload:e,signature:s}=t,{r:n,s:r,yParity:i}=s,a=new Y_.Signature(BigInt(n),BigInt(r)).addRecoveryBit(i).recoverPublicKey(tu(e).substring(2));return f_(a)}var n0={};const r0=":";function _n(t){const[e,s]=t.split(r0);return{namespace:e,reference:s}}function Ag(t,e){return t.includes(":")?[t]:e.chains||[]}var i0=Object.defineProperty,o0=Object.defineProperties,a0=Object.getOwnPropertyDescriptors,gh=Object.getOwnPropertySymbols,c0=Object.prototype.hasOwnProperty,l0=Object.prototype.propertyIsEnumerable,cd=(t,e,s)=>e in t?i0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mh=(t,e)=>{for(var s in e||(e={}))c0.call(e,s)&&cd(t,s,e[s]);if(gh)for(var s of gh(e))l0.call(e,s)&&cd(t,s,e[s]);return t},d0=(t,e)=>o0(t,a0(e)),yh=(t,e,s)=>cd(t,typeof e!="symbol"?e+"":e,s);const u0="ReactNative",ps={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},h0="js";function pc(){return typeof vn<"u"&&typeof vn.versions<"u"&&typeof vn.versions.node<"u"}function nr(){return!In.getDocument()&&!!In.getNavigator()&&navigator.product===u0}function p0(){return nr()&&typeof Ce<"u"&&typeof(Ce==null?void 0:Ce.Platform)<"u"&&(Ce==null?void 0:Ce.Platform.OS)==="android"}function f0(){return nr()&&typeof Ce<"u"&&typeof(Ce==null?void 0:Ce.Platform)<"u"&&(Ce==null?void 0:Ce.Platform.OS)==="ios"}function Ni(){return!pc()&&!!In.getNavigator()&&!!In.getDocument()}function ia(){return nr()?ps.reactNative:pc()?ps.node:Ni()?ps.browser:ps.unknown}function wh(){var t;try{return nr()&&typeof Ce<"u"&&typeof(Ce==null?void 0:Ce.Application)<"u"?(t=Ce.Application)==null?void 0:t.applicationId:void 0}catch{return}}function g0(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 m0(t){var e,s;const n=Sg();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==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(r=>r!=="")),d0(mh(mh({},n),t),{url:(t==null?void 0:t.url)||n.url,name:(t==null?void 0:t.name)||n.name,description:(t==null?void 0:t.description)||n.description,icons:(s=t==null?void 0: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 Sg(){return By.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function y0(){if(ia()===ps.reactNative&&typeof Ce<"u"&&typeof(Ce==null?void 0:Ce.Platform)<"u"){const{OS:s,Version:n}=Ce.Platform;return[s,n].join("-")}const t=Fy();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 w0(){var t;const e=ia();return e===ps.browser?[e,((t=In.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function Ig(t,e,s){const n=y0(),r=w0();return[[t,e].join("-"),[h0,s].join("-"),n,r].join("/")}function E0({protocol:t,version:e,relayUrl:s,sdkVersion:n,auth:r,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),d=Ig(t,e,n),u={auth:r,ua:d,projectId:i,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},h=g0(l[1]||"",u);return l[0]+"?"+h}function wr(t,e){return t.filter(s=>e.includes(s)).length===t.length}function ld(t){return Object.fromEntries(t.entries())}function dd(t){return new Map(Object.entries(t))}function hr(t=Z.FIVE_MINUTES,e){const s=Z.toMiliseconds(t||Z.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 Zs(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 Ng(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 b0(t){return Ng("topic",t)}function v0(t){return Ng("id",t)}function Tg(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 rt(t,e){return Z.fromMiliseconds(Date.now()+Z.toMiliseconds(t))}function Gs(t){return Date.now()>=Z.toMiliseconds(t)}function Fe(t,e){return`${t}${e?`:${e}`:""}`}function Qs(t=[],e=[]){return[...new Set([...t,...e])]}async function C0({id:t,topic:e,wcDeepLink:s}){var n;try{if(!s)return;const r=typeof s=="string"?JSON.parse(s):s,i=r==null?void 0:r.href;if(typeof i!="string")return;const o=_0(i,t,e),a=ia();if(a===ps.browser){if(!((n=In.getDocument())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}A0(o)}else a===ps.reactNative&&typeof(Ce==null?void 0:Ce.Linking)<"u"&&await Ce.Linking.openURL(o)}catch(r){console.error(r)}}function _0(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}${T0(n,!0)}`}else r=`${r}/wc?${n}`;return r}function A0(t){let e="_self";N0()?e="_top":(I0()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function S0(t,e){let s="";try{if(Ni()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(n){console.error(n)}return s}function Eh(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),n=s.indexOf(e);return s[n+2]}function bh(){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 nu(){return typeof vn<"u"&&n0.IS_VITEST==="true"}function I0(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function N0(){try{return window.self!==window.top}catch{return!1}}function T0(t,e=!1){const s=Pe.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function Rg(t){return Pe.from(t,"base64").toString("utf-8")}function R0(t){return new Promise(e=>setTimeout(e,t))}let O0=class{constructor({limit:e}){yh(this,"limit"),yh(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 Ca=BigInt(2**32-1),vh=BigInt(32);function Og(t,e=!1){return e?{h:Number(t&Ca),l:Number(t>>vh&Ca)}:{h:Number(t>>vh&Ca)|0,l:Number(t&Ca)|0}}function Pg(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}=Og(t[i],e);[n[i],r[i]]=[o,a]}return[n,r]}const Ch=(t,e,s)=>t>>>s,_h=(t,e,s)=>t<<32-s|e>>>s,Mn=(t,e,s)=>t>>>s|e<<32-s,Bn=(t,e,s)=>t<<32-s|e>>>s,zi=(t,e,s)=>t<<64-s|e>>>s-32,Vi=(t,e,s)=>t>>>s-32|e<<64-s,P0=(t,e)=>e,x0=(t,e)=>t,k0=(t,e,s)=>t<<s|e>>>32-s,U0=(t,e,s)=>e<<s|t>>>32-s,$0=(t,e,s)=>e<<s-32|t>>>64-s,D0=(t,e,s)=>t<<s-32|e>>>64-s;function xs(t,e,s,n){const r=(e>>>0)+(n>>>0);return{h:t+s+(r/2**32|0)|0,l:r|0}}const ru=(t,e,s)=>(t>>>0)+(e>>>0)+(s>>>0),iu=(t,e,s,n)=>e+s+n+(t/2**32|0)|0,L0=(t,e,s,n)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0),M0=(t,e,s,n,r)=>e+s+n+r+(t/2**32|0)|0,B0=(t,e,s,n,r)=>(t>>>0)+(e>>>0)+(s>>>0)+(n>>>0)+(r>>>0),j0=(t,e,s,n,r,i)=>e+s+n+r+i+(t/2**32|0)|0,Vr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function xc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Tn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function js(t,...e){if(!xc(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 kc(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Tn(t.outputLen),Tn(t.blockLen)}function sr(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 ou(t,e){js(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Io(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ss(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function hl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function qs(t,e){return t<<32-e|t>>>e}const xg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function kg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const un=xg?t=>t:t=>kg(t);function F0(t){for(let e=0;e<t.length;e++)t[e]=kg(t[e]);return t}const jn=xg?t=>t:F0,Ug=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",q0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ci(t){if(js(t),Ug)return t.toHex();let e="";for(let s=0;s<t.length;s++)e+=q0[t[s]];return e}const ln={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ah(t){if(t>=ln._0&&t<=ln._9)return t-ln._0;if(t>=ln.A&&t<=ln.F)return t-(ln.A-10);if(t>=ln.a&&t<=ln.f)return t-(ln.a-10)}function fc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ug)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=Ah(t.charCodeAt(i)),a=Ah(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 $g(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ms(t){return typeof t=="string"&&(t=$g(t)),js(t),t}function Wn(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];js(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}let Uc=class{};function oa(t){const e=n=>t().update(Ms(n)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function W0(t){const e=(n,r)=>t(r).update(Ms(n)).digest(),s=t({});return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}function qr(t=32){if(Vr&&typeof Vr.getRandomValues=="function")return Vr.getRandomValues(new Uint8Array(t));if(Vr&&typeof Vr.randomBytes=="function")return Uint8Array.from(Vr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const H0=BigInt(0),ki=BigInt(1),z0=BigInt(2),V0=BigInt(7),K0=BigInt(256),G0=BigInt(113),Dg=[],Lg=[],Mg=[];for(let t=0,e=ki,s=1,n=0;t<24;t++){[s,n]=[n,(2*s+3*n)%5],Dg.push(2*(5*n+s)),Lg.push((t+1)*(t+2)/2%64);let r=H0;for(let i=0;i<7;i++)e=(e<<ki^(e>>V0)*G0)%K0,e&z0&&(r^=ki<<(ki<<BigInt(i))-ki);Mg.push(r)}const Bg=Pg(Mg,!0),Y0=Bg[0],Z0=Bg[1],Sh=(t,e,s)=>s>32?$0(t,e,s):k0(t,e,s),Ih=(t,e,s)=>s>32?D0(t,e,s):U0(t,e,s);function J0(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],d=s[c+1],u=Sh(l,d,1)^s[a],h=Ih(l,d,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=u,t[o+p+1]^=h}let r=t[2],i=t[3];for(let o=0;o<24;o++){const a=Lg[o],c=Sh(r,i,a),l=Ih(r,i,a),d=Dg[o];r=t[d],i=t[d+1],t[d]=c,t[d+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]^=Y0[n],t[1]^=Z0[n]}Ss(s)}let X0=class jg extends Uc{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,Tn(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Io(this.state)}clone(){return this._cloneInto()}keccak(){jn(this.state32),J0(this.state32,this.rounds),jn(this.state32),this.posOut=0,this.pos=0}update(e){sr(this),e=Ms(e),js(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&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){sr(this,!1),js(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 Tn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ou(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,Ss(this.state)}_cloneInto(e){const{blockLen:s,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new jg(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 Q0=(t,e,s)=>oa(()=>new X0(e,t,s)),eA=Q0(1,136,256/8);function tA(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 sA(t,e,s){return t&e^~t&s}function nA(t,e,s){return t&e^t&s^e&s}let Fg=class extends Uc{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=hl(this.buffer)}update(e){sr(this),e=Ms(e),js(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=hl(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){sr(this),ou(e,this),this.finished=!0;const{buffer:s,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;s[o++]=128,Ss(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let u=o;u<r;u++)s[u]=0;tA(n,r-8,BigInt(this.length*8),i),this.process(n,0);const a=hl(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],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 xn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),It=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]),rA=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]),kn=new Uint32Array(64);class iA extends Fg{constructor(e=32){super(64,e,8,!1),this.A=xn[0]|0,this.B=xn[1]|0,this.C=xn[2]|0,this.D=xn[3]|0,this.E=xn[4]|0,this.F=xn[5]|0,this.G=xn[6]|0,this.H=xn[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 u=0;u<16;u++,s+=4)kn[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const h=kn[u-15],p=kn[u-2],g=qs(h,7)^qs(h,18)^h>>>3,f=qs(p,17)^qs(p,19)^p>>>10;kn[u]=f+kn[u-7]+g+kn[u-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const h=qs(a,6)^qs(a,11)^qs(a,25),p=d+h+sA(a,c,l)+rA[u]+kn[u]|0,g=(qs(n,2)^qs(n,13)^qs(n,22))+nA(n,r,i)|0;d=l,l=c,c=a,a=o+p|0,o=i,i=r,r=n,n=p+g|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,d=d+this.H|0,this.set(n,r,i,o,a,c,l,d)}roundClean(){Ss(kn)}destroy(){this.set(0,0,0,0,0,0,0,0),Ss(this.buffer)}}const qg=Pg(["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))),oA=qg[0],aA=qg[1],Un=new Uint32Array(80),$n=new Uint32Array(80);let au=class extends Fg{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:d,Fh:u,Fl:h,Gh:p,Gl:g,Hh:f,Hl:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,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=d|0,this.Fh=u|0,this.Fl=h|0,this.Gh=p|0,this.Gl=g|0,this.Hh=f|0,this.Hl=w|0}process(e,s){for(let A=0;A<16;A++,s+=4)Un[A]=e.getUint32(s),$n[A]=e.getUint32(s+=4);for(let A=16;A<80;A++){const _=Un[A-15]|0,P=$n[A-15]|0,U=Mn(_,P,1)^Mn(_,P,8)^Ch(_,P,7),L=Bn(_,P,1)^Bn(_,P,8)^_h(_,P,7),W=Un[A-2]|0,k=$n[A-2]|0,q=Mn(W,k,19)^zi(W,k,61)^Ch(W,k,6),V=Bn(W,k,19)^Vi(W,k,61)^_h(W,k,6),x=L0(L,V,$n[A-7],$n[A-16]),I=M0(x,U,q,Un[A-7],Un[A-16]);Un[A]=I|0,$n[A]=x|0}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:d,Eh:u,El:h,Fh:p,Fl:g,Gh:f,Gl:w,Hh:v,Hl:N}=this;for(let A=0;A<80;A++){const _=Mn(u,h,14)^Mn(u,h,18)^zi(u,h,41),P=Bn(u,h,14)^Bn(u,h,18)^Vi(u,h,41),U=u&p^~u&f,L=h&g^~h&w,W=B0(N,P,L,aA[A],$n[A]),k=j0(W,v,_,U,oA[A],Un[A]),q=W|0,V=Mn(n,r,28)^zi(n,r,34)^zi(n,r,39),x=Bn(n,r,28)^Vi(n,r,34)^Vi(n,r,39),I=n&i^n&a^i&a,T=r&o^r&c^o&c;v=f|0,N=w|0,f=p|0,w=g|0,p=u|0,g=h|0,{h:u,l:h}=xs(l|0,d|0,k|0,q|0),l=a|0,d=c|0,a=i|0,c=o|0,i=n|0,o=r|0;const y=ru(q,x,T);n=iu(y,k,V,I),r=y|0}({h:n,l:r}=xs(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:o}=xs(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=xs(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=xs(this.Dh|0,this.Dl|0,l|0,d|0),{h:u,l:h}=xs(this.Eh|0,this.El|0,u|0,h|0),{h:p,l:g}=xs(this.Fh|0,this.Fl|0,p|0,g|0),{h:f,l:w}=xs(this.Gh|0,this.Gl|0,f|0,w|0),{h:v,l:N}=xs(this.Hh|0,this.Hl|0,v|0,N|0),this.set(n,r,i,o,a,c,l,d,u,h,p,g,f,w,v,N)}roundClean(){Ss(Un,$n)}destroy(){Ss(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class cA extends au{constructor(){super(48),this.Ah=It[0]|0,this.Al=It[1]|0,this.Bh=It[2]|0,this.Bl=It[3]|0,this.Ch=It[4]|0,this.Cl=It[5]|0,this.Dh=It[6]|0,this.Dl=It[7]|0,this.Eh=It[8]|0,this.El=It[9]|0,this.Fh=It[10]|0,this.Fl=It[11]|0,this.Gh=It[12]|0,this.Gl=It[13]|0,this.Hh=It[14]|0,this.Hl=It[15]|0}}const Tt=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class lA extends au{constructor(){super(32),this.Ah=Tt[0]|0,this.Al=Tt[1]|0,this.Bh=Tt[2]|0,this.Bl=Tt[3]|0,this.Ch=Tt[4]|0,this.Cl=Tt[5]|0,this.Dh=Tt[6]|0,this.Dl=Tt[7]|0,this.Eh=Tt[8]|0,this.El=Tt[9]|0,this.Fh=Tt[10]|0,this.Fl=Tt[11]|0,this.Gh=Tt[12]|0,this.Gl=Tt[13]|0,this.Hh=Tt[14]|0,this.Hl=Tt[15]|0}}const $c=oa(()=>new iA),dA=oa(()=>new au),uA=oa(()=>new cA),hA=oa(()=>new lA),pA=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]),ct=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),ee=new Uint32Array(32);function Dn(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=ee[2*t],l=ee[2*t+1],d=ee[2*e],u=ee[2*e+1],h=ee[2*s],p=ee[2*s+1],g=ee[2*n],f=ee[2*n+1],w=ru(c,d,o);l=iu(w,l,u,a),c=w|0,{Dh:f,Dl:g}={Dh:f^l,Dl:g^c},{Dh:f,Dl:g}={Dh:P0(f,g),Dl:x0(f)},{h:p,l:h}=xs(p,h,f,g),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:Mn(u,d,24),Bl:Bn(u,d,24)},ee[2*t]=c,ee[2*t+1]=l,ee[2*e]=d,ee[2*e+1]=u,ee[2*s]=h,ee[2*s+1]=p,ee[2*n]=g,ee[2*n+1]=f}function Ln(t,e,s,n,r,i){const o=r[i],a=r[i+1];let c=ee[2*t],l=ee[2*t+1],d=ee[2*e],u=ee[2*e+1],h=ee[2*s],p=ee[2*s+1],g=ee[2*n],f=ee[2*n+1],w=ru(c,d,o);l=iu(w,l,u,a),c=w|0,{Dh:f,Dl:g}={Dh:f^l,Dl:g^c},{Dh:f,Dl:g}={Dh:Mn(f,g,16),Dl:Bn(f,g,16)},{h:p,l:h}=xs(p,h,f,g),{Bh:u,Bl:d}={Bh:u^p,Bl:d^h},{Bh:u,Bl:d}={Bh:zi(u,d,63),Bl:Vi(u,d,63)},ee[2*t]=c,ee[2*t+1]=l,ee[2*e]=d,ee[2*e+1]=u,ee[2*s]=h,ee[2*s+1]=p,ee[2*n]=g,ee[2*n+1]=f}function fA(t,e={},s,n,r){if(Tn(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 gA extends Uc{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Tn(e),Tn(s),this.blockLen=e,this.outputLen=s,this.buffer=new Uint8Array(e),this.buffer32=Io(this.buffer)}update(e){sr(this),e=Ms(e),js(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&&(jn(r),this.compress(r,0,!1),jn(r),this.pos=0);const l=Math.min(s-this.pos,i-c),d=o+c;if(l===s&&!(d%4)&&c+l<i){const u=new Uint32Array(a,d,Math.floor((i-c)/4));jn(u);for(let h=0;c+s<i;h+=r.length,c+=s)this.length+=s,this.compress(u,h,!1);jn(u);continue}n.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){sr(this),ou(e,this);const{pos:s,buffer32:n}=this;this.finished=!0,Ss(this.buffer.subarray(s)),jn(n),this.compress(n,0,!0),jn(n);const r=Io(e);this.get().forEach((i,o)=>r[o]=un(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 mA extends gA{constructor(e={}){const s=e.dkLen===void 0?64:e.dkLen;super(128,s),this.v0l=ct[0]|0,this.v0h=ct[1]|0,this.v1l=ct[2]|0,this.v1h=ct[3]|0,this.v2l=ct[4]|0,this.v2h=ct[5]|0,this.v3l=ct[6]|0,this.v3h=ct[7]|0,this.v4l=ct[8]|0,this.v4h=ct[9]|0,this.v5l=ct[10]|0,this.v5h=ct[11]|0,this.v6l=ct[12]|0,this.v6h=ct[13]|0,this.v7l=ct[14]|0,this.v7h=ct[15]|0,fA(s,e,64,16,16);let{key:n,personalization:r,salt:i}=e,o=0;if(n!==void 0&&(n=Ms(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=Ms(i);const a=Io(i);this.v4l^=un(a[0]),this.v4h^=un(a[1]),this.v5l^=un(a[2]),this.v5h^=un(a[3])}if(r!==void 0){r=Ms(r);const a=Io(r);this.v6l^=un(a[0]),this.v6h^=un(a[1]),this.v7l^=un(a[2]),this.v7h^=un(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:d,v5l:u,v5h:h,v6l:p,v6h:g,v7l:f,v7h:w}=this;return[e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,w]}set(e,s,n,r,i,o,a,c,l,d,u,h,p,g,f,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=d|0,this.v5l=u|0,this.v5h=h|0,this.v6l=p|0,this.v6h=g|0,this.v7l=f|0,this.v7h=w|0}compress(e,s,n){this.get().forEach((c,l)=>ee[l]=c),ee.set(ct,16);let{h:r,l:i}=Og(BigInt(this.length));ee[24]=ct[8]^i,ee[25]=ct[9]^r,n&&(ee[28]=~ee[28],ee[29]=~ee[29]);let o=0;const a=pA;for(let c=0;c<12;c++)Dn(0,4,8,12,e,s+2*a[o++]),Ln(0,4,8,12,e,s+2*a[o++]),Dn(1,5,9,13,e,s+2*a[o++]),Ln(1,5,9,13,e,s+2*a[o++]),Dn(2,6,10,14,e,s+2*a[o++]),Ln(2,6,10,14,e,s+2*a[o++]),Dn(3,7,11,15,e,s+2*a[o++]),Ln(3,7,11,15,e,s+2*a[o++]),Dn(0,5,10,15,e,s+2*a[o++]),Ln(0,5,10,15,e,s+2*a[o++]),Dn(1,6,11,12,e,s+2*a[o++]),Ln(1,6,11,12,e,s+2*a[o++]),Dn(2,7,8,13,e,s+2*a[o++]),Ln(2,7,8,13,e,s+2*a[o++]),Dn(3,4,9,14,e,s+2*a[o++]),Ln(3,4,9,14,e,s+2*a[o++]);this.v0l^=ee[0]^ee[16],this.v0h^=ee[1]^ee[17],this.v1l^=ee[2]^ee[18],this.v1h^=ee[3]^ee[19],this.v2l^=ee[4]^ee[20],this.v2h^=ee[5]^ee[21],this.v3l^=ee[6]^ee[22],this.v3h^=ee[7]^ee[23],this.v4l^=ee[8]^ee[24],this.v4h^=ee[9]^ee[25],this.v5l^=ee[10]^ee[26],this.v5h^=ee[11]^ee[27],this.v6l^=ee[12]^ee[28],this.v6h^=ee[13]^ee[29],this.v7l^=ee[14]^ee[30],this.v7h^=ee[15]^ee[31],Ss(ee)}destroy(){this.destroyed=!0,Ss(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const yA=W0(t=>new mA(t)),wA="https://rpc.walletconnect.org/v1";function Wg(t){const e=`Ethereum Signed Message:
6
+ ${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Pe.from(eA(s)).toString("hex")}async function EA(t,e,s,n,r,i){switch(s.t){case"eip191":return await bA(t,e,s.s);case"eip1271":return await vA(t,e,s.s,n,r,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}function bA(t,e,s){const n=Z_(s);return t0({payload:Wg(e),signature:n}).toLowerCase()===t.toLowerCase()}async function vA(t,e,s,n,r,i){const o=_n(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),d=(l.length/2).toString(16).padStart(64,"0"),u=(e.startsWith("0x")?e:Wg(e)).substring(2),h=a+u+c+d+l,p=await fetch(`${i||wA}/?chainId=${n}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:CA(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:g}=await p.json();return g?g.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function CA(){return Date.now()+Math.floor(Math.random()*1e3)}function _A(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=Pe.from(t,"base64").slice(1,65);return Si.encode(i)}function AA(t){const e=new Uint8Array(Pe.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=yA(n,{dkLen:32});return Si.encode(r)}function Nh(t){const e=new Uint8Array($c(SA(t)));return Si.encode(e)}function SA(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 Th(t){const e=Pe.from(t,"base64"),s=qy(e).txn;if(!s)throw new Error("Invalid signed transaction: missing 'txn' field");const n=Wy(s),r=Pe.from("TX"),i=Pe.concat([r,Pe.from(n)]),o=hA(i);return Iy.encode(o).replace(/=+$/,"")}function pl(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)),Pe.from(e)}function IA(t){const e=Pe.from(t.signed.bodyBytes,"base64"),s=Pe.from(t.signed.authInfoBytes,"base64"),n=Pe.from(t.signature.signature,"base64"),r=[];r.push(Pe.from([10])),r.push(pl(e.length)),r.push(e),r.push(Pe.from([18])),r.push(pl(s.length)),r.push(s),r.push(Pe.from([26])),r.push(pl(n.length)),r.push(n);const i=Pe.concat(r),o=$c(i);return Pe.from(o).toString("hex").toUpperCase()}function NA(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==null?void 0: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 TA=Object.defineProperty,RA=Object.defineProperties,OA=Object.getOwnPropertyDescriptors,Rh=Object.getOwnPropertySymbols,PA=Object.prototype.hasOwnProperty,xA=Object.prototype.propertyIsEnumerable,Oh=(t,e,s)=>e in t?TA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,kA=(t,e)=>{for(var s in e||(e={}))PA.call(e,s)&&Oh(t,s,e[s]);if(Rh)for(var s of Rh(e))xA.call(e,s)&&Oh(t,s,e[s]);return t},UA=(t,e)=>RA(t,OA(e));const Hg="did:pkh:",$A={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},DA=t=>t?$A[t]||t:"",Dc=t=>t==null?void 0:t.split(":"),LA=t=>{const e=t&&Dc(t);if(e)return t.includes(Hg)?e[3]:e[1]},MA=t=>{const e=t&&Dc(t);if(e)return t.includes(Hg)?e[2]:e[0]},ud=t=>{const e=t&&Dc(t);if(e)return e[2]+":"+e[3]},gc=t=>{const e=t&&Dc(t);if(e)return e.pop()};async function Ph(t){const{cacao:e,projectId:s}=t,{s:n,p:r}=e,i=zg(r,r.iss),o=gc(r.iss);return await EA(o,i,n,ud(r.iss),s)}const zg=(t,e)=>{const s=MA(e);if(!s)throw new Error("Invalid issuer: "+e);const n=`${t.domain} wants you to sign in with your ${DA(s)} account:`,r=gc(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0;const o=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,c=`Chain ID: ${LA(e)}`,l=`Nonce: ${t.nonce}`,d=`Issued At: ${t.iat}`,u=t.exp?`Expiration Time: ${t.exp}`:void 0,h=t.nbf?`Not Before: ${t.nbf}`:void 0,p=t.requestId?`Request ID: ${t.requestId}`:void 0,g=t.resources?`Resources:${t.resources.map(w=>`
7
+ - ${w}`).join("")}`:void 0,f=Wa(t.resources);if(f){const w=No(f);i=KA(i,w)}return[n,r,"",i,"",o,a,c,l,d,u,h,p,g].filter(w=>w!=null).join(`
8
+ `)};function BA(t){return Pe.from(JSON.stringify(t)).toString("base64")}function jA(t){return JSON.parse(Pe.from(t,"base64").toString("utf-8"))}function $r(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 FA(t,e,s,n={}){return s==null||s.sort((r,i)=>r.localeCompare(i)),{att:{[t]:qA(e,s,n)}}}function qA(t,e,s={}){e=e==null?void 0:e.sort((r,i)=>r.localeCompare(i));const n=e.map(r=>({[`${t}/${r}`]:[s]}));return Object.assign({},...n)}function Vg(t){return $r(t),`urn:recap:${BA(t).replace(/=/g,"")}`}function No(t){const e=jA(t.replace("urn:recap:",""));return $r(e),e}function WA(t,e,s){const n=FA(t,e,s);return Vg(n)}function HA(t){return t&&t.includes("urn:recap:")}function zA(t,e){const s=No(t),n=No(e),r=VA(s,n);return Vg(r)}function VA(t,e){$r(t),$r(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]=UA(kA({},n.att[r]),{[a]:((c=t.att[r])==null?void 0:c[a])||((l=e.att[r])==null?void 0:l[a])})})}),n}function KA(t="",e){$r(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(u=>({ability:u.split("/")[0],action:u.split("/")[1]}));c.sort((u,h)=>u.action.localeCompare(h.action));const l={};c.forEach(u=>{l[u.ability]||(l[u.ability]=[]),l[u.ability].push(u.action)});const d=Object.keys(l).map(u=>(r++,`(${r}) '${u}': '${l[u].join("', '")}' for '${a}'.`));n.push(d.join(", ").replace(".,","."))});const i=n.join(" "),o=`${s}${i}`;return`${t?t+" ":""}${o}`}function xh(t){var e;const s=No(t);$r(s);const n=(e=s.att)==null?void 0:e.eip155;return n?Object.keys(n).map(r=>r.split("/")[1]):[]}function kh(t){const e=No(t);$r(e);const s=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(r=>{var i;(i=r==null?void 0:r[0])!=null&&i.chains&&s.push(r[0].chains)})}),[...new Set(s.flat())]}function Wa(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return HA(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Kg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function hd(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function fl(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Yt(t,...e){if(!Kg(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 Uh(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 GA(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 Gn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function mi(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function YA(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const ZA=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function JA(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function pd(t){if(typeof t=="string")t=JA(t);else if(Kg(t))t=fd(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function XA(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function QA(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 eS=(t,e)=>{function s(n,...r){if(Yt(n),!ZA)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,d)=>{if(d!==void 0){if(l!==2)throw new Error("cipher output not supported");Yt(d)}};let c=!1;return{encrypt(l,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Yt(l),a(o.encrypt.length,d),o.encrypt(l,d)},decrypt(l,d){if(Yt(l),i&&l.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return a(o.decrypt.length,d),o.decrypt(l,d)}}}return Object.assign(s,t),s};function $h(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&&!sS(e))throw new Error("invalid output, must be aligned");return e}function Dh(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 tS(t,e,s){hd(s);const n=new Uint8Array(16),r=YA(n);return Dh(r,0,BigInt(e),s),Dh(r,8,BigInt(t),s),n}function sS(t){return t.byteOffset%4===0}function fd(t){return Uint8Array.from(t)}const Gg=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),nS=Gg("expand 16-byte k"),rS=Gg("expand 32-byte k"),iS=Gn(nS),oS=Gn(rS);function De(t,e){return t<<e|t>>>32-e}function gd(t){return t.byteOffset%4===0}const _a=64,aS=16,Yg=2**32-1,Lh=new Uint32Array;function cS(t,e,s,n,r,i,o,a){const c=r.length,l=new Uint8Array(_a),d=Gn(l),u=gd(r)&&gd(i),h=u?Gn(r):Lh,p=u?Gn(i):Lh;for(let g=0;g<c;o++){if(t(e,s,n,d,o,a),o>=Yg)throw new Error("arx: counter overflow");const f=Math.min(_a,c-g);if(u&&f===_a){const w=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let v=0,N;v<aS;v++)N=w+v,p[N]=h[N]^d[v];g+=_a;continue}for(let w=0,v;w<f;w++)v=g+w,i[v]=r[v]^l[w];g+=f}}function lS(t,e){const{allowShortKeys:s,extendNonceFn:n,counterLength:r,counterRight:i,rounds:o}=XA({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return fl(r),fl(o),hd(i),hd(s),(a,c,l,d,u=0)=>{Yt(a),Yt(c),Yt(l);const h=l.length;if(d===void 0&&(d=new Uint8Array(h)),Yt(d),fl(u),u<0||u>=Yg)throw new Error("arx: counter overflow");if(d.length<h)throw new Error(`arx: output (${d.length}) is shorter than data (${h})`);const p=[];let g=a.length,f,w;if(g===32)p.push(f=fd(a)),w=oS;else if(g===16&&s)f=new Uint8Array(32),f.set(a),f.set(a,16),w=iS,p.push(f);else throw new Error(`arx: invalid 32-byte key, got length=${g}`);gd(c)||p.push(c=fd(c));const v=Gn(f);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(w,v,Gn(c.subarray(0,16)),v),c=c.subarray(16)}const N=16-r;if(N!==c.length)throw new Error(`arx: nonce must be ${N} or 16 bytes`);if(N!==12){const _=new Uint8Array(12);_.set(c,i?0:12-c.length),c=_,p.push(c)}const A=Gn(c);return cS(t,w,v,A,l,d,u,o),mi(...p),d}}const Et=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class dS{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=pd(e),Yt(e,32);const s=Et(e,0),n=Et(e,2),r=Et(e,4),i=Et(e,6),o=Et(e,8),a=Et(e,10),c=Et(e,12),l=Et(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 d=0;d<8;d++)this.pad[d]=Et(e,16+2*d)}process(e,s,n=!1){const r=n?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],d=o[3],u=o[4],h=o[5],p=o[6],g=o[7],f=o[8],w=o[9],v=Et(e,s+0),N=Et(e,s+2),A=Et(e,s+4),_=Et(e,s+6),P=Et(e,s+8),U=Et(e,s+10),L=Et(e,s+12),W=Et(e,s+14);let k=i[0]+(v&8191),q=i[1]+((v>>>13|N<<3)&8191),V=i[2]+((N>>>10|A<<6)&8191),x=i[3]+((A>>>7|_<<9)&8191),I=i[4]+((_>>>4|P<<12)&8191),T=i[5]+(P>>>1&8191),y=i[6]+((P>>>14|U<<2)&8191),b=i[7]+((U>>>11|L<<5)&8191),S=i[8]+((L>>>8|W<<8)&8191),R=i[9]+(W>>>5|r),C=0,O=C+k*a+q*(5*w)+V*(5*f)+x*(5*g)+I*(5*p);C=O>>>13,O&=8191,O+=T*(5*h)+y*(5*u)+b*(5*d)+S*(5*l)+R*(5*c),C+=O>>>13,O&=8191;let B=C+k*c+q*a+V*(5*w)+x*(5*f)+I*(5*g);C=B>>>13,B&=8191,B+=T*(5*p)+y*(5*h)+b*(5*u)+S*(5*d)+R*(5*l),C+=B>>>13,B&=8191;let M=C+k*l+q*c+V*a+x*(5*w)+I*(5*f);C=M>>>13,M&=8191,M+=T*(5*g)+y*(5*p)+b*(5*h)+S*(5*u)+R*(5*d),C+=M>>>13,M&=8191;let ce=C+k*d+q*l+V*c+x*a+I*(5*w);C=ce>>>13,ce&=8191,ce+=T*(5*f)+y*(5*g)+b*(5*p)+S*(5*h)+R*(5*u),C+=ce>>>13,ce&=8191;let j=C+k*u+q*d+V*l+x*c+I*a;C=j>>>13,j&=8191,j+=T*(5*w)+y*(5*f)+b*(5*g)+S*(5*p)+R*(5*h),C+=j>>>13,j&=8191;let J=C+k*h+q*u+V*d+x*l+I*c;C=J>>>13,J&=8191,J+=T*a+y*(5*w)+b*(5*f)+S*(5*g)+R*(5*p),C+=J>>>13,J&=8191;let he=C+k*p+q*h+V*u+x*d+I*l;C=he>>>13,he&=8191,he+=T*c+y*a+b*(5*w)+S*(5*f)+R*(5*g),C+=he>>>13,he&=8191;let ge=C+k*g+q*p+V*h+x*u+I*d;C=ge>>>13,ge&=8191,ge+=T*l+y*c+b*a+S*(5*w)+R*(5*f),C+=ge>>>13,ge&=8191;let xe=C+k*f+q*g+V*p+x*h+I*u;C=xe>>>13,xe&=8191,xe+=T*d+y*l+b*c+S*a+R*(5*w),C+=xe>>>13,xe&=8191;let ye=C+k*w+q*f+V*g+x*p+I*h;C=ye>>>13,ye&=8191,ye+=T*u+y*d+b*l+S*c+R*a,C+=ye>>>13,ye&=8191,C=(C<<2)+C|0,C=C+O|0,O=C&8191,C=C>>>13,B+=C,i[0]=O,i[1]=B,i[2]=M,i[3]=ce,i[4]=j,i[5]=J,i[6]=he,i[7]=ge,i[8]=xe,i[9]=ye}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;mi(n)}update(e){Uh(this),e=pd(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(){mi(this.h,this.r,this.buffer,this.pad)}digestInto(e){Uh(this),GA(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 uS(t){const e=(n,r)=>t(r).update(pd(n)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=n=>t(n),e}const hS=uS(t=>new dS(t));function pS(t,e,s,n,r,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],d=e[0],u=e[1],h=e[2],p=e[3],g=e[4],f=e[5],w=e[6],v=e[7],N=r,A=s[0],_=s[1],P=s[2],U=o,L=a,W=c,k=l,q=d,V=u,x=h,I=p,T=g,y=f,b=w,S=v,R=N,C=A,O=_,B=P;for(let ce=0;ce<i;ce+=2)U=U+q|0,R=De(R^U,16),T=T+R|0,q=De(q^T,12),U=U+q|0,R=De(R^U,8),T=T+R|0,q=De(q^T,7),L=L+V|0,C=De(C^L,16),y=y+C|0,V=De(V^y,12),L=L+V|0,C=De(C^L,8),y=y+C|0,V=De(V^y,7),W=W+x|0,O=De(O^W,16),b=b+O|0,x=De(x^b,12),W=W+x|0,O=De(O^W,8),b=b+O|0,x=De(x^b,7),k=k+I|0,B=De(B^k,16),S=S+B|0,I=De(I^S,12),k=k+I|0,B=De(B^k,8),S=S+B|0,I=De(I^S,7),U=U+V|0,B=De(B^U,16),b=b+B|0,V=De(V^b,12),U=U+V|0,B=De(B^U,8),b=b+B|0,V=De(V^b,7),L=L+x|0,R=De(R^L,16),S=S+R|0,x=De(x^S,12),L=L+x|0,R=De(R^L,8),S=S+R|0,x=De(x^S,7),W=W+I|0,C=De(C^W,16),T=T+C|0,I=De(I^T,12),W=W+I|0,C=De(C^W,8),T=T+C|0,I=De(I^T,7),k=k+q|0,O=De(O^k,16),y=y+O|0,q=De(q^y,12),k=k+q|0,O=De(O^k,8),y=y+O|0,q=De(q^y,7);let M=0;n[M++]=o+U|0,n[M++]=a+L|0,n[M++]=c+W|0,n[M++]=l+k|0,n[M++]=d+q|0,n[M++]=u+V|0,n[M++]=h+x|0,n[M++]=p+I|0,n[M++]=g+T|0,n[M++]=f+y|0,n[M++]=w+b|0,n[M++]=v+S|0,n[M++]=N+R|0,n[M++]=A+C|0,n[M++]=_+O|0,n[M++]=P+B|0}const fS=lS(pS,{counterRight:!1,counterLength:4,allowShortKeys:!1}),gS=new Uint8Array(16),Mh=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(gS.subarray(s))},mS=new Uint8Array(32);function Bh(t,e,s,n,r){const i=t(e,s,mS),o=hS.create(i);r&&Mh(o,r),Mh(o,n);const a=tS(n.length,r?r.length:0,!0);o.update(a);const c=o.digest();return mi(i,a),c}const yS=t=>(e,s,n)=>({encrypt(r,i){const o=r.length;i=$h(o+16,i,!1),i.set(r);const a=i.subarray(0,-16);t(e,s,a,a,1);const c=Bh(t,e,s,a,n);return i.set(c,o),mi(c),i},decrypt(r,i){i=$h(r.length-16,i,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=Bh(t,e,s,o,n);if(!QA(a,c))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),t(e,s,i,i,1),mi(c),i}}),Zg=eS({blockSize:64,nonceLength:12,tagLength:16},yS(fS));let Jg=class extends Uc{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,kc(e);const n=Ms(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),Ss(i)}update(e){return sr(this),this.iHash.update(e),this}digestInto(e){sr(this),js(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 Lc=(t,e,s)=>new Jg(t,e).update(s).digest();Lc.create=(t,e)=>new Jg(t,e);function wS(t,e,s){return kc(t),s===void 0&&(s=new Uint8Array(t.outputLen)),Lc(t,Ms(s),Ms(e))}const gl=Uint8Array.from([0]),jh=Uint8Array.of();function ES(t,e,s,n=32){kc(t),Tn(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=jh);const o=new Uint8Array(i*r),a=Lc.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)gl[0]=d+1,c.update(d===0?jh:l).update(s).update(gl).digestInto(l),o.set(l,r*d),a._cloneInto(c);return a.destroy(),c.destroy(),Ss(l,gl),o.slice(0,n)}const bS=(t,e,s,n,r)=>ES(t,wS(t,e,s),n,r),Mc=$c,cu=BigInt(0),md=BigInt(1);function mc(t,e=""){if(typeof t!="boolean"){const s=e&&`"${e}"`;throw new Error(s+"expected boolean, got type="+typeof t)}return t}function Er(t,e,s=""){const n=xc(t),r=t==null?void 0: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 Aa(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Xg(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?cu:BigInt("0x"+t)}function Bc(t){return Xg(ci(t))}function yc(t){return js(t),Xg(ci(Uint8Array.from(t).reverse()))}function lu(t,e){return fc(t.toString(16).padStart(e*2,"0"))}function du(t,e){return lu(t,e).reverse()}function xt(t,e,s){let n;if(typeof e=="string")try{n=fc(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(xc(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 ml=t=>typeof t=="bigint"&&cu<=t;function vS(t,e,s){return ml(t)&&ml(e)&&ml(s)&&e<=t&&t<s}function yd(t,e,s,n){if(!vS(e,s,n))throw new Error("expected valid "+t+": "+s+" <= n < "+n+", got "+e)}function Qg(t){let e;for(e=0;t>cu;t>>=md,e+=1);return e}const aa=t=>(md<<BigInt(t))-md;function CS(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),d=(h=n(0))=>{o=l(r(0),h),i=l(),h.length!==0&&(o=l(r(1),h),i=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const p=[];for(;h<e;){i=l();const g=i.slice();p.push(g),h+=i.length}return Wn(...p)};return(h,p)=>{c(),d(h);let g;for(;!(g=p(u()));)d();return c(),g}}function jc(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 Fh(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 Xt=BigInt(0),Bt=BigInt(1),br=BigInt(2),em=BigInt(3),tm=BigInt(4),sm=BigInt(5),_S=BigInt(7),nm=BigInt(8),AS=BigInt(9),rm=BigInt(16);function cs(t,e){const s=t%e;return s>=Xt?s:e+s}function Ps(t,e,s){let n=t;for(;e-- >Xt;)n*=n,n%=s;return n}function qh(t,e){if(t===Xt)throw new Error("invert: expected non-zero number");if(e<=Xt)throw new Error("invert: expected positive modulus, got "+e);let s=cs(t,e),n=e,r=Xt,i=Bt;for(;s!==Xt;){const o=n/s,a=n%s,c=r-i*o;n=s,s=a,r=i,i=c}if(n!==Bt)throw new Error("invert: does not exist");return cs(r,e)}function uu(t,e,s){if(!t.eql(t.sqr(e),s))throw new Error("Cannot find square root")}function im(t,e){const s=(t.ORDER+Bt)/tm,n=t.pow(e,s);return uu(t,n,e),n}function SS(t,e){const s=(t.ORDER-sm)/nm,n=t.mul(e,br),r=t.pow(n,s),i=t.mul(e,r),o=t.mul(t.mul(i,br),r),a=t.mul(i,t.sub(o,t.ONE));return uu(t,a,e),a}function IS(t){const e=rr(t),s=om(t),n=s(e,e.neg(e.ONE)),r=s(e,n),i=s(e,e.neg(n)),o=(t+_S)/rm;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,n);const u=a.mul(l,r),h=a.mul(l,i),p=a.eql(a.sqr(d),c),g=a.eql(a.sqr(u),c);l=a.cmov(l,d,p),d=a.cmov(h,u,g);const f=a.eql(a.sqr(d),c),w=a.cmov(l,d,f);return uu(a,w,c),w}}function om(t){if(t<em)throw new Error("sqrt is not defined for small field");let e=t-Bt,s=0;for(;e%br===Xt;)e/=br,s++;let n=br;const r=rr(t);for(;Wh(r,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return im;let i=r.pow(n,e);const o=(e+Bt)/br;return function(a,c){if(a.is0(c))return c;if(Wh(a,c)!==1)throw new Error("Cannot find square root");let l=s,d=a.mul(a.ONE,i),u=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(u,a.ONE);){if(a.is0(u))return a.ZERO;let p=1,g=a.sqr(u);for(;!a.eql(g,a.ONE);)if(p++,g=a.sqr(g),p===l)throw new Error("Cannot find square root");const f=Bt<<BigInt(l-p-1),w=a.pow(d,f);l=p,d=a.sqr(w),u=a.mul(u,d),h=a.mul(h,w)}return h}}function NS(t){return t%tm===em?im:t%nm===sm?SS:t%rm===AS?IS(t):om(t)}const TS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function RS(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},s=TS.reduce((n,r)=>(n[r]="function",n),e);return jc(t,s),t}function OS(t,e,s){if(s<Xt)throw new Error("invalid exponent, negatives unsupported");if(s===Xt)return t.ONE;if(s===Bt)return e;let n=t.ONE,r=e;for(;s>Xt;)s&Bt&&(n=t.mul(n,r)),r=t.sqr(r),s>>=Bt;return n}function am(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 Wh(t,e){const s=(t.ORDER-Bt)/br,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 cm(t,e){e!==void 0&&Tn(e);const s=e!==void 0?e:t.toString(2).length,n=Math.ceil(s/8);return{nBitLength:s,nByteLength:n}}function rr(t,e,s=!1,n={}){if(t<=Xt)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}=cm(t,r);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:t,isLE:s,BITS:c,BYTES:l,MASK:aa(c),ZERO:Xt,ONE:Bt,allowedLengths:a,create:h=>cs(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Xt<=h&&h<t},is0:h=>h===Xt,isValidNot0:h=>!u.is0(h)&&u.isValid(h),isOdd:h=>(h&Bt)===Bt,neg:h=>cs(-h,t),eql:(h,p)=>h===p,sqr:h=>cs(h*h,t),add:(h,p)=>cs(h+p,t),sub:(h,p)=>cs(h-p,t),mul:(h,p)=>cs(h*p,t),pow:(h,p)=>OS(u,h,p),div:(h,p)=>cs(h*qh(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>qh(h,t),sqrt:i||(h=>(d||(d=NS(t)),d(u,h))),toBytes:h=>s?du(h,l):lu(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 f=new Uint8Array(l);f.set(h,s?0:f.length-h.length),h=f}if(h.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+h.length);let g=s?yc(h):Bc(h);if(o&&(g=cs(g,t)),!p&&!u.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>am(u,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(u)}function lm(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 dm(t){const e=lm(t);return e+Math.ceil(e/2)}function PS(t,e,s=!1){const n=t.length,r=lm(e),i=dm(e);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);const o=s?yc(t):Bc(t),a=cs(o,e-Bt)+Bt;return s?du(a,r):lu(a,r)}const yi=BigInt(0),vr=BigInt(1);function wc(t,e){const s=e.negate();return t?s:e}function yl(t,e){const s=am(t.Fp,e.map(n=>n.Z));return e.map((n,r)=>t.fromAffine(n.toAffine(s[r])))}function um(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function wl(t,e){um(t,e);const s=Math.ceil(e/t)+1,n=2**(t-1),r=2**t,i=aa(t),o=BigInt(t);return{windows:s,windowSize:n,mask:i,maxNumber:r,shiftBy:o}}function Hh(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+=vr);const l=e*n,d=l+Math.abs(a)-1,u=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:h,isNegF:p,offsetF:l}}function xS(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 kS(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 El=new WeakMap,hm=new WeakMap;function bl(t){return hm.get(t)||1}function zh(t){if(t!==yi)throw new Error("invalid wNAF")}class US{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>yi;)s&vr&&(n=n.add(r)),r=r.double(),s>>=vr;return n}precomputeWindow(e,s){const{windows:n,windowSize:r}=wl(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=wl(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:h,offsetF:p}=Hh(n,a,o);n=c,d?i=i.add(wc(h,s[p])):r=r.add(wc(u,s[l]))}return zh(n),{p:r,f:i}}wNAFUnsafe(e,s,n,r=this.ZERO){const i=wl(e,this.bits);for(let o=0;o<i.windows&&n!==yi;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Hh(n,o,i);if(n=a,!l){const u=s[c];r=r.add(d?u.negate():u)}}return zh(n),r}getPrecomputes(e,s,n){let r=El.get(s);return r||(r=this.precomputeWindow(s,e),e!==1&&(typeof n=="function"&&(r=n(r)),El.set(s,r))),r}cached(e,s,n){const r=bl(e);return this.wNAF(r,this.getPrecomputes(r,e,n),s)}unsafe(e,s,n,r){const i=bl(e);return i===1?this._unsafeLadder(e,s,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),s,r)}createCache(e,s){um(s,this.bits),hm.set(e,s),El.delete(e)}hasCache(e){return bl(e)!==1}}function $S(t,e,s,n){let r=e,i=t.ZERO,o=t.ZERO;for(;s>yi||n>yi;)s&vr&&(i=i.add(r)),n&vr&&(o=o.add(r)),r=r.double(),s>>=vr,n>>=vr;return{p1:i,p2:o}}function DS(t,e,s,n){xS(s,t),kS(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=Qg(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=aa(c),d=new Array(Number(l)+1).fill(o),u=Math.floor((e.BITS-1)/c)*c;let h=o;for(let p=u;p>=0;p-=c){d.fill(o);for(let f=0;f<i;f++){const w=n[f],v=Number(w>>BigInt(p)&l);d[v]=d[v].add(s[f])}let g=o;for(let f=d.length-1,w=o;f>0;f--)w=w.add(d[f]),g=g.add(w);if(h=h.add(g),p!==0)for(let f=0;f<c;f++)h=h.double()}return h}function Vh(t,e,s){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return RS(e),e}else return rr(t,{isLE:s})}function LS(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>yi))throw new Error(`CURVE.${a} must be positive bigint`)}const r=Vh(e.p,s.Fp,n),i=Vh(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),$g("HashToScalar-");const Ui=BigInt(0),Kr=BigInt(1),Sa=BigInt(2);function MS(t){return jc(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function BS(t){const e=MS(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||qr,l=a?255:448,d=a?32:56,u=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?Sa**BigInt(254):Sa**BigInt(447),g=a?BigInt(8)*Sa**BigInt(251)-Kr:BigInt(4)*Sa**BigInt(445)-Kr,f=p+g+Kr,w=x=>cs(x,s),v=N(u);function N(x){return du(w(x),d)}function A(x){const I=xt("u coordinate",x,d);return a&&(I[31]&=127),w(yc(I))}function _(x){return yc(r(xt("scalar",x,d)))}function P(x,I){const T=W(A(I),_(x));if(T===Ui)throw new Error("invalid private or public key received");return N(T)}function U(x){return P(x,v)}function L(x,I,T){const y=w(x*(I-T));return I=w(I-y),T=w(T+y),{x_2:I,x_3:T}}function W(x,I){yd("u",x,Ui,s),yd("scalar",I,p,f);const T=I,y=x;let b=Kr,S=Ui,R=x,C=Kr,O=Ui;for(let M=BigInt(l-1);M>=Ui;M--){const ce=T>>M&Kr;O^=ce,{x_2:b,x_3:R}=L(O,b,R),{x_2:S,x_3:C}=L(O,S,C),O=ce;const j=b+S,J=w(j*j),he=b-S,ge=w(he*he),xe=J-ge,ye=R+C,ve=R-C,Ve=w(ve*j),st=w(ye*he),ut=Ve+st,wt=Ve-st;R=w(ut*ut),C=w(y*w(wt*wt)),b=w(J*ge),S=w(xe*(J+w(h*xe)))}({x_2:b,x_3:R}=L(O,b,R)),{x_2:S,x_3:C}=L(O,S,C);const B=i(S);return w(b*B)}const k={secretKey:d,publicKey:d,seed:d},q=(x=c(d))=>(js(x,k.seed),x);function V(x){const I=q(x);return{secretKey:I,publicKey:U(I)}}return{keygen:V,getSharedSecret:(x,I)=>P(x,I),getPublicKey:x=>U(x),scalarMult:P,scalarMultBase:U,utils:{randomSecretKey:q,randomPrivateKey:q},GuBytes:v.slice(),lengths:k}}const jS=BigInt(1),Kh=BigInt(2),FS=BigInt(3),qS=BigInt(5);BigInt(8);const pm=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),WS={p:pm,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function HS(t){const e=BigInt(10),s=BigInt(20),n=BigInt(40),r=BigInt(80),i=pm,o=t*t%i*t%i,a=Ps(o,Kh,i)*o%i,c=Ps(a,jS,i)*t%i,l=Ps(c,qS,i)*c%i,d=Ps(l,e,i)*l%i,u=Ps(d,s,i)*d%i,h=Ps(u,n,i)*u%i,p=Ps(h,r,i)*h%i,g=Ps(p,r,i)*h%i,f=Ps(g,e,i)*l%i;return{pow_p_5_8:Ps(f,Kh,i)*t%i,b2:o}}function zS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const VS=rr(WS.p,{isLE:!0}),wd=(()=>{const t=VS.ORDER;return BS({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:s,b2:n}=HS(e);return cs(Ps(s,FS,t)*n,t)},adjustScalarBytes:zS})})(),Gh=(t,e)=>(t+(t>=0?e:-e)/fm)/e;function KS(t,e,s){const[[n,r],[i,o]]=e,a=Gh(o*t,s),c=Gh(-r*t,s);let l=t-a*n-c*i,d=-a*r-c*o;const u=l<bn,h=d<bn;u&&(l=-l),h&&(d=-d);const p=aa(Math.ceil(Qg(s)/2))+li;if(l<bn||l>=p||d<bn||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:u,k1:l,k2neg:h,k2:d}}function Ed(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function vl(t,e){const s={};for(let n of Object.keys(e))s[n]=t[n]===void 0?e[n]:t[n];return mc(s.lowS,"lowS"),mc(s.prehash,"prehash"),s.format!==void 0&&Ed(s.format),s}class GS extends Error{constructor(e=""){super(e)}}const yn={Err:GS,_tlv:{encode:(t,e)=>{const{Err:s}=yn;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=Aa(n);if(r.length/2&128)throw new s("tlv.encode: long form length too big");const i=n>127?Aa(r.length/2|128):"";return Aa(t)+i+r+e},decode(t,e){const{Err:s}=yn;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 d of l)o=o<<8|d;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}=yn;if(t<bn)throw new e("integer: negative integers are not allowed");let s=Aa(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}=yn;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 Bc(t)}},toSig(t){const{Err:e,_int:s,_tlv:n}=yn,r=xt("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:d}=n.decode(2,c);if(d.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}=yn,n=e.encode(2,s.encode(t.r)),r=e.encode(2,s.encode(t.s)),i=n+r;return e.encode(48,i)}},bn=BigInt(0),li=BigInt(1),fm=BigInt(2),Ia=BigInt(3),YS=BigInt(4);function si(t,e){const{BYTES:s}=t;let n;if(typeof e=="bigint")n=e;else{let r=xt("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 ZS(t,e={}){const s=LS("weierstrass",t,e),{Fp:n,Fn:r}=s;let i=s.CURVE;const{h:o,n:a}=i;jc(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=mm(n,r);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(x,I,T){const{x:y,y:b}=I.toAffine(),S=n.toBytes(y);if(mc(T,"isCompressed"),T){d();const R=!n.isOdd(b);return Wn(gm(R),S)}else return Wn(Uint8Array.of(4),S,n.toBytes(b))}function h(x){Er(x,void 0,"Point");const{publicKey:I,publicKeyUncompressed:T}=l,y=x.length,b=x[0],S=x.subarray(1);if(y===I&&(b===2||b===3)){const R=n.fromBytes(S);if(!n.isValid(R))throw new Error("bad point: is not on curve, wrong x");const C=f(R);let O;try{O=n.sqrt(C)}catch(M){const ce=M instanceof Error?": "+M.message:"";throw new Error("bad point: is not on curve, sqrt error"+ce)}d();const B=n.isOdd(O);return(b&1)===1!==B&&(O=n.neg(O)),{x:R,y:O}}else if(y===T&&b===4){const R=n.BYTES,C=n.fromBytes(S.subarray(0,R)),O=n.fromBytes(S.subarray(R,R*2));if(!w(C,O))throw new Error("bad point: is not on curve");return{x:C,y:O}}else throw new Error(`bad point: got length ${y}, expected compressed=${I} or uncompressed=${T}`)}const p=e.toBytes||u,g=e.fromBytes||h;function f(x){const I=n.sqr(x),T=n.mul(I,x);return n.add(n.add(T,n.mul(x,i.a)),i.b)}function w(x,I){const T=n.sqr(I),y=f(x);return n.eql(T,y)}if(!w(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const v=n.mul(n.pow(i.a,Ia),YS),N=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(v,N)))throw new Error("bad curve params: a or b");function A(x,I,T=!1){if(!n.isValid(I)||T&&n.is0(I))throw new Error(`bad point coordinate ${x}`);return I}function _(x){if(!(x instanceof k))throw new Error("ProjectivePoint expected")}function P(x){if(!c||!c.basises)throw new Error("no endo");return KS(x,c.basises,r.ORDER)}const U=Fh((x,I)=>{const{X:T,Y:y,Z:b}=x;if(n.eql(b,n.ONE))return{x:T,y};const S=x.is0();I==null&&(I=S?n.ONE:n.inv(b));const R=n.mul(T,I),C=n.mul(y,I),O=n.mul(b,I);if(S)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:R,y:C}}),L=Fh(x=>{if(x.is0()){if(e.allowInfinityPoint&&!n.is0(x.Y))return;throw new Error("bad point: ZERO")}const{x:I,y:T}=x.toAffine();if(!n.isValid(I)||!n.isValid(T))throw new Error("bad point: x or y not field elements");if(!w(I,T))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function W(x,I,T,y,b){return T=new k(n.mul(T.X,x),T.Y,T.Z),I=wc(y,I),T=wc(b,T),I.add(T)}class k{constructor(I,T,y){this.X=A("x",I),this.Y=A("y",T,!0),this.Z=A("z",y),Object.freeze(this)}static CURVE(){return i}static fromAffine(I){const{x:T,y}=I||{};if(!I||!n.isValid(T)||!n.isValid(y))throw new Error("invalid affine point");if(I instanceof k)throw new Error("projective point not allowed");return n.is0(T)&&n.is0(y)?k.ZERO:new k(T,y,n.ONE)}static fromBytes(I){const T=k.fromAffine(g(Er(I,void 0,"point")));return T.assertValidity(),T}static fromHex(I){return k.fromBytes(xt("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,T=!0){return V.createCache(this,I),T||this.multiply(Ia),this}assertValidity(){L(this)}hasEvenY(){const{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){_(I);const{X:T,Y:y,Z:b}=this,{X:S,Y:R,Z:C}=I,O=n.eql(n.mul(T,C),n.mul(S,b)),B=n.eql(n.mul(y,C),n.mul(R,b));return O&&B}negate(){return new k(this.X,n.neg(this.Y),this.Z)}double(){const{a:I,b:T}=i,y=n.mul(T,Ia),{X:b,Y:S,Z:R}=this;let C=n.ZERO,O=n.ZERO,B=n.ZERO,M=n.mul(b,b),ce=n.mul(S,S),j=n.mul(R,R),J=n.mul(b,S);return J=n.add(J,J),B=n.mul(b,R),B=n.add(B,B),C=n.mul(I,B),O=n.mul(y,j),O=n.add(C,O),C=n.sub(ce,O),O=n.add(ce,O),O=n.mul(C,O),C=n.mul(J,C),B=n.mul(y,B),j=n.mul(I,j),J=n.sub(M,j),J=n.mul(I,J),J=n.add(J,B),B=n.add(M,M),M=n.add(B,M),M=n.add(M,j),M=n.mul(M,J),O=n.add(O,M),j=n.mul(S,R),j=n.add(j,j),M=n.mul(j,J),C=n.sub(C,M),B=n.mul(j,ce),B=n.add(B,B),B=n.add(B,B),new k(C,O,B)}add(I){_(I);const{X:T,Y:y,Z:b}=this,{X:S,Y:R,Z:C}=I;let O=n.ZERO,B=n.ZERO,M=n.ZERO;const ce=i.a,j=n.mul(i.b,Ia);let J=n.mul(T,S),he=n.mul(y,R),ge=n.mul(b,C),xe=n.add(T,y),ye=n.add(S,R);xe=n.mul(xe,ye),ye=n.add(J,he),xe=n.sub(xe,ye),ye=n.add(T,b);let ve=n.add(S,C);return ye=n.mul(ye,ve),ve=n.add(J,ge),ye=n.sub(ye,ve),ve=n.add(y,b),O=n.add(R,C),ve=n.mul(ve,O),O=n.add(he,ge),ve=n.sub(ve,O),M=n.mul(ce,ye),O=n.mul(j,ge),M=n.add(O,M),O=n.sub(he,M),M=n.add(he,M),B=n.mul(O,M),he=n.add(J,J),he=n.add(he,J),ge=n.mul(ce,ge),ye=n.mul(j,ye),he=n.add(he,ge),ge=n.sub(J,ge),ge=n.mul(ce,ge),ye=n.add(ye,ge),J=n.mul(he,ye),B=n.add(B,J),J=n.mul(ve,ye),O=n.mul(xe,O),O=n.sub(O,J),J=n.mul(xe,he),M=n.mul(ve,M),M=n.add(M,J),new k(O,B,M)}subtract(I){return this.add(I.negate())}is0(){return this.equals(k.ZERO)}multiply(I){const{endo:T}=e;if(!r.isValidNot0(I))throw new Error("invalid scalar: out of range");let y,b;const S=R=>V.cached(this,R,C=>yl(k,C));if(T){const{k1neg:R,k1:C,k2neg:O,k2:B}=P(I),{p:M,f:ce}=S(C),{p:j,f:J}=S(B);b=ce.add(J),y=W(T.beta,M,j,R,O)}else{const{p:R,f:C}=S(I);y=R,b=C}return yl(k,[y,b])[0]}multiplyUnsafe(I){const{endo:T}=e,y=this;if(!r.isValid(I))throw new Error("invalid scalar: out of range");if(I===bn||y.is0())return k.ZERO;if(I===li)return y;if(V.hasCache(this))return this.multiply(I);if(T){const{k1neg:b,k1:S,k2neg:R,k2:C}=P(I),{p1:O,p2:B}=$S(k,y,S,C);return W(T.beta,O,B,b,R)}else return V.unsafe(y,I)}multiplyAndAddUnsafe(I,T,y){const b=this.multiplyUnsafe(T).add(I.multiplyUnsafe(y));return b.is0()?void 0:b}toAffine(I){return U(this,I)}isTorsionFree(){const{isTorsionFree:I}=e;return o===li?!0:I?I(k,this):V.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:I}=e;return o===li?this:I?I(k,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(I=!0){return mc(I,"isCompressed"),this.assertValidity(),p(k,this,I)}toHex(I=!0){return ci(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 yl(k,I)}static msm(I,T){return DS(k,r,I,T)}static fromPrivateKey(I){return k.BASE.multiply(si(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 q=r.BITS,V=new US(k,e.endo?Math.ceil(q/2):q);return k.BASE.precompute(8),k}function gm(t){return Uint8Array.of(t?2:3)}function mm(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function JS(t,e={}){const{Fn:s}=t,n=e.randomBytes||qr,r=Object.assign(mm(t.Fp,s),{seed:dm(s.ORDER)});function i(h){try{return!!si(s,h)}catch{return!1}}function o(h,p){const{publicKey:g,publicKeyUncompressed:f}=r;try{const w=h.length;return p===!0&&w!==g||p===!1&&w!==f?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(r.seed)){return PS(Er(h,r.seed,"seed"),s.ORDER)}function c(h,p=!0){return t.BASE.multiply(si(s,h)).toBytes(p)}function l(h){const p=a(h);return{secretKey:p,publicKey:c(p)}}function d(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:p,publicKey:g,publicKeyUncompressed:f}=r;if(s.allowedLengths||p===g)return;const w=xt("key",h).length;return w===g||w===f}function u(h,p,g=!0){if(d(h)===!0)throw new Error("first arg must be private key");if(d(p)===!1)throw new Error("second arg must be public key");const f=si(s,h);return t.fromHex(p).multiply(f).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:h=>si(s,h),precompute(h=8,p=t.BASE){return p.precompute(h,!1)}},lengths:r})}function XS(t,e,s={}){kc(e),jc(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=s.randomBytes||qr,r=s.hmac||((T,...y)=>Lc(e,T,Wn(...y))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p}=JS(t,s),g={prehash:!1,lowS:typeof s.lowS=="boolean"?s.lowS:!1,format:void 0,extraEntropy:!1},f="compact";function w(T){const y=a>>li;return T>y}function v(T,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${T}: out of range 1..Point.Fn.ORDER`);return y}function N(T,y){Ed(y);const b=p.signature,S=y==="compact"?b:y==="recovered"?b+1:void 0;return Er(T,S,`${y} signature`)}class A{constructor(y,b,S){this.r=v("r",y),this.s=v("s",b),S!=null&&(this.recovery=S),Object.freeze(this)}static fromBytes(y,b=f){N(y,b);let S;if(b==="der"){const{r:B,s:M}=yn.toSig(Er(y));return new A(B,M)}b==="recovered"&&(S=y[0],b="compact",y=y.subarray(1));const R=o.BYTES,C=y.subarray(0,R),O=y.subarray(R,R*2);return new A(o.fromBytes(C),o.fromBytes(O),S)}static fromHex(y,b){return this.fromBytes(fc(y),b)}addRecoveryBit(y){return new A(this.r,this.s,y)}recoverPublicKey(y){const b=i.ORDER,{r:S,s:R,recovery:C}=this;if(C==null||![0,1,2,3].includes(C))throw new Error("recovery id invalid");if(a*fm<b&&C>1)throw new Error("recovery id is ambiguous for h>1 curve");const O=C===2||C===3?S+a:S;if(!i.isValid(O))throw new Error("recovery id 2 or 3 invalid");const B=i.toBytes(O),M=t.fromBytes(Wn(gm((C&1)===0),B)),ce=o.inv(O),j=P(xt("msgHash",y)),J=o.create(-j*ce),he=o.create(R*ce),ge=t.BASE.multiplyUnsafe(J).add(M.multiplyUnsafe(he));if(ge.is0())throw new Error("point at infinify");return ge.assertValidity(),ge}hasHighS(){return w(this.s)}toBytes(y=f){if(Ed(y),y==="der")return fc(yn.hexFromSig(this));const b=o.toBytes(this.r),S=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Wn(Uint8Array.of(this.recovery),b,S)}return Wn(b,S)}toHex(y){return ci(this.toBytes(y))}assertValidity(){}static fromCompact(y){return A.fromBytes(xt("sig",y),"compact")}static fromDER(y){return A.fromBytes(xt("sig",y),"der")}normalizeS(){return this.hasHighS()?new A(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return ci(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ci(this.toBytes("compact"))}}const _=s.bits2int||function(T){if(T.length>8192)throw new Error("input is too large");const y=Bc(T),b=T.length*8-c;return b>0?y>>BigInt(b):y},P=s.bits2int_modN||function(T){return o.create(_(T))},U=aa(c);function L(T){return yd("num < 2^"+c,T,bn,U),o.toBytes(T)}function W(T,y){return Er(T,void 0,"message"),y?Er(e(T),void 0,"prehashed message"):T}function k(T,y,b){if(["recovered","canonical"].some(he=>he in b))throw new Error("sign() legacy options not supported");const{lowS:S,prehash:R,extraEntropy:C}=vl(b,g);T=W(T,R);const O=P(T),B=si(o,y),M=[L(B),L(O)];if(C!=null&&C!==!1){const he=C===!0?n(p.secretKey):C;M.push(xt("extraEntropy",he))}const ce=Wn(...M),j=O;function J(he){const ge=_(he);if(!o.isValidNot0(ge))return;const xe=o.inv(ge),ye=t.BASE.multiply(ge).toAffine(),ve=o.create(ye.x);if(ve===bn)return;const Ve=o.create(xe*o.create(j+ve*B));if(Ve===bn)return;let st=(ye.x===ve?0:2)|Number(ye.y&li),ut=Ve;return S&&w(Ve)&&(ut=o.neg(Ve),st^=1),new A(ve,ut,st)}return{seed:ce,k2sig:J}}function q(T,y,b={}){T=xt("message",T);const{seed:S,k2sig:R}=k(T,y,b);return CS(e.outputLen,o.BYTES,r)(S,R)}function V(T){let y;const b=typeof T=="string"||xc(T),S=!b&&T!==null&&typeof T=="object"&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!b&&!S)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(S)y=new A(T.r,T.s);else if(b){try{y=A.fromBytes(xt("sig",T),"der")}catch(R){if(!(R instanceof yn.Err))throw R}if(!y)try{y=A.fromBytes(xt("sig",T),"compact")}catch{return!1}}return y||!1}function x(T,y,b,S={}){const{lowS:R,prehash:C,format:O}=vl(S,g);if(b=xt("publicKey",b),y=W(xt("message",y),C),"strict"in S)throw new Error("options.strict was renamed to lowS");const B=O===void 0?V(T):A.fromBytes(xt("sig",T),O);if(B===!1)return!1;try{const M=t.fromBytes(b);if(R&&B.hasHighS())return!1;const{r:ce,s:j}=B,J=P(y),he=o.inv(j),ge=o.create(J*he),xe=o.create(ce*he),ye=t.BASE.multiplyUnsafe(ge).add(M.multiplyUnsafe(xe));return ye.is0()?!1:o.create(ye.x)===ce}catch{return!1}}function I(T,y,b={}){const{prehash:S}=vl(b,g);return y=W(y,S),A.fromBytes(T,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:h,lengths:p,Point:t,sign:q,verify:x,recoverPublicKey:I,Signature:A,hash:e})}function QS(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=rr(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 eI(t){const{CURVE:e,curveOpts:s}=QS(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 tI(t,e){const s=e.Point;return Object.assign({},e,{ProjectivePoint:s,CURVE:Object.assign({},t,cm(s.Fn.ORDER,s.Fn.BITS))})}function sI(t){const{CURVE:e,curveOpts:s,hash:n,ecdsaOpts:r}=eI(t),i=ZS(e,s),o=XS(i,n,r);return tI(t,o)}function bd(t,e){const s=n=>sI({...t,hash:n});return{...s(e),create:s}}const ym={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},wm={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Em={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},nI=rr(ym.p),rI=rr(wm.p),iI=rr(Em.p),oI=bd({...ym,Fp:nI,lowS:!1},$c);bd({...wm,Fp:rI,lowS:!1},uA),bd({...Em,Fp:iI,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},dA);const aI=oI,bm="base10",jt="base16",Zt="base64pad",Hn="base64url",ca="utf8",vm=0,An=1,la=2,cI=0,Yh=1,Ji=12,hu=32;function lI(){const t=wd.utils.randomPrivateKey(),e=wd.getPublicKey(t);return{privateKey:Qt(t,jt),publicKey:Qt(e,jt)}}function vd(){const t=qr(hu);return Qt(t,jt)}function dI(t,e){const s=wd.getSharedSecret(As(t,jt),As(e,jt)),n=bS(Mc,s,void 0,void 0,hu);return Qt(n,jt)}function Ha(t){const e=Mc(As(t,jt));return Qt(e,jt)}function vs(t){const e=Mc(As(t,ca));return Qt(e,jt)}function Cm(t){return As(`${t}`,bm)}function Dr(t){return Number(Qt(t,bm))}function _m(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Am(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function uI(t){const e=Cm(typeof t.type<"u"?t.type:vm);if(Dr(e)===An&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?As(t.senderPublicKey,jt):void 0,n=typeof t.iv<"u"?As(t.iv,jt):qr(Ji),r=As(t.symKey,jt),i=Zg(r,n).encrypt(As(t.message,ca)),o=Sm({type:e,sealed:i,iv:n,senderPublicKey:s});return t.encoding===Hn?_m(o):o}function hI(t){const e=As(t.symKey,jt),{sealed:s,iv:n}=To({encoded:t.encoded,encoding:t.encoding}),r=Zg(e,n).decrypt(s);if(r===null)throw new Error("Failed to decrypt");return Qt(r,ca)}function pI(t,e){const s=Cm(la),n=qr(Ji),r=As(t,ca),i=Sm({type:s,sealed:r,iv:n});return e===Hn?_m(i):i}function fI(t,e){const{sealed:s}=To({encoded:t,encoding:e});return Qt(s,ca)}function Sm(t){if(Dr(t.type)===la)return Qt(Yi([t.type,t.sealed]),Zt);if(Dr(t.type)===An){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Qt(Yi([t.type,t.senderPublicKey,t.iv,t.sealed]),Zt)}return Qt(Yi([t.type,t.iv,t.sealed]),Zt)}function To(t){const e=(t.encoding||Zt)===Hn?Am(t.encoded):t.encoded,s=As(e,Zt),n=s.slice(cI,Yh),r=Yh;if(Dr(n)===An){const c=r+hu,l=c+Ji,d=s.slice(r,c),u=s.slice(c,l),h=s.slice(l);return{type:n,sealed:h,iv:u,senderPublicKey:d}}if(Dr(n)===la){const c=s.slice(r),l=qr(Ji);return{type:n,sealed:c,iv:l}}const i=r+Ji,o=s.slice(r,i),a=s.slice(i);return{type:n,sealed:a,iv:o}}function gI(t,e){const s=To({encoded:t,encoding:e==null?void 0:e.encoding});return Im({type:Dr(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?Qt(s.senderPublicKey,jt):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Im(t){const e=(t==null?void 0:t.type)||vm;if(e===An){if(typeof(t==null?void 0:t.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(t==null?void 0:t.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t==null?void 0:t.senderPublicKey,receiverPublicKey:t==null?void 0:t.receiverPublicKey}}function Zh(t){return t.type===An&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Jh(t){return t.type===la}function mI(t){const e=Pe.from(t.x,"base64"),s=Pe.from(t.y,"base64");return Yi([new Uint8Array([4]),e,s])}function yI(t,e){const[s,n,r]=t.split("."),i=Pe.from(Am(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=Mc(c),d=mI(e);if(!aI.verify(Yi([o,a]),l,d))throw new Error("Invalid signature");return Wl(t).payload}const wI="irn";function Ec(t){return(t==null?void 0:t.relay)||{protocol:wI}}function ni(t){const e=jy[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var EI=Object.defineProperty,bI=Object.defineProperties,vI=Object.getOwnPropertyDescriptors,Xh=Object.getOwnPropertySymbols,CI=Object.prototype.hasOwnProperty,_I=Object.prototype.propertyIsEnumerable,Qh=(t,e,s)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Cl=(t,e)=>{for(var s in e||(e={}))CI.call(e,s)&&Qh(t,s,e[s]);if(Xh)for(var s of Xh(e))_I.call(e,s)&&Qh(t,s,e[s]);return t},AI=(t,e)=>bI(t,vI(e));function SI(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 ep(t){if(!t.includes("wc:")){const l=Rg(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:II(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:SI(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function II(t){return t.startsWith("//")?t.substring(2):t}function NI(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 tp(t){const e=new URLSearchParams,s=Cl(Cl(AI(Cl({},NI(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 Na(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var TI=Object.defineProperty,RI=Object.defineProperties,OI=Object.getOwnPropertyDescriptors,sp=Object.getOwnPropertySymbols,PI=Object.prototype.hasOwnProperty,xI=Object.prototype.propertyIsEnumerable,np=(t,e,s)=>e in t?TI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,kI=(t,e)=>{for(var s in e||(e={}))PI.call(e,s)&&np(t,s,e[s]);if(sp)for(var s of sp(e))xI.call(e,s)&&np(t,s,e[s]);return t},UI=(t,e)=>RI(t,OI(e));function Ti(t){const e=[];return t.forEach(s=>{const[n,r]=s.split(":");e.push(`${n}:${r}`)}),e}function Nm(t){const e=[];return Object.values(t).forEach(s=>{e.push(...Ti(s.accounts))}),[...new Set(e)]}function $I(t){const e=[];return Object.values(t).forEach(s=>{e.push(...s.methods)}),[...new Set(e)]}function DI(t){const e=[];return Object.values(t).forEach(s=>{e.push(...s.events)}),[...new Set(e)]}function LI(t,e){const s=[];return Object.values(t).forEach(n=>{Ti(n.accounts).includes(e)&&s.push(...n.methods)}),s}function MI(t,e){const s=[];return Object.values(t).forEach(n=>{Ti(n.accounts).includes(e)&&s.push(...n.events)}),s}function Fc(t){return t.includes(":")}function ri(t){return Fc(t)?t.split(":")[0]:t}function rp(t){var e,s,n;const r={};if(!en(t))return r;for(const[i,o]of Object.entries(t)){const a=Fc(i)?[i]:o.chains,c=o.methods||[],l=o.events||[],d=ri(i);r[d]=UI(kI({},r[d]),{chains:Qs(a,(e=r[d])==null?void 0:e.chains),methods:Qs(c,(s=r[d])==null?void 0:s.methods),events:Qs(l,(n=r[d])==null?void 0:n.events)})}return r}function BI(t){const e={};return t==null||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 ip(t,e){e=e.map(n=>n.replace("did:pkh:",""));const s=BI(e);for(const[n,r]of Object.entries(s))r.methods?r.methods=Qs(r.methods,t):r.methods=t,r.events=["chainChanged","accountsChanged"];return s}function jI(t,e){var s,n,r,i,o,a;const c=rp(t),l=rp(e),d={},u=Object.keys(c).concat(Object.keys(l));for(const h of u)d[h]={chains:Qs((s=c[h])==null?void 0:s.chains,(n=l[h])==null?void 0:n.chains),methods:Qs((r=c[h])==null?void 0:r.methods,(i=l[h])==null?void 0:i.methods),events:Qs((o=c[h])==null?void 0:o.events,(a=l[h])==null?void 0:a.events)};return d}const FI={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}},qI={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 Y(t,e){const{message:s,code:n}=qI[t];return{message:e?`${s} ${e}`:s,code:n}}function Ze(t,e){const{message:s,code:n}=FI[t];return{message:e?`${s} ${e}`:s,code:n}}function Sn(t,e){return!!Array.isArray(t)}function en(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function mt(t){return typeof t>"u"}function ot(t,e){return e&&mt(t)?!0:typeof t=="string"&&!!t.trim().length}function pu(t,e){return typeof t=="number"&&!isNaN(t)}function WI(t,e){const{requiredNamespaces:s}=e,n=Object.keys(t.namespaces),r=Object.keys(s);let i=!0;return wr(r,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],d=Ti(a),u=s[o];(!wr(Ag(o,u),d)||!wr(u.methods,c)||!wr(u.events,l))&&(i=!1)}),i):!1}function bc(t){return ot(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function HI(t){if(ot(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&bc(s)}}return!1}function zI(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(ot(t,!1)){if(e(t))return!0;const s=Rg(t);return e(s)}}catch{}return!1}function VI(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function KI(t){return t==null?void 0:t.topic}function GI(t,e){let s=null;return ot(t==null?void 0:t.publicKey,!1)||(s=Y("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function op(t){let e=!0;return Sn(t)?t.length&&(e=t.every(s=>ot(s,!1))):e=!1,e}function YI(t,e,s){let n=null;return Sn(e)&&e.length?e.forEach(r=>{n||bc(r)||(n=Ze("UNSUPPORTED_CHAINS",`${s}, chain ${r} should be a string and conform to "namespace:chainId" format`))}):bc(t)||(n=Ze("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 ZI(t,e,s){let n=null;return Object.entries(t).forEach(([r,i])=>{if(n)return;const o=YI(r,Ag(r,i),`${e} ${s}`);o&&(n=o)}),n}function JI(t,e){let s=null;return Sn(t)?t.forEach(n=>{s||HI(n)||(s=Ze("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):s=Ze("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function XI(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=JI(n==null?void 0:n.accounts,`${e} namespace`);r&&(s=r)}),s}function QI(t,e){let s=null;return op(t==null?void 0:t.methods)?op(t==null?void 0:t.events)||(s=Ze("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=Ze("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function Tm(t,e){let s=null;return Object.values(t).forEach(n=>{if(s)return;const r=QI(n,`${e}, namespace`);r&&(s=r)}),s}function eN(t,e,s){let n=null;if(t&&en(t)){const r=Tm(t,e);r&&(n=r);const i=ZI(t,e,s);i&&(n=i)}else n=Y("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return n}function _l(t,e){let s=null;if(t&&en(t)){const n=Tm(t,e);n&&(s=n);const r=XI(t,e);r&&(s=r)}else s=Y("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function Rm(t){return ot(t.protocol,!0)}function tN(t,e){let s=!1;return t?t&&Sn(t)&&t.length&&t.forEach(n=>{s=Rm(n)}):s=!0,s}function sN(t){return typeof t=="number"}function Vt(t){return typeof t<"u"&&typeof t!==null}function nN(t){return!(!t||typeof t!="object"||!t.code||!pu(t.code)||!t.message||!ot(t.message,!1))}function rN(t){return!(mt(t)||!ot(t.method,!1))}function iN(t){return!(mt(t)||mt(t.result)&&mt(t.error)||!pu(t.id)||!ot(t.jsonrpc,!1))}function oN(t){return!(mt(t)||!ot(t.name,!1))}function ap(t,e){return!(!bc(e)||!Nm(t).includes(e))}function aN(t,e,s){return ot(s,!1)?LI(t,e).includes(s):!1}function cN(t,e,s){return ot(s,!1)?MI(t,e).includes(s):!1}function cp(t,e,s){let n=null;const r=lN(t),i=dN(e),o=Object.keys(r),a=Object.keys(i),c=lp(Object.keys(t)),l=lp(Object.keys(e)),d=c.filter(u=>!l.includes(u));return d.length&&(n=Y("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
9
+ Required: ${d.toString()}
10
+ Received: ${Object.keys(e).toString()}`)),wr(o,a)||(n=Y("NON_CONFORMING_NAMESPACES",`${s} namespaces chains don't satisfy required namespaces.
11
+ Required: ${o.toString()}
12
+ Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||n)return;const h=Ti(e[u].accounts);h.includes(u)||(n=Y("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${u}
13
+ Required: ${u}
14
+ Approved: ${h.toString()}`))}),o.forEach(u=>{n||(wr(r[u].methods,i[u].methods)?wr(r[u].events,i[u].events)||(n=Y("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${u}`)):n=Y("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${u}`))}),n}function lN(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 lp(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function dN(t){const e={};return Object.keys(t).forEach(s=>{if(s.includes(":"))e[s]=t[s];else{const n=Ti(t[s].accounts);n==null||n.forEach(r=>{e[r]={accounts:t[s].accounts.filter(i=>i.includes(`${r}:`)),methods:t[s].methods,events:t[s].events}})}}),e}function uN(t,e){return pu(t)&&t<=e.max&&t>=e.min}function dp(){const t=ia();return new Promise(e=>{switch(t){case ps.browser:e(hN());break;case ps.reactNative:e(pN());break;case ps.node:e(fN());break;default:e(!0)}})}function hN(){return Ni()&&(navigator==null?void 0:navigator.onLine)}async function pN(){if(nr()&&typeof Ce<"u"&&Ce!=null&&Ce.NetInfo){const t=await(Ce==null?void 0:Ce.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function fN(){return!0}function gN(t){switch(ia()){case ps.browser:mN(t);break;case ps.reactNative:yN(t);break}}function mN(t){!nr()&&Ni()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function yN(t){var e;nr()&&typeof Ce<"u"&&Ce!=null&&Ce.NetInfo&&((e=Ce)==null||e.NetInfo.addEventListener(s=>t(s==null?void 0:s.isConnected)))}function wN(){var t;return Ni()&&In.getDocument()?((t=In.getDocument())==null?void 0:t.visibilityState)==="visible":!0}const Al={};class $i{static get(e){return Al[e]}static set(e,s){Al[e]=s}static delete(e){delete Al[e]}}function EN(t){const e=Si.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function bN({publicKey:t,signature:e,payload:s}){var n;const r=Cd(s.method),i=128|parseInt(((n=s.version)==null?void 0:n.toString())||"4"),o=_N(s.address),a=s.era==="00"?new Uint8Array([0]):Cd(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]),d=BigInt(`0x${CN(s.tip)}`),u=SN(d),h=new Uint8Array([0,...t,o,...e,...a,...l,...u,...r]),p=AN(h.length+1);return new Uint8Array([...p,i,...h])}function vN(t){const e=Cd(t),s=Hy.blake2b(e,void 0,32);return"0x"+Pe.from(s).toString("hex")}function Cd(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function CN(t){return t.startsWith("0x")?t.slice(2):t}function _N(t){const e=Si.decode(t)[0];return e===42?0:e===60?2:1}function AN(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 SN(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 IN(t){const e=Uint8Array.from(Pe.from(t.signature,"hex")),s=EN(t.transaction.address),n=bN({publicKey:s,signature:e,payload:t.transaction}),r=Pe.from(n).toString("hex");return vN(r)}function fu({logger:t,name:e}){const s=typeof t=="string"?Rc({opts:{level:t,name:e}}).logger:t;return s.level=typeof t=="string"?t:t.level,s}var NN={};const Om="wc",Pm=2,_d="core",nn=`${Om}@2:${_d}:`,TN={logger:"error"},RN={database:":memory:"},ON="crypto",up="client_ed25519_seed",PN=Z.ONE_DAY,xN="keychain",kN="0.3",UN="messages",$N="0.3",DN=Z.SIX_HOURS,LN="publisher",xm="irn",MN="error",km="wss://relay.walletconnect.org",BN="relayer",it={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"},jN="_subscription",gs={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},FN=.1,Ad="2.23.0",Ke={link_mode:"link_mode",relay:"relay"},za={inbound:"inbound",outbound:"outbound"},qN="0.3",WN="WALLETCONNECT_CLIENT_ID",hp="WALLETCONNECT_LINK_MODE_APPS",as={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},HN="subscription",zN="0.3",VN="pairing",KN="0.3",Di={wc_pairingDelete:{req:{ttl:Z.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:Z.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:Z.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:Z.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:Z.ONE_DAY,prompt:!1,tag:0},res:{ttl:Z.ONE_DAY,prompt:!1,tag:0}}},pr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ts={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},GN="history",YN="0.3",ZN="expirer",Es={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},JN="0.3",XN="verify-api",QN="https://verify.walletconnect.com",Um="https://verify.walletconnect.org",Xi=Um,e1=`${Xi}/v3`,t1=[QN,Um],s1="echo",n1="https://echo.walletconnect.com",zs={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"},hn={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"},Rs={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"},or={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"},ar={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"},Li={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"},r1=.1,i1="event-client",o1=86400,a1="https://pulse.walletconnect.org/batch";function c1(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),d=Math.log(256)/Math.log(a);function u(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var f=0,w=0,v=0,N=g.length;v!==N&&g[v]===0;)v++,f++;for(var A=(N-v)*d+1>>>0,_=new Uint8Array(A);v!==N;){for(var P=g[v],U=0,L=A-1;(P!==0||U<w)&&L!==-1;L--,U++)P+=256*_[L]>>>0,_[L]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");w=U,v++}for(var W=A-w;W!==A&&_[W]===0;)W++;for(var k=c.repeat(f);W<A;++W)k+=t.charAt(_[W]);return k}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var f=0;if(g[f]!==" "){for(var w=0,v=0;g[f]===c;)w++,f++;for(var N=(g.length-f)*l+1>>>0,A=new Uint8Array(N);g[f];){var _=s[g.charCodeAt(f)];if(_===255)return;for(var P=0,U=N-1;(_!==0||P<v)&&U!==-1;U--,P++)_+=a*A[U]>>>0,A[U]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");v=P,f++}if(g[f]!==" "){for(var L=N-v;L!==N&&A[L]===0;)L++;for(var W=new Uint8Array(w+(N-L)),k=w;L!==N;)W[k++]=A[L++];return W}}}function p(g){var f=h(g);if(f)return f;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:h,decode:p}}var l1=c1,d1=l1;const $m=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")},u1=t=>new TextEncoder().encode(t),h1=t=>new TextDecoder().decode(t);class p1{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 f1{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 Dm(this,e)}}class g1{constructor(e){this.decoders=e}or(e){return Dm(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 Dm=(t,e)=>new g1({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class m1{constructor(e,s,n,r){this.name=e,this.prefix=s,this.baseEncode=n,this.baseDecode=r,this.encoder=new p1(e,s,n),this.decoder=new f1(e,s,r)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const qc=({name:t,prefix:e,encode:s,decode:n})=>new m1(t,e,s,n),da=({prefix:t,name:e,alphabet:s})=>{const{encode:n,decode:r}=d1(s,e);return qc({prefix:t,name:e,encode:n,decode:i=>$m(r(i))})},y1=(t,e,s,n)=>{const r={};for(let d=0;d<e.length;++d)r[e[d]]=d;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 d=0;d<i;++d){const u=r[t[d]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<s|u,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},w1=(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},St=({name:t,prefix:e,bitsPerChar:s,alphabet:n})=>qc({prefix:e,name:t,encode(r){return w1(r,n,s)},decode(r){return y1(r,n,s,t)}}),E1=qc({prefix:"\0",name:"identity",encode:t=>h1(t),decode:t=>u1(t)});var b1=Object.freeze({__proto__:null,identity:E1});const v1=St({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var C1=Object.freeze({__proto__:null,base2:v1});const _1=St({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var A1=Object.freeze({__proto__:null,base8:_1});const S1=da({prefix:"9",name:"base10",alphabet:"0123456789"});var I1=Object.freeze({__proto__:null,base10:S1});const N1=St({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),T1=St({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var R1=Object.freeze({__proto__:null,base16:N1,base16upper:T1});const O1=St({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),P1=St({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),x1=St({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),k1=St({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),U1=St({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),$1=St({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),D1=St({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),L1=St({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),M1=St({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var B1=Object.freeze({__proto__:null,base32:O1,base32upper:P1,base32pad:x1,base32padupper:k1,base32hex:U1,base32hexupper:$1,base32hexpad:D1,base32hexpadupper:L1,base32z:M1});const j1=da({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),F1=da({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var q1=Object.freeze({__proto__:null,base36:j1,base36upper:F1});const W1=da({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),H1=da({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var z1=Object.freeze({__proto__:null,base58btc:W1,base58flickr:H1});const V1=St({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),K1=St({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),G1=St({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Y1=St({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Z1=Object.freeze({__proto__:null,base64:V1,base64pad:K1,base64url:G1,base64urlpad:Y1});const Lm=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),J1=Lm.reduce((t,e,s)=>(t[s]=e,t),[]),X1=Lm.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function Q1(t){return t.reduce((e,s)=>(e+=J1[s],e),"")}function eT(t){const e=[];for(const s of t){const n=X1[s.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(n)}return new Uint8Array(e)}const tT=qc({prefix:"🚀",name:"base256emoji",encode:Q1,decode:eT});var sT=Object.freeze({__proto__:null,base256emoji:tT}),nT=Mm,pp=128,rT=-128,iT=Math.pow(2,31);function Mm(t,e,s){e=e||[],s=s||0;for(var n=s;t>=iT;)e[s++]=t&255|pp,t/=128;for(;t&rT;)e[s++]=t&255|pp,t>>>=7;return e[s]=t|0,Mm.bytes=s-n+1,e}var oT=Sd,aT=128,fp=127;function Sd(t,n){var s=0,n=n||0,r=0,i=n,o,a=t.length;do{if(i>=a)throw Sd.bytes=0,new RangeError("Could not decode varint");o=t[i++],s+=r<28?(o&fp)<<r:(o&fp)*Math.pow(2,r),r+=7}while(o>=aT);return Sd.bytes=i-n,s}var cT=Math.pow(2,7),lT=Math.pow(2,14),dT=Math.pow(2,21),uT=Math.pow(2,28),hT=Math.pow(2,35),pT=Math.pow(2,42),fT=Math.pow(2,49),gT=Math.pow(2,56),mT=Math.pow(2,63),yT=function(t){return t<cT?1:t<lT?2:t<dT?3:t<uT?4:t<hT?5:t<pT?6:t<fT?7:t<gT?8:t<mT?9:10},wT={encode:nT,decode:oT,encodingLength:yT},Bm=wT;const gp=(t,e,s=0)=>(Bm.encode(t,e,s),e),mp=t=>Bm.encodingLength(t),Id=(t,e)=>{const s=e.byteLength,n=mp(t),r=n+mp(s),i=new Uint8Array(r+s);return gp(t,i,0),gp(s,i,n),i.set(e,r),new ET(t,s,e,i)};class ET{constructor(e,s,n,r){this.code=e,this.size=s,this.digest=n,this.bytes=r}}const jm=({name:t,code:e,encode:s})=>new bT(t,e,s);class bT{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?Id(this.code,s):s.then(n=>Id(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Fm=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),vT=jm({name:"sha2-256",code:18,encode:Fm("SHA-256")}),CT=jm({name:"sha2-512",code:19,encode:Fm("SHA-512")});var _T=Object.freeze({__proto__:null,sha256:vT,sha512:CT});const qm=0,AT="identity",Wm=$m,ST=t=>Id(qm,Wm(t)),IT={code:qm,name:AT,encode:Wm,digest:ST};var NT=Object.freeze({__proto__:null,identity:IT});new TextEncoder,new TextDecoder;const yp={...b1,...C1,...A1,...I1,...R1,...B1,...q1,...z1,...Z1,...sT};({..._T,...NT});function Hm(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function TT(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Hm(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function zm(t,e,s,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:n}}}const wp=zm("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Sl=zm("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=TT(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),RT={utf8:wp,"utf-8":wp,hex:yp.base16,latin1:Sl,ascii:Sl,binary:Sl,...yp};function OT(t,e="utf8"){const s=RT[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Hm(globalThis.Buffer.from(t,"utf-8")):s.decoder.decode(`${s.prefix}${t}`)}var PT=Object.defineProperty,xT=(t,e,s)=>e in t?PT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ws=(t,e,s)=>xT(t,typeof e!="symbol"?e+"":e,s);class kT{constructor(e,s){this.core=e,this.logger=s,Ws(this,"keychain",new Map),Ws(this,"name",xN),Ws(this,"version",kN),Ws(this,"initialized",!1),Ws(this,"storagePrefix",nn),Ws(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Ws(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Ws(this,"set",async(n,r)=>{this.isInitialized(),this.keychain.set(n,r),await this.persist()}),Ws(this,"get",n=>{this.isInitialized();const r=this.keychain.get(n);if(typeof r>"u"){const{message:i}=Y("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(i)}return r}),Ws(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=ts(s,this.name)}get context(){return es(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,ld(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?dd(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=Y("NOT_INITIALIZED",this.name);throw new Error(e)}}}var UT=Object.defineProperty,$T=(t,e,s)=>e in t?UT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ht=(t,e,s)=>$T(t,typeof e!="symbol"?e+"":e,s);class DT{constructor(e,s,n){this.core=e,this.logger=s,ht(this,"name",ON),ht(this,"keychain"),ht(this,"randomSessionIdentifier",vd()),ht(this,"initialized",!1),ht(this,"clientId"),ht(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),ht(this,"hasKeys",r=>(this.isInitialized(),this.keychain.has(r))),ht(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const r=await this.getClientSeed(),i=Ru(r),o=Ky(i.publicKey);return this.clientId=o,o}),ht(this,"generateKeyPair",()=>{this.isInitialized();const r=lI();return this.setPrivateKey(r.publicKey,r.privateKey)}),ht(this,"signJWT",async r=>{this.isInitialized();const i=await this.getClientSeed(),o=Ru(i),a=this.randomSessionIdentifier;return await Gy(a,r,PN,o)}),ht(this,"generateSharedKey",(r,i,o)=>{this.isInitialized();const a=this.getPrivateKey(r),c=dI(a,i);return this.setSymKey(c,o)}),ht(this,"setSymKey",async(r,i)=>{this.isInitialized();const o=i||Ha(r);return await this.keychain.set(o,r),o}),ht(this,"deleteKeyPair",async r=>{this.isInitialized(),await this.keychain.del(r)}),ht(this,"deleteSymKey",async r=>{this.isInitialized(),await this.keychain.del(r)}),ht(this,"encode",async(r,i,o)=>{this.isInitialized();const a=Im(o),c=io(i);if(Jh(a))return pI(c,o==null?void 0:o.encoding);if(Zh(a)){const h=a.senderPublicKey,p=a.receiverPublicKey;r=await this.generateSharedKey(h,p)}const l=this.getSymKey(r),{type:d,senderPublicKey:u}=a;return uI({type:d,symKey:l,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),ht(this,"decode",async(r,i,o)=>{this.isInitialized();const a=gI(i,o);if(Jh(a)){const c=fI(i,o==null?void 0:o.encoding);return Ya(c)}if(Zh(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;r=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(r),l=hI({symKey:c,encoded:i,encoding:o==null?void 0:o.encoding});return Ya(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${r}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),ht(this,"getPayloadType",(r,i=Zt)=>{const o=To({encoded:r,encoding:i});return Dr(o.type)}),ht(this,"getPayloadSenderPublicKey",(r,i=Zt)=>{const o=To({encoded:r,encoding:i});return o.senderPublicKey?Qt(o.senderPublicKey,jt):void 0}),this.core=e,this.logger=ts(s,this.name),this.keychain=n||new kT(this.core,this.logger)}get context(){return es(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(up)}catch{e=vd(),await this.keychain.set(up,e)}return OT(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=Y("NOT_INITIALIZED",this.name);throw new Error(e)}}}var LT=Object.defineProperty,MT=Object.defineProperties,BT=Object.getOwnPropertyDescriptors,Ep=Object.getOwnPropertySymbols,jT=Object.prototype.hasOwnProperty,FT=Object.prototype.propertyIsEnumerable,Nd=(t,e,s)=>e in t?LT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,qT=(t,e)=>{for(var s in e||(e={}))jT.call(e,s)&&Nd(t,s,e[s]);if(Ep)for(var s of Ep(e))FT.call(e,s)&&Nd(t,s,e[s]);return t},WT=(t,e)=>MT(t,BT(e)),is=(t,e,s)=>Nd(t,typeof e!="symbol"?e+"":e,s);class HT extends AC{constructor(e,s){super(e,s),this.logger=e,this.core=s,is(this,"messages",new Map),is(this,"messagesWithoutClientAck",new Map),is(this,"name",UN),is(this,"version",$N),is(this,"initialized",!1),is(this,"storagePrefix",nn),is(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}}}),is(this,"set",async(n,r,i)=>{this.isInitialized();const o=vs(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===za.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,WT(qT({},c),{[o]:r}))}return await this.persist(),o}),is(this,"get",n=>{this.isInitialized();let r=this.messages.get(n);return typeof r>"u"&&(r={}),r}),is(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}),is(this,"has",(n,r)=>{this.isInitialized();const i=this.get(n),o=vs(r);return typeof i[o]<"u"}),is(this,"ack",async(n,r)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(n);if(typeof i>"u")return;const o=vs(r);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,i),await this.persist()}),is(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=ts(e,this.name),this.core=s}get context(){return es(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,ld(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,ld(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?dd(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?dd(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=Y("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zT=Object.defineProperty,VT=Object.defineProperties,KT=Object.getOwnPropertyDescriptors,bp=Object.getOwnPropertySymbols,GT=Object.prototype.hasOwnProperty,YT=Object.prototype.propertyIsEnumerable,Td=(t,e,s)=>e in t?zT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Gr=(t,e)=>{for(var s in e||(e={}))GT.call(e,s)&&Td(t,s,e[s]);if(bp)for(var s of bp(e))YT.call(e,s)&&Td(t,s,e[s]);return t},vp=(t,e)=>VT(t,KT(e)),ms=(t,e,s)=>Td(t,typeof e!="symbol"?e+"":e,s);class ZT extends SC{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,ms(this,"events",new Mr.EventEmitter),ms(this,"name",LN),ms(this,"queue",new Map),ms(this,"publishTimeout",Z.toMiliseconds(Z.ONE_MINUTE)),ms(this,"initialPublishTimeout",Z.toMiliseconds(Z.ONE_SECOND*15)),ms(this,"needsTransportRestart",!1),ms(this,"publish",async(n,r,i)=>{var o,a,c,l,d;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:r,opts:i}});const u=(i==null?void 0:i.ttl)||DN,h=(i==null?void 0:i.prompt)||!1,p=(i==null?void 0:i.tag)||0,g=(i==null?void 0:i.id)||mr().toString(),f=ni(Ec().protocol),w={id:g,method:(i==null?void 0:i.publishMethod)||f.publish,params:Gr({topic:n,message:r,ttl:u,prompt:h,tag:p,attestation:i==null?void 0:i.attestation},i==null?void 0:i.tvf)},v=`Failed to publish payload, please try again. id:${g} tag:${p}`;try{mt((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),mt((c=w.params)==null?void 0:c.tag)&&((l=w.params)==null||delete l.tag);const N=new Promise(async A=>{const _=({id:U})=>{var L;((L=w.id)==null?void 0:L.toString())===U.toString()&&(this.removeRequestFromQueue(U),this.relayer.events.removeListener(it.publish,_),A())};this.relayer.events.on(it.publish,_);const P=Zs(new Promise((U,L)=>{this.rpcPublish(w,i).then(U).catch(W=>{this.logger.warn(W,W==null?void 0:W.message),L(W)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${g} tag:${p}`);try{await P,this.events.removeListener(it.publish,_)}catch(U){this.queue.set(g,{request:w,opts:i,attempt:1}),this.logger.warn(U,U==null?void 0:U.message)}});this.logger.trace({type:"method",method:"publish",params:{id:g,topic:n,message:r,opts:i}}),await Zs(N,this.publishTimeout,v)}catch(N){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(N),(d=i==null?void 0:i.internal)!=null&&d.throwOnFailedPublish)throw N}finally{this.queue.delete(g)}}),ms(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:d={}}=n,{attestation:u,tvf:h,publishMethod:p,prompt:g,tag:f,ttl:w=Z.FIVE_MINUTES}=d,v=d.id||mr().toString(),N=ni(Ec().protocol),A=p||N.publish,_={id:v,method:A,params:Gr(vp(Gr({},l),{ttl:w,prompt:g,tag:f,attestation:u}),h)},P=`Failed to publish custom payload, please try again. id:${v} tag:${f}`;try{mt((r=_.params)==null?void 0:r.prompt)&&((i=_.params)==null||delete i.prompt),mt((o=_.params)==null?void 0:o.tag)&&((a=_.params)==null||delete a.tag);const U=new Promise(async L=>{const W=({id:q})=>{var V;((V=_.id)==null?void 0:V.toString())===q.toString()&&(this.removeRequestFromQueue(q),this.relayer.events.removeListener(it.publish,W),L())};this.relayer.events.on(it.publish,W);const k=Zs(new Promise((q,V)=>{this.rpcPublish(_,d).then(q).catch(x=>{this.logger.warn(x,x==null?void 0:x.message),V(x)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${A} id:${v} tag:${f}`);try{await k,this.events.removeListener(it.publish,W)}catch(q){this.queue.set(v,{request:_,opts:d,attempt:1}),this.logger.warn(q,q==null?void 0:q.message)}});this.logger.trace({type:"method",method:"publish",params:{id:v,payload:l,opts:d}}),await Zs(U,this.publishTimeout,P)}catch(U){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(U),(c=d==null?void 0:d.internal)!=null&&c.throwOnFailedPublish)throw U}finally{this.queue.delete(v)}}),ms(this,"on",(n,r)=>{this.events.on(n,r)}),ms(this,"once",(n,r)=>{this.events.once(n,r)}),ms(this,"off",(n,r)=>{this.events.off(n,r)}),ms(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.relayer=e,this.logger=ts(s,this.name),this.registerEventListeners()}get context(){return es(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(it.publish,Gr(Gr({},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,vp(Gr({},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(Ii.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(it.connection_stalled);return}this.checkQueue()}),this.relayer.on(it.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var JT=Object.defineProperty,XT=(t,e,s)=>e in t?JT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Yr=(t,e,s)=>XT(t,typeof e!="symbol"?e+"":e,s);class QT{constructor(){Yr(this,"map",new Map),Yr(this,"set",(e,s)=>{const n=this.get(e);this.exists(e,s)||this.map.set(e,[...n,s])}),Yr(this,"get",e=>this.map.get(e)||[]),Yr(this,"exists",(e,s)=>this.get(e).includes(s)),Yr(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)}),Yr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var eR=Object.defineProperty,tR=Object.defineProperties,sR=Object.getOwnPropertyDescriptors,Cp=Object.getOwnPropertySymbols,nR=Object.prototype.hasOwnProperty,rR=Object.prototype.propertyIsEnumerable,Rd=(t,e,s)=>e in t?eR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Mi=(t,e)=>{for(var s in e||(e={}))nR.call(e,s)&&Rd(t,s,e[s]);if(Cp)for(var s of Cp(e))rR.call(e,s)&&Rd(t,s,e[s]);return t},Il=(t,e)=>tR(t,sR(e)),We=(t,e,s)=>Rd(t,typeof e!="symbol"?e+"":e,s);class iR extends TC{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,We(this,"subscriptions",new Map),We(this,"topicMap",new QT),We(this,"events",new Mr.EventEmitter),We(this,"name",HN),We(this,"version",zN),We(this,"pending",new Map),We(this,"cached",[]),We(this,"initialized",!1),We(this,"storagePrefix",nn),We(this,"subscribeTimeout",Z.toMiliseconds(Z.ONE_MINUTE)),We(this,"initialSubscribeTimeout",Z.toMiliseconds(Z.ONE_SECOND*15)),We(this,"clientId"),We(this,"batchSubscribeTopicsLimit",500),We(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),We(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=Ec(r),a={topic:n,relay:o,transportType:r==null?void 0:r.transportType};(i=r==null?void 0: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}}),We(this,"unsubscribe",async(n,r)=>{this.isInitialized(),typeof(r==null?void 0:r.id)<"u"?await this.unsubscribeById(n,r.id,r):await this.unsubscribeByTopic(n,r)}),We(this,"isSubscribed",n=>new Promise(r=>{r(this.topicMap.topics.includes(n))})),We(this,"isKnownTopic",n=>new Promise(r=>{r(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(i=>i.topic===n))})),We(this,"on",(n,r)=>{this.events.on(n,r)}),We(this,"once",(n,r)=>{this.events.once(n,r)}),We(this,"off",(n,r)=>{this.events.off(n,r)}),We(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),We(this,"start",async()=>{await this.onConnect()}),We(this,"stop",async()=>{await this.onDisconnect()}),We(this,"restart",async()=>{await this.restore(),await this.onRestart()}),We(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)}),We(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Ii.pulse,async()=>{await this.checkPending()}),this.events.on(as.created,async n=>{const r=as.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()}),this.events.on(as.deleted,async n=>{const r=as.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:n}),await this.persist()})}),this.relayer=e,this.logger=ts(s,this.name),this.clientId=""}get context(){return es(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=Ec(n);await this.restartToComplete({topic:e,id:s,relay:r}),await this.rpcUnsubscribe(e,s,r);const i=Ze("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==null?void 0:n.internal)!=null&&r.skipSubscribe)return o;(!n||(n==null?void 0:n.transportType)===Ke.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const a={method:ni(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==null?void 0:n.internal)==null?void 0:i.throwOnFailedPublish;try{if((n==null?void 0:n.transportType)===Ke.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(u=>this.logger.warn(u))},Z.toMiliseconds(Z.ONE_SECOND)),o;const l=new Promise(async u=>{const h=p=>{p.topic===e&&(this.events.removeListener(as.created,h),u(p.id))};this.events.on(as.created,h);try{const p=await Zs(new Promise((g,f)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),f(w)}).then(g)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(as.created,h),u(p)}catch{}}),d=await Zs(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!d&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return d?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(it.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,n={method:ni(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 Zs(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(it.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,n={method:ni(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 Zs(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(it.connection_stalled)}return r}rpcUnsubscribe(e,s,n){const r={method:ni(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,Il(Mi({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,Mi({},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,Mi({},s)),this.topicMap.set(s.topic,e),this.events.emit(as.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}=Y("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(as.deleted,Il(Mi({},n),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(as.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(as.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}=Y("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=>Il(Mi({},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 R0(Z.toMiliseconds(Z.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}=Y("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 vs(e+await this.getClientId())}}var oR=Object.defineProperty,_p=Object.getOwnPropertySymbols,aR=Object.prototype.hasOwnProperty,cR=Object.prototype.propertyIsEnumerable,Od=(t,e,s)=>e in t?oR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ap=(t,e)=>{for(var s in e||(e={}))aR.call(e,s)&&Od(t,s,e[s]);if(_p)for(var s of _p(e))cR.call(e,s)&&Od(t,s,e[s]);return t},Le=(t,e,s)=>Od(t,typeof e!="symbol"?e+"":e,s);class lR extends IC{constructor(e){var s;super(e),Le(this,"protocol","wc"),Le(this,"version",2),Le(this,"core"),Le(this,"logger"),Le(this,"events",new Mr.EventEmitter),Le(this,"provider"),Le(this,"messages"),Le(this,"subscriber"),Le(this,"publisher"),Le(this,"name",BN),Le(this,"transportExplicitlyClosed",!1),Le(this,"initialized",!1),Le(this,"connectionAttemptInProgress",!1),Le(this,"relayUrl"),Le(this,"projectId"),Le(this,"packageName"),Le(this,"bundleId"),Le(this,"hasExperiencedNetworkDisruption",!1),Le(this,"pingTimeout"),Le(this,"heartBeatTimeout",Z.toMiliseconds(Z.THIRTY_SECONDS+Z.FIVE_SECONDS)),Le(this,"reconnectTimeout"),Le(this,"connectPromise"),Le(this,"reconnectInProgress",!1),Le(this,"requestsInFlight",[]),Le(this,"connectTimeout",Z.toMiliseconds(Z.ONE_SECOND*15)),Le(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const o=n.id||mr().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}}),Le(this,"resetPingTimeout",()=>{pc()&&(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==null?void 0:a.message)}},this.heartBeatTimeout))}),Le(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),Le(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(it.connect)}),Le(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Le(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(it.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Le(this,"registerProviderListeners",()=>{this.provider.on(gs.payload,this.onPayloadHandler),this.provider.on(gs.connect,this.onConnectHandler),this.provider.on(gs.disconnect,this.onDisconnectHandler),this.provider.on(gs.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=fu({logger:(s=e.logger)!=null?s:MN,name:this.name}),this.messages=new HT(this.logger,e.core),this.subscriber=new iR(this,this.logger),this.publisher=new ZT(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||km,p0()?this.packageName=wh():f0()&&(this.bundleId=wh()),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==null?void 0:e.message))}get context(){return es(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:Ke.relay},za.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==null?void 0:s.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((n=s==null?void 0:s.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(r=s==null?void 0:s.internal)==null?void 0:r.throwOnFailedPublish;let a=((i=this.subscriber.topicMap.get(e))==null?void 0:i[0])||"",c;const l=d=>{d.topic===e&&(this.subscriber.off(as.created,l),c())};return await Promise.all([new Promise(d=>{c=d,this.subscriber.on(as.created,l)}),new Promise(async(d,u)=>{a=await this.subscriber.subscribe(e,Ap({internal:{throwOnFailedPublish:o}},s)).catch(h=>{o&&u(h)})||a,d()})]),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 Zs(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 dp())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0: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==null?void 0: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=rt(Z.FIVE_MINUTES),i={topic:n,expiry:r,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,i)}this.events.emit(it.message,e),await this.recordMessageEvent(e,za.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(gs.disconnect,i),await Zs(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(gs.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(gs.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(gs.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,Z.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,n,r,i;if(pc())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==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Wd(new Vy(E0({sdkVersion:Ad,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}),Hd(e)){if(!e.method.endsWith(jN))return;const s=e.params,{topic:n,message:r,publishedAt:i,attestation:o}=s.data,a={topic:n,message:r,publishedAt:i,transportType:Ke.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ap({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else zd(e)&&this.events.emit(it.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,za.inbound),this.events.emit(it.message,e))}async acknowledgePayload(e){const s=oo(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(gs.payload,this.onPayloadHandler),this.provider.off(gs.connect,this.onConnectHandler),this.provider.off(gs.disconnect,this.onDisconnectHandler),this.provider.off(gs.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await dp();gN(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(n=>this.logger.error(n,n==null?void 0:n.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Ii.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&wN())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s==null?void 0:s.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(it.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==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},Z.toMiliseconds(FN)))))}isInitialized(){if(!this.initialized){const{message:e}=Y("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 dR(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Sp(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Ip(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const uR="[object RegExp]",hR="[object String]",pR="[object Number]",fR="[object Boolean]",Np="[object Arguments]",gR="[object Symbol]",mR="[object Date]",yR="[object Map]",wR="[object Set]",ER="[object Array]",bR="[object Function]",vR="[object ArrayBuffer]",Nl="[object Object]",CR="[object Error]",_R="[object DataView]",AR="[object Uint8Array]",SR="[object Uint8ClampedArray]",IR="[object Uint16Array]",NR="[object Uint32Array]",TR="[object BigUint64Array]",RR="[object Int8Array]",OR="[object Int16Array]",PR="[object Int32Array]",xR="[object BigInt64Array]",kR="[object Float32Array]",UR="[object Float64Array]";function $R(){}function Tp(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 DR(t,e,s){return Ki(t,e,void 0,void 0,void 0,void 0,s)}function Ki(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 Qi(t,e,i,o)}return Qi(t,e,i,o)}function Qi(t,e,s,n){if(Object.is(t,e))return!0;let r=Ip(t),i=Ip(e);if(r===Np&&(r=Nl),i===Np&&(i=Nl),r!==i)return!1;switch(r){case hR:return t.toString()===e.toString();case pR:{const c=t.valueOf(),l=e.valueOf();return dR(c,l)}case fR:case mR:case gR:return Object.is(t.valueOf(),e.valueOf());case uR:return t.source===e.source&&t.flags===e.flags;case bR: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 yR:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Ki(l,e.get(c),c,t,e,s,n))return!1;return!0}case wR:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let d=0;d<c.length;d++){const u=c[d],h=l.findIndex(p=>Ki(u,p,void 0,t,e,s,n));if(h===-1)return!1;l.splice(h,1)}return!0}case ER:case AR:case SR:case IR:case NR:case TR:case RR:case OR:case PR:case xR:case kR:case UR:{if(typeof Pe<"u"&&Pe.isBuffer(t)!==Pe.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Ki(t[c],e[c],c,t,e,s,n))return!1;return!0}case vR:return t.byteLength!==e.byteLength?!1:Qi(new Uint8Array(t),new Uint8Array(e),s,n);case _R:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Qi(new Uint8Array(t),new Uint8Array(e),s,n);case CR:return t.name===e.name&&t.message===e.message;case Nl:{if(!(Qi(t.constructor,e.constructor,s,n)||Tp(t)&&Tp(e)))return!1;const c=[...Object.keys(t),...Sp(t)],l=[...Object.keys(e),...Sp(e)];if(c.length!==l.length)return!1;for(let d=0;d<c.length;d++){const u=c[d],h=t[u];if(!Object.hasOwn(e,u))return!1;const p=e[u];if(!Ki(h,p,u,t,e,s,n))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function LR(t,e){return DR(t,e,$R)}var MR=Object.defineProperty,Rp=Object.getOwnPropertySymbols,BR=Object.prototype.hasOwnProperty,jR=Object.prototype.propertyIsEnumerable,Pd=(t,e,s)=>e in t?MR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Op=(t,e)=>{for(var s in e||(e={}))BR.call(e,s)&&Pd(t,s,e[s]);if(Rp)for(var s of Rp(e))jR.call(e,s)&&Pd(t,s,e[s]);return t},Ht=(t,e,s)=>Pd(t,typeof e!="symbol"?e+"":e,s);class Wr extends NC{constructor(e,s,n,r=nn,i=void 0){super(e,s,n,r),this.core=e,this.logger=s,this.name=n,Ht(this,"map",new Map),Ht(this,"version",qN),Ht(this,"cached",[]),Ht(this,"initialized",!1),Ht(this,"getKey"),Ht(this,"storagePrefix",nn),Ht(this,"recentlyDeleted",[]),Ht(this,"recentlyDeletedLimit",200),Ht(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!mt(o)?this.map.set(this.getKey(o),o):VI(o)?this.map.set(o.id,o):KI(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ht(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())}),Ht(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ht(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>LR(a[c],o[c]))):this.values)),Ht(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=Op(Op({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ht(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=ts(s,this.name),this.storagePrefix=r,this.getKey=i}get context(){return es(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}=Y("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}const{message:n}=Y("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}=Y("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}=Y("NOT_INITIALIZED",this.name);throw new Error(e)}}}var FR=Object.defineProperty,qR=(t,e,s)=>e in t?FR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Re=(t,e,s)=>qR(t,typeof e!="symbol"?e+"":e,s);class WR{constructor(e,s){this.core=e,this.logger=s,Re(this,"name",VN),Re(this,"version",KN),Re(this,"events",new Vd),Re(this,"pairings"),Re(this,"initialized",!1),Re(this,"storagePrefix",nn),Re(this,"ignoredPayloadTypes",[An]),Re(this,"registeredMethods",[]),Re(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Re(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Re(this,"create",async n=>{this.isInitialized();const r=vd(),i=await this.core.crypto.setSymKey(r),o=rt(Z.FIVE_MINUTES),a={protocol:xm},c={topic:i,expiry:o,relay:a,active:!1,methods:n==null?void 0:n.methods},l=tp({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:r,relay:a,expiryTimestamp:o,methods:n==null?void 0:n.methods});return this.events.emit(pr.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:n==null?void 0:n.transportType,internal:n==null?void 0:n.internal}),{topic:i,uri:l}}),Re(this,"pair",async n=>{this.isInitialized();const r=this.core.eventClient.createEvent({properties:{topic:n==null?void 0:n.uri,trace:[zs.pairing_started]}});this.isValidPair(n,r);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=ep(n.uri);r.props.properties.topic=i,r.addTrace(zs.pairing_uri_validation_success),r.addTrace(zs.pairing_uri_not_expired);let d;if(this.pairings.keys.includes(i)){if(d=this.pairings.get(i),r.addTrace(zs.existing_pairing),d.active)throw r.setError(hn.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);r.addTrace(zs.pairing_not_expired)}const u=c||rt(Z.FIVE_MINUTES),h={topic:i,relay:a,expiry:u,active:!1,methods:l};this.core.expirer.set(i,u),await this.pairings.set(i,h),r.addTrace(zs.store_new_pairing),n.activatePairing&&await this.activate({topic:i}),this.events.emit(pr.create,h),r.addTrace(zs.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),r.addTrace(zs.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{r.setError(hn.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(p){throw r.setError(hn.subscribe_pairing_topic_failure),p}return r.addTrace(zs.subscribe_pairing_topic_success),h}),Re(this,"activate",async({topic:n})=>{this.isInitialized();const r=rt(Z.FIVE_MINUTES);this.core.expirer.set(n,r),await this.pairings.update(n,{active:!0,expiry:r})}),Re(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}=hr();this.events.once(Fe("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}}),Re(this,"updateExpiry",async({topic:n,expiry:r})=>{this.isInitialized(),await this.pairings.update(n,{expiry:r})}),Re(this,"updateMetadata",async({topic:n,metadata:r})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:r})}),Re(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Re(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",Ze("USER_DISCONNECTED")),await this.deletePairing(r))}),Re(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:r,relay:i,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(r);return tp({protocol:this.core.protocol,version:this.core.version,topic:r,symKey:c,relay:i,expiryTimestamp:o,methods:a})}),Re(this,"sendRequest",async(n,r,i)=>{const o=Ks(r,i),a=await this.core.crypto.encode(n,o),c=Di[r].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),Re(this,"sendResult",async(n,r,i)=>{const o=oo(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=Di[c].res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),Re(this,"sendError",async(n,r,i)=>{const o=If(n,i),a=await this.core.crypto.encode(r,o),c=(await this.core.history.get(r,n)).request.method,l=Di[c]?Di[c].res:Di.unregistered_method.res;await this.core.relayer.publish(r,a,l),await this.core.history.resolve(o)}),Re(this,"deletePairing",async(n,r)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,Ze("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),r?Promise.resolve():this.core.expirer.del(n)])}),Re(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(r=>Gs(r.expiry));await Promise.all(n.map(r=>this.deletePairing(r.topic)))}),Re(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)}}),Re(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i}=n,o=(await this.core.history.get(r,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(r,i);default:return this.onUnknownRpcMethodResponse(o)}}),Re(this,"onPairingPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult(i,n,!0),this.events.emit(pr.ping,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),Re(this,"onPairingPingResponse",(n,r)=>{const{id:i}=r;setTimeout(()=>{dn(r)?this.events.emit(Fe("pairing_ping",i),{}):Vs(r)&&this.events.emit(Fe("pairing_ping",i),{error:r.error})},500)}),Re(this,"onPairingDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(pr.delete,{id:i,topic:n})}catch(o){await this.sendError(i,n,o),this.logger.error(o)}}),Re(this,"onUnknownRpcMethodRequest",async(n,r)=>{const{id:i,method:o}=r;try{if(this.registeredMethods.includes(o))return;const a=Ze("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)}}),Re(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(Ze("WC_METHOD_UNSUPPORTED",n))}),Re(this,"isValidPair",(n,r)=>{var i;if(!Vt(n)){const{message:a}=Y("MISSING_OR_INVALID",`pair() params: ${n}`);throw r.setError(hn.malformed_pairing_uri),new Error(a)}if(!zI(n.uri)){const{message:a}=Y("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw r.setError(hn.malformed_pairing_uri),new Error(a)}const o=ep(n==null?void 0:n.uri);if(!((i=o==null?void 0:o.relay)!=null&&i.protocol)){const{message:a}=Y("MISSING_OR_INVALID","pair() uri#relay-protocol");throw r.setError(hn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=Y("MISSING_OR_INVALID","pair() uri#symKey");throw r.setError(hn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&Z.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){r.setError(hn.pairing_expired);const{message:a}=Y("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Re(this,"isValidPing",async n=>{if(!Vt(n)){const{message:i}=Y("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),Re(this,"isValidDisconnect",async n=>{if(!Vt(n)){const{message:i}=Y("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidPairingTopic(r)}),Re(this,"isValidPairingTopic",async n=>{if(!ot(n,!1)){const{message:r}=Y("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(r)}if(!this.pairings.keys.includes(n)){const{message:r}=Y("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(r)}if(Gs(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:r}=Y("EXPIRED",`pairing topic: ${n}`);throw new Error(r)}}),this.core=e,this.logger=ts(s,this.name),this.pairings=new Wr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return es(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=Y("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(it.message,async e=>{const{topic:s,message:n,transportType:r}=e;if(this.pairings.keys.includes(s)&&r!==Ke.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const i=await this.core.crypto.decode(s,n);Hd(i)?(this.core.history.set(s,i),await this.onRelayEventRequest({topic:s,payload:i})):zd(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(Es.expired,async e=>{const{topic:s}=Tg(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(pr.expire,{topic:s}))})}}var HR=Object.defineProperty,zR=(t,e,s)=>e in t?HR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,bt=(t,e,s)=>zR(t,typeof e!="symbol"?e+"":e,s);class VR extends _C{constructor(e,s){super(e,s),this.core=e,this.logger=s,bt(this,"records",new Map),bt(this,"events",new Mr.EventEmitter),bt(this,"name",GN),bt(this,"version",YN),bt(this,"cached",[]),bt(this,"initialized",!1),bt(this,"storagePrefix",nn),bt(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)}),bt(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:rt(Z.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ts.created,o)}),bt(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=Vs(n)?{error:n.error}:{result:n.result},this.records.set(r.id,r),this.persist(),this.events.emit(Ts.updated,r))}),bt(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))),bt(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(Ts.deleted,i)}}),this.persist()}),bt(this,"exists",async(n,r)=>(this.isInitialized(),this.records.has(r)?(await this.getRecord(r)).topic===n:!1)),bt(this,"on",(n,r)=>{this.events.on(n,r)}),bt(this,"once",(n,r)=>{this.events.once(n,r)}),bt(this,"off",(n,r)=>{this.events.off(n,r)}),bt(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=ts(s,this.name)}get context(){return es(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:Ks(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}=Y("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ts.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=Y("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(Ts.created,e=>{const s=Ts.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Ts.updated,e=>{const s=Ts.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Ts.deleted,e=>{const s=Ts.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(Ii.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{Z.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(Ts.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=Y("NOT_INITIALIZED",this.name);throw new Error(e)}}}var KR=Object.defineProperty,GR=(t,e,s)=>e in t?KR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Rt=(t,e,s)=>GR(t,typeof e!="symbol"?e+"":e,s);class YR extends RC{constructor(e,s){super(e,s),this.core=e,this.logger=s,Rt(this,"expirations",new Map),Rt(this,"events",new Mr.EventEmitter),Rt(this,"name",ZN),Rt(this,"version",JN),Rt(this,"cached",[]),Rt(this,"initialized",!1),Rt(this,"storagePrefix",nn),Rt(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)}),Rt(this,"has",n=>{try{const r=this.formatTarget(n);return typeof this.getExpiration(r)<"u"}catch{return!1}}),Rt(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(Es.created,{target:i,expiration:o})}),Rt(this,"get",n=>{this.isInitialized();const r=this.formatTarget(n);return this.getExpiration(r)}),Rt(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(Es.deleted,{target:r,expiration:i})}}),Rt(this,"on",(n,r)=>{this.events.on(n,r)}),Rt(this,"once",(n,r)=>{this.events.once(n,r)}),Rt(this,"off",(n,r)=>{this.events.off(n,r)}),Rt(this,"removeListener",(n,r)=>{this.events.removeListener(n,r)}),this.logger=ts(s,this.name)}get context(){return es(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 b0(e);if(typeof e=="number")return v0(e);const{message:s}=Y("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(Es.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=Y("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}=Y("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return s}checkExpiry(e,s){const{expiry:n}=s;Z.toMiliseconds(n)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit(Es.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(Ii.pulse,()=>this.checkExpirations()),this.events.on(Es.created,e=>{const s=Es.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Es.expired,e=>{const s=Es.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on(Es.deleted,e=>{const s=Es.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=Y("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ZR=Object.defineProperty,JR=(t,e,s)=>e in t?ZR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,nt=(t,e,s)=>JR(t,typeof e!="symbol"?e+"":e,s);class XR extends OC{constructor(e,s,n){super(e,s,n),this.core=e,this.logger=s,this.store=n,nt(this,"name",XN),nt(this,"abortController"),nt(this,"isDevEnv"),nt(this,"verifyUrlV3",e1),nt(this,"storagePrefix",nn),nt(this,"version",Pm),nt(this,"publicKey"),nt(this,"fetchPromise"),nt(this,"init",async()=>{var r;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&Z.toMiliseconds((r=this.publicKey)==null?void 0:r.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),nt(this,"register",async r=>{if(!Ni()||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=In.getDocument(),d=this.startAbortTimer(Z.ONE_SECOND*5),u=await new Promise((h,p)=>{const g=()=>{window.removeEventListener("message",w),l.body.removeChild(f),p("attestation aborted")};this.abortController.signal.addEventListener("abort",g);const f=l.createElement("iframe");f.src=c,f.style.display="none",f.addEventListener("error",g,{signal:this.abortController.signal});const w=v=>{if(v.data&&typeof v.data=="string")try{const N=JSON.parse(v.data);if(N.type==="verify_attestation"){if(Wl(N.attestation).payload.id!==o)return;clearInterval(d),l.body.removeChild(f),this.abortController.signal.removeEventListener("abort",g),window.removeEventListener("message",w),h(N.attestation===null?"":N.attestation)}}catch(N){this.logger.warn(N)}};l.body.appendChild(f),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(u,"jwt attestation"),u}catch(l){this.logger.warn(l)}return""}),nt(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(Wl(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==null?void 0:r.verifyUrl);return this.fetchAttestation(o,c)}),nt(this,"fetchAttestation",async(r,i)=>{this.logger.debug(`resolving attestation: ${r} from url: ${i}`);const o=this.startAbortTimer(Z.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}),nt(this,"getVerifyUrl",r=>{let i=r||Xi;return t1.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Xi}`),i=Xi),i}),nt(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const r=this.startAbortTimer(Z.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)}}),nt(this,"persistPublicKey",async r=>{this.logger.debug(r,"persisting public key to local storage"),await this.store.setItem(this.storeKey,r),this.publicKey=r}),nt(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),nt(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")}}),nt(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),nt(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}),nt(this,"validateAttestation",(r,i)=>{const o=yI(r,i.publicKey),a={hasExpired:Z.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=ts(s,this.name),this.abortController=new AbortController,this.isDevEnv=nu(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return es(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),Z.toMiliseconds(e))}}var QR=Object.defineProperty,eO=(t,e,s)=>e in t?QR(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Pp=(t,e,s)=>eO(t,typeof e!="symbol"?e+"":e,s);class tO extends PC{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,Pp(this,"context",s1),Pp(this,"registerDeviceToken",async n=>{const{clientId:r,token:i,notificationType:o,enableEncrypted:a=!1}=n,c=`${n1}/${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=ts(s,this.context)}}var sO=Object.defineProperty,xp=Object.getOwnPropertySymbols,nO=Object.prototype.hasOwnProperty,rO=Object.prototype.propertyIsEnumerable,xd=(t,e,s)=>e in t?sO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Bi=(t,e)=>{for(var s in e||(e={}))nO.call(e,s)&&xd(t,s,e[s]);if(xp)for(var s of xp(e))rO.call(e,s)&&xd(t,s,e[s]);return t},pt=(t,e,s)=>xd(t,typeof e!="symbol"?e+"":e,s);class iO extends xC{constructor(e,s,n=!0){super(e,s,n),this.core=e,this.logger=s,pt(this,"context",i1),pt(this,"storagePrefix",nn),pt(this,"storageVersion",r1),pt(this,"events",new Map),pt(this,"shouldPersist",!1),pt(this,"init",async()=>{if(!nu())try{const r={eventId:bh(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ig(this.core.relayer.protocol,this.core.relayer.version,Ad)}}};await this.sendEvent([r])}catch(r){this.logger.warn(r)}}),pt(this,"createEvent",r=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=r,l=bh(),d=this.core.projectId||"",u=Date.now(),h=Bi({eventId:l,timestamp:u,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:d,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,h),this.shouldPersist=!0),h}),pt(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 Bi(Bi({},a),this.setMethods(a.eventId))}),pt(this,"deleteEvent",r=>{const{eventId:i}=r;this.events.delete(i),this.shouldPersist=!0}),pt(this,"setEventListeners",()=>{this.core.heartbeat.on(Ii.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(r=>{Z.fromMiliseconds(Date.now())-Z.fromMiliseconds(r.timestamp)>o1&&(this.events.delete(r.eventId),this.shouldPersist=!0)})})}),pt(this,"setMethods",r=>({addTrace:i=>this.addTrace(r,i),setError:i=>this.setError(r,i)})),pt(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)}),pt(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)}),pt(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),pt(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,Bi(Bi({},i),this.setMethods(i.eventId)))})}catch(r){this.logger.warn(r)}}),pt(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)}}),pt(this,"sendEvent",async r=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${a1}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ad}${i}`,{method:"POST",body:JSON.stringify(r)})}),pt(this,"getAppDomain",()=>Sg().url),this.logger=ts(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 oO=Object.defineProperty,kp=Object.getOwnPropertySymbols,aO=Object.prototype.hasOwnProperty,cO=Object.prototype.propertyIsEnumerable,kd=(t,e,s)=>e in t?oO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Up=(t,e)=>{for(var s in e||(e={}))aO.call(e,s)&&kd(t,s,e[s]);if(kp)for(var s of kp(e))cO.call(e,s)&&kd(t,s,e[s]);return t},ze=(t,e,s)=>kd(t,typeof e!="symbol"?e+"":e,s);let lO=class Vm extends EC{constructor(e){var s;super(e),ze(this,"protocol",Om),ze(this,"version",Pm),ze(this,"name",_d),ze(this,"relayUrl"),ze(this,"projectId"),ze(this,"customStoragePrefix"),ze(this,"events",new Mr.EventEmitter),ze(this,"logger"),ze(this,"heartbeat"),ze(this,"relayer"),ze(this,"crypto"),ze(this,"storage"),ze(this,"history"),ze(this,"expirer"),ze(this,"pairing"),ze(this,"verify"),ze(this,"echoClient"),ze(this,"linkModeSupportedApps"),ze(this,"eventClient"),ze(this,"initialized",!1),ze(this,"logChunkController"),ze(this,"on",(a,c)=>this.events.on(a,c)),ze(this,"once",(a,c)=>this.events.once(a,c)),ze(this,"off",(a,c)=>this.events.off(a,c)),ze(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ze(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const d={topic:a,message:c,publishedAt:Date.now(),transportType:Ke.link_mode};this.relayer.onLinkMessageEvent(d,{sessionExists:l})});const n=this.getGlobalCore(e==null?void 0: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==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||km,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Yd({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:TN.logger,name:_d}),{logger:i,chunkLoggerController:o}=Rc({opts:r,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0: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=ts(i,this.name),this.heartbeat=new zy,this.crypto=new DT(this,this.logger,e==null?void 0:e.keychain),this.history=new VR(this,this.logger),this.expirer=new YR(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new mC(Up(Up({},RN),e==null?void 0:e.storageOptions)),this.relayer=new lR({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new WR(this,this.logger),this.verify=new XR(this,this.logger,this.storage),this.echoClient=new tO(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new iO(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new Vm(e);await s.initialize();const n=await s.crypto.getClientId();return await s.storage.setItem(WN,n),s}get context(){return es(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(hp,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(hp)||[],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 vn<"u"&&NN.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const dO=lO,Km="wc",Gm=2,Ym="client",gu=`${Km}@${Gm}:${Ym}:`,Tl={name:Ym,logger:"error"},$p="WALLETCONNECT_DEEPLINK_CHOICE",uO="proposal",Dp="Proposal expired",hO="session",Zr=Z.SEVEN_DAYS,pO="engine",vt={wc_sessionPropose:{req:{ttl:Z.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:Z.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:Z.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:Z.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:Z.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:Z.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:Z.ONE_DAY,prompt:!1,tag:1104},res:{ttl:Z.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:Z.ONE_DAY,prompt:!1,tag:1106},res:{ttl:Z.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:Z.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:Z.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:Z.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:Z.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:Z.ONE_DAY,prompt:!1,tag:1112},res:{ttl:Z.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:Z.ONE_DAY,prompt:!1,tag:1114},res:{ttl:Z.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:Z.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:Z.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:Z.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:Z.FIVE_MINUTES,prompt:!1,tag:1119}}},Rl={min:Z.FIVE_MINUTES,max:Z.SEVEN_DAYS},Hs={idle:"IDLE",active:"ACTIVE"},fO={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:""}},gO="request",mO=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],yO="wc",wO="auth",EO="authKeys",bO="pairingTopics",vO="requests",Wc=`${yO}@${1.5}:${wO}:`,Va=`${Wc}:PUB_KEY`;var CO=Object.defineProperty,_O=Object.defineProperties,AO=Object.getOwnPropertyDescriptors,Lp=Object.getOwnPropertySymbols,SO=Object.prototype.hasOwnProperty,IO=Object.prototype.propertyIsEnumerable,Ud=(t,e,s)=>e in t?CO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Be=(t,e)=>{for(var s in e||(e={}))SO.call(e,s)&&Ud(t,s,e[s]);if(Lp)for(var s of Lp(e))IO.call(e,s)&&Ud(t,s,e[s]);return t},Ct=(t,e)=>_O(t,AO(e)),H=(t,e,s)=>Ud(t,typeof e!="symbol"?e+"":e,s);class NO extends DC{constructor(e){super(e),H(this,"name",pO),H(this,"events",new Vd),H(this,"initialized",!1),H(this,"requestQueue",{state:Hs.idle,queue:[]}),H(this,"sessionRequestQueue",{state:Hs.idle,queue:[]}),H(this,"emittedSessionRequests",new O0({limit:500})),H(this,"requestQueueDelay",Z.ONE_SECOND),H(this,"expectedPairingMethodMap",new Map),H(this,"recentlyDeletedMap",new Map),H(this,"recentlyDeletedLimit",200),H(this,"relayMessageCache",[]),H(this,"pendingSessions",new Map),H(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(vt)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},Z.toMiliseconds(this.requestQueueDelay)))}),H(this,"connect",async s=>{var n;this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=Ct(Be({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=jI(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:d,authentication:u,walletPay:h}=r,p=((n=u==null?void 0:u[0])==null?void 0:n.ttl)||vt.wc_sessionPropose.req.ttl||Z.FIVE_MINUTES;this.validateRequestExpiry(p);let g=i,f,w=!1;try{if(g){const k=this.client.core.pairing.pairings.get(g);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=k.active}}catch(k){throw this.client.logger.error(`connect() -> pairing.get(${g}) failed`),k}if(!g||!w){const{topic:k,uri:q}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});g=k,f=q}if(!g){const{message:k}=Y("NO_MATCHING_KEY",`connect() pairing topic: ${g}`);throw new Error(k)}const v=await this.client.core.crypto.generateKeyPair(),N=rt(p),A=Be(Ct(Be(Be({requiredNamespaces:o,optionalNamespaces:a,relays:d??[{protocol:xm}],proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:N,pairingTopic:g},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:Rn()}),(u||h)&&{requests:{authentication:u==null?void 0:u.map(k=>{const{domain:q,chains:V,nonce:x,uri:I,exp:T,nbf:y,type:b,statement:S,requestId:R,resources:C,signatureTypes:O}=k;return{domain:q,chains:V,nonce:x,type:b??"caip122",aud:I,version:"1",iat:new Date().toISOString(),exp:T,nbf:y,statement:S,requestId:R,resources:C,signatureTypes:O}}),walletPay:h}}),_=Fe("session_connect",A.id),{reject:P,resolve:U,done:L}=hr(p,Dp),W=({id:k})=>{k===A.id&&(this.client.events.off("proposal_expire",W),this.pendingSessions.delete(A.id),this.events.emit(_,{error:{message:Dp,code:0}}))};return this.client.events.on("proposal_expire",W),this.events.once(_,({error:k,session:q})=>{this.client.events.off("proposal_expire",W),k?P(k):q&&U(q)}),await this.setProposal(A.id,A),await this.sendProposeSession({proposal:A,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:A.id}}}).catch(k=>{throw this.deleteProposal(A.id),k}),{uri:f,approval:L}}),H(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}}),H(this,"approve",async s=>{var n,r,i;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=s==null?void 0:s.id)==null?void 0:n.toString(),trace:[Rs.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(q){throw o.setError(or.no_internet_connection),q}try{await this.isValidProposalId(s==null?void 0:s.id)}catch(q){throw this.client.logger.error(`approve() -> proposal.get(${s==null?void 0:s.id}) failed`),o.setError(or.proposal_not_found),q}try{await this.isValidApprove(s)}catch(q){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(or.session_approve_namespace_validation_failure),q}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:d,scopedProperties:u,sessionConfig:h,proposalRequestsResponses:p}=s,g=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:w,requiredNamespaces:v,optionalNamespaces:N}=g;let A=(r=this.client.core.eventClient)==null?void 0:r.getEvent({topic:f});A||(A=(i=this.client.core.eventClient)==null?void 0:i.createEvent({type:Rs.session_approve_started,properties:{topic:f,trace:[Rs.session_approve_started,Rs.session_namespaces_validation_success]}}));const _=await this.client.core.crypto.generateKeyPair(),P=w.publicKey,U=await this.client.core.crypto.generateSharedKey(_,P),L=Ct(Be(Be(Be({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:_,metadata:this.client.metadata},expiry:rt(Zr)},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),{proposalRequestsResponses:p}),W=Ke.relay;A.addTrace(Rs.subscribing_session_topic);try{await this.client.core.relayer.subscribe(U,{transportType:W,internal:{skipSubscribe:!0}})}catch(q){throw A.setError(or.subscribe_session_topic_failure),q}A.addTrace(Rs.subscribe_session_topic_success);const k=Ct(Be({},L),{topic:U,requiredNamespaces:v,optionalNamespaces:N,pairingTopic:f,acknowledged:!1,self:L.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:_,transportType:Ke.relay,authentication:p==null?void 0:p.authentication,walletPayResult:p==null?void 0:p.walletPay});await this.client.session.set(U,k),A.addTrace(Rs.store_session);try{await this.sendApproveSession({sessionTopic:U,proposal:g,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:_},sessionSettleRequest:L,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:Be({correlationId:a},this.getTVFApproveParams(k))}}),A.addTrace(Rs.session_approve_publish_success)}catch(q){throw this.client.logger.error(q),this.client.session.delete(U,Ze("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(U),q}return this.client.core.eventClient.deleteEvent({eventId:A.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:w.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(U,rt(Zr)),{topic:U,acknowledged:()=>Promise.resolve(this.client.session.get(U))}}),H(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:vt.wc_sessionPropose.reject}),await this.deleteProposal(n)}),H(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:n,namespaces:r}=s,{done:i,resolve:o,reject:a}=hr(Z.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Rn(),l=mr().toString(),d=this.client.session.get(n).namespaces;return this.events.once(Fe("session_update",c),({error:u})=>{u?a(u):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(u=>{this.client.logger.error(u),this.client.session.update(n,{namespaces:d}),a(u)}),{acknowledged:i}}),H(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=Rn(),{done:i,resolve:o,reject:a}=hr(Z.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(Fe("session_extend",r),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,rt(Zr)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:r,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}}),H(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=vt.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(i);(a==null?void 0:a.transportType)===Ke.relay&&await this.confirmOnlineStateOrThrow();const c=Rn(),l=mr().toString(),{done:d,resolve:u,reject:h}=hr(o,"Request expired. Please try again.");this.events.once(Fe("session_request",c),({error:w,result:v})=>{w?h(w):u(v)});const p="wc_sessionRequest",g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:{request:Ct(Be({},r),{expiryTimestamp:rt(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(w=>h(w)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),await d();const f={request:Ct(Be({},r),{expiryTimestamp:rt(o)}),chainId:n};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:f,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,f)}).catch(v=>h(v)),this.client.events.emit("session_request_sent",{topic:i,request:r,chainId:n,id:c}),w()}),new Promise(async w=>{var v;if(!((v=a.sessionConfig)!=null&&v.disableDeepLink)){const N=await S0(this.client.core.storage,$p);await C0({id:c,topic:i,wcDeepLink:N})}w()}),d()]).then(w=>w[2])}),H(this,"respond",async s=>{var n,r;this.isInitialized();const i=this.client.core.eventClient.createEvent({properties:{topic:(s==null?void 0:s.topic)||((r=(n=s==null?void 0:s.response)==null?void 0:n.id)==null?void 0:r.toString()),trace:[Rs.session_request_response_started]}});try{await this.isValidRespond(s)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(or.session_request_response_validation_failure),u}i.addTrace(Rs.session_request_response_validation_success);const{topic:o,response:a}=s,{id:c}=a,l=this.client.session.get(o);l.transportType===Ke.relay&&await this.confirmOnlineStateOrThrow();const d=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{i.addTrace(Rs.session_request_response_publish_started),dn(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:d}):Vs(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:d}),this.cleanupAfterResponse(s)}catch(u){throw i.addTrace(u==null?void 0:u.message),i.setError(or.session_request_response_publish_failure),u}}),H(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=Rn(),i=mr().toString(),{done:o,resolve:a,reject:c}=hr(Z.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(Fe("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}))}),H(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:n,event:r,chainId:i}=s,o=mr().toString(),a=Rn();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:r,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),H(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:Ze("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}=Y("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(r)}}),H(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(n=>WI(n,s)))),H(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),H(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?Ke.link_mode:Ke.relay;o===Ke.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:d,nonce:u,type:h,exp:p,nbf:g,methods:f=[],expiry:w}=s,v=[...s.resources||[]],{topic:N,uri:A}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:N,uri:A}});const _=await this.client.core.crypto.generateKeyPair(),P=Ha(_);if(await Promise.all([this.client.auth.authKeys.set(Va,{responseTopic:P,publicKey:_}),this.client.auth.pairingTopics.set(P,{topic:P,pairingTopic:N})]),await this.client.core.relayer.subscribe(P,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${N}`),f.length>0){const{namespace:C}=_n(a[0]);let O=WA(C,"request",f);Wa(v)&&(O=zA(O,v.pop())),v.push(O)}const U=w&&w>vt.wc_sessionAuthenticate.req.ttl?w:vt.wc_sessionAuthenticate.req.ttl,L={authPayload:{type:h??"caip122",chains:a,statement:c,aud:l,domain:d,version:"1",nonce:u,iat:new Date().toISOString(),exp:p,nbf:g,resources:v},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:rt(U)},W={eip155:{chains:a,methods:[...new Set(["personal_sign",...f])],events:["chainChanged","accountsChanged"]}},k={requiredNamespaces:{},optionalNamespaces:W,relays:[{protocol:"irn"}],pairingTopic:N,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:rt(vt.wc_sessionPropose.req.ttl),id:Rn()},{done:q,resolve:V,reject:x}=hr(U,"Request expired"),I=Rn(),T=Fe("session_connect",k.id),y=Fe("session_request",I),b=async({error:C,session:O})=>{this.events.off(y,S),C?x(C):O&&V({session:O})},S=async C=>{var O,B,M;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),C.error){const ye=Ze("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return C.error.code===ye.code?void 0:(this.events.off(T,b),x(C.error.message))}await this.deleteProposal(k.id),this.events.off(T,b);const{cacaos:ce,responder:j}=C.result,J=[],he=[];for(const ye of ce){await Ph({cacao:ye,projectId:this.client.core.projectId})||(this.client.logger.error(ye,"Signature verification failed"),x(Ze("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ve}=ye,Ve=Wa(ve.resources),st=[ud(ve.iss)],ut=gc(ve.iss);if(Ve){const wt=xh(Ve),Fs=kh(Ve);J.push(...wt),st.push(...Fs)}for(const wt of st)he.push(`${wt}:${ut}`)}const ge=await this.client.core.crypto.generateSharedKey(_,j.publicKey);let xe;J.length>0&&(xe={topic:ge,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:j,controller:j.publicKey,expiry:rt(Zr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:N,namespaces:ip([...new Set(J)],[...new Set(he)]),transportType:o},await this.client.core.relayer.subscribe(ge,{transportType:o}),await this.client.session.set(ge,xe),N&&await this.client.core.pairing.updateMetadata({topic:N,metadata:j.metadata}),xe=this.client.session.get(ge)),(O=this.client.metadata.redirect)!=null&&O.linkMode&&(B=j.metadata.redirect)!=null&&B.linkMode&&(M=j.metadata.redirect)!=null&&M.universal&&n&&(this.client.core.addLinkModeSupportedApp(j.metadata.redirect.universal),this.client.session.update(ge,{transportType:Ke.link_mode})),V({auths:ce,session:xe})};this.events.once(T,b),this.events.once(y,S);let R;try{if(i){const C=Ks("wc_sessionAuthenticate",L,I);this.client.core.history.set(N,C);const O=await this.client.core.crypto.encode("",C,{type:la,encoding:Hn});R=Na(n,N,O)}else await Promise.all([this.sendRequest({topic:N,method:"wc_sessionAuthenticate",params:L,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:N,method:"wc_sessionPropose",params:k,expiry:vt.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:k.id})])}catch(C){throw this.events.off(T,b),this.events.off(y,S),C}return await this.setProposal(k.id,k),await this.setAuthRequest(I,{request:Ct(Be({},L),{verifyContext:{}}),pairingTopic:N,transportType:o}),{uri:R??A,response:q}}),H(this,"approveSessionAuthenticate",async s=>{const{id:n,auths:r}=s,i=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[ar.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw i.setError(Li.no_internet_connection),w}const o=this.getPendingAuthRequest(n);if(!o)throw i.setError(Li.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||Ke.relay;a===Ke.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),d=Ha(c),u={type:An,receiverPublicKey:c,senderPublicKey:l},h=[],p=[];for(const w of r){if(!await Ph({cacao:w,projectId:this.client.core.projectId})){i.setError(Li.invalid_cacao);const P=Ze("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:d,error:P,encodeOpts:u}),new Error(P.message)}i.addTrace(ar.cacaos_verified);const{p:v}=w,N=Wa(v.resources),A=[ud(v.iss)],_=gc(v.iss);if(N){const P=xh(N),U=kh(N);h.push(...P),A.push(...U)}for(const P of A)p.push(`${P}:${_}`)}const g=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(ar.create_authenticated_session_topic);let f;if((h==null?void 0:h.length)>0){f={topic:g,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:rt(Zr),authentication:r,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:ip([...new Set(h)],[...new Set(p)]),transportType:a},i.addTrace(ar.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(g,{transportType:a})}catch(w){throw i.setError(Li.subscribe_authenticated_session_topic_failure),w}i.addTrace(ar.subscribe_authenticated_session_topic_success),await this.client.session.set(g,f),i.addTrace(ar.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(ar.publishing_authenticated_session_approve);try{await this.sendResult({topic:d,id:n,result:{cacaos:r,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw i.setError(Li.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:f}}),H(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===Ke.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ha(o),l={type:An,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:r,encodeOpts:l,rpcOpts:vt.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)}),H(this,"formatAuthMessage",s=>{this.isInitialized();const{request:n,iss:r}=s;return zg(n,r)}),H(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)}),H(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)}}),H(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,Ze("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($p).catch(l=>this.client.logger.warn(l)),r===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Hs.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===r).map(l=>this.deletePendingSessionRequest(l.id,Ze("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:r})}),H(this,"deleteProposal",async(s,n)=>{if(n)try{const r=this.client.proposal.get(s),i=this.client.core.eventClient.getEvent({topic:r.pairingTopic});i==null||i.setError(or.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,Ze("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),H(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=Hs.idle,this.client.events.emit("session_request_expire",{id:s}))}),H(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)])}),H(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}))}),H(this,"setProposal",async(s,n)=>{this.client.core.expirer.set(s,rt(vt.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,n)}),H(this,"setAuthRequest",async(s,n)=>{const{request:r,pairingTopic:i,transportType:o=Ke.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})}),H(this,"setPendingSessionRequest",async s=>{const{id:n,topic:r,params:i,verifyContext:o}=s,a=i.request.expiryTimestamp||rt(vt.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})}),H(this,"sendRequest",async s=>{const{topic:n,method:r,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:d,tvf:u,publishOpts:h={}}=s,p=Ks(r,i,c);let g;const f=!!d;try{const N=f?Hn:Zt;g=await this.client.core.crypto.encode(n,p,{encoding:N})}catch(N){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),N}let w;if(mO.includes(r)){const N=vs(JSON.stringify(p)),A=vs(g);w=await this.client.core.verify.register({id:A,decryptedId:N})}const v=Be(Be({},vt[r].req),h);if(v.attestation=w,o&&(v.ttl=o),a&&(v.id=a),this.client.core.history.set(n,p),f){const N=Na(d,n,g);await Ce.Linking.openURL(N,this.client.name)}else v.tvf=Ct(Be({},u),{correlationId:p.id}),l?(v.internal=Ct(Be({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,g,v)):this.client.core.relayer.publish(n,g,v).catch(N=>this.client.logger.error(N));return p.id}),H(this,"sendProposeSession",async s=>{const{proposal:n,publishOpts:r}=s,i=Ks("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:Zt}),a=vs(JSON.stringify(i)),c=vs(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:Ct(Be({},r),{publishMethod:"wc_proposeSession",attestation:l})})}),H(this,"sendApproveSession",async s=>{const{sessionTopic:n,pairingProposalResponse:r,proposal:i,sessionSettleRequest:o,publishOpts:a}=s,c=oo(i.id,r),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:Zt}),d=Ks("wc_sessionSettle",o,a==null?void 0:a.id),u=await this.client.core.crypto.encode(n,d,{encoding:Zt});this.client.core.history.set(n,d),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:u},opts:Ct(Be({},a),{publishMethod:"wc_approveSession"})})}),H(this,"sendResult",async s=>{const{id:n,topic:r,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=oo(n,i);let d;const u=c&&typeof(Ce==null?void 0:Ce.Linking)<"u";try{const g=u?Hn:Zt;d=await this.client.core.crypto.encode(r,l,Ct(Be({},a||{}),{encoding:g}))}catch(g){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${r} failed`),g}let h,p;try{h=await this.client.core.history.get(r,n);const g=h.request;try{p=this.getTVFParams(n,g.params,i)}catch(f){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${f==null?void 0:f.message}`)}}catch(g){throw this.client.logger.error(`sendResult() -> history.get(${r}, ${n}) failed`),g}if(u){const g=Na(c,r,d);await Ce.Linking.openURL(g,this.client.name)}else{const g=h.request.method,f=vt[g].res;f.tvf=Ct(Be({},p),{correlationId:n}),o?(f.internal=Ct(Be({},f.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,d,f)):this.client.core.relayer.publish(r,d,f).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(l)}),H(this,"sendError",async s=>{const{id:n,topic:r,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=If(n,i);let d;const u=c&&typeof(Ce==null?void 0:Ce.Linking)<"u";try{const p=u?Hn:Zt;d=await this.client.core.crypto.encode(r,l,Ct(Be({},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(u){const p=Na(c,r,d);await Ce.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=a||vt[p].res;this.client.core.relayer.publish(r,d,g)}await this.client.core.history.resolve(l)}),H(this,"cleanup",async()=>{const s=[],n=[];this.client.session.getAll().forEach(r=>{let i=!1;Gs(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=>{Gs(r.expiryTimestamp)&&n.push(r.id)}),await Promise.all([...s.map(r=>this.deleteSession({topic:r})),...n.map(r=>this.deleteProposal(r))])}),H(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),H(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),H(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Hs.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=Hs.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Hs.idle}),H(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}`)}}),H(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}`)}}),H(this,"onRelayEventUnknownPayload",s=>{const{topic:n}=s,{message:r}=Y("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(r)}),H(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)}),H(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==null||l.setError(hn.proposal_listener_not_found)),this.isValidConnect(Be({},r.params));const d=a.expiryTimestamp||rt(vt.wc_sessionPropose.req.ttl),u=Be({id:c,pairingTopic:n,expiryTimestamp:d,attestation:i,encryptedId:o},a);await this.setProposal(c,u);const h=await this.getVerifyContext({attestationId:i,hash:vs(JSON.stringify(r)),encryptedId:o,metadata:u.proposer.metadata});l==null||l.addTrace(zs.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:h})}catch(l){await this.sendError({id:c,topic:n,error:l,rpcOpts:vt.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),H(this,"onSessionProposeResponse",async(s,n,r)=>{const{id:i}=n;if(dn(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 d=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(i,{sessionTopic:d,pairingTopic:s,proposalId:i,publicKey:c});const u=await this.client.core.relayer.subscribe(d,{transportType:r});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:s})}else if(Vs(n)){await this.deleteProposal(i);const o=Fe("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})}}),H(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:d,scopedProperties:u,sessionConfig:h,proposalRequestsResponses:p}=n.params,g=[...this.pendingSessions.values()].find(v=>v.sessionTopic===s);if(!g)return this.client.logger.error(`Pending session not found for topic ${s}`);const f=this.client.proposal.get(g.proposalId),w=Ct(Be(Be(Be({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:g.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.optionalNamespaces,controller:a.publicKey,self:{publicKey:g.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},d&&{sessionProperties:d}),u&&{scopedProperties:u}),h&&{sessionConfig:h}),{transportType:Ke.relay,authentication:p==null?void 0:p.authentication,walletPayResult:p==null?void 0:p.walletPay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:g.pairingTopic,metadata:w.peer.metadata}),this.pendingSessions.delete(g.proposalId),this.deleteProposal(g.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:n.id,topic:s,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:w}),this.events.emit(Fe("session_connect",g.proposalId),{session:w})}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),H(this,"onSessionSettleResponse",async(s,n)=>{const{id:r}=n;dn(n)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(Fe("session_approve",r),{})):Vs(n)&&(await this.client.session.delete(s,Ze("USER_DISCONNECTED")),this.events.emit(Fe("session_approve",r),{error:n.error}))}),H(this,"onSessionUpdateRequest",async(s,n)=>{const{params:r,id:i}=n;try{const o=`${s}_session_update`,a=$i.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:Ze("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Be({topic:s},r));try{$i.set(o,i),await this.client.session.update(s,{namespaces:r.namespaces}),await this.sendResult({id:i,topic:s,result:!0})}catch(c){throw $i.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)}}),H(this,"isRequestOutOfSync",(s,n)=>n.toString().slice(0,-3)<s.toString().slice(0,-3)),H(this,"onSessionUpdateResponse",(s,n)=>{const{id:r}=n,i=Fe("session_update",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);dn(n)?this.events.emit(Fe("session_update",r),{}):Vs(n)&&this.events.emit(Fe("session_update",r),{error:n.error})}),H(this,"onSessionExtendRequest",async(s,n)=>{const{id:r}=n;try{this.isValidExtend({topic:s}),await this.setExpiry(s,rt(Zr)),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)}}),H(this,"onSessionExtendResponse",(s,n)=>{const{id:r}=n,i=Fe("session_extend",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);dn(n)?this.events.emit(Fe("session_extend",r),{}):Vs(n)&&this.events.emit(Fe("session_extend",r),{error:n.error})}),H(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)}}),H(this,"onSessionPingResponse",(s,n)=>{const{id:r}=n,i=Fe("session_ping",r);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);dn(n)?this.events.emit(Fe("session_ping",r),{}):Vs(n)&&this.events.emit(Fe("session_ping",r),{error:n.error})},500)}),H(this,"onSessionDeleteRequest",async(s,n)=>{const{id:r}=n;try{await this.isValidDisconnect({topic:s,reason:n.params}),this.cleanupPendingSentRequestsForTopic({topic:s,error:Ze("USER_DISCONNECTED")}),await this.deleteSession({topic:s,id:r})}catch(i){this.client.logger.error(i)}}),H(this,"onSessionRequest",async s=>{var n,r,i;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:d}=s,{id:u,params:h}=a;try{await this.isValidRequest(Be({topic:o},h));const p=this.client.session.get(o),g=await this.getVerifyContext({attestationId:c,hash:vs(JSON.stringify(Ks("wc_sessionRequest",h,u))),encryptedId:l,metadata:p.peer.metadata,transportType:d}),f={id:u,topic:o,params:h,verifyContext:g};await this.setPendingSessionRequest(f),d===Ke.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(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(p){await this.sendError({id:u,topic:o,error:p}),this.client.logger.error(p)}}),H(this,"onSessionRequestResponse",(s,n)=>{const{id:r}=n,i=Fe("session_request",r);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);dn(n)?this.events.emit(Fe("session_request",r),{result:n.result}):Vs(n)&&this.events.emit(Fe("session_request",r),{error:n.error})}),H(this,"onSessionEventRequest",async(s,n)=>{const{id:r,params:i}=n;try{const o=`${s}_session_event_${i.event.name}`,a=$i.get(o);if(a&&this.isRequestOutOfSync(a,r)){this.client.logger.info(`Discarding out of sync request - ${r}`);return}this.isValidEmit(Be({topic:s},i)),this.client.events.emit("session_event",{id:r,topic:s,params:i}),$i.set(o,r)}catch(o){await this.sendError({id:r,topic:s,error:o}),this.client.logger.error(o)}}),H(this,"onSessionAuthenticateResponse",(s,n)=>{const{id:r}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:n}),dn(n)?this.events.emit(Fe("session_request",r),{result:n.result}):Vs(n)&&this.events.emit(Fe("session_request",r),{error:n.error})}),H(this,"onSessionAuthenticateRequest",async s=>{var n;const{topic:r,payload:i,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:d,expiryTimestamp:u}=i.params,h=await this.getVerifyContext({attestationId:o,hash:vs(JSON.stringify(i)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:r,id:i.id,authPayload:d,verifyContext:h,expiryTimestamp:u};await this.setAuthRequest(i.id,{request:p,pairingTopic:r,transportType:c}),c===Ke.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 d=i.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(i.params.requester.metadata,c),p={type:An,receiverPublicKey:d,senderPublicKey:u};await this.sendError({id:i.id,topic:r,error:l,encodeOpts:p,rpcOpts:vt.wc_sessionAuthenticate.autoReject,appLink:h})}}),H(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),H(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Hs.idle,this.processSessionRequestQueue()},Z.toMiliseconds(this.requestQueueDelay))}),H(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=>{this.events.emit(Fe("session_request",i.request.id),{error:n})})}),H(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Hs.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)}}),H(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=Hs.active,this.emittedSessionRequests.add(s.id),this.client.events.emit("session_request",s)}),H(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:Ks("wc_sessionPropose",Ct(Be({},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})}),H(this,"isValidConnect",async s=>{if(!Vt(s)){const{message:l}=Y("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(mt(n)||await this.isValidPairingTopic(n),!tN(c)){const{message:l}=Y("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(r&&!mt(r)&&en(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&&!mt(i)&&en(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),o&&!mt(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!mt(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(r||{}).concat(Object.keys(i||{}));if(!Object.keys(a).every(d=>l.includes(d.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)}`)}}),H(this,"validateNamespaces",(s,n)=>{const r=eN(s,"connect()",n);if(r)throw new Error(r.message)}),H(this,"isValidApprove",async s=>{if(!Vt(s))throw new Error(Y("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=_l(r,"approve()");if(l)throw new Error(l.message);const d=cp(c.requiredNamespaces,r,"approve()");if(d)throw new Error(d.message);if(!ot(i,!0)){const{message:u}=Y("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(u)}if(o&&!mt(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!mt(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(r));if(!Object.keys(a).every(h=>u.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),H(this,"isValidReject",async s=>{if(!Vt(s)){const{message:i}=Y("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(i)}const{id:n,reason:r}=s;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!nN(r)){const{message:i}=Y("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(r)}`);throw new Error(i)}}),H(this,"isValidSessionSettleRequest",s=>{if(!Vt(s)){const{message:l}=Y("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:n,controller:r,namespaces:i,expiry:o}=s;if(!Rm(n)){const{message:l}=Y("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=GI(r,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=_l(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Gs(o)){const{message:l}=Y("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),H(this,"isValidUpdate",async s=>{if(!Vt(s)){const{message:c}=Y("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=_l(r,"update()");if(o)throw new Error(o.message);const a=cp(i.requiredNamespaces,r,"update()");if(a)throw new Error(a.message)}),H(this,"isValidExtend",async s=>{if(!Vt(s)){const{message:r}=Y("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(r)}const{topic:n}=s;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),H(this,"isValidRequest",async s=>{if(!Vt(s)){const{message:c}=Y("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(!ap(a,i)){const{message:c}=Y("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!rN(r)){const{message:c}=Y("MISSING_OR_INVALID",`request() ${JSON.stringify(r)}`);throw new Error(c)}if(!aN(a,i,r.method)){const{message:c}=Y("MISSING_OR_INVALID",`request() method: ${r.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),H(this,"isValidRespond",async s=>{var n;if(!Vt(s)){const{message:a}=Y("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==null?void 0:s.response)!=null&&n.id&&this.cleanupAfterResponse(s),a}if(!iN(i)){const{message:a}=Y("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}=Y("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${i.id}, expected topic: ${o.topic}, received topic: ${r}`);throw new Error(a)}}),H(this,"isValidPing",async s=>{if(!Vt(s)){const{message:r}=Y("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),H(this,"isValidEmit",async s=>{if(!Vt(s)){const{message:a}=Y("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(!ap(o,i)){const{message:a}=Y("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!oN(r)){const{message:a}=Y("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}if(!cN(o,i,r.name)){const{message:a}=Y("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(r)}`);throw new Error(a)}}),H(this,"isValidDisconnect",async s=>{if(!Vt(s)){const{message:r}=Y("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(r)}const{topic:n}=s;await this.isValidSessionOrPairingTopic(n)}),H(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(!ot(r,!1))throw new Error("uri is required parameter");if(!ot(i,!1))throw new Error("domain is required parameter");if(!ot(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>_n(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=_n(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),H(this,"getVerifyContext",async s=>{const{attestationId:n,hash:r,encryptedId:i,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||Xi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Ke.link_mode){const d=this.getAppLinkIfEnabled(o,a);return c.verified.validation=d&&new URL(d).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}),H(this,"validateSessionProps",(s,n)=>{Object.values(s).forEach((r,i)=>{if(r==null){const{message:o}=Y("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${r} for key ${Object.keys(s)[i]}`);throw new Error(o)}})}),H(this,"getPendingAuthRequest",s=>{const n=this.client.auth.requests.get(s);return typeof n=="object"?n:void 0}),H(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)}}}),H(this,"checkRecentlyDeleted",s=>{const n=this.recentlyDeletedMap.get(s);if(n){const{message:r}=Y("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${s}`);throw new Error(r)}}),H(this,"isLinkModeEnabled",(s,n)=>{var r,i,o,a,c,l,d,u,h;return!s||n!==Ke.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)!==""&&((d=s==null?void 0:s.redirect)==null?void 0:d.universal)!==void 0&&((u=s==null?void 0:s.redirect)==null?void 0:u.universal)!==""&&((h=s==null?void 0:s.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(Ce==null?void 0:Ce.Linking)<"u"}),H(this,"getAppLinkIfEnabled",(s,n)=>{var r;return this.isLinkModeEnabled(s,n)?(r=s==null?void 0:s.redirect)==null?void 0:r.universal:void 0}),H(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const n=Eh(s,"topic")||"",r=decodeURIComponent(Eh(s,"wc_ev")||""),i=this.client.session.keys.includes(n);i&&this.client.session.update(n,{transportType:Ke.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:r,sessionExists:i})}),H(this,"registerLinkModeListeners",async()=>{var s;if(nu()||nr()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const n=Ce==null?void 0:Ce.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)}}}),H(this,"getTVFApproveParams",s=>{try{const n=Nm(s.namespaces),r=$I(s.namespaces),i=DI(s.namespaces),o=s.sessionProperties,a=s.scopedProperties;return{approvedChains:n,approvedMethods:r,approvedEvents:i,sessionProperties:o,scopedProperties:a}}catch(n){return this.client.logger.warn(n,"Error getting TVF approve params"),{}}}),H(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}),H(this,"isValidContractData",s=>{var n;if(!s)return!1;try{const r=(s==null?void 0:s.data)||((n=s==null?void 0: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}),H(this,"extractTxHashesFromResult",(s,n)=>{var r;try{if(!n)return[];const i=s.method,o=fO[i];if(i==="sui_signTransaction")return[AA(n.transactionBytes)];if(i==="near_signTransaction")return[Nh(n)];if(i==="near_signTransactions")return n.map(c=>Nh(c));if(i==="xrpl_signTransactionFor"||i==="xrpl_signTransaction")return[(r=n.tx_json)==null?void 0:r.hash];if(i==="polkadot_signTransaction")return[IN({transaction:s.params.transactionPayload,signature:n.signature})];if(i==="algo_signTxn")return Sn(n)?n.map(c=>Th(c)):[Th(n)];if(i==="cosmos_signDirect")return[IA(n)];if(i==="wallet_sendCalls")return NA(n);if(typeof n=="string")return[n];const a=n[o.key];if(Sn(a))return i==="solana_signAllTransactions"?a.map(c=>_A(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}=Y("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(it.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(Va)?this.client.auth.authKeys.get(Va):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,n,{receiverPublicKey:o,encoding:i===Ke.link_mode?Hn:Zt});Hd(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:r,transportType:i,encryptedId:vs(n)})):zd(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)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:i})),await this.client.core.relayer.messages.ack(s,n)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${n}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Es.expired,async e=>{const{topic:s,id:n}=Tg(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,Y("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,Y("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(pr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(pr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ot(e,!1)){const{message:s}=Y("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}=Y("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(Gs(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=Y("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!ot(e,!1)){const{message:s}=Y("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}=Y("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(Gs(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=Y("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=Y("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(ot(e,!1)){const{message:s}=Y("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=Y("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!sN(e)){const{message:s}=Y("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=Y("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(Gs(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=Y("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}validateRequestExpiry(e){if(e&&!uN(e,Rl)){const{message:s}=Y("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${Rl.min} and ${Rl.max}`);throw new Error(s)}}}class TO extends Wr{constructor(e,s){super(e,s,uO,gu),this.core=e,this.logger=s}}let RO=class extends Wr{constructor(e,s){super(e,s,hO,gu),this.core=e,this.logger=s}};class OO extends Wr{constructor(e,s){super(e,s,gO,gu,n=>n.id),this.core=e,this.logger=s}}class PO extends Wr{constructor(e,s){super(e,s,EO,Wc,()=>Va),this.core=e,this.logger=s}}class xO extends Wr{constructor(e,s){super(e,s,bO,Wc),this.core=e,this.logger=s}}class kO extends Wr{constructor(e,s){super(e,s,vO,Wc,n=>n.id),this.core=e,this.logger=s}}var UO=Object.defineProperty,$O=(t,e,s)=>e in t?UO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ol=(t,e,s)=>$O(t,typeof e!="symbol"?e+"":e,s);class DO{constructor(e,s){this.core=e,this.logger=s,Ol(this,"authKeys"),Ol(this,"pairingTopics"),Ol(this,"requests"),this.authKeys=new PO(this.core,this.logger),this.pairingTopics=new xO(this.core,this.logger),this.requests=new kO(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var LO=Object.defineProperty,MO=(t,e,s)=>e in t?LO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Oe=(t,e,s)=>MO(t,typeof e!="symbol"?e+"":e,s);class mu extends $C{constructor(e){super(e),Oe(this,"protocol",Km),Oe(this,"version",Gm),Oe(this,"name",Tl.name),Oe(this,"metadata"),Oe(this,"core"),Oe(this,"logger"),Oe(this,"events",new Mr.EventEmitter),Oe(this,"engine"),Oe(this,"session"),Oe(this,"proposal"),Oe(this,"pendingRequest"),Oe(this,"auth"),Oe(this,"signConfig"),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,"removeAllListeners",n=>this.events.removeAllListeners(n)),Oe(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"update",async n=>{try{return await this.engine.update(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"request",async n=>{try{return await this.engine.request(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"find",n=>{try{return this.engine.find(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),Oe(this,"authenticate",async(n,r)=>{try{return await this.engine.authenticate(n,r)}catch(i){throw this.logger.error(i.message),i}}),Oe(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),Oe(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(r){throw this.logger.error(r.message),r}}),this.name=(e==null?void 0:e.name)||Tl.name,this.metadata=m0(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const s=fu({logger:(e==null?void 0:e.logger)||Tl.logger,name:this.name});this.logger=s,this.core=(e==null?void 0:e.core)||new dO(e),this.session=new RO(this.core,this.logger),this.proposal=new TO(this.core,this.logger),this.pendingRequest=new OO(this.core,this.logger),this.engine=new NO(this),this.auth=new DO(this.core,this.logger)}static async init(e){const s=new mu(e);return await s.initialize(),s}get context(){return es(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 BO=mu;function yu(t){return t==null||typeof t!="object"&&typeof t!="function"}function Zm(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jm(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const jO="[object RegExp]",Xm="[object String]",Qm="[object Number]",ey="[object Boolean]",ty="[object Arguments]",FO="[object Symbol]",qO="[object Date]",WO="[object Map]",HO="[object Set]",zO="[object Array]",VO="[object ArrayBuffer]",KO="[object Object]",GO="[object DataView]",YO="[object Uint8Array]",ZO="[object Uint8ClampedArray]",JO="[object Uint16Array]",XO="[object Uint32Array]",QO="[object Int8Array]",eP="[object Int16Array]",tP="[object Int32Array]",sP="[object Float32Array]",nP="[object Float64Array]";function wu(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function rP(t,e){return ii(t,void 0,t,new Map,e)}function ii(t,e,s,n=new Map,r=void 0){const i=r==null?void 0:r(t,e,s,n);if(i!=null)return i;if(yu(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]=ii(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,ii(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(ii(a,void 0,s,n,r));return o}if(typeof Pe<"u"&&Pe.isBuffer(t))return t.subarray();if(wu(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);n.set(t,o);for(let a=0;a<t.length;a++)o[a]=ii(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),fr(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),fr(o,t,s,n,r),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return n.set(t,o),fr(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,fr(o,t,s,n,r),o}if(typeof t=="object"&&iP(t)){const o=Object.create(Object.getPrototypeOf(t));return n.set(t,o),fr(o,t,s,n,r),o}return t}function fr(t,e,s=t,n,r){const i=[...Object.keys(e),...Zm(e)];for(let o=0;o<i.length;o++){const a=i[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=ii(e[a],a,s,n,r))}}function iP(t){switch(Jm(t)){case ty:case zO:case VO:case GO:case ey:case qO:case sP:case nP:case QO:case eP:case tP:case WO:case Qm:case KO:case jO:case HO:case Xm:case FO:case YO:case ZO:case JO:case XO:return!0;default:return!1}}function oP(t,e){return rP(t,(s,n,r,i)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case Qm:case Xm:case ey:{const o=new t.constructor(t==null?void 0:t.valueOf());return fr(o,t),o}case ty:{const o={};return fr(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function Mp(t){return oP(t)}function Bp(t){return t!==null&&typeof t=="object"&&Jm(t)==="[object Arguments]"}function jp(t){return typeof t=="object"&&t!==null}function aP(){}function cP(t){return wu(t)}function lP(t){var s;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const n=t[Symbol.toStringTag];return n==null||!((s=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&s.writable)?!1:t.toString()===`[object ${n}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function dP(t){if(yu(t))return t;if(Array.isArray(t)||wu(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 uP(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=$d(r,o,n,new Map)}return r}function $d(t,e,s,n){if(yu(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(n.has(e))return dP(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),...Zm(e)];for(let i=0;i<r.length;i++){const o=r[i];let a=e[o],c=t[o];if(Bp(a)&&(a={...a}),Bp(c)&&(c={...c}),typeof Pe<"u"&&Pe.isBuffer(a)&&(a=Mp(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const d=[],u=Reflect.ownKeys(c);for(let h=0;h<u.length;h++){const p=u[h];d[p]=c[p]}c=d}else c=[];const l=s(c,a,o,t,e,n);l!=null?t[o]=l:Array.isArray(a)||jp(c)&&jp(a)?t[o]=$d(c,a,s,n):c==null&&lP(a)?t[o]=$d({},a,s,n):c==null&&cP(a)?t[o]=Mp(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function hP(t,...e){return uP(t,...e,aP)}const Fp="error",pP="wss://relay.walletconnect.org",fP="wc",sy="universal_provider",Ta=`${fP}@2:${sy}:`,ny="https://rpc.walletconnect.org/v1/",ry="generic",gP=`${ny}bundler`,di="call_status",mP=86400,Eu={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var yP=Object.defineProperty,wP=Object.defineProperties,EP=Object.getOwnPropertyDescriptors,qp=Object.getOwnPropertySymbols,bP=Object.prototype.hasOwnProperty,vP=Object.prototype.propertyIsEnumerable,Wp=(t,e,s)=>e in t?yP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ra=(t,e)=>{for(var s in e||(e={}))bP.call(e,s)&&Wp(t,s,e[s]);if(qp)for(var s of qp(e))vP.call(e,s)&&Wp(t,s,e[s]);return t},CP=(t,e)=>wP(t,EP(e));function iy(t,e,s){var n;const r=_n(t);return((n=e.rpcMap)==null?void 0:n[r.reference])||`${ny}?chainId=${r.namespace}:${r.reference}&projectId=${s}`}function _P(t){return t.includes(":")?t.split(":")[1]:t}function oy(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function AP(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 Hp(t){return Object.fromEntries(Object.entries(t).filter(([e,s])=>{var n,r;return((n=s==null?void 0:s.chains)==null?void 0:n.length)&&((r=s==null?void 0:s.chains)==null?void 0:r.length)>0}))}function Oa(t={},e={}){const s=Hp(zp(t)),n=Hp(zp(e));return hP(s,n)}function zp(t){var e,s,n,r,i;const o={};if(!en(t))return o;for(const[a,c]of Object.entries(t)){const l=Fc(a)?[a]:c.chains,d=c.methods||[],u=c.events||[],h=c.rpcMap||{},p=ri(a);o[p]=CP(Ra(Ra({},o[p]),c),{chains:Qs(l,(e=o[p])==null?void 0:e.chains),methods:Qs(d,(s=o[p])==null?void 0:s.methods),events:Qs(u,(n=o[p])==null?void 0:n.events)}),(en(h)||en(((r=o[p])==null?void 0:r.rpcMap)||{}))&&(o[p].rpcMap=Ra(Ra({},h),(i=o[p])==null?void 0:i.rpcMap))}return o}function Vp(t){return t.includes(":")?t.split(":")[2]:t}function Kp(t){const e={};for(const[s,n]of Object.entries(t)){const r=n.methods||[],i=n.events||[],o=n.accounts||[],a=Fc(s)?[s]:n.chains?n.chains:oy(n.accounts);e[s]={chains:a,methods:r,events:i,accounts:o}}return e}function Pl(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 SP(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const ay={},ui=t=>ay[t],xl=(t,e)=>{ay[t]=e};var IP=Object.defineProperty,Gp=Object.getOwnPropertySymbols,NP=Object.prototype.hasOwnProperty,TP=Object.prototype.propertyIsEnumerable,Yp=(t,e,s)=>e in t?IP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Zp=(t,e)=>{for(var s in e||(e={}))NP.call(e,s)&&Yp(t,s,e[s]);if(Gp)for(var s of Gp(e))TP.call(e,s)&&Yp(t,s,e[s]);return t};const Jp="eip155",RP=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],OP=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,kl=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Xp=t=>Object.keys(t).filter(e=>RP.includes(e)).reduce((e,s)=>(e[s]=PP(t[s]),e),{}),PP=t=>typeof t=="string"&&SP(t)?JSON.parse(t):t,xP=(t,e,s)=>{const{sessionProperties:n={},scopedProperties:r={}}=t,i={};if(!en(r)&&!en(n))return;const o=Xp(n);for(const a of s){const c=OP(a);if(!c)continue;i[kl(c)]=o;const l=r==null?void 0:r[`${Jp}:${c}`];if(l){const d=l==null?void 0:l[`${Jp}:${c}:${e}`];i[kl(c)]=Zp(Zp({},i[kl(c)]),Xp(d||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 kP=Object.defineProperty,UP=(t,e,s)=>e in t?kP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$P=(t,e,s)=>UP(t,e+"",s);let Ul;class bu{constructor(e){$P(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 Ul||(Ul=new bu(e)),Ul}}var DP=Object.defineProperty,LP=Object.defineProperties,MP=Object.getOwnPropertyDescriptors,Qp=Object.getOwnPropertySymbols,BP=Object.prototype.hasOwnProperty,jP=Object.prototype.propertyIsEnumerable,ef=(t,e,s)=>e in t?DP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,FP=(t,e)=>{for(var s in e||(e={}))BP.call(e,s)&&ef(t,s,e[s]);if(Qp)for(var s of Qp(e))jP.call(e,s)&&ef(t,s,e[s]);return t},qP=(t,e)=>LP(t,MP(e));async function WP(t,e){const s=_n(t.result.capabilities.caip345.caip2),n=t.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(n.map(u=>HP(s.reference,u,e))),i=r.filter(u=>u.status==="fulfilled").map(u=>u.value).filter(u=>u);r.filter(u=>u.status==="rejected").forEach(u=>console.warn("Failed to fetch transaction receipt:",u.reason));const o=!i.length||i.some(u=>!u),a=i.every(u=>(u==null?void 0:u.status)==="0x1"),c=i.every(u=>(u==null?void 0:u.status)==="0x0"),l=i.some(u=>(u==null?void 0:u.status)==="0x0");let d;return o?d=100:a?d=200:c?d=500:l&&(d=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:i,status:d}}async function HP(t,e,s){return await s(parseInt(t)).request(Ks("eth_getTransactionReceipt",[e]))}async function zP({sendCalls:t,storage:e}){const s=await e.getItem(di);await e.setItem(di,qP(FP({},s),{[t.result.id]:{request:t.request,result:t.result,expiry:rt(mP)}}))}async function VP({resultId:t,storage:e}){const s=await e.getItem(di);if(s){delete s[t],await e.setItem(di,s);for(const n in s)Gs(s[n].expiry)&&delete s[n];await e.setItem(di,s)}}async function KP({resultId:t,storage:e}){const s=await e.getItem(di),n=s==null?void 0:s[t];if(n&&!Gs(n.expiry))return n;await VP({resultId:t,storage:e})}var GP=Object.defineProperty,YP=Object.defineProperties,ZP=Object.getOwnPropertyDescriptors,tf=Object.getOwnPropertySymbols,JP=Object.prototype.hasOwnProperty,XP=Object.prototype.propertyIsEnumerable,Dd=(t,e,s)=>e in t?GP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$l=(t,e)=>{for(var s in e||(e={}))JP.call(e,s)&&Dd(t,s,e[s]);if(tf)for(var s of tf(e))XP.call(e,s)&&Dd(t,s,e[s]);return t},Dl=(t,e)=>YP(t,ZP(e)),cr=(t,e,s)=>Dd(t,typeof e!="symbol"?e+"":e,s);class QP{constructor(e){cr(this,"name","eip155"),cr(this,"client"),cr(this,"chainId"),cr(this,"namespace"),cr(this,"httpProviders"),cr(this,"events"),cr(this,"storage"),this.namespace=e.namespace,this.events=ui("events"),this.client=ui("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=bu.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(Eu.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||iy(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Wd(new Nf(n,ui("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(_P(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=Dl($l({},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),d=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{},u=`${a}${c.join(",")}`,h=d==null?void 0:d[u];if(h)return h;let p;try{p=xP(l,a,c)}catch(f){console.warn("Failed to extract capabilities from session",f)}if(p)return p;const g=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Dl($l({},l.sessionProperties||{}),{capabilities:Dl($l({},d||{}),{[u]:g})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return g}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(d){console.warn("Failed to fetch call status from bundler",d,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 KP({resultId:(r=e.request.params)==null?void 0:r[0],storage:this.storage});if(c)try{return await WP(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(Ks("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`${gP}?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==null?void 0:i.id,c=(i==null?void 0:i.capabilities)||{},l=(n=c==null?void 0:c.caip345)==null?void 0:n.caip2,d=(r=c==null?void 0:c.caip345)==null?void 0:r.transactionHashes;return!a||!l||!(d!=null&&d.length)||await zP({sendCalls:{request:o,result:i},storage:this.storage}),i}}var ex=Object.defineProperty,tx=(t,e,s)=>e in t?ex(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Jr=(t,e,s)=>tx(t,typeof e!="symbol"?e+"":e,s);class sx{constructor(e){Jr(this,"name",ry),Jr(this,"client"),Jr(this,"httpProviders"),Jr(this,"events"),Jr(this,"namespace"),Jr(this,"chainId"),this.namespace=e.namespace,this.events=ui("events"),this.client=ui("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(Eu.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 _n(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=_n(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=_n(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||iy(e,this.namespace,this.client.core.projectId);if(!n)throw new Error(`No RPC url provided for chainId: ${e}`);return new Wd(new Nf(n,ui("disableProviderPing")))}}var nx=Object.defineProperty,rx=Object.defineProperties,ix=Object.getOwnPropertyDescriptors,sf=Object.getOwnPropertySymbols,ox=Object.prototype.hasOwnProperty,ax=Object.prototype.propertyIsEnumerable,Ld=(t,e,s)=>e in t?nx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ji=(t,e)=>{for(var s in e||(e={}))ox.call(e,s)&&Ld(t,s,e[s]);if(sf)for(var s of sf(e))ax.call(e,s)&&Ld(t,s,e[s]);return t},Pa=(t,e)=>rx(t,ix(e)),os=(t,e,s)=>Ld(t,typeof e!="symbol"?e+"":e,s);let cx=class cy{constructor(e){os(this,"client"),os(this,"namespaces"),os(this,"optionalNamespaces"),os(this,"sessionProperties"),os(this,"scopedProperties"),os(this,"events",new Vd),os(this,"rpcProviders",{}),os(this,"session"),os(this,"providerOpts"),os(this,"logger"),os(this,"uri"),os(this,"disableProviderPing",!1),os(this,"connectParams");var s,n;this.providerOpts=e,this.logger=fu({logger:(s=e.logger)!=null?s:Fp,name:(n=this.providerOpts.name)!=null?n:sy}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const s=new cy(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:ji({},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,oo(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:Ze("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,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=Kp(this.session.namespaces);this.namespaces=Oa(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){var s,n;const{uri:r,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(s=this.connectParams)==null?void 0:s.authentication,walletPay:(n=this.connectParams)==null?void 0:n.walletPay});r&&(this.uri=r,this.events.emit("display_uri",r));const o=await i();this.session=o;const a=Kp(o.namespaces);return this.namespaces=Oa(this.namespaces,a),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(!Sn(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 BO.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Fp,relayUrl:this.providerOpts.relayUrl||pP,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=>ri(s)))];xl("client",this.client),xl("events",this.events),xl("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const n=AP(s,this.session);if((n==null?void 0:n.length)===0)return;const r=oy(n),i=Oa(this.namespaces,this.optionalNamespaces),o=Pa(ji({},i[s]),{accounts:n,chains:r});switch(s){case"eip155":this.rpcProviders[s]=new QP({namespace:o});break;default:this.rpcProviders[s]=new sx({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&&Sn(o)&&this.events.emit("accountsChanged",o.map(Vp))}else if(i.name==="chainChanged"){const o=n.chainId,a=n.event.data,c=ri(o),l=Pl(o)!==Pl(a)?`${c}:${Pl(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=Pa(ji({},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",Pa(ji({},Ze("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Eu.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(Pa(ji({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[ry]}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=Oa(s,n),this.sessionProperties=r,this.scopedProperties=i}validateChain(e){const[s,n]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,n];if(s&&!Object.keys(this.namespaces||{}).map(o=>ri(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=ri(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(Vp);if(!Sn(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.connectParams=void 0,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(`${Ta}/${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(`${Ta}/${e}${n}`)}async deleteFromStore(e){var s;const n=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${Ta}/${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(Ta)&&await this.client.core.storage.removeItem(n)}catch(s){this.logger.warn(s,"Failed to cleanup storage")}}};const nf=2147483648,lx={convertEVMChainIdToCoinType(t){if(t>=nf)throw new Error("Invalid chainId");return(nf|t)>>>0}},ys=Ge({suggestions:[],loading:!1}),dx={state:ys,subscribe(t){return _t(ys,()=>t(ys))},subscribeKey(t,e){return At(ys,t,e)},async resolveName(t){var e,s;try{return await fe.lookupEnsName(t)}catch(n){const r=n;throw new Error(((s=(e=r==null?void 0:r.reasons)==null?void 0:e[0])==null?void 0:s.description)||"Error resolving name")}},async isNameRegistered(t){try{return await fe.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{ys.loading=!0,ys.suggestions=[];const e=await fe.getEnsNameSuggestions(t);return ys.suggestions=e.suggestions||[],ys.suggestions}catch(e){const s=eo.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{ys.loading=!1}},async getNamesForAddress(t){try{if(!E.state.activeCaipNetwork)return[];const s=F.getEnsFromCacheForAddress(t);if(s)return s;const n=await fe.reverseLookupEnsName({address:t});return F.updateEnsCache({address:t,ens:n,timestamp:Date.now()}),n}catch(e){const s=eo.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){var r;const e=E.state.activeCaipNetwork,s=(r=E.getAccountData(e==null?void 0:e.chainNamespace))==null?void 0:r.address,n=z.getAuthConnector();if(!e)throw new Error("Network not found");if(!s||!n)throw new Error("Address or auth connector not found");ys.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});ue.pushTransactionStack({onCancel(){ue.replace("RegisterAccountName")}});const o=await G.signMessage(i);ys.loading=!1;const a=e.id;if(!a)throw new Error("Network not found");const c=lx.convertEVMChainIdToCoinType(Number(a));await fe.registerEnsName({coinType:c,address:s,signature:o,message:i}),E.setAccountProp("profileName",t,e.chainNamespace),F.updateEnsCache({address:s,ens:[{name:t,registered_at:new Date().toISOString(),updated_at:void 0,addresses:{},attributes:[]}],timestamp:Date.now()}),ue.replace("RegisterAccountNameSuccess")}catch(i){const o=eo.parseEnsApiError(i,`Error registering name ${t}`);throw ue.replace("RegisterAccountName"),new Error(o)}finally{ys.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){var n,r;const s=t;return((r=(n=s==null?void 0:s.reasons)==null?void 0:n[0])==null?void 0:r.description)||e}},eo=Ns(dx);function Md(t){try{return new URL(t)}catch{return null}}function ux(t){const e=t.split("/"),s=e.length>0&&e[0]!==void 0?e[0]:"",n=s.lastIndexOf(":");return n===-1?{host:s}:{host:s.slice(0,n),port:s.slice(n+1)}}function hx(t){const e=t.indexOf("://");if(e===-1)return null;const s=t.slice(0,e),n=e+3;let r=t.indexOf("/",n);r===-1&&(r=t.length);const i=t.slice(n,r),o=i.lastIndexOf(":");return o===-1?{scheme:s,host:i}:{scheme:s,host:i.slice(0,o),port:i.slice(o+1)}}function px(t,e){if(e.includes("://")){const o=Md(e);return o?o.origin===t:!1}const{host:s,port:n}=ux(e),r=t.indexOf("://");if(r!==-1){const o=r+3;let a=t.indexOf("/",o);a===-1&&(a=t.length);const c=t.slice(o,a);if(n!==void 0)return`${s}:${n}`===c;const l=c.split(":")[0];return s===l}const i=Md(t);return i?n!==void 0?s===i.hostname&&n===(i.port||void 0):s===i.hostname:!1}function fx(t,e,s){let n=s,r;const i=n.indexOf("://");i!==-1&&(r=n.slice(0,i),n=n.slice(i+3));const o=n.indexOf("/");o!==-1&&(n=n.slice(0,o));let a=n,c;const l=a.lastIndexOf(":");l!==-1&&(c=a.slice(l+1),a=a.slice(0,l));const d=a.split(".");for(const f of d)if(f.includes("*")&&f!=="*")return!1;const u=t.protocol.replace(/:$/u,"");if(r&&r!==u||c!==void 0&&c!=="*"&&c!==t.port)return!1;const h=hx(e),g=(h?h.host:t.hostname).split(".");if(d.length!==g.length)return!1;for(let f=d.length-1;f>=0;f-=1){const w=d[f],v=g[f];if(w!=="*"&&w!==v)return!1}return!0}const gx={ton:["ton_sendMessage","ton_signData"],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"]},Yn={RPC_ERROR_CODE:{USER_REJECTED:5e3,USER_REJECTED_METHODS:5002},getMethodsByChainNamespace(t){return gx[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}`,d=n[o];switch(d.chains.push(l),l){case"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":d.chains.push("solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ");break;case"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1":d.chains.push("solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K");break}return d!=null&&d.rpcMap&&c&&(d.rpcMap[i]=c),n},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{var n;const e=await eo.resolveName(t);return((n=(e!=null&&e.addresses?Object.values(e.addresses):[])[0])==null?void 0:n.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===Yn.RPC_ERROR_CODE.USER_REJECTED_METHODS,r=s&&e.code===Yn.RPC_ERROR_CODE.USER_REJECTED;return n||r}return!1}catch{return!1}},isOriginAllowed(t,e,s){const n=[...e,...s];if(e.length===0)return!0;const r=Md(t);if(!r)return n.some(i=>!i.includes("*")&&i===t);if(r.hostname==="localhost"||r.hostname==="127.0.0.1")return!0;for(const i of n)if(i.includes("*")){if(fx(r,t,i))return!0}else if(px(t,i))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=Yn.getWalletConnectAccounts(t,e);s(a)}),n&&t.on("disconnect",()=>{n()}),r&&t.on("accountsChanged",a=>{var c,l,d,u,h;try{const p=((d=(l=(c=t.session)==null?void 0:c.namespaces)==null?void 0:l[e])==null?void 0:d.accounts)||[],g=(h=(u=t.rpcProviders)==null?void 0:u[e])==null?void 0:h.getDefaultChain(),f=a.map(w=>{const v=p.find(_=>_.includes(`${e}:${g}:${w}`));if(!v)return;const{chainId:N,chainNamespace:A}=dt.parseCaipAddress(v);return{address:w,chainId:N,chainNamespace:A}}).filter(w=>w!==void 0);f.length>0&&r(f)}catch(p){console.warn("Failed to parse accounts for namespace on accountsChanged event",e,a,p)}}),i&&t.on("chainChanged",a=>{i(a)}),o&&t.on("display_uri",a=>{o(a)})},getWalletConnectAccounts(t,e){var r,i,o,a;const s=new Set,n=(a=(o=(i=(r=t==null?void 0:t.session)==null?void 0:r.namespaces)==null?void 0:i[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>dt.parseCaipAddress(c)).filter(({address:c})=>s.has(c.toLowerCase())?!1:(s.add(c.toLowerCase()),!0));return n&&n.length>0?n:[]}},mx=[$.CONNECTOR_ID.AUTH,$.CONNECTOR_ID.WALLET_CONNECT];class yx{constructor(e){this.availableConnectors=[],this.availableConnections=[],this.providerHandlers={},this.eventListeners=new Map,this.getCaipNetworks=s=>E.getCaipNetworks(s),this.getConnectorId=s=>z.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==null?void 0:s.toString()));e&&n&&this.addConnection({connectorId:$.CONNECTOR_ID.AUTH,accounts:e,caipNetwork:n})}setAuthProvider(e){e.onConnect(this.onAuthConnected.bind(this)),e.onSocialConnected(this.onAuthConnected.bind(this)),this.addConnector({id:$.CONNECTOR_ID.AUTH,type:"AUTH",name:$.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){E.setAccountProp("status",e,s)}on(e,s){var n;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(n=this.eventListeners.get(e))==null||n.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 Yn.isUserRejectedRequestError(s)?new Pf(s):s}}async switchNetwork(e){var i;const{caipNetwork:s}=e,n=He.getProviderId(s.chainNamespace),r=He.getProvider(s.chainNamespace);if(!r)throw new Error("Provider not found");if(n==="WALLET_CONNECT"){r.setDefaultChain(s.caipNetworkId);return}if(n==="AUTH"){const o=(i=z.getAuthConnector())==null?void 0:i.provider;if(!o)throw new Error("Auth provider not found");const a=us(s.chainNamespace);await o.switchNetwork({chainId:s.caipNetworkId});const c=await o.getUser({chainId:s.caipNetworkId,preferredAccountType:a});this.emit("switchNetwork",c)}}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}=X.getAccount(e[0]),i=this.getCaipNetworks().filter(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===(r==null?void 0: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}=X.getAccount(a);return{address:c}}),caipNetwork:i}))}}onAccountsChanged(e,s,n=!0){var r,i;if(e.length>0){const{address:o}=X.getAccount(e[0]),a=this.getConnection({connectorId:s,connections:this.connections,connectors:this.connectors});o&&((r=this.getConnectorId($.CHAIN.EVM))==null?void 0:r.toLowerCase())===s.toLowerCase()&&this.emit("accountChanged",{address:o,chainId:(i=a==null?void 0:a.caipNetwork)==null?void 0:i.id,connector:a==null?void 0:a.connector}),this.addConnection({connectorId:s,accounts:e.map(c=>{const{address:l}=X.getAccount(c);return{address:l}}),caipNetwork:a==null?void 0:a.caipNetwork})}else n&&this.onDisconnect(s)}onDisconnect(e){var s;this.removeProviderListeners(e),this.deleteConnection(e),((s=this.getConnectorId($.CHAIN.EVM))==null?void 0:s.toLowerCase())===e.toLowerCase()&&this.emitFirstAvailableConnection(),this.connections.length===0&&this.emit("disconnect")}onChainChanged(e,s){var o;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(a=>a.chainNamespace===this.namespace).find(a=>a.id.toString()===n);r&&this.addConnection({connectorId:s,accounts:r.accounts,caipNetwork:i}),((o=this.getConnectorId($.CHAIN.EVM))==null?void 0:o.toLowerCase())===s.toLowerCase()&&this.emit("switchNetwork",{chainId:n})}listenProviderEvents(e,s){if(mx.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(){var s;const e=this.getConnection({connections:this.connections,connectors:this.connectors});if(e){const[n]=e.accounts;this.emit("accountChanged",{address:n==null?void 0:n.address,chainId:(s=e.caipNetwork)==null?void 0:s.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 lr=null;const _s={getSIWX(){return D.state.siwx},async initializeIfEnabled(t=E.getActiveCaipAddress()){var i,o,a;const e=D.state.siwx;if(!(e&&t))return;const[s,n,r]=t.split(":");if(E.checkIfSupportedNetwork(s,`${s}:${n}`))try{if((i=D.state.remoteFeatures)!=null&&i.emailCapture){const l=(o=E.getAccountData(s))==null?void 0:o.user;await Te.open({view:"DataCapture",data:{email:(l==null?void 0:l.email)??void 0}});return}if(lr&&await lr,(await e.getSessions(`${s}:${n}`,r)).length)return;await Te.open({view:"SIWXSignMessage"})}catch(c){console.error("SIWXUtil:initializeIfEnabled",c),Ee.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(c)}),await((a=G._getClient())==null?void 0:a.disconnect().catch(console.error)),ue.reset("Connect"),Ys.showError("A problem occurred while trying initialize authentication")}},async isAuthenticated(t=E.getActiveCaipAddress()){if(!D.state.siwx||!t)return!0;const{chainNamespace:s,chainId:n,address:r}=dt.parseCaipAddress(t),i=`${s}:${n}`;return(await _s.getSessions({address:r,caipNetworkId:i})).length>0},async requestSignMessage(){const t=D.state.siwx,e=X.getPlainAddress(E.getActiveCaipAddress()),s=Hi();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");try{const n=await t.createMessage({chainId:s.caipNetworkId,accountAddress:e}),r=n.toString();let i="";t.signMessage?i=await t.signMessage({message:r,chainId:s.caipNetworkId,accountAddress:e}):(z.getConnectorId(s.chainNamespace)===$.CONNECTOR_ID.AUTH&&ue.pushTransactionStack({}),i=await G.signMessage(r)||""),await t.addSession({data:n,message:r,signature:i}),E.setLastConnectedSIWECaipNetwork(s),Te.close(),Ee.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(n){(!Te.state.open||ue.state.view==="ApproveTransaction")&&await Te.open({view:"SIWXSignMessage"}),Ys.showError("Error signing message"),Ee.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties(n)}),console.error("SWIXUtil:requestSignMessage",n)}},async cancelSignMessage(){var t;try{const e=this.getSIWX();if((t=e==null?void 0:e.getRequired)==null?void 0:t.call(e)){const n=E.getLastConnectedSIWECaipNetwork();if(n){const r=await(e==null?void 0:e.getSessions(n==null?void 0:n.caipNetworkId,X.getPlainAddress(E.getActiveCaipAddress())||""));r&&r.length>0?await E.switchActiveNetwork(n):await G.disconnect()}else await G.disconnect()}else Te.close();Te.close(),Ee.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(e){console.error("SIWXUtil:cancelSignMessage",e)}},async getAllSessions(){const t=this.getSIWX(),e=E.getAllRequestedCaipNetworks(),s=[];return await Promise.all(e.map(async n=>{const r=await(t==null?void 0:t.getSessions(n.caipNetworkId,X.getPlainAddress(E.getActiveCaipAddress())||""));r&&s.push(...r)})),s},async getSessions(t){const e=D.state.siwx;let s=t==null?void 0:t.address;if(!s){const r=E.getActiveCaipAddress();s=X.getPlainAddress(r)}let n=t==null?void 0:t.caipNetworkId;if(!n){const r=E.getActiveCaipNetwork();n=r==null?void 0:r.caipNetworkId}return e&&s&&n?e.getSessions(n,s):[]},async isSIWXCloseDisabled(){var e;const t=this.getSIWX();if(t){const s=ue.state.view==="ApproveTransaction",n=ue.state.view==="SIWXSignMessage";if(s||n)return((e=t.getRequired)==null?void 0:e.call(t))&&(await this.getSessions()).length===0}return!1},async authConnectorAuthenticate({authConnector:t,chainId:e,socialUri:s,preferredAccountType:n,chainNamespace:r}){var u;const i=_s.getSIWX(),o=Hi();if(!i||!r.includes($.CHAIN.EVM)||(u=D.state.remoteFeatures)!=null&&u.emailCapture){const h=await t.connect({chainId:e,socialUri:s,preferredAccountType:n});return{address:h.address,chainId:h.chainId,accounts:h.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()},d=await t.connect({chainId:e,socialUri:s,siwxMessage:l,preferredAccountType:n});return l.accountAddress=d.address,l.serializedMessage=d.message||"",d.signature&&d.message&&await _s.addEmbeddedWalletSession(l,d.message,d.signature),E.setLastConnectedSIWECaipNetwork(o),{address:d.address,chainId:d.chainId,accounts:d.accounts}},async addEmbeddedWalletSession(t,e,s){if(lr)return lr;const n=_s.getSIWX();return n?(lr=n.addSession({data:t,message:e,signature:s}).finally(()=>{lr=null}),lr):Promise.resolve()},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){var l,d,u;const n=_s.getSIWX(),r=Hi(),i=new Set(e.map(h=>h.split(":")[0]));if(!n||i.size!==1||!i.has("eip155"))return!1;const o=await n.createMessage({chainId:((l=Hi())==null?void 0:l.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(h=>h!==o.chainId)]});Ys.showLoading("Authenticating...",{autoClose:!1});const c={...a.session.peer.metadata,name:a.session.peer.metadata.name,icon:(d=a.session.peer.metadata.icons)==null?void 0:d[0],type:"WALLET_CONNECT"};if(E.setAccountProp("connectedWalletInfo",c,Array.from(i)[0]),(u=a==null?void 0:a.auths)!=null&&u.length){const h=a.auths.map(p=>{const g=t.client.formatAuthMessage({request:p.p,iss:p.p.iss});return{data:{...p.p,accountAddress:p.p.iss.split(":").slice(-1).join(""),chainId:p.p.iss.split(":").slice(2,4).join(":"),uri:p.p.aud??"",version:p.p.version||o.version,expirationTime:p.p.exp,issuedAt:p.p.iat,notBefore:p.p.nbf},message:g,signature:p.s.s,cacao:p}});try{await n.setSessions(h),r&&E.setLastConnectedSIWECaipNetwork(r),Ee.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:_s.getSIWXEventProperties()})}catch(p){throw console.error("SIWX:universalProviderAuth - failed to set sessions",p),Ee.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:_s.getSIWXEventProperties(p)}),await t.disconnect().catch(console.error),p}finally{Ys.hide()}}return!0},getSIWXEventProperties(t){var s;const e=E.state.activeChain;if(!e)throw new Error("SIWXUtil:getSIWXEventProperties - namespace is required");return{network:((s=E.state.activeCaipNetwork)==null?void 0:s.caipNetworkId)||"",isSmartAccount:us(e)===et.ACCOUNT_TYPES.SMART_ACCOUNT,message:t?X.parseError(t):void 0}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};class wx{constructor({provider:e,namespace:s}){this.id=$.CONNECTOR_ID.WALLET_CONNECT,this.name="WalletConnect",this.type="WALLET_CONNECT",this.imageId="ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",this.getCaipNetworks=E.getCaipNetworks.bind(E),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=D.state.universalProviderConfigOverride,r=Yn.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 _s.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:Ex})}}const Ex=["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"],Os=Ge({message:"",variant:"info",open:!1}),bx={state:Os,subscribeKey(t,e){return At(Os,t,e)},open(t,e){const{debug:s}=D.state,{code:n,displayMessage:r,debugMessage:i}=t;r&&s&&(Os.message=r,Os.variant=e,Os.open=!0),i&&console.error(typeof i=="function"?i():i,n?{code:n}:void 0)},warn(t,e,s){Os.open=!0,Os.message=t,Os.variant="warning",e&&console.warn(e,s)},close(){Os.open=!1,Os.message="",Os.variant="info"}},Ot=Ns(bx),vx={eip155:{native:{assetNamespace:"slip44",assetReference:"60"},defaultTokenNamespace:"erc20"},solana:{native:{assetNamespace:"slip44",assetReference:"501"},defaultTokenNamespace:"token"}};class Cx extends Error{}function _x(){const{sdkType:t,sdkVersion:e,projectId:s}=D.getSnapshot(),n=new URL("https://rpc.walletconnect.org/v1/json-rpc");return n.searchParams.set("projectId",s),n.searchParams.set("st",t),n.searchParams.set("sv",e),n.searchParams.set("source","fund-wallet"),n.toString()}async function vu(t,e){const s=_x(),{projectId:n}=D.getSnapshot(),r={jsonrpc:"2.0",id:1,method:t,params:{...e||{},projectId:n}},o=await(await fetch(s,{method:"POST",body:JSON.stringify(r),headers:{"Content-Type":"application/json"}})).json();if(o.error)throw new Cx(o.error.message);return o}async function q2(t){return(await vu("reown_getExchanges",t)).result}async function W2(t){return(await vu("reown_getExchangePayUrl",t)).result}async function H2(t){return(await vu("reown_getExchangeBuyStatus",t)).result}function z2(t,e){const{chainNamespace:s,chainId:n}=dt.parseCaipNetworkId(t),r=vx[s];if(!r)throw new Error(`Unsupported chain namespace for CAIP-19 formatting: ${s}`);let i=r.native.assetNamespace,o=r.native.assetReference;return e!=="native"&&(i=r.defaultTokenNamespace,o=e),`${`${s}:${n}`}/${i}:${o}`}const Ax={network:"eip155:1",asset:"native",metadata:{name:"Ethereum",symbol:"ETH",decimals:18}},Sx={network:"eip155:8453",asset:"native",metadata:{name:"Ethereum",symbol:"ETH",decimals:18}},ly={network:"eip155:8453",asset:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},Ix={asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e"},Nx={network:"eip155:84532",asset:"native",metadata:{name:"Ethereum",symbol:"ETH",decimals:18}},Tx={network:"eip155:1",asset:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},Rx={network:"eip155:42161",asset:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},Ox={network:"eip155:137",asset:"0x2791bca1f2de4661ed88a30c99a7a9449aa84174",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},Px={network:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",asset:"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",metadata:{name:"USD Coin",symbol:"USDC",decimals:6}},xx={network:"eip155:1",asset:"0xdAC17F958D2ee523a2206206994597C13D831ec7",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}},kx={network:"eip155:10",asset:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}},Ux={network:"eip155:42161",asset:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}},$x={network:"eip155:137",asset:"0xc2132d05d31c914a87c6611c10748aeb04b58e8f",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}},Dx={network:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",asset:"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB",metadata:{name:"Tether USD",symbol:"USDT",decimals:6}},Lx={network:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",asset:"native",metadata:{name:"Solana",symbol:"SOL",decimals:9}},Mx={ethereumETH:Ax,baseETH:Sx,baseUSDC:ly,baseSepoliaETH:Nx,ethereumUSDC:Tx,arbitrumUSDC:Rx,polygonUSDC:Ox,solanaUSDC:Px,ethereumUSDT:xx,optimismUSDT:kx,arbitrumUSDT:Ux,polygonUSDT:$x,solanaUSDT:Dx,solanaSOL:Lx};function V2(t){return Object.values(Mx).filter(e=>e.network===t)}const Us={getConnectorsByType(t,e,s){const{customWallets:n}=D.state,r=F.getRecentWallets(),i=Kn.filterOutDuplicateWallets(e),o=Kn.filterOutDuplicateWallets(s),a=t.filter(u=>u.type==="MULTI_CHAIN"),c=t.filter(u=>u.type==="ANNOUNCED"),l=t.filter(u=>u.type==="INJECTED"),d=t.filter(u=>u.type==="EXTERNAL");return{custom:n,recent:r,external:d,multiChain:a,announced:c,injected:l,recommended:i,featured:o}},showConnector(t){var r;const e=(r=t.info)==null?void 0:r.rdns,s=!!e&&te.state.excludedWallets.some(i=>!!i.rdns&&i.rdns===e),n=!!t.name&&te.state.excludedWallets.some(i=>Tf.isLowerCaseMatch(i.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!X.isMobile()||X.isMobile()&&!e&&!G.checkInstalled())||s||n)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||n))},getIsConnectedWithWC(){return Array.from(E.state.chains.values()).some(s=>z.getConnectorId(s.namespace)===$.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:n,announced:r,injected:i,multiChain:o,external:a,overriddenConnectors:c=(l=>(l=D.state.features)==null?void 0:l.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),h=new Set(u.map(f=>f.type)),p=c.filter(f=>h.has(f)).map(f=>({type:f,isEnabled:!0})),g=u.filter(({type:f})=>!p.some(({type:v})=>v===f));return Array.from(new Set([...p,...g].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){var e,s;try{if(t.name==="Browser Wallet"&&!X.isMobile())return{accounts:[],chainId:void 0};if(t.id===$.CONNECTOR_ID.AUTH)return{accounts:[],chainId:void 0};const[n,r]=await Promise.all([(e=t.provider)==null?void 0:e.request({method:"eth_accounts"}),(s=t.provider)==null?void 0:s.request({method:"eth_chainId"}).then(i=>Number(i))]);return{accounts:n,chainId:r}}catch(n){return console.warn(`Failed to fetch provider data for ${t.name}`,n),{accounts:[],chainId:void 0}}},getFilteredCustomWallets(t){const e=F.getRecentWallets(),s=z.state.connectors.map(o=>{var a;return(a=o.info)==null?void 0:a.rdns}).filter(Boolean),n=e.map(o=>o.rdns).filter(Boolean),r=s.concat(n);if(r.includes("io.metamask.mobile")&&X.isMobile()){const o=r.indexOf("io.metamask.mobile");r[o]="io.metamask"}return t.filter(o=>!r.includes(String(o==null?void 0:o.rdns)))},hasWalletConnector(t){return z.state.connectors.some(e=>e.id===t.id||e.name===t.name)},isWalletCompatibleWithCurrentChain(t){const e=E.state.activeChain;return e&&t.chains?t.chains.some(s=>{const n=s.split(":")[0];return e===n}):!0},getFilteredRecentWallets(){return F.getRecentWallets().filter(s=>!Kn.isExcluded(s)).filter(s=>!this.hasWalletConnector(s)).filter(s=>this.isWalletCompatibleWithCurrentChain(s))},getCappedRecommendedWallets(t){const{connectors:e}=z.state,{customWallets:s,featuredWalletIds:n}=D.state,r=e.find(N=>N.id==="walletConnect"),i=e.filter(N=>N.type==="INJECTED"||N.type==="ANNOUNCED"||N.type==="MULTI_CHAIN");if(!r&&!i.length&&!(s!=null&&s.length))return[];const o=Zl.isEmailEnabled(),a=Zl.isSocialsEnabled(),c=i.filter(N=>N.name!=="Browser Wallet"&&N.name!=="WalletConnect"),l=(n==null?void 0:n.length)||0,d=(s==null?void 0:s.length)||0,u=c.length||0,h=o?1:0,p=a?1:0,g=l+d+u+h+p,w=Math.max(0,4-g);return w<=0?[]:Kn.filterOutDuplicateWallets(t).slice(0,w)},processConnectorsByType(t,e=!0){const s=Us.sortConnectorsByExplorerWallet([...t]);return e?s.filter(Us.showConnector):s},connectorList(){const t=Us.getConnectorsByType(z.state.connectors,te.state.recommended,te.state.featured),e=this.processConnectorsByType(t.announced.filter(p=>p.id!=="walletConnect")),s=this.processConnectorsByType(t.injected),n=this.processConnectorsByType(t.multiChain.filter(p=>p.name!=="WalletConnect"),!1),r=t.custom,i=t.recent,o=this.processConnectorsByType(t.external.filter(p=>p.id!==$.CONNECTOR_ID.COINBASE_SDK&&p.id!==$.CONNECTOR_ID.BASE_ACCOUNT)),a=t.recommended,c=t.featured,l=Us.getConnectorTypeOrder({custom:r,recent:i,announced:e,injected:s,multiChain:n,recommended:a,featured:c,external:o}),d=z.state.connectors.find(p=>p.id==="walletConnect"),u=X.isMobile(),h=[];for(const p of l)switch(p){case"walletConnect":{!u&&d&&h.push({kind:"connector",subtype:"walletConnect",connector:d});break}case"recent":{Us.getFilteredRecentWallets().forEach(f=>h.push({kind:"wallet",subtype:"recent",wallet:f}));break}case"injected":{n.forEach(g=>h.push({kind:"connector",subtype:"multiChain",connector:g})),e.forEach(g=>h.push({kind:"connector",subtype:"announced",connector:g})),s.forEach(g=>h.push({kind:"connector",subtype:"injected",connector:g}));break}case"featured":{c.forEach(g=>h.push({kind:"wallet",subtype:"featured",wallet:g}));break}case"custom":{Us.getFilteredCustomWallets(r??[]).forEach(f=>h.push({kind:"wallet",subtype:"custom",wallet:f}));break}case"external":{o.forEach(g=>h.push({kind:"connector",subtype:"external",connector:g}));break}case"recommended":{Us.getCappedRecommendedWallets(a).forEach(f=>h.push({kind:"wallet",subtype:"recommended",wallet:f}));break}default:console.warn(`Unknown connector type: ${p}`)}return h},hasInjectedConnectors(){return z.state.connectors.filter(t=>(t.type==="INJECTED"||t.type==="ANNOUNCED"||t.type==="MULTI_CHAIN")&&t.name!=="Browser Wallet"&&t.name!=="WalletConnect").length}},Kn={filterOutDuplicatesByRDNS(t){const e=D.state.enableEIP6963?z.state.connectors:[],s=F.getRecentWallets(),n=e.map(a=>{var c;return(c=a.info)==null?void 0:c.rdns}).filter(Boolean),r=s.map(a=>a.rdns).filter(Boolean),i=n.concat(r);if(i.includes("io.metamask.mobile")&&X.isMobile()){const a=i.indexOf("io.metamask.mobile");i[a]="io.metamask"}return t.filter(a=>!(a!=null&&a.rdns&&i.includes(String(a.rdns))||!(a!=null&&a.rdns)&&e.some(l=>l.name===a.name)))},filterOutDuplicatesByIds(t){const e=z.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"||a.type==="MULTI_CHAIN"),s=F.getRecentWallets(),n=e.map(a=>{var c;return a.explorerId||((c=a.explorerWallet)==null?void 0:c.id)||a.id}),r=s.map(a=>a.id),i=n.concat(r);return t.filter(a=>!i.includes(a==null?void 0:a.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=z.state,{featuredWalletIds:s}=D.state,n=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>{var c;return(c=a.info)!=null&&c.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!=null&&s.length){const l=s.indexOf(o.id),d=s.indexOf(a.id);if(l!==-1&&d!==-1)return l-d;if(l!==-1)return-1;if(d!==-1)return 1}return 0})},getConnectOrderMethod(t,e){var c;const s=(t==null?void 0:t.connectMethodsOrder)||((c=D.state.features)==null?void 0:c.connectMethodsOrder),n=e||z.state.connectors;if(s)return s;const{injected:r,announced:i}=Us.getConnectorsByType(n,te.state.recommended,te.state.featured),o=r.filter(Us.showConnector),a=i.filter(Us.showConnector);return o.length||a.length?["wallet","email","social"]:Ne.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&te.state.excludedWallets.some(n=>n.rdns===t.rdns),s=!!t.name&&te.state.excludedWallets.some(n=>Tf.isLowerCaseMatch(n.name,t.name));return e||s},markWalletsWithDisplayIndex(t){return t.map((e,s)=>({...e,display_index:s}))},filterWalletsByWcSupport(t){return G.state.wcBasic?t.filter(e=>e.supports_wc):X.isMobile()?t.filter(e=>e.supports_wc||Ne.MANDATORY_WALLET_IDS_ON_MOBILE.includes(e.id)):t},getWalletConnectWallets(t){var i;const e=[...te.state.featured,...te.state.recommended];((i=te.state.filteredWallets)==null?void 0:i.length)>0?e.push(...te.state.filteredWallets):e.push(...t);const s=X.uniqueBy(e,"id"),n=Kn.markWalletsAsInstalled(s),r=Kn.filterWalletsByWcSupport(n);return Kn.markWalletsWithDisplayIndex(r)}},Lt={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",OKX_CONNECTOR_NAME:"OKX Wallet",BINANCE_CONNECTOR_NAME:"Binance Wallet",EIP155:$.CHAIN.EVM,ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"AUTH",getSDKVersionWarningMessage(t,e){return`
15
+ @@@@@@@ @@@@@@@@@@@@@@@@@@
16
+ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
17
+ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@
18
+ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
19
+ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@
20
+ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@
21
+ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@
22
+ @@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@
23
+ @@@@@@ @@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@
24
+ @@@@@@ @@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@
25
+ @@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@
26
+ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
27
+ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@
28
+ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
29
+ @@@@@ @@@@@@@@@@@@@@@@@@
30
+
31
+ AppKit SDK version ${t} is outdated. Latest version is ${e}. Please update to the latest version for bug fixes and new features.
32
+
33
+ Changelog: https://github.com/reown-com/appkit/releases
34
+ NPM Registry: https://www.npmjs.com/package/@reown/appkit`}},Bx={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","-239":"20f673c0-095e-49b2-07cf-eb5049dcf600","-3":"20f673c0-095e-49b2-07cf-eb5049dcf600"}},Ro={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,n])=>{e[`${Lt.EIP155}:${s}`]=n}),e},isLowerCaseMatch(t,e){return(t==null?void 0:t.toLowerCase())===(e==null?void 0:e.toLowerCase())},getActiveNamespaceConnectedToAuth(){const t=E.state.activeChain;return $.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(e=>z.getConnectorId(e)===$.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 $.CHAIN.EVM;const[e]=t.split(":");return e},getOtherAuthNamespaces(t){return t?$.AUTH_CONNECTOR_SUPPORTED_CHAINS.filter(n=>n!==t):[]},getConnectorStorageInfo(t,e){const n=F.getConnections()[e]??[];return{hasDisconnected:F.isConnectorDisconnected(t,e),hasConnected:n.some(r=>Ro.isLowerCaseMatch(r.connectorId,t))}}},jx=new AbortController,Pt={EmbeddedWalletAbortController:jx,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 ${Wi()?window.origin:"unknown"} is not in your allow list. Please update your allowed domains at https://dashboard.reown.com. [PID: ${D.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"}}},dy={TOKEN_ADDRESSES_BY_SYMBOL:{USDC:{8453:ly.asset,84532:Ix.asset}},getTokenSymbolByAddress(t){if(!t)return;const[e]=Object.entries(dy.TOKEN_ADDRESSES_BY_SYMBOL).find(([s,n])=>Object.values(n).includes(t))??[];return e}},Fx={createLogger(t,e="error"){const s=Yd({level:e}),{logger:n}=Rc({opts:s});return n.error=(...r)=>{for(const i of r)if(i instanceof Error){t(i,...r);return}t(void 0,...r)},n}};function qx(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function rf(t){return qx(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const uy="2.46.3";let Fi={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${uy}`};class Is extends Error{constructor(e,s={}){var a;const n=(()=>{var c;return s.cause instanceof Is?s.cause.details:(c=s.cause)!=null&&c.message?s.cause.message:s.details})(),r=s.cause instanceof Is&&s.cause.docsPath||s.docsPath,i=(a=Fi.getDocsUrl)==null?void 0:a.call(Fi,{...s,docsPath:r}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...Fi.version?[`Version: ${Fi.version}`]:[]].join(`
35
+ `);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=uy}walk(e){return hy(this,e)}}function hy(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?hy(t.cause,e):e?null:t}class py extends Is{constructor({size:e,targetSize:s,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}}function Wx(t,{dir:e,size:s=32}={}){return typeof t=="string"?Hx(t,{dir:e,size:s}):zx(t,{dir:e,size:s})}function Hx(t,{dir:e,size:s=32}={}){if(s===null)return t;const n=t.replace("0x","");if(n.length>s*2)throw new py({size:Math.ceil(n.length/2),targetSize:s,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function zx(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new py({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 Vx extends Is{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Kx(t,{size:e}){if(rf(t)>e)throw new Vx({givenSize:rf(t),maxSize:e})}const Gx=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Yx(t,e={}){let s="";for(let r=0;r<t.length;r++)s+=Gx[t[r]];const n=`0x${s}`;return typeof e.size=="number"?(Kx(n,{size:e.size}),Wx(n,{dir:"right",size:e.size})):n}const Zx=new TextEncoder;function Jx(t,e={}){const s=Zx.encode(t);return Yx(s,e)}class Xx 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 Nr=(t,e,s)=>JSON.stringify(t,(n,r)=>typeof r=="bigint"?r.toString():r,s),Cu=t=>t;class to extends Is{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: ${Cu(o)}`,e&&`Request body: ${Nr(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 fy extends Is{constructor({body:e,error:s,url:n}){super("RPC Request failed.",{cause:s,details:s.message,metaMessages:[`URL: ${Cu(n)}`,`Request body: ${Nr(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 of extends Is{constructor({body:e,url:s}){super("The request took too long to respond.",{details:"The request timed out.",metaMessages:[`URL: ${Cu(s)}`,`Request body: ${Nr(e)}`],name:"TimeoutError"}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.url=s}}const Qx=-1;class ss extends Is{constructor(e,{code:s,docsPath:n,metaMessages:r,name:i,shortMessage:o}){super(o,{cause:e,docsPath:n,metaMessages:r||(e==null?void 0: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 fy?e.code:s??Qx}}class ns extends ss{constructor(e,s){super(e,s),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=s.data}}class Oo extends ss{constructor(e){super(e,{code:Oo.code,name:"ParseRpcError",shortMessage:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."})}}Object.defineProperty(Oo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});class Po extends ss{constructor(e){super(e,{code:Po.code,name:"InvalidRequestRpcError",shortMessage:"JSON is not a valid request object."})}}Object.defineProperty(Po,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600});class xo extends ss{constructor(e,{method:s}={}){super(e,{code:xo.code,name:"MethodNotFoundRpcError",shortMessage:`The method${s?` "${s}"`:""} does not exist / is not available.`})}}Object.defineProperty(xo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});class ko extends ss{constructor(e){super(e,{code:ko.code,name:"InvalidParamsRpcError",shortMessage:["Invalid parameters were provided to the RPC method.","Double check you have provided the correct parameters."].join(`
36
+ `)})}}Object.defineProperty(ko,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});class wi extends ss{constructor(e){super(e,{code:wi.code,name:"InternalRpcError",shortMessage:"An internal error was received."})}}Object.defineProperty(wi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603});class Uo extends ss{constructor(e){super(e,{code:Uo.code,name:"InvalidInputRpcError",shortMessage:["Missing or invalid parameters.","Double check you have provided the correct parameters."].join(`
37
+ `)})}}Object.defineProperty(Uo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3});class $o extends ss{constructor(e){super(e,{code:$o.code,name:"ResourceNotFoundRpcError",shortMessage:"Requested resource not found."}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ResourceNotFoundRpcError"})}}Object.defineProperty($o,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001});class Do extends ss{constructor(e){super(e,{code:Do.code,name:"ResourceUnavailableRpcError",shortMessage:"Requested resource not available."})}}Object.defineProperty(Do,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});class Ei extends ss{constructor(e){super(e,{code:Ei.code,name:"TransactionRejectedRpcError",shortMessage:"Transaction creation failed."})}}Object.defineProperty(Ei,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003});class Cr extends ss{constructor(e,{method:s}={}){super(e,{code:Cr.code,name:"MethodNotSupportedRpcError",shortMessage:`Method${s?` "${s}"`:""} is not supported.`})}}Object.defineProperty(Cr,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});class bi extends ss{constructor(e){super(e,{code:bi.code,name:"LimitExceededRpcError",shortMessage:"Request exceeds defined limit."})}}Object.defineProperty(bi,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005});class Lo extends ss{constructor(e){super(e,{code:Lo.code,name:"JsonRpcVersionUnsupportedError",shortMessage:"Version of JSON-RPC protocol is not supported."})}}Object.defineProperty(Lo,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006});class Tr extends ns{constructor(e){super(e,{code:Tr.code,name:"UserRejectedRequestError",shortMessage:"User rejected the request."})}}Object.defineProperty(Tr,"code",{enumerable:!0,configurable:!0,writable:!0,value:4001});class Mo extends ns{constructor(e){super(e,{code:Mo.code,name:"UnauthorizedProviderError",shortMessage:"The requested method and/or account has not been authorized by the user."})}}Object.defineProperty(Mo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4100});class Bo extends ns{constructor(e,{method:s}={}){super(e,{code:Bo.code,name:"UnsupportedProviderMethodError",shortMessage:`The Provider does not support the requested method${s?` " ${s}"`:""}.`})}}Object.defineProperty(Bo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4200});class jo extends ns{constructor(e){super(e,{code:jo.code,name:"ProviderDisconnectedError",shortMessage:"The Provider is disconnected from all chains."})}}Object.defineProperty(jo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4900});class Fo extends ns{constructor(e){super(e,{code:Fo.code,name:"ChainDisconnectedError",shortMessage:"The Provider is not connected to the requested chain."})}}Object.defineProperty(Fo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4901});class qo extends ns{constructor(e){super(e,{code:qo.code,name:"SwitchChainError",shortMessage:"An error occurred when attempting to switch chain."})}}Object.defineProperty(qo,"code",{enumerable:!0,configurable:!0,writable:!0,value:4902});class Wo extends ns{constructor(e){super(e,{code:Wo.code,name:"UnsupportedNonOptionalCapabilityError",shortMessage:"This Wallet does not support a capability that was not marked as optional."})}}Object.defineProperty(Wo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5700});class Ho extends ns{constructor(e){super(e,{code:Ho.code,name:"UnsupportedChainIdError",shortMessage:"This Wallet does not support the requested chain ID."})}}Object.defineProperty(Ho,"code",{enumerable:!0,configurable:!0,writable:!0,value:5710});class zo extends ns{constructor(e){super(e,{code:zo.code,name:"DuplicateIdError",shortMessage:"There is already a bundle submitted with this ID."})}}Object.defineProperty(zo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5720});class Vo extends ns{constructor(e){super(e,{code:Vo.code,name:"UnknownBundleIdError",shortMessage:"This bundle id is unknown / has not been submitted"})}}Object.defineProperty(Vo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5730});class Ko extends ns{constructor(e){super(e,{code:Ko.code,name:"BundleTooLargeError",shortMessage:"The call bundle is too large for the Wallet to process."})}}Object.defineProperty(Ko,"code",{enumerable:!0,configurable:!0,writable:!0,value:5740});class Go extends ns{constructor(e){super(e,{code:Go.code,name:"AtomicReadyWalletRejectedUpgradeError",shortMessage:"The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."})}}Object.defineProperty(Go,"code",{enumerable:!0,configurable:!0,writable:!0,value:5750});class Yo extends ns{constructor(e){super(e,{code:Yo.code,name:"AtomicityNotSupportedError",shortMessage:"The wallet does not support atomic execution but the request requires it."})}}Object.defineProperty(Yo,"code",{enumerable:!0,configurable:!0,writable:!0,value:5760});class vi extends ns{constructor(e){super(e,{code:vi.code,name:"WalletConnectSessionSettlementError",shortMessage:"WalletConnect session settlement failed."})}}Object.defineProperty(vi,"code",{enumerable:!0,configurable:!0,writable:!0,value:7e3});class ek extends ss{constructor(e){super(e,{name:"UnknownRpcError",shortMessage:"An unknown RPC error occurred."})}}class _u extends Is{constructor({cause:e,message:s}={}){var r;const n=(r=s==null?void 0:s.replace("execution reverted: ",""))==null?void 0:r.replace("execution reverted","");super(`Execution reverted ${n?`with reason: ${n}`:"for an unknown reason"}.`,{cause:e,name:"ExecutionRevertedError"})}}Object.defineProperty(_u,"code",{enumerable:!0,configurable:!0,writable:!0,value:3});Object.defineProperty(_u,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/execution reverted|gas required exceeds allowance/});function tk(){let t=()=>{},e=()=>{};return{promise:new Promise((n,r)=>{t=n,e=r}),resolve:t,reject:e}}const Ll=new Map;function sk({fn:t,id:e,shouldSplitBatch:s,wait:n=0,sort:r}){const i=async()=>{const d=c();o();const u=d.map(({args:h})=>h);u.length!==0&&t(u).then(h=>{r&&Array.isArray(h)&&h.sort(r);for(let p=0;p<d.length;p++){const{resolve:g}=d[p];g==null||g([h[p],h])}}).catch(h=>{for(let p=0;p<d.length;p++){const{reject:g}=d[p];g==null||g(h)}})},o=()=>Ll.delete(e),a=()=>c().map(({args:d})=>d),c=()=>Ll.get(e)||[],l=d=>Ll.set(e,[...c(),d]);return{flush:o,async schedule(d){const{promise:u,resolve:h,reject:p}=tk();return(s==null?void 0:s([...a(),d]))&&i(),c().length>0?(l({args:d,resolve:h,reject:p}),u):(l({args:d,resolve:h,reject:p}),setTimeout(i,n),u)}}}async function gy(t){return new Promise(e=>setTimeout(e,t))}function nk(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 d=typeof e=="function"?e({count:a,error:l}):e;d&&await gy(d),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 Bd=256;let xa=Bd,ka;function rk(t=11){if(!ka||xa+t>Bd*2){ka="",xa=0;for(let e=0;e<Bd;e++)ka+=(256+Math.random()*256|0).toString(16).substring(1)}return ka.substring(xa,xa+++t)}const Ua=new Xx(8192);function ik(t,{enabled:e=!0,id:s}){if(!e||!s)return t();if(Ua.get(s))return Ua.get(s);const n=t().finally(()=>Ua.delete(s));return Ua.set(s,n),n}function ok(t,e={}){return async(s,n={})=>{var u;const{dedupe:r=!1,methods:i,retryDelay:o=150,retryCount:a=3,uid:c}={...e,...n},{method:l}=s;if((u=i==null?void 0:i.exclude)!=null&&u.includes(l))throw new Cr(new Error("method not supported"),{method:l});if(i!=null&&i.include&&!i.include.includes(l))throw new Cr(new Error("method not supported"),{method:l});const d=r?Jx(`${c}.${Nr(s)}`):void 0;return ik(()=>nk(async()=>{try{return await t(s)}catch(h){const p=h;switch(p.code){case Oo.code:throw new Oo(p);case Po.code:throw new Po(p);case xo.code:throw new xo(p,{method:s.method});case ko.code:throw new ko(p);case wi.code:throw new wi(p);case Uo.code:throw new Uo(p);case $o.code:throw new $o(p);case Do.code:throw new Do(p);case Ei.code:throw new Ei(p);case Cr.code:throw new Cr(p,{method:s.method});case bi.code:throw new bi(p);case Lo.code:throw new Lo(p);case Tr.code:throw new Tr(p);case Mo.code:throw new Mo(p);case Bo.code:throw new Bo(p);case jo.code:throw new jo(p);case Fo.code:throw new Fo(p);case qo.code:throw new qo(p);case Wo.code:throw new Wo(p);case Ho.code:throw new Ho(p);case zo.code:throw new zo(p);case Vo.code:throw new Vo(p);case Ko.code:throw new Ko(p);case Go.code:throw new Go(p);case Yo.code:throw new Yo(p);case 5e3:throw new Tr(p);case vi.code:throw new vi(p);default:throw h instanceof Is?h:new ek(p)}}},{delay:({count:h,error:p})=>{var g;if(p&&p instanceof to){const f=(g=p==null?void 0:p.headers)==null?void 0:g.get("Retry-After");if(f!=null&&f.match(/\d/))return Number.parseInt(f,10)*1e3}return~~(1<<h)*o},retryCount:a,shouldRetry:({error:h})=>ak(h)}),{enabled:r,id:d})}}function ak(t){return"code"in t&&typeof t.code=="number"?t.code===-1||t.code===bi.code||t.code===wi.code:t instanceof to&&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 ck(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==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&i(e),i(a)}finally{clearTimeout(o)}})()})}function lk(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const af=lk();function dk(t,e={}){const{url:s,headers:n}=uk(t);return{async request(r){var g;const{body:i,fetchFn:o=e.fetchFn??fetch,onRequest:a=e.onRequest,onResponse:c=e.onResponse,timeout:l=e.timeout??1e4}=r,d={...e.fetchOptions??{},...r.fetchOptions??{}},{headers:u,method:h,signal:p}=d;try{const f=await ck(async({signal:v})=>{const N={...d,body:Array.isArray(i)?Nr(i.map(U=>({jsonrpc:"2.0",id:U.id??af.take(),...U}))):Nr({jsonrpc:"2.0",id:i.id??af.take(),...i}),headers:{...n,"Content-Type":"application/json",...u},method:h||"POST",signal:p||(l>0?v:null)},A=new Request(s,N),_=await(a==null?void 0:a(A,N))??{...N,url:s};return await o(_.url??s,_)},{errorInstance:new of({body:i,url:s}),timeout:l,signal:!0});c&&await c(f);let w;if((g=f.headers.get("Content-Type"))!=null&&g.startsWith("application/json"))w=await f.json();else{w=await f.text();try{w=JSON.parse(w||"{}")}catch(v){if(f.ok)throw v;w={error:w}}}if(!f.ok)throw new to({body:i,details:Nr(w.error)||f.statusText,headers:f.headers,status:f.status,url:s});return w}catch(f){throw f instanceof to||f instanceof of?f:new to({body:i,cause:f,url:s})}}}}function uk(t){try{const e=new URL(t),s=(()=>{if(e.username){const n=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;return e.username="",e.password="",{url:e.toString(),headers:{Authorization:`Basic ${btoa(n)}`}}}})();return{url:e.toString(),...s}}catch{return{url:t}}}function my({key:t,methods:e,name:s,request:n,retryCount:r=3,retryDelay:i=150,timeout:o,type:a},c){const l=rk();return{config:{key:t,methods:e,name:s,request:n,retryCount:r,retryDelay:i,timeout:o,type:a},request:ok(n,{methods:e,retryCount:r,retryDelay:i,uid:l}),value:c}}function cf(t,e={}){const{key:s="fallback",name:n="Fallback",rank:r=!1,shouldThrow:i=hk,retryCount:o,retryDelay:a}=e;return({chain:c,pollingInterval:l=4e3,timeout:d,...u})=>{let h=t,p=()=>{};const g=my({key:s,name:n,async request({method:f,params:w}){let v;const N=async(A=0)=>{const _=h[A]({...u,chain:c,retryCount:0,timeout:d});try{const P=await _.request({method:f,params:w});return p({method:f,params:w,response:P,transport:_,status:"success"}),P}catch(P){if(p({error:P,method:f,params:w,transport:_,status:"error"}),i(P)||A===h.length-1||(v??(v=h.slice(A+1).some(U=>{const{include:L,exclude:W}=U({chain:c}).config.methods||{};return L?L.includes(f):W?!W.includes(f):!0})),!v))throw P;return N(A+1)}};return N()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:f=>p=f,transports:h.map(f=>f({chain:c,retryCount:0}))});if(r){const f=typeof r=="object"?r:{};pk({chain:c,interval:f.interval??l,onTransports:w=>h=w,ping:f.ping,sampleCount:f.sampleCount,timeout:f.timeout,transports:h,weights:f.weights})}return g}}function hk(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===Ei.code||t.code===Tr.code||t.code===vi.code||_u.nodeMessage.test(t.message)||t.code===5e3))}function pk({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,d=[],u=async()=>{const h=await Promise.all(o.map(async f=>{const w=f({chain:t,retryCount:0,timeout:i}),v=Date.now();let N,A;try{await(n?n({transport:w}):w.request({method:"net_listening"})),A=1}catch{A=0}finally{N=Date.now()}return{latency:N-v,success:A}}));d.push(h),d.length>r&&d.shift();const p=Math.max(...d.map(f=>Math.max(...f.map(({latency:w})=>w)))),g=o.map((f,w)=>{const v=d.map(U=>U[w].latency),A=1-v.reduce((U,L)=>U+L,0)/v.length/p,_=d.map(U=>U[w].success),P=_.reduce((U,L)=>U+L,0)/_.length;return P===0?[0,w]:[l*A+c*P,w]}).sort((f,w)=>w[0]-f[0]);s(g.map(([,f])=>o[f])),await gy(e),u()};u()}class fk extends Is{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 $a(t,e={}){const{batch:s,fetchFn:n,fetchOptions:r,key:i="http",methods:o,name:a="HTTP JSON-RPC",onFetchRequest:c,onFetchResponse:l,retryDelay:d,raw:u}=e;return({chain:h,retryCount:p,timeout:g})=>{const{batchSize:f=1e3,wait:w=0}=typeof s=="object"?s:{},v=e.retryCount??p,N=g??e.timeout??1e4,A=t||(h==null?void 0:h.rpcUrls.default.http[0]);if(!A)throw new fk;const _=dk(A,{fetchFn:n,fetchOptions:r,onRequest:c,onResponse:l,timeout:N});return my({key:i,methods:o,name:a,async request({method:P,params:U}){const L={method:P,params:U},{schedule:W}=sk({id:A,wait:w,shouldSplitBatch(x){return x.length>f},fn:x=>_.request({body:x}),sort:(x,I)=>x.id-I.id}),k=async x=>s?W(x):[await _.request({body:x})],[{error:q,result:V}]=await k(L);if(u)return{error:q,result:V};if(q)throw new fy({body:L,error:q,url:A});return V},retryCount:v,retryDelay:d,timeout:N,type:"http"},{fetchOptions:r,url:A})}}const gk="rpc.walletconnect.org";function lf(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 Ml=["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"],ei={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===gk}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:$.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${$.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){var r,i,o;const n=(o=(i=(r=t.rpcUrls)==null?void 0:r.default)==null?void 0:i.http)==null?void 0:o[0];return Ml.includes(e)?lf(e,s):n||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){var h,p,g,f,w,v,N;const r=this.getChainNamespace(t),i=this.getCaipNetworkId(t),o=(g=(p=(h=t.rpcUrls)==null?void 0:h.default)==null?void 0:p.http)==null?void 0:g[0],a=this.getDefaultRpcUrl(t,i,s),c=((v=(w=(f=t==null?void 0:t.rpcUrls)==null?void 0:f.chainDefault)==null?void 0:w.http)==null?void 0:v[0])||o,l=((N=n==null?void 0:n[i])==null?void 0:N.map(A=>A.url))||[],d=[...l,...a?[a]:[]],u=[...l];return c&&!u.includes(c)&&u.push(c),{...t,chainNamespace:r,caipNetworkId:i,assets:{imageId:Bx.NetworkImageIds[t.id],imageUrl:e==null?void 0:e[t.id]},rpcUrls:{...t.rpcUrls,default:{http:d},chainDefault:{http:u}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:n}){return t.map(r=>ei.extendCaipNetwork(r,{customNetworkImageUrls:e,customRpcUrls:n,projectId:s}))},getViemTransport(t,e,s){var r,i,o;const n=[];return s==null||s.forEach(a=>{n.push($a(a.url,a.config))}),Ml.includes(t.caipNetworkId)&&n.push($a(lf(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),(o=(i=(r=t==null?void 0:t.rpcUrls)==null?void 0:r.default)==null?void 0:i.http)==null||o.forEach(a=>{n.push($a(a))}),cf(n)},extendWagmiTransports(t,e,s){if(Ml.includes(t.caipNetworkId)){const n=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return cf([s,$a(n)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:$.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){var c;const e=F.getActiveCaipNetworkId(),s=E.getAllRequestedCaipNetworks(),n=Array.from(((c=E.state.chains)==null?void 0:c.keys())||[]),r=e==null?void 0:e.split(":")[0],i=r?n.includes(r):!1,o=s==null?void 0:s.find(l=>l.caipNetworkId===e);return i&&!o&&e?this.getUnsupportedNetwork(e):o||t||(s==null?void 0:s[0])}};class so{constructor(){}static getInstance({projectId:e,chainId:s,enableLogger:n,onTimeout:r,abortController:i,getActiveCaipNetwork:o,getCaipNetworks:a}){var u;const{metadata:c,sdkVersion:l,sdkType:d}=D.getSnapshot();return so.instance||(so.instance=new yv({projectId:e,chainId:s,enableLogger:n,onTimeout:r,abortController:i,getActiveCaipNetwork:o,getCaipNetworks:a,enableCloudAuthAccount:!!((u=D.state.remoteFeatures)!=null&&u.emailCapture),metadata:c,sdkVersion:l,sdkType:d})),so.instance}}/**
38
+ * @license
39
+ * Copyright 2019 Google LLC
40
+ * SPDX-License-Identifier: BSD-3-Clause
41
+ */const Ka=globalThis,Au=Ka.ShadowRoot&&(Ka.ShadyCSS===void 0||Ka.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Su=Symbol(),df=new WeakMap;let yy=class{constructor(e,s,n){if(this._$cssResult$=!0,n!==Su)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(Au&&e===void 0){const n=s!==void 0&&s.length===1;n&&(e=df.get(s)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&df.set(s,e))}return e}toString(){return this.cssText}};const ks=t=>new yy(typeof t=="string"?t:t+"",void 0,Su),zn=(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 yy(s,t,Su)},mk=(t,e)=>{if(Au)t.adoptedStyleSheets=e.map(s=>s instanceof CSSStyleSheet?s:s.styleSheet);else for(const s of e){const n=document.createElement("style"),r=Ka.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=s.cssText,t.appendChild(n)}},uf=Au?t=>t:t=>t instanceof CSSStyleSheet?(e=>{let s="";for(const n of e.cssRules)s+=n.cssText;return ks(s)})(t):t;/**
42
+ * @license
43
+ * Copyright 2017 Google LLC
44
+ * SPDX-License-Identifier: BSD-3-Clause
45
+ */const{is:yk,defineProperty:wk,getOwnPropertyDescriptor:Ek,getOwnPropertyNames:bk,getOwnPropertySymbols:vk,getPrototypeOf:Ck}=Object,Zn=globalThis,hf=Zn.trustedTypes,_k=hf?hf.emptyScript:"",Bl=Zn.reactiveElementPolyfillSupport,no=(t,e)=>t,jd={toAttribute(t,e){switch(e){case Boolean:t=t?_k: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}},wy=(t,e)=>!yk(t,e),pf={attribute:!0,type:String,converter:jd,reflect:!1,useDefault:!1,hasChanged:wy};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Zn.litPropertyMetadata??(Zn.litPropertyMetadata=new WeakMap);let ti=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,s=pf){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&&wk(this.prototype,e,r)}}static getPropertyDescriptor(e,s,n){const{get:r,set:i}=Ek(this.prototype,e)??{get(){return this[s]},set(o){this[s]=o}};return{get:r,set(o){const a=r==null?void 0:r.call(this);i==null||i.call(this,o),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??pf}static _$Ei(){if(this.hasOwnProperty(no("elementProperties")))return;const e=Ck(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(no("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(no("properties"))){const s=this.properties,n=[...bk(s),...vk(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(uf(r))}else e!==void 0&&s.push(uf(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(){var e;this._$ES=new Promise(s=>this.enableUpdating=s),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(s=>s(this))}addController(e){var s;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((s=e.hostConnected)==null||s.call(e))}removeController(e){var s;(s=this._$EO)==null||s.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 mk(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(s=>{var n;return(n=s.hostConnected)==null?void 0:n.call(s)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(s=>{var n;return(n=s.hostDisconnected)==null?void 0:n.call(s)})}attributeChangedCallback(e,s,n){this._$AK(e,n)}_$ET(e,s){var i;const n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&n.reflect===!0){const o=(((i=n.converter)==null?void 0:i.toAttribute)!==void 0?n.converter:jd).toAttribute(s,n.type);this._$Em=e,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(e,s){var i,o;const n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const a=n.getPropertyOptions(r),c=typeof a.converter=="function"?{fromAttribute:a.converter}:((i=a.converter)==null?void 0:i.fromAttribute)!==void 0?a.converter:jd;this._$Em=r;const l=c.fromAttribute(s,a.type);this[r]=l??((o=this._$Ej)==null?void 0:o.get(r))??l,this._$Em=null}}requestUpdate(e,s,n,r=!1,i){var o;if(e!==void 0){const a=this.constructor;if(r===!1&&(i=this[e]),n??(n=a.getPropertyOptions(e)),!((n.hasChanged??wy)(i,s)||n.useDefault&&n.reflect&&i===((o=this._$Ej)==null?void 0:o.get(e))&&!this.hasAttribute(a._$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??(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??(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(){var n;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[i,o]of this._$Ep)this[i]=o;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[i,o]of r){const{wrapped:a}=o,c=this[i];a!==!0||this._$AL.has(i)||c===void 0||this.C(i,void 0,o,c)}}let e=!1;const s=this._$AL;try{e=this.shouldUpdate(s),e?(this.willUpdate(s),(n=this._$EO)==null||n.forEach(r=>{var i;return(i=r.hostUpdate)==null?void 0:i.call(r)}),this.update(s)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(s)}willUpdate(e){}_$AE(e){var s;(s=this._$EO)==null||s.forEach(n=>{var r;return(r=n.hostUpdated)==null?void 0:r.call(n)}),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=this._$Eq.forEach(s=>this._$ET(s,this[s]))),this._$EM()}updated(e){}firstUpdated(e){}};ti.elementStyles=[],ti.shadowRootOptions={mode:"open"},ti[no("elementProperties")]=new Map,ti[no("finalized")]=new Map,Bl==null||Bl({ReactiveElement:ti}),(Zn.reactiveElementVersions??(Zn.reactiveElementVersions=[])).push("2.1.2");/**
46
+ * @license
47
+ * Copyright 2017 Google LLC
48
+ * SPDX-License-Identifier: BSD-3-Clause
49
+ */const ro=globalThis,ff=t=>t,vc=ro.trustedTypes,gf=vc?vc.createPolicy("lit-html",{createHTML:t=>t}):void 0,Ey="$lit$",Vn=`lit$${Math.random().toFixed(9).slice(2)}$`,by="?"+Vn,Ak=`<${by}>`,Lr=document,Zo=()=>Lr.createComment(""),Jo=t=>t===null||typeof t!="object"&&typeof t!="function",Iu=Array.isArray,Sk=t=>Iu(t)||typeof(t==null?void 0:t[Symbol.iterator])=="function",jl=`[
50
+ \f\r]`,qi=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,mf=/-->/g,yf=/>/g,dr=RegExp(`>|${jl}(?:([^\\s"'>=/]+)(${jl}*=${jl}*(?:[^
51
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),wf=/'/g,Ef=/"/g,vy=/^(?:script|style|textarea|title)$/i,Cy=t=>(e,...s)=>({_$litType$:t,strings:e,values:s}),Y2=Cy(1),Z2=Cy(2),Ci=Symbol.for("lit-noChange"),yt=Symbol.for("lit-nothing"),bf=new WeakMap,_r=Lr.createTreeWalker(Lr,129);function _y(t,e){if(!Iu(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return gf!==void 0?gf.createHTML(e):e}const Ik=(t,e)=>{const s=t.length-1,n=[];let r,i=e===2?"<svg>":e===3?"<math>":"",o=qi;for(let a=0;a<s;a++){const c=t[a];let l,d,u=-1,h=0;for(;h<c.length&&(o.lastIndex=h,d=o.exec(c),d!==null);)h=o.lastIndex,o===qi?d[1]==="!--"?o=mf:d[1]!==void 0?o=yf:d[2]!==void 0?(vy.test(d[2])&&(r=RegExp("</"+d[2],"g")),o=dr):d[3]!==void 0&&(o=dr):o===dr?d[0]===">"?(o=r??qi,u=-1):d[1]===void 0?u=-2:(u=o.lastIndex-d[2].length,l=d[1],o=d[3]===void 0?dr:d[3]==='"'?Ef:wf):o===Ef||o===wf?o=dr:o===mf||o===yf?o=qi:(o=dr,r=void 0);const p=o===dr&&t[a+1].startsWith("/>")?" ":"";i+=o===qi?c+Ak:u>=0?(n.push(l),c.slice(0,u)+Ey+c.slice(u)+Vn+p):c+Vn+(u===-2?a:p)}return[_y(t,i+(t[s]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]};class Xo{constructor({strings:e,_$litType$:s},n){let r;this.parts=[];let i=0,o=0;const a=e.length-1,c=this.parts,[l,d]=Ik(e,s);if(this.el=Xo.createElement(l,n),_r.currentNode=this.el.content,s===2||s===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(r=_r.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const u of r.getAttributeNames())if(u.endsWith(Ey)){const h=d[o++],p=r.getAttribute(u).split(Vn),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:i,name:g[2],strings:p,ctor:g[1]==="."?Tk:g[1]==="?"?Rk:g[1]==="@"?Ok:Hc}),r.removeAttribute(u)}else u.startsWith(Vn)&&(c.push({type:6,index:i}),r.removeAttribute(u));if(vy.test(r.tagName)){const u=r.textContent.split(Vn),h=u.length-1;if(h>0){r.textContent=vc?vc.emptyScript:"";for(let p=0;p<h;p++)r.append(u[p],Zo()),_r.nextNode(),c.push({type:2,index:++i});r.append(u[h],Zo())}}}else if(r.nodeType===8)if(r.data===by)c.push({type:2,index:i});else{let u=-1;for(;(u=r.data.indexOf(Vn,u+1))!==-1;)c.push({type:7,index:i}),u+=Vn.length-1}i++}}static createElement(e,s){const n=Lr.createElement("template");return n.innerHTML=e,n}}function _i(t,e,s=t,n){var o,a;if(e===Ci)return e;let r=n!==void 0?(o=s._$Co)==null?void 0:o[n]:s._$Cl;const i=Jo(e)?void 0:e._$litDirective$;return(r==null?void 0:r.constructor)!==i&&((a=r==null?void 0:r._$AO)==null||a.call(r,!1),i===void 0?r=void 0:(r=new i(t),r._$AT(t,s,n)),n!==void 0?(s._$Co??(s._$Co=[]))[n]=r:s._$Cl=r),r!==void 0&&(e=_i(t,r._$AS(t,e.values),r,n)),e}class Nk{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==null?void 0:e.creationScope)??Lr).importNode(s,!0);_r.currentNode=r;let i=_r.nextNode(),o=0,a=0,c=n[0];for(;c!==void 0;){if(o===c.index){let l;c.type===2?l=new ua(i,i.nextSibling,this,e):c.type===1?l=new c.ctor(i,c.name,c.strings,this,e):c.type===6&&(l=new Pk(i,this,e)),this._$AV.push(l),c=n[++a]}o!==(c==null?void 0:c.index)&&(i=_r.nextNode(),o++)}return _r.currentNode=Lr,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 ua{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,s,n,r){this.type=2,this._$AH=yt,this._$AN=void 0,this._$AA=e,this._$AB=s,this._$AM=n,this.options=r,this._$Cv=(r==null?void 0:r.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const s=this._$AM;return s!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=s.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,s=this){e=_i(this,e,s),Jo(e)?e===yt||e==null||e===""?(this._$AH!==yt&&this._$AR(),this._$AH=yt):e!==this._$AH&&e!==Ci&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Sk(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!==yt&&Jo(this._$AH)?this._$AA.nextSibling.data=e:this.T(Lr.createTextNode(e)),this._$AH=e}$(e){var i;const{values:s,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=Xo.createElement(_y(n.h,n.h[0]),this.options)),n);if(((i=this._$AH)==null?void 0:i._$AD)===r)this._$AH.p(s);else{const o=new Nk(r,this),a=o.u(this.options);o.p(s),this.T(a),this._$AH=o}}_$AC(e){let s=bf.get(e.strings);return s===void 0&&bf.set(e.strings,s=new Xo(e)),s}k(e){Iu(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 ua(this.O(Zo()),this.O(Zo()),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){var n;for((n=this._$AP)==null?void 0:n.call(this,!1,!0,s);e!==this._$AB;){const r=ff(e).nextSibling;ff(e).remove(),e=r}}setConnected(e){var s;this._$AM===void 0&&(this._$Cv=e,(s=this._$AP)==null||s.call(this,e))}}class Hc{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,s,n,r,i){this.type=1,this._$AH=yt,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=yt}_$AI(e,s=this,n,r){const i=this.strings;let o=!1;if(i===void 0)e=_i(this,e,s,0),o=!Jo(e)||e!==this._$AH&&e!==Ci,o&&(this._$AH=e);else{const a=e;let c,l;for(e=i[0],c=0;c<i.length-1;c++)l=_i(this,a[n+c],s,c),l===Ci&&(l=this._$AH[c]),o||(o=!Jo(l)||l!==this._$AH[c]),l===yt?e=yt:e!==yt&&(e+=(l??"")+i[c+1]),this._$AH[c]=l}o&&!r&&this.j(e)}j(e){e===yt?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Tk extends Hc{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===yt?void 0:e}}class Rk extends Hc{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==yt)}}class Ok extends Hc{constructor(e,s,n,r,i){super(e,s,n,r,i),this.type=5}_$AI(e,s=this){if((e=_i(this,e,s,0)??yt)===Ci)return;const n=this._$AH,r=e===yt&&n!==yt||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==yt&&(n===yt||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var s;typeof this._$AH=="function"?this._$AH.call(((s=this.options)==null?void 0:s.host)??this.element,e):this._$AH.handleEvent(e)}}class Pk{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){_i(this,e)}}const Fl=ro.litHtmlPolyfillSupport;Fl==null||Fl(Xo,ua),(ro.litHtmlVersions??(ro.litHtmlVersions=[])).push("3.3.2");const xk=(t,e,s)=>{const n=(s==null?void 0:s.renderBefore)??e;let r=n._$litPart$;if(r===void 0){const i=(s==null?void 0:s.renderBefore)??null;n._$litPart$=r=new ua(e.insertBefore(Zo(),i),i,void 0,s??{})}return r._$AI(t),r};/**
52
+ * @license
53
+ * Copyright 2017 Google LLC
54
+ * SPDX-License-Identifier: BSD-3-Clause
55
+ */const Rr=globalThis;class Ga extends ti{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var s;const e=super.createRenderRoot();return(s=this.renderOptions).renderBefore??(s.renderBefore=e.firstChild),e}update(e){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=xk(s,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return Ci}}var _f;Ga._$litElement$=!0,Ga.finalized=!0,(_f=Rr.litElementHydrateSupport)==null||_f.call(Rr,{LitElement:Ga});const ql=Rr.litElementPolyfillSupport;ql==null||ql({LitElement:Ga});(Rr.litElementVersions??(Rr.litElementVersions=[])).push("4.2.2");const kk={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)"},Cc={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"}},Uk={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"},Dk={regular:"KHTeka",mono:"KHTekaMono"},Lk={regular:"400",medium:"500"},Mk={h1:"50px",h2:"44px",h3:"38px",h4:"32px",h5:"26px",h6:"20px",large:"16px",medium:"14px",small:"12px"},Bk={"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"}},jk={"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)"},Fk={xl:"400ms",lg:"200ms",md:"125ms",sm:"75ms"},Fd={colors:kk,fontFamily:Dk,fontWeight:Lk,textSize:Mk,typography:Bk,tokens:{core:Cc.core,theme:Cc.dark},borderRadius:Uk,spacing:$k,durations:Fk,easings:jk},vf="--apkt";function Da(t){if(!t)return{};const e={};return e["font-family"]=t["--apkt-font-family"]??t["--w3m-font-family"]??"KHTeka",e.accent=t["--apkt-accent"]??t["--w3m-accent"]??"#0988F0",e["color-mix"]=t["--apkt-color-mix"]??t["--w3m-color-mix"]??"#000",e["color-mix-strength"]=t["--apkt-color-mix-strength"]??t["--w3m-color-mix-strength"]??0,e["font-size-master"]=t["--apkt-font-size-master"]??t["--w3m-font-size-master"]??"10px",e["border-radius-master"]=t["--apkt-border-radius-master"]??t["--w3m-border-radius-master"]??"4px",t["--apkt-z-index"]!==void 0?e["z-index"]=t["--apkt-z-index"]:t["--w3m-z-index"]!==void 0&&(e["z-index"]=t["--w3m-z-index"]),e}const gn={createCSSVariables(t){const e={},s={};function n(i,o,a=""){for(const[c,l]of Object.entries(i)){const d=a?`${a}-${c}`:c;l&&typeof l=="object"&&Object.keys(l).length?(o[c]={},n(l,o[c],d)):typeof l=="string"&&(o[c]=`${vf}-${d}`)}}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,d=i[a];c&&typeof c=="object"?n(c,d,l):typeof d=="string"&&(s[`${vf}-${l}`]=d)}}return n(t,e),s},createRootStyles(t,e){const s={...Fd,tokens:{...Fd.tokens,theme:t==="light"?Cc.light:Cc.dark}},{cssVariables:n}=gn.createCSSVariables(s),r=gn.assignCSSVariables(n,s),i=gn.generateW3MVariables(e),o=gn.generateW3MOverrides(e),a=gn.generateScaledVariables(e),c=gn.generateBaseVariables(r),l={...r,...c,...i,...o,...a},d=gn.applyColorMixToVariables(e,l),u={...l,...d};return`:root {${Object.entries(u).map(([p,g])=>`${p}:${g.replace("/[:;{}</>]/g","")};`).join("")}}`},generateW3MVariables(t){if(!t)return{};const e=Da(t),s={};return s["--w3m-font-family"]=e["font-family"],s["--w3m-accent"]=e.accent,s["--w3m-color-mix"]=e["color-mix"],s["--w3m-color-mix-strength"]=`${e["color-mix-strength"]}%`,s["--w3m-font-size-master"]=e["font-size-master"],s["--w3m-border-radius-master"]=e["border-radius-master"],s},generateW3MOverrides(t){if(!t)return{};const e=Da(t),s={};if(t["--apkt-accent"]||t["--w3m-accent"]){const n=e.accent;s["--apkt-tokens-core-iconAccentPrimary"]=n,s["--apkt-tokens-core-borderAccentPrimary"]=n,s["--apkt-tokens-core-textAccentPrimary"]=n,s["--apkt-tokens-core-backgroundAccentPrimary"]=n}return(t["--apkt-font-family"]||t["--w3m-font-family"])&&(s["--apkt-fontFamily-regular"]=e["font-family"]),e["z-index"]!==void 0&&(s["--apkt-tokens-core-zIndex"]=`${e["z-index"]}`),s},generateScaledVariables(t){if(!t)return{};const e=Da(t),s={};if(t["--apkt-font-size-master"]||t["--w3m-font-size-master"]){const n=parseFloat(e["font-size-master"].replace("px",""));s["--apkt-textSize-h1"]=`${Number(n)*5}px`,s["--apkt-textSize-h2"]=`${Number(n)*4.4}px`,s["--apkt-textSize-h3"]=`${Number(n)*3.8}px`,s["--apkt-textSize-h4"]=`${Number(n)*3.2}px`,s["--apkt-textSize-h5"]=`${Number(n)*2.6}px`,s["--apkt-textSize-h6"]=`${Number(n)*2}px`,s["--apkt-textSize-large"]=`${Number(n)*1.6}px`,s["--apkt-textSize-medium"]=`${Number(n)*1.4}px`,s["--apkt-textSize-small"]=`${Number(n)*1.2}px`}if(t["--apkt-border-radius-master"]||t["--w3m-border-radius-master"]){const n=parseFloat(e["border-radius-master"].replace("px",""));s["--apkt-borderRadius-1"]=`${Number(n)}px`,s["--apkt-borderRadius-2"]=`${Number(n)*2}px`,s["--apkt-borderRadius-3"]=`${Number(n)*3}px`,s["--apkt-borderRadius-4"]=`${Number(n)*4}px`,s["--apkt-borderRadius-5"]=`${Number(n)*5}px`,s["--apkt-borderRadius-6"]=`${Number(n)*6}px`,s["--apkt-borderRadius-8"]=`${Number(n)*8}px`,s["--apkt-borderRadius-16"]=`${Number(n)*16}px`,s["--apkt-borderRadius-20"]=`${Number(n)*20}px`,s["--apkt-borderRadius-32"]=`${Number(n)*32}px`,s["--apkt-borderRadius-64"]=`${Number(n)*64}px`,s["--apkt-borderRadius-128"]=`${Number(n)*128}px`}return s},generateColorMixCSS(t,e){if(!(t!=null&&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)) {
56
+ :root {
57
+ ${r.map(o=>{const a=(e==null?void 0: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("")}
58
+ }
59
+ }`},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={};e!=null&&e["--apkt-tokens-theme-backgroundPrimary"]&&(s["--apkt-tokens-theme-backgroundPrimary"]="var(--apkt-tokens-theme-backgroundPrimary-base)"),e!=null&&e["--apkt-tokens-core-backgroundAccentPrimary"]&&(s["--apkt-tokens-core-backgroundAccentPrimary"]="var(--apkt-tokens-core-backgroundAccentPrimary-base)");const n=Da(t),r=n["color-mix"],i=n["color-mix-strength"];if(!i||i===0)return s;const o=Object.keys(e||{}).filter(a=>{const c=a.includes("-tokens-core-background")||a.includes("-tokens-core-text")||a.includes("-tokens-core-border")||a.includes("-tokens-core-foreground")||a.includes("-tokens-core-icon")||a.includes("-tokens-theme-background")||a.includes("-tokens-theme-text")||a.includes("-tokens-theme-border")||a.includes("-tokens-theme-foreground")||a.includes("-tokens-theme-icon")||a.includes("-tokens-theme-overlay"),l=a.includes("-borderRadius-")||a.includes("-spacing-")||a.includes("-textSize-")||a.includes("-fontFamily-")||a.includes("-fontWeight-")||a.includes("-typography-")||a.includes("-duration-")||a.includes("-ease-")||a.includes("-path-")||a.includes("-width-")||a.includes("-height-")||a.includes("-visual-size-")||a.includes("-modal-width")||a.includes("-cover");return c&&!l});return o.length===0||o.forEach(a=>{const c=(e==null?void 0:e[a])||"";a.endsWith("-base")||(a==="--apkt-tokens-theme-backgroundPrimary"||a==="--apkt-tokens-core-backgroundAccentPrimary"?s[a]=`color-mix(in srgb, ${r} ${i}%, var(${a}-base))`:c.includes("color-mix")||c.startsWith("#")||c.startsWith("rgb")?s[a]=`color-mix(in srgb, ${r} ${i}%, ${c})`:s[a]=`color-mix(in srgb, ${r} ${i}%, var(${a}-base, ${c}))`)}),s}},{cssVariablesVarPrefix:qk}=gn.createCSSVariables(Fd);function J2(t,...e){return zn(t,...e.map(s=>ks(typeof s=="function"?s(qk):s)))}let gr,Ar,Js,ls,_c;const pn={"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 Ac(t,e="dark"){gr&&document.head.removeChild(gr),gr=document.createElement("style"),gr.textContent=gn.createRootStyles(e,t),document.head.appendChild(gr)}function X2(t,e="dark"){if(_c=t,Ar=document.createElement("style"),Js=document.createElement("style"),ls=document.createElement("style"),Ar.textContent=hi(t).core.cssText,Js.textContent=hi(t).dark.cssText,ls.textContent=hi(t).light.cssText,document.head.appendChild(Ar),document.head.appendChild(Js),document.head.appendChild(ls),Ac(t,e),qd(e),!((t==null?void 0:t["--apkt-font-family"])||(t==null?void 0:t["--w3m-font-family"])))for(const[n,r]of Object.entries(pn)){const i=document.createElement("link");i.rel="preload",i.href=r,i.as="font",i.type=n.includes("woff2")?"font/woff2":"font/woff",i.crossOrigin="anonymous",document.head.appendChild(i)}qd(e)}function qd(t="dark"){Js&&ls&&gr&&(t==="light"?(Ac(_c,t),Js.removeAttribute("media"),ls.media="enabled"):(Ac(_c,t),ls.removeAttribute("media"),Js.media="enabled"))}function Wk(t){var e,s,n;if(_c=t,Ar&&Js&&ls){Ar.textContent=hi(t).core.cssText,Js.textContent=hi(t).dark.cssText,ls.textContent=hi(t).light.cssText;const r=(t==null?void 0:t["--apkt-font-family"])||(t==null?void 0:t["--w3m-font-family"]);r&&(Ar.textContent=(e=Ar.textContent)==null?void 0:e.replace("font-family: KHTeka",`font-family: ${r}`),Js.textContent=(s=Js.textContent)==null?void 0:s.replace("font-family: KHTeka",`font-family: ${r}`),ls.textContent=(n=ls.textContent)==null?void 0:n.replace("font-family: KHTeka",`font-family: ${r}`))}if(gr){const r=(ls==null?void 0:ls.media)==="enabled"?"light":"dark";Ac(t,r)}}function hi(t){const e=!!(t!=null&&t["--apkt-font-family"]||t!=null&&t["--w3m-font-family"]);return{core:zn`
60
+ ${e?zn``:zn`
61
+ @font-face {
62
+ font-family: 'KHTeka';
63
+ src:
64
+ url(${ks(pn["KHTeka-400-woff2"])}) format('woff2'),
65
+ url(${ks(pn["KHTeka-400-woff"])}) format('woff');
66
+ font-weight: 400;
67
+ font-style: normal;
68
+ font-display: swap;
69
+ }
70
+
71
+ @font-face {
72
+ font-family: 'KHTeka';
73
+ src:
74
+ url(${ks(pn["KHTeka-300-woff2"])}) format('woff2'),
75
+ url(${ks(pn["KHTeka-300-woff"])}) format('woff');
76
+ font-weight: 300;
77
+ font-style: normal;
78
+ }
79
+
80
+ @font-face {
81
+ font-family: 'KHTekaMono';
82
+ src:
83
+ url(${ks(pn["KHTekaMono-400-woff2"])}) format('woff2'),
84
+ url(${ks(pn["KHTekaMono-400-woff"])}) format('woff');
85
+ font-weight: 400;
86
+ font-style: normal;
87
+ }
88
+
89
+ @font-face {
90
+ font-family: 'KHTeka';
91
+ src:
92
+ url(${ks(pn["KHTeka-400-woff2"])}) format('woff2'),
93
+ url(${ks(pn["KHTeka-400-woff"])}) format('woff');
94
+ font-weight: 400;
95
+ font-style: normal;
96
+ }
97
+ `}
98
+
99
+ @keyframes w3m-shake {
100
+ 0% {
101
+ transform: scale(1) rotate(0deg);
102
+ }
103
+ 20% {
104
+ transform: scale(1) rotate(-1deg);
105
+ }
106
+ 40% {
107
+ transform: scale(1) rotate(1.5deg);
108
+ }
109
+ 60% {
110
+ transform: scale(1) rotate(-1.5deg);
111
+ }
112
+ 80% {
113
+ transform: scale(1) rotate(1deg);
114
+ }
115
+ 100% {
116
+ transform: scale(1) rotate(0deg);
117
+ }
118
+ }
119
+ @keyframes w3m-iframe-fade-out {
120
+ 0% {
121
+ opacity: 1;
122
+ }
123
+ 100% {
124
+ opacity: 0;
125
+ }
126
+ }
127
+ @keyframes w3m-iframe-zoom-in {
128
+ 0% {
129
+ transform: translateY(50px);
130
+ opacity: 0;
131
+ }
132
+ 100% {
133
+ transform: translateY(0px);
134
+ opacity: 1;
135
+ }
136
+ }
137
+ @keyframes w3m-iframe-zoom-in-mobile {
138
+ 0% {
139
+ transform: scale(0.95);
140
+ opacity: 0;
141
+ }
142
+ 100% {
143
+ transform: scale(1);
144
+ opacity: 1;
145
+ }
146
+ }
147
+ :root {
148
+ --apkt-modal-width: 370px;
149
+
150
+ --apkt-visual-size-inherit: inherit;
151
+ --apkt-visual-size-sm: 40px;
152
+ --apkt-visual-size-md: 55px;
153
+ --apkt-visual-size-lg: 80px;
154
+
155
+ --apkt-path-network-sm: path(
156
+ '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'
157
+ );
158
+
159
+ --apkt-path-network-md: path(
160
+ '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'
161
+ );
162
+
163
+ --apkt-path-network-lg: path(
164
+ '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'
165
+ );
166
+
167
+ --apkt-width-network-sm: 36px;
168
+ --apkt-width-network-md: 48px;
169
+ --apkt-width-network-lg: 86px;
170
+
171
+ --apkt-duration-dynamic: 0ms;
172
+ --apkt-height-network-sm: 40px;
173
+ --apkt-height-network-md: 54px;
174
+ --apkt-height-network-lg: 96px;
175
+ }
176
+ `,dark:zn`
177
+ :root {
178
+ }
179
+ `,light:zn`
180
+ :root {
181
+ }
182
+ `}}const Q2=zn`
183
+ div,
184
+ span,
185
+ iframe,
186
+ a,
187
+ img,
188
+ form,
189
+ button,
190
+ label,
191
+ *::after,
192
+ *::before {
193
+ margin: 0;
194
+ padding: 0;
195
+ box-sizing: border-box;
196
+ font-style: normal;
197
+ text-rendering: optimizeSpeed;
198
+ -webkit-font-smoothing: antialiased;
199
+ -moz-osx-font-smoothing: grayscale;
200
+ -webkit-tap-highlight-color: transparent;
201
+ backface-visibility: hidden;
202
+ }
203
+
204
+ :host {
205
+ font-family: var(--apkt-fontFamily-regular);
206
+ }
207
+ `,eU=zn`
208
+ button,
209
+ a {
210
+ cursor: pointer;
211
+ display: flex;
212
+ justify-content: center;
213
+ align-items: center;
214
+ position: relative;
215
+
216
+ will-change: background-color, color, border, box-shadow, width, height, transform, opacity;
217
+ outline: none;
218
+ border: none;
219
+ text-decoration: none;
220
+ transition:
221
+ background-color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
222
+ color var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
223
+ border var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
224
+ box-shadow var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
225
+ width var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
226
+ height var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
227
+ transform var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
228
+ opacity var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
229
+ scale var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2),
230
+ border-radius var(--apkt-durations-lg) var(--apkt-easings-ease-out-power-2);
231
+ will-change:
232
+ background-color, color, border, box-shadow, width, height, transform, opacity, scale,
233
+ border-radius;
234
+ }
235
+
236
+ a:active:not([disabled]),
237
+ button:active:not([disabled]) {
238
+ scale: 0.975;
239
+ transform-origin: center;
240
+ }
241
+
242
+ button:disabled {
243
+ cursor: default;
244
+ }
245
+
246
+ input {
247
+ border: none;
248
+ outline: none;
249
+ appearance: none;
250
+ }
251
+ `,Gi={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603};class Hk extends yx{async setUniversalProvider(e){if(!this.namespace)throw new Error("UniversalAdapter:setUniversalProvider - namespace is required");return this.addConnector(new wx({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}){var r,i,o,a;const s=this.provider,n=((a=(o=(i=(r=s==null?void 0:s.session)==null?void 0:r.namespaces)==null?void 0:i[e])==null?void 0:o.accounts)==null?void 0:a.map(c=>{const[,,l]=c.split(":");return l}).filter((c,l,d)=>d.indexOf(c)===l))||[];return Promise.resolve({accounts:n.map(c=>X.createAccount(e,c,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){var o,a,c,l,d;if(!(e.caipNetwork&&Ne.BALANCE_SUPPORTED_CHAINS.includes((o=e.caipNetwork)==null?void 0:o.chainNamespace))||(a=e.caipNetwork)!=null&&a.testnet)return{balance:"0.00",symbol:((c=e.caipNetwork)==null?void 0:c.nativeCurrency.symbol)||""};const n=E.getAccountData();if(n!=null&&n.balanceLoading&&e.chainId===((l=E.state.activeCaipNetwork)==null?void 0:l.id))return{balance:(n==null?void 0:n.balance)||"0.00",symbol:(n==null?void 0:n.balanceSymbol)||""};const i=(await E.fetchTokenBalance()).find(u=>{var h,p;return u.chainId===`${(h=e.caipNetwork)==null?void 0:h.chainNamespace}:${e.chainId}`&&u.symbol===((p=e.caipNetwork)==null?void 0:p.nativeCurrency.symbol)});return{balance:(i==null?void 0:i.quantity.numeric)||"0.00",symbol:(i==null?void 0:i.symbol)||((d=e.caipNetwork)==null?void 0:d.nativeCurrency.symbol)||""}}async signMessage(e){var o,a,c;const{provider:s,message:n,address:r}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let i="";return((o=E.state.activeCaipNetwork)==null?void 0:o.chainNamespace)===$.CHAIN.SOLANA?i=(await s.request({method:"solana_signMessage",params:{message:Si.encode(new TextEncoder().encode(n)),pubkey:r}},(a=E.state.activeCaipNetwork)==null?void 0:a.caipNetworkId)).signature:i=await s.request({method:"personal_sign",params:[n,r]},(c=E.state.activeCaipNetwork)==null?void 0:c.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){var r,i,o,a,c,l;const{caipNetwork:s}=e,n=this.getWalletConnectConnector();if(s.chainNamespace===$.CHAIN.EVM)try{await((r=n.provider)==null?void 0:r.request({method:"wallet_switchEthereumChain",params:[{chainId:Nu(s.id)}]}))}catch(d){if(d.code===Gi.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||d.code===Gi.ERROR_INVALID_CHAIN_ID||d.code===Gi.ERROR_CODE_DEFAULT||((o=(i=d==null?void 0:d.data)==null?void 0:i.originalError)==null?void 0:o.code)===Gi.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await((l=n.provider)==null?void 0:l.request({method:"wallet_addEthereumChain",params:[{chainId:Nu(s.id),rpcUrls:[(a=s==null?void 0:s.rpcUrls.chainDefault)==null?void 0:a.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[(c=s.blockExplorers)==null?void 0:c.default.url]}]}))}catch{throw new Error("Chain is not supported")}}n.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){const e=this.connectors.find(n=>n.type==="WALLET_CONNECT");return e==null?void 0:e.provider}}const zk=["email","socials","swaps","onramp","activity","reownBranding","multiWallet","emailCapture","payWithExchange","payments","reownAuthentication","headless"],La={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?Ne.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&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?Ne.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?Ne.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?Ne.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?Ne.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!(t!=null&&t.config))return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?Ne.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?Ne.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?Ne.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?Ne.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:()=>Ne.DEFAULT_REMOTE_FEATURES.multiWallet},payWithExchange:{apiFeatureName:"fund_from_exchange",localFeatureName:"payWithExchange",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>Ne.DEFAULT_REMOTE_FEATURES.payWithExchange},payments:{apiFeatureName:"payments",localFeatureName:"payments",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>Ne.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"?Ne.DEFAULT_REMOTE_FEATURES.reownAuthentication:!!t},headless:{apiFeatureName:"headless",localFeatureName:"headless",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:()=>Ne.DEFAULT_REMOTE_FEATURES.headless}},Vk={localSettingsOverridden:new Set,getApiConfig(t,e){return e==null?void 0:e.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=La[e],n=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(n)}},processFeature(t,e,s,n,r){const i=La[t],o=e[i.localFeatureName];if(r&&!i.isAvailableOnBasic)return!1;if(n){const a=this.getApiConfig(i.apiFeatureName,s);return(a==null?void 0:a.config)===null?this.processFallbackFeature(t,o):a!=null&&a.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return La[t].processApi(e)},processFallbackFeature(t,e){return La[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 te.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?Ne.DEFAULT_REMOTE_FEATURES:Ne.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of zk){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),Ne.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.`;Ot.open({debugMessage:Pt.ALERT_WARNINGS.LOCAL_CONFIGURATION_IGNORED.debugMessage(o)},"warning")}return i}};class Kk{constructor(e){this.chainNamespaces=[],this.features={},this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,n)=>{var r,i,o;if(s){const a=(r=E.getCaipNetworks(s))==null?void 0:r.find(d=>d.id===n);if(a)return a;const c=(i=E.getNetworkData(s))==null?void 0:i.caipNetwork;return c||((o=E.getRequestedCaipNetworks(s).filter(d=>d.chainNamespace===s))==null?void 0:o[0])}return E.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>E.getCaipNetworks(s),this.getActiveChainNamespace=()=>E.state.activeChain,this.setRequestedCaipNetworks=(s,n)=>{E.setRequestedCaipNetworks(s,n)},this.getApprovedCaipNetworkIds=()=>E.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>{var n,r;return E.state.activeChain===s||!s?E.state.activeCaipAddress:(r=(n=E.state.chains.get(s))==null?void 0:n.accountState)==null?void 0:r.caipAddress},this.setClientId=s=>{fe.setClientId(s)},this.getProvider=s=>He.getProvider(s),this.getProviderType=s=>He.getProviderId(s),this.getPreferredAccountType=s=>us(s),this.setCaipAddress=(s,n,r=!1)=>{E.setAccountProp("caipAddress",s,n,r),E.setAccountProp("address",X.getPlainAddress(s),n,r)},this.setBalance=(s,n,r)=>{E.setAccountProp("balance",s,r),E.setAccountProp("balanceSymbol",n,r)},this.setProfileName=(s,n)=>{E.setAccountProp("profileName",s,n)},this.setProfileImage=(s,n)=>{E.setAccountProp("profileImage",s,n)},this.setUser=(s,n)=>{E.setAccountProp("user",s,n)},this.resetAccount=s=>{E.resetAccount(s)},this.setCaipNetwork=s=>{E.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,n)=>{E.setChainNetworkData(n,{caipNetwork:s})},this.setStatus=(s,n)=>{E.setAccountProp("status",s,n),z.isConnected()?F.setConnectionStatus("connected"):F.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>{var n;return(n=E.getAccountData(s))==null?void 0:n.address},this.setConnectors=s=>{const n=[...z.state.allConnectors,...s];z.setConnectors(n)},this.setConnections=(s,n)=>{F.setConnections(s,n),G.setConnections(s,n)},this.fetchIdentity=s=>fe.fetchIdentity(s),this.getReownName=s=>eo.getNamesForAddress(s),this.getConnectors=()=>z.getConnectors(),this.getConnectorImage=s=>Kf.getConnectorImage(s),this.getConnections=s=>this.remoteFeatures.multiWallet?cc.getConnectionsData(s).connections:(Ot.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.getRecentConnections=s=>this.remoteFeatures.multiWallet?cc.getConnectionsData(s).recentConnections:(Ot.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),[]),this.switchConnection=async s=>{if(!this.remoteFeatures.multiWallet){Ot.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}await G.switchConnection(s)},this.deleteConnection=s=>{if(!this.remoteFeatures.multiWallet){Ot.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info");return}F.deleteAddressFromConnection(s),G.syncStorageConnections()},this.setConnectedWalletInfo=(s,n)=>{const r=He.getProviderId(n),i=s?{...s,type:r}:void 0;E.setAccountProp("connectedWalletInfo",i,n)},this.getIsConnectedState=()=>!!E.state.activeCaipAddress,this.addAddressLabel=(s,n,r)=>{var o;const i=((o=E.getAccountData(r))==null?void 0:o.addressLabels)||{};E.setAccountProp("addressLabels",{...i,[s]:n},r)},this.removeAddressLabel=(s,n)=>{var i;const r=((i=E.getAccountData(n))==null?void 0:i.addressLabels)||{};E.setAccountProp("addressLabels",{...r,[s]:void 0},n)},this.getAddress=s=>{var r;const n=s||E.state.activeChain;return(r=E.getAccountData(n))==null?void 0:r.address},this.resetNetwork=s=>{E.resetNetwork(s)},this.addConnector=s=>{z.addConnector(s)},this.resetWcConnection=()=>{G.resetWcConnection()},this.setAddressExplorerUrl=(s,n)=>{E.setAccountProp("addressExplorerUrl",s,n)},this.setSmartAccountDeployed=(s,n)=>{E.setAccountProp("smartAccountDeployed",s,n)},this.setPreferredAccountType=(s,n)=>{E.setAccountProp("preferredAccountType",s,n)},this.setEIP6963Enabled=s=>{D.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==null?void 0:e.map(i=>i.namespace).filter(i=>!!i);if(n!=null&&n.length)return[...new Set(n)];const r=s==null?void 0:s.map(i=>i.chainNamespace);return[...new Set(r)]}async initialize(e){var s,n,r,i,o,a;if(this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),(s=e.features)!=null&&s.headless&&!Us.hasInjectedConnectors()&&te.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1,fetchWalletRanks:!1,fetchRecommendedWallets:!0}),D.state.enableReconnect?(await this.syncExistingConnection(),await this.syncAdapterConnections()):await this.unSyncExistingConnection(),!e.basic&&!e.manualWCControl&&(this.remoteFeatures=await Vk.fetchRemoteFeatures(e)),await te.fetchUsage(),D.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&ed.setOnrampProviders(this.remoteFeatures.onramp),((n=D.state.remoteFeatures)!=null&&n.email||Array.isArray((r=D.state.remoteFeatures)==null?void 0:r.socials)&&((i=D.state.remoteFeatures)==null?void 0:i.socials.length)>0)&&await this.checkAllowedOrigins(),(o=D.state.features)!=null&&o.reownAuthentication||(a=D.state.remoteFeatures)!=null&&a.reownAuthentication){const{ReownAuthentication:c}=await Dt(async()=>{const{ReownAuthentication:d}=await import("./features-CWGDlAbL.js");return{ReownAuthentication:d}},__vite__mapDeps([8,1,2,4,5,6,7])),l=D.state.siwx;l instanceof c||(l&&console.warn("ReownAuthentication option is enabled, SIWX configuration will be overridden."),D.setSIWX(new c))}}async openSend(e){var i;const s=e.namespace||E.state.activeChain,n=this.getCaipAddress(s),r=(i=this.getCaipNetwork(s))==null?void 0:i.id;if(!n)throw new Error("openSend: caipAddress not found");if((r==null?void 0:r.toString())!==e.chainId.toString()){const o=E.getCaipNetworkById(e.chainId,s);if(!o)throw new Error(`openSend: caipNetwork with chainId ${e.chainId} not found`);await this.switchNetwork(o,{throwOnFailure:!0})}try{const o=dy.getTokenSymbolByAddress(e.assetAddress);o&&await te.fetchTokenImages([o])}catch{}return await Te.open({view:"WalletSend",data:{send:e}}),new Promise((o,a)=>{const c=Ae.subscribeKey("hash",u=>{u&&(d(),o({hash:u}))}),l=Te.subscribe(u=>{u.open||(d(),a(new Error("Modal closed")))}),d=this.createCleanupHandler([c,l])})}toModalOptions(){function e(n){return(n==null?void 0:n.view)==="Swap"}function s(n){return(n==null?void 0:n.view)==="WalletSend"}return{isSwap:e,isSend:s}}async checkAllowedOrigins(){try{const e=await te.fetchAllowedOrigins();if(!X.isClient())return;const s=window.location.origin;Yn.isOriginAllowed(s,e,$.DEFAULT_ALLOWED_ANCESTORS)||Ot.open(Pt.ALERT_ERRORS.ORIGIN_NOT_ALLOWED,"error")}catch(e){if(!(e instanceof Error))return;switch(e.message){case"RATE_LIMITED":Ot.open(Pt.ALERT_ERRORS.RATE_LIMITED_APP_CONFIGURATION,"error");break;case"SERVER_ERROR":{const s=e.cause instanceof Error?e.cause:e;Ot.open({displayMessage:Pt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.displayMessage,debugMessage:Pt.ALERT_ERRORS.SERVER_ERROR_APP_CONFIGURATION.debugMessage(s.message)},"error");break}}}}createCleanupHandler(e){return()=>{e.forEach(s=>{try{s()}catch{}})}}sendInitializeEvent(e){var n;const{...s}=e;delete s.adapters,delete s.universalProvider,Ee.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(r=>r.id),siweConfig:{options:((n=e.siweConfig)==null?void 0:n.options)||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initAdapterController(){Zf.initialize(this.chainAdapters)}initializeThemeController(e){e.themeMode&&Kt.setThemeMode(e.themeMode),e.themeVariables&&Kt.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient)throw new Error("ConnectionControllerClient must be set");E.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient});const s=this.getDefaultNetwork();s&&E.setActiveCaipNetwork(s)}initializeConnectionController(e){G.initialize(e.adapters??[]),G.setWcBasic(e.basic??!1)}initializeConnectorController(){z.initialize(this.chainNamespaces)}initializeProjectSettings(e){D.setProjectId(e.projectId),D.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){var r;D.setDebug(e.debug!==!1),D.setEnableWalletGuide(e.enableWalletGuide!==!1),D.setEnableWallets(e.enableWallets!==!1),D.setEIP6963Enabled(e.enableEIP6963!==!1),D.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),D.setEnableReconnect(e.enableReconnect!==!1),D.setEnableMobileFullScreen(e.enableMobileFullScreen===!0),D.setCoinbasePreference(e.coinbasePreference),D.setEnableAuthLogger(e.enableAuthLogger!==!1),D.setCustomRpcUrls(e.customRpcUrls),D.setEnableEmbedded(e.enableEmbedded),D.setAllWallets(e.allWallets),D.setIncludeWalletIds(e.includeWalletIds),D.setExcludeWalletIds(e.excludeWalletIds),D.setFeaturedWalletIds(e.featuredWalletIds),D.setTokens(e.tokens),D.setTermsConditionsUrl(e.termsConditionsUrl),D.setPrivacyPolicyUrl(e.privacyPolicyUrl),D.setCustomWallets(e.customWallets),D.setFeatures(e.features),D.setAllowUnsupportedChain(e.allowUnsupportedChain),D.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),D.setPreferUniversalLinks(e.experimental_preferUniversalLinks),D.setDefaultAccountTypes(e.defaultAccountTypes);const s=this.getDefaultMetaData();if(!e.metadata&&s&&(e.metadata=s),D.setMetadata(e.metadata),D.setDisableAppend(e.disableAppend),D.setEnableEmbedded(e.enableEmbedded),D.setSIWX(e.siwx),this.features=D.state.features??{},!e.projectId){Ot.open(Pt.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(((r=e.adapters)==null?void 0:r.find(i=>i.namespace===$.CHAIN.EVM))&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");D.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){var e,s,n,r;return X.isClient()?{name:((s=(e=document.getElementsByTagName("title"))==null?void 0:e[0])==null?void 0:s.textContent)||"",description:((n=document.querySelector('meta[property="og:description"]'))==null?void 0:n.content)||"",url:window.location.origin,icons:[((r=document.querySelector('link[rel~="icon"]'))==null?void 0:r.href)||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const n=ei.getUnsupportedNetwork(`${s}:${e}`);E.setActiveCaipNetwork(n)}}getDefaultNetwork(){return ei.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,s){return ei.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return ei.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(r=>{var i;return r.id===((i=e.defaultNetwork)==null?void 0:i.id)});return s?ei.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectConnector(e,s){var n,r;try{this.setLoading(!0,e);let i={connections:[]};const o=this.getAdapter(e);return(((r=(n=E.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.caipAddress)||!D.state.enableReconnect)&&(o!=null&&o.disconnect)&&(i=await o.disconnect({id:s})),this.setLoading(!1,e),i}catch(i){throw this.setLoading(!1,e),new Error(`Failed to disconnect chains: ${i.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{var l;const e=E.state.activeChain,s=this.getAdapter(e),n=(l=this.getCaipNetwork(e))==null?void 0:l.id,r=G.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==null?void 0:a.clientId)||null),F.setConnectedNamespaces([...E.state.chains.keys()]),await this.syncWalletConnectAccount(),await _s.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})=>{var a;const i=E.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!=null&&o.reconnect&&(await(o==null?void 0:o.reconnect({id:e,info:s,type:n,provider:r,chainId:(a=this.getCaipNetwork())==null?void 0:a.id})),F.addConnectedNamespace(i),this.syncConnectedWalletInfo(i))},disconnectConnector:async e=>{await this.disconnectConnector(e.namespace,e.id)},disconnect:async e=>{var l;const{id:s,chainNamespace:n,initialDisconnect:r}=e||{},i=n||E.state.activeChain,o=z.getConnectorId(i),a=s===$.CONNECTOR_ID.AUTH||o===$.CONNECTOR_ID.AUTH,c=s===$.CONNECTOR_ID.WALLET_CONNECT||o===$.CONNECTOR_ID.WALLET_CONNECT;try{const d=Array.from(E.state.chains.keys());let u=n?[n]:d;(c||a)&&(u=d);const h=u.map(async f=>{const w=z.getConnectorId(f),v=s||w,N=await this.disconnectConnector(f,v);N&&(a&&F.deleteConnectedSocialProvider(),N.connections.forEach(A=>{F.addDisconnectedConnectorId(A.connectorId,f)})),r&&this.onDisconnectNamespace({chainNamespace:f,closeModal:!1})}),p=await Promise.allSettled(h);Ae.resetSend(),G.resetWcConnection(),(l=_s.getSIWX())!=null&&l.signOutOnDisconnect&&await _s.clearSessions(),z.setFilterByNamespace(void 0),G.syncStorageConnections();const g=p.filter(f=>f.status==="rejected");if(g.length>0)throw new Error(g.map(f=>f.reason.message).join(", "));Ee.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:n||"all"}})}catch(d){throw new Error(`Failed to disconnect chains: ${d.message}`)}},checkInstalled:e=>e?e.some(s=>{var n;return!!((n=window.ethereum)!=null&&n[String(s)])}):!!window.ethereum,signMessage:async e=>{const s=E.state.activeChain,n=this.getAdapter(E.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");const i=await(n==null?void 0:n.signMessage({message:e,address:r,provider:He.getProvider(s)}));return(i==null?void 0:i.signature)||""},sendTransaction:async e=>{const s=e.chainNamespace;if(!s)throw new Error("sendTransaction: namespace not found");if(Ne.SEND_SUPPORTED_NAMESPACES.includes(s)){const n=this.getAdapter(s);if(!n)throw new Error("sendTransaction: adapter not found");const r=He.getProvider(s),i=await(n==null?void 0:n.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:r}));return(i==null?void 0:i.hash)||""}return""},estimateGas:async e=>{const s=e.chainNamespace;if(s===$.CHAIN.EVM){const n=this.getAdapter(s);if(!n)throw new Error("estimateGas: adapter is required but got undefined");const r=He.getProvider(s),i=this.getCaipNetwork();if(!i)throw new Error("estimateGas: caipNetwork is required but got undefined");const o=await(n==null?void 0:n.estimateGas({...e,provider:r,caipNetwork:i}));return(o==null?void 0:o.gas)||0n}return 0n},getEnsAvatar:async()=>{var r;const e=E.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");await this.syncIdentity({address:s,chainId:Number((r=this.getCaipNetwork())==null?void 0:r.id),chainNamespace:e});const n=E.getAccountData();return(n==null?void 0:n.profileImage)||!1},getEnsAddress:async e=>await Yn.resolveReownName(e),writeContract:async e=>{const s=E.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=He.getProvider(s);if(!r||!i)throw new Error("writeContract: caipNetwork or caipAddress is required but got undefined");const a=await(n==null?void 0:n.writeContract({...e,caipNetwork:r,provider:o,caipAddress:i}));return a==null?void 0:a.hash},parseUnits:(e,s)=>{const n=this.getAdapter(E.state.activeChain);if(!n)throw new Error("parseUnits: adapter is required but got undefined");return(n==null?void 0:n.parseUnits({value:e,decimals:s}))??0n},formatUnits:(e,s)=>{const n=this.getAdapter(E.state.activeChain);if(!n)throw new Error("formatUnits: adapter is required but got undefined");return(n==null?void 0:n.formatUnits({value:e,decimals:s}))??"0"},getCapabilities:async e=>{const s=this.getAdapter(E.state.activeChain);if(!s)throw new Error("getCapabilities: adapter is required but got undefined");return await(s==null?void 0:s.getCapabilities(e))},grantPermissions:async e=>{const s=this.getAdapter(E.state.activeChain);if(!s)throw new Error("grantPermissions: adapter is required but got undefined");return await(s==null?void 0:s.grantPermissions(e))},revokePermissions:async e=>{const s=this.getAdapter(E.state.activeChain);if(!s)throw new Error("revokePermissions: adapter is required but got undefined");return s!=null&&s.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>{const s=this.getAdapter(E.state.activeChain);if(!s)throw new Error("walletGetAssets: adapter is required but got undefined");return await(s==null?void 0:s.walletGetAssets(e))??{}},updateBalance:e=>{const s=this.getAddress(e),n=this.getCaipNetwork(e);!n||!s||this.updateNativeBalance(s,n==null?void 0:n.id,e)}},G.setClient(this.connectionControllerClient)}async onConnectExternal(e){var l,d,u,h,p,g,f,w;const s=E.state.activeChain,n=e.chain||s,r=this.getAdapter(n);let i=!0;if(e.type===Lt.CONNECTOR_TYPE_AUTH&&$.AUTH_CONNECTOR_SUPPORTED_CHAINS.some(A=>z.getConnectorId(A)===$.CONNECTOR_ID.AUTH)&&e.chain!==s&&(i=!1),e.chain&&e.chain!==s&&!e.caipNetwork){const v=this.getCaipNetworks().find(N=>N.chainNamespace===e.chain);v&&i&&this.setCaipNetwork(v)}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:((l=e.caipNetwork)==null?void 0:l.id)||(o==null?void 0:o.id),rpcUrl:((p=(h=(u=(d=e.caipNetwork)==null?void 0:d.rpcUrls)==null?void 0:u.default)==null?void 0:h.http)==null?void 0:p[0])||((w=(f=(g=o==null?void 0:o.rpcUrls)==null?void 0:g.default)==null?void 0:f.http)==null?void 0:w[0])});if(c)return F.addConnectedNamespace(n),this.syncProvider({...c,chainNamespace:n}),this.setStatus("connected",n),this.syncConnectedWalletInfo(n),F.removeDisconnectedConnectorId(e.id,n),{address:c.address,connectedCaipNetwork:a}}async connectInactiveNamespaces(e,s){var a;const n=e.type===Lt.CONNECTOR_TYPE_AUTH,r=Ro.getOtherAuthNamespaces((a=s==null?void 0:s.connectedCaipNetwork)==null?void 0:a.chainNamespace),i=E.state.activeCaipNetwork,o=this.getAdapter(i==null?void 0:i.chainNamespace);n&&(await Promise.all(r.map(async c=>{var l,d,u;try{const h=He.getProvider(c),p=this.getCaipNetwork(c),g=this.getAdapter(c);await(g==null?void 0:g.connect({...e,provider:h,socialUri:void 0,chainId:p==null?void 0:p.id,rpcUrl:(u=(d=(l=p==null?void 0:p.rpcUrls)==null?void 0:l.default)==null?void 0:d.http)==null?void 0:u[0]}))&&(F.addConnectedNamespace(c),F.removeDisconnectedConnectorId(e.id,c),this.setStatus("connected",c),this.syncConnectedWalletInfo(c))}catch(h){Ot.warn(Pt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.displayMessage,Pt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.debugMessage(c,h instanceof Error?h.message:void 0),Pt.ALERT_WARNINGS.INACTIVE_NAMESPACE_NOT_CONNECTED.code)}})),i&&await(o==null?void 0:o.switchNetwork({caipNetwork:i})))}getApprovedCaipNetworksData(){var s,n,r,i,o;if(He.getProviderId(E.state.activeChain)===Lt.CONNECTOR_TYPE_WALLET_CONNECT){const a=(n=(s=this.universalProvider)==null?void 0:s.session)==null?void 0:n.namespaces;return{supportsAllNetworks:((o=(i=(r=this.universalProvider)==null?void 0:r.session)==null?void 0:i.peer)==null?void 0:o.metadata.name)==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(a)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const r=He.getProviderId(s);if(e.chainNamespace===E.state.activeChain){const i=this.getAdapter(s);await(i==null?void 0:i.switchNetwork({caipNetwork:e}))}else if(this.setCaipNetwork(e),r===Lt.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}=dt.parseCaipAddress(i);return`${a}:${o}`});return Array.from(new Set([...n,...r]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,n)=>{var i,o;const r=e==null?void 0:e.find(a=>a.namespace===n);return r?(r.construct({namespace:n,projectId:(i=this.options)==null?void 0:i.projectId,networks:(o=this.caipNetworks)==null?void 0:o.filter(({chainNamespace:a})=>a===n)}),s[n]=r):s[n]=new Hk({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){const s=this.getAdapter(e);s==null||s.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const n=F.getConnectionStatus();D.state.enableReconnect===!1?this.setStatus("disconnected",e):n==="connected"?this.setStatus("connecting",e):n==="disconnected"?(F.clearAddressCache(),this.setStatus(n,e)):this.setStatus(n,e),s.on("switchNetwork",({address:r,chainId:i})=>{var l,d;const o=this.getCaipNetworks().find(u=>u.id.toString()===i.toString()||u.caipNetworkId.toString()===i.toString()),a=E.state.activeChain===e,c=(d=(l=E.state.chains.get(e))==null?void 0:l.accountState)==null?void 0:d.address;if(o){const u=a&&r?r:c;u&&this.syncAccount({address:u,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(i)}),s.on("disconnect",()=>{const r=this.remoteFeatures.multiWallet,i=Array.from(G.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=E.state.activeCaipNetwork;!r||!(i!=null&&i.id)||this.updateNativeBalance(r,i.id,i.chainNamespace)}),s.on("accountChanged",({address:r,chainId:i,connector:o})=>{var d,u;this.handlePreviousConnectorConnection(o);const a=E.state.activeChain===e;o!=null&&o.provider&&(this.syncProvider({id:o.id,type:o.type,provider:o==null?void 0:o.provider,chainNamespace:e}),this.syncConnectedWalletInfo(e));const c=(u=(d=E.getNetworkData(e))==null?void 0:d.caipNetwork)==null?void 0:u.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),F.addConnectedNamespace(e)})}async handlePreviousConnectorConnection(e){var c;const s=e==null?void 0:e.chain,n=e==null?void 0:e.id,r=z.getConnectorId(s),i=(c=D.state.remoteFeatures)==null?void 0:c.multiWallet,a=s&&n&&r&&r!==n&&!i;try{a&&await G.disconnect({id:r,namespace:s})}catch(l){console.warn("Error disconnecting previous connector",l)}}async createUniversalProviderForAdapter(e){var s,n,r;await this.getUniversalProvider(),this.universalProvider&&await((r=(n=(s=this.chainAdapters)==null?void 0:s[e])==null?void 0:n.setUniversalProvider)==null?void 0:r.call(n,this.universalProvider))}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async unSyncExistingConnection(){try{await Promise.allSettled(this.chainNamespaces.map(e=>G.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()||F.deleteRecentWallet();const s=F.getRecentWallet();Ee.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:e,properties:{method:X.isMobile()?"mobile":"qrcode",name:(s==null?void 0:s.name)||"Unknown",reconnect:!0,view:ue.state.view,walletRank:s==null?void 0:s.order}})}async syncNamespaceConnection(e){try{e===$.CHAIN.EVM&&X.isSafeApp()&&z.setConnectorId($.CONNECTOR_ID.SAFE,e);const s=z.getConnectorId(e);switch(this.setStatus("connecting",e),s){case $.CONNECTOR_ID.WALLET_CONNECT:await this.reconnectWalletConnect();break;case $.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||{};E.resetAccount(s),E.resetNetwork(s),F.removeConnectedNamespace(s);const r=Array.from(E.state.chains.keys());(s?[s]:r).forEach(o=>F.addDisconnectedConnectorId(z.getConnectorId(o)||"",o)),z.removeConnectorId(s),He.resetChain(s),this.setUser(null,s),this.setStatus("disconnected",s),this.setConnectedWalletInfo(null,s),n!==!1&&Te.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==null?void 0:s.syncConnections({connectToFirstConnector:!n,caipNetwork:r})}))}async syncAdapterConnection(e){var a,c,l,d,u;const s=this.getAdapter(e),n=this.getCaipNetwork(e),r=z.getConnectorId(e),o=z.getConnectors(e).find(h=>h.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!(n!=null&&n.id))throw new Error("CaipNetwork not found");const h=await(s==null?void 0:s.syncConnection({namespace:e,id:o.id,chainId:n.id,rpcUrl:(l=(c=(a=n==null?void 0:n.rpcUrls)==null?void 0:a.default)==null?void 0:c.http)==null?void 0:l[0]}));h?(this.syncProvider({...h,chainNamespace:e}),await this.syncAccount({...h,chainNamespace:e}),this.setStatus("connected",e),Ee.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:h.address,properties:{method:"browser",name:((d=o.info)==null?void 0:d.name)||o.name||"Unknown",reconnect:!0,view:ue.state.view,walletRank:(u=o==null?void 0:o.explorerWallet)==null?void 0:u.order}})):this.setStatus("disconnected",e)}catch{this.onDisconnectNamespace({chainNamespace:e,closeModal:!1})}}async syncWalletConnectAccount(){var n,r;const e=Object.keys(((r=(n=this.universalProvider)==null?void 0:n.session)==null?void 0:r.namespaces)||{}),s=this.chainNamespaces.map(async i=>{var u,h,p,g,f;const o=this.getAdapter(i);if(!o)return;const a=((g=(p=(h=(u=this.universalProvider)==null?void 0:u.session)==null?void 0:h.namespaces)==null?void 0:p[i])==null?void 0:g.accounts)||[],c=(f=E.state.activeCaipNetwork)==null?void 0:f.id,l=a.find(w=>{const{chainId:v}=dt.parseCaipAddress(w);return v===(c==null?void 0:c.toString())})||a[0];if(l){const w=dt.validateCaipAddress(l),{chainId:v,address:N}=dt.parseCaipAddress(w);if(He.setProviderId(i,Lt.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&E.state.activeCaipNetwork&&o.namespace!==$.CHAIN.EVM){const A=o.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:E.state.activeCaipNetwork});He.setProvider(i,A)}else He.setProvider(i,this.universalProvider);z.setConnectorId($.CONNECTOR_ID.WALLET_CONNECT,i),F.addConnectedNamespace(i),await this.syncAccount({address:N,chainId:v,chainNamespace:i})}else e.includes(i)&&this.setStatus("disconnected",i);const d=this.getApprovedCaipNetworksData();this.syncConnectedWalletInfo(i),E.setApprovedCaipNetworksData(i,{approvedCaipNetworkIds:d.approvedCaipNetworkIds,supportsAllNetworks:d.supportsAllNetworks})});await Promise.all(s)}syncProvider({type:e,provider:s,id:n,chainNamespace:r}){He.setProviderId(r,e),He.setProvider(r,s),z.setConnectorId(n,r)}async syncAccount(e){var u,h;const s=e.chainNamespace===E.state.activeChain,n=E.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:r,chainId:i,chainNamespace:o}=e,{chainId:a}=F.getActiveNetworkProps(),c=(n==null?void 0:n.id)||a,l=((u=E.state.activeCaipNetwork)==null?void 0:u.name)===$.UNSUPPORTED_NETWORK_NAME,d=E.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!d)&&c){let p=this.getCaipNetworks().find(v=>v.id.toString()===c.toString()),g=this.getCaipNetworks().find(v=>v.chainNamespace===o);if(!d&&!p&&!g){const v=this.getApprovedCaipNetworkIds()||[],N=v.find(_=>{var P;return((P=dt.parseCaipNetworkId(_))==null?void 0:P.chainId)===c.toString()}),A=v.find(_=>{var P;return((P=dt.parseCaipNetworkId(_))==null?void 0:P.chainNamespace)===o});p=this.getCaipNetworks().find(_=>_.caipNetworkId===N),g=this.getCaipNetworks().find(_=>_.caipNetworkId===A||"deprecatedCaipNetworkId"in _&&_.deprecatedCaipNetworkId===A)}const f=p||g;(f==null?void 0:f.chainNamespace)===E.state.activeChain?D.state.enableNetworkSwitch&&!D.state.allowUnsupportedChain&&((h=E.state.activeCaipNetwork)==null?void 0:h.name)===$.UNSUPPORTED_NETWORK_NAME?E.showUnsupportedChainUI():this.setCaipNetwork(f):s||n&&this.setCaipNetworkOfNamespace(n,o),this.syncConnectedWalletInfo(o);const w=this.getAddress(o);Ro.isLowerCaseMatch(r,w)||this.syncAccountInfo(r,f==null?void 0:f.id,o),s?await this.syncBalance({address:r,chainId:f==null?void 0:f.id,chainNamespace:o}):await this.syncBalance({address:r,chainId:n==null?void 0: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==null?void 0: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){var r;const s=z.getConnectorId(e),n=He.getProviderId(e);if(n===Lt.CONNECTOR_TYPE_ANNOUNCED||n===Lt.CONNECTOR_TYPE_INJECTED){if(s){const o=this.getConnectors().find(a=>{var u,h;const c=a.id===s,l=((u=a.info)==null?void 0:u.rdns)===s,d=(h=a.connectors)==null?void 0:h.some(p=>{var g;return p.id===s||((g=p.info)==null?void 0:g.rdns)===s});return c||l||!!d});if(o){const{info:a,name:c,imageUrl:l}=o,d=l||this.getConnectorImage(o);this.setConnectedWalletInfo({name:c,icon:d,...a},e)}}}else if(n===Lt.CONNECTOR_TYPE_WALLET_CONNECT){const i=He.getProvider(e);i!=null&&i.session&&this.setConnectedWalletInfo({...i.session.peer.metadata,name:i.session.peer.metadata.name,icon:(r=i.session.peer.metadata.icons)==null?void 0:r[0]},e)}else if(s&&(s===$.CONNECTOR_ID.COINBASE_SDK||s===$.CONNECTOR_ID.COINBASE)){const i=this.getConnectors().find(l=>l.id===s),o=(i==null?void 0:i.name)||"Coinbase Wallet",a=(i==null?void 0:i.imageUrl)||this.getConnectorImage(i),c=i==null?void 0:i.info;this.setConnectedWalletInfo({...c,name:o,icon:a},e)}}async syncBalance(e){!Sf.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(n=>{var r;return n.id.toString()===((r=e.chainId)==null?void 0:r.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=E.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(){var r,i,o,a,c,l,d,u,h,p;const e=Fx.createLogger((g,...f)=>{g&&this.handleAlertError(g),console.error(...f)}),s={projectId:(r=this.options)==null?void 0:r.projectId,metadata:{name:(i=this.options)!=null&&i.metadata?(o=this.options)==null?void 0:o.metadata.name:"",description:(a=this.options)!=null&&a.metadata?(c=this.options)==null?void 0:c.metadata.description:"",url:(l=this.options)!=null&&l.metadata?(d=this.options)==null?void 0:d.metadata.url:"",icons:(u=this.options)!=null&&u.metadata?(h=this.options)==null?void 0:h.metadata.icons:[""]},logger:e};D.setManualWCControl(!!((p=this.options)!=null&&p.manualWCControl)),this.universalProvider=this.options.universalProvider??await cx.init(s);const n=this.universalProvider.disconnect.bind(this.universalProvider);this.universalProvider.disconnect=async()=>{try{return await n()}catch(g){if(g instanceof Error&&g.message.includes("Missing or invalid. Record was recently deleted"))return;throw g}},D.state.enableReconnect===!1&&this.universalProvider.session&&await this.universalProvider.disconnect(),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&this.chainNamespaces.forEach(e=>{Yn.listenWcProvider({universalProvider:this.universalProvider,namespace:e,onDisplayUri:s=>{G.setUri(s)},onConnect:s=>{const{address:n}=X.getAccount(s[0]);G.finalizeWcConnection(n)},onDisconnect:()=>{E.state.noAdapters&&this.resetAccount(e),G.resetWcConnection()},onChainChanged:s=>{const n=E.state.activeChain,r=n&&z.state.activeConnectorIds[n]===$.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(E.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==null?void 0:o.id.toString())!==(i==null?void 0:i.id.toString())&&(o==null?void 0:o.chainNamespace)===(i==null?void 0:i.chainNamespace)&&this.setCaipNetwork(i)}},onAccountsChanged:s=>{const n=E.state.activeChain,r=n&&z.state.activeConnectorIds[n]===$.CONNECTOR_ID.WALLET_CONNECT;if(n===e&&(E.state.noAdapters||r)){const i=s==null?void 0:s[0];i&&this.syncAccount({address:i.address,chainId:i.chainId,chainNamespace:i.chainNamespace})}}})})}createUniversalProvider(){var e;return!this.universalProviderInitPromise&&X.isClient()&&((e=this.options)!=null&&e.projectId)&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){Ee.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=E.getAllApprovedCaipNetworkIds(),s=E.getAllRequestedCaipNetworks();return X.sortRequestedNetworks(e,s).filter(r=>E.isCaipNetworkDisabled(r))}handleAlertError(e){const s=Object.entries(Pt.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[n,r]=s??[],{message:i,alertErrorKey:o}=r??{};if(n&&i&&!this.reportedAlertErrors[n]){const a=Pt.ALERT_ERRORS[o];a&&(Ot.open(a,"error"),this.reportedAlertErrors[n]=!0)}}getAdapter(e){var s;if(e)return(s=this.chainAdapters)==null?void 0:s[e]}createAdapter(e){var r,i;if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const n=e;n.namespace=s,n.construct({namespace:s,projectId:(r=this.options)==null?void 0:r.projectId,networks:(i=this.caipNetworks)==null?void 0:i.filter(({chainNamespace:o})=>o===s)}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=n)}async open(e){await this.injectModalUi(),e!=null&&e.uri&&G.setUri(e.uri);const{isSwap:s,isSend:n}=this.toModalOptions();return s(e)?Te.open({...e,data:{swap:e.arguments}}):n(e)&&e.arguments?this.openSend(e.arguments):Te.open(e)}async close(){await this.injectModalUi(),Te.close()}setLoading(e,s){Te.setLoading(e,s)}async disconnect(e){await G.disconnect({namespace:e})}getSIWX(){return D.state.siwx}getError(){return""}getChainId(){var e;return(e=E.state.activeCaipNetwork)==null?void 0:e.id}async switchNetwork(e,{throwOnFailure:s=!1}={}){const n=this.getCaipNetworks().find(r=>r.id===e.id);if(!n){Ot.open(Pt.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await E.switchActiveNetwork(n,{throwOnFailure:s})}getWalletProvider(){return E.state.activeChain?He.state.providers[E.state.activeChain]:null}getWalletProviderType(){return He.getProviderId(E.state.activeChain)}subscribeProviders(e){return He.subscribeProviders(e)}getThemeMode(){return Kt.state.themeMode}getThemeVariables(){return Kt.state.themeVariables}setThemeMode(e){Kt.setThemeMode(e),qd(Kt.state.themeMode)}setTermsConditionsUrl(e){D.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){D.setPrivacyPolicyUrl(e)}setThemeVariables(e){Kt.setThemeVariables(e),Wk(Kt.state.themeVariables)}subscribeTheme(e){return Kt.subscribe(e)}subscribeConnections(e){return this.remoteFeatures.multiWallet?G.subscribe(e):(Ot.open($.REMOTE_FEATURES_ALERTS.MULTI_WALLET_NOT_ENABLED.DEFAULT,"info"),()=>{})}getWalletInfo(e){var n,r;if(e)return(r=(n=E.state.chains.get(e))==null?void 0:n.accountState)==null?void 0:r.connectedWalletInfo;const s=E.getAccountData();return s==null?void 0:s.connectedWalletInfo}getAccount(e){const s=e||E.state.activeChain,n=z.getAuthConnector(s),r=E.getAccountData(s),i=F.getConnectedConnectorId(E.state.activeChain),o=G.getConnections(s);if(!s)throw new Error("AppKit:getAccount - namespace is required");const a=o.flatMap(c=>c.accounts.map(({address:l,type:d,publicKey:u})=>X.createAccount(s,l,d||"eoa",u)));if(r)return{allAccounts:a,caipAddress:r.caipAddress,address:X.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:n&&i===$.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:F.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:us(s),isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const n=()=>{const r=this.getAccount(s);r&&e(r)};s?E.subscribeChainProp("accountState",n,s):E.subscribe(n),z.subscribe(n)}subscribeNetwork(e){return E.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s==null?void 0:s.id,caipNetworkId:s==null?void 0:s.caipNetworkId})})}subscribeWalletInfo(e,s){return s?E.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo),s):E.subscribeChainProp("accountState",n=>e(n==null?void 0:n.connectedWalletInfo))}subscribeShouldUpdateToAddress(e){E.subscribeChainProp("accountState",s=>e(s==null?void 0:s.shouldUpdateToAddress))}subscribeCaipNetworkChange(e){E.subscribeKey("activeCaipNetwork",e)}getState(){return hs.state}getRemoteFeatures(){return D.state.remoteFeatures}subscribeState(e){return hs.subscribe(e)}subscribeRemoteFeatures(e){return D.subscribeKey("remoteFeatures",e)}showErrorMessage(e){Ys.showError(e)}showSuccessMessage(e){Ys.showSuccess(e)}getEvent(){return{...Ee.state}}subscribeEvents(e){return Ee.subscribe(e)}replace(e){ue.replace(e)}redirect(e){ue.push(e)}popTransactionStack(e){ue.popTransactionStack(e)}isOpen(){return Te.state.open}isTransactionStackEmpty(){return ue.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){D.setFeatures(e)}updateRemoteFeatures(e){D.setRemoteFeatures(e)}updateOptions(e){const n={...D.state||{},...e};D.setOptions(n)}setConnectMethodsOrder(e){D.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){D.setWalletFeaturesOrder(e)}setCollapseWallets(e){D.setCollapseWallets(e)}setSocialsOrder(e){D.setSocialsOrder(e)}getConnectMethodsOrder(){return Kn.getConnectOrderMethod(D.state.features,z.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)||E.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)&&E.removeNetwork(e,s)}}let Cf=!1;class Ay extends Kk{async onAuthProviderConnected(e){const s=Ro.userChainIdToChainNamespace(e==null?void 0:e.chainId);if(e.message&&e.signature&&e.siwxMessage&&await _s.addEmbeddedWalletSession({chainId:e.siwxMessage.chainId,accountAddress:e.address,notBefore:e.siwxMessage.notBefore,statement:e.siwxMessage.statement,resources:e.siwxMessage.resources,requestId:e.siwxMessage.requestId,issuedAt:e.siwxMessage.issuedAt,domain:e.siwxMessage.domain,uri:e.siwxMessage.uri,version:e.siwxMessage.version,nonce:e.siwxMessage.nonce},e.message,e.signature),!s)throw new Error("AppKit:onAuthProviderConnected - namespace is required");const n=s===$.CHAIN.EVM?`eip155:${e.chainId}:${e.address}`:`${e.chainId}:${e.address}`,r=D.state.defaultAccountTypes[s],i=us(s),o=e.preferredAccountType||i||r;this.setCaipAddress(n,s);const{signature:a,siwxMessage:c,message:l,...d}=e,u=E.getAccountData(s);this.setUser({...(u==null?void 0:u.user)||{},...d},s),this.setSmartAccountDeployed(!!e.smartAccountDeployed,s),this.setPreferredAccountType(o,s),await Promise.all([this.syncAuthConnectorTheme(this.authProvider),this.syncAccount({address:e.address,chainId:e.chainId,chainNamespace:s})]),this.setLoading(!1,s)}setupAuthConnectorListeners(e){e.onRpcRequest(s=>{ds.checkIfRequestExists(s)?ds.checkIfRequestIsSafe(s)||this.handleUnsafeRPCRequest():(this.open(),console.error(et.RPC_METHOD_NOT_ALLOWED_MESSAGE,{method:s.method}),setTimeout(()=>{this.showErrorMessage(et.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE)},300),e.rejectRpcRequests())}),e.onRpcError(()=>{this.isOpen()&&(this.isTransactionStackEmpty()?this.close():this.popTransactionStack("error"))}),e.onRpcSuccess((s,n)=>{const r=ds.checkIfRequestIsSafe(n),i=this.getAddress(),o=E.state.activeCaipNetwork;r||(i&&(o!=null&&o.id)&&this.updateNativeBalance(i,o.id,o.chainNamespace),this.isTransactionStackEmpty()?this.close():this.popTransactionStack("success"))}),e.onNotConnected(()=>{const s=E.state.activeChain;if(!s)throw new Error("AppKit:onNotConnected - namespace is required");z.getConnectorId(s)===$.CONNECTOR_ID.AUTH&&(this.setCaipAddress(null,s),this.setLoading(!1,s))}),e.onConnect(this.onAuthProviderConnected.bind(this)),e.onSocialConnected(this.onAuthProviderConnected.bind(this)),e.onSetPreferredAccount(({address:s,type:n})=>{const r=E.state.activeChain;if(!r)throw new Error("AppKit:onSetPreferredAccount - namespace is required");s&&this.setPreferredAccountType(n,r)})}async syncAuthConnectorTheme(e){if(!e)return;const s=Kt.getSnapshot();await e.syncTheme({themeMode:s.themeMode,themeVariables:s.themeVariables,w3mThemeVariables:ao(s.themeVariables,s.themeMode)})}async syncAuthConnector(e,s){var d,u,h,p,g,f,w,v,N;const n=$.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(s),r=s===E.state.activeChain;if(!n)return;this.setLoading(!0,s);const i=e.getLoginEmailUsed();this.setLoading(i,s),i&&this.setStatus("connecting",s);const o=e.getEmail(),a=e.getUsername(),c=((d=E.getAccountData(s))==null?void 0:d.user)||{};this.setUser({...c,username:a,email:o},s),this.setupAuthConnectorListeners(e);const{isConnected:l}=await e.isConnected();if(s&&n&&r)if(l&&((u=this.connectionControllerClient)!=null&&u.connectExternal)){await e.init(),await this.syncAuthConnectorTheme(e),await((g=this.connectionControllerClient)==null?void 0:g.connectExternal({id:$.CONNECTOR_ID.AUTH,info:{name:$.CONNECTOR_ID.AUTH},type:Lt.CONNECTOR_TYPE_AUTH,provider:e,chainId:(p=(h=E.getNetworkData(s))==null?void 0:h.caipNetwork)==null?void 0:p.id,chain:s})),this.setStatus("connected",s);const A=F.getConnectedSocialProvider();A?Ee.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",address:this.getAddress(),properties:{provider:A,reconnect:!0}}):Ee.sendEvent({type:"track",event:"CONNECT_SUCCESS",address:this.getAddress(),properties:{method:"email",name:((N=(v=(w=(f=this.universalProvider)==null?void 0:f.session)==null?void 0:w.peer)==null?void 0:v.metadata)==null?void 0:N.name)||"Unknown",reconnect:!0,view:ue.state.view,walletRank:void 0}})}else z.getConnectorId(s)===$.CONNECTOR_ID.AUTH&&(this.setStatus("disconnected",s),F.removeConnectedNamespace(s));this.setLoading(!1,s)}async checkExistingTelegramSocialConnection(e){var s;try{if(!X.isTelegram())return;const n=F.getTelegramSocialProvider();if(!n||!X.isClient())return;const i=new URL(window.location.href).searchParams.get("result_uri");if(!i)return;n&&E.setAccountProp("socialProvider",n,e),await((s=this.authProvider)==null?void 0:s.init());const o=z.getAuthConnector();n&&o&&(this.setLoading(!0,e),await G.connectExternal({id:o.id,type:o.type,socialUri:i},o.chain),F.setConnectedSocialProvider(n),F.removeTelegramSocialProvider(),Ee.sendEvent({type:"track",event:"SOCIAL_LOGIN_SUCCESS",properties:{provider:n}}))}catch(n){this.setLoading(!1,e),console.error("checkExistingSTelegramocialConnection error",n)}try{const n=new URL(window.location.href);n.searchParams.delete("result_uri"),window.history.replaceState({},document.title,n.toString())}catch(n){console.error("tma social login failed",n)}}createAuthProvider(e){var l,d,u,h;if(!$.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(e))return;const n=(l=this.remoteFeatures)==null?void 0:l.email,r=Array.isArray((d=this.remoteFeatures)==null?void 0:d.socials)&&this.remoteFeatures.socials.length>0,i=n||r,a=Ro.getActiveNamespaceConnectedToAuth()||e;!this.authProvider&&((u=this.options)!=null&&u.projectId)&&i&&(this.authProvider=so.getInstance({projectId:this.options.projectId,enableLogger:this.options.enableAuthLogger,chainId:(h=this.getCaipNetwork(a))==null?void 0:h.caipNetworkId,abortController:Pt.EmbeddedWalletAbortController,onTimeout:p=>{p==="iframe_load_failed"?Ot.open(Pt.ALERT_ERRORS.IFRAME_LOAD_FAILED,"error"):p==="iframe_request_timeout"?Ot.open(Pt.ALERT_ERRORS.IFRAME_REQUEST_TIMEOUT,"error"):p==="unverified_domain"&&Ot.open(Pt.ALERT_ERRORS.UNVERIFIED_DOMAIN,"error")},getActiveCaipNetwork:p=>Hi(p),getCaipNetworks:p=>E.getCaipNetworks(p)}),hs.subscribeOpen(p=>{var g;!p&&this.isTransactionStackEmpty()&&((g=this.authProvider)==null||g.rejectRpcRequests())}));const c=e===E.state.activeChain&&D.state.enableReconnect;D.state.enableReconnect===!1?this.syncAuthConnectorTheme(this.authProvider):this.authProvider&&c&&(this.syncAuthConnector(this.authProvider,e),this.checkExistingTelegramSocialConnection(e))}createAuthProviderForAdapter(e){var s,n,r;this.createAuthProvider(e),this.authProvider&&((r=(n=(s=this.chainAdapters)==null?void 0:s[e])==null?void 0:n.setAuthProvider)==null||r.call(n,this.authProvider))}initControllers(e){super.initControllers(e),this.options.excludeWalletIds&&te.initializeExcludedWallets({ids:this.options.excludeWalletIds})}async switchCaipNetwork(e){var o,a,c;if(!e)return;const s=E.state.activeChain,n=e.chainNamespace,r=this.getAddressByChainNamespace(n);if(n===s&&((o=E.getAccountData(n))!=null&&o.caipAddress)){const l=this.getAdapter(n);await(l==null?void 0:l.switchNetwork({caipNetwork:e})),this.setCaipNetwork(e)}else{const d=He.getProviderId(s)===Lt.CONNECTOR_TYPE_AUTH,u=He.getProviderId(n),h=u===Lt.CONNECTOR_TYPE_AUTH,p=$.AUTH_CONNECTOR_SUPPORTED_CHAINS.includes(n);if(!n)throw new Error("AppKit:switchCaipNetwork - networkNamespace is required");if((d&&u===void 0||h)&&p)try{if(E.state.activeChain=e.chainNamespace,r){const g=this.getAdapter(n);await(g==null?void 0:g.switchNetwork({caipNetwork:e}))}else await((c=(a=this.connectionControllerClient)==null?void 0:a.connectExternal)==null?void 0:c.call(a,{id:$.CONNECTOR_ID.AUTH,provider:this.authProvider,chain:n,chainId:e.id,type:Lt.CONNECTOR_TYPE_AUTH,caipNetwork:e}));this.setCaipNetwork(e)}catch{const f=this.getAdapter(n);await(f==null?void 0:f.switchNetwork({caipNetwork:e}))}else if(u===Lt.CONNECTOR_TYPE_WALLET_CONNECT){if(!E.state.noAdapters){const g=this.getAdapter(n);await(g==null?void 0:g.switchNetwork({caipNetwork:e}))}this.setCaipNetwork(e),this.syncWalletConnectAccount()}else this.setCaipNetwork(e),r&&this.syncAccount({address:r,chainId:e.id,chainNamespace:n})}}async initialize(e){var s;await super.initialize(e),(s=this.chainNamespaces)==null||s.forEach(n=>{this.createAuthProviderForAdapter(n)}),await this.injectModalUi(),hs.set({initialized:!0})}async syncIdentity({address:e,chainId:s,chainNamespace:n}){var a;const r=`${n}:${s}`,i=(a=this.caipNetworks)==null?void 0:a.find(c=>c.caipNetworkId===r);if(i!=null&&i.testnet){this.setProfileName(null,n),this.setProfileImage(null,n);return}const o=z.getConnectorId(n)===$.CONNECTOR_ID.AUTH;try{const{name:c,avatar:l}=await this.fetchIdentity({address:e});!c&&o?await this.syncReownName(e,n):(this.setProfileName(c,n),this.setProfileImage(l,n))}catch{s!==1&&this.setProfileImage(null,n)}}syncConnectedWalletInfo(e){const s=He.getProviderId(e);if(s===Lt.CONNECTOR_TYPE_AUTH){const n=this.authProvider;if(n){const r=F.getConnectedSocialProvider()??"email",i=n.getEmail()??n.getUsername();this.setConnectedWalletInfo({name:s,identifier:i,social:r},e)}}else super.syncConnectedWalletInfo(e)}async injectModalUi(){if(X.isClient()&&!Cf)try{const e={...Ne.DEFAULT_FEATURES,...this.options.features},s=this.remoteFeatures;if(await this.loadModalComponents(e,s),X.isClient()&&!document.querySelector("w3m-modal")){const r=document.createElement("w3m-modal");!D.state.disableAppend&&!D.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",r)}Cf=!0}catch(e){console.error("Error injecting modal UI:",e)}}async loadModalComponents(e,s){if(!X.isClient())return;const n=[];(s.email||s.socials&&s.socials.length>0)&&n.push(Dt(()=>import("./embedded-wallet-ByhNQW_m.js"),__vite__mapDeps([9,10,2,11,12,1,13,14,15,16,17,18,19,20,21,22,4,5,6,7]))),s.email&&n.push(Dt(()=>import("./email-fUFAiT2-.js"),__vite__mapDeps([23,10,2,24,21,14,20,12,13,19,25,17,1,4,5,6,7]))),s.socials&&n.push(Dt(()=>import("./socials-Cx5_uD8B.js"),__vite__mapDeps([26,10,2,12,27,13,28,1,20,29,16,19,14,30,11,4,5,6,7,31]))),s.swaps&&s.swaps.length>0&&n.push(Dt(()=>import("./swaps-BQNZs4oR.js"),__vite__mapDeps([32,10,2,19,14,20,12,33,34,35,1,31,36,11,17,13,4,5,6,7]))),e.send&&n.push(Dt(()=>import("./send-BGQ3IUrv.js"),__vite__mapDeps([37,10,2,19,14,20,12,38,13,39,21,36,11,31,35,1,17,40,41,4,5,6,7]))),e.receive&&n.push(Dt(()=>import("./receive-DJ-kCiiX.js"),__vite__mapDeps([42,10,2,12,11,30,4,5,6,7,1]))),s.onramp&&s.onramp.length>0&&n.push(Dt(()=>import("./onramp-DNtmpA6Y.js"),__vite__mapDeps([43,10,2,12,44,14,27,13,11,45,46,21,19,20,29,17,1,4,5,6,7]))),s.payWithExchange&&n.push(Dt(()=>import("./pay-with-exchange-COuzct72.js"),__vite__mapDeps([47,10,2,12,11,18,44,14,31,19,39,13,21,48,20,17,40,38,1,4,5,6,7]))),s.activity&&n.push(Dt(()=>import("./transactions-4STPUm57.js"),__vite__mapDeps([49,10,2,50,20,12,21,11,31,1,4,5,6,7]))),(e.pay||s.payments)&&n.push(Dt(()=>import("./index-DGiPcc80.js"),__vite__mapDeps([51,10,2,12,19,14,52,18,11,44,53,38,54,20,1,29,4,5,6,7]))),s.emailCapture&&n.push(Dt(()=>import("./data-capture-CsxiqOap.js"),__vite__mapDeps([55,10,2,24,21,14,8,1,4,5,6,7]))),await Promise.all([...n,Dt(()=>import("./index-Cb7OJiUx.js"),__vite__mapDeps([56,10,2,12,11,14,41,20,57,46,21,15,16,1,54,18,44,19,48,50,31,40,33,34,38,13,17,53,25,27,28,29,30,4,5,6,7,22,45])),Dt(()=>import("./w3m-modal-HqHeH3Ma.js"),__vite__mapDeps([58,10,2,12,52,11,15,16,1,14,20,34,57,46,21,54,35,19,4,5,6,7]))])}}const Gk="1.8.15";function Yk(t){return new Ay({...t,sdkVersion:X.generateSdkVersion(t.adapters??[],"html",Gk)})}const tU=Object.freeze(Object.defineProperty({__proto__:null,AppKit:Ay,CoreHelperUtil:X,WcConstantsUtil:Gi,createAppKit:Yk},Symbol.toStringTag,{value:"Module"}));export{eo as $,yt as A,fe as B,E as C,Z2 as D,Ee as E,uo as F,F as G,ds as H,ae as I,le as J,Lt as K,te as L,Te as M,nw as N,D as O,yv as P,Pt as Q,ue as R,Ys as S,Kt as T,dt as U,He as V,et as W,aw as X,ao as Y,lt as Z,Ae as _,X as a,ed as a0,Cs as a1,Ur as a2,wn as a3,_s as a4,X2 as a5,Zf as a6,ja as a7,wy as a8,jd as a9,Ci as aa,Us as ab,cc as ac,Ro as ad,Kn as ae,ei as af,Wv as ag,Hf as ah,a2 as ai,c2 as aj,h2 as ak,l2 as al,u2 as am,d2 as an,p2 as ao,f2 as ap,ya as aq,Hi as ar,tU as as,W2 as b,q2 as c,Ne as d,Yf as e,z2 as f,H2 as g,V2 as h,_t as i,J2 as j,eU as k,Ga as l,Y2 as m,zn as n,G as o,Ge as p,us as q,Q2 as r,At as s,Fv as t,Ot as u,qk as v,Ns as w,Zd as x,z as y,Kf as z};