@dev.sail.money/sailor 1.2.1-90 → 1.2.1-93

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 (95) hide show
  1. package/package.json +1 -1
  2. package/packages/sdk/dist/intelligence.d.ts +1 -1
  3. package/packages/sdk/dist/intelligence.js +1 -1
  4. package/packages/ui/dist/assets/{add-R0xP2zko.js → add-BER1P0s8.js} +1 -1
  5. package/packages/ui/dist/assets/{all-wallets-qnzttqV_.js → all-wallets-Dpvf_Fgb.js} +1 -1
  6. package/packages/ui/dist/assets/{app-store-DpKGxR0G.js → app-store-CRRn8Odw.js} +1 -1
  7. package/packages/ui/dist/assets/{apple-Ckb9o1LK.js → apple-Dt7cfB4T.js} +1 -1
  8. package/packages/ui/dist/assets/{arrow-bottom-circle-BH2TcYm0.js → arrow-bottom-circle-CX3JbHmW.js} +1 -1
  9. package/packages/ui/dist/assets/{arrow-bottom-D1FAx-yB.js → arrow-bottom-nnnn08j6.js} +1 -1
  10. package/packages/ui/dist/assets/{arrow-left-CaaYjdtV.js → arrow-left-CA_ePKfw.js} +1 -1
  11. package/packages/ui/dist/assets/{arrow-right-DW-rnoD_.js → arrow-right-PdNbPXya.js} +1 -1
  12. package/packages/ui/dist/assets/{arrow-top-M7CVCSnU.js → arrow-top-Bi7Vtz7K.js} +1 -1
  13. package/packages/ui/dist/assets/{bank-DVbh1inT.js → bank-pst7NvBz.js} +1 -1
  14. package/packages/ui/dist/assets/{basic-BWLPh793.js → basic-CoHdyAX2.js} +1 -1
  15. package/packages/ui/dist/assets/{browser-BW0QiXeN.js → browser-FFX3Izi4.js} +1 -1
  16. package/packages/ui/dist/assets/{card-BNNvJESX.js → card-DnCzRGnr.js} +1 -1
  17. package/packages/ui/dist/assets/{ccip-C2ivRCFf.js → ccip-DSxi6VpP.js} +1 -1
  18. package/packages/ui/dist/assets/{checkmark-FoCkBDzR.js → checkmark-DYPnyuve.js} +1 -1
  19. package/packages/ui/dist/assets/{checkmark-bold-B7P2Bvsd.js → checkmark-bold-Cw0Vp6CM.js} +1 -1
  20. package/packages/ui/dist/assets/{chevron-bottom-DOhAc7rS.js → chevron-bottom-EVHy9xJn.js} +1 -1
  21. package/packages/ui/dist/assets/{chevron-left-BiWf2KCl.js → chevron-left-CxY9fiDc.js} +1 -1
  22. package/packages/ui/dist/assets/{chevron-right-BH7i9-GZ.js → chevron-right-Br_OBI9u.js} +1 -1
  23. package/packages/ui/dist/assets/{chevron-top-C9zp-WFB.js → chevron-top-BpU3ntbA.js} +1 -1
  24. package/packages/ui/dist/assets/{chrome-store-vDr9wSYG.js → chrome-store-Dpgj_H8i.js} +1 -1
  25. package/packages/ui/dist/assets/{clock-CZlsrGmg.js → clock-BXeQYwif.js} +1 -1
  26. package/packages/ui/dist/assets/{close-C7369YAf.js → close-DL5E5Xp_.js} +1 -1
  27. package/packages/ui/dist/assets/{coinPlaceholder-CEONEmQj.js → coinPlaceholder-DrwJ2B_l.js} +1 -1
  28. package/packages/ui/dist/assets/{compass-DzhhABp6.js → compass-E5e-CeJQ.js} +1 -1
  29. package/packages/ui/dist/assets/{copy-zuwgIOLp.js → copy-BeNB4dl_.js} +1 -1
  30. package/packages/ui/dist/assets/{core-DjR_jD64.js → core-tNZO_nnA.js} +3 -3
  31. package/packages/ui/dist/assets/cursor-DV0oS1UQ.js +3 -0
  32. package/packages/ui/dist/assets/{cursor-transparent-DQOaLcvd.js → cursor-transparent-DZDjASnn.js} +1 -1
  33. package/packages/ui/dist/assets/{desktop-Bv7fy2f-.js → desktop-Cius6BUw.js} +1 -1
  34. package/packages/ui/dist/assets/{disconnect-DT21kQcX.js → disconnect-Bj35sHVy.js} +1 -1
  35. package/packages/ui/dist/assets/{discord-DnM6J12l.js → discord-DfrcpsIk.js} +1 -1
  36. package/packages/ui/dist/assets/{etherscan-CkYGysSe.js → etherscan-CBbH0szp.js} +1 -1
  37. package/packages/ui/dist/assets/{events-Bzlx_C-j.js → events-C79WI7iD.js} +1 -1
  38. package/packages/ui/dist/assets/{exclamation-triangle-CowxL_9E.js → exclamation-triangle-BNJwMq9S.js} +1 -1
  39. package/packages/ui/dist/assets/{extension-Dq3IsAUN.js → extension-CvYgSO7v.js} +1 -1
  40. package/packages/ui/dist/assets/{external-link-CVa7Or9W.js → external-link-CERn9oXB.js} +1 -1
  41. package/packages/ui/dist/assets/{facebook-CeigZ-Dq.js → facebook-B7m7SaqX.js} +1 -1
  42. package/packages/ui/dist/assets/{fallback-QmdVrhdj.js → fallback-BQkB1W8W.js} +1 -1
  43. package/packages/ui/dist/assets/{farcaster-CmxCGnX5.js → farcaster-Bwlsctme.js} +1 -1
  44. package/packages/ui/dist/assets/{filters-CY5pHglU.js → filters-C8rBtKff.js} +1 -1
  45. package/packages/ui/dist/assets/{github-DrSj44zE.js → github-PsXcSjMp.js} +1 -1
  46. package/packages/ui/dist/assets/{google-DTfyabXp.js → google-C_z3OmPf.js} +1 -1
  47. package/packages/ui/dist/assets/{help-circle-kFOxdrQz.js → help-circle-DwWgeVHE.js} +1 -1
  48. package/packages/ui/dist/assets/{id-5pW65QwE.js → id-CLuydosc.js} +1 -1
  49. package/packages/ui/dist/assets/{image-D2FlAtVU.js → image-BsLEVlQ9.js} +1 -1
  50. package/packages/ui/dist/assets/{index-CqeISmow.js → index-B075MYIF.js} +1 -1
  51. package/packages/ui/dist/assets/{index-DZwl1NkD.js → index-B9uA_-pd.js} +1 -1
  52. package/packages/ui/dist/assets/{index-DxcSXSQt.js → index-B_Jv-Jat.js} +1 -1
  53. package/packages/ui/dist/assets/{index-C62B8KTP.js → index-BrDR678h.js} +5 -5
  54. package/packages/ui/dist/assets/{index-CNJJ8w4T.js → index-CQ2Kvj0a.js} +3 -3
  55. package/packages/ui/dist/assets/{index-BkS9kyuf.js → index-_AI1Rhpq.js} +1 -1
  56. package/packages/ui/dist/assets/{index.es-CdKoInzi.js → index.es-C70kk3Fw.js} +4 -4
  57. package/packages/ui/dist/assets/{info-DbUUs-7h.js → info-BjPgE-Fn.js} +1 -1
  58. package/packages/ui/dist/assets/{info-circle-pK0azOfA.js → info-circle-CjkQM-HJ.js} +1 -1
  59. package/packages/ui/dist/assets/{lightbulb-BapmKP8y.js → lightbulb-FhGsti_A.js} +1 -1
  60. package/packages/ui/dist/assets/{mail-CdYd0Rh9.js → mail-Bg5yFmja.js} +1 -1
  61. package/packages/ui/dist/assets/{metamask-sdk-CmHF3TFo.js → metamask-sdk-DtKlSkak.js} +1 -1
  62. package/packages/ui/dist/assets/{mobile-DkjGiGYO.js → mobile-BzAf0T-M.js} +1 -1
  63. package/packages/ui/dist/assets/{more-BsU5N8hZ.js → more-Ccm3EzWe.js} +1 -1
  64. package/packages/ui/dist/assets/{network-placeholder-DLlzj024.js → network-placeholder-DJBjBRGX.js} +1 -1
  65. package/packages/ui/dist/assets/{nftPlaceholder-D2naVFFA.js → nftPlaceholder-DDTtQFge.js} +1 -1
  66. package/packages/ui/dist/assets/{off-O4fs0RcI.js → off-UsG8XtRe.js} +1 -1
  67. package/packages/ui/dist/assets/{parseSignature-Ipc8B6L-.js → parseSignature-CfnKWXKa.js} +1 -1
  68. package/packages/ui/dist/assets/{play-store-BySsEKjB.js → play-store-DCX3LKbh.js} +1 -1
  69. package/packages/ui/dist/assets/{plus-DcwXbThh.js → plus-JIY8UK-q.js} +1 -1
  70. package/packages/ui/dist/assets/{qr-code-DXcikaWN.js → qr-code-D7zoAbI2.js} +1 -1
  71. package/packages/ui/dist/assets/{recycle-horizontal-QHdoxezF.js → recycle-horizontal-D-TJ0tMe.js} +1 -1
  72. package/packages/ui/dist/assets/{refresh-CimMVwX6.js → refresh-BLW9ZCWM.js} +1 -1
  73. package/packages/ui/dist/assets/{reown-logo-DAmY3tUR.js → reown-logo-a6-yZeCb.js} +1 -1
  74. package/packages/ui/dist/assets/{search-YYHOSKxV.js → search-DL22Jf3a.js} +1 -1
  75. package/packages/ui/dist/assets/{secp256k1-DziXvsDr.js → secp256k1-CcCxXqQL.js} +1 -1
  76. package/packages/ui/dist/assets/{send-BohgZ4SZ.js → send-CEqsNJ4v.js} +1 -1
  77. package/packages/ui/dist/assets/{swapHorizontal-gdiztcz1.js → swapHorizontal-qHIvFSq_.js} +1 -1
  78. package/packages/ui/dist/assets/{swapHorizontalBold-C4PPuw1r.js → swapHorizontalBold-BPLu_S-H.js} +1 -1
  79. package/packages/ui/dist/assets/{swapHorizontalMedium-CmhTo_53.js → swapHorizontalMedium-BtzOrTEk.js} +1 -1
  80. package/packages/ui/dist/assets/{swapHorizontalRoundedBold-BPNMkAqM.js → swapHorizontalRoundedBold-CxFUoyan.js} +1 -1
  81. package/packages/ui/dist/assets/{swapVertical-Cnulu56K.js → swapVertical-CKwy7QFB.js} +1 -1
  82. package/packages/ui/dist/assets/{telegram-rBBqAA42.js → telegram-NqtkQg8v.js} +1 -1
  83. package/packages/ui/dist/assets/{three-dots-DhYHC0m3.js → three-dots-CVGMz7ju.js} +1 -1
  84. package/packages/ui/dist/assets/{twitch-DKwUBfEi.js → twitch-DLWcevwY.js} +1 -1
  85. package/packages/ui/dist/assets/{twitterIcon-BEW1pHCf.js → twitterIcon-BWNZUbJU.js} +1 -1
  86. package/packages/ui/dist/assets/{verify-filled-BGkV52th.js → verify-filled-nLelz9C-.js} +1 -1
  87. package/packages/ui/dist/assets/{verify-BVZjkQ2n.js → verify-rPul4L0m.js} +1 -1
  88. package/packages/ui/dist/assets/{w3m-modal-B7m-K8vL.js → w3m-modal-jmFSiKg3.js} +1 -1
  89. package/packages/ui/dist/assets/{wallet-BOwiO_Zr.js → wallet-CbYcUDfO.js} +1 -1
  90. package/packages/ui/dist/assets/{wallet-placeholder-C5O9rl_6.js → wallet-placeholder-6xP3kuxz.js} +1 -1
  91. package/packages/ui/dist/assets/{walletconnect-CKSy8TKP.js → walletconnect-Bj3tR3Jr.js} +1 -1
  92. package/packages/ui/dist/assets/{warning-circle-CwXtaT0N.js → warning-circle-vtLDBHkc.js} +1 -1
  93. package/packages/ui/dist/assets/{x-32UJYpvE.js → x-C5WNnyzd.js} +1 -1
  94. package/packages/ui/dist/index.html +1 -1
  95. package/packages/ui/dist/assets/cursor-DeDBddRQ.js +0 -3
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-DziXvsDr.js","assets/index-C62B8KTP.js","assets/index-CxWif5qB.css","assets/events-Bzlx_C-j.js","assets/core-DjR_jD64.js","assets/fallback-QmdVrhdj.js"])))=>i.map(i=>d[i]);
2
- import{cM as jd,bk as el,cS as tl,bQ as vt}from"./index-C62B8KTP.js";import{e as rt,N as Do}from"./events-Bzlx_C-j.js";function pr(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function rl(t,e){let r;const i=()=>{if(r)return r;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),r=pr(s),r.then(n=>{n.onclose=()=>r=void 0},()=>{}),r};return(s,n)=>i().then(o=>n(o.transaction(e,s).objectStore(e)))}let Js;function Bi(){return Js||(Js=rl("keyval-store","keyval")),Js}function ia(t,e=Bi()){return e("readonly",r=>pr(r.get(t)))}function Ud(t,e,r=Bi()){return r("readwrite",i=>(i.put(e,t),pr(i.transaction)))}function Fd(t,e=Bi()){return e("readwrite",r=>(r.delete(t),pr(r.transaction)))}function Ld(t=Bi()){return t("readwrite",e=>(e.clear(),pr(e.transaction)))}function kd(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},pr(t.transaction)}function Md(t=Bi()){return t("readonly",e=>{if(e.getAllKeys)return pr(e.getAllKeys());const r=[];return kd(e,i=>r.push(i.key)).then(()=>r)})}var sa=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},qd=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),zd=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),Hd=function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t}(),Vd=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Kd=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Wd=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Gd=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,na=3,Yd=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Wd]],oa=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function Jd(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Kd:typeof navigator<"u"?Qd(navigator.userAgent):ep()}function Zd(t){return t!==""&&Yd.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function Qd(t){var e=Zd(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new Vd;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<na&&(s=sa(sa([],s,!0),tp(na-s.length),!0)):s=[];var n=s.join("."),o=Xd(t),a=Gd.exec(t);return a&&a[1]?new Hd(r,n,o,a[1]):new qd(r,n,o)}function Xd(t){for(var e=0,r=oa.length;e<r;e++){var i=oa[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function ep(){var t=typeof process<"u"&&process.version;return t?new zd(process.version.slice(1)):null}function tp(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var N={};/*! *****************************************************************************
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-CcCxXqQL.js","assets/index-BrDR678h.js","assets/index-CxWif5qB.css","assets/events-C79WI7iD.js","assets/core-tNZO_nnA.js","assets/fallback-BQkB1W8W.js"])))=>i.map(i=>d[i]);
2
+ import{cM as jd,bk as el,cS as tl,bQ as vt}from"./index-BrDR678h.js";import{e as rt,N as Do}from"./events-C79WI7iD.js";function pr(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function rl(t,e){let r;const i=()=>{if(r)return r;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),r=pr(s),r.then(n=>{n.onclose=()=>r=void 0},()=>{}),r};return(s,n)=>i().then(o=>n(o.transaction(e,s).objectStore(e)))}let Js;function Bi(){return Js||(Js=rl("keyval-store","keyval")),Js}function ia(t,e=Bi()){return e("readonly",r=>pr(r.get(t)))}function Ud(t,e,r=Bi()){return r("readwrite",i=>(i.put(e,t),pr(i.transaction)))}function Fd(t,e=Bi()){return e("readwrite",r=>(r.delete(t),pr(r.transaction)))}function Ld(t=Bi()){return t("readwrite",e=>(e.clear(),pr(e.transaction)))}function kd(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},pr(t.transaction)}function Md(t=Bi()){return t("readonly",e=>{if(e.getAllKeys)return pr(e.getAllKeys());const r=[];return kd(e,i=>r.push(i.key)).then(()=>r)})}var sa=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},qd=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),zd=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),Hd=function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t}(),Vd=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Kd=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Wd=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Gd=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,na=3,Yd=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Wd]],oa=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function Jd(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Kd:typeof navigator<"u"?Qd(navigator.userAgent):ep()}function Zd(t){return t!==""&&Yd.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function Qd(t){var e=Zd(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new Vd;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<na&&(s=sa(sa([],s,!0),tp(na-s.length),!0)):s=[];var n=s.join("."),o=Xd(t),a=Gd.exec(t);return a&&a[1]?new Hd(r,n,o,a[1]):new qd(r,n,o)}function Xd(t){for(var e=0,r=oa.length;e<r;e++){var i=oa[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function ep(){var t=typeof process<"u"&&process.version;return t?new zd(process.version.slice(1)):null}function tp(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var N={};/*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
5
5
  Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
13
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
14
  PERFORMANCE OF THIS SOFTWARE.
15
15
  ***************************************************************************** */var jn=function(t,e){return jn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},jn(t,e)};function rp(t,e){jn(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Un=function(){return Un=Object.assign||function(e){for(var r,i=1,s=arguments.length;i<s;i++){r=arguments[i];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Un.apply(this,arguments)};function ip(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]]);return r}function sp(t,e,r,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,r,n):o(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n}function np(t,e){return function(r,i){e(r,i,t)}}function op(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function ap(t,e,r,i){function s(n){return n instanceof r?n:new r(function(o){o(n)})}return new(r||(r=Promise))(function(n,o){function a(l){try{h(i.next(l))}catch(u){o(u)}}function c(l){try{h(i.throw(l))}catch(u){o(u)}}function h(l){l.done?n(l.value):s(l.value).then(a,c)}h((i=i.apply(t,e||[])).next())})}function cp(t,e){var r={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(h){return function(l){return c([h,l])}}function c(h){if(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,s&&(n=h[0]&2?s.return:h[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,h[1])).done)return n;switch(s=0,n&&(h=[h[0]&2,n.value]),h[0]){case 0:case 1:n=h;break;case 4:return r.label++,{value:h[1],done:!1};case 5:r.label++,s=h[1],h=[0];continue;case 7:h=r.ops.pop(),r.trys.pop();continue;default:if(n=r.trys,!(n=n.length>0&&n[n.length-1])&&(h[0]===6||h[0]===2)){r=0;continue}if(h[0]===3&&(!n||h[1]>n[0]&&h[1]<n[3])){r.label=h[1];break}if(h[0]===6&&r.label<n[1]){r.label=n[1],n=h;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(h);break}n[2]&&r.ops.pop(),r.trys.pop();continue}h=e.call(t,r)}catch(l){h=[6,l],s=0}finally{i=n=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}}function hp(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function lp(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Fn(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function il(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return n}function up(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(il(arguments[e]));return t}function dp(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),s=0,e=0;e<r;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function Si(t){return this instanceof Si?(this.v=t,this):new Si(t)}function pp(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(d){i[d]&&(s[d]=function(f){return new Promise(function(p,y){n.push([d,f,p,y])>1||a(d,f)})})}function a(d,f){try{c(i[d](f))}catch(p){u(n[0][3],p)}}function c(d){d.value instanceof Si?Promise.resolve(d.value.v).then(h,l):u(n[0][2],d)}function h(d){a("next",d)}function l(d){a("throw",d)}function u(d,f){d(f),n.shift(),n.length&&a(n[0][0],n[0][1])}}function fp(t){var e,r;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=t[s]?function(o){return(r=!r)?{value:Si(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function gp(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Fn=="function"?Fn(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(n){r[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(h){n({value:h,done:a})},o)}}function yp(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function mp(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function wp(t){return t&&t.__esModule?t:{default:t}}function bp(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function vp(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const Ep=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Un},__asyncDelegator:fp,__asyncGenerator:pp,__asyncValues:gp,__await:Si,__awaiter:ap,__classPrivateFieldGet:bp,__classPrivateFieldSet:vp,__createBinding:hp,__decorate:sp,__exportStar:lp,__extends:rp,__generator:cp,__importDefault:wp,__importStar:mp,__makeTemplateObject:yp,__metadata:op,__param:np,__read:il,__rest:ip,__spread:up,__spreadArrays:dp,__values:Fn},Symbol.toStringTag,{value:"Module"})),ji=jd(Ep);var Zs={},ai={},aa;function _p(){if(aa)return ai;aa=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return ai.delay=t,ai}var Gt={},Qs={},Yt={},ca;function Ip(){return ca||(ca=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.ONE_THOUSAND=Yt.ONE_HUNDRED=void 0,Yt.ONE_HUNDRED=100,Yt.ONE_THOUSAND=1e3),Yt}var Xs={},ha;function $p(){return ha||(ha=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(Xs)),Xs}var la;function sl(){return la||(la=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ji;e.__exportStar(Ip(),t),e.__exportStar($p(),t)}(Qs)),Qs}var ua;function Dp(){if(ua)return Gt;ua=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.fromMiliseconds=Gt.toMiliseconds=void 0;const t=sl();function e(i){return i*t.ONE_THOUSAND}Gt.toMiliseconds=e;function r(i){return Math.floor(i/t.ONE_THOUSAND)}return Gt.fromMiliseconds=r,Gt}var da;function Sp(){return da||(da=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ji;e.__exportStar(_p(),t),e.__exportStar(Dp(),t)}(Zs)),Zs}var vr={},pa;function Op(){if(pa)return vr;pa=1,Object.defineProperty(vr,"__esModule",{value:!0}),vr.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const i=this.get(r);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const s=Date.now()-i.started;this.timestamps.set(r,{started:i.started,elapsed:s})}get(r){const i=this.timestamps.get(r);if(typeof i>"u")throw new Error(`No timestamp found for label: ${r}`);return i}elapsed(r){const i=this.get(r);return i.elapsed||Date.now()-i.started}}return vr.Watch=t,vr.default=t,vr}var en={},ci={},fa;function Pp(){if(fa)return ci;fa=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.IWatch=void 0;class t{}return ci.IWatch=t,ci}var ga;function Ap(){return ga||(ga=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),ji.__exportStar(Pp(),t)}(en)),en}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ji;e.__exportStar(Sp(),t),e.__exportStar(Op(),t),e.__exportStar(Ap(),t),e.__exportStar(sl(),t)})(N);var oe={};Object.defineProperty(oe,"__esModule",{value:!0});oe.getLocalStorage=oe.getLocalStorageOrThrow=oe.getCrypto=oe.getCryptoOrThrow=nl=oe.getLocation=oe.getLocationOrThrow=So=oe.getNavigator=oe.getNavigatorOrThrow=ar=oe.getDocument=oe.getDocumentOrThrow=oe.getFromWindowOrThrow=oe.getFromWindow=void 0;function fr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}oe.getFromWindow=fr;function Xr(t){const e=fr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}oe.getFromWindowOrThrow=Xr;function xp(){return Xr("document")}oe.getDocumentOrThrow=xp;function Cp(){return fr("document")}var ar=oe.getDocument=Cp;function Tp(){return Xr("navigator")}oe.getNavigatorOrThrow=Tp;function Rp(){return fr("navigator")}var So=oe.getNavigator=Rp;function Np(){return Xr("location")}oe.getLocationOrThrow=Np;function Bp(){return fr("location")}var nl=oe.getLocation=Bp;function jp(){return Xr("crypto")}oe.getCryptoOrThrow=jp;function Up(){return fr("crypto")}oe.getCrypto=Up;function Fp(){return Xr("localStorage")}oe.getLocalStorageOrThrow=Fp;function Lp(){return fr("localStorage")}oe.getLocalStorage=Lp;var Oo={};Object.defineProperty(Oo,"__esModule",{value:!0});var ol=Oo.getWindowMetadata=void 0;const ya=oe;function kp(){let t,e;try{t=ya.getDocumentOrThrow(),e=ya.getLocationOrThrow()}catch{return null}function r(){const u=t.getElementsByTagName("link"),d=[];for(let f=0;f<u.length;f++){const p=u[f],y=p.getAttribute("rel");if(y&&y.toLowerCase().indexOf("icon")>-1){const w=p.getAttribute("href");if(w)if(w.toLowerCase().indexOf("https:")===-1&&w.toLowerCase().indexOf("http:")===-1&&w.indexOf("//")!==0){let v=e.protocol+"//"+e.host;if(w.indexOf("/")===0)v+=w;else{const b=e.pathname.split("/");b.pop();const E=b.join("/");v+=E+"/"+w}d.push(v)}else if(w.indexOf("//")===0){const v=e.protocol+w;d.push(v)}else d.push(w)}}return d}function i(...u){const d=t.getElementsByTagName("meta");for(let f=0;f<d.length;f++){const p=d[f],y=["itemprop","property","name"].map(w=>p.getAttribute(w)).filter(w=>w?u.includes(w):!1);if(y.length&&y){const w=p.getAttribute("content");if(w)return w}}return""}function s(){let u=i("name","og:site_name","og:title","twitter:title");return u||(u=t.title),u}function n(){return i("description","og:description","twitter:description","keywords")}const o=s(),a=n(),c=e.origin,h=r();return{description:a,url:c,icons:h,name:o}}ol=Oo.getWindowMetadata=kp;function Oi(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function ma(t){return Oi(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const al="2.23.2";let hi={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${al}`};class cr extends Error{constructor(e,r={}){var a;const i=(()=>{var c;return r.cause instanceof cr?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),s=r.cause instanceof cr&&r.cause.docsPath||r.docsPath,n=(a=hi.getDocsUrl)==null?void 0:a.call(hi,{...r,docsPath:s}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...i?[`Details: ${i}`]:[],...hi.version?[`Version: ${hi.version}`]:[]].join(`
16
- `);super(o,r.cause?{cause:r.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=i,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=al}walk(e){return cl(this,e)}}function cl(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?cl(t.cause,e):e?null:t}class hl extends cr{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function ei(t,{dir:e,size:r=32}={}){return typeof t=="string"?Mp(t,{dir:e,size:r}):qp(t,{dir:e,size:r})}function Mp(t,{dir:e,size:r=32}={}){if(r===null)return t;const i=t.replace("0x","");if(i.length>r*2)throw new hl({size:Math.ceil(i.length/2),targetSize:r,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function qp(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new hl({size:t.length,targetSize:r,type:"bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const n=e==="right";i[n?s:r-s-1]=t[n?s:t.length-s-1]}return i}class zp extends cr{constructor({max:e,min:r,signed:i,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class Hp extends cr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ti(t,{size:e}){if(ma(t)>e)throw new Hp({givenSize:ma(t),maxSize:e})}function Ln(t,e={}){const{signed:r}=e;e.size&&ti(t,{size:e.size});const i=BigInt(t);if(!r)return i;const s=(t.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function Vp(t,e={}){return Number(Ln(t,e))}const Kp=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function kn(t,e={}){return typeof t=="number"||typeof t=="bigint"?ul(t,e):typeof t=="string"?Yp(t,e):typeof t=="boolean"?Wp(t,e):ll(t,e)}function Wp(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(ti(r,{size:e.size}),ei(r,{size:e.size})):r}function ll(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=Kp[t[s]];const i=`0x${r}`;return typeof e.size=="number"?(ti(i,{size:e.size}),ei(i,{dir:"right",size:e.size})):i}function ul(t,e={}){const{signed:r,size:i}=e,s=BigInt(t);let n;i?r?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&r?-n-1n:0;if(n&&s>n||s<o){const c=typeof t=="bigint"?"n":"";throw new zp({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:r,size:i,value:`${t}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?ei(a,{size:i}):a}const Gp=new TextEncoder;function Yp(t,e={}){const r=Gp.encode(t);return ll(r,e)}const Jp=new TextEncoder;function Zp(t,e={}){return typeof t=="number"||typeof t=="bigint"?Xp(t,e):typeof t=="boolean"?Qp(t,e):Oi(t)?dl(t,e):pl(t,e)}function Qp(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(ti(r,{size:e.size}),ei(r,{size:e.size})):r}const Dt={zero:48,nine:57,A:65,F:70,a:97,f:102};function wa(t){if(t>=Dt.zero&&t<=Dt.nine)return t-Dt.zero;if(t>=Dt.A&&t<=Dt.F)return t-(Dt.A-10);if(t>=Dt.a&&t<=Dt.f)return t-(Dt.a-10)}function dl(t,e={}){let r=t;e.size&&(ti(r,{size:e.size}),r=ei(r,{dir:"right",size:e.size}));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=wa(i.charCodeAt(a++)),h=wa(i.charCodeAt(a++));if(c===void 0||h===void 0)throw new cr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+h}return n}function Xp(t,e){const r=ul(t,e);return dl(r)}function pl(t,e={}){const r=Jp.encode(t);return typeof e.size=="number"?(ti(r,{size:e.size}),ei(r,{dir:"right",size:e.size})):r}function ws(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ef(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xs(t,...e){if(!ef(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 mO(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ws(t.outputLen),ws(t.blockLen)}function ba(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 tf(t,e){xs(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Gi=BigInt(2**32-1),va=BigInt(32);function rf(t,e=!1){return e?{h:Number(t&Gi),l:Number(t>>va&Gi)}:{h:Number(t>>va&Gi)|0,l:Number(t&Gi)|0}}function sf(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=rf(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const nf=(t,e,r)=>t<<r|e>>>32-r,of=(t,e,r)=>e<<r|t>>>32-r,af=(t,e,r)=>e<<r-32|t>>>64-r,cf=(t,e,r)=>t<<r-32|e>>>64-r,Er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function hf(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function wO(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function bO(t,e){return t<<32-e|t>>>e}const Ea=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function lf(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function _a(t){for(let e=0;e<t.length;e++)t[e]=lf(t[e])}function uf(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function fl(t){return typeof t=="string"&&(t=uf(t)),xs(t),t}function vO(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];xs(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}class df{clone(){return this._cloneInto()}}function pf(t){const e=i=>t().update(fl(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function EO(t=32){if(Er&&typeof Er.getRandomValues=="function")return Er.getRandomValues(new Uint8Array(t));if(Er&&typeof Er.randomBytes=="function")return Er.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const gl=[],yl=[],ml=[],ff=BigInt(0),li=BigInt(1),gf=BigInt(2),yf=BigInt(7),mf=BigInt(256),wf=BigInt(113);for(let t=0,e=li,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],gl.push(2*(5*i+r)),yl.push((t+1)*(t+2)/2%64);let s=ff;for(let n=0;n<7;n++)e=(e<<li^(e>>yf)*wf)%mf,e&gf&&(s^=li<<(li<<BigInt(n))-li);ml.push(s)}const[bf,vf]=sf(ml,!0),Ia=(t,e,r)=>r>32?af(t,e,r):nf(t,e,r),$a=(t,e,r)=>r>32?cf(t,e,r):of(t,e,r);function Ef(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[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,h=r[c],l=r[c+1],u=Ia(h,l,1)^r[a],d=$a(h,l,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=u,t[o+f+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=yl[o],c=Ia(s,n,a),h=$a(s,n,a),l=gl[o];s=t[l],n=t[l+1],t[l]=c,t[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=bf[i],t[1]^=vf[i]}r.fill(0)}class Po extends df{constructor(e,r,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ws(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=hf(this.state)}keccak(){Ea||_a(this.state32),Ef(this.state32,this.rounds),Ea||_a(this.state32),this.posOut=0,this.pos=0}update(e){ba(this);const{blockLen:r,state:i}=this;e=fl(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){ba(this,!1),xs(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=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 ws(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(tf(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,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Po(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const _f=(t,e,r)=>pf(()=>new Po(e,t,r)),If=_f(1,136,256/8);function wl(t,e){const r=e||"hex",i=If(Oi(t,{strict:!1})?Zp(t):t);return r==="bytes"?i:kn(i)}class $f extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const tn=new $f(8192);function Df(t,e){if(tn.has(`${t}.${e}`))return tn.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),i=wl(pl(r),"bytes"),s=r.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(i[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return tn.set(`${t}.${e}`,n),n}function Sf(t){const e=wl(`0x${t.substring(4)}`).substring(26);return Df(`0x${e}`)}async function Of({hash:t,signature:e}){const r=Oi(t)?t:kn(t),{secp256k1:i}=await el(async()=>{const{secp256k1:o}=await import("./secp256k1-DziXvsDr.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:u,yParity:d}=e,f=Number(d??u),p=Da(f);return new i.Signature(Ln(h),Ln(l)).addRecoveryBit(p)}const o=Oi(e)?e:kn(e),a=Vp(`0x${o.slice(130)}`),c=Da(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Da(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Pf({hash:t,signature:e}){return Sf(await Of({hash:t,signature:e}))}function Af(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<t.length;h++){const l=t.charAt(h),u=l.charCodeAt(0);if(e[u]!==255)throw new TypeError(l+" is ambiguous");e[u]=h}const r=t.length,i=t.charAt(0),s=Math.log(r)/Math.log(256),n=Math.log(256)/Math.log(r);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let l=0,u=0,d=0;const f=h.length;for(;d!==f&&h[d]===0;)d++,l++;const p=(f-d)*n+1>>>0,y=new Uint8Array(p);for(;d!==f;){let b=h[d],E=0;for(let I=p-1;(b!==0||E<u)&&I!==-1;I--,E++)b+=256*y[I]>>>0,y[I]=b%r>>>0,b=b/r>>>0;if(b!==0)throw new Error("Non-zero carry");u=E,d++}let w=p-u;for(;w!==p&&y[w]===0;)w++;let v=i.repeat(l);for(;w<p;++w)v+=t.charAt(y[w]);return v}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,u=0,d=0;for(;h[l]===i;)u++,l++;const f=(h.length-l)*s+1>>>0,p=new Uint8Array(f);for(;l<h.length;){const b=h.charCodeAt(l);if(b>255)return;let E=e[b];if(E===255)return;let I=0;for(let P=f-1;(E!==0||I<d)&&P!==-1;P--,I++)E+=r*p[P]>>>0,p[P]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=I,l++}let y=f-d;for(;y!==f&&p[y]===0;)y++;const w=new Uint8Array(u+(f-y));let v=u;for(;y!==f;)w[v++]=p[y++];return w}function c(h){const l=a(h);if(l)return l;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var xf="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Cf=Af(xf),Tf=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),Rf=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function hr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Rf(t)}catch{return t}}function jt(t){return typeof t=="string"?t:Tf(t)||""}function Nf(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function bl(t,...e){if(!Nf(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 Sa(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 Bf(t,e){bl(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const _r=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rn=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function jf(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function vl(t){return typeof t=="string"&&(t=jf(t)),bl(t),t}let Uf=class{clone(){return this._cloneInto()}};function Ff(t){const e=i=>t().update(vl(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function El(t=32){if(_r&&typeof _r.getRandomValues=="function")return _r.getRandomValues(new Uint8Array(t));if(_r&&typeof _r.randomBytes=="function")return _r.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Lf(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,h=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+h,a,i)}let kf=class extends Uf{constructor(e,r,i,s){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=rn(this.buffer)}update(e){Sa(this);const{view:r,buffer:i,blockLen:s}=this;e=vl(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=rn(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Sa(this),Bf(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let u=o;u<s;u++)r[u]=0;Lf(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=rn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%r&&e.buffer.set(i),e}};const Yi=BigInt(2**32-1),Mn=BigInt(32);function _l(t,e=!1){return e?{h:Number(t&Yi),l:Number(t>>Mn&Yi)}:{h:Number(t>>Mn&Yi)|0,l:Number(t&Yi)|0}}function Mf(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=_l(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const qf=(t,e)=>BigInt(t>>>0)<<Mn|BigInt(e>>>0),zf=(t,e,r)=>t>>>r,Hf=(t,e,r)=>t<<32-r|e>>>r,Vf=(t,e,r)=>t>>>r|e<<32-r,Kf=(t,e,r)=>t<<32-r|e>>>r,Wf=(t,e,r)=>t<<64-r|e>>>r-32,Gf=(t,e,r)=>t>>>r-32|e<<64-r,Yf=(t,e)=>e,Jf=(t,e)=>t,Zf=(t,e,r)=>t<<r|e>>>32-r,Qf=(t,e,r)=>e<<r|t>>>32-r,Xf=(t,e,r)=>e<<r-32|t>>>64-r,eg=(t,e,r)=>t<<r-32|e>>>64-r;function tg(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const rg=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),ig=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,sg=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),ng=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,og=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),ag=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,V={fromBig:_l,split:Mf,toBig:qf,shrSH:zf,shrSL:Hf,rotrSH:Vf,rotrSL:Kf,rotrBH:Wf,rotrBL:Gf,rotr32H:Yf,rotr32L:Jf,rotlSH:Zf,rotlSL:Qf,rotlBH:Xf,rotlBL:eg,add:tg,add3L:rg,add3H:ig,add4L:sg,add4H:ng,add5H:ag,add5L:og},[cg,hg]=V.split(["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))),Ut=new Uint32Array(80),Ft=new Uint32Array(80);let lg=class extends kf{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:h,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:y,Hl:w}=this;return[e,r,i,s,n,o,a,c,h,l,u,d,f,p,y,w]}set(e,r,i,s,n,o,a,c,h,l,u,d,f,p,y,w){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=h|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=y|0,this.Hl=w|0}process(e,r){for(let E=0;E<16;E++,r+=4)Ut[E]=e.getUint32(r),Ft[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){const I=Ut[E-15]|0,P=Ft[E-15]|0,A=V.rotrSH(I,P,1)^V.rotrSH(I,P,8)^V.shrSH(I,P,7),O=V.rotrSL(I,P,1)^V.rotrSL(I,P,8)^V.shrSL(I,P,7),C=Ut[E-2]|0,D=Ft[E-2]|0,M=V.rotrSH(C,D,19)^V.rotrBH(C,D,61)^V.shrSH(C,D,6),U=V.rotrSL(C,D,19)^V.rotrBL(C,D,61)^V.shrSL(C,D,6),j=V.add4L(O,U,Ft[E-7],Ft[E-16]),q=V.add4H(j,A,M,Ut[E-7],Ut[E-16]);Ut[E]=q|0,Ft[E]=j|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:h,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:y,Gl:w,Hh:v,Hl:b}=this;for(let E=0;E<80;E++){const I=V.rotrSH(u,d,14)^V.rotrSH(u,d,18)^V.rotrBH(u,d,41),P=V.rotrSL(u,d,14)^V.rotrSL(u,d,18)^V.rotrBL(u,d,41),A=u&f^~u&y,O=d&p^~d&w,C=V.add5L(b,P,O,hg[E],Ft[E]),D=V.add5H(C,v,I,A,cg[E],Ut[E]),M=C|0,U=V.rotrSH(i,s,28)^V.rotrBH(i,s,34)^V.rotrBH(i,s,39),j=V.rotrSL(i,s,28)^V.rotrBL(i,s,34)^V.rotrBL(i,s,39),q=i&n^i&a^n&a,T=s&o^s&c^o&c;v=y|0,b=w|0,y=f|0,w=p|0,f=u|0,p=d|0,{h:u,l:d}=V.add(h|0,l|0,D|0,M|0),h=a|0,l=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const g=V.add3L(M,j,T);i=V.add3H(g,D,U,q),s=g|0}({h:i,l:s}=V.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=V.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=V.add(this.Ch|0,this.Cl|0,a|0,c|0),{h,l}=V.add(this.Dh|0,this.Dl|0,h|0,l|0),{h:u,l:d}=V.add(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=V.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:y,l:w}=V.add(this.Gh|0,this.Gl|0,y|0,w|0),{h:v,l:b}=V.add(this.Hh|0,this.Hl|0,v|0,b|0),this.set(i,s,n,o,a,c,h,l,u,d,f,p,y,w,v,b)}roundClean(){Ut.fill(0),Ft.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};const ug=Ff(()=>new lg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ao=BigInt(0),Il=BigInt(1),dg=BigInt(2);function xo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Co(t){if(!xo(t))throw new Error("Uint8Array expected")}function sn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const pg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function To(t){Co(t);let e="";for(let r=0;r<t.length;r++)e+=pg[t[r]];return e}function $l(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ao:BigInt("0x"+t)}const St={_0:48,_9:57,A:65,F:70,a:97,f:102};function Oa(t){if(t>=St._0&&t<=St._9)return t-St._0;if(t>=St.A&&t<=St.F)return t-(St.A-10);if(t>=St.a&&t<=St.f)return t-(St.a-10)}function Dl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Oa(t.charCodeAt(n)),a=Oa(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function fg(t){return $l(To(t))}function us(t){return Co(t),$l(To(Uint8Array.from(t).reverse()))}function Sl(t,e){return Dl(t.toString(16).padStart(e*2,"0"))}function qn(t,e){return Sl(t,e).reverse()}function Ot(t,e,r){let i;if(typeof e=="string")try{i=Dl(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(xo(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function Pa(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];Co(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}const nn=t=>typeof t=="bigint"&&Ao<=t;function gg(t,e,r){return nn(t)&&nn(e)&&nn(r)&&e<=t&&t<r}function ui(t,e,r,i){if(!gg(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function yg(t){let e;for(e=0;t>Ao;t>>=Il,e+=1);return e}const mg=t=>(dg<<BigInt(t-1))-Il,wg={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"||xo(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 Ro(t,e,r={}){const i=(s,n,o)=>{const a=wg[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}function Aa(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}const be=BigInt(0),ce=BigInt(1),er=BigInt(2),bg=BigInt(3),zn=BigInt(4),xa=BigInt(5),Ca=BigInt(8);function pe(t,e){const r=t%e;return r>=be?r:e+r}function vg(t,e,r){if(e<be)throw new Error("invalid exponent, negatives unsupported");if(r<=be)throw new Error("invalid modulus");if(r===ce)return be;let i=ce;for(;e>be;)e&ce&&(i=i*t%r),t=t*t%r,e>>=ce;return i}function pt(t,e,r){let i=t;for(;e-- >be;)i*=i,i%=r;return i}function Ta(t,e){if(t===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let r=pe(t,e),i=e,s=be,n=ce;for(;r!==be;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==ce)throw new Error("invert: does not exist");return pe(s,e)}function Eg(t){const e=(t-ce)/er;let r,i,s;for(r=t-ce,i=0;r%er===be;r/=er,i++);for(s=er;s<t&&vg(s,e,t)!==t-ce;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+ce)/zn;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(r+ce)/er;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,h=o.pow(o.mul(o.ONE,s),r),l=o.pow(a,n),u=o.pow(a,r);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let d=1;for(let p=o.sqr(u);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const f=o.pow(h,ce<<BigInt(c-d-1));h=o.sqr(f),l=o.mul(l,f),u=o.mul(u,h),c=d}return l}}function _g(t){if(t%zn===bg){const e=(t+ce)/zn;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%Ca===xa){const e=(t-xa)/Ca;return function(r,i){const s=r.mul(i,er),n=r.pow(s,e),o=r.mul(i,n),a=r.mul(r.mul(o,er),n),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return Eg(t)}const Ig=(t,e)=>(pe(t,e)&ce)===ce,$g=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Dg(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=$g.reduce((i,s)=>(i[s]="function",i),e);return Ro(t,r)}function Sg(t,e,r){if(r<be)throw new Error("invalid exponent, negatives unsupported");if(r===be)return t.ONE;if(r===ce)return e;let i=t.ONE,s=e;for(;r>be;)r&ce&&(i=t.mul(i,s)),s=t.sqr(s),r>>=ce;return i}function Og(t,e){const r=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(r[a]=n,t.mul(n,o)),t.ONE),s=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(r[a]=t.mul(n,r[a]),t.mul(n,o)),s),r}function Ol(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Pl(t,e,r=!1,i={}){if(t<=be)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=Ol(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:mg(s),ZERO:be,ONE:ce,create:c=>pe(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return be<=c&&c<t},is0:c=>c===be,isOdd:c=>(c&ce)===ce,neg:c=>pe(-c,t),eql:(c,h)=>c===h,sqr:c=>pe(c*c,t),add:(c,h)=>pe(c+h,t),sub:(c,h)=>pe(c-h,t),mul:(c,h)=>pe(c*h,t),pow:(c,h)=>Sg(a,c,h),div:(c,h)=>pe(c*Ta(h,t),t),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>Ta(c,t),sqrt:i.sqrt||(c=>(o||(o=_g(t)),o(a,c))),invertBatch:c=>Og(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>r?qn(c,n):Sl(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?us(c):fg(c)}});return Object.freeze(a)}const Ra=BigInt(0),Ji=BigInt(1);function on(t,e){const r=e.negate();return t?r:e}function Al(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function an(t,e){Al(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function Pg(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function Ag(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const cn=new WeakMap,xl=new WeakMap;function hn(t){return xl.get(t)||1}function xg(t,e){return{constTimeNegate:on,hasPrecomputes(r){return hn(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>Ra;)i&Ji&&(s=s.add(n)),n=n.double(),i>>=Ji;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=an(i,e),o=[];let a=r,c=a;for(let h=0;h<s;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){const{windows:n,windowSize:o}=an(r,e);let a=t.ZERO,c=t.BASE;const h=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&h);s>>=u,p>o&&(p-=l,s+=Ji);const y=f,w=f+Math.abs(p)-1,v=d%2!==0,b=p<0;p===0?c=c.add(on(v,i[y])):a=a.add(on(b,i[w]))}return{p:a,f:c}},wNAFUnsafe(r,i,s,n=t.ZERO){const{windows:o,windowSize:a}=an(r,e),c=BigInt(2**r-1),h=2**r,l=BigInt(r);for(let u=0;u<o;u++){const d=u*a;if(s===Ra)break;let f=Number(s&c);if(s>>=l,f>a&&(f-=h,s+=Ji),f===0)continue;let p=i[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(r,i,s){let n=cn.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&cn.set(i,s(n))),n},wNAFCached(r,i,s){const n=hn(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=hn(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){Al(i,e),xl.set(r,i),cn.delete(r)}}}function Cg(t,e,r,i){if(Pg(r,t),Ag(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=yg(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),h=Math.floor((e.BITS-1)/o)*o;let l=s;for(let u=h;u>=0;u-=o){c.fill(s);for(let f=0;f<i.length;f++){const p=i[f],y=Number(p>>BigInt(u)&BigInt(a));c[y]=c[y].add(r[f])}let d=s;for(let f=c.length-1,p=s;f>0;f--)p=p.add(c[f]),d=d.add(p);if(l=l.add(d),u!==0)for(let f=0;f<o;f++)l=l.double()}return l}function Tg(t){return Dg(t.Fp),Ro(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ol(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const nt=BigInt(0),Be=BigInt(1),Zi=BigInt(2),Rg=BigInt(8),Ng={zip215:!0};function Bg(t){const e=Tg(t);return Ro(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function jg(t){const e=Bg(t),{Fp:r,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,h=Zi<<BigInt(a*8)-Be,l=r.create,u=Pl(e.n,e.nBitLength),d=e.uvRatio||((g,m)=>{try{return{isValid:!0,value:r.sqrt(g*r.inv(m))}}catch{return{isValid:!1,value:nt}}}),f=e.adjustScalarBytes||(g=>g),p=e.domain||((g,m,_)=>{if(sn("phflag",_),m.length||_)throw new Error("Contexts/pre-hash are not supported");return g});function y(g,m){ui("coordinate "+g,m,nt,h)}function w(g){if(!(g instanceof E))throw new Error("ExtendedPoint expected")}const v=Aa((g,m)=>{const{ex:_,ey:S,ez:$}=g,x=g.is0();m==null&&(m=x?Rg:r.inv($));const F=l(_*m),k=l(S*m),z=l($*m);if(x)return{x:nt,y:Be};if(z!==Be)throw new Error("invZ was invalid");return{x:F,y:k}}),b=Aa(g=>{const{a:m,d:_}=e;if(g.is0())throw new Error("bad point: ZERO");const{ex:S,ey:$,ez:x,et:F}=g,k=l(S*S),z=l($*$),L=l(x*x),H=l(L*L),G=l(k*m),se=l(L*l(G+z)),ee=l(H+l(_*l(k*z)));if(se!==ee)throw new Error("bad point: equation left != right (1)");const Y=l(S*$),Ae=l(x*F);if(Y!==Ae)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(m,_,S,$){this.ex=m,this.ey=_,this.ez=S,this.et=$,y("x",m),y("y",_),y("z",S),y("t",$),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof E)throw new Error("extended point not allowed");const{x:_,y:S}=m||{};return y("x",_),y("y",S),new E(_,S,Be,l(_*S))}static normalizeZ(m){const _=r.invertBatch(m.map(S=>S.ez));return m.map((S,$)=>S.toAffine(_[$])).map(E.fromAffine)}static msm(m,_){return Cg(E,u,m,_)}_setWindowSize(m){A.setWindowSize(this,m)}assertValidity(){b(this)}equals(m){w(m);const{ex:_,ey:S,ez:$}=this,{ex:x,ey:F,ez:k}=m,z=l(_*k),L=l(x*$),H=l(S*k),G=l(F*$);return z===L&&H===G}is0(){return this.equals(E.ZERO)}negate(){return new E(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:m}=e,{ex:_,ey:S,ez:$}=this,x=l(_*_),F=l(S*S),k=l(Zi*l($*$)),z=l(m*x),L=_+S,H=l(l(L*L)-x-F),G=z+F,se=G-k,ee=z-F,Y=l(H*se),Ae=l(G*ee),Ee=l(H*ee),Ce=l(se*G);return new E(Y,Ae,Ce,Ee)}add(m){w(m);const{a:_,d:S}=e,{ex:$,ey:x,ez:F,et:k}=this,{ex:z,ey:L,ez:H,et:G}=m;if(_===BigInt(-1)){const Jo=l((x-$)*(L+z)),Zo=l((x+$)*(L-z)),Ys=l(Zo-Jo);if(Ys===nt)return this.double();const Qo=l(F*Zi*G),Xo=l(k*Zi*H),ea=Xo+Qo,ta=Zo+Jo,ra=Xo-Qo,Td=l(ea*Ys),Rd=l(ta*ra),Nd=l(ea*ra),Bd=l(Ys*ta);return new E(Td,Rd,Bd,Nd)}const se=l($*z),ee=l(x*L),Y=l(k*S*G),Ae=l(F*H),Ee=l(($+x)*(z+L)-se-ee),Ce=Ae-Y,Ye=Ae+Y,Je=l(ee-_*se),br=l(Ee*Ce),Ad=l(Ye*Je),xd=l(Ee*Je),Cd=l(Ce*Ye);return new E(br,Ad,Cd,xd)}subtract(m){return this.add(m.negate())}wNAF(m){return A.wNAFCached(this,m,E.normalizeZ)}multiply(m){const _=m;ui("scalar",_,Be,i);const{p:S,f:$}=this.wNAF(_);return E.normalizeZ([S,$])[0]}multiplyUnsafe(m,_=E.ZERO){const S=m;return ui("scalar",S,nt,i),S===nt?P:this.is0()||S===Be?this:A.wNAFCachedUnsafe(this,S,E.normalizeZ,_)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,i).is0()}toAffine(m){return v(this,m)}clearCofactor(){const{h:m}=e;return m===Be?this:this.multiplyUnsafe(m)}static fromHex(m,_=!1){const{d:S,a:$}=e,x=r.BYTES;m=Ot("pointHex",m,x),sn("zip215",_);const F=m.slice(),k=m[x-1];F[x-1]=k&-129;const z=us(F),L=_?h:r.ORDER;ui("pointHex.y",z,nt,L);const H=l(z*z),G=l(H-Be),se=l(S*H-$);let{isValid:ee,value:Y}=d(G,se);if(!ee)throw new Error("Point.fromHex: invalid y coordinate");const Ae=(Y&Be)===Be,Ee=(k&128)!==0;if(!_&&Y===nt&&Ee)throw new Error("Point.fromHex: x=0 and x_0=1");return Ee!==Ae&&(Y=l(-Y)),E.fromAffine({x:Y,y:z})}static fromPrivateKey(m){return D(m).point}toRawBytes(){const{x:m,y:_}=this.toAffine(),S=qn(_,r.BYTES);return S[S.length-1]|=m&Be?128:0,S}toHex(){return To(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,Be,l(e.Gx*e.Gy)),E.ZERO=new E(nt,Be,Be,nt);const{BASE:I,ZERO:P}=E,A=xg(E,a*8);function O(g){return pe(g,i)}function C(g){return O(us(g))}function D(g){const m=r.BYTES;g=Ot("private key",g,m);const _=Ot("hashed private key",n(g),2*m),S=f(_.slice(0,m)),$=_.slice(m,2*m),x=C(S),F=I.multiply(x),k=F.toRawBytes();return{head:S,prefix:$,scalar:x,point:F,pointBytes:k}}function M(g){return D(g).pointBytes}function U(g=new Uint8Array,...m){const _=Pa(...m);return C(n(p(_,Ot("context",g),!!s)))}function j(g,m,_={}){g=Ot("message",g),s&&(g=s(g));const{prefix:S,scalar:$,pointBytes:x}=D(m),F=U(_.context,S,g),k=I.multiply(F).toRawBytes(),z=U(_.context,k,x,g),L=O(F+z*$);ui("signature.s",L,nt,i);const H=Pa(k,qn(L,r.BYTES));return Ot("result",H,r.BYTES*2)}const q=Ng;function T(g,m,_,S=q){const{context:$,zip215:x}=S,F=r.BYTES;g=Ot("signature",g,2*F),m=Ot("message",m),_=Ot("publicKey",_,F),x!==void 0&&sn("zip215",x),s&&(m=s(m));const k=us(g.slice(F,2*F));let z,L,H;try{z=E.fromHex(_,x),L=E.fromHex(g.slice(0,F),x),H=I.multiplyUnsafe(k)}catch{return!1}if(!x&&z.isSmallOrder())return!1;const G=U($,L.toRawBytes(),z.toRawBytes(),m);return L.add(z.multiplyUnsafe(G)).subtract(H).clearCofactor().equals(E.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:M,sign:j,verify:T,ExtendedPoint:E,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>o(r.BYTES),precompute(g=8,m=E.BASE){return m._setWindowSize(g),m.multiply(BigInt(3)),m}}}}BigInt(0),BigInt(1);const No=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Na=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Ug=BigInt(1),Ba=BigInt(2);BigInt(3);const Fg=BigInt(5),Lg=BigInt(8);function kg(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=No,o=t*t%n*t%n,a=pt(o,Ba,n)*o%n,c=pt(a,Ug,n)*t%n,h=pt(c,Fg,n)*c%n,l=pt(h,e,n)*h%n,u=pt(l,r,n)*l%n,d=pt(u,i,n)*u%n,f=pt(d,s,n)*d%n,p=pt(f,s,n)*d%n,y=pt(p,e,n)*h%n;return{pow_p_5_8:pt(y,Ba,n)*t%n,b2:o}}function Mg(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function qg(t,e){const r=No,i=pe(e*e*e,r),s=pe(i*i*e,r),n=kg(t*s).pow_p_5_8;let o=pe(t*i*n,r);const a=pe(e*o*o,r),c=o,h=pe(o*Na,r),l=a===t,u=a===pe(-t,r),d=a===pe(-t*Na,r);return l&&(o=c),(u||d)&&(o=h),Ig(o,r)&&(o=pe(-o,r)),{isValid:l||u,value:o}}const zg=Pl(No,void 0,!0),Hg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:zg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Lg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ug,randomBytes:El,adjustScalarBytes:Mg,uvRatio:qg},Cl=jg(Hg),Vg="EdDSA",Kg="JWT",bs=".",Cs="base64url",Tl="utf8",Rl="utf8",Wg=":",Gg="did",Yg="key",ja="base58btc",Jg="z",Zg="K36",Qg=32;function Bo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Nl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Bo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Bl(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Nl(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return Bo(r)}function Xg(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var P=p[v],A=0,O=E-1;(P!==0||A<w)&&O!==-1;O--,A++)P+=256*I[O]>>>0,I[O]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var D=c.repeat(y);C<E;++C)D+=t.charAt(I[C]);return D}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*h+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var P=0,A=b-1;(I!==0||P<v)&&A!==-1;A--,P++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=P,y++}if(p[y]!==" "){for(var O=b-v;O!==b&&E[O]===0;)O++;for(var C=new Uint8Array(w+(b-O)),D=w;O!==b;)C[D++]=E[O++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:f}}var ey=Xg,ty=ey;const jl=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")},ry=t=>new TextEncoder().encode(t),iy=t=>new TextDecoder().decode(t);let sy=class{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ny=class{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}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 Ul(this,e)}},oy=class{constructor(e){this.decoders=e}or(e){return Ul(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Ul=(t,e)=>new oy({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let ay=class{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new sy(e,r,i),this.decoder=new ny(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Ts=({name:t,prefix:e,encode:r,decode:i})=>new ay(t,e,r,i),Ui=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=ty(r,e);return Ts({prefix:t,name:e,encode:i,decode:n=>jl(s(n))})},cy=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const u=s[t[l]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|u,a+=r,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},hy=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Se=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ts({prefix:e,name:t,encode(s){return hy(s,i,r)},decode(s){return cy(s,i,r,t)}}),ly=Ts({prefix:"\0",name:"identity",encode:t=>iy(t),decode:t=>ry(t)});var uy=Object.freeze({__proto__:null,identity:ly});const dy=Se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var py=Object.freeze({__proto__:null,base2:dy});const fy=Se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gy=Object.freeze({__proto__:null,base8:fy});const yy=Ui({prefix:"9",name:"base10",alphabet:"0123456789"});var my=Object.freeze({__proto__:null,base10:yy});const wy=Se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),by=Se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var vy=Object.freeze({__proto__:null,base16:wy,base16upper:by});const Ey=Se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),_y=Se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Iy=Se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$y=Se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Dy=Se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Sy=Se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Oy=Se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Py=Se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ay=Se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xy=Object.freeze({__proto__:null,base32:Ey,base32upper:_y,base32pad:Iy,base32padupper:$y,base32hex:Dy,base32hexupper:Sy,base32hexpad:Oy,base32hexpadupper:Py,base32z:Ay});const Cy=Ui({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ty=Ui({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ry=Object.freeze({__proto__:null,base36:Cy,base36upper:Ty});const Ny=Ui({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),By=Ui({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var jy=Object.freeze({__proto__:null,base58btc:Ny,base58flickr:By});const Uy=Se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Fy=Se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ly=Se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ky=Se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var My=Object.freeze({__proto__:null,base64:Uy,base64pad:Fy,base64url:Ly,base64urlpad:ky});const Fl=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),qy=Fl.reduce((t,e,r)=>(t[r]=e,t),[]),zy=Fl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Hy(t){return t.reduce((e,r)=>(e+=qy[r],e),"")}function Vy(t){const e=[];for(const r of t){const i=zy[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const Ky=Ts({prefix:"🚀",name:"base256emoji",encode:Hy,decode:Vy});var Wy=Object.freeze({__proto__:null,base256emoji:Ky}),Gy=Ll,Ua=128,Yy=-128,Jy=Math.pow(2,31);function Ll(t,e,r){e=e||[],r=r||0;for(var i=r;t>=Jy;)e[r++]=t&255|Ua,t/=128;for(;t&Yy;)e[r++]=t&255|Ua,t>>>=7;return e[r]=t|0,Ll.bytes=r-i+1,e}var Zy=Hn,Qy=128,Fa=127;function Hn(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw Hn.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Fa)<<s:(o&Fa)*Math.pow(2,s),s+=7}while(o>=Qy);return Hn.bytes=n-i,r}var Xy=Math.pow(2,7),em=Math.pow(2,14),tm=Math.pow(2,21),rm=Math.pow(2,28),im=Math.pow(2,35),sm=Math.pow(2,42),nm=Math.pow(2,49),om=Math.pow(2,56),am=Math.pow(2,63),cm=function(t){return t<Xy?1:t<em?2:t<tm?3:t<rm?4:t<im?5:t<sm?6:t<nm?7:t<om?8:t<am?9:10},hm={encode:Gy,decode:Zy,encodingLength:cm},kl=hm;const La=(t,e,r=0)=>(kl.encode(t,e,r),e),ka=t=>kl.encodingLength(t),Vn=(t,e)=>{const r=e.byteLength,i=ka(t),s=i+ka(r),n=new Uint8Array(s+r);return La(t,n,0),La(r,n,i),n.set(e,s),new lm(t,r,e,n)};let lm=class{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}};const Ml=({name:t,code:e,encode:r})=>new um(t,e,r);let um=class{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Vn(this.code,r):r.then(i=>Vn(this.code,i))}else throw Error("Unknown type, must be binary type")}};const ql=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),dm=Ml({name:"sha2-256",code:18,encode:ql("SHA-256")}),pm=Ml({name:"sha2-512",code:19,encode:ql("SHA-512")});var fm=Object.freeze({__proto__:null,sha256:dm,sha512:pm});const zl=0,gm="identity",Hl=jl,ym=t=>Vn(zl,Hl(t)),mm={code:zl,name:gm,encode:Hl,digest:ym};var wm=Object.freeze({__proto__:null,identity:mm});new TextEncoder,new TextDecoder;const Ma={...uy,...py,...gy,...my,...vy,...xy,...Ry,...jy,...My,...Wy};({...fm,...wm});function Vl(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const qa=Vl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ln=Vl("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Nl(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Kl={utf8:qa,"utf-8":qa,hex:Ma.base16,latin1:ln,ascii:ln,binary:ln,...Ma};function Rs(t,e="utf8"){const r=Kl[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}function ri(t,e="utf8"){const r=Kl[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Bo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function za(t){return hr(Rs(ri(t,Cs),Tl))}function vs(t){return Rs(ri(jt(t),Tl),Cs)}function Wl(t){const e=ri(Zg,ja),r=Jg+Rs(Bl([e,t]),ja);return[Gg,Yg,r].join(Wg)}function bm(t){return Rs(t,Cs)}function vm(t){return ri(t,Cs)}function Em(t){return ri([vs(t.header),vs(t.payload)].join(bs),Rl)}function _m(t){return[vs(t.header),vs(t.payload),bm(t.signature)].join(bs)}function Kn(t){const e=t.split(bs),r=za(e[0]),i=za(e[1]),s=vm(e[2]),n=ri(e.slice(0,2).join(bs),Rl);return{header:r,payload:i,signature:s,data:n}}function Ha(t=El(Qg)){const e=Cl.getPublicKey(t);return{secretKey:Bl([t,e]),publicKey:e}}async function Im(t,e,r,i,s=N.fromMiliseconds(Date.now())){const n={alg:Vg,typ:Kg},o=Wl(i.publicKey),a=s+r,c={iss:o,sub:t,aud:e,iat:s,exp:a},h=Em({header:n,payload:c}),l=Cl.sign(h,i.secretKey.slice(0,32));return _m({header:n,payload:c,signature:l})}function Gl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Ei(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Gl(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return r}function $m(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var P=p[v],A=0,O=E-1;(P!==0||A<w)&&O!==-1;O--,A++)P+=256*I[O]>>>0,I[O]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var D=c.repeat(y);C<E;++C)D+=t.charAt(I[C]);return D}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*h+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var P=0,A=b-1;(I!==0||P<v)&&A!==-1;A--,P++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=P,y++}if(p[y]!==" "){for(var O=b-v;O!==b&&E[O]===0;)O++;for(var C=new Uint8Array(w+(b-O)),D=w;O!==b;)C[D++]=E[O++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:f}}var Dm=$m,Sm=Dm;const Om=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")},Pm=t=>new TextEncoder().encode(t),Am=t=>new TextDecoder().decode(t);class xm{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Cm{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}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 Yl(this,e)}}class Tm{constructor(e){this.decoders=e}or(e){return Yl(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yl=(t,e)=>new Tm({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Rm{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new xm(e,r,i),this.decoder=new Cm(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ns=({name:t,prefix:e,encode:r,decode:i})=>new Rm(t,e,r,i),Fi=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=Sm(r,e);return Ns({prefix:t,name:e,encode:i,decode:n=>Om(s(n))})},Nm=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const u=s[t[l]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|u,a+=r,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Bm=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Oe=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ns({prefix:e,name:t,encode(s){return Bm(s,i,r)},decode(s){return Nm(s,i,r,t)}}),jm=Ns({prefix:"\0",name:"identity",encode:t=>Am(t),decode:t=>Pm(t)}),Um=Object.freeze(Object.defineProperty({__proto__:null,identity:jm},Symbol.toStringTag,{value:"Module"})),Fm=Oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Lm=Object.freeze(Object.defineProperty({__proto__:null,base2:Fm},Symbol.toStringTag,{value:"Module"})),km=Oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Mm=Object.freeze(Object.defineProperty({__proto__:null,base8:km},Symbol.toStringTag,{value:"Module"})),qm=Fi({prefix:"9",name:"base10",alphabet:"0123456789"}),zm=Object.freeze(Object.defineProperty({__proto__:null,base10:qm},Symbol.toStringTag,{value:"Module"})),Hm=Oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vm=Oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Km=Object.freeze(Object.defineProperty({__proto__:null,base16:Hm,base16upper:Vm},Symbol.toStringTag,{value:"Module"})),Wm=Oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gm=Oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ym=Oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Jm=Oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Zm=Oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qm=Oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xm=Oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ew=Oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tw=Oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),rw=Object.freeze(Object.defineProperty({__proto__:null,base32:Wm,base32hex:Zm,base32hexpad:Xm,base32hexpadupper:ew,base32hexupper:Qm,base32pad:Ym,base32padupper:Jm,base32upper:Gm,base32z:tw},Symbol.toStringTag,{value:"Module"})),iw=Fi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sw=Fi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),nw=Object.freeze(Object.defineProperty({__proto__:null,base36:iw,base36upper:sw},Symbol.toStringTag,{value:"Module"})),ow=Fi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),aw=Fi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),cw=Object.freeze(Object.defineProperty({__proto__:null,base58btc:ow,base58flickr:aw},Symbol.toStringTag,{value:"Module"})),hw=Oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),lw=Oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uw=Oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),dw=Oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),pw=Object.freeze(Object.defineProperty({__proto__:null,base64:hw,base64pad:lw,base64url:uw,base64urlpad:dw},Symbol.toStringTag,{value:"Module"})),Jl=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),fw=Jl.reduce((t,e,r)=>(t[r]=e,t),[]),gw=Jl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function yw(t){return t.reduce((e,r)=>(e+=fw[r],e),"")}function mw(t){const e=[];for(const r of t){const i=gw[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const ww=Ns({prefix:"🚀",name:"base256emoji",encode:yw,decode:mw}),bw=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:ww},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Va={...Um,...Lm,...Mm,...zm,...Km,...rw,...nw,...cw,...pw,...bw};function Zl(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Ka=Zl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),un=Zl("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Gl(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Ql={utf8:Ka,"utf-8":Ka,hex:Va.base16,latin1:un,ascii:un,binary:un,...Va};function tt(t,e="utf8"){const r=Ql[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}function ke(t,e="utf8"){const r=Ql[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}const vw={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}};var Ew={};const _w=":";function Vr(t){const[e,r]=t.split(_w);return{namespace:e,reference:r}}function Wa(t,e=[]){const r=[];return Object.keys(t).forEach(i=>{if(e.length&&!e.includes(i))return;const s=t[i];r.push(...s.accounts)}),r}function Xl(t,e){return t.includes(":")?[t]:e.chains||[]}var Iw=Object.defineProperty,$w=Object.defineProperties,Dw=Object.getOwnPropertyDescriptors,Ga=Object.getOwnPropertySymbols,Sw=Object.prototype.hasOwnProperty,Ow=Object.prototype.propertyIsEnumerable,Ya=(t,e,r)=>e in t?Iw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ja=(t,e)=>{for(var r in e||(e={}))Sw.call(e,r)&&Ya(t,r,e[r]);if(Ga)for(var r of Ga(e))Ow.call(e,r)&&Ya(t,r,e[r]);return t},Pw=(t,e)=>$w(t,Dw(e));const Aw="ReactNative",We={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},xw="js";function Es(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Wt(){return!ar()&&!!So()&&navigator.product===Aw}function Cw(){return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function Tw(){return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function ii(){return!Es()&&!!So()&&!!ar()}function Li(){return Wt()?We.reactNative:Es()?We.node:ii()?We.browser:We.unknown}function Za(){var t;try{return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Rw(t,e){const r=new URLSearchParams(t);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const s=e[i];s!==void 0&&r.set(i,s)}return r.toString()}function Nw(t){var e,r;const i=eu();try{return t!=null&&t.url&&i.url&&new URL(t.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),t.url=i.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),Pw(Ja(Ja({},i),t),{url:(t==null?void 0:t.url)||i.url,name:(t==null?void 0:t.name)||i.name,description:(t==null?void 0:t.description)||i.description,icons:(r=t==null?void 0:t.icons)!=null&&r.length&&t.icons.length>0?t.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),t||i}}function eu(){return ol()||{name:"",description:"",url:"",icons:[""]}}function Bw(){if(Li()===We.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:r,Version:i}=global.Platform;return[r,i].join("-")}const t=Jd();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 jw(){var t;const e=Li();return e===We.browser?[e,((t=nl())==null?void 0:t.host)||"unknown"].join(":"):e}function tu(t,e,r){const i=Bw(),s=jw();return[[t,e].join("-"),[xw,r].join("-"),i,s].join("/")}function Uw({protocol:t,version:e,relayUrl:r,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=r.split("?"),l=tu(t,e,i),u={auth:s,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=Rw(h[1]||"",u);return h[0]+"?"+d}function sr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Wn(t){return Object.fromEntries(t.entries())}function Gn(t){return new Map(Object.entries(t))}function Qt(t=N.FIVE_MINUTES,e){const r=N.toMiliseconds(t||N.FIVE_MINUTES);let i,s,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const h=new Error(e);o=Promise.reject(h),c(h)},r),i=a,s=c})}}function zt(t,e,r){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(r)),e);try{const o=await t;i(o)}catch(o){s(o)}clearTimeout(n)})}function ru(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 Fw(t){return ru("topic",t)}function Lw(t){return ru("id",t)}function iu(t){const[e,r]=t.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")i.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))i.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return i}function de(t,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(t))}function Mt(t){return Date.now()>=N.toMiliseconds(t)}function X(t,e){return`${t}${e?`:${e}`:""}`}function _t(t=[],e=[]){return[...new Set([...t,...e])]}async function kw({id:t,topic:e,wcDeepLink:r}){var i;try{if(!r)return;const s=typeof r=="string"?JSON.parse(r):r,n=s==null?void 0:s.href;if(typeof n!="string")return;const o=Mw(n,t,e),a=Li();if(a===We.browser){if(!((i=ar())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}qw(o)}else a===We.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function Mw(t,e,r){const i=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${Kw(i,!0)}`}else s=`${s}/wc?${i}`;return s}function qw(t){let e="_self";Vw()?e="_top":(Hw()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function zw(t,e){let r="";try{if(ii()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(i){console.error(i)}return r}function Qa(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),i=r.indexOf(e);return r[i+2]}function Xa(){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 jo(){return typeof process<"u"&&Ew.IS_VITEST==="true"}function Hw(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Vw(){try{return window.self!==window.top}catch{return!1}}function Kw(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function su(t){return Buffer.from(t,"base64").toString("utf-8")}function Ww(t){return new Promise(e=>setTimeout(e,t))}function Pi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Gw(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ki(t,...e){if(!Gw(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 Uo(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Pi(t.outputLen),Pi(t.blockLen)}function Kr(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 nu(t,e){ki(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Qi=BigInt(2**32-1),ec=BigInt(32);function Yw(t,e=!1){return e?{h:Number(t&Qi),l:Number(t>>ec&Qi)}:{h:Number(t>>ec&Qi)|0,l:Number(t&Qi)|0}}function Jw(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=Yw(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const Zw=(t,e,r)=>t<<r|e>>>32-r,Qw=(t,e,r)=>e<<r|t>>>32-r,Xw=(t,e,r)=>e<<r-32|t>>>64-r,eb=(t,e,r)=>t<<r-32|e>>>64-r,Ir=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function tb(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function dn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function ft(t,e){return t<<32-e|t>>>e}const tc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function rb(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function rc(t){for(let e=0;e<t.length;e++)t[e]=rb(t[e])}function ib(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Wr(t){return typeof t=="string"&&(t=ib(t)),ki(t),t}function sb(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];ki(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}let Fo=class{clone(){return this._cloneInto()}};function ou(t){const e=i=>t().update(Wr(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function si(t=32){if(Ir&&typeof Ir.getRandomValues=="function")return Ir.getRandomValues(new Uint8Array(t));if(Ir&&typeof Ir.randomBytes=="function")return Ir.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const au=[],cu=[],hu=[],nb=BigInt(0),di=BigInt(1),ob=BigInt(2),ab=BigInt(7),cb=BigInt(256),hb=BigInt(113);for(let t=0,e=di,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],au.push(2*(5*i+r)),cu.push((t+1)*(t+2)/2%64);let s=nb;for(let n=0;n<7;n++)e=(e<<di^(e>>ab)*hb)%cb,e&ob&&(s^=di<<(di<<BigInt(n))-di);hu.push(s)}const[lb,ub]=Jw(hu,!0),ic=(t,e,r)=>r>32?Xw(t,e,r):Zw(t,e,r),sc=(t,e,r)=>r>32?eb(t,e,r):Qw(t,e,r);function db(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[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,h=r[c],l=r[c+1],u=ic(h,l,1)^r[a],d=sc(h,l,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=u,t[o+f+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=cu[o],c=ic(s,n,a),h=sc(s,n,a),l=au[o];s=t[l],n=t[l+1],t[l]=c,t[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=lb[i],t[1]^=ub[i]}r.fill(0)}let pb=class lu extends Fo{constructor(e,r,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Pi(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=tb(this.state)}keccak(){tc||rc(this.state32),db(this.state32,this.rounds),tc||rc(this.state32),this.posOut=0,this.pos=0}update(e){Kr(this);const{blockLen:r,state:i}=this;e=Wr(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Kr(this,!1),ki(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=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 Pi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(nu(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,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new lu(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const fb=(t,e,r)=>ou(()=>new pb(e,t,r)),gb=fb(1,136,256/8),yb="https://rpc.walletconnect.org/v1";function uu(t){const e=`Ethereum Signed Message:
16
+ `);super(o,r.cause?{cause:r.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=i,this.docsPath=s,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=al}walk(e){return cl(this,e)}}function cl(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?cl(t.cause,e):e?null:t}class hl extends cr{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function ei(t,{dir:e,size:r=32}={}){return typeof t=="string"?Mp(t,{dir:e,size:r}):qp(t,{dir:e,size:r})}function Mp(t,{dir:e,size:r=32}={}){if(r===null)return t;const i=t.replace("0x","");if(i.length>r*2)throw new hl({size:Math.ceil(i.length/2),targetSize:r,type:"hex"});return`0x${i[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function qp(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new hl({size:t.length,targetSize:r,type:"bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const n=e==="right";i[n?s:r-s-1]=t[n?s:t.length-s-1]}return i}class zp extends cr{constructor({max:e,min:r,signed:i,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${i?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class Hp extends cr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ti(t,{size:e}){if(ma(t)>e)throw new Hp({givenSize:ma(t),maxSize:e})}function Ln(t,e={}){const{signed:r}=e;e.size&&ti(t,{size:e.size});const i=BigInt(t);if(!r)return i;const s=(t.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return i<=n?i:i-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function Vp(t,e={}){return Number(Ln(t,e))}const Kp=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function kn(t,e={}){return typeof t=="number"||typeof t=="bigint"?ul(t,e):typeof t=="string"?Yp(t,e):typeof t=="boolean"?Wp(t,e):ll(t,e)}function Wp(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(ti(r,{size:e.size}),ei(r,{size:e.size})):r}function ll(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=Kp[t[s]];const i=`0x${r}`;return typeof e.size=="number"?(ti(i,{size:e.size}),ei(i,{dir:"right",size:e.size})):i}function ul(t,e={}){const{signed:r,size:i}=e,s=BigInt(t);let n;i?r?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&r?-n-1n:0;if(n&&s>n||s<o){const c=typeof t=="bigint"?"n":"";throw new zp({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:r,size:i,value:`${t}${c}`})}const a=`0x${(r&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?ei(a,{size:i}):a}const Gp=new TextEncoder;function Yp(t,e={}){const r=Gp.encode(t);return ll(r,e)}const Jp=new TextEncoder;function Zp(t,e={}){return typeof t=="number"||typeof t=="bigint"?Xp(t,e):typeof t=="boolean"?Qp(t,e):Oi(t)?dl(t,e):pl(t,e)}function Qp(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(ti(r,{size:e.size}),ei(r,{size:e.size})):r}const Dt={zero:48,nine:57,A:65,F:70,a:97,f:102};function wa(t){if(t>=Dt.zero&&t<=Dt.nine)return t-Dt.zero;if(t>=Dt.A&&t<=Dt.F)return t-(Dt.A-10);if(t>=Dt.a&&t<=Dt.f)return t-(Dt.a-10)}function dl(t,e={}){let r=t;e.size&&(ti(r,{size:e.size}),r=ei(r,{dir:"right",size:e.size}));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=wa(i.charCodeAt(a++)),h=wa(i.charCodeAt(a++));if(c===void 0||h===void 0)throw new cr(`Invalid byte sequence ("${i[a-2]}${i[a-1]}" in "${i}").`);n[o]=c*16+h}return n}function Xp(t,e){const r=ul(t,e);return dl(r)}function pl(t,e={}){const r=Jp.encode(t);return typeof e.size=="number"?(ti(r,{size:e.size}),ei(r,{dir:"right",size:e.size})):r}function ws(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ef(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xs(t,...e){if(!ef(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 mO(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ws(t.outputLen),ws(t.blockLen)}function ba(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 tf(t,e){xs(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Gi=BigInt(2**32-1),va=BigInt(32);function rf(t,e=!1){return e?{h:Number(t&Gi),l:Number(t>>va&Gi)}:{h:Number(t>>va&Gi)|0,l:Number(t&Gi)|0}}function sf(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=rf(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const nf=(t,e,r)=>t<<r|e>>>32-r,of=(t,e,r)=>e<<r|t>>>32-r,af=(t,e,r)=>e<<r-32|t>>>64-r,cf=(t,e,r)=>t<<r-32|e>>>64-r,Er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function hf(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function wO(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function bO(t,e){return t<<32-e|t>>>e}const Ea=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function lf(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function _a(t){for(let e=0;e<t.length;e++)t[e]=lf(t[e])}function uf(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function fl(t){return typeof t=="string"&&(t=uf(t)),xs(t),t}function vO(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];xs(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}class df{clone(){return this._cloneInto()}}function pf(t){const e=i=>t().update(fl(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function EO(t=32){if(Er&&typeof Er.getRandomValues=="function")return Er.getRandomValues(new Uint8Array(t));if(Er&&typeof Er.randomBytes=="function")return Er.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const gl=[],yl=[],ml=[],ff=BigInt(0),li=BigInt(1),gf=BigInt(2),yf=BigInt(7),mf=BigInt(256),wf=BigInt(113);for(let t=0,e=li,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],gl.push(2*(5*i+r)),yl.push((t+1)*(t+2)/2%64);let s=ff;for(let n=0;n<7;n++)e=(e<<li^(e>>yf)*wf)%mf,e&gf&&(s^=li<<(li<<BigInt(n))-li);ml.push(s)}const[bf,vf]=sf(ml,!0),Ia=(t,e,r)=>r>32?af(t,e,r):nf(t,e,r),$a=(t,e,r)=>r>32?cf(t,e,r):of(t,e,r);function Ef(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[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,h=r[c],l=r[c+1],u=Ia(h,l,1)^r[a],d=$a(h,l,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=u,t[o+f+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=yl[o],c=Ia(s,n,a),h=$a(s,n,a),l=gl[o];s=t[l],n=t[l+1],t[l]=c,t[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=bf[i],t[1]^=vf[i]}r.fill(0)}class Po extends df{constructor(e,r,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,ws(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=hf(this.state)}keccak(){Ea||_a(this.state32),Ef(this.state32,this.rounds),Ea||_a(this.state32),this.posOut=0,this.pos=0}update(e){ba(this);const{blockLen:r,state:i}=this;e=fl(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){ba(this,!1),xs(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=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 ws(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(tf(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,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Po(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const _f=(t,e,r)=>pf(()=>new Po(e,t,r)),If=_f(1,136,256/8);function wl(t,e){const r=e||"hex",i=If(Oi(t,{strict:!1})?Zp(t):t);return r==="bytes"?i:kn(i)}class $f extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const tn=new $f(8192);function Df(t,e){if(tn.has(`${t}.${e}`))return tn.get(`${t}.${e}`);const r=t.substring(2).toLowerCase(),i=wl(pl(r),"bytes"),s=r.split("");for(let o=0;o<40;o+=2)i[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(i[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return tn.set(`${t}.${e}`,n),n}function Sf(t){const e=wl(`0x${t.substring(4)}`).substring(26);return Df(`0x${e}`)}async function Of({hash:t,signature:e}){const r=Oi(t)?t:kn(t),{secp256k1:i}=await el(async()=>{const{secp256k1:o}=await import("./secp256k1-CcCxXqQL.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:h,s:l,v:u,yParity:d}=e,f=Number(d??u),p=Da(f);return new i.Signature(Ln(h),Ln(l)).addRecoveryBit(p)}const o=Oi(e)?e:kn(e),a=Vp(`0x${o.slice(130)}`),c=Da(a);return i.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Da(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Pf({hash:t,signature:e}){return Sf(await Of({hash:t,signature:e}))}function Af(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let h=0;h<e.length;h++)e[h]=255;for(let h=0;h<t.length;h++){const l=t.charAt(h),u=l.charCodeAt(0);if(e[u]!==255)throw new TypeError(l+" is ambiguous");e[u]=h}const r=t.length,i=t.charAt(0),s=Math.log(r)/Math.log(256),n=Math.log(256)/Math.log(r);function o(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";let l=0,u=0,d=0;const f=h.length;for(;d!==f&&h[d]===0;)d++,l++;const p=(f-d)*n+1>>>0,y=new Uint8Array(p);for(;d!==f;){let b=h[d],E=0;for(let I=p-1;(b!==0||E<u)&&I!==-1;I--,E++)b+=256*y[I]>>>0,y[I]=b%r>>>0,b=b/r>>>0;if(b!==0)throw new Error("Non-zero carry");u=E,d++}let w=p-u;for(;w!==p&&y[w]===0;)w++;let v=i.repeat(l);for(;w<p;++w)v+=t.charAt(y[w]);return v}function a(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;let l=0,u=0,d=0;for(;h[l]===i;)u++,l++;const f=(h.length-l)*s+1>>>0,p=new Uint8Array(f);for(;l<h.length;){const b=h.charCodeAt(l);if(b>255)return;let E=e[b];if(E===255)return;let I=0;for(let P=f-1;(E!==0||I<d)&&P!==-1;P--,I++)E+=r*p[P]>>>0,p[P]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");d=I,l++}let y=f-d;for(;y!==f&&p[y]===0;)y++;const w=new Uint8Array(u+(f-y));let v=u;for(;y!==f;)w[v++]=p[y++];return w}function c(h){const l=a(h);if(l)return l;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var xf="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Cf=Af(xf),Tf=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),Rf=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function hr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Rf(t)}catch{return t}}function jt(t){return typeof t=="string"?t:Tf(t)||""}function Nf(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function bl(t,...e){if(!Nf(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 Sa(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 Bf(t,e){bl(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const _r=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rn=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function jf(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function vl(t){return typeof t=="string"&&(t=jf(t)),bl(t),t}let Uf=class{clone(){return this._cloneInto()}};function Ff(t){const e=i=>t().update(vl(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function El(t=32){if(_r&&typeof _r.getRandomValues=="function")return _r.getRandomValues(new Uint8Array(t));if(_r&&typeof _r.randomBytes=="function")return _r.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Lf(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,h=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+h,a,i)}let kf=class extends Uf{constructor(e,r,i,s){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=rn(this.buffer)}update(e){Sa(this);const{view:r,buffer:i,blockLen:s}=this;e=vl(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=rn(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Sa(this),Bf(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let u=o;u<s;u++)r[u]=0;Lf(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=rn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%r&&e.buffer.set(i),e}};const Yi=BigInt(2**32-1),Mn=BigInt(32);function _l(t,e=!1){return e?{h:Number(t&Yi),l:Number(t>>Mn&Yi)}:{h:Number(t>>Mn&Yi)|0,l:Number(t&Yi)|0}}function Mf(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=_l(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const qf=(t,e)=>BigInt(t>>>0)<<Mn|BigInt(e>>>0),zf=(t,e,r)=>t>>>r,Hf=(t,e,r)=>t<<32-r|e>>>r,Vf=(t,e,r)=>t>>>r|e<<32-r,Kf=(t,e,r)=>t<<32-r|e>>>r,Wf=(t,e,r)=>t<<64-r|e>>>r-32,Gf=(t,e,r)=>t>>>r-32|e<<64-r,Yf=(t,e)=>e,Jf=(t,e)=>t,Zf=(t,e,r)=>t<<r|e>>>32-r,Qf=(t,e,r)=>e<<r|t>>>32-r,Xf=(t,e,r)=>e<<r-32|t>>>64-r,eg=(t,e,r)=>t<<r-32|e>>>64-r;function tg(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const rg=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),ig=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,sg=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),ng=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,og=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),ag=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,V={fromBig:_l,split:Mf,toBig:qf,shrSH:zf,shrSL:Hf,rotrSH:Vf,rotrSL:Kf,rotrBH:Wf,rotrBL:Gf,rotr32H:Yf,rotr32L:Jf,rotlSH:Zf,rotlSL:Qf,rotlBH:Xf,rotlBL:eg,add:tg,add3L:rg,add3H:ig,add4L:sg,add4H:ng,add5H:ag,add5L:og},[cg,hg]=V.split(["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))),Ut=new Uint32Array(80),Ft=new Uint32Array(80);let lg=class extends kf{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:h,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:y,Hl:w}=this;return[e,r,i,s,n,o,a,c,h,l,u,d,f,p,y,w]}set(e,r,i,s,n,o,a,c,h,l,u,d,f,p,y,w){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=h|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=y|0,this.Hl=w|0}process(e,r){for(let E=0;E<16;E++,r+=4)Ut[E]=e.getUint32(r),Ft[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){const I=Ut[E-15]|0,P=Ft[E-15]|0,A=V.rotrSH(I,P,1)^V.rotrSH(I,P,8)^V.shrSH(I,P,7),O=V.rotrSL(I,P,1)^V.rotrSL(I,P,8)^V.shrSL(I,P,7),C=Ut[E-2]|0,D=Ft[E-2]|0,M=V.rotrSH(C,D,19)^V.rotrBH(C,D,61)^V.shrSH(C,D,6),U=V.rotrSL(C,D,19)^V.rotrBL(C,D,61)^V.shrSL(C,D,6),j=V.add4L(O,U,Ft[E-7],Ft[E-16]),q=V.add4H(j,A,M,Ut[E-7],Ut[E-16]);Ut[E]=q|0,Ft[E]=j|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:h,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:y,Gl:w,Hh:v,Hl:b}=this;for(let E=0;E<80;E++){const I=V.rotrSH(u,d,14)^V.rotrSH(u,d,18)^V.rotrBH(u,d,41),P=V.rotrSL(u,d,14)^V.rotrSL(u,d,18)^V.rotrBL(u,d,41),A=u&f^~u&y,O=d&p^~d&w,C=V.add5L(b,P,O,hg[E],Ft[E]),D=V.add5H(C,v,I,A,cg[E],Ut[E]),M=C|0,U=V.rotrSH(i,s,28)^V.rotrBH(i,s,34)^V.rotrBH(i,s,39),j=V.rotrSL(i,s,28)^V.rotrBL(i,s,34)^V.rotrBL(i,s,39),q=i&n^i&a^n&a,T=s&o^s&c^o&c;v=y|0,b=w|0,y=f|0,w=p|0,f=u|0,p=d|0,{h:u,l:d}=V.add(h|0,l|0,D|0,M|0),h=a|0,l=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const g=V.add3L(M,j,T);i=V.add3H(g,D,U,q),s=g|0}({h:i,l:s}=V.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=V.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=V.add(this.Ch|0,this.Cl|0,a|0,c|0),{h,l}=V.add(this.Dh|0,this.Dl|0,h|0,l|0),{h:u,l:d}=V.add(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=V.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:y,l:w}=V.add(this.Gh|0,this.Gl|0,y|0,w|0),{h:v,l:b}=V.add(this.Hh|0,this.Hl|0,v|0,b|0),this.set(i,s,n,o,a,c,h,l,u,d,f,p,y,w,v,b)}roundClean(){Ut.fill(0),Ft.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};const ug=Ff(()=>new lg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ao=BigInt(0),Il=BigInt(1),dg=BigInt(2);function xo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Co(t){if(!xo(t))throw new Error("Uint8Array expected")}function sn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const pg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function To(t){Co(t);let e="";for(let r=0;r<t.length;r++)e+=pg[t[r]];return e}function $l(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ao:BigInt("0x"+t)}const St={_0:48,_9:57,A:65,F:70,a:97,f:102};function Oa(t){if(t>=St._0&&t<=St._9)return t-St._0;if(t>=St.A&&t<=St.F)return t-(St.A-10);if(t>=St.a&&t<=St.f)return t-(St.a-10)}function Dl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Oa(t.charCodeAt(n)),a=Oa(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function fg(t){return $l(To(t))}function us(t){return Co(t),$l(To(Uint8Array.from(t).reverse()))}function Sl(t,e){return Dl(t.toString(16).padStart(e*2,"0"))}function qn(t,e){return Sl(t,e).reverse()}function Ot(t,e,r){let i;if(typeof e=="string")try{i=Dl(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(xo(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function Pa(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];Co(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}const nn=t=>typeof t=="bigint"&&Ao<=t;function gg(t,e,r){return nn(t)&&nn(e)&&nn(r)&&e<=t&&t<r}function ui(t,e,r,i){if(!gg(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function yg(t){let e;for(e=0;t>Ao;t>>=Il,e+=1);return e}const mg=t=>(dg<<BigInt(t-1))-Il,wg={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"||xo(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 Ro(t,e,r={}){const i=(s,n,o)=>{const a=wg[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}function Aa(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}const be=BigInt(0),ce=BigInt(1),er=BigInt(2),bg=BigInt(3),zn=BigInt(4),xa=BigInt(5),Ca=BigInt(8);function pe(t,e){const r=t%e;return r>=be?r:e+r}function vg(t,e,r){if(e<be)throw new Error("invalid exponent, negatives unsupported");if(r<=be)throw new Error("invalid modulus");if(r===ce)return be;let i=ce;for(;e>be;)e&ce&&(i=i*t%r),t=t*t%r,e>>=ce;return i}function pt(t,e,r){let i=t;for(;e-- >be;)i*=i,i%=r;return i}function Ta(t,e){if(t===be)throw new Error("invert: expected non-zero number");if(e<=be)throw new Error("invert: expected positive modulus, got "+e);let r=pe(t,e),i=e,s=be,n=ce;for(;r!==be;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==ce)throw new Error("invert: does not exist");return pe(s,e)}function Eg(t){const e=(t-ce)/er;let r,i,s;for(r=t-ce,i=0;r%er===be;r/=er,i++);for(s=er;s<t&&vg(s,e,t)!==t-ce;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+ce)/zn;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(r+ce)/er;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,h=o.pow(o.mul(o.ONE,s),r),l=o.pow(a,n),u=o.pow(a,r);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let d=1;for(let p=o.sqr(u);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const f=o.pow(h,ce<<BigInt(c-d-1));h=o.sqr(f),l=o.mul(l,f),u=o.mul(u,h),c=d}return l}}function _g(t){if(t%zn===bg){const e=(t+ce)/zn;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%Ca===xa){const e=(t-xa)/Ca;return function(r,i){const s=r.mul(i,er),n=r.pow(s,e),o=r.mul(i,n),a=r.mul(r.mul(o,er),n),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return Eg(t)}const Ig=(t,e)=>(pe(t,e)&ce)===ce,$g=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Dg(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=$g.reduce((i,s)=>(i[s]="function",i),e);return Ro(t,r)}function Sg(t,e,r){if(r<be)throw new Error("invalid exponent, negatives unsupported");if(r===be)return t.ONE;if(r===ce)return e;let i=t.ONE,s=e;for(;r>be;)r&ce&&(i=t.mul(i,s)),s=t.sqr(s),r>>=ce;return i}function Og(t,e){const r=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(r[a]=n,t.mul(n,o)),t.ONE),s=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(r[a]=t.mul(n,r[a]),t.mul(n,o)),s),r}function Ol(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Pl(t,e,r=!1,i={}){if(t<=be)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=Ol(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:mg(s),ZERO:be,ONE:ce,create:c=>pe(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return be<=c&&c<t},is0:c=>c===be,isOdd:c=>(c&ce)===ce,neg:c=>pe(-c,t),eql:(c,h)=>c===h,sqr:c=>pe(c*c,t),add:(c,h)=>pe(c+h,t),sub:(c,h)=>pe(c-h,t),mul:(c,h)=>pe(c*h,t),pow:(c,h)=>Sg(a,c,h),div:(c,h)=>pe(c*Ta(h,t),t),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>Ta(c,t),sqrt:i.sqrt||(c=>(o||(o=_g(t)),o(a,c))),invertBatch:c=>Og(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>r?qn(c,n):Sl(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?us(c):fg(c)}});return Object.freeze(a)}const Ra=BigInt(0),Ji=BigInt(1);function on(t,e){const r=e.negate();return t?r:e}function Al(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function an(t,e){Al(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function Pg(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function Ag(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const cn=new WeakMap,xl=new WeakMap;function hn(t){return xl.get(t)||1}function xg(t,e){return{constTimeNegate:on,hasPrecomputes(r){return hn(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>Ra;)i&Ji&&(s=s.add(n)),n=n.double(),i>>=Ji;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=an(i,e),o=[];let a=r,c=a;for(let h=0;h<s;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){const{windows:n,windowSize:o}=an(r,e);let a=t.ZERO,c=t.BASE;const h=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&h);s>>=u,p>o&&(p-=l,s+=Ji);const y=f,w=f+Math.abs(p)-1,v=d%2!==0,b=p<0;p===0?c=c.add(on(v,i[y])):a=a.add(on(b,i[w]))}return{p:a,f:c}},wNAFUnsafe(r,i,s,n=t.ZERO){const{windows:o,windowSize:a}=an(r,e),c=BigInt(2**r-1),h=2**r,l=BigInt(r);for(let u=0;u<o;u++){const d=u*a;if(s===Ra)break;let f=Number(s&c);if(s>>=l,f>a&&(f-=h,s+=Ji),f===0)continue;let p=i[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(r,i,s){let n=cn.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&cn.set(i,s(n))),n},wNAFCached(r,i,s){const n=hn(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=hn(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){Al(i,e),xl.set(r,i),cn.delete(r)}}}function Cg(t,e,r,i){if(Pg(r,t),Ag(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=yg(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),h=Math.floor((e.BITS-1)/o)*o;let l=s;for(let u=h;u>=0;u-=o){c.fill(s);for(let f=0;f<i.length;f++){const p=i[f],y=Number(p>>BigInt(u)&BigInt(a));c[y]=c[y].add(r[f])}let d=s;for(let f=c.length-1,p=s;f>0;f--)p=p.add(c[f]),d=d.add(p);if(l=l.add(d),u!==0)for(let f=0;f<o;f++)l=l.double()}return l}function Tg(t){return Dg(t.Fp),Ro(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ol(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const nt=BigInt(0),Be=BigInt(1),Zi=BigInt(2),Rg=BigInt(8),Ng={zip215:!0};function Bg(t){const e=Tg(t);return Ro(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function jg(t){const e=Bg(t),{Fp:r,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,h=Zi<<BigInt(a*8)-Be,l=r.create,u=Pl(e.n,e.nBitLength),d=e.uvRatio||((g,m)=>{try{return{isValid:!0,value:r.sqrt(g*r.inv(m))}}catch{return{isValid:!1,value:nt}}}),f=e.adjustScalarBytes||(g=>g),p=e.domain||((g,m,_)=>{if(sn("phflag",_),m.length||_)throw new Error("Contexts/pre-hash are not supported");return g});function y(g,m){ui("coordinate "+g,m,nt,h)}function w(g){if(!(g instanceof E))throw new Error("ExtendedPoint expected")}const v=Aa((g,m)=>{const{ex:_,ey:S,ez:$}=g,x=g.is0();m==null&&(m=x?Rg:r.inv($));const F=l(_*m),k=l(S*m),z=l($*m);if(x)return{x:nt,y:Be};if(z!==Be)throw new Error("invZ was invalid");return{x:F,y:k}}),b=Aa(g=>{const{a:m,d:_}=e;if(g.is0())throw new Error("bad point: ZERO");const{ex:S,ey:$,ez:x,et:F}=g,k=l(S*S),z=l($*$),L=l(x*x),H=l(L*L),G=l(k*m),se=l(L*l(G+z)),ee=l(H+l(_*l(k*z)));if(se!==ee)throw new Error("bad point: equation left != right (1)");const Y=l(S*$),Ae=l(x*F);if(Y!==Ae)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(m,_,S,$){this.ex=m,this.ey=_,this.ez=S,this.et=$,y("x",m),y("y",_),y("z",S),y("t",$),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(m){if(m instanceof E)throw new Error("extended point not allowed");const{x:_,y:S}=m||{};return y("x",_),y("y",S),new E(_,S,Be,l(_*S))}static normalizeZ(m){const _=r.invertBatch(m.map(S=>S.ez));return m.map((S,$)=>S.toAffine(_[$])).map(E.fromAffine)}static msm(m,_){return Cg(E,u,m,_)}_setWindowSize(m){A.setWindowSize(this,m)}assertValidity(){b(this)}equals(m){w(m);const{ex:_,ey:S,ez:$}=this,{ex:x,ey:F,ez:k}=m,z=l(_*k),L=l(x*$),H=l(S*k),G=l(F*$);return z===L&&H===G}is0(){return this.equals(E.ZERO)}negate(){return new E(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:m}=e,{ex:_,ey:S,ez:$}=this,x=l(_*_),F=l(S*S),k=l(Zi*l($*$)),z=l(m*x),L=_+S,H=l(l(L*L)-x-F),G=z+F,se=G-k,ee=z-F,Y=l(H*se),Ae=l(G*ee),Ee=l(H*ee),Ce=l(se*G);return new E(Y,Ae,Ce,Ee)}add(m){w(m);const{a:_,d:S}=e,{ex:$,ey:x,ez:F,et:k}=this,{ex:z,ey:L,ez:H,et:G}=m;if(_===BigInt(-1)){const Jo=l((x-$)*(L+z)),Zo=l((x+$)*(L-z)),Ys=l(Zo-Jo);if(Ys===nt)return this.double();const Qo=l(F*Zi*G),Xo=l(k*Zi*H),ea=Xo+Qo,ta=Zo+Jo,ra=Xo-Qo,Td=l(ea*Ys),Rd=l(ta*ra),Nd=l(ea*ra),Bd=l(Ys*ta);return new E(Td,Rd,Bd,Nd)}const se=l($*z),ee=l(x*L),Y=l(k*S*G),Ae=l(F*H),Ee=l(($+x)*(z+L)-se-ee),Ce=Ae-Y,Ye=Ae+Y,Je=l(ee-_*se),br=l(Ee*Ce),Ad=l(Ye*Je),xd=l(Ee*Je),Cd=l(Ce*Ye);return new E(br,Ad,Cd,xd)}subtract(m){return this.add(m.negate())}wNAF(m){return A.wNAFCached(this,m,E.normalizeZ)}multiply(m){const _=m;ui("scalar",_,Be,i);const{p:S,f:$}=this.wNAF(_);return E.normalizeZ([S,$])[0]}multiplyUnsafe(m,_=E.ZERO){const S=m;return ui("scalar",S,nt,i),S===nt?P:this.is0()||S===Be?this:A.wNAFCachedUnsafe(this,S,E.normalizeZ,_)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return A.unsafeLadder(this,i).is0()}toAffine(m){return v(this,m)}clearCofactor(){const{h:m}=e;return m===Be?this:this.multiplyUnsafe(m)}static fromHex(m,_=!1){const{d:S,a:$}=e,x=r.BYTES;m=Ot("pointHex",m,x),sn("zip215",_);const F=m.slice(),k=m[x-1];F[x-1]=k&-129;const z=us(F),L=_?h:r.ORDER;ui("pointHex.y",z,nt,L);const H=l(z*z),G=l(H-Be),se=l(S*H-$);let{isValid:ee,value:Y}=d(G,se);if(!ee)throw new Error("Point.fromHex: invalid y coordinate");const Ae=(Y&Be)===Be,Ee=(k&128)!==0;if(!_&&Y===nt&&Ee)throw new Error("Point.fromHex: x=0 and x_0=1");return Ee!==Ae&&(Y=l(-Y)),E.fromAffine({x:Y,y:z})}static fromPrivateKey(m){return D(m).point}toRawBytes(){const{x:m,y:_}=this.toAffine(),S=qn(_,r.BYTES);return S[S.length-1]|=m&Be?128:0,S}toHex(){return To(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,Be,l(e.Gx*e.Gy)),E.ZERO=new E(nt,Be,Be,nt);const{BASE:I,ZERO:P}=E,A=xg(E,a*8);function O(g){return pe(g,i)}function C(g){return O(us(g))}function D(g){const m=r.BYTES;g=Ot("private key",g,m);const _=Ot("hashed private key",n(g),2*m),S=f(_.slice(0,m)),$=_.slice(m,2*m),x=C(S),F=I.multiply(x),k=F.toRawBytes();return{head:S,prefix:$,scalar:x,point:F,pointBytes:k}}function M(g){return D(g).pointBytes}function U(g=new Uint8Array,...m){const _=Pa(...m);return C(n(p(_,Ot("context",g),!!s)))}function j(g,m,_={}){g=Ot("message",g),s&&(g=s(g));const{prefix:S,scalar:$,pointBytes:x}=D(m),F=U(_.context,S,g),k=I.multiply(F).toRawBytes(),z=U(_.context,k,x,g),L=O(F+z*$);ui("signature.s",L,nt,i);const H=Pa(k,qn(L,r.BYTES));return Ot("result",H,r.BYTES*2)}const q=Ng;function T(g,m,_,S=q){const{context:$,zip215:x}=S,F=r.BYTES;g=Ot("signature",g,2*F),m=Ot("message",m),_=Ot("publicKey",_,F),x!==void 0&&sn("zip215",x),s&&(m=s(m));const k=us(g.slice(F,2*F));let z,L,H;try{z=E.fromHex(_,x),L=E.fromHex(g.slice(0,F),x),H=I.multiplyUnsafe(k)}catch{return!1}if(!x&&z.isSmallOrder())return!1;const G=U($,L.toRawBytes(),z.toRawBytes(),m);return L.add(z.multiplyUnsafe(G)).subtract(H).clearCofactor().equals(E.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:M,sign:j,verify:T,ExtendedPoint:E,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>o(r.BYTES),precompute(g=8,m=E.BASE){return m._setWindowSize(g),m.multiply(BigInt(3)),m}}}}BigInt(0),BigInt(1);const No=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Na=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Ug=BigInt(1),Ba=BigInt(2);BigInt(3);const Fg=BigInt(5),Lg=BigInt(8);function kg(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=No,o=t*t%n*t%n,a=pt(o,Ba,n)*o%n,c=pt(a,Ug,n)*t%n,h=pt(c,Fg,n)*c%n,l=pt(h,e,n)*h%n,u=pt(l,r,n)*l%n,d=pt(u,i,n)*u%n,f=pt(d,s,n)*d%n,p=pt(f,s,n)*d%n,y=pt(p,e,n)*h%n;return{pow_p_5_8:pt(y,Ba,n)*t%n,b2:o}}function Mg(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function qg(t,e){const r=No,i=pe(e*e*e,r),s=pe(i*i*e,r),n=kg(t*s).pow_p_5_8;let o=pe(t*i*n,r);const a=pe(e*o*o,r),c=o,h=pe(o*Na,r),l=a===t,u=a===pe(-t,r),d=a===pe(-t*Na,r);return l&&(o=c),(u||d)&&(o=h),Ig(o,r)&&(o=pe(-o,r)),{isValid:l||u,value:o}}const zg=Pl(No,void 0,!0),Hg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:zg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Lg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ug,randomBytes:El,adjustScalarBytes:Mg,uvRatio:qg},Cl=jg(Hg),Vg="EdDSA",Kg="JWT",bs=".",Cs="base64url",Tl="utf8",Rl="utf8",Wg=":",Gg="did",Yg="key",ja="base58btc",Jg="z",Zg="K36",Qg=32;function Bo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Nl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Bo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Bl(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Nl(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return Bo(r)}function Xg(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var P=p[v],A=0,O=E-1;(P!==0||A<w)&&O!==-1;O--,A++)P+=256*I[O]>>>0,I[O]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var D=c.repeat(y);C<E;++C)D+=t.charAt(I[C]);return D}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*h+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var P=0,A=b-1;(I!==0||P<v)&&A!==-1;A--,P++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=P,y++}if(p[y]!==" "){for(var O=b-v;O!==b&&E[O]===0;)O++;for(var C=new Uint8Array(w+(b-O)),D=w;O!==b;)C[D++]=E[O++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:f}}var ey=Xg,ty=ey;const jl=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")},ry=t=>new TextEncoder().encode(t),iy=t=>new TextDecoder().decode(t);let sy=class{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ny=class{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}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 Ul(this,e)}},oy=class{constructor(e){this.decoders=e}or(e){return Ul(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Ul=(t,e)=>new oy({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let ay=class{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new sy(e,r,i),this.decoder=new ny(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Ts=({name:t,prefix:e,encode:r,decode:i})=>new ay(t,e,r,i),Ui=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=ty(r,e);return Ts({prefix:t,name:e,encode:i,decode:n=>jl(s(n))})},cy=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const u=s[t[l]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|u,a+=r,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},hy=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Se=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ts({prefix:e,name:t,encode(s){return hy(s,i,r)},decode(s){return cy(s,i,r,t)}}),ly=Ts({prefix:"\0",name:"identity",encode:t=>iy(t),decode:t=>ry(t)});var uy=Object.freeze({__proto__:null,identity:ly});const dy=Se({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var py=Object.freeze({__proto__:null,base2:dy});const fy=Se({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var gy=Object.freeze({__proto__:null,base8:fy});const yy=Ui({prefix:"9",name:"base10",alphabet:"0123456789"});var my=Object.freeze({__proto__:null,base10:yy});const wy=Se({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),by=Se({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var vy=Object.freeze({__proto__:null,base16:wy,base16upper:by});const Ey=Se({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),_y=Se({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Iy=Se({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$y=Se({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Dy=Se({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Sy=Se({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Oy=Se({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Py=Se({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ay=Se({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xy=Object.freeze({__proto__:null,base32:Ey,base32upper:_y,base32pad:Iy,base32padupper:$y,base32hex:Dy,base32hexupper:Sy,base32hexpad:Oy,base32hexpadupper:Py,base32z:Ay});const Cy=Ui({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ty=Ui({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ry=Object.freeze({__proto__:null,base36:Cy,base36upper:Ty});const Ny=Ui({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),By=Ui({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var jy=Object.freeze({__proto__:null,base58btc:Ny,base58flickr:By});const Uy=Se({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Fy=Se({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ly=Se({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ky=Se({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var My=Object.freeze({__proto__:null,base64:Uy,base64pad:Fy,base64url:Ly,base64urlpad:ky});const Fl=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),qy=Fl.reduce((t,e,r)=>(t[r]=e,t),[]),zy=Fl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Hy(t){return t.reduce((e,r)=>(e+=qy[r],e),"")}function Vy(t){const e=[];for(const r of t){const i=zy[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const Ky=Ts({prefix:"🚀",name:"base256emoji",encode:Hy,decode:Vy});var Wy=Object.freeze({__proto__:null,base256emoji:Ky}),Gy=Ll,Ua=128,Yy=-128,Jy=Math.pow(2,31);function Ll(t,e,r){e=e||[],r=r||0;for(var i=r;t>=Jy;)e[r++]=t&255|Ua,t/=128;for(;t&Yy;)e[r++]=t&255|Ua,t>>>=7;return e[r]=t|0,Ll.bytes=r-i+1,e}var Zy=Hn,Qy=128,Fa=127;function Hn(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw Hn.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Fa)<<s:(o&Fa)*Math.pow(2,s),s+=7}while(o>=Qy);return Hn.bytes=n-i,r}var Xy=Math.pow(2,7),em=Math.pow(2,14),tm=Math.pow(2,21),rm=Math.pow(2,28),im=Math.pow(2,35),sm=Math.pow(2,42),nm=Math.pow(2,49),om=Math.pow(2,56),am=Math.pow(2,63),cm=function(t){return t<Xy?1:t<em?2:t<tm?3:t<rm?4:t<im?5:t<sm?6:t<nm?7:t<om?8:t<am?9:10},hm={encode:Gy,decode:Zy,encodingLength:cm},kl=hm;const La=(t,e,r=0)=>(kl.encode(t,e,r),e),ka=t=>kl.encodingLength(t),Vn=(t,e)=>{const r=e.byteLength,i=ka(t),s=i+ka(r),n=new Uint8Array(s+r);return La(t,n,0),La(r,n,i),n.set(e,s),new lm(t,r,e,n)};let lm=class{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}};const Ml=({name:t,code:e,encode:r})=>new um(t,e,r);let um=class{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Vn(this.code,r):r.then(i=>Vn(this.code,i))}else throw Error("Unknown type, must be binary type")}};const ql=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),dm=Ml({name:"sha2-256",code:18,encode:ql("SHA-256")}),pm=Ml({name:"sha2-512",code:19,encode:ql("SHA-512")});var fm=Object.freeze({__proto__:null,sha256:dm,sha512:pm});const zl=0,gm="identity",Hl=jl,ym=t=>Vn(zl,Hl(t)),mm={code:zl,name:gm,encode:Hl,digest:ym};var wm=Object.freeze({__proto__:null,identity:mm});new TextEncoder,new TextDecoder;const Ma={...uy,...py,...gy,...my,...vy,...xy,...Ry,...jy,...My,...Wy};({...fm,...wm});function Vl(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const qa=Vl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ln=Vl("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Nl(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Kl={utf8:qa,"utf-8":qa,hex:Ma.base16,latin1:ln,ascii:ln,binary:ln,...Ma};function Rs(t,e="utf8"){const r=Kl[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}function ri(t,e="utf8"){const r=Kl[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Bo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function za(t){return hr(Rs(ri(t,Cs),Tl))}function vs(t){return Rs(ri(jt(t),Tl),Cs)}function Wl(t){const e=ri(Zg,ja),r=Jg+Rs(Bl([e,t]),ja);return[Gg,Yg,r].join(Wg)}function bm(t){return Rs(t,Cs)}function vm(t){return ri(t,Cs)}function Em(t){return ri([vs(t.header),vs(t.payload)].join(bs),Rl)}function _m(t){return[vs(t.header),vs(t.payload),bm(t.signature)].join(bs)}function Kn(t){const e=t.split(bs),r=za(e[0]),i=za(e[1]),s=vm(e[2]),n=ri(e.slice(0,2).join(bs),Rl);return{header:r,payload:i,signature:s,data:n}}function Ha(t=El(Qg)){const e=Cl.getPublicKey(t);return{secretKey:Bl([t,e]),publicKey:e}}async function Im(t,e,r,i,s=N.fromMiliseconds(Date.now())){const n={alg:Vg,typ:Kg},o=Wl(i.publicKey),a=s+r,c={iss:o,sub:t,aud:e,iat:s,exp:a},h=Em({header:n,payload:c}),l=Cl.sign(h,i.secretKey.slice(0,32));return _m({header:n,payload:c,signature:l})}function Gl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Ei(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Gl(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return r}function $m(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var P=p[v],A=0,O=E-1;(P!==0||A<w)&&O!==-1;O--,A++)P+=256*I[O]>>>0,I[O]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var D=c.repeat(y);C<E;++C)D+=t.charAt(I[C]);return D}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*h+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var P=0,A=b-1;(I!==0||P<v)&&A!==-1;A--,P++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=P,y++}if(p[y]!==" "){for(var O=b-v;O!==b&&E[O]===0;)O++;for(var C=new Uint8Array(w+(b-O)),D=w;O!==b;)C[D++]=E[O++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:f}}var Dm=$m,Sm=Dm;const Om=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")},Pm=t=>new TextEncoder().encode(t),Am=t=>new TextDecoder().decode(t);class xm{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Cm{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}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 Yl(this,e)}}class Tm{constructor(e){this.decoders=e}or(e){return Yl(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yl=(t,e)=>new Tm({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Rm{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new xm(e,r,i),this.decoder=new Cm(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ns=({name:t,prefix:e,encode:r,decode:i})=>new Rm(t,e,r,i),Fi=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=Sm(r,e);return Ns({prefix:t,name:e,encode:i,decode:n=>Om(s(n))})},Nm=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const u=s[t[l]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|u,a+=r,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Bm=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Oe=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ns({prefix:e,name:t,encode(s){return Bm(s,i,r)},decode(s){return Nm(s,i,r,t)}}),jm=Ns({prefix:"\0",name:"identity",encode:t=>Am(t),decode:t=>Pm(t)}),Um=Object.freeze(Object.defineProperty({__proto__:null,identity:jm},Symbol.toStringTag,{value:"Module"})),Fm=Oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Lm=Object.freeze(Object.defineProperty({__proto__:null,base2:Fm},Symbol.toStringTag,{value:"Module"})),km=Oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Mm=Object.freeze(Object.defineProperty({__proto__:null,base8:km},Symbol.toStringTag,{value:"Module"})),qm=Fi({prefix:"9",name:"base10",alphabet:"0123456789"}),zm=Object.freeze(Object.defineProperty({__proto__:null,base10:qm},Symbol.toStringTag,{value:"Module"})),Hm=Oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vm=Oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Km=Object.freeze(Object.defineProperty({__proto__:null,base16:Hm,base16upper:Vm},Symbol.toStringTag,{value:"Module"})),Wm=Oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gm=Oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ym=Oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Jm=Oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Zm=Oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Qm=Oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Xm=Oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ew=Oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),tw=Oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),rw=Object.freeze(Object.defineProperty({__proto__:null,base32:Wm,base32hex:Zm,base32hexpad:Xm,base32hexpadupper:ew,base32hexupper:Qm,base32pad:Ym,base32padupper:Jm,base32upper:Gm,base32z:tw},Symbol.toStringTag,{value:"Module"})),iw=Fi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sw=Fi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),nw=Object.freeze(Object.defineProperty({__proto__:null,base36:iw,base36upper:sw},Symbol.toStringTag,{value:"Module"})),ow=Fi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),aw=Fi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),cw=Object.freeze(Object.defineProperty({__proto__:null,base58btc:ow,base58flickr:aw},Symbol.toStringTag,{value:"Module"})),hw=Oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),lw=Oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),uw=Oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),dw=Oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),pw=Object.freeze(Object.defineProperty({__proto__:null,base64:hw,base64pad:lw,base64url:uw,base64urlpad:dw},Symbol.toStringTag,{value:"Module"})),Jl=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),fw=Jl.reduce((t,e,r)=>(t[r]=e,t),[]),gw=Jl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function yw(t){return t.reduce((e,r)=>(e+=fw[r],e),"")}function mw(t){const e=[];for(const r of t){const i=gw[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const ww=Ns({prefix:"🚀",name:"base256emoji",encode:yw,decode:mw}),bw=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:ww},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Va={...Um,...Lm,...Mm,...zm,...Km,...rw,...nw,...cw,...pw,...bw};function Zl(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Ka=Zl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),un=Zl("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Gl(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Ql={utf8:Ka,"utf-8":Ka,hex:Va.base16,latin1:un,ascii:un,binary:un,...Va};function tt(t,e="utf8"){const r=Ql[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}function ke(t,e="utf8"){const r=Ql[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}const vw={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}};var Ew={};const _w=":";function Vr(t){const[e,r]=t.split(_w);return{namespace:e,reference:r}}function Wa(t,e=[]){const r=[];return Object.keys(t).forEach(i=>{if(e.length&&!e.includes(i))return;const s=t[i];r.push(...s.accounts)}),r}function Xl(t,e){return t.includes(":")?[t]:e.chains||[]}var Iw=Object.defineProperty,$w=Object.defineProperties,Dw=Object.getOwnPropertyDescriptors,Ga=Object.getOwnPropertySymbols,Sw=Object.prototype.hasOwnProperty,Ow=Object.prototype.propertyIsEnumerable,Ya=(t,e,r)=>e in t?Iw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ja=(t,e)=>{for(var r in e||(e={}))Sw.call(e,r)&&Ya(t,r,e[r]);if(Ga)for(var r of Ga(e))Ow.call(e,r)&&Ya(t,r,e[r]);return t},Pw=(t,e)=>$w(t,Dw(e));const Aw="ReactNative",We={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},xw="js";function Es(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Wt(){return!ar()&&!!So()&&navigator.product===Aw}function Cw(){return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function Tw(){return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function ii(){return!Es()&&!!So()&&!!ar()}function Li(){return Wt()?We.reactNative:Es()?We.node:ii()?We.browser:We.unknown}function Za(){var t;try{return Wt()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Rw(t,e){const r=new URLSearchParams(t);for(const i of Object.keys(e).sort())if(e.hasOwnProperty(i)){const s=e[i];s!==void 0&&r.set(i,s)}return r.toString()}function Nw(t){var e,r;const i=eu();try{return t!=null&&t.url&&i.url&&new URL(t.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),t.url=i.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),Pw(Ja(Ja({},i),t),{url:(t==null?void 0:t.url)||i.url,name:(t==null?void 0:t.name)||i.name,description:(t==null?void 0:t.description)||i.description,icons:(r=t==null?void 0:t.icons)!=null&&r.length&&t.icons.length>0?t.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),t||i}}function eu(){return ol()||{name:"",description:"",url:"",icons:[""]}}function Bw(){if(Li()===We.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:r,Version:i}=global.Platform;return[r,i].join("-")}const t=Jd();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 jw(){var t;const e=Li();return e===We.browser?[e,((t=nl())==null?void 0:t.host)||"unknown"].join(":"):e}function tu(t,e,r){const i=Bw(),s=jw();return[[t,e].join("-"),[xw,r].join("-"),i,s].join("/")}function Uw({protocol:t,version:e,relayUrl:r,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=r.split("?"),l=tu(t,e,i),u={auth:s,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},d=Rw(h[1]||"",u);return h[0]+"?"+d}function sr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Wn(t){return Object.fromEntries(t.entries())}function Gn(t){return new Map(Object.entries(t))}function Qt(t=N.FIVE_MINUTES,e){const r=N.toMiliseconds(t||N.FIVE_MINUTES);let i,s,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const h=new Error(e);o=Promise.reject(h),c(h)},r),i=a,s=c})}}function zt(t,e,r){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(r)),e);try{const o=await t;i(o)}catch(o){s(o)}clearTimeout(n)})}function ru(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 Fw(t){return ru("topic",t)}function Lw(t){return ru("id",t)}function iu(t){const[e,r]=t.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")i.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))i.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return i}function de(t,e){return N.fromMiliseconds(Date.now()+N.toMiliseconds(t))}function Mt(t){return Date.now()>=N.toMiliseconds(t)}function X(t,e){return`${t}${e?`:${e}`:""}`}function _t(t=[],e=[]){return[...new Set([...t,...e])]}async function kw({id:t,topic:e,wcDeepLink:r}){var i;try{if(!r)return;const s=typeof r=="string"?JSON.parse(r):r,n=s==null?void 0:s.href;if(typeof n!="string")return;const o=Mw(n,t,e),a=Li();if(a===We.browser){if(!((i=ar())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}qw(o)}else a===We.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function Mw(t,e,r){const i=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${Kw(i,!0)}`}else s=`${s}/wc?${i}`;return s}function qw(t){let e="_self";Vw()?e="_top":(Hw()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function zw(t,e){let r="";try{if(ii()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(i){console.error(i)}return r}function Qa(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),i=r.indexOf(e);return r[i+2]}function Xa(){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 jo(){return typeof process<"u"&&Ew.IS_VITEST==="true"}function Hw(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Vw(){try{return window.self!==window.top}catch{return!1}}function Kw(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function su(t){return Buffer.from(t,"base64").toString("utf-8")}function Ww(t){return new Promise(e=>setTimeout(e,t))}function Pi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Gw(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ki(t,...e){if(!Gw(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 Uo(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Pi(t.outputLen),Pi(t.blockLen)}function Kr(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 nu(t,e){ki(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Qi=BigInt(2**32-1),ec=BigInt(32);function Yw(t,e=!1){return e?{h:Number(t&Qi),l:Number(t>>ec&Qi)}:{h:Number(t>>ec&Qi)|0,l:Number(t&Qi)|0}}function Jw(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=Yw(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const Zw=(t,e,r)=>t<<r|e>>>32-r,Qw=(t,e,r)=>e<<r|t>>>32-r,Xw=(t,e,r)=>e<<r-32|t>>>64-r,eb=(t,e,r)=>t<<r-32|e>>>64-r,Ir=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function tb(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function dn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function ft(t,e){return t<<32-e|t>>>e}const tc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function rb(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function rc(t){for(let e=0;e<t.length;e++)t[e]=rb(t[e])}function ib(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Wr(t){return typeof t=="string"&&(t=ib(t)),ki(t),t}function sb(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];ki(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}let Fo=class{clone(){return this._cloneInto()}};function ou(t){const e=i=>t().update(Wr(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function si(t=32){if(Ir&&typeof Ir.getRandomValues=="function")return Ir.getRandomValues(new Uint8Array(t));if(Ir&&typeof Ir.randomBytes=="function")return Ir.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const au=[],cu=[],hu=[],nb=BigInt(0),di=BigInt(1),ob=BigInt(2),ab=BigInt(7),cb=BigInt(256),hb=BigInt(113);for(let t=0,e=di,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],au.push(2*(5*i+r)),cu.push((t+1)*(t+2)/2%64);let s=nb;for(let n=0;n<7;n++)e=(e<<di^(e>>ab)*hb)%cb,e&ob&&(s^=di<<(di<<BigInt(n))-di);hu.push(s)}const[lb,ub]=Jw(hu,!0),ic=(t,e,r)=>r>32?Xw(t,e,r):Zw(t,e,r),sc=(t,e,r)=>r>32?eb(t,e,r):Qw(t,e,r);function db(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[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,h=r[c],l=r[c+1],u=ic(h,l,1)^r[a],d=sc(h,l,1)^r[a+1];for(let f=0;f<50;f+=10)t[o+f]^=u,t[o+f+1]^=d}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=cu[o],c=ic(s,n,a),h=sc(s,n,a),l=au[o];s=t[l],n=t[l+1],t[l]=c,t[l+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=lb[i],t[1]^=ub[i]}r.fill(0)}let pb=class lu extends Fo{constructor(e,r,i,s=!1,n=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Pi(i),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=tb(this.state)}keccak(){tc||rc(this.state32),db(this.state32,this.rounds),tc||rc(this.state32),this.posOut=0,this.pos=0}update(e){Kr(this);const{blockLen:r,state:i}=this;e=Wr(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,r&128&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Kr(this,!1),ki(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=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 Pi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(nu(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,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new lu(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const fb=(t,e,r)=>ou(()=>new pb(e,t,r)),gb=fb(1,136,256/8),yb="https://rpc.walletconnect.org/v1";function uu(t){const e=`Ethereum Signed Message:
17
17
  ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(gb(r)).toString("hex")}async function mb(t,e,r,i,s,n){switch(r.t){case"eip191":return await wb(t,e,r.s);case"eip1271":return await bb(t,e,r.s,i,s,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}async function wb(t,e,r){return(await Pf({hash:uu(e),signature:r})).toLowerCase()===t.toLowerCase()}async function bb(t,e,r,i,s,n){const o=Vr(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",h="0000000000000000000000000000000000000000000000000000000000000041",l=r.substring(2),u=uu(e).substring(2),d=a+u+c+h+l,f=await fetch(`${n||yb}/?chainId=${i}&projectId=${s}`,{method:"POST",body:JSON.stringify({id:vb(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:p}=await f.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function vb(){return Date.now()+Math.floor(Math.random()*1e3)}function Eb(t){const e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);const i=r[0];if(i===0)throw new Error("No signatures found");const s=1+i*64;if(r.length<s)throw new Error("Transaction data too short for claimed signature count");if(r.length<100)throw new Error("Transaction too short");const n=Buffer.from(t,"base64").slice(1,65);return Cf.encode(n)}var _b=Object.defineProperty,Ib=Object.defineProperties,$b=Object.getOwnPropertyDescriptors,nc=Object.getOwnPropertySymbols,Db=Object.prototype.hasOwnProperty,Sb=Object.prototype.propertyIsEnumerable,oc=(t,e,r)=>e in t?_b(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ob=(t,e)=>{for(var r in e||(e={}))Db.call(e,r)&&oc(t,r,e[r]);if(nc)for(var r of nc(e))Sb.call(e,r)&&oc(t,r,e[r]);return t},Pb=(t,e)=>Ib(t,$b(e));const Ab="did:pkh:",Lo=t=>t==null?void 0:t.split(":"),xb=t=>{const e=t&&Lo(t);if(e)return t.includes(Ab)?e[3]:e[1]},Yn=t=>{const e=t&&Lo(t);if(e)return e[2]+":"+e[3]},_s=t=>{const e=t&&Lo(t);if(e)return e.pop()};async function ac(t){const{cacao:e,projectId:r}=t,{s:i,p:s}=e,n=du(s,s.iss),o=_s(s.iss);return await mb(o,n,i,Yn(s.iss),r)}const du=(t,e)=>{const r=`${t.domain} wants you to sign in with your Ethereum account:`,i=_s(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=t.statement||void 0;const n=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${xb(e)}`,c=`Nonce: ${t.nonce}`,h=`Issued At: ${t.iat}`,l=t.exp?`Expiration Time: ${t.exp}`:void 0,u=t.nbf?`Not Before: ${t.nbf}`:void 0,d=t.requestId?`Request ID: ${t.requestId}`:void 0,f=t.resources?`Resources:${t.resources.map(y=>`
18
18
  - ${y}`).join("")}`:void 0,p=ds(t.resources);if(p){const y=Ai(p);s=Lb(s,y)}return[r,i,"",s,"",n,o,a,c,h,l,u,d,f].filter(y=>y!=null).join(`
19
19
  `)};function Cb(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function Tb(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function lr(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(r=>{const i=t.att[r];if(Array.isArray(i))throw new Error(`Resource must be an object: ${r}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(i).forEach(s=>{const n=i[s];if(!Array.isArray(n))throw new Error(`Ability limits ${s} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function Rb(t,e,r,i={}){return r==null||r.sort((s,n)=>s.localeCompare(n)),{att:{[t]:Nb(e,r,i)}}}function Nb(t,e,r={}){e=e==null?void 0:e.sort((s,n)=>s.localeCompare(n));const i=e.map(s=>({[`${t}/${s}`]:[r]}));return Object.assign({},...i)}function pu(t){return lr(t),`urn:recap:${Cb(t).replace(/=/g,"")}`}function Ai(t){const e=Tb(t.replace("urn:recap:",""));return lr(e),e}function Bb(t,e,r){const i=Rb(t,e,r);return pu(i)}function jb(t){return t&&t.includes("urn:recap:")}function Ub(t,e){const r=Ai(t),i=Ai(e),s=Fb(r,i);return pu(s)}function Fb(t,e){lr(t),lr(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((s,n)=>s.localeCompare(n)),i={att:{}};return r.forEach(s=>{var n,o;Object.keys(((n=t.att)==null?void 0:n[s])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[s])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,h;i.att[s]=Pb(Ob({},i.att[s]),{[a]:((c=t.att[s])==null?void 0:c[a])||((h=e.att[s])==null?void 0:h[a])})})}),i}function Lb(t="",e){lr(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const i=[];let s=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,d)=>u.action.localeCompare(d.action));const h={};c.forEach(u=>{h[u.ability]||(h[u.ability]=[]),h[u.ability].push(u.action)});const l=Object.keys(h).map(u=>(s++,`(${s}) '${u}': '${h[u].join("', '")}' for '${a}'.`));i.push(l.join(", ").replace(".,","."))});const n=i.join(" "),o=`${r}${n}`;return`${t?t+" ":""}${o}`}function cc(t){var e;const r=Ai(t);lr(r);const i=(e=r.att)==null?void 0:e.eip155;return i?Object.keys(i).map(s=>s.split("/")[1]):[]}function hc(t){const e=Ai(t);lr(e);const r=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(s=>{var n;(n=s==null?void 0:s[0])!=null&&n.chains&&r.push(s[0].chains)})}),[...new Set(r.flat())]}function ds(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return jb(e)?e:void 0}function pn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function fu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ke(t,...e){if(!fu(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 lc(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 kb(t,e){Ke(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function uc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const Vt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),Mb=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),qb=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!qb)throw new Error("Non little-endian hardware is not supported");function zb(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Jn(t){if(typeof t=="string")t=zb(t);else if(fu(t))t=Zn(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Hb(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Vb(t,e){if(t.length!==e.length)return!1;let r=0;for(let i=0;i<t.length;i++)r|=t[i]^e[i];return r===0}const Kb=(t,e)=>{function r(i,...s){if(Ke(i),t.nonceLength!==void 0){const h=s[0];if(!h)throw new Error("nonce / iv required");t.varSizeNonce?Ke(h):Ke(h,t.nonceLength)}const n=t.tagLength;n&&s[1]!==void 0&&Ke(s[1]);const o=e(i,...s),a=(h,l)=>{if(l!==void 0){if(h!==2)throw new Error("cipher output not supported");Ke(l)}};let c=!1;return{encrypt(h,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ke(h),a(o.encrypt.length,l),o.encrypt(h,l)},decrypt(h,l){if(Ke(h),n&&h.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(h,l)}}}return Object.assign(r,t),r};function dc(t,e,r=!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(r&&!Wb(e))throw new Error("invalid output, must be aligned");return e}function pc(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n);t.setUint32(e+4,o,i),t.setUint32(e+0,a,i)}function Wb(t){return t.byteOffset%4===0}function Zn(t){return Uint8Array.from(t)}function Gr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const gu=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),Gb=gu("expand 16-byte k"),Yb=gu("expand 32-byte k"),Jb=Vt(Gb),Zb=Vt(Yb);function J(t,e){return t<<e|t>>>32-e}function Qn(t){return t.byteOffset%4===0}const Xi=64,Qb=16,yu=2**32-1,fc=new Uint32Array;function Xb(t,e,r,i,s,n,o,a){const c=s.length,h=new Uint8Array(Xi),l=Vt(h),u=Qn(s)&&Qn(n),d=u?Vt(s):fc,f=u?Vt(n):fc;for(let p=0;p<c;o++){if(t(e,r,i,l,o,a),o>=yu)throw new Error("arx: counter overflow");const y=Math.min(Xi,c-p);if(u&&y===Xi){const w=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let v=0,b;v<Qb;v++)b=w+v,f[b]=d[b]^l[v];p+=Xi;continue}for(let w=0,v;w<y;w++)v=p+w,n[v]=s[v]^h[w];p+=y}}function ev(t,e){const{allowShortKeys:r,extendNonceFn:i,counterLength:s,counterRight:n,rounds:o}=Hb({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return pn(s),pn(o),uc(n),uc(r),(a,c,h,l,u=0)=>{Ke(a),Ke(c),Ke(h);const d=h.length;if(l===void 0&&(l=new Uint8Array(d)),Ke(l),pn(u),u<0||u>=yu)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const f=[];let p=a.length,y,w;if(p===32)f.push(y=Zn(a)),w=Zb;else if(p===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),w=Jb,f.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Qn(c)||f.push(c=Zn(c));const v=Vt(y);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(w,v,Vt(c.subarray(0,16)),v),c=c.subarray(16)}const b=16-s;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){const I=new Uint8Array(12);I.set(c,n?0:12-c.length),c=I,f.push(c)}const E=Vt(c);return Xb(t,w,v,E,h,l,u,o),Gr(...f),l}}const _e=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class tv{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=Jn(e),Ke(e,32);const r=_e(e,0),i=_e(e,2),s=_e(e,4),n=_e(e,6),o=_e(e,8),a=_e(e,10),c=_e(e,12),h=_e(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|i<<3)&8191,this.r[2]=(i>>>10|s<<6)&7939,this.r[3]=(s>>>7|n<<9)&8191,this.r[4]=(n>>>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|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=_e(e,16+2*l)}process(e,r,i=!1){const s=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],h=o[2],l=o[3],u=o[4],d=o[5],f=o[6],p=o[7],y=o[8],w=o[9],v=_e(e,r+0),b=_e(e,r+2),E=_e(e,r+4),I=_e(e,r+6),P=_e(e,r+8),A=_e(e,r+10),O=_e(e,r+12),C=_e(e,r+14);let D=n[0]+(v&8191),M=n[1]+((v>>>13|b<<3)&8191),U=n[2]+((b>>>10|E<<6)&8191),j=n[3]+((E>>>7|I<<9)&8191),q=n[4]+((I>>>4|P<<12)&8191),T=n[5]+(P>>>1&8191),g=n[6]+((P>>>14|A<<2)&8191),m=n[7]+((A>>>11|O<<5)&8191),_=n[8]+((O>>>8|C<<8)&8191),S=n[9]+(C>>>5|s),$=0,x=$+D*a+M*(5*w)+U*(5*y)+j*(5*p)+q*(5*f);$=x>>>13,x&=8191,x+=T*(5*d)+g*(5*u)+m*(5*l)+_*(5*h)+S*(5*c),$+=x>>>13,x&=8191;let F=$+D*c+M*a+U*(5*w)+j*(5*y)+q*(5*p);$=F>>>13,F&=8191,F+=T*(5*f)+g*(5*d)+m*(5*u)+_*(5*l)+S*(5*h),$+=F>>>13,F&=8191;let k=$+D*h+M*c+U*a+j*(5*w)+q*(5*y);$=k>>>13,k&=8191,k+=T*(5*p)+g*(5*f)+m*(5*d)+_*(5*u)+S*(5*l),$+=k>>>13,k&=8191;let z=$+D*l+M*h+U*c+j*a+q*(5*w);$=z>>>13,z&=8191,z+=T*(5*y)+g*(5*p)+m*(5*f)+_*(5*d)+S*(5*u),$+=z>>>13,z&=8191;let L=$+D*u+M*l+U*h+j*c+q*a;$=L>>>13,L&=8191,L+=T*(5*w)+g*(5*y)+m*(5*p)+_*(5*f)+S*(5*d),$+=L>>>13,L&=8191;let H=$+D*d+M*u+U*l+j*h+q*c;$=H>>>13,H&=8191,H+=T*a+g*(5*w)+m*(5*y)+_*(5*p)+S*(5*f),$+=H>>>13,H&=8191;let G=$+D*f+M*d+U*u+j*l+q*h;$=G>>>13,G&=8191,G+=T*c+g*a+m*(5*w)+_*(5*y)+S*(5*p),$+=G>>>13,G&=8191;let se=$+D*p+M*f+U*d+j*u+q*l;$=se>>>13,se&=8191,se+=T*h+g*c+m*a+_*(5*w)+S*(5*y),$+=se>>>13,se&=8191;let ee=$+D*y+M*p+U*f+j*d+q*u;$=ee>>>13,ee&=8191,ee+=T*l+g*h+m*c+_*a+S*(5*w),$+=ee>>>13,ee&=8191;let Y=$+D*w+M*y+U*p+j*f+q*d;$=Y>>>13,Y&=8191,Y+=T*u+g*l+m*h+_*c+S*a,$+=Y>>>13,Y&=8191,$=($<<2)+$|0,$=$+x|0,x=$&8191,$=$>>>13,F+=$,n[0]=x,n[1]=F,n[2]=k,n[3]=z,n[4]=L,n[5]=H,n[6]=G,n[7]=se,n[8]=ee,n[9]=Y}finalize(){const{h:e,pad:r}=this,i=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,i[0]=e[0]+5,s=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+s,s=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(s^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[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]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Gr(i)}update(e){lc(this);const{buffer:r,blockLen:i}=this;e=Jn(e);const s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);if(o===i){for(;i<=s-n;n+=i)this.process(e,n);continue}r.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){Gr(this.h,this.r,this.buffer,this.pad)}digestInto(e){lc(this),kb(e,this),this.finished=!0;const{buffer:r,h:i}=this;let{pos:s}=this;if(s){for(r[s++]=1;s<16;s++)r[s]=0;this.process(r,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}}function rv(t){const e=(i,s)=>t(s).update(Jn(i)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}const iv=rv(t=>new tv(t));function sv(t,e,r,i,s,n=20){let o=t[0],a=t[1],c=t[2],h=t[3],l=e[0],u=e[1],d=e[2],f=e[3],p=e[4],y=e[5],w=e[6],v=e[7],b=s,E=r[0],I=r[1],P=r[2],A=o,O=a,C=c,D=h,M=l,U=u,j=d,q=f,T=p,g=y,m=w,_=v,S=b,$=E,x=I,F=P;for(let z=0;z<n;z+=2)A=A+M|0,S=J(S^A,16),T=T+S|0,M=J(M^T,12),A=A+M|0,S=J(S^A,8),T=T+S|0,M=J(M^T,7),O=O+U|0,$=J($^O,16),g=g+$|0,U=J(U^g,12),O=O+U|0,$=J($^O,8),g=g+$|0,U=J(U^g,7),C=C+j|0,x=J(x^C,16),m=m+x|0,j=J(j^m,12),C=C+j|0,x=J(x^C,8),m=m+x|0,j=J(j^m,7),D=D+q|0,F=J(F^D,16),_=_+F|0,q=J(q^_,12),D=D+q|0,F=J(F^D,8),_=_+F|0,q=J(q^_,7),A=A+U|0,F=J(F^A,16),m=m+F|0,U=J(U^m,12),A=A+U|0,F=J(F^A,8),m=m+F|0,U=J(U^m,7),O=O+j|0,S=J(S^O,16),_=_+S|0,j=J(j^_,12),O=O+j|0,S=J(S^O,8),_=_+S|0,j=J(j^_,7),C=C+q|0,$=J($^C,16),T=T+$|0,q=J(q^T,12),C=C+q|0,$=J($^C,8),T=T+$|0,q=J(q^T,7),D=D+M|0,x=J(x^D,16),g=g+x|0,M=J(M^g,12),D=D+M|0,x=J(x^D,8),g=g+x|0,M=J(M^g,7);let k=0;i[k++]=o+A|0,i[k++]=a+O|0,i[k++]=c+C|0,i[k++]=h+D|0,i[k++]=l+M|0,i[k++]=u+U|0,i[k++]=d+j|0,i[k++]=f+q|0,i[k++]=p+T|0,i[k++]=y+g|0,i[k++]=w+m|0,i[k++]=v+_|0,i[k++]=b+S|0,i[k++]=E+$|0,i[k++]=I+x|0,i[k++]=P+F|0}const nv=ev(sv,{counterRight:!1,counterLength:4,allowShortKeys:!1}),ov=new Uint8Array(16),gc=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(ov.subarray(r))},av=new Uint8Array(32);function yc(t,e,r,i,s){const n=t(e,r,av),o=iv.create(n);s&&gc(o,s),gc(o,i);const a=new Uint8Array(16),c=Mb(a);pc(c,0,BigInt(s?s.length:0),!0),pc(c,8,BigInt(i.length),!0),o.update(a);const h=o.digest();return Gr(n,a),h}const cv=t=>(e,r,i)=>({encrypt(s,n){const o=s.length;n=dc(o+16,n,!1),n.set(s);const a=n.subarray(0,-16);t(e,r,a,a,1);const c=yc(t,e,r,a,i);return n.set(c,o),Gr(c),n},decrypt(s,n){n=dc(s.length-16,n,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=yc(t,e,r,o,i);if(!Vb(a,c))throw new Error("invalid tag");return n.set(s.subarray(0,-16)),t(e,r,n,n,1),Gr(c),n}}),mu=Kb({blockSize:64,nonceLength:12,tagLength:16},cv(nv));let wu=class extends Fo{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Uo(e);const i=Wr(r);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 s=this.blockLen,n=new Uint8Array(s);n.set(i.length>s?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return Kr(this),this.iHash.update(e),this}digestInto(e){Kr(this),ki(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:r,iHash:i,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Bs=(t,e,r)=>new wu(t,e).update(r).digest();Bs.create=(t,e)=>new wu(t,e);function hv(t,e,r){return Uo(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Bs(t,Wr(r),Wr(e))}const fn=new Uint8Array([0]),mc=new Uint8Array;function lv(t,e,r,i=32){if(Uo(t),Pi(i),i>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(i/t.outputLen);r===void 0&&(r=mc);const n=new Uint8Array(s*t.outputLen),o=Bs.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let h=0;h<s;h++)fn[0]=h+1,a.update(h===0?mc:c).update(r).update(fn).digestInto(c),n.set(c,t.outputLen*h),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),fn.fill(0),n.slice(0,i)}const uv=(t,e,r,i,s)=>lv(t,hv(t,e,r),i,s);function dv(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,h=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+h,a,i)}function pv(t,e,r){return t&e^~t&r}function fv(t,e,r){return t&e^t&r^e&r}let gv=class extends Fo{constructor(e,r,i,s){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=dn(this.buffer)}update(e){Kr(this);const{view:r,buffer:i,blockLen:s}=this;e=Wr(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=dn(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Kr(this),nu(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let u=o;u<s;u++)r[u]=0;dv(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=dn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=c/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%r&&e.buffer.set(i),e}};const yv=new Uint32Array([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]),Lt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),kt=new Uint32Array(64);class mv extends gv{constructor(){super(64,32,8,!1),this.A=Lt[0]|0,this.B=Lt[1]|0,this.C=Lt[2]|0,this.D=Lt[3]|0,this.E=Lt[4]|0,this.F=Lt[5]|0,this.G=Lt[6]|0,this.H=Lt[7]|0}get(){const{A:e,B:r,C:i,D:s,E:n,F:o,G:a,H:c}=this;return[e,r,i,s,n,o,a,c]}set(e,r,i,s,n,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let u=0;u<16;u++,r+=4)kt[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){const d=kt[u-15],f=kt[u-2],p=ft(d,7)^ft(d,18)^d>>>3,y=ft(f,17)^ft(f,19)^f>>>10;kt[u]=y+kt[u-7]+p+kt[u-16]|0}let{A:i,B:s,C:n,D:o,E:a,F:c,G:h,H:l}=this;for(let u=0;u<64;u++){const d=ft(a,6)^ft(a,11)^ft(a,25),f=l+d+pv(a,c,h)+yv[u]+kt[u]|0,p=(ft(i,2)^ft(i,13)^ft(i,22))+fv(i,s,n)|0;l=h,h=c,c=a,a=o+f|0,o=n,n=s,s=i,i=f+p|0}i=i+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(i,s,n,o,a,c,h,l)}roundClean(){kt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Mi=ou(()=>new mv);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const js=BigInt(0),Us=BigInt(1),wv=BigInt(2);function ur(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function qi(t){if(!ur(t))throw new Error("Uint8Array expected")}function Yr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const bv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Jr(t){qi(t);let e="";for(let r=0;r<t.length;r++)e+=bv[t[r]];return e}function qr(t){const e=t.toString(16);return e.length&1?"0"+e:e}function ko(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?js:BigInt("0x"+t)}const Pt={_0:48,_9:57,A:65,F:70,a:97,f:102};function wc(t){if(t>=Pt._0&&t<=Pt._9)return t-Pt._0;if(t>=Pt.A&&t<=Pt.F)return t-(Pt.A-10);if(t>=Pt.a&&t<=Pt.f)return t-(Pt.a-10)}function Zr(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=wc(t.charCodeAt(n)),a=wc(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function or(t){return ko(Jr(t))}function xi(t){return qi(t),ko(Jr(Uint8Array.from(t).reverse()))}function Qr(t,e){return Zr(t.toString(16).padStart(e*2,"0"))}function Fs(t,e){return Qr(t,e).reverse()}function vv(t){return Zr(qr(t))}function Ve(t,e,r){let i;if(typeof e=="string")try{i=Zr(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(ur(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function Ci(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];qi(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}function Ev(t,e){if(t.length!==e.length)return!1;let r=0;for(let i=0;i<t.length;i++)r|=t[i]^e[i];return r===0}function _v(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const gn=t=>typeof t=="bigint"&&js<=t;function Ls(t,e,r){return gn(t)&&gn(e)&&gn(r)&&e<=t&&t<r}function Nt(t,e,r,i){if(!Ls(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function bu(t){let e;for(e=0;t>js;t>>=Us,e+=1);return e}function Iv(t,e){return t>>BigInt(e)&Us}function $v(t,e,r){return t|(r?Us:js)<<BigInt(e)}const Mo=t=>(wv<<BigInt(t-1))-Us,yn=t=>new Uint8Array(t),bc=t=>Uint8Array.from(t);function vu(t,e,r){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 r!="function")throw new Error("hmacFn must be a function");let i=yn(t),s=yn(t),n=0;const o=()=>{i.fill(1),s.fill(0),n=0},a=(...l)=>r(s,i,...l),c=(l=yn())=>{s=a(bc([0]),l),i=a(),l.length!==0&&(s=a(bc([1]),l),i=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const u=[];for(;l<e;){i=a();const d=i.slice();u.push(d),l+=i.length}return Ci(...u)};return(l,u)=>{o(),c(l);let d;for(;!(d=u(h()));)c();return o(),d}}const Dv={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"||ur(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 ni(t,e,r={}){const i=(s,n,o)=>{const a=Dv[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}const Sv=()=>{throw new Error("not implemented")};function Xn(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}var Ov=Object.freeze({__proto__:null,isBytes:ur,abytes:qi,abool:Yr,bytesToHex:Jr,numberToHexUnpadded:qr,hexToNumber:ko,hexToBytes:Zr,bytesToNumberBE:or,bytesToNumberLE:xi,numberToBytesBE:Qr,numberToBytesLE:Fs,numberToVarBytesBE:vv,ensureBytes:Ve,concatBytes:Ci,equalBytes:Ev,utf8ToBytes:_v,inRange:Ls,aInRange:Nt,bitLen:bu,bitGet:Iv,bitSet:$v,bitMask:Mo,createHmacDrbg:vu,validateObject:ni,notImplemented:Sv,memoized:Xn});const ve=BigInt(0),he=BigInt(1),tr=BigInt(2),Pv=BigInt(3),eo=BigInt(4),vc=BigInt(5),Ec=BigInt(8);function Le(t,e){const r=t%e;return r>=ve?r:e+r}function Eu(t,e,r){if(e<ve)throw new Error("invalid exponent, negatives unsupported");if(r<=ve)throw new Error("invalid modulus");if(r===he)return ve;let i=he;for(;e>ve;)e&he&&(i=i*t%r),t=t*t%r,e>>=he;return i}function ht(t,e,r){let i=t;for(;e-- >ve;)i*=i,i%=r;return i}function to(t,e){if(t===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let r=Le(t,e),i=e,s=ve,n=he;for(;r!==ve;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==he)throw new Error("invert: does not exist");return Le(s,e)}function Av(t){const e=(t-he)/tr;let r,i,s;for(r=t-he,i=0;r%tr===ve;r/=tr,i++);for(s=tr;s<t&&Eu(s,e,t)!==t-he;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+he)/eo;return function(a,c){const h=a.pow(c,o);if(!a.eql(a.sqr(h),c))throw new Error("Cannot find square root");return h}}const n=(r+he)/tr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,h=o.pow(o.mul(o.ONE,s),r),l=o.pow(a,n),u=o.pow(a,r);for(;!o.eql(u,o.ONE);){if(o.eql(u,o.ZERO))return o.ZERO;let d=1;for(let p=o.sqr(u);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const f=o.pow(h,he<<BigInt(c-d-1));h=o.sqr(f),l=o.mul(l,f),u=o.mul(u,h),c=d}return l}}function xv(t){if(t%eo===Pv){const e=(t+he)/eo;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%Ec===vc){const e=(t-vc)/Ec;return function(r,i){const s=r.mul(i,tr),n=r.pow(s,e),o=r.mul(i,n),a=r.mul(r.mul(o,tr),n),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return Av(t)}const Cv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Tv(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Cv.reduce((i,s)=>(i[s]="function",i),e);return ni(t,r)}function Rv(t,e,r){if(r<ve)throw new Error("invalid exponent, negatives unsupported");if(r===ve)return t.ONE;if(r===he)return e;let i=t.ONE,s=e;for(;r>ve;)r&he&&(i=t.mul(i,s)),s=t.sqr(s),r>>=he;return i}function Nv(t,e){const r=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(r[a]=n,t.mul(n,o)),t.ONE),s=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(r[a]=t.mul(n,r[a]),t.mul(n,o)),s),r}function _u(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Iu(t,e,r=!1,i={}){if(t<=ve)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=_u(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:Mo(s),ZERO:ve,ONE:he,create:c=>Le(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ve<=c&&c<t},is0:c=>c===ve,isOdd:c=>(c&he)===he,neg:c=>Le(-c,t),eql:(c,h)=>c===h,sqr:c=>Le(c*c,t),add:(c,h)=>Le(c+h,t),sub:(c,h)=>Le(c-h,t),mul:(c,h)=>Le(c*h,t),pow:(c,h)=>Rv(a,c,h),div:(c,h)=>Le(c*to(h,t),t),sqrN:c=>c*c,addN:(c,h)=>c+h,subN:(c,h)=>c-h,mulN:(c,h)=>c*h,inv:c=>to(c,t),sqrt:i.sqrt||(c=>(o||(o=xv(t)),o(a,c))),invertBatch:c=>Nv(a,c),cmov:(c,h,l)=>l?h:c,toBytes:c=>r?Fs(c,n):Qr(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?xi(c):or(c)}});return Object.freeze(a)}function $u(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 Du(t){const e=$u(t);return e+Math.ceil(e/2)}function Bv(t,e,r=!1){const i=t.length,s=$u(e),n=Du(e);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=r?xi(t):or(t),a=Le(o,e-he)+he;return r?Fs(a,s):Qr(a,s)}const _c=BigInt(0),es=BigInt(1);function mn(t,e){const r=e.negate();return t?r:e}function Su(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function wn(t,e){Su(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function jv(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function Uv(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const bn=new WeakMap,Ou=new WeakMap;function vn(t){return Ou.get(t)||1}function Fv(t,e){return{constTimeNegate:mn,hasPrecomputes(r){return vn(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>_c;)i&es&&(s=s.add(n)),n=n.double(),i>>=es;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=wn(i,e),o=[];let a=r,c=a;for(let h=0;h<s;h++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){const{windows:n,windowSize:o}=wn(r,e);let a=t.ZERO,c=t.BASE;const h=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let d=0;d<n;d++){const f=d*o;let p=Number(s&h);s>>=u,p>o&&(p-=l,s+=es);const y=f,w=f+Math.abs(p)-1,v=d%2!==0,b=p<0;p===0?c=c.add(mn(v,i[y])):a=a.add(mn(b,i[w]))}return{p:a,f:c}},wNAFUnsafe(r,i,s,n=t.ZERO){const{windows:o,windowSize:a}=wn(r,e),c=BigInt(2**r-1),h=2**r,l=BigInt(r);for(let u=0;u<o;u++){const d=u*a;if(s===_c)break;let f=Number(s&c);if(s>>=l,f>a&&(f-=h,s+=es),f===0)continue;let p=i[d+Math.abs(f)-1];f<0&&(p=p.negate()),n=n.add(p)}return n},getPrecomputes(r,i,s){let n=bn.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&bn.set(i,s(n))),n},wNAFCached(r,i,s){const n=vn(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=vn(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){Su(i,e),Ou.set(r,i),bn.delete(r)}}}function Lv(t,e,r,i){if(jv(r,t),Uv(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=bu(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),h=Math.floor((e.BITS-1)/o)*o;let l=s;for(let u=h;u>=0;u-=o){c.fill(s);for(let f=0;f<i.length;f++){const p=i[f],y=Number(p>>BigInt(u)&BigInt(a));c[y]=c[y].add(r[f])}let d=s;for(let f=c.length-1,p=s;f>0;f--)p=p.add(c[f]),d=d.add(p);if(l=l.add(d),u!==0)for(let f=0;f<o;f++)l=l.double()}return l}function Pu(t){return Tv(t.Fp),ni(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({..._u(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const $r=BigInt(0),En=BigInt(1);function kv(t){return ni(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function Mv(t){const e=kv(t),{P:r}=e,i=b=>Le(b,r),s=e.montgomeryBits,n=Math.ceil(s/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),c=e.powPminus2||(b=>Eu(b,r-BigInt(2),r));function h(b,E,I){const P=i(b*(E-I));return E=i(E-P),I=i(I+P),[E,I]}const l=(e.a-BigInt(2))/BigInt(4);function u(b,E){Nt("u",b,$r,r),Nt("scalar",E,$r,r);const I=E,P=b;let A=En,O=$r,C=b,D=En,M=$r,U;for(let q=BigInt(s-1);q>=$r;q--){const T=I>>q&En;M^=T,U=h(M,A,C),A=U[0],C=U[1],U=h(M,O,D),O=U[0],D=U[1],M=T;const g=A+O,m=i(g*g),_=A-O,S=i(_*_),$=m-S,x=C+D,F=C-D,k=i(F*g),z=i(x*_),L=k+z,H=k-z;C=i(L*L),D=i(P*i(H*H)),A=i(m*S),O=i($*(m+i(l*$)))}U=h(M,A,C),A=U[0],C=U[1],U=h(M,O,D),O=U[0],D=U[1];const j=c(O);return i(A*j)}function d(b){return Fs(i(b),n)}function f(b){const E=Ve("u coordinate",b,n);return o===32&&(E[31]&=127),xi(E)}function p(b){const E=Ve("scalar",b),I=E.length;if(I!==n&&I!==o){let P=""+n+" or "+o;throw new Error("invalid scalar, expected "+P+" bytes, got "+I)}return xi(a(E))}function y(b,E){const I=f(E),P=p(b),A=u(I,P);if(A===$r)throw new Error("invalid private or public key received");return d(A)}const w=d(e.Gu);function v(b){return y(b,w)}return{scalarMult:y,scalarMultBase:v,getSharedSecret:(b,E)=>y(b,E),getPublicKey:b=>v(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:w}}const ro=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const qv=BigInt(1),Ic=BigInt(2),zv=BigInt(3),Hv=BigInt(5);BigInt(8);function Vv(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=ro,o=t*t%n*t%n,a=ht(o,Ic,n)*o%n,c=ht(a,qv,n)*t%n,h=ht(c,Hv,n)*c%n,l=ht(h,e,n)*h%n,u=ht(l,r,n)*l%n,d=ht(u,i,n)*u%n,f=ht(d,s,n)*d%n,p=ht(f,s,n)*d%n,y=ht(p,e,n)*h%n;return{pow_p_5_8:ht(y,Ic,n)*t%n,b2:o}}function Kv(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const io=Mv({P:ro,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=ro,{pow_p_5_8:r,b2:i}=Vv(t);return Le(ht(r,zv,e)*i,e)},adjustScalarBytes:Kv,randomBytes:si});function $c(t){t.lowS!==void 0&&Yr("lowS",t.lowS),t.prehash!==void 0&&Yr("prehash",t.prehash)}function Wv(t){const e=Pu(t);ni(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:i,a:s}=e;if(r){if(!i.eql(s,i.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:Gv,hexToBytes:Yv}=Ov;class Jv extends Error{constructor(e=""){super(e)}}const Tt={Err:Jv,_tlv:{encode:(t,e)=>{const{Err:r}=Tt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,s=qr(i);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const n=i>127?qr(s.length/2|128):"";return qr(t)+n+s+e},decode(t,e){const{Err:r}=Tt;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[i++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const h=e.subarray(i,i+c);if(h.length!==c)throw new r("tlv.decode: length bytes not complete");if(h[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of h)o=o<<8|l;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=Tt;if(t<Rt)throw new e("integer: negative integers are not allowed");let r=qr(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=Tt;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 Gv(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=Tt,s=typeof t=="string"?Yv(t):t;qi(s);const{v:n,l:o}=i.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:h,l}=i.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(h)}},hexFromSig(t){const{_tlv:e,_int:r}=Tt,i=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),n=i+s;return e.encode(48,n)}},Rt=BigInt(0),me=BigInt(1);BigInt(2);const Dc=BigInt(3);BigInt(4);function Zv(t){const e=Wv(t),{Fp:r}=e,i=Iu(e.n,e.nBitLength),s=e.toBytes||((y,w,v)=>{const b=w.toAffine();return Ci(Uint8Array.from([4]),r.toBytes(b.x),r.toBytes(b.y))}),n=e.fromBytes||(y=>{const w=y.subarray(1),v=r.fromBytes(w.subarray(0,r.BYTES)),b=r.fromBytes(w.subarray(r.BYTES,2*r.BYTES));return{x:v,y:b}});function o(y){const{a:w,b:v}=e,b=r.sqr(y),E=r.mul(b,y);return r.add(r.add(E,r.mul(y,w)),v)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Ls(y,me,e.n)}function c(y){const{allowedPrivateKeyLengths:w,nByteLength:v,wrapPrivateKey:b,n:E}=e;if(w&&typeof y!="bigint"){if(ur(y)&&(y=Jr(y)),typeof y!="string"||!w.includes(y.length))throw new Error("invalid private key");y=y.padStart(v*2,"0")}let I;try{I=typeof y=="bigint"?y:or(Ve("private key",y,v))}catch{throw new Error("invalid private key, expected hex or "+v+" bytes, got "+typeof y)}return b&&(I=Le(I,E)),Nt("private key",I,me,E),I}function h(y){if(!(y instanceof d))throw new Error("ProjectivePoint expected")}const l=Xn((y,w)=>{const{px:v,py:b,pz:E}=y;if(r.eql(E,r.ONE))return{x:v,y:b};const I=y.is0();w==null&&(w=I?r.ONE:r.inv(E));const P=r.mul(v,w),A=r.mul(b,w),O=r.mul(E,w);if(I)return{x:r.ZERO,y:r.ZERO};if(!r.eql(O,r.ONE))throw new Error("invZ was invalid");return{x:P,y:A}}),u=Xn(y=>{if(y.is0()){if(e.allowInfinityPoint&&!r.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:w,y:v}=y.toAffine();if(!r.isValid(w)||!r.isValid(v))throw new Error("bad point: x or y not FE");const b=r.sqr(v),E=o(w);if(!r.eql(b,E))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(w,v,b){if(this.px=w,this.py=v,this.pz=b,w==null||!r.isValid(w))throw new Error("x required");if(v==null||!r.isValid(v))throw new Error("y required");if(b==null||!r.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(w){const{x:v,y:b}=w||{};if(!w||!r.isValid(v)||!r.isValid(b))throw new Error("invalid affine point");if(w instanceof d)throw new Error("projective point not allowed");const E=I=>r.eql(I,r.ZERO);return E(v)&&E(b)?d.ZERO:new d(v,b,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){const v=r.invertBatch(w.map(b=>b.pz));return w.map((b,E)=>b.toAffine(v[E])).map(d.fromAffine)}static fromHex(w){const v=d.fromAffine(n(Ve("pointHex",w)));return v.assertValidity(),v}static fromPrivateKey(w){return d.BASE.multiply(c(w))}static msm(w,v){return Lv(d,i,w,v)}_setWindowSize(w){p.setWindowSize(this,w)}assertValidity(){u(this)}hasEvenY(){const{y:w}=this.toAffine();if(r.isOdd)return!r.isOdd(w);throw new Error("Field doesn't support isOdd")}equals(w){h(w);const{px:v,py:b,pz:E}=this,{px:I,py:P,pz:A}=w,O=r.eql(r.mul(v,A),r.mul(I,E)),C=r.eql(r.mul(b,A),r.mul(P,E));return O&&C}negate(){return new d(this.px,r.neg(this.py),this.pz)}double(){const{a:w,b:v}=e,b=r.mul(v,Dc),{px:E,py:I,pz:P}=this;let A=r.ZERO,O=r.ZERO,C=r.ZERO,D=r.mul(E,E),M=r.mul(I,I),U=r.mul(P,P),j=r.mul(E,I);return j=r.add(j,j),C=r.mul(E,P),C=r.add(C,C),A=r.mul(w,C),O=r.mul(b,U),O=r.add(A,O),A=r.sub(M,O),O=r.add(M,O),O=r.mul(A,O),A=r.mul(j,A),C=r.mul(b,C),U=r.mul(w,U),j=r.sub(D,U),j=r.mul(w,j),j=r.add(j,C),C=r.add(D,D),D=r.add(C,D),D=r.add(D,U),D=r.mul(D,j),O=r.add(O,D),U=r.mul(I,P),U=r.add(U,U),D=r.mul(U,j),A=r.sub(A,D),C=r.mul(U,M),C=r.add(C,C),C=r.add(C,C),new d(A,O,C)}add(w){h(w);const{px:v,py:b,pz:E}=this,{px:I,py:P,pz:A}=w;let O=r.ZERO,C=r.ZERO,D=r.ZERO;const M=e.a,U=r.mul(e.b,Dc);let j=r.mul(v,I),q=r.mul(b,P),T=r.mul(E,A),g=r.add(v,b),m=r.add(I,P);g=r.mul(g,m),m=r.add(j,q),g=r.sub(g,m),m=r.add(v,E);let _=r.add(I,A);return m=r.mul(m,_),_=r.add(j,T),m=r.sub(m,_),_=r.add(b,E),O=r.add(P,A),_=r.mul(_,O),O=r.add(q,T),_=r.sub(_,O),D=r.mul(M,m),O=r.mul(U,T),D=r.add(O,D),O=r.sub(q,D),D=r.add(q,D),C=r.mul(O,D),q=r.add(j,j),q=r.add(q,j),T=r.mul(M,T),m=r.mul(U,m),q=r.add(q,T),T=r.sub(j,T),T=r.mul(M,T),m=r.add(m,T),j=r.mul(q,m),C=r.add(C,j),j=r.mul(_,m),O=r.mul(g,O),O=r.sub(O,j),j=r.mul(g,q),D=r.mul(_,D),D=r.add(D,j),new d(O,C,D)}subtract(w){return this.add(w.negate())}is0(){return this.equals(d.ZERO)}wNAF(w){return p.wNAFCached(this,w,d.normalizeZ)}multiplyUnsafe(w){const{endo:v,n:b}=e;Nt("scalar",w,Rt,b);const E=d.ZERO;if(w===Rt)return E;if(this.is0()||w===me)return this;if(!v||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,w,d.normalizeZ);let{k1neg:I,k1:P,k2neg:A,k2:O}=v.splitScalar(w),C=E,D=E,M=this;for(;P>Rt||O>Rt;)P&me&&(C=C.add(M)),O&me&&(D=D.add(M)),M=M.double(),P>>=me,O>>=me;return I&&(C=C.negate()),A&&(D=D.negate()),D=new d(r.mul(D.px,v.beta),D.py,D.pz),C.add(D)}multiply(w){const{endo:v,n:b}=e;Nt("scalar",w,me,b);let E,I;if(v){const{k1neg:P,k1:A,k2neg:O,k2:C}=v.splitScalar(w);let{p:D,f:M}=this.wNAF(A),{p:U,f:j}=this.wNAF(C);D=p.constTimeNegate(P,D),U=p.constTimeNegate(O,U),U=new d(r.mul(U.px,v.beta),U.py,U.pz),E=D.add(U),I=M.add(j)}else{const{p:P,f:A}=this.wNAF(w);E=P,I=A}return d.normalizeZ([E,I])[0]}multiplyAndAddUnsafe(w,v,b){const E=d.BASE,I=(A,O)=>O===Rt||O===me||!A.equals(E)?A.multiplyUnsafe(O):A.multiply(O),P=I(this,v).add(I(w,b));return P.is0()?void 0:P}toAffine(w){return l(this,w)}isTorsionFree(){const{h:w,isTorsionFree:v}=e;if(w===me)return!0;if(v)return v(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:w,clearCofactor:v}=e;return w===me?this:v?v(d,this):this.multiplyUnsafe(e.h)}toRawBytes(w=!0){return Yr("isCompressed",w),this.assertValidity(),s(d,this,w)}toHex(w=!0){return Yr("isCompressed",w),Jr(this.toRawBytes(w))}}d.BASE=new d(e.Gx,e.Gy,r.ONE),d.ZERO=new d(r.ZERO,r.ONE,r.ZERO);const f=e.nBitLength,p=Fv(d,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function Qv(t){const e=Pu(t);return ni(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Xv(t){const e=Qv(t),{Fp:r,n:i}=e,s=r.BYTES+1,n=2*r.BYTES+1;function o(T){return Le(T,i)}function a(T){return to(T,i)}const{ProjectivePoint:c,normPrivateKeyToScalar:h,weierstrassEquation:l,isWithinCurveOrder:u}=Zv({...e,toBytes(T,g,m){const _=g.toAffine(),S=r.toBytes(_.x),$=Ci;return Yr("isCompressed",m),m?$(Uint8Array.from([g.hasEvenY()?2:3]),S):$(Uint8Array.from([4]),S,r.toBytes(_.y))},fromBytes(T){const g=T.length,m=T[0],_=T.subarray(1);if(g===s&&(m===2||m===3)){const S=or(_);if(!Ls(S,me,r.ORDER))throw new Error("Point is not on curve");const $=l(S);let x;try{x=r.sqrt($)}catch(k){const z=k instanceof Error?": "+k.message:"";throw new Error("Point is not on curve"+z)}const F=(x&me)===me;return(m&1)===1!==F&&(x=r.neg(x)),{x:S,y:x}}else if(g===n&&m===4){const S=r.fromBytes(_.subarray(0,r.BYTES)),$=r.fromBytes(_.subarray(r.BYTES,2*r.BYTES));return{x:S,y:$}}else{const S=s,$=n;throw new Error("invalid Point, expected length of "+S+", or uncompressed "+$+", got "+g)}}}),d=T=>Jr(Qr(T,e.nByteLength));function f(T){const g=i>>me;return T>g}function p(T){return f(T)?o(-T):T}const y=(T,g,m)=>or(T.slice(g,m));class w{constructor(g,m,_){this.r=g,this.s=m,this.recovery=_,this.assertValidity()}static fromCompact(g){const m=e.nByteLength;return g=Ve("compactSignature",g,m*2),new w(y(g,0,m),y(g,m,2*m))}static fromDER(g){const{r:m,s:_}=Tt.toSig(Ve("DER",g));return new w(m,_)}assertValidity(){Nt("r",this.r,me,i),Nt("s",this.s,me,i)}addRecoveryBit(g){return new w(this.r,this.s,g)}recoverPublicKey(g){const{r:m,s:_,recovery:S}=this,$=A(Ve("msgHash",g));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");const x=S===2||S===3?m+e.n:m;if(x>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const F=S&1?"03":"02",k=c.fromHex(F+d(x)),z=a(x),L=o(-$*z),H=o(_*z),G=c.BASE.multiplyAndAddUnsafe(k,L,H);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Zr(this.toDERHex())}toDERHex(){return Tt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Zr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const v={isValidPrivateKey(T){try{return h(T),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const T=Du(e.n);return Bv(e.randomBytes(T),e.n)},precompute(T=8,g=c.BASE){return g._setWindowSize(T),g.multiply(BigInt(3)),g}};function b(T,g=!0){return c.fromPrivateKey(T).toRawBytes(g)}function E(T){const g=ur(T),m=typeof T=="string",_=(g||m)&&T.length;return g?_===s||_===n:m?_===2*s||_===2*n:T instanceof c}function I(T,g,m=!0){if(E(T))throw new Error("first arg must be private key");if(!E(g))throw new Error("second arg must be public key");return c.fromHex(g).multiply(h(T)).toRawBytes(m)}const P=e.bits2int||function(T){if(T.length>8192)throw new Error("input is too large");const g=or(T),m=T.length*8-e.nBitLength;return m>0?g>>BigInt(m):g},A=e.bits2int_modN||function(T){return o(P(T))},O=Mo(e.nBitLength);function C(T){return Nt("num < 2^"+e.nBitLength,T,Rt,O),Qr(T,e.nByteLength)}function D(T,g,m=M){if(["recovered","canonical"].some(ee=>ee in m))throw new Error("sign() legacy options not supported");const{hash:_,randomBytes:S}=e;let{lowS:$,prehash:x,extraEntropy:F}=m;$==null&&($=!0),T=Ve("msgHash",T),$c(m),x&&(T=Ve("prehashed msgHash",_(T)));const k=A(T),z=h(g),L=[C(z),C(k)];if(F!=null&&F!==!1){const ee=F===!0?S(r.BYTES):F;L.push(Ve("extraEntropy",ee))}const H=Ci(...L),G=k;function se(ee){const Y=P(ee);if(!u(Y))return;const Ae=a(Y),Ee=c.BASE.multiply(Y).toAffine(),Ce=o(Ee.x);if(Ce===Rt)return;const Ye=o(Ae*o(G+Ce*z));if(Ye===Rt)return;let Je=(Ee.x===Ce?0:2)|Number(Ee.y&me),br=Ye;return $&&f(Ye)&&(br=p(Ye),Je^=1),new w(Ce,br,Je)}return{seed:H,k2sig:se}}const M={lowS:e.lowS,prehash:!1},U={lowS:e.lowS,prehash:!1};function j(T,g,m=M){const{seed:_,k2sig:S}=D(T,g,m),$=e;return vu($.hash.outputLen,$.nByteLength,$.hmac)(_,S)}c.BASE._setWindowSize(8);function q(T,g,m,_=U){var Ye;const S=T;g=Ve("msgHash",g),m=Ve("publicKey",m);const{lowS:$,prehash:x,format:F}=_;if($c(_),"strict"in _)throw new Error("options.strict was renamed to lowS");if(F!==void 0&&F!=="compact"&&F!=="der")throw new Error("format must be compact or der");const k=typeof S=="string"||ur(S),z=!k&&!F&&typeof S=="object"&&S!==null&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!k&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let L,H;try{if(z&&(L=new w(S.r,S.s)),k){try{F!=="compact"&&(L=w.fromDER(S))}catch(Je){if(!(Je instanceof Tt.Err))throw Je}!L&&F!=="der"&&(L=w.fromCompact(S))}H=c.fromHex(m)}catch{return!1}if(!L||$&&L.hasHighS())return!1;x&&(g=e.hash(g));const{r:G,s:se}=L,ee=A(g),Y=a(se),Ae=o(ee*Y),Ee=o(G*Y),Ce=(Ye=c.BASE.multiplyAndAddUnsafe(H,Ae,Ee))==null?void 0:Ye.toAffine();return Ce?o(Ce.x)===G:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:I,sign:j,verify:q,ProjectivePoint:c,Signature:w,utils:v}}function e0(t){return{hash:t,hmac:(e,...r)=>Bs(t,e,sb(...r)),randomBytes:si}}function t0(t,e){const r=i=>Xv({...t,...e0(i)});return{...r(e),create:r}}const Au=Iu(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),r0=Au.create(BigInt("-3")),i0=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),s0=t0({a:r0,b:i0,Fp:Au,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Mi),xu="base10",Re="base16",lt="base64pad",qt="base64url",zi="utf8",Cu=0,Bt=1,Hi=2,n0=0,Sc=1,_i=12,qo=32;function o0(){const t=io.utils.randomPrivateKey(),e=io.getPublicKey(t);return{privateKey:ke(t,Re),publicKey:ke(e,Re)}}function so(){const t=si(qo);return ke(t,Re)}function a0(t,e){const r=io.getSharedSecret(tt(t,Re),tt(e,Re)),i=uv(Mi,r,void 0,void 0,qo);return ke(i,Re)}function ps(t){const e=Mi(tt(t,Re));return ke(e,Re)}function Et(t){const e=Mi(tt(t,zi));return ke(e,Re)}function Tu(t){return tt(`${t}`,xu)}function dr(t){return Number(ke(t,xu))}function Ru(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Nu(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function c0(t){const e=Tu(typeof t.type<"u"?t.type:Cu);if(dr(e)===Bt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?tt(t.senderPublicKey,Re):void 0,i=typeof t.iv<"u"?tt(t.iv,Re):si(_i),s=tt(t.symKey,Re),n=mu(s,i).encrypt(tt(t.message,zi)),o=Bu({type:e,sealed:n,iv:i,senderPublicKey:r});return t.encoding===qt?Ru(o):o}function h0(t){const e=tt(t.symKey,Re),{sealed:r,iv:i}=Ti({encoded:t.encoded,encoding:t.encoding}),s=mu(e,i).decrypt(r);if(s===null)throw new Error("Failed to decrypt");return ke(s,zi)}function l0(t,e){const r=Tu(Hi),i=si(_i),s=tt(t,zi),n=Bu({type:r,sealed:s,iv:i});return e===qt?Ru(n):n}function u0(t,e){const{sealed:r}=Ti({encoded:t,encoding:e});return ke(r,zi)}function Bu(t){if(dr(t.type)===Hi)return ke(Ei([t.type,t.sealed]),lt);if(dr(t.type)===Bt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return ke(Ei([t.type,t.senderPublicKey,t.iv,t.sealed]),lt)}return ke(Ei([t.type,t.iv,t.sealed]),lt)}function Ti(t){const e=(t.encoding||lt)===qt?Nu(t.encoded):t.encoded,r=tt(e,lt),i=r.slice(n0,Sc),s=Sc;if(dr(i)===Bt){const c=s+qo,h=c+_i,l=r.slice(s,c),u=r.slice(c,h),d=r.slice(h);return{type:i,sealed:d,iv:u,senderPublicKey:l}}if(dr(i)===Hi){const c=r.slice(s),h=si(_i);return{type:i,sealed:c,iv:h}}const n=s+_i,o=r.slice(s,n),a=r.slice(n);return{type:i,sealed:a,iv:o}}function d0(t,e){const r=Ti({encoded:t,encoding:e==null?void 0:e.encoding});return ju({type:dr(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?ke(r.senderPublicKey,Re):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function ju(t){const e=(t==null?void 0:t.type)||Cu;if(e===Bt){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 Oc(t){return t.type===Bt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Pc(t){return t.type===Hi}function p0(t){const e=Buffer.from(t.x,"base64"),r=Buffer.from(t.y,"base64");return Ei([new Uint8Array([4]),e,r])}function f0(t,e){const[r,i,s]=t.split("."),n=Buffer.from(Nu(s),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${r}.${i}`,h=Mi(c),l=p0(e);if(!s0.verify(Ei([o,a]),h,l))throw new Error("Invalid signature");return Kn(t).payload}const g0="irn";function Is(t){return(t==null?void 0:t.relay)||{protocol:g0}}function bi(t){const e=vw[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function y0(t,e="-"){const r={},i="relay"+e;return Object.keys(t).forEach(s=>{if(s.startsWith(i)){const n=s.replace(i,""),o=t[s];r[n]=o}}),r}function Ac(t){if(!t.includes("wc:")){const h=su(t);h!=null&&h.includes("wc:")&&(t=h)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,i=t.substring(0,e),s=t.substring(e+1,r).split("@"),n=typeof r<"u"?t.substring(r):"",o=new URLSearchParams(n),a={};o.forEach((h,l)=>{a[l]=h});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:m0(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:y0(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function m0(t){return t.startsWith("//")?t.substring(2):t}function w0(t,e="-"){const r="relay",i={};return Object.keys(t).forEach(s=>{const n=s,o=r+e+n;t[n]&&(i[o]=t[n])}),i}function xc(t){const e=new URLSearchParams,r=w0(t.relay);Object.keys(r).sort().forEach(s=>{e.set(s,r[s])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const i=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${i}`}function ts(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var b0=Object.defineProperty,v0=Object.defineProperties,E0=Object.getOwnPropertyDescriptors,Cc=Object.getOwnPropertySymbols,_0=Object.prototype.hasOwnProperty,I0=Object.prototype.propertyIsEnumerable,Tc=(t,e,r)=>e in t?b0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$0=(t,e)=>{for(var r in e||(e={}))_0.call(e,r)&&Tc(t,r,e[r]);if(Cc)for(var r of Cc(e))I0.call(e,r)&&Tc(t,r,e[r]);return t},D0=(t,e)=>v0(t,E0(e));function oi(t){const e=[];return t.forEach(r=>{const[i,s]=r.split(":");e.push(`${i}:${s}`)}),e}function S0(t){const e=[];return Object.values(t).forEach(r=>{e.push(...oi(r.accounts))}),e}function O0(t,e){const r=[];return Object.values(t).forEach(i=>{oi(i.accounts).includes(e)&&r.push(...i.methods)}),r}function P0(t,e){const r=[];return Object.values(t).forEach(i=>{oi(i.accounts).includes(e)&&r.push(...i.events)}),r}function ks(t){return t.includes(":")}function zr(t){return ks(t)?t.split(":")[0]:t}function Rc(t){var e,r,i;const s={};if(!Kt(t))return s;for(const[n,o]of Object.entries(t)){const a=ks(n)?[n]:o.chains,c=o.methods||[],h=o.events||[],l=zr(n);s[l]=D0($0({},s[l]),{chains:_t(a,(e=s[l])==null?void 0:e.chains),methods:_t(c,(r=s[l])==null?void 0:r.methods),events:_t(h,(i=s[l])==null?void 0:i.events)})}return s}function A0(t){const e={};return t==null||t.forEach(r=>{var i;const[s,n]=r.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(r),(i=e[s].chains)==null||i.push(`${s}:${n}`)}),e}function Nc(t,e){e=e.map(i=>i.replace("did:pkh:",""));const r=A0(e);for(const[i,s]of Object.entries(r))s.methods?s.methods=_t(s.methods,t):s.methods=t,s.events=["chainChanged","accountsChanged"];return r}function x0(t,e){var r,i,s,n,o,a;const c=Rc(t),h=Rc(e),l={},u=Object.keys(c).concat(Object.keys(h));for(const d of u)l[d]={chains:_t((r=c[d])==null?void 0:r.chains,(i=h[d])==null?void 0:i.chains),methods:_t((s=c[d])==null?void 0:s.methods,(n=h[d])==null?void 0:n.methods),events:_t((o=c[d])==null?void 0:o.events,(a=h[d])==null?void 0:a.events)};return l}const C0={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},T0={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function B(t,e){const{message:r,code:i}=T0[t];return{message:e?`${r} ${e}`:r,code:i}}function te(t,e){const{message:r,code:i}=C0[t];return{message:e?`${r} ${e}`:r,code:i}}function ut(t,e){return!!Array.isArray(t)}function Kt(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function De(t){return typeof t>"u"}function ue(t,e){return e&&De(t)?!0:typeof t=="string"&&!!t.trim().length}function zo(t,e){return e&&De(t)?!0:typeof t=="number"&&!isNaN(t)}function R0(t,e){const{requiredNamespaces:r}=e,i=Object.keys(t.namespaces),s=Object.keys(r);let n=!0;return sr(s,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:h}=t.namespaces[o],l=oi(a),u=r[o];(!sr(Xl(o,u),l)||!sr(u.methods,c)||!sr(u.events,h))&&(n=!1)}),n):!1}function $s(t){return ue(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function N0(t){if(ue(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&$s(r)}}return!1}function B0(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(ue(t,!1)){if(e(t))return!0;const r=su(t);return e(r)}}catch{}return!1}function j0(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function U0(t){return t==null?void 0:t.topic}function F0(t,e){let r=null;return ue(t==null?void 0:t.publicKey,!1)||(r=B("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function Bc(t){let e=!0;return ut(t)?t.length&&(e=t.every(r=>ue(r,!1))):e=!1,e}function L0(t,e,r){let i=null;return ut(e)&&e.length?e.forEach(s=>{i||$s(s)||(i=te("UNSUPPORTED_CHAINS",`${r}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):$s(t)||(i=te("UNSUPPORTED_CHAINS",`${r}, 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"] }`)),i}function k0(t,e,r){let i=null;return Object.entries(t).forEach(([s,n])=>{if(i)return;const o=L0(s,Xl(s,n),`${e} ${r}`);o&&(i=o)}),i}function M0(t,e){let r=null;return ut(t)?t.forEach(i=>{r||N0(i)||(r=te("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):r=te("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function q0(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const s=M0(i==null?void 0:i.accounts,`${e} namespace`);s&&(r=s)}),r}function z0(t,e){let r=null;return Bc(t==null?void 0:t.methods)?Bc(t==null?void 0:t.events)||(r=te("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=te("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function Uu(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const s=z0(i,`${e}, namespace`);s&&(r=s)}),r}function H0(t,e,r){let i=null;if(t&&Kt(t)){const s=Uu(t,e);s&&(i=s);const n=k0(t,e,r);n&&(i=n)}else i=B("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return i}function _n(t,e){let r=null;if(t&&Kt(t)){const i=Uu(t,e);i&&(r=i);const s=q0(t,e);s&&(r=s)}else r=B("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function Fu(t){return ue(t.protocol,!0)}function V0(t,e){let r=!1;return t?t&&ut(t)&&t.length&&t.forEach(i=>{r=Fu(i)}):r=!0,r}function K0(t){return typeof t=="number"}function Fe(t){return typeof t<"u"&&typeof t!==null}function W0(t){return!(!t||typeof t!="object"||!t.code||!zo(t.code,!1)||!t.message||!ue(t.message,!1))}function G0(t){return!(De(t)||!ue(t.method,!1))}function Y0(t){return!(De(t)||De(t.result)&&De(t.error)||!zo(t.id,!1)||!ue(t.jsonrpc,!1))}function J0(t){return!(De(t)||!ue(t.name,!1))}function jc(t,e){return!(!$s(e)||!S0(t).includes(e))}function Z0(t,e,r){return ue(r,!1)?O0(t,e).includes(r):!1}function Q0(t,e,r){return ue(r,!1)?P0(t,e).includes(r):!1}function Uc(t,e,r){let i=null;const s=X0(t),n=e1(e),o=Object.keys(s),a=Object.keys(n),c=Fc(Object.keys(t)),h=Fc(Object.keys(e)),l=c.filter(u=>!h.includes(u));return l.length&&(i=B("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
@@ -23,4 +23,4 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(gb(r)).toStr
23
23
  Approved: ${a.toString()}`)),Object.keys(e).forEach(u=>{if(!u.includes(":")||i)return;const d=oi(e[u].accounts);d.includes(u)||(i=B("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${u}
24
24
  Required: ${u}
25
25
  Approved: ${d.toString()}`))}),o.forEach(u=>{i||(sr(s[u].methods,n[u].methods)?sr(s[u].events,n[u].events)||(i=B("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${u}`)):i=B("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${u}`))}),i}function X0(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(s=>{e[s]={methods:t[r].methods,events:t[r].events}})}),e}function Fc(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function e1(t){const e={};return Object.keys(t).forEach(r=>{if(r.includes(":"))e[r]=t[r];else{const i=oi(t[r].accounts);i==null||i.forEach(s=>{e[s]={accounts:t[r].accounts.filter(n=>n.includes(`${s}:`)),methods:t[r].methods,events:t[r].events}})}}),e}function t1(t,e){return zo(t,!1)&&t<=e.max&&t>=e.min}function Lc(){const t=Li();return new Promise(e=>{switch(t){case We.browser:e(r1());break;case We.reactNative:e(i1());break;case We.node:e(s1());break;default:e(!0)}})}function r1(){return ii()&&(navigator==null?void 0:navigator.onLine)}async function i1(){if(Wt()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function s1(){return!0}function n1(t){switch(Li()){case We.browser:o1(t);break;case We.reactNative:a1(t);break}}function o1(t){!Wt()&&ii()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function a1(t){Wt()&&typeof global<"u"&&global!=null&&global.NetInfo&&(global==null||global.NetInfo.addEventListener(e=>t(e==null?void 0:e.isConnected)))}function c1(){var t;return ii()&&ar()?((t=ar())==null?void 0:t.visibilityState)==="visible":!0}const In={};class pi{static get(e){return In[e]}static set(e,r){In[e]=r}static delete(e){delete In[e]}}class gr{}let h1=class extends gr{constructor(e){super()}};const kc=N.FIVE_SECONDS,yr={pulse:"heartbeat_pulse"};let l1=class Lu extends h1{constructor(e){super(e),this.events=new rt.EventEmitter,this.interval=kc,this.interval=(e==null?void 0:e.interval)||kc}static async init(e){const r=new Lu(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),N.toMiliseconds(this.interval))}pulse(){this.events.emit(yr.pulse)}};const u1=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,d1=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,p1=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function f1(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){g1(t);return}return e}function g1(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function rs(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const r=t.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!p1.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(u1.test(t)||d1.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,f1)}return JSON.parse(t)}catch(i){if(e.strict)throw i;return t}}function y1(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function ye(t,...e){try{return y1(t(...e))}catch(r){return Promise.reject(r)}}function m1(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function w1(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function fs(t){if(m1(t))return String(t);if(w1(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return fs(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const no="base64:";function b1(t){return typeof t=="string"?t:no+_1(t)}function v1(t){return typeof t!="string"||!t.startsWith(no)?t:E1(t.slice(no.length))}function E1(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function _1(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Ue(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function I1(...t){return Ue(t.join(":"))}function is(t){return t=Ue(t),t?t+":":""}function $1(t,e){if(e===void 0)return!0;let r=0,i=t.indexOf(":");for(;i>-1;)r++,i=t.indexOf(":",i+1);return r<=e}function D1(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const S1="memory",O1=()=>{const t=new Map;return{name:S1,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function P1(t={}){const e={mounts:{"":t.driver||O1()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=h=>{for(const l of e.mountpoints)if(h.startsWith(l))return{base:l,relativeKey:h.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:h,driver:e.mounts[""]}},i=(h,l)=>e.mountpoints.filter(u=>u.startsWith(h)||l&&h.startsWith(u)).map(u=>({relativeBase:h.length>u.length?h.slice(u.length):void 0,mountpoint:u,driver:e.mounts[u]})),s=(h,l)=>{if(e.watching){l=Ue(l);for(const u of e.watchListeners)u(h,l)}},n=async()=>{if(!e.watching){e.watching=!0;for(const h in e.mounts)e.unwatch[h]=await Mc(e.mounts[h],s,h)}},o=async()=>{if(e.watching){for(const h in e.unwatch)await e.unwatch[h]();e.unwatch={},e.watching=!1}},a=(h,l,u)=>{const d=new Map,f=p=>{let y=d.get(p.base);return y||(y={driver:p.driver,base:p.base,items:[]},d.set(p.base,y)),y};for(const p of h){const y=typeof p=="string",w=Ue(y?p:p.key),v=y?void 0:p.value,b=y||!p.options?l:{...l,...p.options},E=r(w);f(E).items.push({key:w,value:v,relativeKey:E.relativeKey,options:b})}return Promise.all([...d.values()].map(p=>u(p))).then(p=>p.flat())},c={hasItem(h,l={}){h=Ue(h);const{relativeKey:u,driver:d}=r(h);return ye(d.hasItem,u,l)},getItem(h,l={}){h=Ue(h);const{relativeKey:u,driver:d}=r(h);return ye(d.getItem,u,l).then(f=>rs(f))},getItems(h,l={}){return a(h,l,u=>u.driver.getItems?ye(u.driver.getItems,u.items.map(d=>({key:d.relativeKey,options:d.options})),l).then(d=>d.map(f=>({key:I1(u.base,f.key),value:rs(f.value)}))):Promise.all(u.items.map(d=>ye(u.driver.getItem,d.relativeKey,d.options).then(f=>({key:d.key,value:rs(f)})))))},getItemRaw(h,l={}){h=Ue(h);const{relativeKey:u,driver:d}=r(h);return d.getItemRaw?ye(d.getItemRaw,u,l):ye(d.getItem,u,l).then(f=>v1(f))},async setItem(h,l,u={}){if(l===void 0)return c.removeItem(h);h=Ue(h);const{relativeKey:d,driver:f}=r(h);f.setItem&&(await ye(f.setItem,d,fs(l),u),f.watch||s("update",h))},async setItems(h,l){await a(h,l,async u=>{if(u.driver.setItems)return ye(u.driver.setItems,u.items.map(d=>({key:d.relativeKey,value:fs(d.value),options:d.options})),l);u.driver.setItem&&await Promise.all(u.items.map(d=>ye(u.driver.setItem,d.relativeKey,fs(d.value),d.options)))})},async setItemRaw(h,l,u={}){if(l===void 0)return c.removeItem(h,u);h=Ue(h);const{relativeKey:d,driver:f}=r(h);if(f.setItemRaw)await ye(f.setItemRaw,d,l,u);else if(f.setItem)await ye(f.setItem,d,b1(l),u);else return;f.watch||s("update",h)},async removeItem(h,l={}){typeof l=="boolean"&&(l={removeMeta:l}),h=Ue(h);const{relativeKey:u,driver:d}=r(h);d.removeItem&&(await ye(d.removeItem,u,l),(l.removeMeta||l.removeMata)&&await ye(d.removeItem,u+"$",l),d.watch||s("remove",h))},async getMeta(h,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),h=Ue(h);const{relativeKey:u,driver:d}=r(h),f=Object.create(null);if(d.getMeta&&Object.assign(f,await ye(d.getMeta,u,l)),!l.nativeOnly){const p=await ye(d.getItem,u+"$",l).then(y=>rs(y));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(f,p))}return f},setMeta(h,l,u={}){return this.setItem(h+"$",l,u)},removeMeta(h,l={}){return this.removeItem(h+"$",l)},async getKeys(h,l={}){var w;h=is(h);const u=i(h,!0);let d=[];const f=[];let p=!0;for(const v of u){(w=v.driver.flags)!=null&&w.maxDepth||(p=!1);const b=await ye(v.driver.getKeys,v.relativeBase,l);for(const E of b){const I=v.mountpoint+Ue(E);d.some(P=>I.startsWith(P))||f.push(I)}d=[v.mountpoint,...d.filter(E=>!E.startsWith(v.mountpoint))]}const y=l.maxDepth!==void 0&&!p;return f.filter(v=>(!y||$1(v,l.maxDepth))&&D1(v,h))},async clear(h,l={}){h=is(h),await Promise.all(i(h,!1).map(async u=>{if(u.driver.clear)return ye(u.driver.clear,u.relativeBase,l);if(u.driver.removeItem){const d=await u.driver.getKeys(u.relativeBase||"",l);return Promise.all(d.map(f=>u.driver.removeItem(f,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(h=>qc(h)))},async watch(h){return await n(),e.watchListeners.push(h),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==h),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(h,l){if(h=is(h),h&&e.mounts[h])throw new Error(`already mounted at ${h}`);return h&&(e.mountpoints.push(h),e.mountpoints.sort((u,d)=>d.length-u.length)),e.mounts[h]=l,e.watching&&Promise.resolve(Mc(l,s,h)).then(u=>{e.unwatch[h]=u}).catch(console.error),c},async unmount(h,l=!0){var u,d;h=is(h),!(!h||!e.mounts[h])&&(e.watching&&h in e.unwatch&&((d=(u=e.unwatch)[h])==null||d.call(u),delete e.unwatch[h]),l&&await qc(e.mounts[h]),e.mountpoints=e.mountpoints.filter(f=>f!==h),delete e.mounts[h])},getMount(h=""){h=Ue(h)+":";const l=r(h);return{driver:l.driver,base:l.base}},getMounts(h="",l={}){return h=Ue(h),i(h,l.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(h,l={})=>c.getKeys(h,l),get:(h,l={})=>c.getItem(h,l),set:(h,l,u={})=>c.setItem(h,l,u),has:(h,l={})=>c.hasItem(h,l),del:(h,l={})=>c.removeItem(h,l),remove:(h,l={})=>c.removeItem(h,l)};return c}function Mc(t,e,r){return t.watch?t.watch((i,s)=>e(i,r+s)):()=>{}}async function qc(t){typeof t.dispose=="function"&&await ye(t.dispose)}const A1="idb-keyval";var x1=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=s=>e+s;let i;return t.dbName&&t.storeName&&(i=rl(t.dbName,t.storeName)),{name:A1,options:t,async hasItem(s){return!(typeof await ia(r(s),i)>"u")},async getItem(s){return await ia(r(s),i)??null},setItem(s,n){return Ud(r(s),n,i)},removeItem(s){return Fd(r(s),i)},getKeys(){return Md(i)},clear(){return Ld(i)}}};const C1="WALLET_CONNECT_V2_INDEXED_DB",T1="keyvaluestorage";let R1=class{constructor(){this.indexedDb=P1({driver:x1({dbName:C1,storeName:T1})})}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 r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,jt(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var $n=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},gs={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,i){this[r]=String(i)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(i){r[i]=void 0,delete r[i]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof $n<"u"&&$n.localStorage?gs.exports=$n.localStorage:typeof window<"u"&&window.localStorage?gs.exports=window.localStorage:gs.exports=new e})();function N1(t){var e;return[t[0],hr((e=t[1])!=null?e:"")]}let B1=class{constructor(){this.localStorage=gs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(N1)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return hr(r)}async setItem(e,r){this.localStorage.setItem(e,jt(r))}async removeItem(e){this.localStorage.removeItem(e)}};const j1="wc_storage_version",zc=1,U1=async(t,e,r)=>{const i=j1,s=await e.getItem(i);if(s&&s>=zc){r(e);return}const n=await t.getKeys();if(!n.length){r(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const h=await t.getItem(a);await e.setItem(a,h),o.push(a)}}await e.setItem(i,zc),r(e),F1(t,o)},F1=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let L1=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new B1;this.storage=e;try{const r=new R1;U1(e,r,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,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}};function k1(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var M1=q1;function q1(t,e,r){var i=r&&r.stringify||k1,s=1;if(typeof t=="object"&&t!==null){var n=e.length+s;if(n===1)return t;var o=new Array(n);o[0]=i(t);for(var a=1;a<n;a++)o[a]=i(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var h="",l=1-s,u=-1,d=t&&t.length||0,f=0;f<d;){if(t.charCodeAt(f)===37&&f+1<d){switch(u=u>-1?u:0,t.charCodeAt(f+1)){case 100:case 102:if(l>=c||e[l]==null)break;u<f&&(h+=t.slice(u,f)),h+=Number(e[l]),u=f+2,f++;break;case 105:if(l>=c||e[l]==null)break;u<f&&(h+=t.slice(u,f)),h+=Math.floor(Number(e[l])),u=f+2,f++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;u<f&&(h+=t.slice(u,f));var p=typeof e[l];if(p==="string"){h+="'"+e[l]+"'",u=f+2,f++;break}if(p==="function"){h+=e[l].name||"<anonymous>",u=f+2,f++;break}h+=i(e[l]),u=f+2,f++;break;case 115:if(l>=c)break;u<f&&(h+=t.slice(u,f)),h+=String(e[l]),u=f+2,f++;break;case 37:u<f&&(h+=t.slice(u,f)),h+="%",u=f+2,f++,l--;break}++l}++f}return u===-1?t:(u<d&&(h+=t.slice(u)),h)}const Hc=M1;var kr=It;const Ri=Q1().console||{},z1={mapHttpRequest:ss,mapHttpResponse:ss,wrapRequestSerializer:Dn,wrapResponseSerializer:Dn,wrapErrorSerializer:Dn,req:ss,res:ss,err:G1};function H1(t,e){return Array.isArray(t)?t.filter(function(i){return i!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function It(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const r=t.browser.write||Ri;t.browser.write&&(t.browser.asObject=!0);const i=t.serializers||{},s=H1(t.browser.serialize,i);let n=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(r);c.log||(c.log=Ni),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:u,set:d});const h={transmit:e,serialize:s,asObject:t.browser.asObject,levels:o,timestamp:Y1(t)};c.levels=It.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=Ni,c.serializers=i,c._serialize=s,c._stdErrSerialize=n,c.child=f,e&&(c._logEvent=oo());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function u(){return this._level}function d(p){if(p!=="silent"&&!this.levels.values[p])throw Error("unknown level "+p);this._level=p,Dr(h,c,"error","log"),Dr(h,c,"fatal","error"),Dr(h,c,"warn","error"),Dr(h,c,"info","log"),Dr(h,c,"debug","log"),Dr(h,c,"trace","log")}function f(p,y){if(!p)throw new Error("missing bindings for child Pino");y=y||{},s&&p.serializers&&(y.serializers=p.serializers);const w=y.serializers;if(s&&w){var v=Object.assign({},i,w),b=t.browser.serialize===!0?Object.keys(v):s;delete p.serializers,Ms([p],b,v,this._stdErrSerialize)}function E(I){this._childLevel=(I._childLevel|0)+1,this.error=Sr(I,p,"error"),this.fatal=Sr(I,p,"fatal"),this.warn=Sr(I,p,"warn"),this.info=Sr(I,p,"info"),this.debug=Sr(I,p,"debug"),this.trace=Sr(I,p,"trace"),v&&(this.serializers=v,this._serialize=b),e&&(this._logEvent=oo([].concat(I._logEvent.bindings,p)))}return E.prototype=this,new E(this)}return c}It.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"}};It.stdSerializers=z1;It.stdTimeFunctions=Object.assign({},{nullTime:ku,epochTime:Mu,unixTime:J1,isoTime:Z1});function Dr(t,e,r,i){const s=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?Ni:s[r]?s[r]:Ri[r]||Ri[i]||Ni,V1(t,e,r)}function V1(t,e,r){!t.transmit&&e[r]===Ni||(e[r]=function(i){return function(){const n=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Ri?Ri:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&Ms(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?i.call(a,K1(this,r,o,n)):i.apply(a,o),t.transmit){const h=t.transmit.level||e.level,l=It.levels.values[h],u=It.levels.values[r];if(u<l)return;W1(this,{ts:n,methodLevel:r,methodValue:u,transmitValue:It.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[r]))}function K1(t,e,r,i){t._serialize&&Ms(r,t._serialize,t.serializers,t._stdErrSerialize);const s=r.slice();let n=s[0];const o={};i&&(o.time=i),o.level=It.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),n!==null&&typeof n=="object"){for(;a--&&typeof s[0]=="object";)Object.assign(o,s.shift());n=s.length?Hc(s.shift(),s):void 0}else typeof n=="string"&&(n=Hc(s.shift(),s));return n!==void 0&&(o.msg=n),o}function Ms(t,e,r,i){for(const s in t)if(i&&t[s]instanceof Error)t[s]=It.stdSerializers.err(t[s]);else if(typeof t[s]=="object"&&!Array.isArray(t[s]))for(const n in t[s])e&&e.indexOf(n)>-1&&n in r&&(t[s][n]=r[n](t[s][n]))}function Sr(t,e,r){return function(){const i=new Array(1+arguments.length);i[0]=e;for(var s=1;s<i.length;s++)i[s]=arguments[s-1];return t[r].apply(this,i)}}function W1(t,e,r){const i=e.send,s=e.ts,n=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;Ms(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=s,t._logEvent.messages=r.filter(function(h){return c.indexOf(h)===-1}),t._logEvent.level.label=n,t._logEvent.level.value=o,i(n,t._logEvent,a),t._logEvent=oo(c)}function oo(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function G1(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function Y1(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?ku:Mu}function ss(){return{}}function Dn(t){return t}function Ni(){}function ku(){return!1}function Mu(){return Date.now()}function J1(){return Math.round(Date.now()/1e3)}function Z1(){return new Date(Date.now()).toISOString()}function Q1(){function t(e){return typeof e<"u"&&e}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 t(self)||t(window)||t(this)||{}}}const Vi=tl(kr),X1={level:"info"},Ki="custom_context",Ho=1e3*1024;let eE=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Vc=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new eE(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.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 r=this.head;for(;r!==null;)e.push(r.value),r=r.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 r=e.value;return e=e.next,{done:!1,value:r}}}}},qu=class{constructor(e,r=Ho){this.level=e??"error",this.levelValue=kr.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new Vc(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===kr.levels.values.error?console.error(e):r===kr.levels.values.warn?console.warn(e):r===kr.levels.values.debug?console.debug(e):r===kr.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(jt({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new Vc(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(jt({extraMetadata:e})),new Blob(r,{type:"application/json"})}},tE=class{constructor(e,r=Ho){this.baseChunkLogger=new qu(e,r)}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 r=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=r,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}},rE=class{constructor(e,r=Ho){this.baseChunkLogger=new qu(e,r)}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 iE=Object.defineProperty,sE=Object.defineProperties,nE=Object.getOwnPropertyDescriptors,Kc=Object.getOwnPropertySymbols,oE=Object.prototype.hasOwnProperty,aE=Object.prototype.propertyIsEnumerable,Wc=(t,e,r)=>e in t?iE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ds=(t,e)=>{for(var r in e||(e={}))oE.call(e,r)&&Wc(t,r,e[r]);if(Kc)for(var r of Kc(e))aE.call(e,r)&&Wc(t,r,e[r]);return t},Ss=(t,e)=>sE(t,nE(e));function qs(t){return Ss(Ds({},t),{level:(t==null?void 0:t.level)||X1.level})}function cE(t,e=Ki){return t[e]||""}function hE(t,e,r=Ki){return t[r]=e,t}function Me(t,e=Ki){let r="";return typeof t.bindings>"u"?r=cE(t,e):r=t.bindings().context||"",r}function lE(t,e,r=Ki){const i=Me(t,r);return i.trim()?`${i}/${e}`:e}function Ne(t,e,r=Ki){const i=lE(t,e,r),s=t.child({context:i});return hE(s,i,r)}function uE(t){var e,r;const i=new tE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Vi(Ss(Ds({},t.opts),{level:"trace",browser:Ss(Ds({},(r=t.opts)==null?void 0:r.browser),{write:s=>i.write(s)})})),chunkLoggerController:i}}function dE(t){var e;const r=new rE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Vi(Ss(Ds({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function pE(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?uE(t):dE(t)}var fE=Object.defineProperty,gE=(t,e,r)=>e in t?fE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gc=(t,e,r)=>gE(t,typeof e!="symbol"?e+"":e,r);let yE=class extends gr{constructor(e){super(),this.opts=e,Gc(this,"protocol","wc"),Gc(this,"version",2)}};var mE=Object.defineProperty,wE=(t,e,r)=>e in t?mE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bE=(t,e,r)=>wE(t,e+"",r);let vE=class extends gr{constructor(e,r){super(),this.core=e,this.logger=r,bE(this,"records",new Map)}},EE=class{constructor(e,r){this.logger=e,this.core=r}};class _E extends gr{constructor(e,r){super(),this.relayer=e,this.logger=r}}let IE=class extends gr{constructor(e){super()}},$E=class{constructor(e,r,i,s){this.core=e,this.logger=r,this.name=i}},DE=class extends gr{constructor(e,r){super(),this.relayer=e,this.logger=r}},SE=class extends gr{constructor(e,r){super(),this.core=e,this.logger=r}},OE=class{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}},PE=class{constructor(e,r){this.projectId=e,this.logger=r}},AE=class{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}};var xE=Object.defineProperty,CE=(t,e,r)=>e in t?xE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yc=(t,e,r)=>CE(t,typeof e!="symbol"?e+"":e,r);let TE=class{constructor(e){this.opts=e,Yc(this,"protocol","wc"),Yc(this,"version",2)}},RE=class{constructor(e){this.client=e}};const NE="PARSE_ERROR",BE="INVALID_REQUEST",jE="METHOD_NOT_FOUND",UE="INVALID_PARAMS",zu="INTERNAL_ERROR",Vo="SERVER_ERROR",FE=[-32700,-32600,-32601,-32602,-32603],Ii={[NE]:{code:-32700,message:"Parse error"},[BE]:{code:-32600,message:"Invalid Request"},[jE]:{code:-32601,message:"Method not found"},[UE]:{code:-32602,message:"Invalid params"},[zu]:{code:-32603,message:"Internal error"},[Vo]:{code:-32e3,message:"Server error"}},Hu=Vo;function LE(t){return FE.includes(t)}function Jc(t){return Object.keys(Ii).includes(t)?Ii[t]:Ii[Hu]}function kE(t){const e=Object.values(Ii).find(r=>r.code===t);return e||Ii[Hu]}function Vu(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Ku={},At={},Zc;function ME(){if(Zc)return At;Zc=1,Object.defineProperty(At,"__esModule",{value:!0}),At.isBrowserCryptoAvailable=At.getSubtleCrypto=At.getBrowerCrypto=void 0;function t(){return(vt===null||vt===void 0?void 0:vt.crypto)||(vt===null||vt===void 0?void 0:vt.msCrypto)||{}}At.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}At.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return At.isBrowserCryptoAvailable=r,At}var xt={},Qc;function qE(){if(Qc)return xt;Qc=1,Object.defineProperty(xt,"__esModule",{value:!0}),xt.isBrowser=xt.isNode=xt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}xt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}xt.isNode=e;function r(){return!t()&&!e()}return xt.isBrowser=r,xt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ji;e.__exportStar(ME(),t),e.__exportStar(qE(),t)})(Ku);function wt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function nr(t=6){return BigInt(wt(t))}function Ht(t,e,r){return{id:r||wt(),jsonrpc:"2.0",method:t,params:e}}function zs(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Hs(t,e,r){return{id:t,jsonrpc:"2.0",error:zE(e)}}function zE(t,e){return typeof t>"u"?Jc(zu):(typeof t=="string"&&(t=Object.assign(Object.assign({},Jc(Vo)),{message:t})),LE(t.code)&&(t=kE(t.code)),t)}class HE{}class VE extends HE{constructor(){super()}}class KE extends VE{constructor(e){super()}}const WE="^https?:",GE="^wss?:";function YE(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Wu(t,e){const r=YE(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Xc(t){return Wu(t,WE)}function eh(t){return Wu(t,GE)}function JE(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Gu(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Ko(t){return Gu(t)&&"method"in t}function Vs(t){return Gu(t)&&(bt(t)||et(t))}function bt(t){return"result"in t}function et(t){return"error"in t}let it=class extends KE{constructor(e){super(e),this.events=new rt.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Ht(e.method,e.params||[],e.id||nr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{et(n)?s(n.error):i(n.result)});try{await this.connection.send(e,r)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Vs(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const ZE=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),QE=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",th=t=>t.split("?")[0],rh=10,XE=ZE();let e_=class{constructor(e){if(this.url=e,this.events=new rt.EventEmitter,this.registering=!1,!eh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(jt(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!eh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const s=Ku.isReactNative()?void 0:{rejectUnauthorized:!JE(e)},n=new XE(e,[],s);QE()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),r(n)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?hr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=Hs(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return Vu(e,th(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>rh&&this.events.setMaxListeners(rh)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${th(this.url)}`));return this.events.emit("register_error",r),r}};var t_={};const Yu="wc",Ju=2,ao="core",$t=`${Yu}@2:${ao}:`,r_={logger:"error"},i_={database:":memory:"},s_="crypto",ih="client_ed25519_seed",n_=N.ONE_DAY,o_="keychain",a_="0.3",c_="messages",h_="0.3",sh=N.SIX_HOURS,l_="publisher",Zu="irn",u_="error",Qu="wss://relay.walletconnect.org",d_="relayer",we={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"},p_="_subscription",Ze={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},f_=.1,co="2.21.1",ae={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},g_="0.3",y_="WALLETCONNECT_CLIENT_ID",nh="WALLETCONNECT_LINK_MODE_APPS",He={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},m_="subscription",w_="0.3",b_="pairing",v_="0.3",fi={wc_pairingDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:N.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:N.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:N.ONE_DAY,prompt:!1,tag:0},res:{ttl:N.ONE_DAY,prompt:!1,tag:0}}},rr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},E_="history",__="0.3",I_="expirer",Xe={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},$_="0.3",D_="verify-api",S_="https://verify.walletconnect.com",Xu="https://verify.walletconnect.org",$i=Xu,O_=`${$i}/v3`,P_=[S_,Xu],A_="echo",x_="https://echo.walletconnect.com",mt={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"},Ct={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"},at={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"},Jt={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"},Zt={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"},gi={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"},C_=.1,T_="event-client",R_=86400,N_="https://pulse.walletconnect.org/batch";function B_(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var y=0,w=0,v=0,b=p.length;v!==b&&p[v]===0;)v++,y++;for(var E=(b-v)*l+1>>>0,I=new Uint8Array(E);v!==b;){for(var P=p[v],A=0,O=E-1;(P!==0||A<w)&&O!==-1;O--,A++)P+=256*I[O]>>>0,I[O]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");w=A,v++}for(var C=E-w;C!==E&&I[C]===0;)C++;for(var D=c.repeat(y);C<E;++C)D+=t.charAt(I[C]);return D}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var y=0;if(p[y]!==" "){for(var w=0,v=0;p[y]===c;)w++,y++;for(var b=(p.length-y)*h+1>>>0,E=new Uint8Array(b);p[y];){var I=r[p.charCodeAt(y)];if(I===255)return;for(var P=0,A=b-1;(I!==0||P<v)&&A!==-1;A--,P++)I+=a*E[A]>>>0,E[A]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");v=P,y++}if(p[y]!==" "){for(var O=b-v;O!==b&&E[O]===0;)O++;for(var C=new Uint8Array(w+(b-O)),D=w;O!==b;)C[D++]=E[O++];return C}}}function f(p){var y=d(p);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:u,decodeUnsafe:d,decode:f}}var j_=B_,U_=j_;const ed=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")},F_=t=>new TextEncoder().encode(t),L_=t=>new TextDecoder().decode(t);class k_{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class M_{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}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 td(this,e)}}class q_{constructor(e){this.decoders=e}or(e){return td(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const td=(t,e)=>new q_({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class z_{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new k_(e,r,i),this.decoder=new M_(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ks=({name:t,prefix:e,encode:r,decode:i})=>new z_(t,e,r,i),Wi=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=U_(r,e);return Ks({prefix:t,name:e,encode:i,decode:n=>ed(s(n))})},H_=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,h=0;for(let l=0;l<n;++l){const u=s[t[l]];if(u===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|u,a+=r,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},V_=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Pe=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ks({prefix:e,name:t,encode(s){return V_(s,i,r)},decode(s){return H_(s,i,r,t)}}),K_=Ks({prefix:"\0",name:"identity",encode:t=>L_(t),decode:t=>F_(t)});var W_=Object.freeze({__proto__:null,identity:K_});const G_=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Y_=Object.freeze({__proto__:null,base2:G_});const J_=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Z_=Object.freeze({__proto__:null,base8:J_});const Q_=Wi({prefix:"9",name:"base10",alphabet:"0123456789"});var X_=Object.freeze({__proto__:null,base10:Q_});const eI=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),tI=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rI=Object.freeze({__proto__:null,base16:eI,base16upper:tI});const iI=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),sI=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),nI=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),oI=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),aI=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),cI=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),hI=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lI=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),uI=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var dI=Object.freeze({__proto__:null,base32:iI,base32upper:sI,base32pad:nI,base32padupper:oI,base32hex:aI,base32hexupper:cI,base32hexpad:hI,base32hexpadupper:lI,base32z:uI});const pI=Wi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),fI=Wi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gI=Object.freeze({__proto__:null,base36:pI,base36upper:fI});const yI=Wi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mI=Wi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var wI=Object.freeze({__proto__:null,base58btc:yI,base58flickr:mI});const bI=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),vI=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),EI=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_I=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var II=Object.freeze({__proto__:null,base64:bI,base64pad:vI,base64url:EI,base64urlpad:_I});const rd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),$I=rd.reduce((t,e,r)=>(t[r]=e,t),[]),DI=rd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function SI(t){return t.reduce((e,r)=>(e+=$I[r],e),"")}function OI(t){const e=[];for(const r of t){const i=DI[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const PI=Ks({prefix:"🚀",name:"base256emoji",encode:SI,decode:OI});var AI=Object.freeze({__proto__:null,base256emoji:PI}),xI=id,oh=128,CI=-128,TI=Math.pow(2,31);function id(t,e,r){e=e||[],r=r||0;for(var i=r;t>=TI;)e[r++]=t&255|oh,t/=128;for(;t&CI;)e[r++]=t&255|oh,t>>>=7;return e[r]=t|0,id.bytes=r-i+1,e}var RI=ho,NI=128,ah=127;function ho(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw ho.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&ah)<<s:(o&ah)*Math.pow(2,s),s+=7}while(o>=NI);return ho.bytes=n-i,r}var BI=Math.pow(2,7),jI=Math.pow(2,14),UI=Math.pow(2,21),FI=Math.pow(2,28),LI=Math.pow(2,35),kI=Math.pow(2,42),MI=Math.pow(2,49),qI=Math.pow(2,56),zI=Math.pow(2,63),HI=function(t){return t<BI?1:t<jI?2:t<UI?3:t<FI?4:t<LI?5:t<kI?6:t<MI?7:t<qI?8:t<zI?9:10},VI={encode:xI,decode:RI,encodingLength:HI},sd=VI;const ch=(t,e,r=0)=>(sd.encode(t,e,r),e),hh=t=>sd.encodingLength(t),lo=(t,e)=>{const r=e.byteLength,i=hh(t),s=i+hh(r),n=new Uint8Array(s+r);return ch(t,n,0),ch(r,n,i),n.set(e,s),new KI(t,r,e,n)};class KI{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}}const nd=({name:t,code:e,encode:r})=>new WI(t,e,r);class WI{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?lo(this.code,r):r.then(i=>lo(this.code,i))}else throw Error("Unknown type, must be binary type")}}const od=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),GI=nd({name:"sha2-256",code:18,encode:od("SHA-256")}),YI=nd({name:"sha2-512",code:19,encode:od("SHA-512")});var JI=Object.freeze({__proto__:null,sha256:GI,sha512:YI});const ad=0,ZI="identity",cd=ed,QI=t=>lo(ad,cd(t)),XI={code:ad,name:ZI,encode:cd,digest:QI};var e2=Object.freeze({__proto__:null,identity:XI});new TextEncoder,new TextDecoder;const lh={...W_,...Y_,...Z_,...X_,...rI,...dI,...gI,...wI,...II,...AI};({...JI,...e2});function t2(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function hd(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const uh=hd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Sn=hd("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=t2(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),r2={utf8:uh,"utf-8":uh,hex:lh.base16,latin1:Sn,ascii:Sn,binary:Sn,...lh};function i2(t,e="utf8"){const r=r2[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var s2=Object.defineProperty,n2=(t,e,r)=>e in t?s2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gt=(t,e,r)=>n2(t,typeof e!="symbol"?e+"":e,r);class o2{constructor(e,r){this.core=e,this.logger=r,gt(this,"keychain",new Map),gt(this,"name",o_),gt(this,"version",a_),gt(this,"initialized",!1),gt(this,"storagePrefix",$t),gt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),gt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),gt(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),gt(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=B("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),gt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=Ne(r,this.name)}get context(){return Me(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Wn(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Gn(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=B("NOT_INITIALIZED",this.name);throw new Error(e)}}}var a2=Object.defineProperty,c2=(t,e,r)=>e in t?a2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ie=(t,e,r)=>c2(t,typeof e!="symbol"?e+"":e,r);class h2{constructor(e,r,i){this.core=e,this.logger=r,Ie(this,"name",s_),Ie(this,"keychain"),Ie(this,"randomSessionIdentifier",so()),Ie(this,"initialized",!1),Ie(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ie(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Ie(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=Ha(s);return Wl(n.publicKey)}),Ie(this,"generateKeyPair",()=>{this.isInitialized();const s=o0();return this.setPrivateKey(s.publicKey,s.privateKey)}),Ie(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=Ha(n),a=this.randomSessionIdentifier;return await Im(a,s,n_,o)}),Ie(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=a0(a,n);return this.setSymKey(c,o)}),Ie(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||ps(s);return await this.keychain.set(o,s),o}),Ie(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ie(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ie(this,"encode",async(s,n,o)=>{this.isInitialized();const a=ju(o),c=jt(n);if(Pc(a))return l0(c,o==null?void 0:o.encoding);if(Oc(a)){const d=a.senderPublicKey,f=a.receiverPublicKey;s=await this.generateSharedKey(d,f)}const h=this.getSymKey(s),{type:l,senderPublicKey:u}=a;return c0({type:l,symKey:h,message:c,senderPublicKey:u,encoding:o==null?void 0:o.encoding})}),Ie(this,"decode",async(s,n,o)=>{this.isInitialized();const a=d0(n,o);if(Pc(a)){const c=u0(n,o==null?void 0:o.encoding);return hr(c)}if(Oc(a)){const c=a.receiverPublicKey,h=a.senderPublicKey;s=await this.generateSharedKey(c,h)}try{const c=this.getSymKey(s),h=h0({symKey:c,encoded:n,encoding:o==null?void 0:o.encoding});return hr(h)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ie(this,"getPayloadType",(s,n=lt)=>{const o=Ti({encoded:s,encoding:n});return dr(o.type)}),Ie(this,"getPayloadSenderPublicKey",(s,n=lt)=>{const o=Ti({encoded:s,encoding:n});return o.senderPublicKey?ke(o.senderPublicKey,Re):void 0}),this.core=e,this.logger=Ne(r,this.name),this.keychain=i||new o2(this.core,this.logger)}get context(){return Me(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ih)}catch{e=so(),await this.keychain.set(ih,e)}return i2(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=B("NOT_INITIALIZED",this.name);throw new Error(e)}}}var l2=Object.defineProperty,u2=Object.defineProperties,d2=Object.getOwnPropertyDescriptors,dh=Object.getOwnPropertySymbols,p2=Object.prototype.hasOwnProperty,f2=Object.prototype.propertyIsEnumerable,uo=(t,e,r)=>e in t?l2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,g2=(t,e)=>{for(var r in e||(e={}))p2.call(e,r)&&uo(t,r,e[r]);if(dh)for(var r of dh(e))f2.call(e,r)&&uo(t,r,e[r]);return t},y2=(t,e)=>u2(t,d2(e)),qe=(t,e,r)=>uo(t,typeof e!="symbol"?e+"":e,r);class m2 extends EE{constructor(e,r){super(e,r),this.logger=e,this.core=r,qe(this,"messages",new Map),qe(this,"messagesWithoutClientAck",new Map),qe(this,"name",c_),qe(this,"version",h_),qe(this,"initialized",!1),qe(this,"storagePrefix",$t),qe(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),qe(this,"set",async(i,s,n)=>{this.isInitialized();const o=Et(s);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(i,a),n===ys.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,y2(g2({},c),{[o]:s}))}return await this.persist(),o}),qe(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),qe(this,"getWithoutAck",i=>{this.isInitialized();const s={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),qe(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=Et(s);return typeof n[o]<"u"}),qe(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=Et(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),qe(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=Ne(e,this.name),this.core=r}get context(){return Me(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,Wn(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Wn(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Gn(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Gn(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=B("NOT_INITIALIZED",this.name);throw new Error(e)}}}var w2=Object.defineProperty,b2=Object.defineProperties,v2=Object.getOwnPropertyDescriptors,ph=Object.getOwnPropertySymbols,E2=Object.prototype.hasOwnProperty,_2=Object.prototype.propertyIsEnumerable,po=(t,e,r)=>e in t?w2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ns=(t,e)=>{for(var r in e||(e={}))E2.call(e,r)&&po(t,r,e[r]);if(ph)for(var r of ph(e))_2.call(e,r)&&po(t,r,e[r]);return t},On=(t,e)=>b2(t,v2(e)),ct=(t,e,r)=>po(t,typeof e!="symbol"?e+"":e,r);class I2 extends _E{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ct(this,"events",new rt.EventEmitter),ct(this,"name",l_),ct(this,"queue",new Map),ct(this,"publishTimeout",N.toMiliseconds(N.ONE_MINUTE)),ct(this,"initialPublishTimeout",N.toMiliseconds(N.ONE_SECOND*15)),ct(this,"needsTransportRestart",!1),ct(this,"publish",async(i,s,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const a=(n==null?void 0:n.ttl)||sh,c=Is(n),h=(n==null?void 0:n.prompt)||!1,l=(n==null?void 0:n.tag)||0,u=(n==null?void 0:n.id)||nr().toString(),d={topic:i,message:s,opts:{ttl:a,relay:c,prompt:h,tag:l,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}},f=`Failed to publish payload, please try again. id:${u} tag:${l}`;try{const p=new Promise(async y=>{const w=({id:b})=>{d.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(we.publish,w),y(d))};this.relayer.events.on(we.publish,w);const v=zt(new Promise((b,E)=>{this.rpcPublish({topic:i,message:s,ttl:a,prompt:h,tag:l,id:u,attestation:n==null?void 0:n.attestation,tvf:n==null?void 0:n.tvf}).then(b).catch(I=>{this.logger.warn(I,I==null?void 0:I.message),E(I)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${u} tag:${l}`);try{await v,this.events.removeListener(we.publish,w)}catch(b){this.queue.set(u,On(ns({},d),{attempt:1})),this.logger.warn(b,b==null?void 0:b.message)}});this.logger.trace({type:"method",method:"publish",params:{id:u,topic:i,message:s,opts:n}}),await zt(p,this.publishTimeout,f)}catch(p){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(p),(o=n==null?void 0:n.internal)!=null&&o.throwOnFailedPublish)throw p}finally{this.queue.delete(u)}}),ct(this,"on",(i,s)=>{this.events.on(i,s)}),ct(this,"once",(i,s)=>{this.events.once(i,s)}),ct(this,"off",(i,s)=>{this.events.off(i,s)}),ct(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=Ne(r,this.name),this.registerEventListeners()}get context(){return Me(this.logger)}async rpcPublish(e){var r,i,s,n;const{topic:o,message:a,ttl:c=sh,prompt:h,tag:l,id:u,attestation:d,tvf:f}=e,p={method:bi(Is().protocol).publish,params:ns({topic:o,message:a,ttl:c,prompt:h,tag:l,attestation:d},f),id:u};De((r=p.params)==null?void 0:r.prompt)&&((i=p.params)==null||delete i.prompt),De((s=p.params)==null?void 0:s.tag)&&((n=p.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:p});const y=await this.relayer.request(p);return this.relayer.events.emit(we.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const i=e.attempt+1;this.queue.set(r,On(ns({},e),{attempt:i}));const{topic:s,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${i}`),await this.rpcPublish(On(ns({},e),{topic:s,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(yr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(we.connection_stalled);return}this.checkQueue()}),this.relayer.on(we.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var $2=Object.defineProperty,D2=(t,e,r)=>e in t?$2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Or=(t,e,r)=>D2(t,typeof e!="symbol"?e+"":e,r);class S2{constructor(){Or(this,"map",new Map),Or(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),Or(this,"get",e=>this.map.get(e)||[]),Or(this,"exists",(e,r)=>this.get(e).includes(r)),Or(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const s=i.filter(n=>n!==r);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),Or(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var O2=Object.defineProperty,P2=Object.defineProperties,A2=Object.getOwnPropertyDescriptors,fh=Object.getOwnPropertySymbols,x2=Object.prototype.hasOwnProperty,C2=Object.prototype.propertyIsEnumerable,fo=(t,e,r)=>e in t?O2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yi=(t,e)=>{for(var r in e||(e={}))x2.call(e,r)&&fo(t,r,e[r]);if(fh)for(var r of fh(e))C2.call(e,r)&&fo(t,r,e[r]);return t},Pn=(t,e)=>P2(t,A2(e)),re=(t,e,r)=>fo(t,typeof e!="symbol"?e+"":e,r);class T2 extends DE{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,re(this,"subscriptions",new Map),re(this,"topicMap",new S2),re(this,"events",new rt.EventEmitter),re(this,"name",m_),re(this,"version",w_),re(this,"pending",new Map),re(this,"cached",[]),re(this,"initialized",!1),re(this,"storagePrefix",$t),re(this,"subscribeTimeout",N.toMiliseconds(N.ONE_MINUTE)),re(this,"initialSubscribeTimeout",N.toMiliseconds(N.ONE_SECOND*15)),re(this,"clientId"),re(this,"batchSubscribeTopicsLimit",500),re(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),re(this,"subscribe",async(i,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const n=Is(s),o={topic:i,relay:n,transportType:s==null?void 0:s.transportType};this.pending.set(i,o);const a=await this.rpcSubscribe(i,n,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),re(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof(s==null?void 0:s.id)<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),re(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),re(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),re(this,"on",(i,s)=>{this.events.on(i,s)}),re(this,"once",(i,s)=>{this.events.once(i,s)}),re(this,"off",(i,s)=>{this.events.off(i,s)}),re(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),re(this,"start",async()=>{await this.onConnect()}),re(this,"stop",async()=>{await this.onDisconnect()}),re(this,"restart",async()=>{await this.restore(),await this.onRestart()}),re(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(s=>{i.push(s)}),await this.batchSubscribe(i)}),re(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(yr.pulse,async()=>{await this.checkPending()}),this.events.on(He.created,async i=>{const s=He.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(He.deleted,async i=>{const s=He.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=Ne(r,this.name),this.clientId=""}get context(){return Me(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,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async s=>await this.unsubscribeById(e,s,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const s=Is(i);await this.restartToComplete({topic:e,id:r,relay:s}),await this.rpcUnsubscribe(e,r,s);const n=te("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,r,i){var s;(!i||(i==null?void 0:i.transportType)===ae.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const n={method:bi(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if((i==null?void 0:i.transportType)===ae.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(l=>this.logger.warn(l))},N.toMiliseconds(N.ONE_SECOND)),a;const c=new Promise(async l=>{const u=d=>{d.topic===e&&(this.events.removeListener(He.created,u),l(d.id))};this.events.on(He.created,u);try{const d=await zt(new Promise((f,p)=>{this.relayer.request(n).catch(y=>{this.logger.warn(y,y==null?void 0:y.message),p(y)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(He.created,u),l(d)}catch{}}),h=await zt(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return h?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(we.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,i={method:bi(r.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await zt(new Promise(s=>{this.relayer.request(i).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(we.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:bi(r.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let s;try{s=await await zt(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(we.connection_stalled)}return s}rpcUnsubscribe(e,r,i){const s={method:bi(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,r){this.setSubscription(e,Pn(yi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,yi({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),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,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,yi({},r)),this.topicMap.set(r.topic,e),this.events.emit(He.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=B("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(He.deleted,Pn(yi({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(He.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(He.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=B("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}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 r=>Pn(yi({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await Ww(N.toMiliseconds(N.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=B("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 Et(e+await this.getClientId())}}var R2=Object.defineProperty,gh=Object.getOwnPropertySymbols,N2=Object.prototype.hasOwnProperty,B2=Object.prototype.propertyIsEnumerable,go=(t,e,r)=>e in t?R2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yh=(t,e)=>{for(var r in e||(e={}))N2.call(e,r)&&go(t,r,e[r]);if(gh)for(var r of gh(e))B2.call(e,r)&&go(t,r,e[r]);return t},Z=(t,e,r)=>go(t,typeof e!="symbol"?e+"":e,r);class j2 extends IE{constructor(e){super(e),Z(this,"protocol","wc"),Z(this,"version",2),Z(this,"core"),Z(this,"logger"),Z(this,"events",new rt.EventEmitter),Z(this,"provider"),Z(this,"messages"),Z(this,"subscriber"),Z(this,"publisher"),Z(this,"name",d_),Z(this,"transportExplicitlyClosed",!1),Z(this,"initialized",!1),Z(this,"connectionAttemptInProgress",!1),Z(this,"relayUrl"),Z(this,"projectId"),Z(this,"packageName"),Z(this,"bundleId"),Z(this,"hasExperiencedNetworkDisruption",!1),Z(this,"pingTimeout"),Z(this,"heartBeatTimeout",N.toMiliseconds(N.THIRTY_SECONDS+N.FIVE_SECONDS)),Z(this,"reconnectTimeout"),Z(this,"connectPromise"),Z(this,"reconnectInProgress",!1),Z(this,"requestsInFlight",[]),Z(this,"connectTimeout",N.toMiliseconds(N.ONE_SECOND*15)),Z(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const n=r.id||nr().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const o=`${n}:${((s=r.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),Z(this,"resetPingTimeout",()=>{Es()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||n.call(s)}catch(o){this.logger.warn(o,o==null?void 0:o.message)}},this.heartBeatTimeout))}),Z(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),Z(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(we.connect)}),Z(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),Z(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(we.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),Z(this,"registerProviderListeners",()=>{this.provider.on(Ze.payload,this.onPayloadHandler),this.provider.on(Ze.connect,this.onConnectHandler),this.provider.on(Ze.disconnect,this.onDisconnectHandler),this.provider.on(Ze.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ne(e.logger,this.name):Vi(qs({level:e.logger||u_})),this.messages=new m2(this.logger,e.core),this.subscriber=new T2(this,this.logger),this.publisher=new I2(this,this.logger),this.relayUrl=(e==null?void 0:e.relayUrl)||Qu,this.projectId=e.projectId,Cw()?this.packageName=Za():Tw()&&(this.bundleId=Za()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e==null?void 0:e.message)}}get context(){return Me(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:ae.relay},ys.outbound)}async subscribe(e,r){var i,s,n;this.isInitialized(),(!(r!=null&&r.transportType)||(r==null?void 0:r.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=r==null?void 0:r.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const h=l=>{l.topic===e&&(this.subscriber.off(He.created,h),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(He.created,h)}),new Promise(async(l,u)=>{a=await this.subscriber.subscribe(e,yh({internal:{throwOnFailedPublish:o}},r)).catch(d=>{o&&u(d)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await zt(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.warn("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(r,i)=>{await this.connect(e).then(r).catch(i).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 Lc())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 r=e.sort((i,s)=>i.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+(s==null?void 0:s.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const s=de(N.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(we.message,e),await this.recordMessageEvent(e,ys.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ze.disconnect,n),await zt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(Ze.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ze.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Ze.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const s=i;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,N.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,s,n;if(Es())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null||n.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 it(new e_(Uw({sdkVersion:co,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,r){const{topic:i,message:s}=e;await this.messages.set(i,s,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const s=this.messages.has(r,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Ko(e)){if(!e.method.endsWith(p_))return;const r=e.params,{topic:i,message:s,publishedAt:n,attestation:o}=r.data,a={topic:i,message:s,publishedAt:n,transportType:ae.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(yh({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Vs(e)&&this.events.emit(we.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ys.inbound),this.events.emit(we.message,e))}async acknowledgePayload(e){const r=zs(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(Ze.payload,this.onPayloadHandler),this.provider.off(Ze.connect,this.onConnectHandler),this.provider.off(Ze.disconnect,this.onDisconnectHandler),this.provider.off(Ze.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Lc();n1(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(yr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&c1())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r==null?void 0:r.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(we.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},N.toMiliseconds(f_)))))}isInitialized(){if(!this.initialized){const{message:e}=B("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 U2(){}function mh(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 wh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function bh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const F2="[object RegExp]",L2="[object String]",k2="[object Number]",M2="[object Boolean]",vh="[object Arguments]",q2="[object Symbol]",z2="[object Date]",H2="[object Map]",V2="[object Set]",K2="[object Array]",W2="[object Function]",G2="[object ArrayBuffer]",An="[object Object]",Y2="[object Error]",J2="[object DataView]",Z2="[object Uint8Array]",Q2="[object Uint8ClampedArray]",X2="[object Uint16Array]",e$="[object Uint32Array]",t$="[object BigUint64Array]",r$="[object Int8Array]",i$="[object Int16Array]",s$="[object Int32Array]",n$="[object BigInt64Array]",o$="[object Float32Array]",a$="[object Float64Array]";function c$(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function h$(t,e,r){return vi(t,e,void 0,void 0,void 0,void 0,r)}function vi(t,e,r,i,s,n,o){const a=o(t,e,r,i,s,n);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 Di(t,e,n,o)}return Di(t,e,n,o)}function Di(t,e,r,i){if(Object.is(t,e))return!0;let s=bh(t),n=bh(e);if(s===vh&&(s=An),n===vh&&(n=An),s!==n)return!1;switch(s){case L2:return t.toString()===e.toString();case k2:{const c=t.valueOf(),h=e.valueOf();return c$(c,h)}case M2:case z2:case q2:return Object.is(t.valueOf(),e.valueOf());case F2:return t.source===e.source&&t.flags===e.flags;case W2:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(s){case H2:{if(t.size!==e.size)return!1;for(const[c,h]of t.entries())if(!e.has(c)||!vi(h,e.get(c),c,t,e,r,i))return!1;return!0}case V2:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),h=Array.from(e.values());for(let l=0;l<c.length;l++){const u=c[l],d=h.findIndex(f=>vi(u,f,void 0,t,e,r,i));if(d===-1)return!1;h.splice(d,1)}return!0}case K2:case Z2:case Q2:case X2:case e$:case t$:case r$:case i$:case s$:case n$:case o$:case a$:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!vi(t[c],e[c],c,t,e,r,i))return!1;return!0}case G2:return t.byteLength!==e.byteLength?!1:Di(new Uint8Array(t),new Uint8Array(e),r,i);case J2:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Di(new Uint8Array(t),new Uint8Array(e),r,i);case Y2:return t.name===e.name&&t.message===e.message;case An:{if(!(Di(t.constructor,e.constructor,r,i)||mh(t)&&mh(e)))return!1;const c=[...Object.keys(t),...wh(t)],h=[...Object.keys(e),...wh(e)];if(c.length!==h.length)return!1;for(let l=0;l<c.length;l++){const u=c[l],d=t[u];if(!Object.hasOwn(e,u))return!1;const f=e[u];if(!vi(d,f,u,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function l$(t,e){return h$(t,e,U2)}var u$=Object.defineProperty,Eh=Object.getOwnPropertySymbols,d$=Object.prototype.hasOwnProperty,p$=Object.prototype.propertyIsEnumerable,yo=(t,e,r)=>e in t?u$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_h=(t,e)=>{for(var r in e||(e={}))d$.call(e,r)&&yo(t,r,e[r]);if(Eh)for(var r of Eh(e))p$.call(e,r)&&yo(t,r,e[r]);return t},je=(t,e,r)=>yo(t,typeof e!="symbol"?e+"":e,r);class mr extends $E{constructor(e,r,i,s=$t,n=void 0){super(e,r,i,s),this.core=e,this.logger=r,this.name=i,je(this,"map",new Map),je(this,"version",g_),je(this,"cached",[]),je(this,"initialized",!1),je(this,"getKey"),je(this,"storagePrefix",$t),je(this,"recentlyDeleted",[]),je(this,"recentlyDeletedLimit",200),je(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!De(o)?this.map.set(this.getKey(o),o):j0(o)?this.map.set(o.id,o):U0(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),je(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())}),je(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),je(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>l$(a[c],o[c]))):this.values)),je(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=_h(_h({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),je(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=Ne(r,this.name),this.storagePrefix=s,this.getKey=n}get context(){return Me(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 r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:s}=B("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:i}=B("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}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:r}=B("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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}=B("NOT_INITIALIZED",this.name);throw new Error(e)}}}var f$=Object.defineProperty,g$=(t,e,r)=>e in t?f$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,K=(t,e,r)=>g$(t,typeof e!="symbol"?e+"":e,r);class y${constructor(e,r){this.core=e,this.logger=r,K(this,"name",b_),K(this,"version",v_),K(this,"events",new Do),K(this,"pairings"),K(this,"initialized",!1),K(this,"storagePrefix",$t),K(this,"ignoredPayloadTypes",[Bt]),K(this,"registeredMethods",[]),K(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),K(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),K(this,"create",async i=>{this.isInitialized();const s=so(),n=await this.core.crypto.setSymKey(s),o=de(N.FIVE_MINUTES),a={protocol:Zu},c={topic:n,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},h=xc({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(rr.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i==null?void 0:i.transportType}),{topic:n,uri:h}}),K(this,"pair",async i=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[mt.pairing_started]}});this.isValidPair(i,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:h}=Ac(i.uri);s.props.properties.topic=n,s.addTrace(mt.pairing_uri_validation_success),s.addTrace(mt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),s.addTrace(mt.existing_pairing),l.active)throw s.setError(Ct.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(mt.pairing_not_expired)}const u=c||de(N.FIVE_MINUTES),d={topic:n,relay:a,expiry:u,active:!1,methods:h};this.core.expirer.set(n,u),await this.pairings.set(n,d),s.addTrace(mt.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(rr.create,d),s.addTrace(mt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(mt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(Ct.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(f){throw s.setError(Ct.subscribe_pairing_topic_failure),f}return s.addTrace(mt.subscribe_pairing_topic_success),d}),K(this,"activate",async({topic:i})=>{this.isInitialized();const s=de(N.FIVE_MINUTES);this.core.expirer.set(i,s),await this.pairings.update(i,{active:!0,expiry:s})}),K(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=i;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Qt();this.events.once(X("pairing_ping",n),({error:h})=>{h?c(h):a()}),await o()}}),K(this,"updateExpiry",async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})}),K(this,"updateMetadata",async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})}),K(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),K(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:s}=i;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",te("USER_DISCONNECTED")),await this.deletePairing(s))}),K(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(s);return xc({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),K(this,"sendRequest",async(i,s,n)=>{const o=Ht(s,n),a=await this.core.crypto.encode(i,o),c=fi[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),K(this,"sendResult",async(i,s,n)=>{const o=zs(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,h=fi[c].res;await this.core.relayer.publish(s,a,h),await this.core.history.resolve(o)}),K(this,"sendError",async(i,s,n)=>{const o=Hs(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,h=fi[c]?fi[c].res:fi.unregistered_method.res;await this.core.relayer.publish(s,a,h),await this.core.history.resolve(o)}),K(this,"deletePairing",async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])}),K(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(s=>Mt(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))}),K(this,"onRelayEventRequest",async i=>{const{topic:s,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),K(this,"onRelayEventResponse",async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),K(this,"onPairingPingRequest",async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(rr.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),K(this,"onPairingPingResponse",(i,s)=>{const{id:n}=s;setTimeout(()=>{bt(s)?this.events.emit(X("pairing_ping",n),{}):et(s)&&this.events.emit(X("pairing_ping",n),{error:s.error})},500)}),K(this,"onPairingDeleteRequest",async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(rr.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),K(this,"onUnknownRpcMethodRequest",async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=te("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),K(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(te("WC_METHOD_UNSUPPORTED",i))}),K(this,"isValidPair",(i,s)=>{var n;if(!Fe(i)){const{message:a}=B("MISSING_OR_INVALID",`pair() params: ${i}`);throw s.setError(Ct.malformed_pairing_uri),new Error(a)}if(!B0(i.uri)){const{message:a}=B("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw s.setError(Ct.malformed_pairing_uri),new Error(a)}const o=Ac(i==null?void 0:i.uri);if(!((n=o==null?void 0:o.relay)!=null&&n.protocol)){const{message:a}=B("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(Ct.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=B("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(Ct.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&N.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){s.setError(Ct.pairing_expired);const{message:a}=B("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),K(this,"isValidPing",async i=>{if(!Fe(i)){const{message:n}=B("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),K(this,"isValidDisconnect",async i=>{if(!Fe(i)){const{message:n}=B("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),K(this,"isValidPairingTopic",async i=>{if(!ue(i,!1)){const{message:s}=B("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=B("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(Mt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=B("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}}),this.core=e,this.logger=Ne(r,this.name),this.pairings=new mr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Me(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=B("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(we.message,async e=>{const{topic:r,message:i,transportType:s}=e;if(this.pairings.keys.includes(r)&&s!==ae.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(r,i);Ko(n)?(this.core.history.set(r,n),await this.onRelayEventRequest({topic:r,payload:n})):Vs(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:r,payload:n}),this.core.history.delete(r,n.id)),await this.core.relayer.messages.ack(r,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(Xe.expired,async e=>{const{topic:r}=iu(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(rr.expire,{topic:r}))})}}var m$=Object.defineProperty,w$=(t,e,r)=>e in t?m$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$e=(t,e,r)=>w$(t,typeof e!="symbol"?e+"":e,r);class b$ extends vE{constructor(e,r){super(e,r),this.core=e,this.logger=r,$e(this,"records",new Map),$e(this,"events",new rt.EventEmitter),$e(this,"name",E_),$e(this,"version",__),$e(this,"cached",[]),$e(this,"initialized",!1),$e(this,"storagePrefix",$t),$e(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),$e(this,"set",(i,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:i,request:{method:s.method,params:s.params||null},chainId:n,expiry:de(N.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ot.created,o)}),$e(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const s=await this.getRecord(i.id);typeof s.response>"u"&&(s.response=et(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.persist(),this.events.emit(ot.updated,s))}),$e(this,"get",async(i,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:s}),await this.getRecord(s))),$e(this,"delete",(i,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===i){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(ot.deleted,n)}}),this.persist()}),$e(this,"exists",async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1)),$e(this,"on",(i,s)=>{this.events.on(i,s)}),$e(this,"once",(i,s)=>{this.events.once(i,s)}),$e(this,"off",(i,s)=>{this.events.off(i,s)}),$e(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Ne(r,this.name)}get context(){return Me(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(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Ht(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),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 r=this.records.get(e);if(!r){const{message:i}=B("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=B("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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(ot.created,e=>{const r=ot.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ot.updated,e=>{const r=ot.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ot.deleted,e=>{const r=ot.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(yr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{N.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(ot.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=B("NOT_INITIALIZED",this.name);throw new Error(e)}}}var v$=Object.defineProperty,E$=(t,e,r)=>e in t?v$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xe=(t,e,r)=>E$(t,typeof e!="symbol"?e+"":e,r);class _$ extends SE{constructor(e,r){super(e,r),this.core=e,this.logger=r,xe(this,"expirations",new Map),xe(this,"events",new rt.EventEmitter),xe(this,"name",I_),xe(this,"version",$_),xe(this,"cached",[]),xe(this,"initialized",!1),xe(this,"storagePrefix",$t),xe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),xe(this,"has",i=>{try{const s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}}),xe(this,"set",(i,s)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(Xe.created,{target:n,expiration:o})}),xe(this,"get",i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)}),xe(this,"del",i=>{if(this.isInitialized(),this.has(i)){const s=this.formatTarget(i),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(Xe.deleted,{target:s,expiration:n})}}),xe(this,"on",(i,s)=>{this.events.on(i,s)}),xe(this,"once",(i,s)=>{this.events.once(i,s)}),xe(this,"off",(i,s)=>{this.events.off(i,s)}),xe(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=Ne(r,this.name)}get context(){return Me(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 Fw(e);if(typeof e=="number")return Lw(e);const{message:r}=B("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}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(Xe.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=B("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 r=this.expirations.get(e);if(!r){const{message:i}=B("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;N.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(Xe.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(yr.pulse,()=>this.checkExpirations()),this.events.on(Xe.created,e=>{const r=Xe.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xe.expired,e=>{const r=Xe.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(Xe.deleted,e=>{const r=Xe.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=B("NOT_INITIALIZED",this.name);throw new Error(e)}}}var I$=Object.defineProperty,$$=(t,e,r)=>e in t?I$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,le=(t,e,r)=>$$(t,typeof e!="symbol"?e+"":e,r);class D$ extends OE{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,le(this,"name",D_),le(this,"abortController"),le(this,"isDevEnv"),le(this,"verifyUrlV3",O_),le(this,"storagePrefix",$t),le(this,"version",Ju),le(this,"publicKey"),le(this,"fetchPromise"),le(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&N.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),le(this,"register",async s=>{if(!ii()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const h=ar(),l=this.startAbortTimer(N.ONE_SECOND*5),u=await new Promise((d,f)=>{const p=()=>{window.removeEventListener("message",w),h.body.removeChild(y),f("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const y=h.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",p,{signal:this.abortController.signal});const w=v=>{if(v.data&&typeof v.data=="string")try{const b=JSON.parse(v.data);if(b.type==="verify_attestation"){if(Kn(b.attestation).payload.id!==o)return;clearInterval(l),h.body.removeChild(y),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),d(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};h.body.appendChild(y),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",u),u}catch(h){this.logger.warn(h)}return""}),le(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=s;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(Kn(n).payload.id!==a)return;const h=await this.isValidJwtAttestation(n);if(h){if(!h.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return h}}if(!o)return;const c=this.getVerifyUrl(s==null?void 0:s.verifyUrl);return this.fetchAttestation(o,c)}),le(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(N.ONE_SECOND*5),a=await fetch(`${n}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),le(this,"getVerifyUrl",s=>{let n=s||$i;return P_.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${$i}`),n=$i),n}),le(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(N.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await n.json()}catch(s){this.logger.warn(s)}}),le(this,"persistPublicKey",async s=>{this.logger.debug("persisting public key to local storage",s),await this.store.setItem(this.storeKey,s),this.publicKey=s}),le(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),le(this,"isValidJwtAttestation",async s=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(s,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),le(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),le(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),le(this,"validateAttestation",(s,n)=>{const o=f0(s,n.publicKey),a={hasExpired:N.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=Ne(r,this.name),this.abortController=new AbortController,this.isDevEnv=jo(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Me(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),N.toMiliseconds(e))}}var S$=Object.defineProperty,O$=(t,e,r)=>e in t?S$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ih=(t,e,r)=>O$(t,typeof e!="symbol"?e+"":e,r);class P$ extends PE{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Ih(this,"context",A_),Ih(this,"registerDeviceToken",async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${x_}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:a})})}),this.logger=Ne(r,this.context)}}var A$=Object.defineProperty,$h=Object.getOwnPropertySymbols,x$=Object.prototype.hasOwnProperty,C$=Object.prototype.propertyIsEnumerable,mo=(t,e,r)=>e in t?A$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,mi=(t,e)=>{for(var r in e||(e={}))x$.call(e,r)&&mo(t,r,e[r]);if($h)for(var r of $h(e))C$.call(e,r)&&mo(t,r,e[r]);return t},fe=(t,e,r)=>mo(t,typeof e!="symbol"?e+"":e,r);class T$ extends AE{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,fe(this,"context",T_),fe(this,"storagePrefix",$t),fe(this,"storageVersion",C_),fe(this,"events",new Map),fe(this,"shouldPersist",!1),fe(this,"init",async()=>{if(!jo())try{const s={eventId:Xa(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:tu(this.core.relayer.protocol,this.core.relayer.version,co)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),fe(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,h=Xa(),l=this.core.projectId||"",u=Date.now(),d=mi({eventId:h,timestamp:u,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(h));return this.telemetryEnabled&&(this.events.set(h,d),this.shouldPersist=!0),d}),fe(this,"getEvent",s=>{const{eventId:n,topic:o}=s;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return mi(mi({},a),this.setMethods(a.eventId))}),fe(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),fe(this,"setEventListeners",()=>{this.core.heartbeat.on(yr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{N.fromMiliseconds(Date.now())-N.fromMiliseconds(s.timestamp)>R_&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),fe(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),fe(this,"addTrace",(s,n)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(n),this.events.set(s,o),this.shouldPersist=!0)}),fe(this,"setError",(s,n)=>{const o=this.events.get(s);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),fe(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),fe(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(n=>{this.events.set(n.eventId,mi(mi({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),fe(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[n,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const n of s)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),fe(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${N_}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${co}${n}`,{method:"POST",body:JSON.stringify(s)})}),fe(this,"getAppDomain",()=>eu().url),this.logger=Ne(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var R$=Object.defineProperty,Dh=Object.getOwnPropertySymbols,N$=Object.prototype.hasOwnProperty,B$=Object.prototype.propertyIsEnumerable,wo=(t,e,r)=>e in t?R$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Sh=(t,e)=>{for(var r in e||(e={}))N$.call(e,r)&&wo(t,r,e[r]);if(Dh)for(var r of Dh(e))B$.call(e,r)&&wo(t,r,e[r]);return t},ne=(t,e,r)=>wo(t,typeof e!="symbol"?e+"":e,r);let j$=class ld extends yE{constructor(e){var r;super(e),ne(this,"protocol",Yu),ne(this,"version",Ju),ne(this,"name",ao),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"customStoragePrefix"),ne(this,"events",new rt.EventEmitter),ne(this,"logger"),ne(this,"heartbeat"),ne(this,"relayer"),ne(this,"crypto"),ne(this,"storage"),ne(this,"history"),ne(this,"expirer"),ne(this,"pairing"),ne(this,"verify"),ne(this,"echoClient"),ne(this,"linkModeSupportedApps"),ne(this,"eventClient"),ne(this,"initialized",!1),ne(this,"logChunkController"),ne(this,"on",(a,c)=>this.events.on(a,c)),ne(this,"once",(a,c)=>this.events.once(a,c)),ne(this,"off",(a,c)=>this.events.off(a,c)),ne(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ne(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:h})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ae.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:h})});const i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}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)||Qu,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=qs({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:r_.logger,name:ao}),{logger:n,chunkLoggerController:o}=pE({opts:s,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.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=Ne(n,this.name),this.heartbeat=new l1,this.crypto=new h2(this,this.logger,e==null?void 0:e.keychain),this.history=new b$(this,this.logger),this.expirer=new _$(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new L1(Sh(Sh({},i_),e==null?void 0:e.storageOptions)),this.relayer=new j2({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new y$(this,this.logger),this.verify=new D$(this,this.logger,this.storage),this.echoClient=new P$(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new T$(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new ld(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(y_,i),r}get context(){return Me(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(nh,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(nh)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${e}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&t_.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const U$=j$,ud="wc",dd=2,pd="client",Wo=`${ud}@${dd}:${pd}:`,xn={name:pd,logger:"error"},Oh="WALLETCONNECT_DEEPLINK_CHOICE",F$="proposal",Ph="Proposal expired",L$="session",Pr=N.SEVEN_DAYS,k$="engine",ge={wc_sessionPropose:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1104},res:{ttl:N.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1106},res:{ttl:N.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:N.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1112},res:{ttl:N.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:N.ONE_DAY,prompt:!1,tag:1114},res:{ttl:N.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:N.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:N.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:N.FIVE_MINUTES,prompt:!1,tag:1119}}},Cn={min:N.FIVE_MINUTES,max:N.SEVEN_DAYS},yt={idle:"IDLE",active:"ACTIVE"},Ah={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},M$="request",q$=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],z$="wc",H$="auth",V$="authKeys",K$="pairingTopics",W$="requests",Ws=`${z$}@${1.5}:${H$}:`,ms=`${Ws}:PUB_KEY`;var G$=Object.defineProperty,Y$=Object.defineProperties,J$=Object.getOwnPropertyDescriptors,xh=Object.getOwnPropertySymbols,Z$=Object.prototype.hasOwnProperty,Q$=Object.prototype.propertyIsEnumerable,bo=(t,e,r)=>e in t?G$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ie=(t,e)=>{for(var r in e||(e={}))Z$.call(e,r)&&bo(t,r,e[r]);if(xh)for(var r of xh(e))Q$.call(e,r)&&bo(t,r,e[r]);return t},Te=(t,e)=>Y$(t,J$(e)),R=(t,e,r)=>bo(t,typeof e!="symbol"?e+"":e,r);class X$ extends RE{constructor(e){super(e),R(this,"name",k$),R(this,"events",new Do),R(this,"initialized",!1),R(this,"requestQueue",{state:yt.idle,queue:[]}),R(this,"sessionRequestQueue",{state:yt.idle,queue:[]}),R(this,"requestQueueDelay",N.ONE_SECOND),R(this,"expectedPairingMethodMap",new Map),R(this,"recentlyDeletedMap",new Map),R(this,"recentlyDeletedLimit",200),R(this,"relayMessageCache",[]),R(this,"pendingSessions",new Map),R(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(ge)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=Te(ie({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=x0(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:h}=i;let l=s,u,d=!1;try{if(l){const A=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=A.active}}catch(A){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),A}if(!l||!d){const{topic:A,uri:O}=await this.client.core.pairing.create();l=A,u=O}if(!l){const{message:A}=B("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(A)}const f=await this.client.core.crypto.generateKeyPair(),p=ge.wc_sessionPropose.req.ttl||N.FIVE_MINUTES,y=de(p),w=Te(ie(ie({requiredNamespaces:n,optionalNamespaces:o,relays:h??[{protocol:Zu}],proposer:{publicKey:f,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:wt()}),v=X("session_connect",w.id),{reject:b,resolve:E,done:I}=Qt(p,Ph),P=({id:A})=>{A===w.id&&(this.client.events.off("proposal_expire",P),this.pendingSessions.delete(w.id),this.events.emit(v,{error:{message:Ph,code:0}}))};return this.client.events.on("proposal_expire",P),this.events.once(v,({error:A,session:O})=>{this.client.events.off("proposal_expire",P),A?b(A):O&&E(O)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:w,throwOnFailedPublish:!0,clientRpcId:w.id}),await this.setProposal(w.id,w),{uri:u,approval:I}}),R(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),R(this,"approve",async r=>{var i,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[at.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(D){throw o.setError(Jt.no_internet_connection),D}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(D){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(Jt.proposal_not_found),D}try{await this.isValidApprove(r)}catch(D){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Jt.session_approve_namespace_validation_failure),D}const{id:a,relayProtocol:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:d}=r,f=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:y,requiredNamespaces:w,optionalNamespaces:v}=f;let b=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:p});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:at.session_approve_started,properties:{topic:p,trace:[at.session_approve_started,at.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),I=y.publicKey,P=await this.client.core.crypto.generateSharedKey(E,I),A=ie(ie(ie({relay:{protocol:c??"irn"},namespaces:h,controller:{publicKey:E,metadata:this.client.metadata},expiry:de(Pr)},l&&{sessionProperties:l}),u&&{scopedProperties:u}),d&&{sessionConfig:d}),O=ae.relay;b.addTrace(at.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:O})}catch(D){throw b.setError(Jt.subscribe_session_topic_failure),D}b.addTrace(at.subscribe_session_topic_success);const C=Te(ie({},A),{topic:P,requiredNamespaces:w,optionalNamespaces:v,pairingTopic:p,acknowledged:!1,self:A.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:E,transportType:ae.relay});await this.client.session.set(P,C),b.addTrace(at.store_session);try{b.addTrace(at.publishing_session_settle),await this.sendRequest({topic:P,method:"wc_sessionSettle",params:A,throwOnFailedPublish:!0}).catch(D=>{throw b==null||b.setError(Jt.session_settle_publish_failure),D}),b.addTrace(at.session_settle_publish_success),b.addTrace(at.publishing_session_approve),await this.sendResult({id:a,topic:p,result:{relay:{protocol:c??"irn"},responderPublicKey:E},throwOnFailedPublish:!0}).catch(D=>{throw b==null||b.setError(Jt.session_approve_publish_failure),D}),b.addTrace(at.session_approve_publish_success)}catch(D){throw this.client.logger.error(D),this.client.session.delete(P,te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),D}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:y.metadata}),await this.client.proposal.delete(a,te("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(P,de(Pr)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),R(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:s}=r;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&(await this.sendError({id:i,topic:n,error:s,rpcOpts:ge.wc_sessionPropose.reject}),await this.client.proposal.delete(i,te("USER_DISCONNECTED")))}),R(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(u){throw this.client.logger.error("update() -> isValidUpdate() failed"),u}const{topic:i,namespaces:s}=r,{done:n,resolve:o,reject:a}=Qt(),c=wt(),h=nr().toString(),l=this.client.session.get(i).namespaces;return this.events.once(X("session_update",c),({error:u})=>{u?a(u):o()}),await this.client.session.update(i,{namespaces:s}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:h}).catch(u=>{this.client.logger.error(u),this.client.session.update(i,{namespaces:l}),a(u)}),{acknowledged:n}}),R(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,s=wt(),{done:n,resolve:o,reject:a}=Qt();return this.events.once(X("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,de(Pr)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),R(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(v){throw this.client.logger.error("request() -> isValidRequest() failed"),v}const{chainId:i,request:s,topic:n,expiry:o=ge.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(n);(a==null?void 0:a.transportType)===ae.relay&&await this.confirmOnlineStateOrThrow();const c=wt(),h=nr().toString(),{done:l,resolve:u,reject:d}=Qt(o,"Request expired. Please try again.");this.events.once(X("session_request",c),({error:v,result:b})=>{v?d(v):u(b)});const f="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:h,topic:n,method:f,params:{request:Te(ie({},s),{expiryTimestamp:de(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(v=>d(v)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),await l();const y={request:Te(ie({},s),{expiryTimestamp:de(o)}),chainId:i},w=this.shouldSetTVF(f,y);return await Promise.all([new Promise(async v=>{await this.sendRequest(ie({clientRpcId:c,relayRpcId:h,topic:n,method:f,params:y,expiry:o,throwOnFailedPublish:!0},w&&{tvf:this.getTVFParams(c,y)})).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),v()}),new Promise(async v=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const E=await zw(this.client.core.storage,Oh);await kw({id:c,topic:n,wcDeepLink:E})}v()}),l()]).then(v=>v[2])}),R(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:i,response:s}=r,{id:n}=s,o=this.client.session.get(i);o.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);bt(s)?await this.sendResult({id:n,topic:i,result:s.result,throwOnFailedPublish:!0,appLink:a}):et(s)&&await this.sendError({id:n,topic:i,error:s.error,appLink:a}),this.cleanupAfterResponse(r)}),R(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:i}=r;if(this.client.session.keys.includes(i)){const s=wt(),n=nr().toString(),{done:o,resolve:a,reject:c}=Qt();this.events.once(X("session_ping",s),({error:h})=>{h?c(h):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(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:i}))}),R(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:s,chainId:n}=r,o=nr().toString(),a=wt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:te("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:s}=B("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(s)}}),R(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>R0(i,r)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(this,"authenticate",async(r,i)=>{var s;this.isInitialized(),this.isValidAuthenticate(r);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?ae.link_mode:ae.relay;o===ae.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:h,domain:l,nonce:u,type:d,exp:f,nbf:p,methods:y=[],expiry:w}=r,v=[...r.resources||[]],{topic:b,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:E}});const I=await this.client.core.crypto.generateKeyPair(),P=ps(I);if(await Promise.all([this.client.auth.authKeys.set(ms,{responseTopic:P,publicKey:I}),this.client.auth.pairingTopics.set(P,{topic:P,pairingTopic:b})]),await this.client.core.relayer.subscribe(P,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),y.length>0){const{namespace:$}=Vr(a[0]);let x=Bb($,"request",y);ds(v)&&(x=Ub(x,v.pop())),v.push(x)}const A=w&&w>ge.wc_sessionAuthenticate.req.ttl?w:ge.wc_sessionAuthenticate.req.ttl,O={authPayload:{type:d??"caip122",chains:a,statement:c,aud:h,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:f,nbf:p,resources:v},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:de(A)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},D={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:de(ge.wc_sessionPropose.req.ttl),id:wt()},{done:M,resolve:U,reject:j}=Qt(A,"Request expired"),q=wt(),T=X("session_connect",D.id),g=X("session_request",q),m=async({error:$,session:x})=>{this.events.off(g,_),$?j($):x&&U({session:x})},_=async $=>{var x,F,k;if(await this.deletePendingAuthRequest(q,{message:"fulfilled",code:0}),$.error){const Y=te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return $.error.code===Y.code?void 0:(this.events.off(T,m),j($.error.message))}await this.deleteProposal(D.id),this.events.off(T,m);const{cacaos:z,responder:L}=$.result,H=[],G=[];for(const Y of z){await ac({cacao:Y,projectId:this.client.core.projectId})||(this.client.logger.error(Y,"Signature verification failed"),j(te("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Ae}=Y,Ee=ds(Ae.resources),Ce=[Yn(Ae.iss)],Ye=_s(Ae.iss);if(Ee){const Je=cc(Ee),br=hc(Ee);H.push(...Je),Ce.push(...br)}for(const Je of Ce)G.push(`${Je}:${Ye}`)}const se=await this.client.core.crypto.generateSharedKey(I,L.publicKey);let ee;H.length>0&&(ee={topic:se,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:de(Pr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:Nc([...new Set(H)],[...new Set(G)]),transportType:o},await this.client.core.relayer.subscribe(se,{transportType:o}),await this.client.session.set(se,ee),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:L.metadata}),ee=this.client.session.get(se)),(x=this.client.metadata.redirect)!=null&&x.linkMode&&(F=L.metadata.redirect)!=null&&F.linkMode&&(k=L.metadata.redirect)!=null&&k.universal&&i&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(se,{transportType:ae.link_mode})),U({auths:z,session:ee})};this.events.once(T,m),this.events.once(g,_);let S;try{if(n){const $=Ht("wc_sessionAuthenticate",O,q);this.client.core.history.set(b,$);const x=await this.client.core.crypto.encode("",$,{type:Hi,encoding:qt});S=ts(i,b,x)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:O,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:q}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:D,expiry:ge.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:D.id})])}catch($){throw this.events.off(T,m),this.events.off(g,_),$}return await this.setProposal(D.id,D),await this.setAuthRequest(q,{request:Te(ie({},O),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:S??E,response:M}}),R(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:s}=r,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Zt.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw n.setError(gi.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(gi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||ae.relay;a===ae.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),l=ps(c),u={type:Bt,receiverPublicKey:c,senderPublicKey:h},d=[],f=[];for(const w of s){if(!await ac({cacao:w,projectId:this.client.core.projectId})){n.setError(gi.invalid_cacao);const P=te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:l,error:P,encodeOpts:u}),new Error(P.message)}n.addTrace(Zt.cacaos_verified);const{p:v}=w,b=ds(v.resources),E=[Yn(v.iss)],I=_s(v.iss);if(b){const P=cc(b),A=hc(b);d.push(...P),E.push(...A)}for(const P of E)f.push(`${P}:${I}`)}const p=await this.client.core.crypto.generateSharedKey(h,c);n.addTrace(Zt.create_authenticated_session_topic);let y;if((d==null?void 0:d.length)>0){y={topic:p,acknowledged:!0,self:{publicKey:h,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:de(Pr),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Nc([...new Set(d)],[...new Set(f)]),transportType:a},n.addTrace(Zt.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw n.setError(gi.subscribe_authenticated_session_topic_failure),w}n.addTrace(Zt.subscribe_authenticated_session_topic_success),await this.client.session.set(p,y),n.addTrace(Zt.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Zt.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:i,result:{cacaos:s,responder:{publicKey:h,metadata:this.client.metadata}},encodeOpts:u,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw n.setError(gi.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:y}}),R(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:s}=r,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===ae.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ps(o),h={type:Bt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:s,encodeOpts:h,rpcOpts:ge.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.client.proposal.delete(i,te("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:s}=r;return du(i,s)}),R(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),R(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),R(this,"deleteSession",async r=>{var i;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,te("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem(Oh).catch(h=>this.client.logger.warn(h)),this.getPendingSessionRequests().forEach(h=>{h.topic===s&&this.deletePendingSessionRequest(h.id,te("USER_DISCONNECTED"))}),s===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=yt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),R(this,"deleteProposal",async(r,i)=>{if(i)try{const s=this.client.proposal.get(r),n=this.client.core.eventClient.getEvent({topic:s.pairingTopic});n==null||n.setError(Jt.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,te("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),R(this,"deletePendingSessionRequest",async(r,i,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==r),s&&(this.sessionRequestQueue.state=yt.idle,this.client.events.emit("session_request_expire",{id:r}))}),R(this,"deletePendingAuthRequest",async(r,i,s=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)])}),R(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),R(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,de(ge.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),R(this,"setAuthRequest",async(r,i)=>{const{request:s,pairingTopic:n,transportType:o=ae.relay}=i;this.client.core.expirer.set(r,s.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:r,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),R(this,"setPendingSessionRequest",async r=>{const{id:i,topic:s,params:n,verifyContext:o}=r,a=n.request.expiryTimestamp||de(ge.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:s,params:n,verifyContext:o})}),R(this,"sendRequest",async r=>{const{topic:i,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:h,appLink:l,tvf:u}=r,d=Ht(s,n,c);let f;const p=!!l;try{const v=p?qt:lt;f=await this.client.core.crypto.encode(i,d,{encoding:v})}catch(v){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),v}let y;if(q$.includes(s)){const v=Et(JSON.stringify(d)),b=Et(f);y=await this.client.core.verify.register({id:b,decryptedId:v})}const w=ge[s].req;if(w.attestation=y,o&&(w.ttl=o),a&&(w.id=a),this.client.core.history.set(i,d),p){const v=ts(l,i,f);await global.Linking.openURL(v,this.client.name)}else{const v=ge[s].req;o&&(v.ttl=o),a&&(v.id=a),v.tvf=Te(ie({},u),{correlationId:d.id}),h?(v.internal=Te(ie({},v.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,f,v)):this.client.core.relayer.publish(i,f,v).catch(b=>this.client.logger.error(b))}return d.id}),R(this,"sendResult",async r=>{const{id:i,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,h=zs(i,n);let l;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=u?qt:lt;l=await this.client.core.crypto.encode(s,h,Te(ie({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),p}let d,f;try{d=await this.client.core.history.get(s,i);const p=d.request;try{this.shouldSetTVF(p.method,p.params)&&(f=this.getTVFParams(i,p.params,n))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${i}) failed`),p}if(u){const p=ts(c,s,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,y=ge[p].res;y.tvf=Te(ie({},f),{correlationId:i}),o?(y.internal=Te(ie({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,l,y)):this.client.core.relayer.publish(s,l,y).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(h)}),R(this,"sendError",async r=>{const{id:i,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=r,h=Hs(i,n);let l;const u=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=u?qt:lt;l=await this.client.core.crypto.encode(s,h,Te(ie({},o||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),f}let d;try{d=await this.client.core.history.get(s,i)}catch(f){throw this.client.logger.error(`sendError() -> history.get(${s}, ${i}) failed`),f}if(u){const f=ts(c,s,l);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,p=a||ge[f].res;this.client.core.relayer.publish(s,l,p)}await this.client.core.history.resolve(h)}),R(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(s=>{let n=!1;Mt(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&r.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{Mt(s.expiryTimestamp)&&i.push(s.id)}),await Promise.all([...r.map(s=>this.deleteSession({topic:s})),...i.map(s=>this.deleteProposal(s))])}),R(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),R(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===yt.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=yt.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=yt.idle}),R(this,"processRequest",async r=>{const{topic:i,payload:s,attestation:n,transportType:o,encryptedId:a}=r,c=s.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,s);case"wc_sessionPing":return await this.onSessionPingRequest(i,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),R(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s,transportType:n}=r,o=(await this.client.core.history.get(i,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,s);case"wc_sessionExtend":return this.onSessionExtendResponse(i,s);case"wc_sessionPing":return this.onSessionPingResponse(i,s);case"wc_sessionRequest":return this.onSessionRequestResponse(i,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),R(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:s}=B("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),R(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:s}=r,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),R(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:s,attestation:n,encryptedId:o}=r,{params:a,id:c}=s;try{const h=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),h==null||h.setError(Ct.proposal_listener_not_found)),this.isValidConnect(ie({},s.params));const l=a.expiryTimestamp||de(ge.wc_sessionPropose.req.ttl),u=ie({id:c,pairingTopic:i,expiryTimestamp:l},a);await this.setProposal(c,u);const d=await this.getVerifyContext({attestationId:n,hash:Et(JSON.stringify(s)),encryptedId:o,metadata:u.proposer.metadata});h==null||h.addTrace(mt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:u,verifyContext:d})}catch(h){await this.sendError({id:c,topic:i,error:h,rpcOpts:ge.wc_sessionPropose.autoReject}),this.client.logger.error(h)}}),R(this,"onSessionProposeResponse",async(r,i,s)=>{const{id:n}=i;if(bt(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);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 h=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:h});const l=await this.client.core.crypto.generateSharedKey(c,h);this.pendingSessions.set(n,{sessionTopic:l,pairingTopic:r,proposalId:n,publicKey:c});const u=await this.client.core.relayer.subscribe(l,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:u}),await this.client.core.pairing.activate({topic:r})}else if(et(i)){await this.client.proposal.delete(n,te("USER_DISCONNECTED"));const o=X("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),R(this,"onSessionSettleRequest",async(r,i)=>{const{id:s,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:h,sessionProperties:l,scopedProperties:u,sessionConfig:d}=i.params,f=[...this.pendingSessions.values()].find(w=>w.sessionTopic===r);if(!f)return this.client.logger.error(`Pending session not found for topic ${r}`);const p=this.client.proposal.get(f.proposalId),y=Te(ie(ie(ie({topic:r,relay:o,expiry:c,namespaces:h,acknowledged:!0,pairingTopic:f.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:f.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),u&&{scopedProperties:u}),d&&{sessionConfig:d}),{transportType:ae.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:f.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(X("session_connect",f.proposalId),{session:y}),this.pendingSessions.delete(f.proposalId),this.deleteProposal(f.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:i.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(r,i)=>{const{id:s}=i;bt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(X("session_approve",s),{})):et(i)&&(await this.client.session.delete(r,te("USER_DISCONNECTED")),this.events.emit(X("session_approve",s),{error:i.error}))}),R(this,"onSessionUpdateRequest",async(r,i)=>{const{params:s,id:n}=i;try{const o=`${r}_session_update`,a=pi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:r,error:te("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ie({topic:r},s));try{pi.set(o,n),await this.client.session.update(r,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw pi.delete(o),c}this.client.events.emit("session_update",{id:n,topic:r,params:s})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(r,i)=>{const{id:s}=i,n=X("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_update",s),{}):et(i)&&this.events.emit(X("session_update",s),{error:i.error})}),R(this,"onSessionExtendRequest",async(r,i)=>{const{id:s}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,de(Pr)),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),R(this,"onSessionExtendResponse",(r,i)=>{const{id:s}=i,n=X("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_extend",s),{}):et(i)&&this.events.emit(X("session_extend",s),{error:i.error})}),R(this,"onSessionPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),R(this,"onSessionPingResponse",(r,i)=>{const{id:s}=i,n=X("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);bt(i)?this.events.emit(X("session_ping",s),{}):et(i)&&this.events.emit(X("session_ping",s),{error:i.error})},500)}),R(this,"onSessionDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r,reason:i.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(we.publish,async()=>{n(await this.deleteSession({topic:r,id:s}))})}),this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:te("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),R(this,"onSessionRequest",async r=>{var i,s,n;const{topic:o,payload:a,attestation:c,encryptedId:h,transportType:l}=r,{id:u,params:d}=a;try{await this.isValidRequest(ie({topic:o},d));const f=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Et(JSON.stringify(Ht("wc_sessionRequest",d,u))),encryptedId:h,metadata:f.peer.metadata,transportType:l}),y={id:u,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(y),l===ae.link_mode&&(i=f.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((s=f.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(f){await this.sendError({id:u,topic:o,error:f}),this.client.logger.error(f)}}),R(this,"onSessionRequestResponse",(r,i)=>{const{id:s}=i,n=X("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);bt(i)?this.events.emit(X("session_request",s),{result:i.result}):et(i)&&this.events.emit(X("session_request",s),{error:i.error})}),R(this,"onSessionEventRequest",async(r,i)=>{const{id:s,params:n}=i;try{const o=`${r}_session_event_${n.event.name}`,a=pi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(ie({topic:r},n)),this.client.events.emit("session_event",{id:s,topic:r,params:n}),pi.set(o,s)}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:s}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),bt(i)?this.events.emit(X("session_request",s),{result:i.result}):et(i)&&this.events.emit(X("session_request",s),{error:i.error})}),R(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:h,authPayload:l,expiryTimestamp:u}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Et(JSON.stringify(n)),encryptedId:a,metadata:h.metadata,transportType:c}),f={requester:h,pairingTopic:s,id:n.id,authPayload:l,verifyContext:d,expiryTimestamp:u};await this.setAuthRequest(n.id,{request:f,pairingTopic:s,transportType:c}),c===ae.link_mode&&(i=h.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(h.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:d})}catch(h){this.client.logger.error(h);const l=n.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),f={type:Bt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:n.id,topic:s,error:h,encodeOpts:f,rpcOpts:ge.wc_sessionAuthenticate.autoReject,appLink:d})}}),R(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),R(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=yt.idle,this.processSessionRequestQueue()},N.toMiliseconds(this.requestQueueDelay))}),R(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===r&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=X("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(X("session_request",n.request.id),{error:i})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===yt.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=yt.active,this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),R(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),R(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(s=>s.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Ht("wc_sessionPropose",Te(ie({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id)})}),R(this,"isValidConnect",async r=>{if(!Fe(r)){const{message:h}=B("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(h)}const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=r;if(De(i)||await this.isValidPairingTopic(i),!V0(c)){const{message:h}=B("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(h)}if(!De(s)&&Kt(s)!==0){const h="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(h):this.client.logger.warn(h),this.validateNamespaces(s,"requiredNamespaces")}if(!De(n)&&Kt(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),De(o)||this.validateSessionProps(o,"sessionProperties"),!De(a)){this.validateSessionProps(a,"scopedProperties");const h=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(l=>h.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(h)}`)}}),R(this,"validateNamespaces",(r,i)=>{const s=H0(r,"connect()",i);if(s)throw new Error(s.message)}),R(this,"isValidApprove",async r=>{if(!Fe(r))throw new Error(B("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),h=_n(s,"approve()");if(h)throw new Error(h.message);const l=Uc(c.requiredNamespaces,s,"approve()");if(l)throw new Error(l.message);if(!ue(n,!0)){const{message:u}=B("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(u)}if(De(o)||this.validateSessionProps(o,"sessionProperties"),!De(a)){this.validateSessionProps(a,"scopedProperties");const u=new Set(Object.keys(s));if(!Object.keys(a).every(d=>u.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(u).join(", ")}`)}}),R(this,"isValidReject",async r=>{if(!Fe(r)){const{message:n}=B("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(n)}const{id:i,reason:s}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!W0(s)){const{message:n}=B("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),R(this,"isValidSessionSettleRequest",r=>{if(!Fe(r)){const{message:h}=B("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(h)}const{relay:i,controller:s,namespaces:n,expiry:o}=r;if(!Fu(i)){const{message:h}=B("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(h)}const a=F0(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=_n(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Mt(o)){const{message:h}=B("EXPIRED","onSessionSettleRequest()");throw new Error(h)}}),R(this,"isValidUpdate",async r=>{if(!Fe(r)){const{message:c}=B("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:s}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=_n(s,"update()");if(o)throw new Error(o.message);const a=Uc(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async r=>{if(!Fe(r)){const{message:s}=B("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(s)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),R(this,"isValidRequest",async r=>{if(!Fe(r)){const{message:c}=B("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:s,chainId:n,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!jc(a,n)){const{message:c}=B("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!G0(s)){const{message:c}=B("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!Z0(a,n,s.method)){const{message:c}=B("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!t1(o,Cn)){const{message:c}=B("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Cn.min} and ${Cn.max}`);throw new Error(c)}}),R(this,"isValidRespond",async r=>{var i;if(!Fe(r)){const{message:o}=B("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:s,response:n}=r;try{await this.isValidSessionTopic(s)}catch(o){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),o}if(!Y0(n)){const{message:o}=B("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),R(this,"isValidPing",async r=>{if(!Fe(r)){const{message:s}=B("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),R(this,"isValidEmit",async r=>{if(!Fe(r)){const{message:a}=B("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:s,chainId:n}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!jc(o,n)){const{message:a}=B("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!J0(s)){const{message:a}=B("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!Q0(o,n,s.name)){const{message:a}=B("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async r=>{if(!Fe(r)){const{message:s}=B("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),R(this,"isValidAuthenticate",r=>{const{chains:i,uri:s,domain:n,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!ue(s,!1))throw new Error("uri is required parameter");if(!ue(n,!1))throw new Error("domain is required parameter");if(!ue(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>Vr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Vr(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),R(this,"getVerifyContext",async r=>{const{attestationId:i,hash:s,encryptedId:n,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||$i,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ae.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const h=await this.client.core.verify.resolve({attestationId:i,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});h&&(c.verified.origin=h.origin,c.verified.isScam=h.isScam,c.verified.validation=h.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(h){this.client.logger.warn(h)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),R(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((s,n)=>{if(s==null){const{message:o}=B("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${s} for key ${Object.keys(r)[n]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),R(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),R(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:s}=B("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(s)}}),R(this,"isLinkModeEnabled",(r,i)=>{var s,n,o,a,c,h,l,u,d;return!r||i!==ae.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((h=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:h.universal)!==""&&((l=r==null?void 0:r.redirect)==null?void 0:l.universal)!==void 0&&((u=r==null?void 0:r.redirect)==null?void 0:u.universal)!==""&&((d=r==null?void 0:r.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(r,i)=>{var s;return this.isLinkModeEnabled(r,i)?(s=r==null?void 0:r.redirect)==null?void 0:s.universal:void 0}),R(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Qa(r,"topic")||"",s=decodeURIComponent(Qa(r,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:ae.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:s,sessionExists:n})}),R(this,"registerLinkModeListeners",async()=>{var r;if(jo()||Wt()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=global==null?void 0:global.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await i.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),R(this,"shouldSetTVF",(r,i)=>{if(!i||r!=="wc_sessionRequest")return!1;const{request:s}=i;return Object.keys(Ah).includes(s.method)}),R(this,"getTVFParams",(r,i,s)=>{var n,o;try{const a=i.request.method,c=this.extractTxHashesFromResult(a,s);return Te(ie({correlationId:r,rpcMethods:[a],chainId:i.chainId},this.isValidContractData(i.request.params)&&{contractAddresses:[(o=(n=i.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const s=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),R(this,"extractTxHashesFromResult",(r,i)=>{try{const s=Ah[r];if(typeof i=="string")return[i];const n=i[s.key];if(ut(n))return r==="solana_signAllTransactions"?n.map(o=>Eb(o)):n;if(typeof n=="string")return[n]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,s]of Object.entries(r))for(const n of s)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=B("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(we.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ms)?this.client.auth.authKeys.get(ms):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:n===ae.link_mode?qt:lt});Ko(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:s,transportType:n,encryptedId:Et(i)})):Vs(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:n}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Xe.expired,async e=>{const{topic:r,id:i}=iu(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,B("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,B("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(rr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(rr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ue(e,!1)){const{message:r}=B("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=B("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(Mt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=B("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ue(e,!1)){const{message:r}=B("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=B("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(Mt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=B("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=B("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}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(ue(e,!1)){const{message:r}=B("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=B("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!K0(e)){const{message:r}=B("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=B("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(Mt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=B("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class eD extends mr{constructor(e,r){super(e,r,F$,Wo),this.core=e,this.logger=r}}let tD=class extends mr{constructor(e,r){super(e,r,L$,Wo),this.core=e,this.logger=r}};class rD extends mr{constructor(e,r){super(e,r,M$,Wo,i=>i.id),this.core=e,this.logger=r}}class iD extends mr{constructor(e,r){super(e,r,V$,Ws,()=>ms),this.core=e,this.logger=r}}class sD extends mr{constructor(e,r){super(e,r,K$,Ws),this.core=e,this.logger=r}}class nD extends mr{constructor(e,r){super(e,r,W$,Ws,i=>i.id),this.core=e,this.logger=r}}var oD=Object.defineProperty,aD=(t,e,r)=>e in t?oD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tn=(t,e,r)=>aD(t,typeof e!="symbol"?e+"":e,r);class cD{constructor(e,r){this.core=e,this.logger=r,Tn(this,"authKeys"),Tn(this,"pairingTopics"),Tn(this,"requests"),this.authKeys=new iD(this.core,this.logger),this.pairingTopics=new sD(this.core,this.logger),this.requests=new nD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var hD=Object.defineProperty,lD=(t,e,r)=>e in t?hD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,W=(t,e,r)=>lD(t,typeof e!="symbol"?e+"":e,r);let uD=class fd extends TE{constructor(e){super(e),W(this,"protocol",ud),W(this,"version",dd),W(this,"name",xn.name),W(this,"metadata"),W(this,"core"),W(this,"logger"),W(this,"events",new rt.EventEmitter),W(this,"engine"),W(this,"session"),W(this,"proposal"),W(this,"pendingRequest"),W(this,"auth"),W(this,"signConfig"),W(this,"on",(i,s)=>this.events.on(i,s)),W(this,"once",(i,s)=>this.events.once(i,s)),W(this,"off",(i,s)=>this.events.off(i,s)),W(this,"removeListener",(i,s)=>this.events.removeListener(i,s)),W(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),W(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"update",async i=>{try{return await this.engine.update(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"request",async i=>{try{return await this.engine.request(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"find",i=>{try{return this.engine.find(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),W(this,"authenticate",async(i,s)=>{try{return await this.engine.authenticate(i,s)}catch(n){throw this.logger.error(n.message),n}}),W(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),W(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),this.name=(e==null?void 0:e.name)||xn.name,this.metadata=Nw(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Vi(qs({level:(e==null?void 0:e.logger)||xn.logger}));this.core=(e==null?void 0:e.core)||new U$(e),this.logger=Ne(r,this.name),this.session=new tD(this.core,this.logger),this.proposal=new eD(this.core,this.logger),this.pendingRequest=new rD(this.core,this.logger),this.engine=new X$(this),this.auth=new cD(this.core,this.logger)}static async init(e){const r=new fd(e);return await r.initialize(),r}get context(){return Me(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"),setTimeout(()=>{this.engine.processRelayMessageCache()},N.toMiliseconds(N.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var vo={exports:{}};(function(t,e){var r=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof vt<"u"&&vt,i=function(){function n(){this.fetch=!1,this.DOMException=r.DOMException}return n.prototype=r,new n}();(function(n){(function(o){var a=typeof n<"u"&&n||typeof self<"u"&&self||typeof vt<"u"&&vt||{},c={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function h(g){return g&&DataView.prototype.isPrototypeOf(g)}if(c.arrayBuffer)var l=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(g){return g&&l.indexOf(Object.prototype.toString.call(g))>-1};function d(g){if(typeof g!="string"&&(g=String(g)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(g)||g==="")throw new TypeError('Invalid character in header field name: "'+g+'"');return g.toLowerCase()}function f(g){return typeof g!="string"&&(g=String(g)),g}function p(g){var m={next:function(){var _=g.shift();return{done:_===void 0,value:_}}};return c.iterable&&(m[Symbol.iterator]=function(){return m}),m}function y(g){this.map={},g instanceof y?g.forEach(function(m,_){this.append(_,m)},this):Array.isArray(g)?g.forEach(function(m){if(m.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+m.length);this.append(m[0],m[1])},this):g&&Object.getOwnPropertyNames(g).forEach(function(m){this.append(m,g[m])},this)}y.prototype.append=function(g,m){g=d(g),m=f(m);var _=this.map[g];this.map[g]=_?_+", "+m:m},y.prototype.delete=function(g){delete this.map[d(g)]},y.prototype.get=function(g){return g=d(g),this.has(g)?this.map[g]:null},y.prototype.has=function(g){return this.map.hasOwnProperty(d(g))},y.prototype.set=function(g,m){this.map[d(g)]=f(m)},y.prototype.forEach=function(g,m){for(var _ in this.map)this.map.hasOwnProperty(_)&&g.call(m,this.map[_],_,this)},y.prototype.keys=function(){var g=[];return this.forEach(function(m,_){g.push(_)}),p(g)},y.prototype.values=function(){var g=[];return this.forEach(function(m){g.push(m)}),p(g)},y.prototype.entries=function(){var g=[];return this.forEach(function(m,_){g.push([_,m])}),p(g)},c.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function w(g){if(!g._noBody){if(g.bodyUsed)return Promise.reject(new TypeError("Already read"));g.bodyUsed=!0}}function v(g){return new Promise(function(m,_){g.onload=function(){m(g.result)},g.onerror=function(){_(g.error)}})}function b(g){var m=new FileReader,_=v(m);return m.readAsArrayBuffer(g),_}function E(g){var m=new FileReader,_=v(m),S=/charset=([A-Za-z0-9_-]+)/.exec(g.type),$=S?S[1]:"utf-8";return m.readAsText(g,$),_}function I(g){for(var m=new Uint8Array(g),_=new Array(m.length),S=0;S<m.length;S++)_[S]=String.fromCharCode(m[S]);return _.join("")}function P(g){if(g.slice)return g.slice(0);var m=new Uint8Array(g.byteLength);return m.set(new Uint8Array(g)),m.buffer}function A(){return this.bodyUsed=!1,this._initBody=function(g){this.bodyUsed=this.bodyUsed,this._bodyInit=g,g?typeof g=="string"?this._bodyText=g:c.blob&&Blob.prototype.isPrototypeOf(g)?this._bodyBlob=g:c.formData&&FormData.prototype.isPrototypeOf(g)?this._bodyFormData=g:c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)?this._bodyText=g.toString():c.arrayBuffer&&c.blob&&h(g)?(this._bodyArrayBuffer=P(g.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):c.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(g)||u(g))?this._bodyArrayBuffer=P(g):this._bodyText=g=Object.prototype.toString.call(g):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof g=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):c.searchParams&&URLSearchParams.prototype.isPrototypeOf(g)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},c.blob&&(this.blob=function(){var g=w(this);if(g)return g;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var g=w(this);return g||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(c.blob)return this.blob().then(b);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var g=w(this);if(g)return g;if(this._bodyBlob)return E(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(I(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},c.formData&&(this.formData=function(){return this.text().then(M)}),this.json=function(){return this.text().then(JSON.parse)},this}var O=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function C(g){var m=g.toUpperCase();return O.indexOf(m)>-1?m:g}function D(g,m){if(!(this instanceof D))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');m=m||{};var _=m.body;if(g instanceof D){if(g.bodyUsed)throw new TypeError("Already read");this.url=g.url,this.credentials=g.credentials,m.headers||(this.headers=new y(g.headers)),this.method=g.method,this.mode=g.mode,this.signal=g.signal,!_&&g._bodyInit!=null&&(_=g._bodyInit,g.bodyUsed=!0)}else this.url=String(g);if(this.credentials=m.credentials||this.credentials||"same-origin",(m.headers||!this.headers)&&(this.headers=new y(m.headers)),this.method=C(m.method||this.method||"GET"),this.mode=m.mode||this.mode||null,this.signal=m.signal||this.signal||function(){if("AbortController"in a){var x=new AbortController;return x.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&_)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(_),(this.method==="GET"||this.method==="HEAD")&&(m.cache==="no-store"||m.cache==="no-cache")){var S=/([?&])_=[^&]*/;if(S.test(this.url))this.url=this.url.replace(S,"$1_="+new Date().getTime());else{var $=/\?/;this.url+=($.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}D.prototype.clone=function(){return new D(this,{body:this._bodyInit})};function M(g){var m=new FormData;return g.trim().split("&").forEach(function(_){if(_){var S=_.split("="),$=S.shift().replace(/\+/g," "),x=S.join("=").replace(/\+/g," ");m.append(decodeURIComponent($),decodeURIComponent(x))}}),m}function U(g){var m=new y,_=g.replace(/\r?\n[\t ]+/g," ");return _.split("\r").map(function(S){return S.indexOf(`
26
- `)===0?S.substr(1,S.length):S}).forEach(function(S){var $=S.split(":"),x=$.shift().trim();if(x){var F=$.join(":").trim();try{m.append(x,F)}catch(k){console.warn("Response "+k.message)}}}),m}A.call(D.prototype);function j(g,m){if(!(this instanceof j))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new y(m.headers),this.url=m.url||"",this._initBody(g)}A.call(j.prototype),j.prototype.clone=function(){return new j(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},j.error=function(){var g=new j(null,{status:200,statusText:""});return g.ok=!1,g.status=0,g.type="error",g};var q=[301,302,303,307,308];j.redirect=function(g,m){if(q.indexOf(m)===-1)throw new RangeError("Invalid status code");return new j(null,{status:m,headers:{location:g}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,_){this.message=m,this.name=_;var S=Error(m);this.stack=S.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function T(g,m){return new Promise(function(_,S){var $=new D(g,m);if($.signal&&$.signal.aborted)return S(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function F(){x.abort()}x.onload=function(){var L={statusText:x.statusText,headers:U(x.getAllResponseHeaders()||"")};$.url.indexOf("file://")===0&&(x.status<200||x.status>599)?L.status=200:L.status=x.status,L.url="responseURL"in x?x.responseURL:L.headers.get("X-Request-URL");var H="response"in x?x.response:x.responseText;setTimeout(function(){_(new j(H,L))},0)},x.onerror=function(){setTimeout(function(){S(new TypeError("Network request failed"))},0)},x.ontimeout=function(){setTimeout(function(){S(new TypeError("Network request timed out"))},0)},x.onabort=function(){setTimeout(function(){S(new o.DOMException("Aborted","AbortError"))},0)};function k(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(x.open($.method,k($.url),!0),$.credentials==="include"?x.withCredentials=!0:$.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&(c.blob?x.responseType="blob":c.arrayBuffer&&(x.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof y||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(L){z.push(d(L)),x.setRequestHeader(L,f(m.headers[L]))}),$.headers.forEach(function(L,H){z.indexOf(H)===-1&&x.setRequestHeader(H,L)})}else $.headers.forEach(function(L,H){x.setRequestHeader(H,L)});$.signal&&($.signal.addEventListener("abort",F),x.onreadystatechange=function(){x.readyState===4&&$.signal.removeEventListener("abort",F)}),x.send(typeof $._bodyInit>"u"?null:$._bodyInit)})}return T.polyfill=!0,a.fetch||(a.fetch=T,a.Headers=y,a.Request=D,a.Response=j),o.Headers=y,o.Request=D,o.Response=j,o.fetch=T,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=r.fetch?r:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})(vo,vo.exports);var dD=vo.exports;const Ch=tl(dD);var pD=Object.defineProperty,fD=Object.defineProperties,gD=Object.getOwnPropertyDescriptors,Th=Object.getOwnPropertySymbols,yD=Object.prototype.hasOwnProperty,mD=Object.prototype.propertyIsEnumerable,Rh=(t,e,r)=>e in t?pD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nh=(t,e)=>{for(var r in e||(e={}))yD.call(e,r)&&Rh(t,r,e[r]);if(Th)for(var r of Th(e))mD.call(e,r)&&Rh(t,r,e[r]);return t},Bh=(t,e)=>fD(t,gD(e));const wD={Accept:"application/json","Content-Type":"application/json"},bD="POST",jh={headers:wD,method:bD},Uh=10;let dt=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new rt.EventEmitter,this.isAvailable=!1,this.registering=!1,!Xc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=jt(e),i=await(await Ch(this.url,Bh(Nh({},jh),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Xc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=jt({id:1,jsonrpc:"2.0",method:"test",params:[]});await Ch(e,Bh(Nh({},jh),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?hr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=Hs(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return Vu(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Uh&&this.events.setMaxListeners(Uh)}};const Fh="error",vD="wss://relay.walletconnect.org",ED="wc",_D="universal_provider",os=`${ED}@2:${_D}:`,gd="https://rpc.walletconnect.org/v1/",Mr="generic",ID=`${gd}bundler`,st={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function $D(){}function Go(t){return t==null||typeof t!="object"&&typeof t!="function"}function Yo(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function DD(t){if(Go(t))return t;if(Array.isArray(t)||Yo(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function Lh(t){return typeof t=="object"&&t!==null}function yd(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function md(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const SD="[object RegExp]",wd="[object String]",bd="[object Number]",vd="[object Boolean]",Ed="[object Arguments]",OD="[object Symbol]",PD="[object Date]",AD="[object Map]",xD="[object Set]",CD="[object Array]",TD="[object ArrayBuffer]",RD="[object Object]",ND="[object DataView]",BD="[object Uint8Array]",jD="[object Uint8ClampedArray]",UD="[object Uint16Array]",FD="[object Uint32Array]",LD="[object Int8Array]",kD="[object Int16Array]",MD="[object Int32Array]",qD="[object Float32Array]",zD="[object Float64Array]";function HD(t,e){return Hr(t,void 0,t,new Map,e)}function Hr(t,e,r,i=new Map,s=void 0){const n=s==null?void 0:s(t,e,r,i);if(n!=null)return n;if(Go(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Hr(t[a],a,r,i,s);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;i.set(t,o);for(const[a,c]of t)o.set(a,Hr(c,a,r,i,s));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Hr(a,void 0,r,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(Yo(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Hr(t[a],a,r,i,s);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 i.set(t,o),ir(o,t,r,i,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),ir(o,t,r,i,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),ir(o,t,r,i,s),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,ir(o,t,r,i,s),o}if(typeof t=="object"&&VD(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),ir(o,t,r,i,s),o}return t}function ir(t,e,r=t,i,s){const n=[...Object.keys(e),...yd(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Hr(e[a],a,r,i,s))}}function VD(t){switch(md(t)){case Ed:case CD:case TD:case ND:case vd:case PD:case qD:case zD:case LD:case kD:case MD:case AD:case bd:case RD:case SD:case xD:case wd:case OD:case BD:case jD:case UD:case FD:return!0;default:return!1}}function KD(t,e){return HD(t,(r,i,s,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case bd:case wd:case vd:{const o=new t.constructor(t==null?void 0:t.valueOf());return ir(o,t),o}case Ed:{const o={};return ir(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function kh(t){return KD(t)}function Mh(t){return t!==null&&typeof t=="object"&&md(t)==="[object Arguments]"}function WD(t){return Yo(t)}function GD(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function YD(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let s=t;for(let n=0;n<r.length;n++){const o=r[n];s=Eo(s,o,i,new Map)}return s}function Eo(t,e,r,i){if(Go(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return DD(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...yd(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(Mh(a)&&(a={...a}),Mh(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=kh(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],u=Reflect.ownKeys(c);for(let d=0;d<u.length;d++){const f=u[d];l[f]=c[f]}c=l}else c=[];const h=r(c,a,o,t,e,i);h!=null?t[o]=h:Array.isArray(a)||Lh(c)&&Lh(a)?t[o]=Eo(c,a,r,i):c==null&&GD(a)?t[o]=Eo({},a,r,i):c==null&&WD(a)?t[o]=kh(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function JD(t,...e){return YD(t,...e,$D)}var ZD=Object.defineProperty,QD=Object.defineProperties,XD=Object.getOwnPropertyDescriptors,qh=Object.getOwnPropertySymbols,eS=Object.prototype.hasOwnProperty,tS=Object.prototype.propertyIsEnumerable,zh=(t,e,r)=>e in t?ZD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,as=(t,e)=>{for(var r in e||(e={}))eS.call(e,r)&&zh(t,r,e[r]);if(qh)for(var r of qh(e))tS.call(e,r)&&zh(t,r,e[r]);return t},rS=(t,e)=>QD(t,XD(e));function Ge(t,e,r){var i;const s=Vr(t);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${gd}?chainId=${s.namespace}:${s.reference}&projectId=${r}`}function wr(t){return t.includes(":")?t.split(":")[1]:t}function _d(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function iS(t,e){const r=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!r.length)return[];const i=[];return r.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function cs(t={},e={}){const r=Hh(t),i=Hh(e);return JD(r,i)}function Hh(t){var e,r,i,s,n;const o={};if(!Kt(t))return o;for(const[a,c]of Object.entries(t)){const h=ks(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],d=c.rpcMap||{},f=zr(a);o[f]=rS(as(as({},o[f]),c),{chains:_t(h,(e=o[f])==null?void 0:e.chains),methods:_t(l,(r=o[f])==null?void 0:r.methods),events:_t(u,(i=o[f])==null?void 0:i.events)}),(Kt(d)||Kt(((s=o[f])==null?void 0:s.rpcMap)||{}))&&(o[f].rpcMap=as(as({},d),(n=o[f])==null?void 0:n.rpcMap))}return o}function Vh(t){return t.includes(":")?t.split(":")[2]:t}function Kh(t){const e={};for(const[r,i]of Object.entries(t)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=ks(r)?[r]:i.chains?i.chains:_d(i.accounts);e[r]={chains:a,methods:s,events:n,accounts:o}}return e}function Rn(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))}const Id={},Q=t=>Id[t],Nn=(t,e)=>{Id[t]=e};var sS=Object.defineProperty,nS=(t,e,r)=>e in t?sS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ar=(t,e,r)=>nS(t,typeof e!="symbol"?e+"":e,r);class oS{constructor(e){Ar(this,"name","polkadot"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var aS=Object.defineProperty,cS=Object.defineProperties,hS=Object.getOwnPropertyDescriptors,Wh=Object.getOwnPropertySymbols,lS=Object.prototype.hasOwnProperty,uS=Object.prototype.propertyIsEnumerable,_o=(t,e,r)=>e in t?aS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gh=(t,e)=>{for(var r in e||(e={}))lS.call(e,r)&&_o(t,r,e[r]);if(Wh)for(var r of Wh(e))uS.call(e,r)&&_o(t,r,e[r]);return t},Yh=(t,e)=>cS(t,hS(e)),xr=(t,e,r)=>_o(t,typeof e!="symbol"?e+"":e,r);class dS{constructor(e){xr(this,"name","eip155"),xr(this,"client"),xr(this,"chainId"),xr(this,"namespace"),xr(this,"httpProviders"),xr(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}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)}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,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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,r){const i=r||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=parseInt(wr(r));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,i;let s=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. 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 r,i,s,n,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u==null?void 0:u[h];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Yh(Gh({},l.sessionProperties||{}),{capabilities:Yh(Gh({},u||{}),{[h]:d})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(e){var r,i;const s=this.client.session.get(e.topic),n=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}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,r){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ht("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,r){return`${ID}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var pS=Object.defineProperty,fS=(t,e,r)=>e in t?pS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Cr=(t,e,r)=>fS(t,typeof e!="symbol"?e+"":e,r);class gS{constructor(e){Cr(this,"name","solana"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var yS=Object.defineProperty,mS=(t,e,r)=>e in t?yS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tr=(t,e,r)=>mS(t,typeof e!="symbol"?e+"":e,r);class wS{constructor(e){Tr(this,"name","cosmos"),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var bS=Object.defineProperty,vS=(t,e,r)=>e in t?bS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e,r)=>vS(t,typeof e!="symbol"?e+"":e,r);class ES{constructor(e){Rr(this,"name","algorand"),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const i=r||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var _S=Object.defineProperty,IS=(t,e,r)=>e in t?_S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nr=(t,e,r)=>IS(t,typeof e!="symbol"?e+"":e,r);class $S{constructor(e){Nr(this,"name","cip34"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const i=this.getCardanoRPCUrl(r),s=wr(r);e[s]=this.createHttpProvider(s,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var DS=Object.defineProperty,SS=(t,e,r)=>e in t?DS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Br=(t,e,r)=>SS(t,typeof e!="symbol"?e+"":e,r);class OS{constructor(e){Br(this,"name","elrond"),Br(this,"client"),Br(this,"httpProviders"),Br(this,"events"),Br(this,"namespace"),Br(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var PS=Object.defineProperty,AS=(t,e,r)=>e in t?PS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jr=(t,e,r)=>AS(t,typeof e!="symbol"?e+"":e,r);class xS{constructor(e){jr(this,"name","multiversx"),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var CS=Object.defineProperty,TS=(t,e,r)=>e in t?CS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ur=(t,e,r)=>TS(t,typeof e!="symbol"?e+"":e,r);class RS{constructor(e){Ur(this,"name","near"),Ur(this,"client"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"namespace"),Ur(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var NS=Object.defineProperty,BS=(t,e,r)=>e in t?NS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fr=(t,e,r)=>BS(t,typeof e!="symbol"?e+"":e,r);class jS{constructor(e){Fr(this,"name","tezos"),Fr(this,"client"),Fr(this,"httpProviders"),Fr(this,"events"),Fr(this,"namespace"),Fr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i))}}var US=Object.defineProperty,FS=(t,e,r)=>e in t?US(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lr=(t,e,r)=>FS(t,typeof e!="symbol"?e+"":e,r);class LS{constructor(e){Lr(this,"name",Mr),Lr(this,"client"),Lr(this,"httpProviders"),Lr(this,"events"),Lr(this,"namespace"),Lr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(s=>{const n=Vr(s);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),i}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var kS=Object.defineProperty,MS=Object.defineProperties,qS=Object.getOwnPropertyDescriptors,Jh=Object.getOwnPropertySymbols,zS=Object.prototype.hasOwnProperty,HS=Object.prototype.propertyIsEnumerable,Io=(t,e,r)=>e in t?kS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hs=(t,e)=>{for(var r in e||(e={}))zS.call(e,r)&&Io(t,r,e[r]);if(Jh)for(var r of Jh(e))HS.call(e,r)&&Io(t,r,e[r]);return t},Bn=(t,e)=>MS(t,qS(e)),Qe=(t,e,r)=>Io(t,typeof e!="symbol"?e+"":e,r);let VS=class $d{constructor(e){Qe(this,"client"),Qe(this,"namespaces"),Qe(this,"optionalNamespaces"),Qe(this,"sessionProperties"),Qe(this,"scopedProperties"),Qe(this,"events",new Do),Qe(this,"rpcProviders",{}),Qe(this,"session"),Qe(this,"providerOpts"),Qe(this,"logger"),Qe(this,"uri"),Qe(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Vi(qs({level:(e==null?void 0:e.logger)||Fh})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new $d(e);return await r.initialize(),r}async request(e,r,i){const[s,n]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:hs({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>r(null,zs(n,o))).catch(o=>r(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:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=Kh(this.session.namespaces);this.namespaces=cs(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){const{uri:r,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});r&&(this.uri=r,this.events.emit("display_uri",r));const s=await i();this.session=s;const n=Kh(s.namespaces);return this.namespaces=cs(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,s]=this.validateChain(e),n=this.getProvider(i);n.name===Mr?n.setDefaultChain(`${i}:${s}`,r):n.setDefaultChain(s,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(ut(r)){for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}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,r;if(this.client=this.providerOpts.client||await uD.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Fh,relayUrl:this.providerOpts.relayUrl||vD,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(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[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(r=>zr(r)))];Nn("client",this.client),Nn("events",this.events),Nn("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=iS(r,this.session),s=_d(i),n=cs(this.namespaces,this.optionalNamespaces),o=Bn(hs({},n[r]),{accounts:i,chains:s});switch(r){case"eip155":this.rpcProviders[r]=new dS({namespace:o});break;case"algorand":this.rpcProviders[r]=new ES({namespace:o});break;case"solana":this.rpcProviders[r]=new gS({namespace:o});break;case"cosmos":this.rpcProviders[r]=new wS({namespace:o});break;case"polkadot":this.rpcProviders[r]=new oS({namespace:o});break;case"cip34":this.rpcProviders[r]=new $S({namespace:o});break;case"elrond":this.rpcProviders[r]=new OS({namespace:o});break;case"multiversx":this.rpcProviders[r]=new xS({namespace:o});break;case"near":this.rpcProviders[r]=new RS({namespace:o});break;case"tezos":this.rpcProviders[r]=new jS({namespace:o});break;default:this.rpcProviders[Mr]?this.rpcProviders[Mr].updateNamespace(o):this.rpcProviders[Mr]=new LS({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:s}=e;if(s!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&ut(o)&&this.events.emit("accountsChanged",o.map(Vh))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=zr(o),h=Rn(o)!==Rn(a)?`${c}:${Rn(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=r,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Bn(hs({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Bn(hs({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(st.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Mr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=cs(r,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>zr(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const s=zr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,r=!1){if(!this.namespaces)return;const[i,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(i,s),this.events.emit("chainChanged",s);const n=this.getProvider(i).getDefaultChain();r||this.getProvider(i).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:r,newChainId:i}){var s,n;try{if(r===i)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(Vh);if(!ut(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,s={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${os}/${e}${s}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${os}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${os}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const i of r)i.startsWith(os)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}};const KS=VS,WS="wc",GS="ethereum_provider",YS=`${WS}@2:${GS}:`,JS="https://rpc.walletconnect.org/v1/",Os=["eth_sendTransaction","personal_sign"],Dd=["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_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Ps=["chainChanged","accountsChanged"],Sd=["chainChanged","accountsChanged","message","disconnect","connect"],ZS=async()=>{const{createAppKit:t}=await el(()=>import("./core-DjR_jD64.js").then(e=>e.r),__vite__mapDeps([4,1,2,3,5]));return t};var QS=Object.defineProperty,XS=Object.defineProperties,eO=Object.getOwnPropertyDescriptors,Zh=Object.getOwnPropertySymbols,tO=Object.prototype.hasOwnProperty,rO=Object.prototype.propertyIsEnumerable,$o=(t,e,r)=>e in t?QS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xt=(t,e)=>{for(var r in e||(e={}))tO.call(e,r)&&$o(t,r,e[r]);if(Zh)for(var r of Zh(e))rO.call(e,r)&&$o(t,r,e[r]);return t},wi=(t,e)=>XS(t,eO(e)),ze=(t,e,r)=>$o(t,typeof e!="symbol"?e+"":e,r);function As(t){return Number(t[0].split(":")[1])}function ls(t){return`0x${t.toString(16)}`}function iO(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!ut(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Os,events:n||Ps,rpcMap:Xt({},e.length?{[As(e)]:a[As(e)]}:{})},h=n==null?void 0:n.filter(f=>!Ps.includes(f)),l=i==null?void 0:i.filter(f=>!Os.includes(f));if(!r&&!o&&!s&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=(h==null?void 0:h.length)&&(l==null?void 0:l.length)||!r,d={chains:[...new Set(u?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Dd))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Sd))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?d:void 0}}class Gs{constructor(){ze(this,"events",new rt.EventEmitter),ze(this,"namespace","eip155"),ze(this,"accounts",[]),ze(this,"signer"),ze(this,"chainId",1),ze(this,"modal"),ze(this,"rpc"),ze(this,"STORAGE_KEY",YS),ze(this,"on",(e,r)=>(this.events.on(e,r),this)),ze(this,"once",(e,r)=>(this.events.once(e,r),this)),ze(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ze(this,"off",(e,r)=>(this.events.off(e,r),this)),ze(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Gs;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=iO(this.rpc);try{const n=await new Promise(async(a,c)=>{var h,l;this.rpc.showQrModal&&((h=this.modal)==null||h.open(),(l=this.modal)==null||l.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(wi(Xt({namespaces:Xt({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:u})).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=Wa(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const s=await new Promise(async(o,a)=>{var c,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(wi(Xt({},e),{chains:this.rpc.chains}),r).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=s.session;if(n){const o=Wa(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",ls(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",wi(Xt({},te("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ls(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,s]=e.split(":");return{chainId:`${r}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const s=(r=e==null?void 0:e.chains)!=null?r:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||Os:[],c=s.length?(e==null?void 0:e.events)||Ps:[],h=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],u=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:h,optionalEvents:l,rpcMap:u,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,r)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?As(this.rpc.chains):As(this.rpc.optionalChains),this.signer=await KS.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const i=await ZS(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return fO}),n=s(wi(Xt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");r=i(wi(Xt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:s}=e;r&&ut(r)&&(this.rpc.chains=r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&ut(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${JS}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const sO=Gs;var nO=Object.defineProperty,oO=Object.defineProperties,aO=Object.getOwnPropertyDescriptors,Qh=Object.getOwnPropertySymbols,cO=Object.prototype.hasOwnProperty,hO=Object.prototype.propertyIsEnumerable,Xh=(t,e,r)=>e in t?nO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Od=(t,e)=>{for(var r in e||(e={}))cO.call(e,r)&&Xh(t,r,e[r]);if(Qh)for(var r of Qh(e))hO.call(e,r)&&Xh(t,r,e[r]);return t},lO=(t,e)=>oO(t,aO(e));function uO(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const dO=t=>{const[e,r]=t.split(":");return Pd({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function pO(t){var e,r,i,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(dO).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(u=>{var d;return u.id===((d=t.defaultChain)==null?void 0:d.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:uO(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:h,metadata:lO(Od({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=t.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=t.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const u=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],f=u.filter(p=>!d.includes(p.id));f.length&&(l.customWallets=f)}return l}function Pd(t){return Od({formatters:void 0,fees:void 0,serializers:void 0},t)}var fO=Object.freeze({__proto__:null,convertWCMToAppKitOptions:pO,defineChain:Pd});const nP=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:sO,OPTIONAL_EVENTS:Sd,OPTIONAL_METHODS:Dd,REQUIRED_EVENTS:Ps,REQUIRED_METHODS:Os,default:Gs},Symbol.toStringTag,{value:"Module"}));export{pE as A,Ko as B,vw as C,Vs as D,Ne as E,bt as F,qs as G,df as H,gr as I,it as J,wt as K,yr as L,EO as M,Pf as N,Vi as O,Ha as P,Wl as Q,bO as R,hr as S,jt as T,Kn as U,fl as V,ke as W,pf as X,Me as Y,Im as a,xs as b,ba as c,mO as d,tf as e,Cf as f,N as g,Ei as h,vO as i,wO as j,Jd as k,e_ as l,dt as m,Hs as n,Ht as o,zs as p,tt as q,nr as r,ar as s,nl as t,So as u,ol as v,L1 as w,l1 as x,nP as y,et as z};
26
+ `)===0?S.substr(1,S.length):S}).forEach(function(S){var $=S.split(":"),x=$.shift().trim();if(x){var F=$.join(":").trim();try{m.append(x,F)}catch(k){console.warn("Response "+k.message)}}}),m}A.call(D.prototype);function j(g,m){if(!(this instanceof j))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(m||(m={}),this.type="default",this.status=m.status===void 0?200:m.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=m.statusText===void 0?"":""+m.statusText,this.headers=new y(m.headers),this.url=m.url||"",this._initBody(g)}A.call(j.prototype),j.prototype.clone=function(){return new j(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},j.error=function(){var g=new j(null,{status:200,statusText:""});return g.ok=!1,g.status=0,g.type="error",g};var q=[301,302,303,307,308];j.redirect=function(g,m){if(q.indexOf(m)===-1)throw new RangeError("Invalid status code");return new j(null,{status:m,headers:{location:g}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(m,_){this.message=m,this.name=_;var S=Error(m);this.stack=S.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function T(g,m){return new Promise(function(_,S){var $=new D(g,m);if($.signal&&$.signal.aborted)return S(new o.DOMException("Aborted","AbortError"));var x=new XMLHttpRequest;function F(){x.abort()}x.onload=function(){var L={statusText:x.statusText,headers:U(x.getAllResponseHeaders()||"")};$.url.indexOf("file://")===0&&(x.status<200||x.status>599)?L.status=200:L.status=x.status,L.url="responseURL"in x?x.responseURL:L.headers.get("X-Request-URL");var H="response"in x?x.response:x.responseText;setTimeout(function(){_(new j(H,L))},0)},x.onerror=function(){setTimeout(function(){S(new TypeError("Network request failed"))},0)},x.ontimeout=function(){setTimeout(function(){S(new TypeError("Network request timed out"))},0)},x.onabort=function(){setTimeout(function(){S(new o.DOMException("Aborted","AbortError"))},0)};function k(L){try{return L===""&&a.location.href?a.location.href:L}catch{return L}}if(x.open($.method,k($.url),!0),$.credentials==="include"?x.withCredentials=!0:$.credentials==="omit"&&(x.withCredentials=!1),"responseType"in x&&(c.blob?x.responseType="blob":c.arrayBuffer&&(x.responseType="arraybuffer")),m&&typeof m.headers=="object"&&!(m.headers instanceof y||a.Headers&&m.headers instanceof a.Headers)){var z=[];Object.getOwnPropertyNames(m.headers).forEach(function(L){z.push(d(L)),x.setRequestHeader(L,f(m.headers[L]))}),$.headers.forEach(function(L,H){z.indexOf(H)===-1&&x.setRequestHeader(H,L)})}else $.headers.forEach(function(L,H){x.setRequestHeader(H,L)});$.signal&&($.signal.addEventListener("abort",F),x.onreadystatechange=function(){x.readyState===4&&$.signal.removeEventListener("abort",F)}),x.send(typeof $._bodyInit>"u"?null:$._bodyInit)})}return T.polyfill=!0,a.fetch||(a.fetch=T,a.Headers=y,a.Request=D,a.Response=j),o.Headers=y,o.Request=D,o.Response=j,o.fetch=T,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=r.fetch?r:i;e=s.fetch,e.default=s.fetch,e.fetch=s.fetch,e.Headers=s.Headers,e.Request=s.Request,e.Response=s.Response,t.exports=e})(vo,vo.exports);var dD=vo.exports;const Ch=tl(dD);var pD=Object.defineProperty,fD=Object.defineProperties,gD=Object.getOwnPropertyDescriptors,Th=Object.getOwnPropertySymbols,yD=Object.prototype.hasOwnProperty,mD=Object.prototype.propertyIsEnumerable,Rh=(t,e,r)=>e in t?pD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nh=(t,e)=>{for(var r in e||(e={}))yD.call(e,r)&&Rh(t,r,e[r]);if(Th)for(var r of Th(e))mD.call(e,r)&&Rh(t,r,e[r]);return t},Bh=(t,e)=>fD(t,gD(e));const wD={Accept:"application/json","Content-Type":"application/json"},bD="POST",jh={headers:wD,method:bD},Uh=10;let dt=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new rt.EventEmitter,this.isAvailable=!1,this.registering=!1,!Xc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=jt(e),i=await(await Ch(this.url,Bh(Nh({},jh),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Xc(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return s(new Error("HTTP connection is missing or invalid"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=jt({id:1,jsonrpc:"2.0",method:"test",params:[]});await Ch(e,Bh(Nh({},jh),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?hr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=Hs(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return Vu(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>Uh&&this.events.setMaxListeners(Uh)}};const Fh="error",vD="wss://relay.walletconnect.org",ED="wc",_D="universal_provider",os=`${ED}@2:${_D}:`,gd="https://rpc.walletconnect.org/v1/",Mr="generic",ID=`${gd}bundler`,st={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function $D(){}function Go(t){return t==null||typeof t!="object"&&typeof t!="function"}function Yo(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function DD(t){if(Go(t))return t;if(Array.isArray(t)||Yo(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function Lh(t){return typeof t=="object"&&t!==null}function yd(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function md(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const SD="[object RegExp]",wd="[object String]",bd="[object Number]",vd="[object Boolean]",Ed="[object Arguments]",OD="[object Symbol]",PD="[object Date]",AD="[object Map]",xD="[object Set]",CD="[object Array]",TD="[object ArrayBuffer]",RD="[object Object]",ND="[object DataView]",BD="[object Uint8Array]",jD="[object Uint8ClampedArray]",UD="[object Uint16Array]",FD="[object Uint32Array]",LD="[object Int8Array]",kD="[object Int16Array]",MD="[object Int32Array]",qD="[object Float32Array]",zD="[object Float64Array]";function HD(t,e){return Hr(t,void 0,t,new Map,e)}function Hr(t,e,r,i=new Map,s=void 0){const n=s==null?void 0:s(t,e,r,i);if(n!=null)return n;if(Go(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Hr(t[a],a,r,i,s);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;i.set(t,o);for(const[a,c]of t)o.set(a,Hr(c,a,r,i,s));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Hr(a,void 0,r,i,s));return o}if(typeof Buffer<"u"&&Buffer.isBuffer(t))return t.subarray();if(Yo(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Hr(t[a],a,r,i,s);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 i.set(t,o),ir(o,t,r,i,s),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),ir(o,t,r,i,s),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),ir(o,t,r,i,s),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,ir(o,t,r,i,s),o}if(typeof t=="object"&&VD(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),ir(o,t,r,i,s),o}return t}function ir(t,e,r=t,i,s){const n=[...Object.keys(e),...yd(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Hr(e[a],a,r,i,s))}}function VD(t){switch(md(t)){case Ed:case CD:case TD:case ND:case vd:case PD:case qD:case zD:case LD:case kD:case MD:case AD:case bd:case RD:case SD:case xD:case wd:case OD:case BD:case jD:case UD:case FD:return!0;default:return!1}}function KD(t,e){return HD(t,(r,i,s,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case bd:case wd:case vd:{const o=new t.constructor(t==null?void 0:t.valueOf());return ir(o,t),o}case Ed:{const o={};return ir(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function kh(t){return KD(t)}function Mh(t){return t!==null&&typeof t=="object"&&md(t)==="[object Arguments]"}function WD(t){return Yo(t)}function GD(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function YD(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let s=t;for(let n=0;n<r.length;n++){const o=r[n];s=Eo(s,o,i,new Map)}return s}function Eo(t,e,r,i){if(Go(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return DD(i.get(e));if(i.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const s=[...Object.keys(e),...yd(e)];for(let n=0;n<s.length;n++){const o=s[n];let a=e[o],c=t[o];if(Mh(a)&&(a={...a}),Mh(c)&&(c={...c}),typeof Buffer<"u"&&Buffer.isBuffer(a)&&(a=kh(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const l=[],u=Reflect.ownKeys(c);for(let d=0;d<u.length;d++){const f=u[d];l[f]=c[f]}c=l}else c=[];const h=r(c,a,o,t,e,i);h!=null?t[o]=h:Array.isArray(a)||Lh(c)&&Lh(a)?t[o]=Eo(c,a,r,i):c==null&&GD(a)?t[o]=Eo({},a,r,i):c==null&&WD(a)?t[o]=kh(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function JD(t,...e){return YD(t,...e,$D)}var ZD=Object.defineProperty,QD=Object.defineProperties,XD=Object.getOwnPropertyDescriptors,qh=Object.getOwnPropertySymbols,eS=Object.prototype.hasOwnProperty,tS=Object.prototype.propertyIsEnumerable,zh=(t,e,r)=>e in t?ZD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,as=(t,e)=>{for(var r in e||(e={}))eS.call(e,r)&&zh(t,r,e[r]);if(qh)for(var r of qh(e))tS.call(e,r)&&zh(t,r,e[r]);return t},rS=(t,e)=>QD(t,XD(e));function Ge(t,e,r){var i;const s=Vr(t);return((i=e.rpcMap)==null?void 0:i[s.reference])||`${gd}?chainId=${s.namespace}:${s.reference}&projectId=${r}`}function wr(t){return t.includes(":")?t.split(":")[1]:t}function _d(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function iS(t,e){const r=Object.keys(e.namespaces).filter(s=>s.includes(t));if(!r.length)return[];const i=[];return r.forEach(s=>{const n=e.namespaces[s].accounts;i.push(...n)}),i}function cs(t={},e={}){const r=Hh(t),i=Hh(e);return JD(r,i)}function Hh(t){var e,r,i,s,n;const o={};if(!Kt(t))return o;for(const[a,c]of Object.entries(t)){const h=ks(a)?[a]:c.chains,l=c.methods||[],u=c.events||[],d=c.rpcMap||{},f=zr(a);o[f]=rS(as(as({},o[f]),c),{chains:_t(h,(e=o[f])==null?void 0:e.chains),methods:_t(l,(r=o[f])==null?void 0:r.methods),events:_t(u,(i=o[f])==null?void 0:i.events)}),(Kt(d)||Kt(((s=o[f])==null?void 0:s.rpcMap)||{}))&&(o[f].rpcMap=as(as({},d),(n=o[f])==null?void 0:n.rpcMap))}return o}function Vh(t){return t.includes(":")?t.split(":")[2]:t}function Kh(t){const e={};for(const[r,i]of Object.entries(t)){const s=i.methods||[],n=i.events||[],o=i.accounts||[],a=ks(r)?[r]:i.chains?i.chains:_d(i.accounts);e[r]={chains:a,methods:s,events:n,accounts:o}}return e}function Rn(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))}const Id={},Q=t=>Id[t],Nn=(t,e)=>{Id[t]=e};var sS=Object.defineProperty,nS=(t,e,r)=>e in t?sS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ar=(t,e,r)=>nS(t,typeof e!="symbol"?e+"":e,r);class oS{constructor(e){Ar(this,"name","polkadot"),Ar(this,"client"),Ar(this,"httpProviders"),Ar(this,"events"),Ar(this,"namespace"),Ar(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var aS=Object.defineProperty,cS=Object.defineProperties,hS=Object.getOwnPropertyDescriptors,Wh=Object.getOwnPropertySymbols,lS=Object.prototype.hasOwnProperty,uS=Object.prototype.propertyIsEnumerable,_o=(t,e,r)=>e in t?aS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gh=(t,e)=>{for(var r in e||(e={}))lS.call(e,r)&&_o(t,r,e[r]);if(Wh)for(var r of Wh(e))uS.call(e,r)&&_o(t,r,e[r]);return t},Yh=(t,e)=>cS(t,hS(e)),xr=(t,e,r)=>_o(t,typeof e!="symbol"?e+"":e,r);class dS{constructor(e){xr(this,"name","eip155"),xr(this,"client"),xr(this,"chainId"),xr(this,"namespace"),xr(this,"httpProviders"),xr(this,"events"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}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)}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,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r),this.chainId=parseInt(e),this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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,r){const i=r||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=parseInt(wr(r));e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}async handleSwitchChain(e){var r,i;let s=e.request.params?(r=e.request.params[0])==null?void 0:r.chainId:"0x0";s=s.startsWith("0x")?s:`0x${s}`;const n=parseInt(s,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:s}]},chainId:(i=this.namespace.chains)==null?void 0:i[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. 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 r,i,s,n,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[0],c=((n=(s=e.request)==null?void 0:s.params)==null?void 0:n[1])||[],h=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{};if(u!=null&&u[h])return u==null?void 0:u[h];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Yh(Gh({},l.sessionProperties||{}),{capabilities:Yh(Gh({},u||{}),{[h]:d})})})}catch(f){console.warn("Failed to update session with capabilities",f)}return d}async getCallStatus(e){var r,i;const s=this.client.session.get(e.topic),n=(r=s.sessionProperties)==null?void 0:r.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(i=s.sessionProperties)==null?void 0:i.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}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,r){var i;const s=new URL(e),n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ht("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,r){return`${ID}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}}var pS=Object.defineProperty,fS=(t,e,r)=>e in t?pS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Cr=(t,e,r)=>fS(t,typeof e!="symbol"?e+"":e,r);class gS{constructor(e){Cr(this,"name","solana"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var yS=Object.defineProperty,mS=(t,e,r)=>e in t?yS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tr=(t,e,r)=>mS(t,typeof e!="symbol"?e+"":e,r);class wS{constructor(e){Tr(this,"name","cosmos"),Tr(this,"client"),Tr(this,"httpProviders"),Tr(this,"events"),Tr(this,"namespace"),Tr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var bS=Object.defineProperty,vS=(t,e,r)=>e in t?bS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rr=(t,e,r)=>vS(t,typeof e!="symbol"?e+"":e,r);class ES{constructor(e){Rr(this,"name","algorand"),Rr(this,"client"),Rr(this,"httpProviders"),Rr(this,"events"),Rr(this,"namespace"),Rr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(!this.httpProviders[e]){const i=r||Ge(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var _S=Object.defineProperty,IS=(t,e,r)=>e in t?_S(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nr=(t,e,r)=>IS(t,typeof e!="symbol"?e+"":e,r);class $S{constructor(e){Nr(this,"name","cip34"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{const i=this.getCardanoRPCUrl(r),s=wr(r);e[s]=this.createHttpProvider(s,i)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}getCardanoRPCUrl(e){const r=this.namespace.rpcMap;if(r)return r[e]}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||this.getCardanoRPCUrl(e);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var DS=Object.defineProperty,SS=(t,e,r)=>e in t?DS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Br=(t,e,r)=>SS(t,typeof e!="symbol"?e+"":e,r);class OS{constructor(e){Br(this,"name","elrond"),Br(this,"client"),Br(this,"httpProviders"),Br(this,"events"),Br(this,"namespace"),Br(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var PS=Object.defineProperty,AS=(t,e,r)=>e in t?PS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jr=(t,e,r)=>AS(t,typeof e!="symbol"?e+"":e,r);class xS{constructor(e){jr(this,"name","multiversx"),jr(this,"client"),jr(this,"httpProviders"),jr(this,"events"),jr(this,"namespace"),jr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const s=wr(r);e[s]=this.createHttpProvider(s,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var CS=Object.defineProperty,TS=(t,e,r)=>e in t?CS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ur=(t,e,r)=>TS(t,typeof e!="symbol"?e+"":e,r);class RS{constructor(e){Ur(this,"name","near"),Ur(this,"client"),Ur(this,"httpProviders"),Ur(this,"events"),Ur(this,"namespace"),Ur(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;e[r]=this.createHttpProvider(r,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i,Q("disableProviderPing")))}}var NS=Object.defineProperty,BS=(t,e,r)=>e in t?NS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fr=(t,e,r)=>BS(t,typeof e!="symbol"?e+"":e,r);class jS{constructor(e){Fr(this,"name","tezos"),Fr(this,"client"),Fr(this,"httpProviders"),Fr(this,"events"),Fr(this,"namespace"),Fr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}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]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,r){if(this.chainId=e,!this.httpProviders[e]){const i=r||Ge(`${this.name}:${e}`,this.namespace);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,i)}this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{e[r]=this.createHttpProvider(r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace);return typeof i>"u"?void 0:new it(new dt(i))}}var US=Object.defineProperty,FS=(t,e,r)=>e in t?US(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lr=(t,e,r)=>FS(t,typeof e!="symbol"?e+"":e,r);class LS{constructor(e){Lr(this,"name",Mr),Lr(this,"client"),Lr(this,"httpProviders"),Lr(this,"events"),Lr(this,"namespace"),Lr(this,"chainId"),this.namespace=e.namespace,this.events=Q("events"),this.client=Q("client"),this.chainId=this.getDefaultChain(),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,r){this.httpProviders[e]||this.setHttpProvider(e,r),this.chainId=e,this.events.emit(st.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}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]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(s=>{const n=Vr(s);i[`${n.namespace}:${n.reference}`]=this.createHttpProvider(s)}),i}getHttpProvider(e){const r=this.httpProviders[e];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||Ge(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new it(new dt(i,Q("disableProviderPing")))}}var kS=Object.defineProperty,MS=Object.defineProperties,qS=Object.getOwnPropertyDescriptors,Jh=Object.getOwnPropertySymbols,zS=Object.prototype.hasOwnProperty,HS=Object.prototype.propertyIsEnumerable,Io=(t,e,r)=>e in t?kS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hs=(t,e)=>{for(var r in e||(e={}))zS.call(e,r)&&Io(t,r,e[r]);if(Jh)for(var r of Jh(e))HS.call(e,r)&&Io(t,r,e[r]);return t},Bn=(t,e)=>MS(t,qS(e)),Qe=(t,e,r)=>Io(t,typeof e!="symbol"?e+"":e,r);let VS=class $d{constructor(e){Qe(this,"client"),Qe(this,"namespaces"),Qe(this,"optionalNamespaces"),Qe(this,"sessionProperties"),Qe(this,"scopedProperties"),Qe(this,"events",new Do),Qe(this,"rpcProviders",{}),Qe(this,"session"),Qe(this,"providerOpts"),Qe(this,"logger"),Qe(this,"uri"),Qe(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof(e==null?void 0:e.logger)<"u"&&typeof(e==null?void 0:e.logger)!="string"?e.logger:Vi(qs({level:(e==null?void 0:e.logger)||Fh})),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new $d(e);return await r.initialize(),r}async request(e,r,i){const[s,n]=this.validateChain(r);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:hs({},e),chainId:`${s}:${n}`,topic:this.session.topic,expiry:i})}sendAsync(e,r,i,s){const n=new Date().getTime();this.request(e,i,s).then(o=>r(null,zs(n,o))).catch(o=>r(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:te("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:s}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const n=await s();if(this.session=n.session,this.session){const o=Kh(this.session.namespaces);this.namespaces=cs(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){const{uri:r,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});r&&(this.uri=r,this.events.emit("display_uri",r));const s=await i();this.session=s;const n=Kh(s.namespaces);return this.namespaces=cs(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,r){try{if(!this.session)return;const[i,s]=this.validateChain(e),n=this.getProvider(i);n.name===Mr?n.setDefaultChain(`${i}:${s}`,r):n.setDefaultChain(s,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(ut(r)){for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}}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,r;if(this.client=this.providerOpts.client||await uD.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Fh,relayUrl:this.providerOpts.relayUrl||vD,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(i){throw this.logger.error("Failed to get session",i),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[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(r=>zr(r)))];Nn("client",this.client),Nn("events",this.events),Nn("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=iS(r,this.session),s=_d(i),n=cs(this.namespaces,this.optionalNamespaces),o=Bn(hs({},n[r]),{accounts:i,chains:s});switch(r){case"eip155":this.rpcProviders[r]=new dS({namespace:o});break;case"algorand":this.rpcProviders[r]=new ES({namespace:o});break;case"solana":this.rpcProviders[r]=new gS({namespace:o});break;case"cosmos":this.rpcProviders[r]=new wS({namespace:o});break;case"polkadot":this.rpcProviders[r]=new oS({namespace:o});break;case"cip34":this.rpcProviders[r]=new $S({namespace:o});break;case"elrond":this.rpcProviders[r]=new OS({namespace:o});break;case"multiversx":this.rpcProviders[r]=new xS({namespace:o});break;case"near":this.rpcProviders[r]=new RS({namespace:o});break;case"tezos":this.rpcProviders[r]=new jS({namespace:o});break;default:this.rpcProviders[Mr]?this.rpcProviders[Mr].updateNamespace(o):this.rpcProviders[Mr]=new LS({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:s}=e;if(s!==((r=this.session)==null?void 0:r.topic))return;const{event:n}=i;if(n.name==="accountsChanged"){const o=n.data;o&&ut(o)&&this.events.emit("accountsChanged",o.map(Vh))}else if(n.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=zr(o),h=Rn(o)!==Rn(a)?`${c}:${Rn(a)}`:o;this.onChainChanged(h)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:r})=>{var i,s;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:n}=r,o=(s=this.client)==null?void 0:s.session.get(e);this.session=Bn(hs({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",Bn(hs({},te("USER_DISCONNECTED")),{data:e.topic})))}),this.on(st.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Mr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:n}=e;this.optionalNamespaces=cs(r,i),this.sessionProperties=s,this.scopedProperties=n}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>zr(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const s=zr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[s].getDefaultChain();return[s,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,r=!1){if(!this.namespaces)return;const[i,s]=this.validateChain(e);if(!s)return;this.updateNamespaceChain(i,s),this.events.emit("chainChanged",s);const n=this.getProvider(i).getDefaultChain();r||this.getProvider(i).setDefaultChain(s),this.emitAccountsChangedOnChainChange({namespace:i,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:r,newChainId:i}){var s,n;try{if(r===i)return;const o=(n=(s=this.session)==null?void 0:s.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(Vh);if(!ut(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,s={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,r){var i;const s=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${os}/${e}${s}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${os}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${os}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const i of r)i.startsWith(os)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn("Failed to cleanup storage",r)}}};const KS=VS,WS="wc",GS="ethereum_provider",YS=`${WS}@2:${GS}:`,JS="https://rpc.walletconnect.org/v1/",Os=["eth_sendTransaction","personal_sign"],Dd=["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_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],Ps=["chainChanged","accountsChanged"],Sd=["chainChanged","accountsChanged","message","disconnect","connect"],ZS=async()=>{const{createAppKit:t}=await el(()=>import("./core-tNZO_nnA.js").then(e=>e.r),__vite__mapDeps([4,1,2,3,5]));return t};var QS=Object.defineProperty,XS=Object.defineProperties,eO=Object.getOwnPropertyDescriptors,Zh=Object.getOwnPropertySymbols,tO=Object.prototype.hasOwnProperty,rO=Object.prototype.propertyIsEnumerable,$o=(t,e,r)=>e in t?QS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Xt=(t,e)=>{for(var r in e||(e={}))tO.call(e,r)&&$o(t,r,e[r]);if(Zh)for(var r of Zh(e))rO.call(e,r)&&$o(t,r,e[r]);return t},wi=(t,e)=>XS(t,eO(e)),ze=(t,e,r)=>$o(t,typeof e!="symbol"?e+"":e,r);function As(t){return Number(t[0].split(":")[1])}function ls(t){return`0x${t.toString(16)}`}function iO(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:s,events:n,optionalEvents:o,rpcMap:a}=t;if(!ut(e))throw new Error("Invalid chains");const c={chains:e,methods:i||Os,events:n||Ps,rpcMap:Xt({},e.length?{[As(e)]:a[As(e)]}:{})},h=n==null?void 0:n.filter(f=>!Ps.includes(f)),l=i==null?void 0:i.filter(f=>!Os.includes(f));if(!r&&!o&&!s&&!(h!=null&&h.length)&&!(l!=null&&l.length))return{required:e.length?c:void 0};const u=(h==null?void 0:h.length)&&(l==null?void 0:l.length)||!r,d={chains:[...new Set(u?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(s!=null&&s.length?s:Dd))],events:[...new Set(c.events.concat(o!=null&&o.length?o:Sd))],rpcMap:a};return{required:e.length?c:void 0,optional:r.length?d:void 0}}class Gs{constructor(){ze(this,"events",new rt.EventEmitter),ze(this,"namespace","eip155"),ze(this,"accounts",[]),ze(this,"signer"),ze(this,"chainId",1),ze(this,"modal"),ze(this,"rpc"),ze(this,"STORAGE_KEY",YS),ze(this,"on",(e,r)=>(this.events.on(e,r),this)),ze(this,"once",(e,r)=>(this.events.once(e,r),this)),ze(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ze(this,"off",(e,r)=>(this.events.off(e,r),this)),ze(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new Gs;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:s}=iO(this.rpc);try{const n=await new Promise(async(a,c)=>{var h,l;this.rpc.showQrModal&&((h=this.modal)==null||h.open(),(l=this.modal)==null||l.subscribeState(d=>{!d.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const u=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(wi(Xt({namespaces:Xt({},i&&{[this.namespace]:i})},s&&{optionalNamespaces:{[this.namespace]:s}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:u})).then(d=>{a(d)}).catch(d=>{var f;(f=this.modal)==null||f.showErrorMessage("Unable to connect"),c(new Error(d.message))})});if(!n)return;const o=Wa(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const s=await new Promise(async(o,a)=>{var c,h;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(h=this.modal)==null||h.subscribeState(l=>{!l.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(wi(Xt({},e),{chains:this.rpc.chains}),r).then(l=>{o(l)}).catch(l=>{var u;(u=this.modal)==null||u.showErrorMessage("Unable to connect"),a(new Error(l.message))})}),n=s.session;if(n){const o=Wa(n.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}return s}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const r=parseInt(e);this.chainId=r,this.events.emit("chainChanged",ls(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",wi(Xt({},te("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ls(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,s]=e.split(":");return{chainId:`${r}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const s=(r=e==null?void 0:e.chains)!=null?r:[],n=(i=e==null?void 0:e.optionalChains)!=null?i:[],o=s.concat(n);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=s.length?(e==null?void 0:e.methods)||Os:[],c=s.length?(e==null?void 0:e.events)||Ps:[],h=(e==null?void 0:e.optionalMethods)||[],l=(e==null?void 0:e.optionalEvents)||[],u=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),d=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:s==null?void 0:s.map(f=>this.formatChainId(f)),optionalChains:n.map(f=>this.formatChainId(f)),methods:a,events:c,optionalMethods:h,optionalEvents:l,rpcMap:u,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:d,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,r){const i={};return e.forEach(s=>{i[s]=this.getRpcUrl(s,r)}),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?As(this.rpc.chains):As(this.rpc.optionalChains),this.signer=await KS.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const i=await ZS(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return fO}),n=s(wi(Xt({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!n.networks.length)throw new Error("No networks found for WalletConnect·");r=i(wi(Xt({},n),{universalProvider:this.signer,manualWCControl:!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:s}=e;r&&ut(r)&&(this.rpc.chains=r.map(n=>this.formatChainId(n)),r.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)})),i&&ut(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(n=>this.formatChainId(n)),i.forEach(n=>{this.rpc.rpcMap[n]=(s==null?void 0:s[n])||this.getRpcUrl(n)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${JS}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(r=>this.parseAccount(r))}}const sO=Gs;var nO=Object.defineProperty,oO=Object.defineProperties,aO=Object.getOwnPropertyDescriptors,Qh=Object.getOwnPropertySymbols,cO=Object.prototype.hasOwnProperty,hO=Object.prototype.propertyIsEnumerable,Xh=(t,e,r)=>e in t?nO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Od=(t,e)=>{for(var r in e||(e={}))cO.call(e,r)&&Xh(t,r,e[r]);if(Qh)for(var r of Qh(e))hO.call(e,r)&&Xh(t,r,e[r]);return t},lO=(t,e)=>oO(t,aO(e));function uO(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const dO=t=>{const[e,r]=t.split(":");return Pd({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function pO(t){var e,r,i,s,n,o,a;const c=(e=t.chains)==null?void 0:e.map(dO).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const h=c.find(u=>{var d;return u.id===((d=t.defaultChain)==null?void 0:d.id)}),l={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:uO(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:h,metadata:lO(Od({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.description)||"Connect to WalletConnect-compatible wallets",url:((s=t.metadata)==null?void 0:s.url)||"https://walletconnect.org",icons:((n=t.metadata)==null?void 0:n.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const u=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],d=[...l.featuredWalletIds||[],...l.excludeWalletIds||[]],f=u.filter(p=>!d.includes(p.id));f.length&&(l.customWallets=f)}return l}function Pd(t){return Od({formatters:void 0,fees:void 0,serializers:void 0},t)}var fO=Object.freeze({__proto__:null,convertWCMToAppKitOptions:pO,defineChain:Pd});const nP=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:sO,OPTIONAL_EVENTS:Sd,OPTIONAL_METHODS:Dd,REQUIRED_EVENTS:Ps,REQUIRED_METHODS:Os,default:Gs},Symbol.toStringTag,{value:"Module"}));export{pE as A,Ko as B,vw as C,Vs as D,Ne as E,bt as F,qs as G,df as H,gr as I,it as J,wt as K,yr as L,EO as M,Pf as N,Vi as O,Ha as P,Wl as Q,bO as R,hr as S,jt as T,Kn as U,fl as V,ke as W,pf as X,Me as Y,Im as a,xs as b,ba as c,mO as d,tf as e,Cf as f,N as g,Ei as h,vO as i,wO as j,Jd as k,e_ as l,dt as m,Hs as n,Ht as o,zs as p,tt as q,nr as r,ar as s,nl as t,So as u,ol as v,L1 as w,l1 as x,nP as y,et as z};