@dodoex/wallet-web3 0.6.3 → 0.6.5

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 (217) hide show
  1. package/dist/PhArrowCircleDown-4a08ae8e.js +14 -0
  2. package/dist/PhArrowClockwise-401ea1c0.js +14 -0
  3. package/dist/PhArrowDown-789ae7d2.js +14 -0
  4. package/dist/PhArrowLeft-2e6d4940.js +14 -0
  5. package/dist/PhArrowRight-2928b0dc.js +14 -0
  6. package/dist/PhArrowSquareOut-17d61d08.js +14 -0
  7. package/dist/PhArrowUp-1cfcf9df.js +14 -0
  8. package/dist/PhArrowUpRight-552c41cb.js +14 -0
  9. package/dist/PhArrowsClockwise-92a70162.js +14 -0
  10. package/dist/PhArrowsDownUp-ce27c8a7.js +14 -0
  11. package/dist/PhArrowsLeftRight-ed549dc7.js +14 -0
  12. package/dist/PhBank-92a1a1df.js +14 -0
  13. package/dist/PhBrowser-495dc3ce.js +14 -0
  14. package/dist/PhCaretDown-610f20fc.js +14 -0
  15. package/dist/PhCaretLeft-2a86ee53.js +14 -0
  16. package/dist/PhCaretRight-f3057f58.js +14 -0
  17. package/dist/PhCaretUp-7b74b8cb.js +14 -0
  18. package/dist/PhCheck-c514f32c.js +14 -0
  19. package/dist/PhCircleHalf-3bfd24c9.js +14 -0
  20. package/dist/PhClock-29284ead.js +14 -0
  21. package/dist/PhCompass-101d3241.js +14 -0
  22. package/dist/PhCopy-d92dcd27.js +14 -0
  23. package/dist/PhCreditCard-d8d77fc2.js +14 -0
  24. package/dist/PhCurrencyDollar-6553df79.js +14 -0
  25. package/dist/PhDesktop-91653c8e.js +14 -0
  26. package/dist/PhDeviceMobile-0f3d8fa2.js +14 -0
  27. package/dist/PhDotsThree-67debca2.js +14 -0
  28. package/dist/PhEnvelope-f83faab2.js +14 -0
  29. package/dist/PhFunnelSimple-5058af43.js +14 -0
  30. package/dist/PhGlobe-c4653621.js +14 -0
  31. package/dist/PhIdentificationCard-848bf9a1.js +14 -0
  32. package/dist/PhImage-de71fc6b.js +14 -0
  33. package/dist/PhInfo-9614a766.js +14 -0
  34. package/dist/PhLightbulb-7d582ae7.js +14 -0
  35. package/dist/PhMagnifyingGlass-c926bd63.js +14 -0
  36. package/dist/PhPaperPlaneRight-76b25832.js +14 -0
  37. package/dist/PhPlus-767ddc55.js +14 -0
  38. package/dist/PhPower-95f188dd.js +14 -0
  39. package/dist/PhPuzzlePiece-f016afe5.js +14 -0
  40. package/dist/PhQrCode-e9b7ab93.js +14 -0
  41. package/dist/PhQuestion-ea0e639d.js +14 -0
  42. package/dist/PhQuestionMark-13d6338e.js +14 -0
  43. package/dist/PhSealCheck-45bb7b9c.js +14 -0
  44. package/dist/PhSignOut-6b91c59c.js +14 -0
  45. package/dist/PhSpinner-eb9b7ac1.js +14 -0
  46. package/dist/PhTrash-758cc3b3.js +14 -0
  47. package/dist/PhUser-0834861d.js +14 -0
  48. package/dist/PhVault-e4d6f9af.js +14 -0
  49. package/dist/PhWallet-5e257abe.js +14 -0
  50. package/dist/PhWarning-6af3740e.js +14 -0
  51. package/dist/PhWarningCircle-a78fd8e8.js +14 -0
  52. package/dist/PhX-60c46532.js +14 -0
  53. package/dist/{__tslib-2b1b6d17.js → __tslib-6d6a586c.js} +1 -1
  54. package/dist/{alchemy-provider-5870b6fa-b23243a1.js → alchemy-provider-5870b6fa-a9fe5aa5.js} +1 -1
  55. package/dist/{alchemy-websocket-provider-213da986-559da73b.js → alchemy-websocket-provider-213da986-16164c2e.js} +1 -1
  56. package/dist/basic-77fe1b96.js +1320 -0
  57. package/dist/{blocto-8e69bccf.js → blocto-ab8ba330.js} +1 -1
  58. package/dist/{ccip-99b4ad16.js → ccip-e246f9cf.js} +1 -1
  59. package/dist/cjs/PhArrowCircleDown-df23d036.cjs +14 -0
  60. package/dist/cjs/PhArrowClockwise-440d23dc.cjs +14 -0
  61. package/dist/cjs/PhArrowDown-252590ed.cjs +14 -0
  62. package/dist/cjs/PhArrowLeft-d480faa4.cjs +14 -0
  63. package/dist/cjs/PhArrowRight-969dbdd8.cjs +14 -0
  64. package/dist/cjs/PhArrowSquareOut-eabfdecb.cjs +14 -0
  65. package/dist/cjs/PhArrowUp-66bd5f15.cjs +14 -0
  66. package/dist/cjs/PhArrowUpRight-6df3b31b.cjs +14 -0
  67. package/dist/cjs/PhArrowsClockwise-3a9d2dc6.cjs +14 -0
  68. package/dist/cjs/PhArrowsDownUp-47a7788f.cjs +14 -0
  69. package/dist/cjs/PhArrowsLeftRight-f90368dd.cjs +14 -0
  70. package/dist/cjs/PhBank-670a2708.cjs +14 -0
  71. package/dist/cjs/PhBrowser-b9c35fd1.cjs +14 -0
  72. package/dist/cjs/PhCaretDown-11a46455.cjs +14 -0
  73. package/dist/cjs/PhCaretLeft-04f11ca7.cjs +14 -0
  74. package/dist/cjs/PhCaretRight-391111c1.cjs +14 -0
  75. package/dist/cjs/PhCaretUp-b17dccf6.cjs +14 -0
  76. package/dist/cjs/PhCheck-08bf36b0.cjs +14 -0
  77. package/dist/cjs/PhCircleHalf-0a9eac35.cjs +14 -0
  78. package/dist/cjs/PhClock-cf1cc2cb.cjs +14 -0
  79. package/dist/cjs/PhCompass-e9671b30.cjs +14 -0
  80. package/dist/cjs/PhCopy-9132cbc5.cjs +14 -0
  81. package/dist/cjs/PhCreditCard-853e1556.cjs +14 -0
  82. package/dist/cjs/PhCurrencyDollar-34eea829.cjs +14 -0
  83. package/dist/cjs/PhDesktop-c02b883b.cjs +14 -0
  84. package/dist/cjs/PhDeviceMobile-93c2088c.cjs +14 -0
  85. package/dist/cjs/PhDotsThree-69beaba7.cjs +14 -0
  86. package/dist/cjs/PhEnvelope-86ee730e.cjs +14 -0
  87. package/dist/cjs/PhFunnelSimple-056c2f76.cjs +14 -0
  88. package/dist/cjs/PhGlobe-64c4ee8e.cjs +14 -0
  89. package/dist/cjs/PhIdentificationCard-ec7a98e0.cjs +14 -0
  90. package/dist/cjs/PhImage-07904cbb.cjs +14 -0
  91. package/dist/cjs/PhInfo-34eeeace.cjs +14 -0
  92. package/dist/cjs/PhLightbulb-39ebe854.cjs +14 -0
  93. package/dist/cjs/PhMagnifyingGlass-2fbe4400.cjs +14 -0
  94. package/dist/cjs/PhPaperPlaneRight-e06c210f.cjs +14 -0
  95. package/dist/cjs/PhPlus-03a04ed3.cjs +14 -0
  96. package/dist/cjs/PhPower-4cc2ecb8.cjs +14 -0
  97. package/dist/cjs/PhPuzzlePiece-035d561e.cjs +14 -0
  98. package/dist/cjs/PhQrCode-37e23b36.cjs +14 -0
  99. package/dist/cjs/PhQuestion-bfba435e.cjs +14 -0
  100. package/dist/cjs/PhQuestionMark-8ef38ecf.cjs +14 -0
  101. package/dist/cjs/PhSealCheck-5458de15.cjs +14 -0
  102. package/dist/cjs/PhSignOut-2d177ea1.cjs +14 -0
  103. package/dist/cjs/PhSpinner-e7c590df.cjs +14 -0
  104. package/dist/cjs/PhTrash-1920f5dc.cjs +14 -0
  105. package/dist/cjs/PhUser-84a1a685.cjs +14 -0
  106. package/dist/cjs/PhVault-1493c03f.cjs +14 -0
  107. package/dist/cjs/PhWallet-f0502f03.cjs +14 -0
  108. package/dist/cjs/PhWarning-1bf637ba.cjs +14 -0
  109. package/dist/cjs/PhWarningCircle-b1747661.cjs +14 -0
  110. package/dist/cjs/PhX-f864d86c.cjs +14 -0
  111. package/dist/cjs/{__tslib-91c50e46.cjs → __tslib-a9f27ba6.cjs} +1 -1
  112. package/dist/cjs/{alchemy-provider-5870b6fa-a824dbf0.cjs → alchemy-provider-5870b6fa-bb1c607e.cjs} +1 -1
  113. package/dist/cjs/{alchemy-websocket-provider-213da986-f96378c8.cjs → alchemy-websocket-provider-213da986-521569b5.cjs} +1 -1
  114. package/dist/cjs/basic-b777d2b1.cjs +1320 -0
  115. package/dist/cjs/{blocto-255deb25.cjs → blocto-09e0d574.cjs} +1 -1
  116. package/dist/cjs/{ccip-58f4c3ce.cjs → ccip-6ebee1cf.cjs} +1 -1
  117. package/dist/cjs/core-78a709db.cjs +210 -0
  118. package/dist/cjs/{draggabilly-b00ba129.cjs → draggabilly-76af6217.cjs} +1 -1
  119. package/dist/cjs/features-fa5c5622.cjs +1 -0
  120. package/dist/cjs/id-c0538166.cjs +1 -0
  121. package/dist/cjs/{index-4cb4044e.cjs → index-07e81389.cjs} +1 -1
  122. package/dist/cjs/{index-28fe8dc2.cjs → index-093cef5a.cjs} +2 -2
  123. package/dist/cjs/{index-0f3e4a4a.cjs → index-208df3f3.cjs} +1 -1
  124. package/dist/cjs/{index-9cbeb66d.cjs → index-253e7cce.cjs} +1 -1
  125. package/dist/cjs/index-2e8e7a50.cjs +4 -0
  126. package/dist/cjs/index-395b933d.cjs +2 -0
  127. package/dist/cjs/{index-b0eb86b6.cjs → index-54d7fc75.cjs} +1 -1
  128. package/dist/cjs/{index-5d1879f6.cjs → index-5d28acf4.cjs} +3 -3
  129. package/dist/cjs/{index-02043814.cjs → index-5dac528b.cjs} +4 -4
  130. package/dist/cjs/index-702e8f89.cjs +15 -0
  131. package/dist/cjs/{index-7d213984.cjs → index-823e17e6.cjs} +1 -1
  132. package/dist/cjs/{index-2c339ec0.cjs → index-916994aa.cjs} +1 -1
  133. package/dist/cjs/{index-96c22872.cjs → index-a2b665f4.cjs} +1 -1
  134. package/dist/cjs/{index-110f55af.cjs → index-b099293c.cjs} +1 -1
  135. package/dist/cjs/index-d72ddbc1.cjs +17 -0
  136. package/dist/cjs/index-ef4ef0cc.cjs +1449 -0
  137. package/dist/cjs/index.cjs +1 -1
  138. package/dist/cjs/{interface-a67cd05c.cjs → interface-4947cfa6.cjs} +1 -1
  139. package/dist/cjs/lib-typedarrays-a9baf142.cjs +1 -0
  140. package/dist/cjs/native-55bb141d.cjs +1 -0
  141. package/dist/cjs/{portis-ec737dc5.cjs → portis-08d9d731.cjs} +1 -1
  142. package/dist/cjs/property-29e6f732.cjs +29 -0
  143. package/dist/cjs/providers/connector/safeGnosis/query.d.ts +2 -1
  144. package/dist/cjs/providers/connector/types.d.ts +1 -1
  145. package/dist/cjs/providers/wallets/index.d.ts +1 -0
  146. package/dist/cjs/rainbow-6e84bcfa.cjs +1 -0
  147. package/dist/cjs/sha224-b46bc3e6.cjs +1 -0
  148. package/dist/cjs/sha256-ccd47519.cjs +1 -0
  149. package/dist/cjs/{typed-data-65a82f1e.cjs → typed-data-5176b792.cjs} +1 -1
  150. package/dist/cjs/uAuth-b29d2670.cjs +1 -0
  151. package/dist/cjs/w3m-modal-70bcf6d8.cjs +2380 -0
  152. package/dist/cjs/walletConnect-20d477a9.cjs +1 -0
  153. package/dist/cjs/{walletLink-095edc5f.cjs → walletLink-08b8da20.cjs} +2 -2
  154. package/dist/core-4d7ad6f2.js +210 -0
  155. package/dist/{draggabilly-919fe798.js → draggabilly-daf3b444.js} +1 -1
  156. package/dist/features-d8d1c9ce.js +1 -0
  157. package/dist/id-d4d22b29.js +1 -0
  158. package/dist/{index-de7476e4.js → index-09298bd0.js} +7 -7
  159. package/dist/{index-085a063c.js → index-244a8189.js} +1 -1
  160. package/dist/{index-23ae718c.js → index-2ad0fb2a.js} +1 -1
  161. package/dist/index-35d87b79.js +17 -0
  162. package/dist/{index-bbaf7a43.js → index-587ff998.js} +1 -1
  163. package/dist/{index-601a6250.js → index-750a7dfe.js} +1 -1
  164. package/dist/{index-cc764016.js → index-8bd12de1.js} +1 -1
  165. package/dist/{index-6382b40b.js → index-938686fb.js} +1 -1
  166. package/dist/{index-3cf73206.js → index-9d7fee1e.js} +2 -2
  167. package/dist/{index-fd3058aa.js → index-aa744ca0.js} +1 -1
  168. package/dist/{index-7fabb817.js → index-b7d25e8a.js} +3 -3
  169. package/dist/index-bb1a0019.js +15 -0
  170. package/dist/index-c5ca8a4e.js +4 -0
  171. package/dist/{index-f5d95949.js → index-cddbc8e8.js} +1 -1
  172. package/dist/index-f095c09e.js +2 -0
  173. package/dist/index-ffdf981b.js +1449 -0
  174. package/dist/index.js +1 -1
  175. package/dist/{interface-82bdcddb.js → interface-0c535796.js} +1 -1
  176. package/dist/lib-typedarrays-979d2723.js +1 -0
  177. package/dist/native-029c50f7.js +1 -0
  178. package/dist/{portis-0a2bd95e.js → portis-9602ac9f.js} +1 -1
  179. package/dist/property-8eb37909.js +35 -0
  180. package/dist/providers/connector/safeGnosis/query.d.ts +2 -1
  181. package/dist/providers/connector/types.d.ts +1 -1
  182. package/dist/providers/wallets/index.d.ts +1 -0
  183. package/dist/rainbow-ccab7a95.js +1 -0
  184. package/dist/sha224-fe98e1bf.js +1 -0
  185. package/dist/sha256-5a24dfd5.js +1 -0
  186. package/dist/{typed-data-83d7ae9a.js → typed-data-3a3d44dc.js} +1 -1
  187. package/dist/uAuth-27f5728d.js +1 -0
  188. package/dist/w3m-modal-49add722.js +2380 -0
  189. package/dist/walletConnect-a541881e.js +1 -0
  190. package/dist/{walletLink-1b3cb067.js → walletLink-67264328.js} +2 -2
  191. package/package.json +5 -5
  192. package/dist/_commonjs-dynamic-modules-7cfc9805.js +0 -1
  193. package/dist/cjs/_commonjs-dynamic-modules-f09a98c7.cjs +0 -1
  194. package/dist/cjs/id-0c26cee0.cjs +0 -1
  195. package/dist/cjs/index-21f86827.cjs +0 -17
  196. package/dist/cjs/index-35edc6a0.cjs +0 -60
  197. package/dist/cjs/index-568647cf.cjs +0 -15
  198. package/dist/cjs/index-9f2a69d5.cjs +0 -1
  199. package/dist/cjs/index.es-2a36620f.cjs +0 -9
  200. package/dist/cjs/lib-typedarrays-f921c603.cjs +0 -1
  201. package/dist/cjs/rainbow-322fb6a9.cjs +0 -1
  202. package/dist/cjs/sha224-f0657d8a.cjs +0 -1
  203. package/dist/cjs/sha256-a0c6063a.cjs +0 -1
  204. package/dist/cjs/uAuth-d389b45d.cjs +0 -1
  205. package/dist/cjs/walletConnect-3c32ceb8.cjs +0 -1
  206. package/dist/id-bc1ef47c.js +0 -1
  207. package/dist/index-24d19ee3.js +0 -15
  208. package/dist/index-65d96278.js +0 -60
  209. package/dist/index-e4c02dc7.js +0 -17
  210. package/dist/index-f08d6a6b.js +0 -1
  211. package/dist/index.es-474ba2f2.js +0 -9
  212. package/dist/lib-typedarrays-becaa8ad.js +0 -1
  213. package/dist/rainbow-aa24fa3b.js +0 -1
  214. package/dist/sha224-e9d5a920.js +0 -1
  215. package/dist/sha256-65d6895c.js +0 -1
  216. package/dist/uAuth-8aef513a.js +0 -1
  217. package/dist/walletConnect-f12ca9e1.js +0 -1
@@ -0,0 +1,4 @@
1
+ import e,{EventEmitter as t}from"events";import{r as i}from"./__tslib-6d6a586c.js";import{c as s,O as r}from"./index-09298bd0.js";var n=function(e,t,i){if(i||2===arguments.length)for(var s,r=0,n=t.length;r<n;r++)!s&&r in t||(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))},o=function(e,t,i){this.name=e,this.version=t,this.os=i,this.type="browser"},a=function(e){this.version=e,this.type="node",this.name="node",this.os=process.platform},c=function(e,t,i,s){this.name=e,this.version=t,this.os=i,this.bot=s,this.type="bot-device"},h=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},l=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},u=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,d=3,f=[["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",/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/]],p=[["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 g(e){return e?y(e):"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new l:"undefined"!=typeof navigator?y(navigator.userAgent):"undefined"!=typeof process&&process.version?new a(process.version.slice(1)):null}function y(e){var t=function(e){return""!==e&&f.reduce((function(t,i){var s=i[0],r=i[1];if(t)return t;var n=r.exec(e);return!!n&&[s,n]}),!1)}(e);if(!t)return null;var i=t[0],s=t[1];if("searchbot"===i)return new h;var r=s[1]&&s[1].split(".").join("_").split("_").slice(0,3);r?r.length<d&&(r=n(n([],r,!0),function(e){for(var t=[],i=0;i<e;i++)t.push("0");return t}(d-r.length),!0)):r=[];var a=r.join("."),l=function(e){for(var t=0,i=p.length;t<i;t++){var s=p[t],r=s[0];if(s[1].exec(e))return r}return null}(e),g=u.exec(e);return g&&g[1]?new c(i,a,l,g[1]):new o(i,a,l)}var w,m={},b={},v={};var E,x={},I={},S={};var O,_,A,P,T={};function B(){return _||(_=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=i;t.__exportStar((E||(E=1,Object.defineProperty(S,"__esModule",{value:!0}),S.ONE_THOUSAND=S.ONE_HUNDRED=void 0,S.ONE_HUNDRED=100,S.ONE_THOUSAND=1e3),S),e),t.__exportStar(function(){return O||(O=1,e=T,Object.defineProperty(e,"__esModule",{value:!0}),e.ONE_YEAR=e.FOUR_WEEKS=e.THREE_WEEKS=e.TWO_WEEKS=e.ONE_WEEK=e.THIRTY_DAYS=e.SEVEN_DAYS=e.FIVE_DAYS=e.THREE_DAYS=e.ONE_DAY=e.TWENTY_FOUR_HOURS=e.TWELVE_HOURS=e.SIX_HOURS=e.THREE_HOURS=e.ONE_HOUR=e.SIXTY_MINUTES=e.THIRTY_MINUTES=e.TEN_MINUTES=e.FIVE_MINUTES=e.ONE_MINUTE=e.SIXTY_SECONDS=e.THIRTY_SECONDS=e.TEN_SECONDS=e.FIVE_SECONDS=e.ONE_SECOND=void 0,e.ONE_SECOND=1,e.FIVE_SECONDS=5,e.TEN_SECONDS=10,e.THIRTY_SECONDS=30,e.SIXTY_SECONDS=60,e.ONE_MINUTE=e.SIXTY_SECONDS,e.FIVE_MINUTES=5*e.ONE_MINUTE,e.TEN_MINUTES=10*e.ONE_MINUTE,e.THIRTY_MINUTES=30*e.ONE_MINUTE,e.SIXTY_MINUTES=60*e.ONE_MINUTE,e.ONE_HOUR=e.SIXTY_MINUTES,e.THREE_HOURS=3*e.ONE_HOUR,e.SIX_HOURS=6*e.ONE_HOUR,e.TWELVE_HOURS=12*e.ONE_HOUR,e.TWENTY_FOUR_HOURS=24*e.ONE_HOUR,e.ONE_DAY=e.TWENTY_FOUR_HOURS,e.THREE_DAYS=3*e.ONE_DAY,e.FIVE_DAYS=5*e.ONE_DAY,e.SEVEN_DAYS=7*e.ONE_DAY,e.THIRTY_DAYS=30*e.ONE_DAY,e.ONE_WEEK=e.SEVEN_DAYS,e.TWO_WEEKS=2*e.ONE_WEEK,e.THREE_WEEKS=3*e.ONE_WEEK,e.FOUR_WEEKS=4*e.ONE_WEEK,e.ONE_YEAR=365*e.ONE_DAY),T;var e}(),e)}(I)),I}function R(){return P||(P=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=i;t.__exportStar((w||(w=1,Object.defineProperty(v,"__esModule",{value:!0}),v.delay=void 0,v.delay=function(e){return new Promise((t=>{setTimeout((()=>{t(!0)}),e)}))}),v),e),t.__exportStar(function(){if(A)return x;A=1,Object.defineProperty(x,"__esModule",{value:!0}),x.fromMiliseconds=x.toMiliseconds=void 0;const e=B();return x.toMiliseconds=function(t){return t*e.ONE_THOUSAND},x.fromMiliseconds=function(t){return Math.floor(t/e.ONE_THOUSAND)},x}(),e)}(b)),b}var N,C={};var U,k,L={},q={};function D(){return k||(k=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});i.__exportStar((U||(U=1,Object.defineProperty(q,"__esModule",{value:!0}),q.IWatch=void 0,q.IWatch=class{}),q),e)}(L)),L}!function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=i;t.__exportStar(R(),e),t.__exportStar(function(){if(N)return C;N=1,Object.defineProperty(C,"__esModule",{value:!0}),C.Watch=void 0;class e{constructor(){this.timestamps=new Map}start(e){if(this.timestamps.has(e))throw new Error(`Watch already started for label: ${e}`);this.timestamps.set(e,{started:Date.now()})}stop(e){const t=this.get(e);if(void 0!==t.elapsed)throw new Error(`Watch already stopped for label: ${e}`);const i=Date.now()-t.started;this.timestamps.set(e,{started:t.started,elapsed:i})}get(e){const t=this.timestamps.get(e);if(void 0===t)throw new Error(`No timestamp found for label: ${e}`);return t}elapsed(e){const t=this.get(e);return t.elapsed||Date.now()-t.started}}return C.Watch=e,C.default=e,C}(),e),t.__exportStar(D(),e),t.__exportStar(B(),e)}(m);var M={};function $(e){let t;return"undefined"!=typeof window&&void 0!==window[e]&&(t=window[e]),t}function j(e){const t=$(e);if(!t)throw new Error(`${e} is not defined in Window`);return t}Object.defineProperty(M,"__esModule",{value:!0}),M.getLocalStorage=M.getLocalStorageOrThrow=M.getCrypto=M.getCryptoOrThrow=K=M.getLocation=M.getLocationOrThrow=F=M.getNavigator=M.getNavigatorOrThrow=z=M.getDocument=M.getDocumentOrThrow=M.getFromWindowOrThrow=M.getFromWindow=void 0,M.getFromWindow=$,M.getFromWindowOrThrow=j,M.getDocumentOrThrow=function(){return j("document")};var z=M.getDocument=function(){return $("document")};M.getNavigatorOrThrow=function(){return j("navigator")};var F=M.getNavigator=function(){return $("navigator")};M.getLocationOrThrow=function(){return j("location")};var K=M.getLocation=function(){return $("location")};M.getCryptoOrThrow=function(){return j("crypto")},M.getCrypto=function(){return $("crypto")},M.getLocalStorageOrThrow=function(){return j("localStorage")},M.getLocalStorage=function(){return $("localStorage")};var V={};Object.defineProperty(V,"__esModule",{value:!0});var H=V.getWindowMetadata=void 0;const W=M;H=V.getWindowMetadata=function(){let e,t;try{e=W.getDocumentOrThrow(),t=W.getLocationOrThrow()}catch(e){return null}function i(...t){const i=e.getElementsByTagName("meta");for(let e=0;e<i.length;e++){const s=i[e],r=["itemprop","property","name"].map((e=>s.getAttribute(e))).filter((e=>!!e&&t.includes(e)));if(r.length&&r){const e=s.getAttribute("content");if(e)return e}}return""}const s=function(){let t=i("name","og:site_name","og:title","twitter:title");return t||(t=e.title),t}(),r=i("description","og:description","twitter:description","keywords"),n=t.origin,o=function(){const i=e.getElementsByTagName("link"),s=[];for(let e=0;e<i.length;e++){const r=i[e],n=r.getAttribute("rel");if(n&&n.toLowerCase().indexOf("icon")>-1){const e=r.getAttribute("href");if(e)if(-1===e.toLowerCase().indexOf("https:")&&-1===e.toLowerCase().indexOf("http:")&&0!==e.indexOf("//")){let i=t.protocol+"//"+t.host;if(0===e.indexOf("/"))i+=e;else{const s=t.pathname.split("/");s.pop();i+=s.join("/")+"/"+e}s.push(i)}else if(0===e.indexOf("//")){const i=t.protocol+e;s.push(i)}else s.push(e)}}return s}();return{description:r,url:n,icons:o,name:s}};const G=BigInt(2**32-1),Y=BigInt(32);function Z(e,t=!1){return t?{h:Number(e&G),l:Number(e>>Y&G)}:{h:0|Number(e>>Y&G),l:0|Number(e&G)}}function X(e,t=!1){const i=e.length;let s=new Uint32Array(i),r=new Uint32Array(i);for(let n=0;n<i;n++){const{h:i,l:o}=Z(e[n],t);[s[n],r[n]]=[i,o]}return[s,r]}const J=(e,t,i)=>e>>>i,Q=(e,t,i)=>e<<32-i|t>>>i,ee=(e,t,i)=>e>>>i|t<<32-i,te=(e,t,i)=>e<<32-i|t>>>i,ie=(e,t,i)=>e<<64-i|t>>>i-32,se=(e,t,i)=>e>>>i-32|t<<64-i,re=(e,t)=>t,ne=(e,t)=>e;function oe(e,t,i,s){const r=(t>>>0)+(s>>>0);return{h:e+i+(r/2**32|0)|0,l:0|r}}const ae=(e,t,i)=>(e>>>0)+(t>>>0)+(i>>>0),ce=(e,t,i,s)=>t+i+s+(e/2**32|0)|0,he=(e,t,i,s)=>(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0),le=(e,t,i,s,r)=>t+i+s+r+(e/2**32|0)|0,ue=(e,t,i,s,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0)+(r>>>0),de=(e,t,i,s,r,n)=>t+i+s+r+n+(e/2**32|0)|0,fe="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function pe(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ge(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ye(e,...t){if(!pe(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function we(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");ge(e.outputLen),ge(e.blockLen)}function me(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function be(e,t){ye(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function ve(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Ee(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function xe(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ie(e,t){return e<<32-t|e>>>t}const Se=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Oe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const _e=Se?e=>e:e=>Oe(e);const Ae=Se?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=Oe(e[t]);return e},Pe=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Te=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Be(e){if(ye(e),Pe)return e.toHex();let t="";for(let i=0;i<e.length;i++)t+=Te[e[i]];return t}const Re={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ne(e){return e>=Re._0&&e<=Re._9?e-Re._0:e>=Re.A&&e<=Re.F?e-(Re.A-10):e>=Re.a&&e<=Re.f?e-(Re.a-10):void 0}function Ce(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Pe)return Uint8Array.fromHex(e);const t=e.length,i=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(i);for(let t=0,r=0;t<i;t++,r+=2){const i=Ne(e.charCodeAt(r)),n=Ne(e.charCodeAt(r+1));if(void 0===i||void 0===n){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}s[t]=16*i+n}return s}function Ue(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),ye(e),e}function ke(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];ye(s),t+=s.length}const i=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}class Le{}function qe(e){const t=t=>e().update(Ue(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}function De(e){const t=(t,i)=>e(i).update(Ue(t)).digest(),i=e({});return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=t=>e(t),t}function Me(e=32){if(fe&&"function"==typeof fe.getRandomValues)return fe.getRandomValues(new Uint8Array(e));if(fe&&"function"==typeof fe.randomBytes)return Uint8Array.from(fe.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}const $e=BigInt(0),je=BigInt(1),ze=BigInt(2),Fe=BigInt(7),Ke=BigInt(256),Ve=BigInt(113),He=[],We=[],Ge=[];for(let e=0,t=je,i=1,s=0;e<24;e++){[i,s]=[s,(2*i+3*s)%5],He.push(2*(5*s+i)),We.push((e+1)*(e+2)/2%64);let r=$e;for(let e=0;e<7;e++)t=(t<<je^(t>>Fe)*Ve)%Ke,t&ze&&(r^=je<<(je<<BigInt(e))-je);Ge.push(r)}const Ye=X(Ge,!0),Ze=Ye[0],Xe=Ye[1],Je=(e,t,i)=>i>32?((e,t,i)=>t<<i-32|e>>>64-i)(e,t,i):((e,t,i)=>e<<i|t>>>32-i)(e,t,i),Qe=(e,t,i)=>i>32?((e,t,i)=>e<<i-32|t>>>64-i)(e,t,i):((e,t,i)=>t<<i|e>>>32-i)(e,t,i);class et extends Le{constructor(e,t,i,s=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=r,ge(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ve(this.state)}clone(){return this._cloneInto()}keccak(){Ae(this.state32),function(e,t=24){const i=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let t=0;t<10;t++)i[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const s=(t+8)%10,r=(t+2)%10,n=i[r],o=i[r+1],a=Je(n,o,1)^i[s],c=Qe(n,o,1)^i[s+1];for(let i=0;i<50;i+=10)e[t+i]^=a,e[t+i+1]^=c}let t=e[2],r=e[3];for(let i=0;i<24;i++){const s=We[i],n=Je(t,r,s),o=Qe(t,r,s),a=He[i];t=e[a],r=e[a+1],e[a]=n,e[a+1]=o}for(let t=0;t<50;t+=10){for(let s=0;s<10;s++)i[s]=e[t+s];for(let s=0;s<10;s++)e[t+s]^=~i[(s+2)%10]&i[(s+4)%10]}e[0]^=Ze[s],e[1]^=Xe[s]}Ee(i)}(this.state32,this.rounds),Ae(this.state32),this.posOut=0,this.pos=0}update(e){me(this),ye(e=Ue(e));const{blockLen:t,state:i}=this,s=e.length;for(let r=0;r<s;){const n=Math.min(t-this.pos,s-r);for(let t=0;t<n;t++)i[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,0!=(128&t)&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){me(this,!1),ye(e),this.finish();const t=this.state,{blockLen:i}=this;for(let s=0,r=e.length;s<r;){this.posOut>=i&&this.keccak();const n=Math.min(i-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+n),s),this.posOut+=n,s+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ge(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(be(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,Ee(this.state)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:r,enableXOF:n}=this;return e||(e=new et(t,i,s,n,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=i,e.outputLen=s,e.enableXOF=n,e.destroyed=this.destroyed,e}}const tt=(()=>{return e=1,t=136,i=32,qe((()=>new et(t,e,i)));var e,t,i})();class it extends Error{constructor(e,t={}){const i=(()=>{if(t.cause instanceof it){if(t.cause.details)return t.cause.details;if(t.cause.shortMessage)return t.cause.shortMessage}return t.cause&&"details"in t.cause&&"string"==typeof t.cause.details?t.cause.details:t.cause?.message?t.cause.message:t.details})(),s=t.cause instanceof it&&t.cause.docsPath||t.docsPath,r=`https://oxlib.sh${s??""}`,n=[e||"An error occurred.",...t.metaMessages?["",...t.metaMessages]:[],...i||s?["",i?`Details: ${i}`:void 0,s?`See: ${r}`:void 0]:[]].filter((e=>"string"==typeof e)).join("\n");super(n,t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:"ox@0.1.1"}),this.cause=t.cause,this.details=i,this.docs=r,this.docsPath=s,this.shortMessage=e}walk(e){return st(this,e)}}function st(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&e.cause?st(e.cause,t):t?null:e}const rt="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function nt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function ot(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function at(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ct(e,t){ot(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function ht(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function lt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ut(e,t){return e<<32-t|e>>>t}const dt=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let i=0;i<e.length;i++)e[i]=(t=e[i])<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;var t;return e};function ft(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),ot(e),e}class pt{}function gt(e){const t=t=>e().update(ft(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}function yt(e=32){if(rt&&"function"==typeof rt.getRandomValues)return rt.getRandomValues(new Uint8Array(e));if(rt&&"function"==typeof rt.randomBytes)return Uint8Array.from(rt.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function wt(e,t,i){return e&t^~e&i}function mt(e,t,i){return e&t^e&i^t&i}class bt extends pt{constructor(e,t,i,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(e),this.view=lt(this.buffer)}update(e){at(this),ot(e=ft(e));const{view:t,buffer:i,blockLen:s}=this,r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o!==s)i.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=lt(e);for(;s<=r-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){at(this),ct(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:r}=this;let{pos:n}=this;t[n++]=128,ht(this.buffer.subarray(n)),this.padOffset>s-n&&(this.process(i,0),n=0);for(let e=n;e<s;e++)t[e]=0;!function(e,t,i,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(i>>r&n),a=Number(i&n),c=s?4:0,h=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+h,a,s)}(i,s-8,BigInt(8*this.length),r),this.process(i,0);const o=lt(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,h[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:r,destroyed:n,pos:o}=this;return e.destroyed=n,e.finished=r,e.length=s,e.pos=o,s%t&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const vt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Et=BigInt(2**32-1),xt=BigInt(32);function It(e,t=!1){return t?{h:Number(e&Et),l:Number(e>>xt&Et)}:{h:0|Number(e>>xt&Et),l:0|Number(e&Et)}}function St(e,t=!1){const i=e.length;let s=new Uint32Array(i),r=new Uint32Array(i);for(let n=0;n<i;n++){const{h:i,l:o}=It(e[n],t);[s[n],r[n]]=[i,o]}return[s,r]}const Ot=BigInt(0),_t=BigInt(1),At=BigInt(2),Pt=BigInt(7),Tt=BigInt(256),Bt=BigInt(113),Rt=[],Nt=[],Ct=[];for(let e=0,t=_t,i=1,s=0;e<24;e++){[i,s]=[s,(2*i+3*s)%5],Rt.push(2*(5*s+i)),Nt.push((e+1)*(e+2)/2%64);let r=Ot;for(let e=0;e<7;e++)t=(t<<_t^(t>>Pt)*Bt)%Tt,t&At&&(r^=_t<<(_t<<BigInt(e))-_t);Ct.push(r)}const Ut=St(Ct,!0),kt=Ut[0],Lt=Ut[1],qt=(e,t,i)=>i>32?((e,t,i)=>t<<i-32|e>>>64-i)(e,t,i):((e,t,i)=>e<<i|t>>>32-i)(e,t,i),Dt=(e,t,i)=>i>32?((e,t,i)=>e<<i-32|t>>>64-i)(e,t,i):((e,t,i)=>t<<i|e>>>32-i)(e,t,i);class Mt extends pt{constructor(e,t,i,s=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=i,this.enableXOF=s,this.rounds=r,nt(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var n;this.state=new Uint8Array(200),this.state32=(n=this.state,new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)))}clone(){return this._cloneInto()}keccak(){dt(this.state32),function(e,t=24){const i=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let t=0;t<10;t++)i[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const s=(t+8)%10,r=(t+2)%10,n=i[r],o=i[r+1],a=qt(n,o,1)^i[s],c=Dt(n,o,1)^i[s+1];for(let i=0;i<50;i+=10)e[t+i]^=a,e[t+i+1]^=c}let t=e[2],r=e[3];for(let i=0;i<24;i++){const s=Nt[i],n=qt(t,r,s),o=Dt(t,r,s),a=Rt[i];t=e[a],r=e[a+1],e[a]=n,e[a+1]=o}for(let t=0;t<50;t+=10){for(let s=0;s<10;s++)i[s]=e[t+s];for(let s=0;s<10;s++)e[t+s]^=~i[(s+2)%10]&i[(s+4)%10]}e[0]^=kt[s],e[1]^=Lt[s]}ht(i)}(this.state32,this.rounds),dt(this.state32),this.posOut=0,this.pos=0}update(e){at(this),ot(e=ft(e));const{blockLen:t,state:i}=this,s=e.length;for(let r=0;r<s;){const n=Math.min(t-this.pos,s-r);for(let t=0;t<n;t++)i[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:i,blockLen:s}=this;e[i]^=t,0!=(128&t)&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){at(this,!1),ot(e),this.finish();const t=this.state,{blockLen:i}=this;for(let s=0,r=e.length;s<r;){this.posOut>=i&&this.keccak();const n=Math.min(i-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+n),s),this.posOut+=n,s+=n}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return nt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ct(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,ht(this.state)}_cloneInto(e){const{blockLen:t,suffix:i,outputLen:s,rounds:r,enableXOF:n}=this;return e||(e=new Mt(t,i,s,n,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=i,e.outputLen=s,e.enableXOF=n,e.destroyed=this.destroyed,e}}const $t=(()=>{return e=1,t=136,i=32,gt((()=>new Mt(t,e,i)));var e,t,i})(),jt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),zt=new Uint32Array(64);class Ft extends bt{constructor(e=32){super(64,e,8,!1),this.A=0|vt[0],this.B=0|vt[1],this.C=0|vt[2],this.D=0|vt[3],this.E=0|vt[4],this.F=0|vt[5],this.G=0|vt[6],this.H=0|vt[7]}get(){const{A:e,B:t,C:i,D:s,E:r,F:n,G:o,H:a}=this;return[e,t,i,s,r,n,o,a]}set(e,t,i,s,r,n,o,a){this.A=0|e,this.B=0|t,this.C=0|i,this.D=0|s,this.E=0|r,this.F=0|n,this.G=0|o,this.H=0|a}process(e,t){for(let i=0;i<16;i++,t+=4)zt[i]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=zt[e-15],i=zt[e-2],s=ut(t,7)^ut(t,18)^t>>>3,r=ut(i,17)^ut(i,19)^i>>>10;zt[e]=r+zt[e-7]+s+zt[e-16]|0}let{A:i,B:s,C:r,D:n,E:o,F:a,G:c,H:h}=this;for(let e=0;e<64;e++){const t=h+(ut(o,6)^ut(o,11)^ut(o,25))+wt(o,a,c)+jt[e]+zt[e]|0,l=(ut(i,2)^ut(i,13)^ut(i,22))+mt(i,s,r)|0;h=c,c=a,a=o,o=n+t|0,n=r,r=s,s=i,i=t+l|0}i=i+this.A|0,s=s+this.B|0,r=r+this.C|0,n=n+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(i,s,r,n,o,a,c,h)}roundClean(){ht(zt)}destroy(){this.set(0,0,0,0,0,0,0,0),ht(this.buffer)}}const Kt=gt((()=>new Ft)),Vt=BigInt(0),Ht=BigInt(1);
2
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Wt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Gt(e){if(!Wt(e))throw new Error("Uint8Array expected")}function Yt(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function Zt(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Xt(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Vt:BigInt("0x"+e)}const Jt="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,Qt=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function ei(e){if(Gt(e),Jt)return e.toHex();let t="";for(let i=0;i<e.length;i++)t+=Qt[e[i]];return t}const ti={_0:48,_9:57,A:65,F:70,a:97,f:102};function ii(e){return e>=ti._0&&e<=ti._9?e-ti._0:e>=ti.A&&e<=ti.F?e-(ti.A-10):e>=ti.a&&e<=ti.f?e-(ti.a-10):void 0}function si(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Jt)return Uint8Array.fromHex(e);const t=e.length,i=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(i);for(let t=0,r=0;t<i;t++,r+=2){const i=ii(e.charCodeAt(r)),n=ii(e.charCodeAt(r+1));if(void 0===i||void 0===n){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}s[t]=16*i+n}return s}function ri(e){return Xt(ei(e))}function ni(e){return Gt(e),Xt(ei(Uint8Array.from(e).reverse()))}function oi(e,t){return si(e.toString(16).padStart(2*t,"0"))}function ai(e,t){return oi(e,t).reverse()}function ci(e,t,i){let s;if("string"==typeof t)try{s=si(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Wt(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const r=s.length;if("number"==typeof i&&r!==i)throw new Error(e+" of length "+i+" expected, got "+r);return s}function hi(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];Gt(s),t+=s.length}const i=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}const li=e=>"bigint"==typeof e&&Vt<=e;function ui(e,t,i){return li(e)&&li(t)&&li(i)&&t<=e&&e<i}function di(e,t,i,s){if(!ui(t,i,s))throw new Error("expected valid "+e+": "+i+" <= n < "+s+", got "+t)}const fi=e=>(Ht<<BigInt(e))-Ht,pi=e=>new Uint8Array(e),gi=e=>Uint8Array.from(e);const yi={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||Wt(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function wi(e,t,i={}){const s=(t,i,s)=>{const r=yi[i];if("function"!=typeof r)throw new Error("invalid validator function");const n=e[t];if(!(s&&void 0===n||r(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+i+", got "+n)};for(const[e,i]of Object.entries(t))s(e,i,!1);for(const[e,t]of Object.entries(i))s(e,t,!0);return e}function mi(e){const t=new WeakMap;return(i,...s)=>{const r=t.get(i);if(void 0!==r)return r;const n=e(i,...s);return t.set(i,n),n}}function bi(e,t){if(zi(e)>t)throw new Vi({givenSize:zi(e),maxSize:t})}const vi={zero:48,nine:57,A:65,F:70,a:97,f:102};function Ei(e){return e>=vi.zero&&e<=vi.nine?e-vi.zero:e>=vi.A&&e<=vi.F?e-(vi.A-10):e>=vi.a&&e<=vi.f?e-(vi.a-10):void 0}function xi(e,t){if(Ri(e)>t)throw new Li({givenSize:Ri(e),maxSize:t})}function Ii(e,t={}){const{dir:i,size:s=32}=t;if(0===s)return e;const r=e.replace("0x","");if(r.length>2*s)throw new Di({size:Math.ceil(r.length/2),targetSize:s,type:"Hex"});return`0x${r["right"===i?"padEnd":"padStart"](2*s,"0")}`}function Si(e,t,i){return JSON.stringify(e,((e,i)=>"function"==typeof t?t(e,i):"bigint"==typeof i?i.toString()+"#__bigint":i),i)}const Oi=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function _i(e){return e instanceof Uint8Array?Ai(e):Array.isArray(e)?Ai(new Uint8Array(e)):e}function Ai(e,t={}){let i="";for(let t=0;t<e.length;t++)i+=Oi[e[t]];const s=`0x${i}`;return"number"==typeof t.size?(xi(s,t.size),Ti(s,t.size)):s}function Pi(e,t={}){const{signed:i,size:s}=t,r=BigInt(e);let n;s?n=i?(1n<<8n*BigInt(s)-1n)-1n:2n**(8n*BigInt(s))-1n:"number"==typeof e&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof n&&i?-n-1n:0;if(n&&r>n||r<o){const t="bigint"==typeof e?"n":"";throw new Ci({max:n?`${n}${t}`:void 0,min:`${o}${t}`,signed:i,size:s,value:`${e}${t}`})}const a=`0x${(i&&r<0?(1n<<BigInt(8*s))+BigInt(r):r).toString(16)}`;return s?function(e,t){return Ii(e,{dir:"left",size:t})}(a,s):a}function Ti(e,t){return Ii(e,{dir:"right",size:t})}function Bi(e,t,i,s={}){const{strict:r}=s;!function(e,t){if("number"==typeof t&&t>0&&t>Ri(e)-1)throw new qi({offset:t,position:"start",size:Ri(e)})}(e,t);const n=`0x${e.replace("0x","").slice(2*(t??0),2*(i??e.length))}`;return r&&function(e,t,i){if("number"==typeof t&&"number"==typeof i&&Ri(e)!==i-t)throw new qi({offset:i,position:"end",size:Ri(e)})}(n,t,i),n}function Ri(e){return Math.ceil((e.length-2)/2)}function Ni(e,t={}){const{strict:i=!1}=t;try{return function(e,t={}){const{strict:i=!1}=t;if(!e)throw new Ui(e);if("string"!=typeof e)throw new Ui(e);if(i&&!/^0x[0-9a-fA-F]*$/.test(e))throw new ki(e);if(!e.startsWith("0x"))throw new ki(e)}(e,{strict:i}),!0}catch{return!1}}class Ci extends it{constructor({max:e,min:t,signed:i,size:s,value:r}){super(`Number \`${r}\` is not in safe${s?` ${8*s}-bit`:""}${i?" signed":" unsigned"} integer range ${e?`(\`${t}\` to \`${e}\`)`:`(above \`${t}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Ui extends it{constructor(e){super(`Value \`${"object"==typeof e?Si(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class ki extends it{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class Li extends it{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class qi extends it{constructor({offset:e,position:t,size:i}){super(`Slice ${"start"===t?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class Di extends it{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}const Mi=new TextEncoder;function $i(e){return e instanceof Uint8Array?e:"string"==typeof e?function(e,t={}){const{size:i}=t;let s=e;i&&(xi(e,i),s=Ti(e,i));let r=s.slice(2);r.length%2&&(r=`0${r}`);const n=r.length/2,o=new Uint8Array(n);for(let e=0,t=0;e<n;e++){const i=Ei(r.charCodeAt(t++)),s=Ei(r.charCodeAt(t++));if(void 0===i||void 0===s)throw new it(`Invalid byte sequence ("${r[t-2]}${r[t-1]}" in "${r}").`);o[e]=16*i+s}return o}(e):function(e){return e instanceof Uint8Array?e:new Uint8Array(e)}(e)}function ji(e,t={}){const{size:i}=t,s=Mi.encode(e);return"number"==typeof i?(bi(s,i),function(e,t){return function(e,t={}){const{dir:i,size:s=32}=t;if(0===s)return e;if(e.length>s)throw new Hi({size:e.length,targetSize:s,type:"Bytes"});const r=new Uint8Array(s);for(let t=0;t<s;t++){const n="right"===i;r[n?t:s-t-1]=e[n?t:e.length-t-1]}return r}(e,{dir:"right",size:t})}(s,i)):s}function zi(e){return e.length}function Fi(e){try{return function(e){if(!(e instanceof Uint8Array)){if(!e)throw new Ki(e);if("object"!=typeof e)throw new Ki(e);if(!("BYTES_PER_ELEMENT"in e))throw new Ki(e);if(1!==e.BYTES_PER_ELEMENT||"Uint8Array"!==e.constructor.name)throw new Ki(e)}}(e),!0}catch{return!1}}class Ki extends it{constructor(e){super(`Value \`${"object"==typeof e?Si(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class Vi extends it{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed \`${t}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class Hi extends it{constructor({size:e,targetSize:t,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${t}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function Wi(e,t={}){const{as:i=("string"==typeof e?"Hex":"Bytes")}=t,s=$t($i(e));return"Bytes"===i?s:Ai(s)}class Gi extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const Yi={checksum:new Gi(8192)}.checksum;function Zi(e,t={}){const{compressed:i}=t,{prefix:s,x:r,y:n}=e;if(!1===i||"bigint"==typeof r&&"bigint"==typeof n){if(4!==s)throw new es({prefix:s,cause:new is})}else{if(!0!==i&&("bigint"!=typeof r||void 0!==n))throw new Qi({publicKey:e});if(3!==s&&2!==s)throw new es({prefix:s,cause:new ts})}}function Xi(e){const t=(()=>{if(Ni(e))return Ji(e);if(Fi(e))return function(e){return Ji(Ai(e))}(e);const{prefix:t,x:i,y:s}=e;return"bigint"==typeof i&&"bigint"==typeof s?{prefix:t??4,x:i,y:s}:{prefix:t,x:i}})();return Zi(t),t}function Ji(e){if(132!==e.length&&130!==e.length&&68!==e.length)throw new ss({publicKey:e});if(130===e.length){return{prefix:4,x:BigInt(Bi(e,0,32)),y:BigInt(Bi(e,32,64))}}if(132===e.length){return{prefix:Number(Bi(e,0,1)),x:BigInt(Bi(e,1,33)),y:BigInt(Bi(e,33,65))}}return{prefix:Number(Bi(e,0,1)),x:BigInt(Bi(e,1,33))}}class Qi extends it{constructor({publicKey:e}){super(`Value \`${Si(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class es extends it{constructor({prefix:e,cause:t}){super(`Prefix "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class ts extends it{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class is extends it{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class ss extends it{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${Ri(_i(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}const rs=/^0x[a-fA-F0-9]{40}$/;function ns(e,t={}){const{strict:i=!0}=t;if(!rs.test(e))throw new cs({address:e,cause:new hs});if(i){if(e.toLowerCase()===e)return;if(os(e)!==e)throw new cs({address:e,cause:new ls})}}function os(e){if(Yi.has(e))return Yi.get(e);ns(e,{strict:!1});const t=e.substring(2).toLowerCase(),i=Wi(ji(t),{as:"Bytes"}),s=t.split("");for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&s[e]&&(s[e]=s[e].toUpperCase()),(15&i[e>>1])>=8&&s[e+1]&&(s[e+1]=s[e+1].toUpperCase());const r=`0x${s.join("")}`;return Yi.set(e,r),r}function as(e,t={}){const i=Wi(`0x${function(e,t={}){Zi(e);const{prefix:i,x:s,y:r}=e,{includePrefix:n=!0}=t,o=function(...e){return`0x${e.reduce(((e,t)=>e+t.replace("0x","")),"")}`}(n?Pi(i,{size:1}):"0x",Pi(s,{size:32}),"bigint"==typeof r?Pi(r,{size:32}):"0x");return o}(e).slice(4)}`).substring(26);return function(e,t={}){const{checksum:i=!1}=t;return ns(e),i?os(e):e}(`0x${i}`,t)}class cs extends it{constructor({address:e,cause:t}){super(`Address "${e}" is invalid.`,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class hs extends it{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class ls extends it{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class us extends pt{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");nt(e.outputLen),nt(e.blockLen)}(e);const i=ft(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)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,r=new Uint8Array(s);r.set(i.length>s?e.create().update(i).digest():i);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),ht(r)}update(e){return at(this),this.iHash.update(e),this}digestInto(e){at(this),ot(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:t,iHash:i,finished:s,destroyed:r,blockLen:n,outputLen:o}=this;return e.finished=s,e.destroyed=r,e.blockLen=n,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ds=(e,t,i)=>new us(e,t).update(i).digest();ds.create=(e,t)=>new us(e,t);const fs=BigInt(0),ps=BigInt(1),gs=BigInt(2),ys=BigInt(3),ws=BigInt(4),ms=BigInt(5),bs=BigInt(8);function vs(e,t){const i=e%t;return i>=fs?i:t+i}function Es(e,t,i){let s=e;for(;t-- >fs;)s*=s,s%=i;return s}function xs(e,t){if(e===fs)throw new Error("invert: expected non-zero number");if(t<=fs)throw new Error("invert: expected positive modulus, got "+t);let i=vs(e,t),s=t,r=fs,n=ps;for(;i!==fs;){const e=s%i,t=r-n*(s/i);s=i,i=e,r=n,n=t}if(s!==ps)throw new Error("invert: does not exist");return vs(r,t)}function Is(e,t){const i=(e.ORDER+ps)/ws,s=e.pow(t,i);if(!e.eql(e.sqr(s),t))throw new Error("Cannot find square root");return s}function Ss(e,t){const i=(e.ORDER-ms)/bs,s=e.mul(t,gs),r=e.pow(s,i),n=e.mul(t,r),o=e.mul(e.mul(n,gs),r),a=e.mul(n,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function Os(e){return e%ws===ys?Is:e%bs===ms?Ss:function(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-ps,i=0;for(;t%gs===fs;)t/=gs,i++;let s=gs;const r=Bs(e);for(;1===Ps(r,s);)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===i)return Is;let n=r.pow(s,t);const o=(t+ps)/gs;return function(e,s){if(e.is0(s))return s;if(1!==Ps(e,s))throw new Error("Cannot find square root");let r=i,a=e.mul(e.ONE,n),c=e.pow(s,t),h=e.pow(s,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,i=e.sqr(c);for(;!e.eql(i,e.ONE);)if(t++,i=e.sqr(i),t===r)throw new Error("Cannot find square root");const s=ps<<BigInt(r-t-1),n=e.pow(a,s);r=t,a=e.sqr(n),c=e.mul(c,a),h=e.mul(h,n)}return h}}(e)}const _s=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function As(e,t,i=!1){const s=new Array(t.length).fill(i?e.ZERO:void 0),r=t.reduce(((t,i,r)=>e.is0(i)?t:(s[r]=t,e.mul(t,i))),e.ONE),n=e.inv(r);return t.reduceRight(((t,i,r)=>e.is0(i)?t:(s[r]=e.mul(t,s[r]),e.mul(t,i))),n),s}function Ps(e,t){const i=(e.ORDER-ps)/gs,s=e.pow(t,i),r=e.eql(s,e.ONE),n=e.eql(s,e.ZERO),o=e.eql(s,e.neg(e.ONE));if(!r&&!n&&!o)throw new Error("invalid Legendre symbol result");return r?1:n?0:-1}function Ts(e,t){void 0!==t&&nt(t);const i=void 0!==t?t:e.toString(2).length;return{nBitLength:i,nByteLength:Math.ceil(i/8)}}function Bs(e,t,i=!1,s={}){if(e<=fs)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:n}=Ts(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:i,BITS:r,BYTES:n,MASK:fi(r),ZERO:fs,ONE:ps,create:t=>vs(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return fs<=t&&t<e},is0:e=>e===fs,isOdd:e=>(e&ps)===ps,neg:t=>vs(-t,e),eql:(e,t)=>e===t,sqr:t=>vs(t*t,e),add:(t,i)=>vs(t+i,e),sub:(t,i)=>vs(t-i,e),mul:(t,i)=>vs(t*i,e),pow:(e,t)=>function(e,t,i){if(i<fs)throw new Error("invalid exponent, negatives unsupported");if(i===fs)return e.ONE;if(i===ps)return t;let s=e.ONE,r=t;for(;i>fs;)i&ps&&(s=e.mul(s,r)),r=e.sqr(r),i>>=ps;return s}(a,e,t),div:(t,i)=>vs(t*xs(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>xs(t,e),sqrt:s.sqrt||(t=>(o||(o=Os(e)),o(a,t))),toBytes:e=>i?ai(e,n):oi(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return i?ni(e):ri(e)},invertBatch:e=>As(a,e),cmov:(e,t,i)=>i?t:e});return Object.freeze(a)}function Rs(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ns(e){const t=Rs(e);return t+Math.ceil(t/2)}const Cs=BigInt(0),Us=BigInt(1);function ks(e,t){const i=t.negate();return e?i:t}function Ls(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function qs(e,t){Ls(e,t);const i=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:fi(e),maxNumber:i,shiftBy:BigInt(e)}}function Ds(e,t,i){const{windowSize:s,mask:r,maxNumber:n,shiftBy:o}=i;let a=Number(e&r),c=e>>o;a>s&&(a-=n,c+=Us);const h=t*s;return{nextN:c,offset:h+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:h}}const Ms=new WeakMap,$s=new WeakMap;function js(e){return $s.get(e)||1}function zs(e,t,i,s){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,i)=>{if(!(e instanceof t))throw new Error("invalid point at index "+i)}))}(i,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,i)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+i)}))}(s,t);const r=i.length,n=s.length;if(r!==n)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=function(e){let t;for(t=0;e>Vt;e>>=Ht,t+=1);return t}(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const h=fi(c),l=new Array(Number(h)+1).fill(o);let u=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){l.fill(o);for(let t=0;t<n;t++){const r=s[t],n=Number(r>>BigInt(e)&h);l[n]=l[n].add(i[t])}let t=o;for(let e=l.length-1,i=o;e>0;e--)i=i.add(l[e]),t=t.add(i);if(u=u.add(t),0!==e)for(let e=0;e<c;e++)u=u.double()}return u}function Fs(e){return wi(e.Fp,_s.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),wi(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ts(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}function Ks(e){void 0!==e.lowS&&Yt("lowS",e.lowS),void 0!==e.prehash&&Yt("prehash",e.prehash)}class Vs extends Error{constructor(e=""){super(e)}}const Hs={Err:Vs,_tlv:{encode:(e,t)=>{const{Err:i}=Hs;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(1&t.length)throw new i("tlv.encode: unpadded data");const s=t.length/2,r=Zt(s);if(r.length/2&128)throw new i("tlv.encode: long form length too big");const n=s>127?Zt(r.length/2|128):"";return Zt(e)+n+r+t},decode(e,t){const{Err:i}=Hs;let s=0;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(t.length<2||t[s++]!==e)throw new i("tlv.decode: wrong tlv");const r=t[s++];let n=0;if(!!(128&r)){const e=127&r;if(!e)throw new i("tlv.decode(long): indefinite length not supported");if(e>4)throw new i("tlv.decode(long): byte length is too big");const o=t.subarray(s,s+e);if(o.length!==e)throw new i("tlv.decode: length bytes not complete");if(0===o[0])throw new i("tlv.decode(long): zero leftmost byte");for(const e of o)n=n<<8|e;if(s+=e,n<128)throw new i("tlv.decode(long): not minimal encoding")}else n=r;const o=t.subarray(s,s+n);if(o.length!==n)throw new i("tlv.decode: wrong value length");return{v:o,l:t.subarray(s+n)}}},_int:{encode(e){const{Err:t}=Hs;if(e<Gs)throw new t("integer: negative integers are not allowed");let i=Zt(e);if(8&Number.parseInt(i[0],16)&&(i="00"+i),1&i.length)throw new t("unexpected DER parsing assertion: unpadded hex");return i},decode(e){const{Err:t}=Hs;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return ri(e)}},toSig(e){const{Err:t,_int:i,_tlv:s}=Hs,r=ci("signature",e),{v:n,l:o}=s.decode(48,r);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l:l}=s.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:i.decode(a),s:i.decode(h)}},hexFromSig(e){const{_tlv:t,_int:i}=Hs,s=t.encode(2,i.encode(e.r))+t.encode(2,i.encode(e.s));return t.encode(48,s)}};function Ws(e,t){return ei(oi(e,t))}const Gs=BigInt(0),Ys=BigInt(1);BigInt(2);const Zs=BigInt(3),Xs=BigInt(4);function Js(e){const t=function(e){const t=Fs(e);wi(t,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:i,Fp:s,a:r}=t;if(i){if(!s.eql(r,s.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if("object"!=typeof i||"bigint"!=typeof i.beta||"function"!=typeof i.splitScalar)throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...t})}(e),{Fp:i}=t,s=Bs(t.n,t.nBitLength),r=t.toBytes||((e,t,s)=>{const r=t.toAffine();return hi(Uint8Array.from([4]),i.toBytes(r.x),i.toBytes(r.y))}),n=t.fromBytes||(e=>{const t=e.subarray(1);return{x:i.fromBytes(t.subarray(0,i.BYTES)),y:i.fromBytes(t.subarray(i.BYTES,2*i.BYTES))}});function o(e){const{a:s,b:r}=t,n=i.sqr(e),o=i.mul(n,e);return i.add(i.add(o,i.mul(e,s)),r)}function a(e,t){const s=i.sqr(t),r=o(e);return i.eql(s,r)}if(!a(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const c=i.mul(i.pow(t.a,Zs),Xs),h=i.mul(i.sqr(t.b),BigInt(27));if(i.is0(i.add(c,h)))throw new Error("bad curve params: a or b");function l(e){const{allowedPrivateKeyLengths:i,nByteLength:s,wrapPrivateKey:r,n:n}=t;if(i&&"bigint"!=typeof e){if(Wt(e)&&(e=ei(e)),"string"!=typeof e||!i.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*s,"0")}let o;try{o="bigint"==typeof e?e:ri(ci("private key",e,s))}catch(t){throw new Error("invalid private key, expected hex or "+s+" bytes, got "+typeof e)}return r&&(o=vs(o,n)),di("private key",o,Ys,n),o}function u(e){if(!(e instanceof p))throw new Error("ProjectivePoint expected")}const d=mi(((e,t)=>{const{px:s,py:r,pz:n}=e;if(i.eql(n,i.ONE))return{x:s,y:r};const o=e.is0();null==t&&(t=o?i.ONE:i.inv(n));const a=i.mul(s,t),c=i.mul(r,t),h=i.mul(n,t);if(o)return{x:i.ZERO,y:i.ZERO};if(!i.eql(h,i.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),f=mi((e=>{if(e.is0()){if(t.allowInfinityPoint&&!i.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:s,y:r}=e.toAffine();if(!i.isValid(s)||!i.isValid(r))throw new Error("bad point: x or y not FE");if(!a(s,r))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class p{constructor(e,t,s){if(null==e||!i.isValid(e))throw new Error("x required");if(null==t||!i.isValid(t)||i.is0(t))throw new Error("y required");if(null==s||!i.isValid(s))throw new Error("z required");this.px=e,this.py=t,this.pz=s,Object.freeze(this)}static fromAffine(e){const{x:t,y:s}=e||{};if(!e||!i.isValid(t)||!i.isValid(s))throw new Error("invalid affine point");if(e instanceof p)throw new Error("projective point not allowed");const r=e=>i.eql(e,i.ZERO);return r(t)&&r(s)?p.ZERO:new p(t,s,i.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=As(i,e.map((e=>e.pz)));return e.map(((e,i)=>e.toAffine(t[i]))).map(p.fromAffine)}static fromHex(e){const t=p.fromAffine(n(ci("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return p.BASE.multiply(l(e))}static msm(e,t){return zs(p,s,e,t)}_setWindowSize(e){w.setWindowSize(this,e)}assertValidity(){f(this)}hasEvenY(){const{y:e}=this.toAffine();if(i.isOdd)return!i.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){u(e);const{px:t,py:s,pz:r}=this,{px:n,py:o,pz:a}=e,c=i.eql(i.mul(t,a),i.mul(n,r)),h=i.eql(i.mul(s,a),i.mul(o,r));return c&&h}negate(){return new p(this.px,i.neg(this.py),this.pz)}double(){const{a:e,b:s}=t,r=i.mul(s,Zs),{px:n,py:o,pz:a}=this;let c=i.ZERO,h=i.ZERO,l=i.ZERO,u=i.mul(n,n),d=i.mul(o,o),f=i.mul(a,a),g=i.mul(n,o);return g=i.add(g,g),l=i.mul(n,a),l=i.add(l,l),c=i.mul(e,l),h=i.mul(r,f),h=i.add(c,h),c=i.sub(d,h),h=i.add(d,h),h=i.mul(c,h),c=i.mul(g,c),l=i.mul(r,l),f=i.mul(e,f),g=i.sub(u,f),g=i.mul(e,g),g=i.add(g,l),l=i.add(u,u),u=i.add(l,u),u=i.add(u,f),u=i.mul(u,g),h=i.add(h,u),f=i.mul(o,a),f=i.add(f,f),u=i.mul(f,g),c=i.sub(c,u),l=i.mul(f,d),l=i.add(l,l),l=i.add(l,l),new p(c,h,l)}add(e){u(e);const{px:s,py:r,pz:n}=this,{px:o,py:a,pz:c}=e;let h=i.ZERO,l=i.ZERO,d=i.ZERO;const f=t.a,g=i.mul(t.b,Zs);let y=i.mul(s,o),w=i.mul(r,a),m=i.mul(n,c),b=i.add(s,r),v=i.add(o,a);b=i.mul(b,v),v=i.add(y,w),b=i.sub(b,v),v=i.add(s,n);let E=i.add(o,c);return v=i.mul(v,E),E=i.add(y,m),v=i.sub(v,E),E=i.add(r,n),h=i.add(a,c),E=i.mul(E,h),h=i.add(w,m),E=i.sub(E,h),d=i.mul(f,v),h=i.mul(g,m),d=i.add(h,d),h=i.sub(w,d),d=i.add(w,d),l=i.mul(h,d),w=i.add(y,y),w=i.add(w,y),m=i.mul(f,m),v=i.mul(g,v),w=i.add(w,m),m=i.sub(y,m),m=i.mul(f,m),v=i.add(v,m),y=i.mul(w,v),l=i.add(l,y),y=i.mul(E,v),h=i.mul(b,h),h=i.sub(h,y),y=i.mul(b,w),d=i.mul(E,d),d=i.add(d,y),new p(h,l,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(p.ZERO)}wNAF(e){return w.wNAFCached(this,e,p.normalizeZ)}multiplyUnsafe(e){const{endo:s,n:r}=t;di("scalar",e,Gs,r);const n=p.ZERO;if(e===Gs)return n;if(this.is0()||e===Ys)return this;if(!s||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,e,p.normalizeZ);let{k1neg:o,k1:a,k2neg:c,k2:h}=s.splitScalar(e),l=n,u=n,d=this;for(;a>Gs||h>Gs;)a&Ys&&(l=l.add(d)),h&Ys&&(u=u.add(d)),d=d.double(),a>>=Ys,h>>=Ys;return o&&(l=l.negate()),c&&(u=u.negate()),u=new p(i.mul(u.px,s.beta),u.py,u.pz),l.add(u)}multiply(e){const{endo:s,n:r}=t;let n,o;if(di("scalar",e,Ys,r),s){const{k1neg:t,k1:r,k2neg:a,k2:c}=s.splitScalar(e);let{p:h,f:l}=this.wNAF(r),{p:u,f:d}=this.wNAF(c);h=w.constTimeNegate(t,h),u=w.constTimeNegate(a,u),u=new p(i.mul(u.px,s.beta),u.py,u.pz),n=h.add(u),o=l.add(d)}else{const{p:t,f:i}=this.wNAF(e);n=t,o=i}return p.normalizeZ([n,o])[0]}multiplyAndAddUnsafe(e,t,i){const s=p.BASE,r=(e,t)=>t!==Gs&&t!==Ys&&e.equals(s)?e.multiply(t):e.multiplyUnsafe(t),n=r(this,t).add(r(e,i));return n.is0()?void 0:n}toAffine(e){return d(this,e)}isTorsionFree(){const{h:e,isTorsionFree:i}=t;if(e===Ys)return!0;if(i)return i(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:i}=t;return e===Ys?this:i?i(p,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return Yt("isCompressed",e),this.assertValidity(),r(p,this,e)}toHex(e=!0){return Yt("isCompressed",e),ei(this.toRawBytes(e))}}p.BASE=new p(t.Gx,t.Gy,i.ONE),p.ZERO=new p(i.ZERO,i.ONE,i.ZERO);const{endo:g,nBitLength:y}=t,w=function(e,t){return{constTimeNegate:ks,hasPrecomputes:e=>1!==js(e),unsafeLadder(t,i,s=e.ZERO){let r=t;for(;i>Cs;)i&Us&&(s=s.add(r)),r=r.double(),i>>=Us;return s},precomputeWindow(e,i){const{windows:s,windowSize:r}=qs(i,t),n=[];let o=e,a=o;for(let e=0;e<s;e++){a=o,n.push(a);for(let e=1;e<r;e++)a=a.add(o),n.push(a);o=a.double()}return n},wNAF(i,s,r){let n=e.ZERO,o=e.BASE;const a=qs(i,t);for(let e=0;e<a.windows;e++){const{nextN:t,offset:i,isZero:c,isNeg:h,isNegF:l,offsetF:u}=Ds(r,e,a);r=t,c?o=o.add(ks(l,s[u])):n=n.add(ks(h,s[i]))}return{p:n,f:o}},wNAFUnsafe(i,s,r,n=e.ZERO){const o=qs(i,t);for(let e=0;e<o.windows&&r!==Cs;e++){const{nextN:t,offset:i,isZero:a,isNeg:c}=Ds(r,e,o);if(r=t,!a){const e=s[i];n=n.add(c?e.negate():e)}}return n},getPrecomputes(e,t,i){let s=Ms.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&Ms.set(t,i(s))),s},wNAFCached(e,t,i){const s=js(e);return this.wNAF(s,this.getPrecomputes(s,e,i),t)},wNAFCachedUnsafe(e,t,i,s){const r=js(e);return 1===r?this.unsafeLadder(e,t,s):this.wNAFUnsafe(r,this.getPrecomputes(r,e,i),t,s)},setWindowSize(e,i){Ls(i,t),$s.set(e,i),Ms.delete(e)}}}(p,g?Math.ceil(y/2):y);return{CURVE:t,ProjectivePoint:p,normPrivateKeyToScalar:l,weierstrassEquation:o,isWithinCurveOrder:function(e){return ui(e,Ys,t.n)}}}function Qs(e){const t=function(e){const t=Fs(e);return wi(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:i,n:s,nByteLength:r,nBitLength:n}=t,o=i.BYTES+1,a=2*i.BYTES+1;function c(e){return vs(e,s)}function h(e){return xs(e,s)}const{ProjectivePoint:l,normPrivateKeyToScalar:u,weierstrassEquation:d,isWithinCurveOrder:f}=Js({...t,toBytes(e,t,s){const r=t.toAffine(),n=i.toBytes(r.x),o=hi;return Yt("isCompressed",s),s?o(Uint8Array.from([t.hasEvenY()?2:3]),n):o(Uint8Array.from([4]),n,i.toBytes(r.y))},fromBytes(e){const t=e.length,s=e[0],r=e.subarray(1);if(t!==o||2!==s&&3!==s){if(t===a&&4===s){return{x:i.fromBytes(r.subarray(0,i.BYTES)),y:i.fromBytes(r.subarray(i.BYTES,2*i.BYTES))}}throw new Error("invalid Point, expected length of "+o+", or uncompressed "+a+", got "+t)}{const e=ri(r);if(!ui(e,Ys,i.ORDER))throw new Error("Point is not on curve");const t=d(e);let n;try{n=i.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return 1==(1&s)!==((n&Ys)===Ys)&&(n=i.neg(n)),{x:e,y:n}}}});function p(e){return e>s>>Ys}const g=(e,t,i)=>ri(e.slice(t,i));class y{constructor(e,t,i){di("r",e,Ys,s),di("s",t,Ys,s),this.r=e,this.s=t,null!=i&&(this.recovery=i),Object.freeze(this)}static fromCompact(e){const t=r;return e=ci("compactSignature",e,2*t),new y(g(e,0,t),g(e,t,2*t))}static fromDER(e){const{r:t,s:i}=Hs.toSig(ci("DER",e));return new y(t,i)}assertValidity(){}addRecoveryBit(e){return new y(this.r,this.s,e)}recoverPublicKey(e){const{r:s,s:r,recovery:n}=this,o=v(ci("msgHash",e));if(null==n||![0,1,2,3].includes(n))throw new Error("recovery id invalid");const a=2===n||3===n?s+t.n:s;if(a>=i.ORDER)throw new Error("recovery id 2 or 3 invalid");const u=0==(1&n)?"02":"03",d=l.fromHex(u+Ws(a,i.BYTES)),f=h(a),p=c(-o*f),g=c(r*f),y=l.BASE.multiplyAndAddUnsafe(d,p,g);if(!y)throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return si(this.toDERHex())}toDERHex(){return Hs.hexFromSig(this)}toCompactRawBytes(){return si(this.toCompactHex())}toCompactHex(){const e=r;return Ws(this.r,e)+Ws(this.s,e)}}const w={isValidPrivateKey(e){try{return u(e),!0}catch(e){return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const e=Ns(t.n);return function(e,t,i=!1){const s=e.length,r=Rs(t),n=Ns(t);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=vs(i?ni(e):ri(e),t-ps)+ps;return i?ai(o,r):oi(o,r)}(t.randomBytes(e),t.n)},precompute:(e=8,t=l.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function m(e){if("bigint"==typeof e)return!1;if(e instanceof l)return!0;const s=ci("key",e).length,n=i.BYTES,o=n+1,a=2*n+1;return t.allowedPrivateKeyLengths||r===o?void 0:s===o||s===a}const b=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=ri(e),i=8*e.length-n;return i>0?t>>BigInt(i):t},v=t.bits2int_modN||function(e){return c(b(e))},E=fi(n);function x(e){return di("num < 2^"+n,e,Gs,E),oi(e,r)}function I(e,s,r=S){if(["recovered","canonical"].some((e=>e in r)))throw new Error("sign() legacy options not supported");const{hash:n,randomBytes:o}=t;let{lowS:a,prehash:d,extraEntropy:g}=r;null==a&&(a=!0),e=ci("msgHash",e),Ks(r),d&&(e=ci("prehashed msgHash",n(e)));const w=v(e),m=u(s),E=[x(m),x(w)];if(null!=g&&!1!==g){const e=!0===g?o(i.BYTES):g;E.push(ci("extraEntropy",e))}const I=hi(...E),O=w;return{seed:I,k2sig:function(e){const t=b(e);if(!f(t))return;const i=h(t),s=l.BASE.multiply(t).toAffine(),r=c(s.x);if(r===Gs)return;const n=c(i*c(O+r*m));if(n===Gs)return;let o=(s.x===r?0:2)|Number(s.y&Ys),u=n;return a&&p(n)&&(u=function(e){return p(e)?c(-e):e}(n),o^=1),new y(r,u,o)}}}const S={lowS:t.lowS,prehash:!1},O={lowS:t.lowS,prehash:!1};return l.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return l.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,i=!0){if(!0===m(e))throw new Error("first arg must be private key");if(!1===m(t))throw new Error("second arg must be public key");return l.fromHex(t).multiply(u(e)).toRawBytes(i)},sign:function(e,i,s=S){const{seed:r,k2sig:n}=I(e,i,s),o=t,a=function(e,t,i){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof i)throw new Error("hmacFn must be a function");let s=pi(e),r=pi(e),n=0;const o=()=>{s.fill(1),r.fill(0),n=0},a=(...e)=>i(r,s,...e),c=(e=pi(0))=>{r=a(gi([0]),e),s=a(),0!==e.length&&(r=a(gi([1]),e),s=a())},h=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const i=[];for(;e<t;){s=a();const t=s.slice();i.push(t),e+=s.length}return hi(...i)};return(e,t)=>{let i;for(o(),c(e);!(i=t(h()));)c();return o(),i}}(o.hash.outputLen,o.nByteLength,o.hmac);return a(r,n)},verify:function(e,i,s,r=O){const n=e;i=ci("msgHash",i),s=ci("publicKey",s);const{lowS:o,prehash:a,format:u}=r;if(Ks(r),"strict"in r)throw new Error("options.strict was renamed to lowS");if(void 0!==u&&"compact"!==u&&"der"!==u)throw new Error("format must be compact or der");const d="string"==typeof n||Wt(n),f=!d&&!u&&"object"==typeof n&&null!==n&&"bigint"==typeof n.r&&"bigint"==typeof n.s;if(!d&&!f)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let p,g;try{if(f&&(p=new y(n.r,n.s)),d){try{"compact"!==u&&(p=y.fromDER(n))}catch(e){if(!(e instanceof Hs.Err))throw e}p||"der"===u||(p=y.fromCompact(n))}g=l.fromHex(s)}catch(e){return!1}if(!p)return!1;if(o&&p.hasHighS())return!1;a&&(i=t.hash(i));const{r:w,s:m}=p,b=v(i),E=h(m),x=c(b*E),I=c(w*E),S=l.BASE.multiplyAndAddUnsafe(g,x,I)?.toAffine();return!!S&&c(S.x)===w},ProjectivePoint:l,Signature:y,utils:w}}function er(e){return{hash:e,hmac:(t,...i)=>ds(e,t,function(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];ot(s),t+=s.length}const i=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}(...i)),randomBytes:yt}}const tr=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ir=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),sr=BigInt(0),rr=BigInt(1),nr=BigInt(2),or=(e,t)=>(e+t/nr)/t;const ar=Bs(tr,void 0,void 0,{sqrt:function(e){const t=tr,i=BigInt(3),s=BigInt(6),r=BigInt(11),n=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),h=e*e*e%t,l=h*h*e%t,u=Es(l,i,t)*l%t,d=Es(u,i,t)*l%t,f=Es(d,nr,t)*h%t,p=Es(f,r,t)*f%t,g=Es(p,n,t)*p%t,y=Es(g,a,t)*g%t,w=Es(y,c,t)*y%t,m=Es(w,a,t)*g%t,b=Es(m,i,t)*l%t,v=Es(b,o,t)*p%t,E=Es(v,s,t)*h%t,x=Es(E,nr,t);if(!ar.eql(ar.sqr(x),e))throw new Error("Cannot find square root");return x}}),cr=function(e,t){const i=t=>Qs({...e,...er(t)});return{...i(t),create:i}}({a:sr,b:BigInt(7),Fp:ar,n:ir,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=ir,i=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),s=-rr*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),n=i,o=BigInt("0x100000000000000000000000000000000"),a=or(n*e,t),c=or(-s*e,t);let h=vs(e-a*i-c*r,t),l=vs(-a*s-c*n,t);const u=h>o,d=l>o;if(u&&(h=t-h),d&&(l=t-l),h>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:h,k2neg:d,k2:l}}}},Kt);function hr(e){if(130!==e.length&&132!==e.length)throw new lr({signature:e});const t=BigInt(Bi(e,0,32)),i=BigInt(Bi(e,32,64)),s=(()=>{const t=Number(`0x${e.slice(130)}`);if(!Number.isNaN(t))try{return function(e){if(0===e||27===e)return 0;if(1===e||28===e)return 1;if(e>=35)return e%2==0?1:0;throw new dr({value:e})}(t)}catch{throw new ur({value:t})}})();return void 0===s?{r:t,s:i}:{r:t,s:i,yParity:s}}class lr extends it{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Ri(_i(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class ur extends it{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class dr extends it{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}function fr(e){return as(function(e){const{payload:t,signature:i}=e,{r:s,s:r,yParity:n}=i,o=new cr.Signature(BigInt(s),BigInt(r)).addRecoveryBit(n);return Xi(o.recoverPublicKey(_i(t).substring(2)))}
3
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */(e))}function pr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function gr(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function yr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function wr(e,...t){if(!pr(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function mr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function br(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function vr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}const Er=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function xr(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!pr(e))throw new Error("Uint8Array expected, got "+typeof e);e=Ar(e)}return e}const Ir=(e,t)=>{function i(i,...s){if(wr(i),!Er)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==e.nonceLength){const t=s[0];if(!t)throw new Error("nonce / iv required");e.varSizeNonce?wr(t):wr(t,e.nonceLength)}const r=e.tagLength;r&&void 0!==s[1]&&wr(s[1]);const n=t(i,...s),o=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");wr(t)}};let a=!1;return{encrypt(e,t){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,wr(e),o(n.encrypt.length,t),n.encrypt(e,t)},decrypt(e,t){if(wr(e),r&&e.length<r)throw new Error("invalid ciphertext length: smaller than tagLength="+r);return o(n.decrypt.length,t),n.decrypt(e,t)}}}return Object.assign(i,e),i};function Sr(e,t,i=!0){if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(i&&t.byteOffset%4!=0)throw new Error("invalid output, must be aligned");return t}function Or(e,t,i,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(i>>r&n),a=Number(i&n),c=s?4:0,h=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+h,a,s)}function _r(e,t,i){gr(i);const s=new Uint8Array(16),r=(n=s,new DataView(n.buffer,n.byteOffset,n.byteLength));var n;return Or(r,0,BigInt(t),i),Or(r,8,BigInt(e),i),s}function Ar(e){return Uint8Array.from(e)}function Pr(e,t,i){return e&t^~e&i}function Tr(e,t,i){return e&t^e&i^t&i}class Br extends Le{constructor(e,t,i,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(e),this.view=xe(this.buffer)}update(e){me(this),ye(e=Ue(e));const{view:t,buffer:i,blockLen:s}=this,r=e.length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o!==s)i.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=xe(e);for(;s<=r-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){me(this),be(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:r}=this;let{pos:n}=this;t[n++]=128,Ee(this.buffer.subarray(n)),this.padOffset>s-n&&(this.process(i,0),n=0);for(let e=n;e<s;e++)t[e]=0;!function(e,t,i,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(i>>r&n),a=Number(i&n),c=s?4:0,h=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+h,a,s)}(i,s-8,BigInt(8*this.length),r),this.process(i,0);const o=xe(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,h[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:r,destroyed:n,pos:o}=this;return e.destroyed=n,e.finished=r,e.length=s,e.pos=o,s%t&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const Rr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Nr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Cr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ur=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),kr=new Uint32Array(64);class Lr extends Br{constructor(e=32){super(64,e,8,!1),this.A=0|Rr[0],this.B=0|Rr[1],this.C=0|Rr[2],this.D=0|Rr[3],this.E=0|Rr[4],this.F=0|Rr[5],this.G=0|Rr[6],this.H=0|Rr[7]}get(){const{A:e,B:t,C:i,D:s,E:r,F:n,G:o,H:a}=this;return[e,t,i,s,r,n,o,a]}set(e,t,i,s,r,n,o,a){this.A=0|e,this.B=0|t,this.C=0|i,this.D=0|s,this.E=0|r,this.F=0|n,this.G=0|o,this.H=0|a}process(e,t){for(let i=0;i<16;i++,t+=4)kr[i]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=kr[e-15],i=kr[e-2],s=Ie(t,7)^Ie(t,18)^t>>>3,r=Ie(i,17)^Ie(i,19)^i>>>10;kr[e]=r+kr[e-7]+s+kr[e-16]|0}let{A:i,B:s,C:r,D:n,E:o,F:a,G:c,H:h}=this;for(let e=0;e<64;e++){const t=h+(Ie(o,6)^Ie(o,11)^Ie(o,25))+Pr(o,a,c)+Ur[e]+kr[e]|0,l=(Ie(i,2)^Ie(i,13)^Ie(i,22))+Tr(i,s,r)|0;h=c,c=a,a=o,o=n+t|0,n=r,r=s,s=i,i=t+l|0}i=i+this.A|0,s=s+this.B|0,r=r+this.C|0,n=n+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(i,s,r,n,o,a,c,h)}roundClean(){Ee(kr)}destroy(){this.set(0,0,0,0,0,0,0,0),Ee(this.buffer)}}const qr=(()=>X(["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((e=>BigInt(e)))))(),Dr=(()=>qr[0])(),Mr=(()=>qr[1])(),$r=new Uint32Array(80),jr=new Uint32Array(80);class zr extends Br{constructor(e=64){super(128,e,16,!1),this.Ah=0|Cr[0],this.Al=0|Cr[1],this.Bh=0|Cr[2],this.Bl=0|Cr[3],this.Ch=0|Cr[4],this.Cl=0|Cr[5],this.Dh=0|Cr[6],this.Dl=0|Cr[7],this.Eh=0|Cr[8],this.El=0|Cr[9],this.Fh=0|Cr[10],this.Fl=0|Cr[11],this.Gh=0|Cr[12],this.Gl=0|Cr[13],this.Hh=0|Cr[14],this.Hl=0|Cr[15]}get(){const{Ah:e,Al:t,Bh:i,Bl:s,Ch:r,Cl:n,Dh:o,Dl:a,Eh:c,El:h,Fh:l,Fl:u,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g]}set(e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|i,this.Bl=0|s,this.Ch=0|r,this.Cl=0|n,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|h,this.Fh=0|l,this.Fl=0|u,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let i=0;i<16;i++,t+=4)$r[i]=e.getUint32(t),jr[i]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|$r[e-15],i=0|jr[e-15],s=ee(t,i,1)^ee(t,i,8)^J(t,0,7),r=te(t,i,1)^te(t,i,8)^Q(t,i,7),n=0|$r[e-2],o=0|jr[e-2],a=ee(n,o,19)^ie(n,o,61)^J(n,0,6),c=te(n,o,19)^se(n,o,61)^Q(n,o,6),h=he(r,c,jr[e-7],jr[e-16]),l=le(h,s,a,$r[e-7],$r[e-16]);$r[e]=0|l,jr[e]=0|h}let{Ah:i,Al:s,Bh:r,Bl:n,Ch:o,Cl:a,Dh:c,Dl:h,Eh:l,El:u,Fh:d,Fl:f,Gh:p,Gl:g,Hh:y,Hl:w}=this;for(let e=0;e<80;e++){const t=ee(l,u,14)^ee(l,u,18)^ie(l,u,41),m=te(l,u,14)^te(l,u,18)^se(l,u,41),b=l&d^~l&p,v=ue(w,m,u&f^~u&g,Mr[e],jr[e]),E=de(v,y,t,b,Dr[e],$r[e]),x=0|v,I=ee(i,s,28)^ie(i,s,34)^ie(i,s,39),S=te(i,s,28)^se(i,s,34)^se(i,s,39),O=i&r^i&o^r&o,_=s&n^s&a^n&a;y=0|p,w=0|g,p=0|d,g=0|f,d=0|l,f=0|u,({h:l,l:u}=oe(0|c,0|h,0|E,0|x)),c=0|o,h=0|a,o=0|r,a=0|n,r=0|i,n=0|s;const A=ae(x,S,_);i=ce(A,E,I,O),s=0|A}({h:i,l:s}=oe(0|this.Ah,0|this.Al,0|i,0|s)),({h:r,l:n}=oe(0|this.Bh,0|this.Bl,0|r,0|n)),({h:o,l:a}=oe(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:h}=oe(0|this.Dh,0|this.Dl,0|c,0|h)),({h:l,l:u}=oe(0|this.Eh,0|this.El,0|l,0|u)),({h:d,l:f}=oe(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=oe(0|this.Gh,0|this.Gl,0|p,0|g)),({h:y,l:w}=oe(0|this.Hh,0|this.Hl,0|y,0|w)),this.set(i,s,r,n,o,a,c,h,l,u,d,f,p,g,y,w)}roundClean(){Ee($r,jr)}destroy(){Ee(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Fr extends zr{constructor(){super(48),this.Ah=0|Nr[0],this.Al=0|Nr[1],this.Bh=0|Nr[2],this.Bl=0|Nr[3],this.Ch=0|Nr[4],this.Cl=0|Nr[5],this.Dh=0|Nr[6],this.Dl=0|Nr[7],this.Eh=0|Nr[8],this.El=0|Nr[9],this.Fh=0|Nr[10],this.Fl=0|Nr[11],this.Gh=0|Nr[12],this.Gl=0|Nr[13],this.Hh=0|Nr[14],this.Hl=0|Nr[15]}}const Kr=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Vr extends zr{constructor(){super(32),this.Ah=0|Kr[0],this.Al=0|Kr[1],this.Bh=0|Kr[2],this.Bl=0|Kr[3],this.Ch=0|Kr[4],this.Cl=0|Kr[5],this.Dh=0|Kr[6],this.Dl=0|Kr[7],this.Eh=0|Kr[8],this.El=0|Kr[9],this.Fh=0|Kr[10],this.Fl=0|Kr[11],this.Gh=0|Kr[12],this.Gl=0|Kr[13],this.Hh=0|Kr[14],this.Hl=0|Kr[15]}}const Hr=qe((()=>new Lr)),Wr=qe((()=>new zr)),Gr=qe((()=>new Fr)),Yr=qe((()=>new Vr)),Zr=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Xr=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Jr=new Uint32Array(32);function Qr(e,t,i,s,r,n){const o=r[n],a=r[n+1];let c=Jr[2*e],h=Jr[2*e+1],l=Jr[2*t],u=Jr[2*t+1],d=Jr[2*i],f=Jr[2*i+1],p=Jr[2*s],g=Jr[2*s+1],y=ae(c,l,o);h=ce(y,h,u,a),c=0|y,({Dh:g,Dl:p}={Dh:g^h,Dl:p^c}),({Dh:g,Dl:p}={Dh:re(0,p),Dl:ne(g)}),({h:f,l:d}=oe(f,d,g,p)),({Bh:u,Bl:l}={Bh:u^f,Bl:l^d}),({Bh:u,Bl:l}={Bh:ee(u,l,24),Bl:te(u,l,24)}),Jr[2*e]=c,Jr[2*e+1]=h,Jr[2*t]=l,Jr[2*t+1]=u,Jr[2*i]=d,Jr[2*i+1]=f,Jr[2*s]=p,Jr[2*s+1]=g}function en(e,t,i,s,r,n){const o=r[n],a=r[n+1];let c=Jr[2*e],h=Jr[2*e+1],l=Jr[2*t],u=Jr[2*t+1],d=Jr[2*i],f=Jr[2*i+1],p=Jr[2*s],g=Jr[2*s+1],y=ae(c,l,o);h=ce(y,h,u,a),c=0|y,({Dh:g,Dl:p}={Dh:g^h,Dl:p^c}),({Dh:g,Dl:p}={Dh:ee(g,p,16),Dl:te(g,p,16)}),({h:f,l:d}=oe(f,d,g,p)),({Bh:u,Bl:l}={Bh:u^f,Bl:l^d}),({Bh:u,Bl:l}={Bh:ie(u,l,63),Bl:se(u,l,63)}),Jr[2*e]=c,Jr[2*e+1]=h,Jr[2*t]=l,Jr[2*t+1]=u,Jr[2*i]=d,Jr[2*i+1]=f,Jr[2*s]=p,Jr[2*s+1]=g}class tn extends Le{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ge(e),ge(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=ve(this.buffer)}update(e){me(this),ye(e=Ue(e));const{blockLen:t,buffer:i,buffer32:s}=this,r=e.length,n=e.byteOffset,o=e.buffer;for(let a=0;a<r;){this.pos===t&&(Ae(s),this.compress(s,0,!1),Ae(s),this.pos=0);const c=Math.min(t-this.pos,r-a),h=n+a;if(c!==t||h%4||!(a+c<r))i.set(e.subarray(a,a+c),this.pos),this.pos+=c,this.length+=c,a+=c;else{const e=new Uint32Array(o,h,Math.floor((r-a)/4));Ae(e);for(let i=0;a+t<r;i+=s.length,a+=t)this.length+=t,this.compress(e,i,!1);Ae(e)}}return this}digestInto(e){me(this),be(e,this);const{pos:t,buffer32:i}=this;this.finished=!0,Ee(this.buffer.subarray(t)),Ae(i),this.compress(i,0,!0),Ae(i);const s=ve(e);this.get().forEach(((e,t)=>s[t]=_e(e)))}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){const{buffer:t,length:i,finished:s,destroyed:r,outputLen:n,pos:o}=this;return e||(e=new this.constructor({dkLen:n})),e.set(...this.get()),e.buffer.set(t),e.destroyed=r,e.finished=s,e.length=i,e.pos=o,e.outputLen=n,e}clone(){return this._cloneInto()}}class sn extends tn{constructor(e={}){const t=void 0===e.dkLen?64:e.dkLen;super(128,t),this.v0l=0|Xr[0],this.v0h=0|Xr[1],this.v1l=0|Xr[2],this.v1h=0|Xr[3],this.v2l=0|Xr[4],this.v2h=0|Xr[5],this.v3l=0|Xr[6],this.v3h=0|Xr[7],this.v4l=0|Xr[8],this.v4h=0|Xr[9],this.v5l=0|Xr[10],this.v5h=0|Xr[11],this.v6l=0|Xr[12],this.v6h=0|Xr[13],this.v7l=0|Xr[14],this.v7h=0|Xr[15],function(e,t={},i,s,r){if(ge(i),e<0||e>i)throw new Error("outputLen bigger than keyLen");const{key:n,salt:o,personalization:a}=t;if(void 0!==n&&(n.length<1||n.length>i))throw new Error("key length must be undefined or 1.."+i);if(void 0!==o&&o.length!==s)throw new Error("salt must be undefined or "+s);if(void 0!==a&&a.length!==r)throw new Error("personalization must be undefined or "+r)}(t,e,64,16,16);let{key:i,personalization:s,salt:r}=e,n=0;if(void 0!==i&&(i=Ue(i),n=i.length),this.v0l^=this.outputLen|n<<8|65536|1<<24,void 0!==r){r=Ue(r);const e=ve(r);this.v4l^=_e(e[0]),this.v4h^=_e(e[1]),this.v5l^=_e(e[2]),this.v5h^=_e(e[3])}if(void 0!==s){s=Ue(s);const e=ve(s);this.v6l^=_e(e[0]),this.v6h^=_e(e[1]),this.v7l^=_e(e[2]),this.v7h^=_e(e[3])}if(void 0!==i){const e=new Uint8Array(this.blockLen);e.set(i),this.update(e)}}get(){let{v0l:e,v0h:t,v1l:i,v1h:s,v2l:r,v2h:n,v3l:o,v3h:a,v4l:c,v4h:h,v5l:l,v5h:u,v6l:d,v6h:f,v7l:p,v7h:g}=this;return[e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g]}set(e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g){this.v0l=0|e,this.v0h=0|t,this.v1l=0|i,this.v1h=0|s,this.v2l=0|r,this.v2h=0|n,this.v3l=0|o,this.v3h=0|a,this.v4l=0|c,this.v4h=0|h,this.v5l=0|l,this.v5h=0|u,this.v6l=0|d,this.v6h=0|f,this.v7l=0|p,this.v7h=0|g}compress(e,t,i){this.get().forEach(((e,t)=>Jr[t]=e)),Jr.set(Xr,16);let{h:s,l:r}=Z(BigInt(this.length));Jr[24]=Xr[8]^r,Jr[25]=Xr[9]^s,i&&(Jr[28]=~Jr[28],Jr[29]=~Jr[29]);let n=0;const o=Zr;for(let i=0;i<12;i++)Qr(0,4,8,12,e,t+2*o[n++]),en(0,4,8,12,e,t+2*o[n++]),Qr(1,5,9,13,e,t+2*o[n++]),en(1,5,9,13,e,t+2*o[n++]),Qr(2,6,10,14,e,t+2*o[n++]),en(2,6,10,14,e,t+2*o[n++]),Qr(3,7,11,15,e,t+2*o[n++]),en(3,7,11,15,e,t+2*o[n++]),Qr(0,5,10,15,e,t+2*o[n++]),en(0,5,10,15,e,t+2*o[n++]),Qr(1,6,11,12,e,t+2*o[n++]),en(1,6,11,12,e,t+2*o[n++]),Qr(2,7,8,13,e,t+2*o[n++]),en(2,7,8,13,e,t+2*o[n++]),Qr(3,4,9,14,e,t+2*o[n++]),en(3,4,9,14,e,t+2*o[n++]);this.v0l^=Jr[0]^Jr[16],this.v0h^=Jr[1]^Jr[17],this.v1l^=Jr[2]^Jr[18],this.v1h^=Jr[3]^Jr[19],this.v2l^=Jr[4]^Jr[20],this.v2h^=Jr[5]^Jr[21],this.v3l^=Jr[6]^Jr[22],this.v3h^=Jr[7]^Jr[23],this.v4l^=Jr[8]^Jr[24],this.v4h^=Jr[9]^Jr[25],this.v5l^=Jr[10]^Jr[26],this.v5h^=Jr[11]^Jr[27],this.v6l^=Jr[12]^Jr[28],this.v6h^=Jr[13]^Jr[29],this.v7l^=Jr[14]^Jr[30],this.v7h^=Jr[15]^Jr[31],Ee(Jr)}destroy(){this.destroyed=!0,Ee(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const rn=De((e=>new sn(e)));const nn=new TextEncoder;function on(e,t,i){e.length>50?function(e,t,i){nn.encodeInto(e,t.subarray(i))}(e,t,i):function(e,t,i){const s=e.length;let r=i,n=0;for(;n<s;){let i=e.charCodeAt(n++);if(0!=(4294967168&i)){if(0==(4294965248&i))t[r++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&n<s){const t=e.charCodeAt(n);56320==(64512&t)&&(++n,i=((1023&i)<<10)+(1023&t)+65536)}0==(4294901760&i)?(t[r++]=i>>12&15|224,t[r++]=i>>6&63|128):(t[r++]=i>>18&7|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128)}t[r++]=63&i|128}else t[r++]=i}}(e,t,i)}const an=4096;function cn(e,t,i){let s=t;const r=s+i,n=[];let o="";for(;s<r;){const t=e[s++];if(0==(128&t))n.push(t);else if(192==(224&t)){const i=63&e[s++];n.push((31&t)<<6|i)}else if(224==(240&t)){const i=63&e[s++],r=63&e[s++];n.push((31&t)<<12|i<<6|r)}else if(240==(248&t)){let i=(7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++];i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i)}else n.push(t);n.length>=an&&(o+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(o+=String.fromCharCode(...n)),o}const hn=new TextDecoder;function ln(e,t,i){return i>200?function(e,t,i){const s=e.subarray(t,t+i);return hn.decode(s)}(e,t,i):cn(e,t,i)}class un{type;data;constructor(e,t){this.type=e,this.data=t}}class dn extends Error{constructor(e){super(e);const t=Object.create(dn.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:dn.name})}}const fn=4294967295;function pn(e,t,i){const s=Math.floor(i/4294967296),r=i;e.setUint32(t,s),e.setUint32(t+4,r)}function gn(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}const yn=4294967295,wn=17179869183;const mn={type:-1,encode:function(e){if(e instanceof Date){return function({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=wn){if(0===t&&e<=yn){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}{const i=e/4294967296,s=4294967295&e,r=new Uint8Array(8),n=new DataView(r.buffer);return n.setUint32(0,t<<2|3&i),n.setUint32(4,s),r}}{const i=new Uint8Array(12),s=new DataView(i.buffer);return s.setUint32(0,t),pn(s,4,e),i}}(function(e){const t=e.getTime(),i=Math.floor(t/1e3),s=1e6*(t-1e3*i),r=Math.floor(s/1e9);return{sec:i+r,nsec:s-1e9*r}}(e))}return null},decode:function(e){const t=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const e=t.getUint32(0);return{sec:4294967296*(3&e)+t.getUint32(4),nsec:e>>>2}}case 12:return{sec:gn(t,4),nsec:t.getUint32(0)};default:throw new dn(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}};class bn{static defaultCodec=new bn;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(mn)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){const s=this.builtInEncoders[i];if(null!=s){const r=s(e,t);if(null!=r){return new un(-1-i,r)}}}for(let i=0;i<this.encoders.length;i++){const s=this.encoders[i];if(null!=s){const r=s(e,t);if(null!=r){return new un(i,r)}}}return e instanceof un?e:null}decode(e,t,i){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,i):new un(t,e)}}function vn(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):function(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}(e)?new Uint8Array(e):Uint8Array.from(e)}class En{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??bn.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??100,this.initialBufferSize=e?.initialBufferSize??2048,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new En({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered){return this.clone().encodeSharedRef(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered){return this.clone().encode(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.useBigInt64&&"bigint"==typeof e?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)}resizeBuffer(e){const t=new ArrayBuffer(e),i=new Uint8Array(t),s=new DataView(t);i.set(this.bytes),this.view=s,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){!1===e?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too long string: ${e} bytes in UTF-8`);this.writeU8(219),this.writeU32(e)}}encodeString(e){const t=function(e){const t=e.length;let i=0,s=0;for(;s<t;){let r=e.charCodeAt(s++);if(0!=(4294967168&r))if(0==(4294965248&r))i+=2;else{if(r>=55296&&r<=56319&&s<t){const t=e.charCodeAt(s);56320==(64512&t)&&(++s,r=((1023&r)<<10)+(1023&t)+65536)}i+=0==(4294901760&r)?3:4}else i++}return i}(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),on(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const i=this.extensionCodec.tryToEncode(e,this.context);if(null!=i)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);this.encodeMap(e,t)}}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large binary: ${t}`);this.writeU8(198),this.writeU32(t)}const i=vn(e);this.writeU8a(i)}encodeArray(e,t){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else{if(!(i<4294967296))throw new Error(`Too large array: ${i}`);this.writeU8(221),this.writeU32(i)}for(const i of e)this.doEncode(i,t+1)}countWithoutUndefined(e,t){let i=0;for(const s of t)void 0!==e[s]&&i++;return i}encodeMap(e,t){const i=Object.keys(e);this.sortKeys&&i.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else{if(!(s<4294967296))throw new Error(`Too large map object: ${s}`);this.writeU8(223),this.writeU32(s)}for(const s of i){const i=e[s];this.ignoreUndefined&&void 0===i||(this.encodeString(s),this.doEncode(i,t+1))}}encodeExtension(e){if("function"==typeof e.data){const t=e.data(this.pos+6),i=t.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);return this.writeU8(201),this.writeU32(i),this.writeI8(e.type),void this.writeU8a(t)}const t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),function(e,t,i){const s=i/4294967296,r=i;e.setUint32(t,s),e.setUint32(t+4,r)}(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),pn(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function xn(e,t){return new En(t).encodeSharedRef(e)}function In(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const Sn="array",On="map_key",_n="map_value",An=e=>{if("string"==typeof e||"number"==typeof e)return e;throw new dn("The type of key must be string or number but "+typeof e)};class Pn{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=Sn,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=On,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Sn){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===On||e.type===_n){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Tn=new DataView(new ArrayBuffer(0)),Bn=new Uint8Array(Tn.buffer);try{Tn.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Rn=new RangeError("Insufficient data"),Nn=new class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=16,t=16){this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){const s=this.caches[i-1];e:for(const r of s){const s=r.bytes;for(let r=0;r<i;r++)if(s[r]!==e[t+r])continue e;return r.str}return null}store(e,t){const i=this.caches[e.length-1],s={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=s:i.push(s)}decode(e,t,i){const s=this.find(e,t,i);if(null!=s)return this.hit++,s;this.miss++;const r=cn(e,t,i),n=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(n,r),r}};class Cn{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Tn;bytes=Bn;headByte=-1;stack=new Pn;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??bn.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??fn,this.maxBinLength=e?.maxBinLength??fn,this.maxArrayLength=e?.maxArrayLength??fn,this.maxMapLength=e?.maxMapLength??fn,this.maxExtLength=e?.maxExtLength??fn,this.keyDecoder=void 0!==e?.keyDecoder?e.keyDecoder:Nn,this.mapKeyConverter=e?.mapKeyConverter??An}clone(){return new Cn({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){const t=vn(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(-1!==this.headByte||this.hasRemaining(1)){const t=this.bytes.subarray(this.pos),i=vn(e),s=new Uint8Array(t.length+i.length);s.set(t),s.set(i,t.length),this.setBuffer(s)}else this.setBuffer(e)}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered){return this.clone().decode(e)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){const t=this.clone();yield*t.decodeMulti(e)}else try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered){return this.clone().decodeAsync(e)}try{this.entered=!0;let t,i=!1;for await(const s of e){if(i)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{t=this.doDecodeSync(),i=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return t}const{headByte:s,pos:r,totalPos:n}=this;throw new RangeError(`Insufficient data in parsing ${In(s)} at ${n} (${r} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){const i=this.clone();yield*i.decodeMultiAsync(e,t)}else try{this.entered=!0;let i=t,s=-1;for await(const r of e){if(t&&0===s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(r),i&&(s=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),0!=--s;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const i=e-128;if(0!==i){this.pushMapState(i),this.complete();continue e}t={}}else if(e<160){const i=e-144;if(0!==i){this.pushArrayState(i),this.complete();continue e}t=[]}else{const i=e-160;t=this.decodeString(i,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===e){const e=this.lookU8();t=this.decodeString(e,1)}else if(218===e){const e=this.lookU16();t=this.decodeString(e,2)}else if(219===e){const e=this.lookU32();t=this.decodeString(e,4)}else if(220===e){const e=this.readU16();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(221===e){const e=this.readU32();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(222===e){const e=this.readU16();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(223===e){const e=this.readU32();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(196===e){const e=this.lookU8();t=this.decodeBinary(e,1)}else if(197===e){const e=this.lookU16();t=this.decodeBinary(e,2)}else if(198===e){const e=this.lookU32();t=this.decodeBinary(e,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){const e=this.lookU8();t=this.decodeExtension(e,1)}else if(200===e){const e=this.lookU16();t=this.decodeExtension(e,2)}else{if(201!==e)throw new dn(`Unrecognized type byte: ${In(e)}`);{const e=this.lookU32();t=this.decodeExtension(e,4)}}this.complete();const i=this.stack;for(;i.length>0;){const e=i.top();if(e.type===Sn){if(e.array[e.position]=t,e.position++,e.position!==e.size)continue e;t=e.array,i.release(e)}else{if(e.type===On){if("__proto__"===t)throw new dn("The key __proto__ is not allowed");e.key=this.mapKeyConverter(t),e.type=_n;continue e}if(e.map[e.key]=t,e.readCount++,e.readCount!==e.size){e.key=null,e.type=On;continue e}t=e.map,i.release(e)}}return t}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new dn(`Unrecognized array type byte: ${In(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new dn(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new dn(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new dn(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Rn;const i=this.pos+t;let s;return s=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,i,e):ln(this.bytes,i,e),this.pos+=t+e,s}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===On}return!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new dn(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Rn;const i=this.pos+t,s=this.bytes.subarray(i,i+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new dn(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=(t=this.view,i=this.pos,4294967296*t.getUint32(i)+t.getUint32(i+4));var t,i;return this.pos+=8,e}readI64(){const e=gn(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Un(e,t){return new Cn(t).decode(e)}
4
+ /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function kn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Ln(e,t){return!!Array.isArray(t)&&(0===t.length||(e?t.every((e=>"string"==typeof e)):t.every((e=>Number.isSafeInteger(e)))))}function qn(e){if("function"!=typeof e)throw new Error("function expected");return!0}function Dn(e,t){if("string"!=typeof t)throw new Error(`${e}: string expected`);return!0}function Mn(e){if(!Number.isSafeInteger(e))throw new Error(`invalid integer: ${e}`)}function $n(e){if(!Array.isArray(e))throw new Error("array expected")}function jn(e,t){if(!Ln(!0,t))throw new Error(`${e}: array of strings expected`)}function zn(e,t){if(!Ln(!1,t))throw new Error(`${e}: array of numbers expected`)}function Fn(...e){const t=e=>e,i=(e,t)=>i=>e(t(i)),s=e.map((e=>e.encode)).reduceRight(i,t),r=e.map((e=>e.decode)).reduce(i,t);return{encode:s,decode:r}}function Kn(e){const t="string"==typeof e?e.split(""):e,i=t.length;jn("alphabet",t);const s=new Map(t.map(((e,t)=>[e,t])));return{encode:s=>($n(s),s.map((s=>{if(!Number.isSafeInteger(s)||s<0||s>=i)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${e}`);return t[s]}))),decode:t=>($n(t),t.map((t=>{Dn("alphabet.decode",t);const i=s.get(t);if(void 0===i)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return i})))}}function Vn(e=""){return Dn("join",e),{encode:t=>(jn("join.decode",t),t.join(e)),decode:t=>(Dn("join.decode",t),t.split(e))}}function Hn(e,t="="){return Mn(e),Dn("padding",t),{encode(i){for(jn("padding.encode",i);i.length*e%8;)i.push(t);return i},decode(i){jn("padding.decode",i);let s=i.length;if(s*e%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;s>0&&i[s-1]===t;s--){if((s-1)*e%8==0)throw new Error("padding: invalid, string has too much padding")}return i.slice(0,s)}}}function Wn(e){return qn(e),{encode:e=>e,decode:t=>e(t)}}function Gn(e,t,i){if(t<2)throw new Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(i<2)throw new Error(`convertRadix: invalid to=${i}, base cannot be less than 2`);if($n(e),!e.length)return[];let s=0;const r=[],n=Array.from(e,(e=>{if(Mn(e),e<0||e>=t)throw new Error(`invalid integer: ${e}`);return e})),o=n.length;for(;;){let e=0,a=!0;for(let r=s;r<o;r++){const o=n[r],c=t*e,h=c+o;if(!Number.isSafeInteger(h)||c/t!==e||h-o!==c)throw new Error("convertRadix: carry overflow");const l=h/i;e=h%i;const u=Math.floor(l);if(n[r]=u,!Number.isSafeInteger(u)||u*i+e!==h)throw new Error("convertRadix: carry overflow");a&&(u?a=!1:s=r)}if(r.push(e),a)break}for(let t=0;t<e.length-1&&0===e[t];t++)r.push(0);return r.reverse()}const Yn=(e,t)=>0===t?e:Yn(t,e%t),Zn=(e,t)=>e+(t-Yn(e,t)),Xn=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function Jn(e,t,i,s){if($n(e),t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(i<=0||i>32)throw new Error(`convertRadix2: wrong to=${i}`);if(Zn(t,i)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${i} carryBits=${Zn(t,i)}`);let r=0,n=0;const o=Xn[t],a=Xn[i]-1,c=[];for(const s of e){if(Mn(s),s>=o)throw new Error(`convertRadix2: invalid data word=${s} from=${t}`);if(r=r<<t|s,n+t>32)throw new Error(`convertRadix2: carry overflow pos=${n} from=${t}`);for(n+=t;n>=i;n-=i)c.push((r>>n-i&a)>>>0);const e=Xn[n];if(void 0===e)throw new Error("invalid carry");r&=e-1}if(r=r<<i-n&a,!s&&n>=t)throw new Error("Excess padding");if(!s&&r>0)throw new Error(`Non-zero padding: ${r}`);return s&&n>0&&c.push(r>>>0),c}function Qn(e,t=!1){if(Mn(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(Zn(8,e)>32||Zn(e,8)>32)throw new Error("radix2: carry overflow");return{encode:i=>{if(!kn(i))throw new Error("radix2.encode input should be Uint8Array");return Jn(Array.from(i),8,e,!t)},decode:i=>(zn("radix2.decode",i),Uint8Array.from(Jn(i,e,8,t)))}}function eo(e){return qn(e),function(...t){try{return e.apply(null,t)}catch(e){}}}Fn(Qn(4),Kn("0123456789ABCDEF"),Vn(""));const to=Fn(Qn(5),Kn("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Hn(5),Vn(""));Fn(Qn(5),Kn("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Vn("")),Fn(Qn(5),Kn("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Hn(5),Vn("")),Fn(Qn(5),Kn("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Vn("")),Fn(Qn(5),Kn("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Vn(""),Wn((e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))));const io=(()=>"function"==typeof Uint8Array.from([]).toBase64&&"function"==typeof Uint8Array.fromBase64)();io||Fn(Qn(6),Kn("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Hn(6),Vn("")),Fn(Qn(6),Kn("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Vn("")),io||Fn(Qn(6),Kn("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Hn(6),Vn("")),Fn(Qn(6),Kn("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Vn(""));const so=e=>{return Fn((Mn(t=58),{encode:e=>{if(!kn(e))throw new Error("radix.encode input should be Uint8Array");return Gn(Array.from(e),256,t)},decode:e=>(zn("radix.decode",e),Uint8Array.from(Gn(e,t,256)))}),Kn(e),Vn(""));var t},ro=so("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");so("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),so("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const no=Fn(Kn("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Vn("")),oo=[996825010,642813549,513874426,1027748829,705979059];function ao(e){const t=e>>25;let i=(33554431&e)<<5;for(let e=0;e<oo.length;e++)1==(t>>e&1)&&(i^=oo[e]);return i}function co(e,t,i=1){const s=e.length;let r=1;for(let t=0;t<s;t++){const i=e.charCodeAt(t);if(i<33||i>126)throw new Error(`Invalid prefix (${e})`);r=ao(r)^i>>5}r=ao(r);for(let t=0;t<s;t++)r=ao(r)^31&e.charCodeAt(t);for(let e of t)r=ao(r)^e;for(let e=0;e<6;e++)r=ao(r);return r^=i,no.encode(Jn([r%Xn[30]],30,5,!1))}function ho(e){const t="bech32"===e?1:734539939,i=Qn(5),s=i.decode,r=i.encode,n=eo(s);function o(e,i,s=90){Dn("bech32.encode prefix",e),kn(i)&&(i=Array.from(i)),zn("bech32.encode",i);const r=e.length;if(0===r)throw new TypeError(`Invalid prefix length ${r}`);const n=r+7+i.length;if(!1!==s&&n>s)throw new TypeError(`Length ${n} exceeds limit ${s}`);const o=e.toLowerCase(),a=co(o,i,t);return`${o}1${no.encode(i)}${a}`}function a(e,i=90){Dn("bech32.decode input",e);const s=e.length;if(s<8||!1!==i&&s>i)throw new TypeError(`invalid string length: ${s} (${e}). Expected (8..${i})`);const r=e.toLowerCase();if(e!==r&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const n=r.lastIndexOf("1");if(0===n||-1===n)throw new Error('Letter "1" must be present between prefix and data only');const o=r.slice(0,n),a=r.slice(n+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const c=no.decode(a).slice(0,-6),h=co(o,c,t);if(!a.endsWith(h))throw new Error(`Invalid checksum in ${e}: expected "${h}"`);return{prefix:o,words:c}}return{encode:o,decode:a,encodeFromBytes:function(e,t){return o(e,r(t))},decodeToBytes:function(e){const{prefix:t,words:i}=a(e,!1);return{prefix:t,words:i,bytes:s(i)}},decodeUnsafe:eo(a),fromWords:s,fromWordsUnsafe:n,toWords:r}}ho("bech32"),ho("bech32m");function lo(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function uo(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?lo(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function fo(e,t){t||(t=e.reduce(((e,t)=>e+t.length),0));const i=uo(t);let s=0;for(const t of e)i.set(t,s),s+=t.length;return lo(i)}(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)()||Fn(Qn(4),Kn("0123456789abcdef"),Vn(""),Wn((e=>{if("string"!=typeof e||e.length%2!=0)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})));var po=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),s=0;s<i.length;s++)i[s]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==i[o])throw new TypeError(n+" is ambiguous");i[o]=r}var a=e.length,c=e.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var s=0,r=0;e[t]===c;)s++,t++;for(var n=(e.length-t)*h+1>>>0,o=new Uint8Array(n);e[t];){var l=i[e.charCodeAt(t)];if(255===l)return;for(var u=0,d=n-1;(0!==l||u<r)&&-1!==d;d--,u++)l+=a*o[d]>>>0,o[d]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=u,t++}if(" "!==e[t]){for(var f=n-r;f!==n&&0===o[f];)f++;for(var p=new Uint8Array(s+(n-f)),g=s;f!==n;)p[g++]=o[f++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,s=0,r=0,n=t.length;r!==n&&0===t[r];)r++,i++;for(var o=(n-r)*l+1>>>0,h=new Uint8Array(o);r!==n;){for(var u=t[r],d=0,f=o-1;(0!==u||d<s)&&-1!==f;f--,d++)u+=256*h[f]>>>0,h[f]=u%a>>>0,u=u/a>>>0;if(0!==u)throw new Error("Non-zero carry");s=d,r++}for(var p=o-s;p!==o&&0===h[p];)p++;for(var g=c.repeat(i);p<o;++p)g+=e.charAt(h[p]);return g},decodeUnsafe:u,decode:function(e){var i=u(e);if(i)return i;throw new Error(`Non-${t} character`)}}},go=po;const yo=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class wo{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class mo{constructor(e,t,i){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return vo(this,e)}}class bo{constructor(e){this.decoders=e}or(e){return vo(this,e)}decode(e){const t=e[0],i=this.decoders[t];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 vo=(e,t)=>new bo({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Eo{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new wo(e,t,i),this.decoder=new mo(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const xo=({name:e,prefix:t,encode:i,decode:s})=>new Eo(e,t,i,s),Io=({prefix:e,name:t,alphabet:i})=>{const{encode:s,decode:r}=go(i,t);return xo({prefix:e,name:t,encode:s,decode:e=>yo(r(e))})},So=({name:e,prefix:t,bitsPerChar:i,alphabet:s})=>xo({prefix:t,name:e,encode:e=>((e,t,i)=>{const s="="===t[t.length-1],r=(1<<i)-1;let n="",o=0,a=0;for(let s=0;s<e.length;++s)for(a=a<<8|e[s],o+=8;o>i;)o-=i,n+=t[r&a>>o];if(o&&(n+=t[r&a<<i-o]),s)for(;n.length*i&7;)n+="=";return n})(e,s,i),decode:t=>((e,t,i,s)=>{const r={};for(let e=0;e<t.length;++e)r[t[e]]=e;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,h=0;for(let t=0;t<n;++t){const n=r[e[t]];if(void 0===n)throw new SyntaxError(`Non-${s} character`);c=c<<i|n,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,s,i,e)}),Oo=xo({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var _o=Object.freeze({__proto__:null,identity:Oo});const Ao=So({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Po=Object.freeze({__proto__:null,base2:Ao});const To=So({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Bo=Object.freeze({__proto__:null,base8:To});const Ro=Io({prefix:"9",name:"base10",alphabet:"0123456789"});var No=Object.freeze({__proto__:null,base10:Ro});const Co=So({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Uo=So({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ko=Object.freeze({__proto__:null,base16:Co,base16upper:Uo});const Lo=So({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),qo=So({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Do=So({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Mo=So({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$o=So({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jo=So({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zo=So({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Fo=So({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ko=So({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Vo=Object.freeze({__proto__:null,base32:Lo,base32upper:qo,base32pad:Do,base32padupper:Mo,base32hex:$o,base32hexupper:jo,base32hexpad:zo,base32hexpadupper:Fo,base32z:Ko});const Ho=Io({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Wo=Io({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Go=Object.freeze({__proto__:null,base36:Ho,base36upper:Wo});const Yo=Io({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Zo=Io({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Xo=Object.freeze({__proto__:null,base58btc:Yo,base58flickr:Zo});const Jo=So({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Qo=So({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ea=So({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ta=So({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ia=Object.freeze({__proto__:null,base64:Jo,base64pad:Qo,base64url:ea,base64urlpad:ta});const sa=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ra=sa.reduce(((e,t,i)=>(e[i]=t,e)),[]),na=sa.reduce(((e,t,i)=>(e[t.codePointAt(0)]=i,e)),[]);const oa=xo({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=ra[t]),"")},decode:function(e){const t=[];for(const i of e){const e=na[i.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}});var aa=Object.freeze({__proto__:null,base256emoji:oa}),ca=function e(t,i,s){i=i||[];var r=s=s||0;for(;t>=ua;)i[s++]=255&t|ha,t/=128;for(;t&la;)i[s++]=255&t|ha,t>>>=7;return i[s]=0|t,e.bytes=s-r+1,i},ha=128,la=-128,ua=Math.pow(2,31);var da=function e(t,i){var s,r=0,n=0,o=i=i||0,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=n<28?(s&pa)<<n:(s&pa)*Math.pow(2,n),n+=7}while(s>=fa);return e.bytes=o-i,r},fa=128,pa=127;var ga=Math.pow(2,7),ya=Math.pow(2,14),wa=Math.pow(2,21),ma=Math.pow(2,28),ba=Math.pow(2,35),va=Math.pow(2,42),Ea=Math.pow(2,49),xa=Math.pow(2,56),Ia=Math.pow(2,63),Sa={encode:ca,decode:da,encodingLength:function(e){return e<ga?1:e<ya?2:e<wa?3:e<ma?4:e<ba?5:e<va?6:e<Ea?7:e<xa?8:e<Ia?9:10}};const Oa=(e,t,i=0)=>(Sa.encode(e,t,i),t),_a=e=>Sa.encodingLength(e),Aa=(e,t)=>{const i=t.byteLength,s=_a(e),r=s+_a(i),n=new Uint8Array(r+i);return Oa(e,n,0),Oa(i,n,s),n.set(t,r),new Pa(e,i,t,n)};class Pa{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const Ta=({name:e,code:t,encode:i})=>new Ba(e,t,i);class Ba{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Aa(this.code,t):t.then((e=>Aa(this.code,e)))}throw Error("Unknown type, must be binary type")}}const Ra=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t));Ta({name:"sha2-256",code:18,encode:Ra("SHA-256")}),Ta({name:"sha2-512",code:19,encode:Ra("SHA-512")});new TextEncoder,new TextDecoder;const Na={..._o,...Po,...Bo,...No,...ko,...Vo,...Go,...Xo,...ia,...aa};function Ca(e,t,i,s){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:s}}}const Ua=Ca("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),ka=Ca("ascii","a",(e=>{let t="a";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t}),(e=>{const t=uo((e=e.substring(1)).length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t})),La={utf8:Ua,"utf-8":Ua,hex:Na.base16,latin1:ka,ascii:ka,binary:ka,...Na};function qa(e,t="utf8"){const i=La[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.decoder.decode(`${i.prefix}${e}`):lo(globalThis.Buffer.from(e,"utf-8"))}function Da(e,t="utf8"){const i=La[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.encoder.encode(e).substring(1):globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}const Ma=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),$a=Ma("expand 16-byte k"),ja=Ma("expand 32-byte k"),za=br($a),Fa=br(ja);function Ka(e,t){return e<<t|e>>>32-t}function Va(e){return e.byteOffset%4==0}const Ha=64,Wa=16,Ga=2**32-1,Ya=new Uint32Array;function Za(e,t){const{allowShortKeys:i,extendNonceFn:s,counterLength:r,counterRight:n,rounds:o}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return yr(r),yr(o),gr(n),gr(i),(t,a,c,h,l=0)=>{wr(t),wr(a),wr(c);const u=c.length;if(void 0===h&&(h=new Uint8Array(u)),wr(h),yr(l),l<0||l>=Ga)throw new Error("arx: counter overflow");if(h.length<u)throw new Error(`arx: output (${h.length}) is shorter than data (${u})`);const d=[];let f,p,g=t.length;if(32===g)d.push(f=Ar(t)),p=Fa;else{if(16!==g||!i)throw new Error(`arx: invalid 32-byte key, got length=${g}`);f=new Uint8Array(32),f.set(t),f.set(t,16),p=za,d.push(f)}Va(a)||d.push(a=Ar(a));const y=br(f);if(s){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");s(p,y,br(a.subarray(0,16)),y),a=a.subarray(16)}const w=16-r;if(w!==a.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(12!==w){const e=new Uint8Array(12);e.set(a,n?0:12-a.length),a=e,d.push(a)}const m=br(a);return function(e,t,i,s,r,n,o,a){const c=r.length,h=new Uint8Array(Ha),l=br(h),u=Va(r)&&Va(n),d=u?br(r):Ya,f=u?br(n):Ya;for(let p=0;p<c;o++){if(e(t,i,s,l,o,a),o>=Ga)throw new Error("arx: counter overflow");const g=Math.min(Ha,c-p);if(u&&g===Ha){const e=p/4;if(p%4!=0)throw new Error("arx: invalid block position");for(let t,i=0;i<Wa;i++)t=e+i,f[t]=d[t]^l[i];p+=Ha}else{for(let e,t=0;t<g;t++)e=p+t,n[e]=r[e]^h[t];p+=g}}}(e,p,y,m,c,h,l,o),vr(...d),h}}const Xa=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Ja{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,wr(e=xr(e),32);const t=Xa(e,0),i=Xa(e,2),s=Xa(e,4),r=Xa(e,6),n=Xa(e,8),o=Xa(e,10),a=Xa(e,12),c=Xa(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|i<<3),this.r[2]=7939&(i>>>10|s<<6),this.r[3]=8191&(s>>>7|r<<9),this.r[4]=255&(r>>>4|n<<12),this.r[5]=n>>>1&8190,this.r[6]=8191&(n>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Xa(e,16+2*t)}process(e,t,i=!1){const s=i?0:2048,{h:r,r:n}=this,o=n[0],a=n[1],c=n[2],h=n[3],l=n[4],u=n[5],d=n[6],f=n[7],p=n[8],g=n[9],y=Xa(e,t+0),w=Xa(e,t+2),m=Xa(e,t+4),b=Xa(e,t+6),v=Xa(e,t+8),E=Xa(e,t+10),x=Xa(e,t+12),I=Xa(e,t+14);let S=r[0]+(8191&y),O=r[1]+(8191&(y>>>13|w<<3)),_=r[2]+(8191&(w>>>10|m<<6)),A=r[3]+(8191&(m>>>7|b<<9)),P=r[4]+(8191&(b>>>4|v<<12)),T=r[5]+(v>>>1&8191),B=r[6]+(8191&(v>>>14|E<<2)),R=r[7]+(8191&(E>>>11|x<<5)),N=r[8]+(8191&(x>>>8|I<<8)),C=r[9]+(I>>>5|s),U=0,k=U+S*o+O*(5*g)+_*(5*p)+A*(5*f)+P*(5*d);U=k>>>13,k&=8191,k+=T*(5*u)+B*(5*l)+R*(5*h)+N*(5*c)+C*(5*a),U+=k>>>13,k&=8191;let L=U+S*a+O*o+_*(5*g)+A*(5*p)+P*(5*f);U=L>>>13,L&=8191,L+=T*(5*d)+B*(5*u)+R*(5*l)+N*(5*h)+C*(5*c),U+=L>>>13,L&=8191;let q=U+S*c+O*a+_*o+A*(5*g)+P*(5*p);U=q>>>13,q&=8191,q+=T*(5*f)+B*(5*d)+R*(5*u)+N*(5*l)+C*(5*h),U+=q>>>13,q&=8191;let D=U+S*h+O*c+_*a+A*o+P*(5*g);U=D>>>13,D&=8191,D+=T*(5*p)+B*(5*f)+R*(5*d)+N*(5*u)+C*(5*l),U+=D>>>13,D&=8191;let M=U+S*l+O*h+_*c+A*a+P*o;U=M>>>13,M&=8191,M+=T*(5*g)+B*(5*p)+R*(5*f)+N*(5*d)+C*(5*u),U+=M>>>13,M&=8191;let $=U+S*u+O*l+_*h+A*c+P*a;U=$>>>13,$&=8191,$+=T*o+B*(5*g)+R*(5*p)+N*(5*f)+C*(5*d),U+=$>>>13,$&=8191;let j=U+S*d+O*u+_*l+A*h+P*c;U=j>>>13,j&=8191,j+=T*a+B*o+R*(5*g)+N*(5*p)+C*(5*f),U+=j>>>13,j&=8191;let z=U+S*f+O*d+_*u+A*l+P*h;U=z>>>13,z&=8191,z+=T*c+B*a+R*o+N*(5*g)+C*(5*p),U+=z>>>13,z&=8191;let F=U+S*p+O*f+_*d+A*u+P*l;U=F>>>13,F&=8191,F+=T*h+B*c+R*a+N*o+C*(5*g),U+=F>>>13,F&=8191;let K=U+S*g+O*p+_*f+A*d+P*u;U=K>>>13,K&=8191,K+=T*l+B*h+R*c+N*a+C*o,U+=K>>>13,K&=8191,U=(U<<2)+U|0,U=U+k|0,k=8191&U,U>>>=13,L+=U,r[0]=k,r[1]=L,r[2]=q,r[3]=D,r[4]=M,r[5]=$,r[6]=j,r[7]=z,r[8]=F,r[9]=K}finalize(){const{h:e,pad:t}=this,i=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=s,s=e[t]>>>13,e[t]&=8191;e[0]+=5*s,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 t=1;t<10;t++)i[t]=e[t]+s,s=i[t]>>>13,i[t]&=8191;i[9]-=8192;let r=(1^s)-1;for(let e=0;e<10;e++)i[e]&=r;r=~r;for(let t=0;t<10;t++)e[t]=e[t]&r|i[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let n=e[0]+t[0];e[0]=65535&n;for(let i=1;i<8;i++)n=(e[i]+t[i]|0)+(n>>>16)|0,e[i]=65535&n;vr(i)}update(e){mr(this),wr(e=xr(e));const{buffer:t,blockLen:i}=this,s=e.length;for(let r=0;r<s;){const n=Math.min(i-this.pos,s-r);if(n!==i)t.set(e.subarray(r,r+n),this.pos),this.pos+=n,r+=n,this.pos===i&&(this.process(t,0,!1),this.pos=0);else for(;i<=s-r;r+=i)this.process(e,r)}return this}destroy(){vr(this.h,this.r,this.buffer,this.pad)}digestInto(e){mr(this),function(e,t){wr(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}(e,this),this.finished=!0;const{buffer:t,h:i}=this;let{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let r=0;for(let t=0;t<8;t++)e[r++]=i[t]>>>0,e[r++]=i[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}}const Qa=function(e){const t=(t,i)=>e(i).update(xr(t)).digest(),i=e(new Uint8Array(32));return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=t=>e(t),t}((e=>new Ja(e)));function ec(e,t,i,s,r,n=20){let o=e[0],a=e[1],c=e[2],h=e[3],l=t[0],u=t[1],d=t[2],f=t[3],p=t[4],g=t[5],y=t[6],w=t[7],m=r,b=i[0],v=i[1],E=i[2],x=o,I=a,S=c,O=h,_=l,A=u,P=d,T=f,B=p,R=g,N=y,C=w,U=m,k=b,L=v,q=E;for(let e=0;e<n;e+=2)x=x+_|0,U=Ka(U^x,16),B=B+U|0,_=Ka(_^B,12),x=x+_|0,U=Ka(U^x,8),B=B+U|0,_=Ka(_^B,7),I=I+A|0,k=Ka(k^I,16),R=R+k|0,A=Ka(A^R,12),I=I+A|0,k=Ka(k^I,8),R=R+k|0,A=Ka(A^R,7),S=S+P|0,L=Ka(L^S,16),N=N+L|0,P=Ka(P^N,12),S=S+P|0,L=Ka(L^S,8),N=N+L|0,P=Ka(P^N,7),O=O+T|0,q=Ka(q^O,16),C=C+q|0,T=Ka(T^C,12),O=O+T|0,q=Ka(q^O,8),C=C+q|0,T=Ka(T^C,7),x=x+A|0,q=Ka(q^x,16),N=N+q|0,A=Ka(A^N,12),x=x+A|0,q=Ka(q^x,8),N=N+q|0,A=Ka(A^N,7),I=I+P|0,U=Ka(U^I,16),C=C+U|0,P=Ka(P^C,12),I=I+P|0,U=Ka(U^I,8),C=C+U|0,P=Ka(P^C,7),S=S+T|0,k=Ka(k^S,16),B=B+k|0,T=Ka(T^B,12),S=S+T|0,k=Ka(k^S,8),B=B+k|0,T=Ka(T^B,7),O=O+_|0,L=Ka(L^O,16),R=R+L|0,_=Ka(_^R,12),O=O+_|0,L=Ka(L^O,8),R=R+L|0,_=Ka(_^R,7);let D=0;s[D++]=o+x|0,s[D++]=a+I|0,s[D++]=c+S|0,s[D++]=h+O|0,s[D++]=l+_|0,s[D++]=u+A|0,s[D++]=d+P|0,s[D++]=f+T|0,s[D++]=p+B|0,s[D++]=g+R|0,s[D++]=y+N|0,s[D++]=w+C|0,s[D++]=m+U|0,s[D++]=b+k|0,s[D++]=v+L|0,s[D++]=E+q|0}const tc=Za(ec,{counterRight:!1,counterLength:4,allowShortKeys:!1}),ic=new Uint8Array(16),sc=(e,t)=>{e.update(t);const i=t.length%16;i&&e.update(ic.subarray(i))},rc=new Uint8Array(32);function nc(e,t,i,s,r){const n=e(t,i,rc),o=Qa.create(n);r&&sc(o,r),sc(o,s);const a=_r(s.length,r?r.length:0,!0);o.update(a);const c=o.digest();return vr(n,a),c}const oc=Ir({blockSize:64,nonceLength:12,tagLength:16},(ac=tc,(e,t,i)=>{const s=16;return{encrypt(r,n){const o=r.length;(n=Sr(o+s,n,!1)).set(r);const a=n.subarray(0,-16);ac(e,t,a,a,1);const c=nc(ac,e,t,a,i);return n.set(c,o),vr(c),n},decrypt(r,n){n=Sr(r.length-s,n,!1);const o=r.subarray(0,-16),a=r.subarray(-16),c=nc(ac,e,t,o,i);if(!function(e,t){if(e.length!==t.length)return!1;let i=0;for(let s=0;s<e.length;s++)i|=e[s]^t[s];return 0===i}(a,c))throw new Error("invalid tag");return n.set(r.subarray(0,-16)),ac(e,t,n,n,1),vr(c),n}}}));var ac;class cc extends Le{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,we(e);const i=Ue(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)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,r=new Uint8Array(s);r.set(i.length>s?e.create().update(i).digest():i);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),Ee(r)}update(e){return me(this),this.iHash.update(e),this}digestInto(e){me(this),ye(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:t,iHash:i,finished:s,destroyed:r,blockLen:n,outputLen:o}=this;return e.finished=s,e.destroyed=r,e.blockLen=n,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hc=(e,t,i)=>new cc(e,t).update(i).digest();hc.create=(e,t)=>new cc(e,t);const lc=Uint8Array.from([0]),uc=Uint8Array.of();const dc=(e,t,i,s,r)=>function(e,t,i,s=32){we(e),ge(s);const r=e.outputLen;if(s>255*r)throw new Error("Length should be <= 255*HashLen");const n=Math.ceil(s/r);void 0===i&&(i=uc);const o=new Uint8Array(n*r),a=hc.create(e,t),c=a._cloneInto(),h=new Uint8Array(a.outputLen);for(let e=0;e<n;e++)lc[0]=e+1,c.update(0===e?uc:h).update(i).update(lc).digestInto(h),o.set(h,r*e),a._cloneInto(c);return a.destroy(),c.destroy(),Ee(h,lc),o.slice(0,s)}(e,function(e,t,i){return we(e),void 0===i&&(i=new Uint8Array(e.outputLen)),hc(e,Ue(i),Ue(t))}(e,t,i),s,r),fc=Hr,pc=BigInt(0),gc=BigInt(1);function yc(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function wc(e,t,i=""){const s=pe(e),r=e?.length,n=void 0!==t;if(!s||n&&r!==t){throw new Error((i&&`"${i}" `)+"expected Uint8Array"+(n?` of length ${t}`:"")+", got "+(s?`length=${r}`:"type="+typeof e))}return e}function mc(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function bc(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?pc:BigInt("0x"+e)}function vc(e){return bc(Be(e))}function Ec(e){return ye(e),bc(Be(Uint8Array.from(e).reverse()))}function xc(e,t){return Ce(e.toString(16).padStart(2*t,"0"))}function Ic(e,t){return xc(e,t).reverse()}function Sc(e,t,i){let s;if("string"==typeof t)try{s=Ce(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!pe(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const r=s.length;if("number"==typeof i&&r!==i)throw new Error(e+" of length "+i+" expected, got "+r);return s}function Oc(e){return Uint8Array.from(e)}const _c=e=>"bigint"==typeof e&&pc<=e;function Ac(e,t,i,s){if(!function(e,t,i){return _c(e)&&_c(t)&&_c(i)&&t<=e&&e<i}(t,i,s))throw new Error("expected valid "+e+": "+i+" <= n < "+s+", got "+t)}function Pc(e){let t;for(t=0;e>pc;e>>=gc,t+=1);return t}const Tc=e=>(gc<<BigInt(e))-gc;function Bc(e,t,i={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function s(t,i,s){const r=e[t];if(s&&void 0===r)return;const n=typeof r;if(n!==i||null===r)throw new Error(`param "${t}" is invalid: expected ${i}, got ${n}`)}Object.entries(t).forEach((([e,t])=>s(e,t,!1))),Object.entries(i).forEach((([e,t])=>s(e,t,!0)))}const Rc=()=>{throw new Error("not implemented")};function Nc(e){const t=new WeakMap;return(i,...s)=>{const r=t.get(i);if(void 0!==r)return r;const n=e(i,...s);return t.set(i,n),n}}const Cc=BigInt(0),Uc=BigInt(1),kc=BigInt(2),Lc=BigInt(3),qc=BigInt(4),Dc=BigInt(5),Mc=BigInt(7),$c=BigInt(8),jc=BigInt(9),zc=BigInt(16);function Fc(e,t){const i=e%t;return i>=Cc?i:t+i}function Kc(e,t,i){let s=e;for(;t-- >Cc;)s*=s,s%=i;return s}function Vc(e,t){if(e===Cc)throw new Error("invert: expected non-zero number");if(t<=Cc)throw new Error("invert: expected positive modulus, got "+t);let i=Fc(e,t),s=t,r=Cc,n=Uc;for(;i!==Cc;){const e=s%i,t=r-n*(s/i);s=i,i=e,r=n,n=t}if(s!==Uc)throw new Error("invert: does not exist");return Fc(r,t)}function Hc(e,t,i){if(!e.eql(e.sqr(t),i))throw new Error("Cannot find square root")}function Wc(e,t){const i=(e.ORDER+Uc)/qc,s=e.pow(t,i);return Hc(e,s,t),s}function Gc(e,t){const i=(e.ORDER-Dc)/$c,s=e.mul(t,kc),r=e.pow(s,i),n=e.mul(t,r),o=e.mul(e.mul(n,kc),r),a=e.mul(n,e.sub(o,e.ONE));return Hc(e,a,t),a}function Yc(e){if(e<Lc)throw new Error("sqrt is not defined for small field");let t=e-Uc,i=0;for(;t%kc===Cc;)t/=kc,i++;let s=kc;const r=ih(e);for(;1===eh(r,s);)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===i)return Wc;let n=r.pow(s,t);const o=(t+Uc)/kc;return function(e,s){if(e.is0(s))return s;if(1!==eh(e,s))throw new Error("Cannot find square root");let r=i,a=e.mul(e.ONE,n),c=e.pow(s,t),h=e.pow(s,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,i=e.sqr(c);for(;!e.eql(i,e.ONE);)if(t++,i=e.sqr(i),t===r)throw new Error("Cannot find square root");const s=Uc<<BigInt(r-t-1),n=e.pow(a,s);r=t,a=e.sqr(n),c=e.mul(c,a),h=e.mul(h,n)}return h}}function Zc(e){return e%qc===Lc?Wc:e%$c===Dc?Gc:e%zc===jc?function(e){const t=ih(e),i=Yc(e),s=i(t,t.neg(t.ONE)),r=i(t,s),n=i(t,t.neg(s)),o=(e+Mc)/zc;return(e,t)=>{let i=e.pow(t,o),a=e.mul(i,s);const c=e.mul(i,r),h=e.mul(i,n),l=e.eql(e.sqr(a),t),u=e.eql(e.sqr(c),t);i=e.cmov(i,a,l),a=e.cmov(h,c,u);const d=e.eql(e.sqr(a),t),f=e.cmov(i,a,d);return Hc(e,f,t),f}}(e):Yc(e)}const Xc=(e,t)=>(Fc(e,t)&Uc)===Uc,Jc=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Qc(e,t,i=!1){const s=new Array(t.length).fill(i?e.ZERO:void 0),r=t.reduce(((t,i,r)=>e.is0(i)?t:(s[r]=t,e.mul(t,i))),e.ONE),n=e.inv(r);return t.reduceRight(((t,i,r)=>e.is0(i)?t:(s[r]=e.mul(t,s[r]),e.mul(t,i))),n),s}function eh(e,t){const i=(e.ORDER-Uc)/kc,s=e.pow(t,i),r=e.eql(s,e.ONE),n=e.eql(s,e.ZERO),o=e.eql(s,e.neg(e.ONE));if(!r&&!n&&!o)throw new Error("invalid Legendre symbol result");return r?1:n?0:-1}function th(e,t){void 0!==t&&ge(t);const i=void 0!==t?t:e.toString(2).length;return{nBitLength:i,nByteLength:Math.ceil(i/8)}}function ih(e,t,i=!1,s={}){if(e<=Cc)throw new Error("invalid field: expected ORDER > 0, got "+e);let r,n,o,a=!1;if("object"==typeof t&&null!=t){if(s.sqrt||i)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(r=e.BITS),e.sqrt&&(n=e.sqrt),"boolean"==typeof e.isLE&&(i=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(r=t),s.sqrt&&(n=s.sqrt);const{nBitLength:c,nByteLength:h}=th(e,r);if(h>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const u=Object.freeze({ORDER:e,isLE:i,BITS:c,BYTES:h,MASK:Tc(c),ZERO:Cc,ONE:Uc,allowedLengths:o,create:t=>Fc(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Cc<=t&&t<e},is0:e=>e===Cc,isValidNot0:e=>!u.is0(e)&&u.isValid(e),isOdd:e=>(e&Uc)===Uc,neg:t=>Fc(-t,e),eql:(e,t)=>e===t,sqr:t=>Fc(t*t,e),add:(t,i)=>Fc(t+i,e),sub:(t,i)=>Fc(t-i,e),mul:(t,i)=>Fc(t*i,e),pow:(e,t)=>function(e,t,i){if(i<Cc)throw new Error("invalid exponent, negatives unsupported");if(i===Cc)return e.ONE;if(i===Uc)return t;let s=e.ONE,r=t;for(;i>Cc;)i&Uc&&(s=e.mul(s,r)),r=e.sqr(r),i>>=Uc;return s}(u,e,t),div:(t,i)=>Fc(t*Vc(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Vc(t,e),sqrt:n||(t=>(l||(l=Zc(e)),l(u,t))),toBytes:e=>i?Ic(e,h):xc(e,h),fromBytes:(t,s=!0)=>{if(o){if(!o.includes(t.length)||t.length>h)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(h);e.set(t,i?0:e.length-t.length),t=e}if(t.length!==h)throw new Error("Field.fromBytes: expected "+h+" bytes, got "+t.length);let r=i?Ec(t):vc(t);if(a&&(r=Fc(r,e)),!s&&!u.isValid(r))throw new Error("invalid field element: outside of range 0..ORDER");return r},invertBatch:e=>Qc(u,e),cmov:(e,t,i)=>i?t:e});return Object.freeze(u)}function sh(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function rh(e){const t=sh(e);return t+Math.ceil(t/2)}const nh=BigInt(0),oh=BigInt(1);function ah(e,t){const i=t.negate();return e?i:t}function ch(e,t){const i=Qc(e.Fp,t.map((e=>e.Z)));return t.map(((t,s)=>e.fromAffine(t.toAffine(i[s]))))}function hh(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function lh(e,t){hh(e,t);const i=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Tc(e),maxNumber:i,shiftBy:BigInt(e)}}function uh(e,t,i){const{windowSize:s,mask:r,maxNumber:n,shiftBy:o}=i;let a=Number(e&r),c=e>>o;a>s&&(a-=n,c+=oh);const h=t*s;return{nextN:c,offset:h+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:h}}const dh=new WeakMap,fh=new WeakMap;function ph(e){return fh.get(e)||1}function gh(e){if(e!==nh)throw new Error("invalid wNAF")}class yh{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,i=this.ZERO){let s=e;for(;t>nh;)t&oh&&(i=i.add(s)),s=s.double(),t>>=oh;return i}precomputeWindow(e,t){const{windows:i,windowSize:s}=lh(t,this.bits),r=[];let n=e,o=n;for(let e=0;e<i;e++){o=n,r.push(o);for(let e=1;e<s;e++)o=o.add(n),r.push(o);n=o.double()}return r}wNAF(e,t,i){if(!this.Fn.isValid(i))throw new Error("invalid scalar");let s=this.ZERO,r=this.BASE;const n=lh(e,this.bits);for(let e=0;e<n.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:h,isNegF:l,offsetF:u}=uh(i,e,n);i=o,c?r=r.add(ah(l,t[u])):s=s.add(ah(h,t[a]))}return gh(i),{p:s,f:r}}wNAFUnsafe(e,t,i,s=this.ZERO){const r=lh(e,this.bits);for(let e=0;e<r.windows&&i!==nh;e++){const{nextN:n,offset:o,isZero:a,isNeg:c}=uh(i,e,r);if(i=n,!a){const e=t[o];s=s.add(c?e.negate():e)}}return gh(i),s}getPrecomputes(e,t,i){let s=dh.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&("function"==typeof i&&(s=i(s)),dh.set(t,s))),s}cached(e,t,i){const s=ph(e);return this.wNAF(s,this.getPrecomputes(s,e,i),t)}unsafe(e,t,i,s){const r=ph(e);return 1===r?this._unsafeLadder(e,t,s):this.wNAFUnsafe(r,this.getPrecomputes(r,e,i),t,s)}createCache(e,t){hh(t,this.bits),fh.set(e,t),dh.delete(e)}hasCache(e){return 1!==ph(e)}}function wh(e,t,i,s){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,i)=>{if(!(e instanceof t))throw new Error("invalid point at index "+i)}))}(i,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,i)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+i)}))}(s,t);const r=i.length,n=s.length;if(r!==n)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Pc(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const h=Tc(c),l=new Array(Number(h)+1).fill(o);let u=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){l.fill(o);for(let t=0;t<n;t++){const r=s[t],n=Number(r>>BigInt(e)&h);l[n]=l[n].add(i[t])}let t=o;for(let e=l.length-1,i=o;e>0;e--)i=i.add(l[e]),t=t.add(i);if(u=u.add(t),0!==e)for(let e=0;e<c;e++)u=u.double()}return u}function mh(e,t,i){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){Bc(e,Jc.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return ih(e,{isLE:i})}function bh(e,t,i={},s){if(void 0===s&&(s="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const i=t[e];if(!("bigint"==typeof i&&i>nh))throw new Error(`CURVE.${e} must be positive bigint`)}const r=mh(t.p,i.Fp,s),n=mh(t.n,i.Fn,s),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!r.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:r,Fn:n}}const vh=BigInt(0),Eh=BigInt(1),xh=BigInt(2),Ih=BigInt(8);class Sh{constructor(e){this.ep=e}static fromBytes(e){Rc()}static fromHex(e){Rc()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Be(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}}function Oh(e,t,i={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Bc(i,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:s}=i,{BASE:r,Fp:n,Fn:o}=e,a=i.randomBytes||Me,c=i.adjustScalarBytes||(e=>e),h=i.domain||((e,t,i)=>{if(yc(i,"phflag"),t.length||i)throw new Error("Contexts/pre-hash are not supported");return e});function l(e){return o.create(Ec(e))}function u(e){const{head:i,prefix:s,scalar:n}=function(e){const i=y.secretKey;e=Sc("private key",e,i);const s=Sc("hashed private key",t(e),2*i),r=c(s.slice(0,i));return{head:r,prefix:s.slice(i,2*i),scalar:l(r)}}(e),o=r.multiply(n),a=o.toBytes();return{head:i,prefix:s,scalar:n,point:o,pointBytes:a}}function d(e){return u(e).pointBytes}function f(e=Uint8Array.of(),...i){const r=ke(...i);return l(t(h(r,Sc("context",e),!!s)))}const p={zip215:!0};const g=n.BYTES,y={secretKey:g,publicKey:g,signature:2*g,seed:g};function w(e=a(y.seed)){return wc(e,y.seed,"seed")}const m={getExtendedPublicKey:u,randomSecretKey:w,isValidSecretKey:function(e){return pe(e)&&e.length===o.BYTES},isValidPublicKey:function(t,i){try{return!!e.fromBytes(t,i)}catch(e){return!1}},toMontgomery(t){const{y:i}=e.fromBytes(t),s=y.publicKey,r=32===s;if(!r&&57!==s)throw new Error("only defined for 25519 and 448");const o=r?n.div(Eh+i,Eh-i):n.div(i-Eh,i+Eh);return n.toBytes(o)},toMontgomerySecret(e){const i=y.secretKey;wc(e,i);const s=t(e.subarray(0,i));return c(s).subarray(0,i)},randomPrivateKey:w,precompute:(t=8,i=e.BASE)=>i.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=m.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign:function(e,t,i={}){e=Sc("message",e),s&&(e=s(e));const{prefix:n,scalar:a,pointBytes:c}=u(t),h=f(i.context,n,e),l=r.multiply(h).toBytes(),d=f(i.context,l,c,e),p=o.create(h+d*a);if(!o.isValid(p))throw new Error("sign failed: invalid s");return wc(ke(l,o.toBytes(p)),y.signature,"result")},verify:function(t,i,n,o=p){const{context:a,zip215:c}=o,h=y.signature;t=Sc("signature",t,h),i=Sc("message",i),n=Sc("publicKey",n,y.publicKey),void 0!==c&&yc(c,"zip215"),s&&(i=s(i));const l=h/2,u=t.subarray(0,l),d=Ec(t.subarray(l,h));let g,w,m;try{g=e.fromBytes(n,c),w=e.fromBytes(u,c),m=r.multiplyUnsafe(d)}catch(e){return!1}if(!c&&g.isSmallOrder())return!1;const b=f(a,w.toBytes(),g.toBytes(),i);return w.add(g.multiplyUnsafe(b)).subtract(m).clearCofactor().is0()},utils:m,Point:e,lengths:y})}function _h(e){const{CURVE:t,curveOpts:i,hash:s,eddsaOpts:r}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},i={Fp:e.Fp,Fn:ih(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:i,hash:e.hash,eddsaOpts:s}}(e),n=function(e,t={}){const i=bh("edwards",e,t,t.FpFnLE),{Fp:s,Fn:r}=i;let n=i.CURVE;const{h:o}=n;Bc(t,{},{uvRatio:"function"});const a=xh<<BigInt(8*r.BYTES)-Eh,c=e=>s.create(e),h=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:s.sqrt(s.div(e,t))}}catch(e){return{isValid:!1,value:vh}}});if(!function(e,t,i,s){const r=e.sqr(i),n=e.sqr(s),o=e.add(e.mul(t.a,r),n),a=e.add(e.ONE,e.mul(t.d,e.mul(r,n)));return e.eql(o,a)}(s,n,n.Gx,n.Gy))throw new Error("bad curve params: generator point");function l(e,t,i=!1){return Ac("coordinate "+e,t,i?Eh:vh,a),t}function u(e){if(!(e instanceof p))throw new Error("ExtendedPoint expected")}const d=Nc(((e,t)=>{const{X:i,Y:r,Z:n}=e,o=e.is0();null==t&&(t=o?Ih:s.inv(n));const a=c(i*t),h=c(r*t),l=s.mul(n,t);if(o)return{x:vh,y:Eh};if(l!==Eh)throw new Error("invZ was invalid");return{x:a,y:h}})),f=Nc((e=>{const{a:t,d:i}=n;if(e.is0())throw new Error("bad point: ZERO");const{X:s,Y:r,Z:o,T:a}=e,h=c(s*s),l=c(r*r),u=c(o*o),d=c(u*u),f=c(h*t);if(c(u*c(f+l))!==c(d+c(i*c(h*l))))throw new Error("bad point: equation left != right (1)");if(c(s*r)!==c(o*a))throw new Error("bad point: equation left != right (2)");return!0}));class p{constructor(e,t,i,s){this.X=l("x",e),this.Y=l("y",t),this.Z=l("z",i,!0),this.T=l("t",s),Object.freeze(this)}static CURVE(){return n}static fromAffine(e){if(e instanceof p)throw new Error("extended point not allowed");const{x:t,y:i}=e||{};return l("x",t),l("y",i),new p(t,i,Eh,c(t*i))}static fromBytes(e,t=!1){const i=s.BYTES,{a:r,d:o}=n;e=Oc(wc(e,i,"point")),yc(t,"zip215");const l=Oc(e),u=e[i-1];l[i-1]=-129&u;const d=Ec(l),f=t?a:s.ORDER;Ac("point.y",d,vh,f);const g=c(d*d),y=c(g-Eh),w=c(o*g-r);let{isValid:m,value:b}=h(y,w);if(!m)throw new Error("bad point: invalid y coordinate");const v=(b&Eh)===Eh,E=0!=(128&u);if(!t&&b===vh&&E)throw new Error("bad point: x=0 and x_0=1");return E!==v&&(b=c(-b)),p.fromAffine({x:b,y:d})}static fromHex(e,t=!1){return p.fromBytes(Sc("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return g.createCache(this,e),t||this.multiply(xh),this}assertValidity(){f(this)}equals(e){u(e);const{X:t,Y:i,Z:s}=this,{X:r,Y:n,Z:o}=e,a=c(t*o),h=c(r*s),l=c(i*o),d=c(n*s);return a===h&&l===d}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=n,{X:t,Y:i,Z:s}=this,r=c(t*t),o=c(i*i),a=c(xh*c(s*s)),h=c(e*r),l=t+i,u=c(c(l*l)-r-o),d=h+o,f=d-a,g=h-o,y=c(u*f),w=c(d*g),m=c(u*g),b=c(f*d);return new p(y,w,b,m)}add(e){u(e);const{a:t,d:i}=n,{X:s,Y:r,Z:o,T:a}=this,{X:h,Y:l,Z:d,T:f}=e,g=c(s*h),y=c(r*l),w=c(a*i*f),m=c(o*d),b=c((s+r)*(h+l)-g-y),v=m-w,E=m+w,x=c(y-t*g),I=c(b*v),S=c(E*x),O=c(b*x),_=c(v*E);return new p(I,S,_,O)}subtract(e){return this.add(e.negate())}multiply(e){if(!r.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:i}=g.cached(this,e,(e=>ch(p,e)));return ch(p,[t,i])[0]}multiplyUnsafe(e,t=p.ZERO){if(!r.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===vh?p.ZERO:this.is0()||e===Eh?this:g.unsafe(this,e,(e=>ch(p,e)),t)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return g.unsafe(this,n.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return o===Eh?this:this.multiplyUnsafe(o)}toBytes(){const{x:e,y:t}=this.toAffine(),i=s.toBytes(t);return i[i.length-1]|=e&Eh?128:0,i}toHex(){return Be(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return ch(p,e)}static msm(e,t){return wh(p,r,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}p.BASE=new p(n.Gx,n.Gy,Eh,c(n.Gx*n.Gy)),p.ZERO=new p(vh,Eh,Eh,vh),p.Fp=s,p.Fn=r;const g=new yh(p,r.BITS);return p.BASE.precompute(8),p}(t,i);return function(e,t){const i=t.Point;return Object.assign({},t,{ExtendedPoint:i,CURVE:e,nBitLength:i.Fn.BITS,nByteLength:i.Fn.BYTES})}(e,Oh(n,s,r))}const Ah=BigInt(0),Ph=BigInt(1),Th=BigInt(2);function Bh(e){const t=(Bc(i=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...i}));var i;const{P:s,type:r,adjustScalarBytes:n,powPminus2:o,randomBytes:a}=t,c="x25519"===r;if(!c&&"x448"!==r)throw new Error("invalid type");const h=a||Me,l=c?255:448,u=c?32:56,d=c?BigInt(9):BigInt(5),f=c?BigInt(121665):BigInt(39081),p=c?Th**BigInt(254):Th**BigInt(447),g=c?BigInt(8)*Th**BigInt(251)-Ph:BigInt(4)*Th**BigInt(445)-Ph,y=p+g+Ph,w=e=>Fc(e,s),m=b(d);function b(e){return Ic(w(e),u)}function v(e,t){const i=function(e,t){Ac("u",e,Ah,s),Ac("scalar",t,p,y);const i=t,r=e;let n=Ph,a=Ah,c=e,h=Ph,u=Ah;for(let e=BigInt(l-1);e>=Ah;e--){const t=i>>e&Ph;u^=t,({x_2:n,x_3:c}=x(u,n,c)),({x_2:a,x_3:h}=x(u,a,h)),u=t;const s=n+a,o=w(s*s),l=n-a,d=w(l*l),p=o-d,g=c+h,y=w((c-h)*s),m=w(g*l),b=y+m,v=y-m;c=w(b*b),h=w(r*w(v*v)),n=w(o*d),a=w(p*(o+w(f*p)))}({x_2:n,x_3:c}=x(u,n,c)),({x_2:a,x_3:h}=x(u,a,h));const d=o(a);return w(n*d)}(function(e){const t=Sc("u coordinate",e,u);return c&&(t[31]&=127),w(Ec(t))}(t),function(e){return Ec(n(Sc("scalar",e,u)))}(e));if(i===Ah)throw new Error("invalid private or public key received");return b(i)}function E(e){return v(e,m)}function x(e,t,i){const s=w(e*(t-i));return{x_2:t=w(t-s),x_3:i=w(i+s)}}const I={secretKey:u,publicKey:u,seed:u},S=(e=h(u))=>(ye(e,I.seed),e);return{keygen:function(e){const t=S(e);return{secretKey:t,publicKey:E(t)}},getSharedSecret:(e,t)=>v(e,t),getPublicKey:e=>E(e),scalarMult:v,scalarMultBase:E,utils:{randomSecretKey:S,randomPrivateKey:S},GuBytes:m.slice(),lengths:I}}const Rh=BigInt(0),Nh=BigInt(1),Ch=BigInt(2),Uh=BigInt(3),kh=BigInt(5),Lh=BigInt(8),qh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Dh=(()=>({p:qh,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Lh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Mh(e){const t=BigInt(10),i=BigInt(20),s=BigInt(40),r=BigInt(80),n=qh,o=e*e%n*e%n,a=Kc(o,Ch,n)*o%n,c=Kc(a,Nh,n)*e%n,h=Kc(c,kh,n)*c%n,l=Kc(h,t,n)*h%n,u=Kc(l,i,n)*l%n,d=Kc(u,s,n)*u%n,f=Kc(d,r,n)*d%n,p=Kc(f,r,n)*d%n,g=Kc(p,t,n)*h%n;return{pow_p_5_8:Kc(g,Ch,n)*e%n,b2:o}}function $h(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const jh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function zh(e,t){const i=qh,s=Fc(t*t*t,i),r=Fc(s*s*t,i);let n=Fc(e*s*Mh(e*r).pow_p_5_8,i);const o=Fc(t*n*n,i),a=n,c=Fc(n*jh,i),h=o===e,l=o===Fc(-e,i),u=o===Fc(-e*jh,i);return h&&(n=a),(l||u)&&(n=c),Xc(n,i)&&(n=Fc(-n,i)),{isValid:h||l,value:n}}const Fh=(()=>ih(Dh.p,{isLE:!0}))(),Kh=(()=>ih(Dh.n,{isLE:!0}))(),Vh=(()=>({...Dh,Fp:Fh,hash:Wr,adjustScalarBytes:$h,uvRatio:zh}))(),Hh=(()=>_h(Vh))(),Wh=(()=>{const e=Fh.ORDER;return Bh({P:e,type:"x25519",powPminus2:t=>{const{pow_p_5_8:i,b2:s}=Mh(t);return Fc(Kc(i,Uh,e)*s,e)},adjustScalarBytes:$h})})(),Gh=jh,Yh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Zh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Xh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Jh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Qh=e=>zh(Nh,e),el=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),tl=e=>Hh.Point.Fp.create(Ec(e)&el);function il(e){const{d:t}=Dh,i=qh,s=e=>Fh.create(e),r=s(Gh*e*e),n=s((r+Nh)*Xh);let o=BigInt(-1);const a=s((o-t*r)*s(r+t));let{isValid:c,value:h}=zh(n,a),l=s(h*e);Xc(l,i)||(l=s(-l)),c||(h=l),c||(o=r);const u=s(o*(r-Nh)*Jh-a),d=h*h,f=s((h+h)*a),p=s(u*Yh),g=s(Nh-d),y=s(Nh+d);return new Hh.Point(s(f*y),s(g*p),s(p*y),s(f*g))}class sl extends Sh{constructor(e){super(e)}static fromAffine(e){return new sl(Hh.Point.fromAffine(e))}assertSame(e){if(!(e instanceof sl))throw new Error("RistrettoPoint expected")}init(e){return new sl(e)}static hashToCurve(e){return function(e){ye(e,64);const t=il(tl(e.subarray(0,32))),i=il(tl(e.subarray(32,64)));return new sl(t.add(i))}(Sc("ristrettoHash",e,64))}static fromBytes(e){ye(e,32);const{a:t,d:i}=Dh,s=qh,r=e=>Fh.create(e),n=tl(e);if(!function(e,t){if(e.length!==t.length)return!1;let i=0;for(let s=0;s<e.length;s++)i|=e[s]^t[s];return 0===i}(Fh.toBytes(n),e)||Xc(n,s))throw new Error("invalid ristretto255 encoding 1");const o=r(n*n),a=r(Nh+t*o),c=r(Nh-t*o),h=r(a*a),l=r(c*c),u=r(t*i*h-l),{isValid:d,value:f}=Qh(r(u*l)),p=r(f*c),g=r(f*p*u);let y=r((n+n)*p);Xc(y,s)&&(y=r(-y));const w=r(a*g),m=r(y*w);if(!d||Xc(m,s)||w===Rh)throw new Error("invalid ristretto255 encoding 2");return new sl(new Hh.Point(y,w,Nh,m))}static fromHex(e){return sl.fromBytes(Sc("ristrettoHex",e,32))}static msm(e,t){return wh(sl,Hh.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:i,T:s}=this.ep;const r=qh,n=e=>Fh.create(e),o=n(n(i+t)*n(i-t)),a=n(e*t),c=n(a*a),{value:h}=Qh(n(o*c)),l=n(h*o),u=n(h*a),d=n(l*u*s);let f;if(Xc(s*d,r)){let i=n(t*Gh),s=n(e*Gh);e=i,t=s,f=n(l*Zh)}else f=u;Xc(e*d,r)&&(t=n(-t));let p=n((i-t)*f);return Xc(p,r)&&(p=n(-p)),Fh.toBytes(p)}equals(e){this.assertSame(e);const{X:t,Y:i}=this.ep,{X:s,Y:r}=e.ep,n=e=>Fh.create(e),o=n(t*r)===n(i*s),a=n(i*r)===n(t*s);return o||a}is0(){return this.equals(sl.ZERO)}}sl.BASE=(()=>new sl(Hh.Point.BASE))(),sl.ZERO=(()=>new sl(Hh.Point.ZERO))(),sl.Fp=(()=>Fh)(),sl.Fn=(()=>Kh)();const rl=(e,t)=>(e+(e>=0?t:-t)/ul)/t;function nl(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function ol(e,t){const i={};for(let s of Object.keys(t))i[s]=void 0===e[s]?t[s]:e[s];return yc(i.lowS,"lowS"),yc(i.prehash,"prehash"),void 0!==i.format&&nl(i.format),i}class al extends Error{constructor(e=""){super(e)}}const cl={Err:al,_tlv:{encode:(e,t)=>{const{Err:i}=cl;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(1&t.length)throw new i("tlv.encode: unpadded data");const s=t.length/2,r=mc(s);if(r.length/2&128)throw new i("tlv.encode: long form length too big");const n=s>127?mc(r.length/2|128):"";return mc(e)+n+r+t},decode(e,t){const{Err:i}=cl;let s=0;if(e<0||e>256)throw new i("tlv.encode: wrong tag");if(t.length<2||t[s++]!==e)throw new i("tlv.decode: wrong tlv");const r=t[s++];let n=0;if(!!(128&r)){const e=127&r;if(!e)throw new i("tlv.decode(long): indefinite length not supported");if(e>4)throw new i("tlv.decode(long): byte length is too big");const o=t.subarray(s,s+e);if(o.length!==e)throw new i("tlv.decode: length bytes not complete");if(0===o[0])throw new i("tlv.decode(long): zero leftmost byte");for(const e of o)n=n<<8|e;if(s+=e,n<128)throw new i("tlv.decode(long): not minimal encoding")}else n=r;const o=t.subarray(s,s+n);if(o.length!==n)throw new i("tlv.decode: wrong value length");return{v:o,l:t.subarray(s+n)}}},_int:{encode(e){const{Err:t}=cl;if(e<hl)throw new t("integer: negative integers are not allowed");let i=mc(e);if(8&Number.parseInt(i[0],16)&&(i="00"+i),1&i.length)throw new t("unexpected DER parsing assertion: unpadded hex");return i},decode(e){const{Err:t}=cl;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return vc(e)}},toSig(e){const{Err:t,_int:i,_tlv:s}=cl,r=Sc("signature",e),{v:n,l:o}=s.decode(48,r);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,n),{v:h,l:l}=s.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:i.decode(a),s:i.decode(h)}},hexFromSig(e){const{_tlv:t,_int:i}=cl,s=t.encode(2,i.encode(e.r))+t.encode(2,i.encode(e.s));return t.encode(48,s)}},hl=BigInt(0),ll=BigInt(1),ul=BigInt(2),dl=BigInt(3),fl=BigInt(4);function pl(e,t){const{BYTES:i}=e;let s;if("bigint"==typeof t)s=t;else{let r=Sc("private key",t);try{s=e.fromBytes(r)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${i}, got ${typeof t}`)}}if(!e.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}function gl(e,t={}){const i=bh("weierstrass",e,t),{Fp:s,Fn:r}=i;let n=i.CURVE;const{h:o,n:a}=n;Bc(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!s.is0(n.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const h=wl(s,r);function l(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const u=t.toBytes||function(e,t,i){const{x:r,y:n}=t.toAffine(),o=s.toBytes(r);if(yc(i,"isCompressed"),i){l();return ke(yl(!s.isOdd(n)),o)}return ke(Uint8Array.of(4),o,s.toBytes(n))},d=t.fromBytes||function(e){wc(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:i}=h,r=e.length,n=e[0],o=e.subarray(1);if(r!==t||2!==n&&3!==n){if(r===i&&4===n){const e=s.BYTES,t=s.fromBytes(o.subarray(0,e)),i=s.fromBytes(o.subarray(e,2*e));if(!p(t,i))throw new Error("bad point: is not on curve");return{x:t,y:i}}throw new Error(`bad point: got length ${r}, expected compressed=${t} or uncompressed=${i}`)}{const e=s.fromBytes(o);if(!s.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=f(e);let i;try{i=s.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}l();return 1==(1&n)!==s.isOdd(i)&&(i=s.neg(i)),{x:e,y:i}}};function f(e){const t=s.sqr(e),i=s.mul(t,e);return s.add(s.add(i,s.mul(e,n.a)),n.b)}function p(e,t){const i=s.sqr(t),r=f(e);return s.eql(i,r)}if(!p(n.Gx,n.Gy))throw new Error("bad curve params: generator point");const g=s.mul(s.pow(n.a,dl),fl),y=s.mul(s.sqr(n.b),BigInt(27));if(s.is0(s.add(g,y)))throw new Error("bad curve params: a or b");function w(e,t,i=!1){if(!s.isValid(t)||i&&s.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function m(e){if(!(e instanceof I))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,i){const[[s,r],[n,o]]=t,a=rl(o*e,i),c=rl(-r*e,i);let h=e-a*s-c*n,l=-a*r-c*o;const u=h<hl,d=l<hl;u&&(h=-h),d&&(l=-l);const f=Tc(Math.ceil(Pc(i)/2))+ll;if(h<hl||h>=f||l<hl||l>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:u,k1:h,k2neg:d,k2:l}}(e,c.basises,r.ORDER)}const v=Nc(((e,t)=>{const{X:i,Y:r,Z:n}=e;if(s.eql(n,s.ONE))return{x:i,y:r};const o=e.is0();null==t&&(t=o?s.ONE:s.inv(n));const a=s.mul(i,t),c=s.mul(r,t),h=s.mul(n,t);if(o)return{x:s.ZERO,y:s.ZERO};if(!s.eql(h,s.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),E=Nc((e=>{if(e.is0()){if(t.allowInfinityPoint&&!s.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:i,y:r}=e.toAffine();if(!s.isValid(i)||!s.isValid(r))throw new Error("bad point: x or y not field elements");if(!p(i,r))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));function x(e,t,i,r,n){return i=new I(s.mul(i.X,e),i.Y,i.Z),t=ah(r,t),i=ah(n,i),t.add(i)}class I{constructor(e,t,i){this.X=w("x",e),this.Y=w("y",t,!0),this.Z=w("z",i),Object.freeze(this)}static CURVE(){return n}static fromAffine(e){const{x:t,y:i}=e||{};if(!e||!s.isValid(t)||!s.isValid(i))throw new Error("invalid affine point");if(e instanceof I)throw new Error("projective point not allowed");return s.is0(t)&&s.is0(i)?I.ZERO:new I(t,i,s.ONE)}static fromBytes(e){const t=I.fromAffine(d(wc(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return I.fromBytes(Sc("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return O.createCache(this,e),t||this.multiply(dl),this}assertValidity(){E(this)}hasEvenY(){const{y:e}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(e)}equals(e){m(e);const{X:t,Y:i,Z:r}=this,{X:n,Y:o,Z:a}=e,c=s.eql(s.mul(t,a),s.mul(n,r)),h=s.eql(s.mul(i,a),s.mul(o,r));return c&&h}negate(){return new I(this.X,s.neg(this.Y),this.Z)}double(){const{a:e,b:t}=n,i=s.mul(t,dl),{X:r,Y:o,Z:a}=this;let c=s.ZERO,h=s.ZERO,l=s.ZERO,u=s.mul(r,r),d=s.mul(o,o),f=s.mul(a,a),p=s.mul(r,o);return p=s.add(p,p),l=s.mul(r,a),l=s.add(l,l),c=s.mul(e,l),h=s.mul(i,f),h=s.add(c,h),c=s.sub(d,h),h=s.add(d,h),h=s.mul(c,h),c=s.mul(p,c),l=s.mul(i,l),f=s.mul(e,f),p=s.sub(u,f),p=s.mul(e,p),p=s.add(p,l),l=s.add(u,u),u=s.add(l,u),u=s.add(u,f),u=s.mul(u,p),h=s.add(h,u),f=s.mul(o,a),f=s.add(f,f),u=s.mul(f,p),c=s.sub(c,u),l=s.mul(f,d),l=s.add(l,l),l=s.add(l,l),new I(c,h,l)}add(e){m(e);const{X:t,Y:i,Z:r}=this,{X:o,Y:a,Z:c}=e;let h=s.ZERO,l=s.ZERO,u=s.ZERO;const d=n.a,f=s.mul(n.b,dl);let p=s.mul(t,o),g=s.mul(i,a),y=s.mul(r,c),w=s.add(t,i),b=s.add(o,a);w=s.mul(w,b),b=s.add(p,g),w=s.sub(w,b),b=s.add(t,r);let v=s.add(o,c);return b=s.mul(b,v),v=s.add(p,y),b=s.sub(b,v),v=s.add(i,r),h=s.add(a,c),v=s.mul(v,h),h=s.add(g,y),v=s.sub(v,h),u=s.mul(d,b),h=s.mul(f,y),u=s.add(h,u),h=s.sub(g,u),u=s.add(g,u),l=s.mul(h,u),g=s.add(p,p),g=s.add(g,p),y=s.mul(d,y),b=s.mul(f,b),g=s.add(g,y),y=s.sub(p,y),y=s.mul(d,y),b=s.add(b,y),p=s.mul(g,b),l=s.add(l,p),p=s.mul(v,b),h=s.mul(w,h),h=s.sub(h,p),p=s.mul(w,g),u=s.mul(v,u),u=s.add(u,p),new I(h,l,u)}subtract(e){return this.add(e.negate())}is0(){return this.equals(I.ZERO)}multiply(e){const{endo:i}=t;if(!r.isValidNot0(e))throw new Error("invalid scalar: out of range");let s,n;const o=e=>O.cached(this,e,(e=>ch(I,e)));if(i){const{k1neg:t,k1:r,k2neg:a,k2:c}=b(e),{p:h,f:l}=o(r),{p:u,f:d}=o(c);n=l.add(d),s=x(i.beta,h,u,t,a)}else{const{p:t,f:i}=o(e);s=t,n=i}return ch(I,[s,n])[0]}multiplyUnsafe(e){const{endo:i}=t,s=this;if(!r.isValid(e))throw new Error("invalid scalar: out of range");if(e===hl||s.is0())return I.ZERO;if(e===ll)return s;if(O.hasCache(this))return this.multiply(e);if(i){const{k1neg:t,k1:r,k2neg:n,k2:o}=b(e),{p1:a,p2:c}=function(e,t,i,s){let r=t,n=e.ZERO,o=e.ZERO;for(;i>nh||s>nh;)i&oh&&(n=n.add(r)),s&oh&&(o=o.add(r)),r=r.double(),i>>=oh,s>>=oh;return{p1:n,p2:o}}(I,s,r,o);return x(i.beta,a,c,t,n)}return O.unsafe(s,e)}multiplyAndAddUnsafe(e,t,i){const s=this.multiplyUnsafe(t).add(e.multiplyUnsafe(i));return s.is0()?void 0:s}toAffine(e){return v(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===ll||(e?e(I,this):O.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===ll?this:e?e(I,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return yc(e,"isCompressed"),this.assertValidity(),u(I,this,e)}toHex(e=!0){return Be(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return ch(I,e)}static msm(e,t){return wh(I,r,e,t)}static fromPrivateKey(e){return I.BASE.multiply(pl(r,e))}}I.BASE=new I(n.Gx,n.Gy,s.ONE),I.ZERO=new I(s.ZERO,s.ONE,s.ZERO),I.Fp=s,I.Fn=r;const S=r.BITS,O=new yh(I,t.endo?Math.ceil(S/2):S);return I.BASE.precompute(8),I}function yl(e){return Uint8Array.of(e?2:3)}function wl(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function ml(e,t={}){const{Fn:i}=e,s=t.randomBytes||Me,r=Object.assign(wl(e.Fp,i),{seed:rh(i.ORDER)});function n(e){try{return!!pl(i,e)}catch(e){return!1}}function o(e=s(r.seed)){return function(e,t,i=!1){const s=e.length,r=sh(t),n=rh(t);if(s<16||s<n||s>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+s);const o=Fc(i?Ec(e):vc(e),t-Uc)+Uc;return i?Ic(o,r):xc(o,r)}(wc(e,r.seed,"seed"),i.ORDER)}function a(t,s=!0){return e.BASE.multiply(pl(i,t)).toBytes(s)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:s,publicKey:n,publicKeyUncompressed:o}=r;if(i.allowedLengths||s===n)return;const a=Sc("key",t).length;return a===n||a===o}const h={isValidSecretKey:n,isValidPublicKey:function(t,i){const{publicKey:s,publicKeyUncompressed:n}=r;try{const r=t.length;return(!0!==i||r===s)&&((!1!==i||r===n)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:n,randomPrivateKey:o,normPrivateKeyToScalar:e=>pl(i,e),precompute:(t=8,i=e.BASE)=>i.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,s,r=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(s))throw new Error("second arg must be public key");const n=pl(i,t);return e.fromHex(s).multiply(n).toBytes(r)},keygen:function(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:h,lengths:r})}function bl(e,t,i={}){we(t),Bc(i,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const s=i.randomBytes||Me,r=i.hmac||((e,...i)=>hc(t,e,ke(...i))),{Fp:n,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:h,getPublicKey:l,getSharedSecret:u,utils:d,lengths:f}=ml(e,i),p={prehash:!1,lowS:"boolean"==typeof i.lowS&&i.lowS,format:void 0,extraEntropy:!1},g="compact";function y(e){return e>a>>ll}function w(e,t){if(!o.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class m{constructor(e,t,i){this.r=w("r",e),this.s=w("s",t),null!=i&&(this.recovery=i),Object.freeze(this)}static fromBytes(e,t=g){let i;if(function(e,t){nl(t);const i=f.signature;wc(e,"compact"===t?i:"recovered"===t?i+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:i}=cl.toSig(wc(e));return new m(t,i)}"recovered"===t&&(i=e[0],t="compact",e=e.subarray(1));const s=o.BYTES,r=e.subarray(0,s),n=e.subarray(s,2*s);return new m(o.fromBytes(r),o.fromBytes(n),i)}static fromHex(e,t){return this.fromBytes(Ce(e),t)}addRecoveryBit(e){return new m(this.r,this.s,e)}recoverPublicKey(t){const i=n.ORDER,{r:s,s:r,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*ul<i&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const h=2===c||3===c?s+a:s;if(!n.isValid(h))throw new Error("recovery id 2 or 3 invalid");const l=n.toBytes(h),u=e.fromBytes(ke(yl(0==(1&c)),l)),d=o.inv(h),f=v(Sc("msgHash",t)),p=o.create(-f*d),g=o.create(r*d),y=e.BASE.multiplyUnsafe(p).add(u.multiplyUnsafe(g));if(y.is0())throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return y(this.s)}toBytes(e=g){if(nl(e),"der"===e)return Ce(cl.hexFromSig(this));const t=o.toBytes(this.r),i=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return ke(Uint8Array.of(this.recovery),t,i)}return ke(t,i)}toHex(e){return Be(this.toBytes(e))}assertValidity(){}static fromCompact(e){return m.fromBytes(Sc("sig",e),"compact")}static fromDER(e){return m.fromBytes(Sc("sig",e),"der")}normalizeS(){return this.hasHighS()?new m(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Be(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Be(this.toBytes("compact"))}}const b=i.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=vc(e),i=8*e.length-c;return i>0?t>>BigInt(i):t},v=i.bits2int_modN||function(e){return o.create(b(e))},E=Tc(c);function x(e){return Ac("num < 2^"+c,e,hl,E),o.toBytes(e)}function I(e,i){return wc(e,void 0,"message"),i?wc(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:h,getPublicKey:l,getSharedSecret:u,utils:d,lengths:f,Point:e,sign:function(i,n,a={}){i=Sc("message",i);const{seed:c,k2sig:h}=function(t,i,r){if(["recovered","canonical"].some((e=>e in r)))throw new Error("sign() legacy options not supported");const{lowS:n,prehash:a,extraEntropy:c}=ol(r,p);t=I(t,a);const h=v(t),l=pl(o,i),u=[x(l),x(h)];if(null!=c&&!1!==c){const e=!0===c?s(f.secretKey):c;u.push(Sc("extraEntropy",e))}const d=ke(...u),g=h;return{seed:d,k2sig:function(t){const i=b(t);if(!o.isValidNot0(i))return;const s=o.inv(i),r=e.BASE.multiply(i).toAffine(),a=o.create(r.x);if(a===hl)return;const c=o.create(s*o.create(g+a*l));if(c===hl)return;let h=(r.x===a?0:2)|Number(r.y&ll),u=c;return n&&y(c)&&(u=o.neg(c),h^=1),new m(a,u,h)}}}(i,n,a),l=function(e,t,i){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof i)throw new Error("hmacFn must be a function");const s=e=>new Uint8Array(e),r=e=>Uint8Array.of(e);let n=s(e),o=s(e),a=0;const c=()=>{n.fill(1),o.fill(0),a=0},h=(...e)=>i(o,n,...e),l=(e=s(0))=>{o=h(r(0),e),n=h(),0!==e.length&&(o=h(r(1),e),n=h())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const i=[];for(;e<t;){n=h();const t=n.slice();i.push(t),e+=n.length}return ke(...i)};return(e,t)=>{let i;for(c(),l(e);!(i=t(u()));)l();return c(),i}}(t.outputLen,o.BYTES,r);return l(c,h)},verify:function(t,i,s,r={}){const{lowS:n,prehash:a,format:c}=ol(r,p);if(s=Sc("publicKey",s),i=I(Sc("message",i),a),"strict"in r)throw new Error("options.strict was renamed to lowS");const h=void 0===c?function(e){let t;const i="string"==typeof e||pe(e),s=!i&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!i&&!s)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(s)t=new m(e.r,e.s);else if(i){try{t=m.fromBytes(Sc("sig",e),"der")}catch(e){if(!(e instanceof cl.Err))throw e}if(!t)try{t=m.fromBytes(Sc("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):m.fromBytes(Sc("sig",t),c);if(!1===h)return!1;try{const t=e.fromBytes(s);if(n&&h.hasHighS())return!1;const{r:r,s:a}=h,c=v(i),l=o.inv(a),u=o.create(c*l),d=o.create(r*l),f=e.BASE.multiplyUnsafe(u).add(t.multiplyUnsafe(d));if(f.is0())return!1;return o.create(f.x)===r}catch(e){return!1}},recoverPublicKey:function(e,t,i={}){const{prehash:s}=ol(i,p);return t=I(t,s),m.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:m,hash:t})}function vl(e){const{CURVE:t,curveOpts:i}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},i=e.Fp;let s=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map((e=>Math.ceil(e/2))))):void 0;return{CURVE:t,curveOpts:{Fp:i,Fn:ih(t.n,{BITS:e.nBitLength,allowedLengths:s,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),s={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:i,hash:e.hash,ecdsaOpts:s}}function El(e){const{CURVE:t,curveOpts:i,hash:s,ecdsaOpts:r}=vl(e);return function(e,t){const i=t.Point;return Object.assign({},t,{ProjectivePoint:i,CURVE:Object.assign({},e,th(i.Fn.ORDER,i.Fn.BITS))})}(e,bl(gl(t,i),s,r))}function xl(e,t){const i=t=>El({...e,hash:t});return{...i(t),create:i}}const Il={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Sl={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Ol={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},_l=ih(Il.p),Al=ih(Sl.p),Pl=ih(Ol.p),Tl=xl({...Il,Fp:_l,lowS:!1},Hr);xl({...Sl,Fp:Al,lowS:!1},Gr),xl({...Ol,Fp:Pl,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Wr);const Bl=Tl,Rl=e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t)),Nl=e=>{const t=e.replace(/([\[:])?(\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,'$1"$2n"$3');return JSON.parse(t,((e,t)=>"string"==typeof t&&t.match(/^\d+n$/)?BigInt(t.substring(0,t.length-1)):t))};function Cl(e){if("string"!=typeof e)throw new Error("Cannot safe json parse value of type "+typeof e);try{return Nl(e)}catch(t){return e}}function Ul(e){return"string"==typeof e?e:Rl(e)||""}function kl(e,...t){if(!function(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ll(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const ql="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Dl=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ml(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),kl(e),e}class $l{clone(){return this._cloneInto()}}function jl(e=32){if(ql&&"function"==typeof ql.getRandomValues)return ql.getRandomValues(new Uint8Array(e));if(ql&&"function"==typeof ql.randomBytes)return ql.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}class zl extends $l{constructor(e,t,i,s){super(),this.blockLen=e,this.outputLen=t,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=Dl(this.buffer)}update(e){Ll(this);const{view:t,buffer:i,blockLen:s}=this,r=(e=Ml(e)).length;for(let n=0;n<r;){const o=Math.min(s-this.pos,r-n);if(o!==s)i.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===s&&(this.process(t,0),this.pos=0);else{const t=Dl(e);for(;s<=r-n;n+=s)this.process(t,n)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ll(this),function(e,t){kl(e);const i=t.outputLen;if(e.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}(e,this),this.finished=!0;const{buffer:t,view:i,blockLen:s,isLE:r}=this;let{pos:n}=this;t[n++]=128,this.buffer.subarray(n).fill(0),this.padOffset>s-n&&(this.process(i,0),n=0);for(let e=n;e<s;e++)t[e]=0;(function(e,t,i,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,i,s);const r=BigInt(32),n=BigInt(4294967295),o=Number(i>>r&n),a=Number(i&n),c=s?4:0,h=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+h,a,s)})(i,s-8,BigInt(8*this.length),r),this.process(i,0);const o=Dl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,h=this.get();if(c>h.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,h[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:i,length:s,finished:r,destroyed:n,pos:o}=this;return e.length=s,e.pos=o,e.finished=r,e.destroyed=n,s%t&&e.buffer.set(i),e}}const Fl=BigInt(2**32-1),Kl=BigInt(32);function Vl(e,t=!1){return t?{h:Number(e&Fl),l:Number(e>>Kl&Fl)}:{h:0|Number(e>>Kl&Fl),l:0|Number(e&Fl)}}const Hl={fromBig:Vl,split:function(e,t=!1){let i=new Uint32Array(e.length),s=new Uint32Array(e.length);for(let r=0;r<e.length;r++){const{h:n,l:o}=Vl(e[r],t);[i[r],s[r]]=[n,o]}return[i,s]},toBig:(e,t)=>BigInt(e>>>0)<<Kl|BigInt(t>>>0),shrSH:(e,t,i)=>e>>>i,shrSL:(e,t,i)=>e<<32-i|t>>>i,rotrSH:(e,t,i)=>e>>>i|t<<32-i,rotrSL:(e,t,i)=>e<<32-i|t>>>i,rotrBH:(e,t,i)=>e<<64-i|t>>>i-32,rotrBL:(e,t,i)=>e>>>i-32|t<<64-i,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,i)=>e<<i|t>>>32-i,rotlSL:(e,t,i)=>t<<i|e>>>32-i,rotlBH:(e,t,i)=>t<<i-32|e>>>64-i,rotlBL:(e,t,i)=>e<<i-32|t>>>64-i,add:function(e,t,i,s){const r=(t>>>0)+(s>>>0);return{h:e+i+(r/2**32|0)|0,l:0|r}},add3L:(e,t,i)=>(e>>>0)+(t>>>0)+(i>>>0),add3H:(e,t,i,s)=>t+i+s+(e/2**32|0)|0,add4L:(e,t,i,s)=>(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0),add4H:(e,t,i,s,r)=>t+i+s+r+(e/2**32|0)|0,add5H:(e,t,i,s,r,n)=>t+i+s+r+n+(e/2**32|0)|0,add5L:(e,t,i,s,r)=>(e>>>0)+(t>>>0)+(i>>>0)+(s>>>0)+(r>>>0)},[Wl,Gl]=Hl.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((e=>BigInt(e)))),Yl=new Uint32Array(80),Zl=new Uint32Array(80);class Xl extends zl{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:t,Bh:i,Bl:s,Ch:r,Cl:n,Dh:o,Dl:a,Eh:c,El:h,Fh:l,Fl:u,Gh:d,Gl:f,Hh:p,Hl:g}=this;return[e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g]}set(e,t,i,s,r,n,o,a,c,h,l,u,d,f,p,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|i,this.Bl=0|s,this.Ch=0|r,this.Cl=0|n,this.Dh=0|o,this.Dl=0|a,this.Eh=0|c,this.El=0|h,this.Fh=0|l,this.Fl=0|u,this.Gh=0|d,this.Gl=0|f,this.Hh=0|p,this.Hl=0|g}process(e,t){for(let i=0;i<16;i++,t+=4)Yl[i]=e.getUint32(t),Zl[i]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Yl[e-15],i=0|Zl[e-15],s=Hl.rotrSH(t,i,1)^Hl.rotrSH(t,i,8)^Hl.shrSH(t,i,7),r=Hl.rotrSL(t,i,1)^Hl.rotrSL(t,i,8)^Hl.shrSL(t,i,7),n=0|Yl[e-2],o=0|Zl[e-2],a=Hl.rotrSH(n,o,19)^Hl.rotrBH(n,o,61)^Hl.shrSH(n,o,6),c=Hl.rotrSL(n,o,19)^Hl.rotrBL(n,o,61)^Hl.shrSL(n,o,6),h=Hl.add4L(r,c,Zl[e-7],Zl[e-16]),l=Hl.add4H(h,s,a,Yl[e-7],Yl[e-16]);Yl[e]=0|l,Zl[e]=0|h}let{Ah:i,Al:s,Bh:r,Bl:n,Ch:o,Cl:a,Dh:c,Dl:h,Eh:l,El:u,Fh:d,Fl:f,Gh:p,Gl:g,Hh:y,Hl:w}=this;for(let e=0;e<80;e++){const t=Hl.rotrSH(l,u,14)^Hl.rotrSH(l,u,18)^Hl.rotrBH(l,u,41),m=Hl.rotrSL(l,u,14)^Hl.rotrSL(l,u,18)^Hl.rotrBL(l,u,41),b=l&d^~l&p,v=u&f^~u&g,E=Hl.add5L(w,m,v,Gl[e],Zl[e]),x=Hl.add5H(E,y,t,b,Wl[e],Yl[e]),I=0|E,S=Hl.rotrSH(i,s,28)^Hl.rotrBH(i,s,34)^Hl.rotrBH(i,s,39),O=Hl.rotrSL(i,s,28)^Hl.rotrBL(i,s,34)^Hl.rotrBL(i,s,39),_=i&r^i&o^r&o,A=s&n^s&a^n&a;y=0|p,w=0|g,p=0|d,g=0|f,d=0|l,f=0|u,({h:l,l:u}=Hl.add(0|c,0|h,0|x,0|I)),c=0|o,h=0|a,o=0|r,a=0|n,r=0|i,n=0|s;const P=Hl.add3L(I,O,A);i=Hl.add3H(P,x,S,_),s=0|P}({h:i,l:s}=Hl.add(0|this.Ah,0|this.Al,0|i,0|s)),({h:r,l:n}=Hl.add(0|this.Bh,0|this.Bl,0|r,0|n)),({h:o,l:a}=Hl.add(0|this.Ch,0|this.Cl,0|o,0|a)),({h:c,l:h}=Hl.add(0|this.Dh,0|this.Dl,0|c,0|h)),({h:l,l:u}=Hl.add(0|this.Eh,0|this.El,0|l,0|u)),({h:d,l:f}=Hl.add(0|this.Fh,0|this.Fl,0|d,0|f)),({h:p,l:g}=Hl.add(0|this.Gh,0|this.Gl,0|p,0|g)),({h:y,l:w}=Hl.add(0|this.Hh,0|this.Hl,0|y,0|w)),this.set(i,s,r,n,o,a,c,h,l,u,d,f,p,g,y,w)}roundClean(){Yl.fill(0),Zl.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 Jl=function(e){const t=t=>e().update(Ml(t)).digest(),i=e();return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.create=()=>e(),t}((()=>new Xl)),Ql=BigInt(0),eu=BigInt(1),tu=BigInt(2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function iu(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function su(e){if(!iu(e))throw new Error("Uint8Array expected")}function ru(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const nu=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function ou(e){su(e);let t="";for(let i=0;i<e.length;i++)t+=nu[e[i]];return t}function au(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Ql:BigInt("0x"+e)}const cu={_0:48,_9:57,A:65,F:70,a:97,f:102};function hu(e){return e>=cu._0&&e<=cu._9?e-cu._0:e>=cu.A&&e<=cu.F?e-(cu.A-10):e>=cu.a&&e<=cu.f?e-(cu.a-10):void 0}function lu(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,i=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(i);for(let t=0,r=0;t<i;t++,r+=2){const i=hu(e.charCodeAt(r)),n=hu(e.charCodeAt(r+1));if(void 0===i||void 0===n){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}s[t]=16*i+n}return s}function uu(e){return su(e),au(ou(Uint8Array.from(e).reverse()))}function du(e,t){return lu(e.toString(16).padStart(2*t,"0"))}function fu(e,t){return du(e,t).reverse()}function pu(e,t,i){let s;if("string"==typeof t)try{s=lu(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!iu(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const r=s.length;if("number"==typeof i&&r!==i)throw new Error(e+" of length "+i+" expected, got "+r);return s}function gu(...e){let t=0;for(let i=0;i<e.length;i++){const s=e[i];su(s),t+=s.length}const i=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const r=e[t];i.set(r,s),s+=r.length}return i}const yu=e=>"bigint"==typeof e&&Ql<=e;function wu(e,t,i,s){if(!function(e,t,i){return yu(e)&&yu(t)&&yu(i)&&t<=e&&e<i}(t,i,s))throw new Error("expected valid "+e+": "+i+" <= n < "+s+", got "+t)}const mu=e=>(tu<<BigInt(e-1))-eu,bu={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||iu(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function vu(e,t,i={}){const s=(t,i,s)=>{const r=bu[i];if("function"!=typeof r)throw new Error("invalid validator function");const n=e[t];if(!(s&&void 0===n||r(n,e)))throw new Error("param "+String(t)+" is invalid. Expected "+i+", got "+n)};for(const[e,i]of Object.entries(t))s(e,i,!1);for(const[e,t]of Object.entries(i))s(e,t,!0);return e}function Eu(e){const t=new WeakMap;return(i,...s)=>{const r=t.get(i);if(void 0!==r)return r;const n=e(i,...s);return t.set(i,n),n}}const xu=BigInt(0),Iu=BigInt(1),Su=BigInt(2),Ou=BigInt(3),_u=BigInt(4),Au=BigInt(5),Pu=BigInt(8);function Tu(e,t){const i=e%t;return i>=xu?i:t+i}function Bu(e,t,i){if(t<xu)throw new Error("invalid exponent, negatives unsupported");if(i<=xu)throw new Error("invalid modulus");if(i===Iu)return xu;let s=Iu;for(;t>xu;)t&Iu&&(s=s*e%i),e=e*e%i,t>>=Iu;return s}function Ru(e,t,i){let s=e;for(;t-- >xu;)s*=s,s%=i;return s}function Nu(e,t){if(e===xu)throw new Error("invert: expected non-zero number");if(t<=xu)throw new Error("invert: expected positive modulus, got "+t);let i=Tu(e,t),s=t,r=xu,n=Iu;for(;i!==xu;){const e=s%i,t=r-n*(s/i);s=i,i=e,r=n,n=t}if(s!==Iu)throw new Error("invert: does not exist");return Tu(r,t)}function Cu(e){if(e%_u===Ou){const t=(e+Iu)/_u;return function(e,i){const s=e.pow(i,t);if(!e.eql(e.sqr(s),i))throw new Error("Cannot find square root");return s}}if(e%Pu===Au){const t=(e-Au)/Pu;return function(e,i){const s=e.mul(i,Su),r=e.pow(s,t),n=e.mul(i,r),o=e.mul(e.mul(n,Su),r),a=e.mul(n,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),i))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-Iu)/Su;let i,s,r;for(i=e-Iu,s=0;i%Su===xu;i/=Su,s++);for(r=Su;r<e&&Bu(r,t,e)!==e-Iu;r++)if(r>1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===s){const t=(e+Iu)/_u;return function(e,i){const s=e.pow(i,t);if(!e.eql(e.sqr(s),i))throw new Error("Cannot find square root");return s}}const n=(i+Iu)/Su;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=s,c=e.pow(e.mul(e.ONE,r),i),h=e.pow(o,n),l=e.pow(o,i);for(;!e.eql(l,e.ONE);){if(e.eql(l,e.ZERO))return e.ZERO;let t=1;for(let i=e.sqr(l);t<a&&!e.eql(i,e.ONE);t++)i=e.sqr(i);const i=e.pow(c,Iu<<BigInt(a-t-1));c=e.sqr(i),h=e.mul(h,i),l=e.mul(l,c),a=t}return h}}(e)}const Uu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ku(e,t){const i=void 0!==t?t:e.toString(2).length;return{nBitLength:i,nByteLength:Math.ceil(i/8)}}function Lu(e,t,i=!1,s={}){if(e<=xu)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:r,nByteLength:n}=ku(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:e,isLE:i,BITS:r,BYTES:n,MASK:mu(r),ZERO:xu,ONE:Iu,create:t=>Tu(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return xu<=t&&t<e},is0:e=>e===xu,isOdd:e=>(e&Iu)===Iu,neg:t=>Tu(-t,e),eql:(e,t)=>e===t,sqr:t=>Tu(t*t,e),add:(t,i)=>Tu(t+i,e),sub:(t,i)=>Tu(t-i,e),mul:(t,i)=>Tu(t*i,e),pow:(e,t)=>function(e,t,i){if(i<xu)throw new Error("invalid exponent, negatives unsupported");if(i===xu)return e.ONE;if(i===Iu)return t;let s=e.ONE,r=t;for(;i>xu;)i&Iu&&(s=e.mul(s,r)),r=e.sqr(r),i>>=Iu;return s}(a,e,t),div:(t,i)=>Tu(t*Nu(i,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Nu(t,e),sqrt:s.sqrt||(t=>(o||(o=Cu(e)),o(a,t))),invertBatch:e=>function(e,t){const i=new Array(t.length),s=t.reduce(((t,s,r)=>e.is0(s)?t:(i[r]=t,e.mul(t,s))),e.ONE),r=e.inv(s);return t.reduceRight(((t,s,r)=>e.is0(s)?t:(i[r]=e.mul(t,i[r]),e.mul(t,s))),r),i}(a,e),cmov:(e,t,i)=>i?t:e,toBytes:e=>i?fu(e,n):du(e,n),fromBytes:e=>{if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);return i?uu(e):function(e){return au(ou(e))}(e)}});return Object.freeze(a)}const qu=BigInt(0),Du=BigInt(1);function Mu(e,t){const i=t.negate();return e?i:t}function $u(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ju(e,t){$u(e,t);return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const zu=new WeakMap,Fu=new WeakMap;function Ku(e){return Fu.get(e)||1}function Vu(e,t,i,s){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,i)=>{if(!(e instanceof t))throw new Error("invalid point at index "+i)}))}(i,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,i)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+i)}))}(s,t),i.length!==s.length)throw new Error("arrays of points and scalars must have equal length");const r=e.ZERO,n=function(e){let t;for(t=0;e>Ql;e>>=eu,t+=1);return t}(BigInt(i.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(r);let h=r;for(let e=Math.floor((t.BITS-1)/o)*o;e>=0;e-=o){c.fill(r);for(let t=0;t<s.length;t++){const r=s[t],n=Number(r>>BigInt(e)&BigInt(a));c[n]=c[n].add(i[t])}let t=r;for(let e=c.length-1,i=r;e>0;e--)i=i.add(c[e]),t=t.add(i);if(h=h.add(t),0!==e)for(let e=0;e<o;e++)h=h.double()}return h}function Hu(e){return function(e){const t=Uu.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});vu(e,t)}(e.Fp),vu(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ku(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const Wu=BigInt(0),Gu=BigInt(1),Yu=BigInt(2),Zu=BigInt(8),Xu={zip215:!0};function Ju(e){const t=function(e){const t=Hu(e);return vu(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:i,n:s,prehash:r,hash:n,randomBytes:o,nByteLength:a,h:c}=t,h=Yu<<BigInt(8*a)-Gu,l=i.create,u=Lu(t.n,t.nBitLength),d=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:i.sqrt(e*i.inv(t))}}catch{return{isValid:!1,value:Wu}}}),f=t.adjustScalarBytes||(e=>e),p=t.domain||((e,t,i)=>{if(ru("phflag",i),t.length||i)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){wu("coordinate "+e,t,Wu,h)}function y(e){if(!(e instanceof b))throw new Error("ExtendedPoint expected")}const w=Eu(((e,t)=>{const{ex:s,ey:r,ez:n}=e,o=e.is0();null==t&&(t=o?Zu:i.inv(n));const a=l(s*t),c=l(r*t),h=l(n*t);if(o)return{x:Wu,y:Gu};if(h!==Gu)throw new Error("invZ was invalid");return{x:a,y:c}})),m=Eu((e=>{const{a:i,d:s}=t;if(e.is0())throw new Error("bad point: ZERO");const{ex:r,ey:n,ez:o,et:a}=e,c=l(r*r),h=l(n*n),u=l(o*o),d=l(u*u),f=l(c*i);if(l(u*l(f+h))!==l(d+l(s*l(c*h))))throw new Error("bad point: equation left != right (1)");if(l(r*n)!==l(o*a))throw new Error("bad point: equation left != right (2)");return!0}));class b{constructor(e,t,i,s){this.ex=e,this.ey=t,this.ez=i,this.et=s,g("x",e),g("y",t),g("z",i),g("t",s),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof b)throw new Error("extended point not allowed");const{x:t,y:i}=e||{};return g("x",t),g("y",i),new b(t,i,Gu,l(t*i))}static normalizeZ(e){const t=i.invertBatch(e.map((e=>e.ez)));return e.map(((e,i)=>e.toAffine(t[i]))).map(b.fromAffine)}static msm(e,t){return Vu(b,u,e,t)}_setWindowSize(e){x.setWindowSize(this,e)}assertValidity(){m(this)}equals(e){y(e);const{ex:t,ey:i,ez:s}=this,{ex:r,ey:n,ez:o}=e,a=l(t*o),c=l(r*s),h=l(i*o),u=l(n*s);return a===c&&h===u}is0(){return this.equals(b.ZERO)}negate(){return new b(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:e}=t,{ex:i,ey:s,ez:r}=this,n=l(i*i),o=l(s*s),a=l(Yu*l(r*r)),c=l(e*n),h=i+s,u=l(l(h*h)-n-o),d=c+o,f=d-a,p=c-o,g=l(u*f),y=l(d*p),w=l(u*p),m=l(f*d);return new b(g,y,m,w)}add(e){y(e);const{a:i,d:s}=t,{ex:r,ey:n,ez:o,et:a}=this,{ex:c,ey:h,ez:u,et:d}=e;if(i===BigInt(-1)){const e=l((n-r)*(h+c)),t=l((n+r)*(h-c)),i=l(t-e);if(i===Wu)return this.double();const s=l(o*Yu*d),f=l(a*Yu*u),p=f+s,g=t+e,y=f-s,w=l(p*i),m=l(g*y),v=l(p*y),E=l(i*g);return new b(w,m,E,v)}const f=l(r*c),p=l(n*h),g=l(a*s*d),w=l(o*u),m=l((r+n)*(c+h)-f-p),v=w-g,E=w+g,x=l(p-i*f),I=l(m*v),S=l(E*x),O=l(m*x),_=l(v*E);return new b(I,S,_,O)}subtract(e){return this.add(e.negate())}wNAF(e){return x.wNAFCached(this,e,b.normalizeZ)}multiply(e){const t=e;wu("scalar",t,Gu,s);const{p:i,f:r}=this.wNAF(t);return b.normalizeZ([i,r])[0]}multiplyUnsafe(e,t=b.ZERO){const i=e;return wu("scalar",i,Wu,s),i===Wu?E:this.is0()||i===Gu?this:x.wNAFCachedUnsafe(this,i,b.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return x.unsafeLadder(this,s).is0()}toAffine(e){return w(this,e)}clearCofactor(){const{h:e}=t;return e===Gu?this:this.multiplyUnsafe(e)}static fromHex(e,s=!1){const{d:r,a:n}=t,o=i.BYTES;e=pu("pointHex",e,o),ru("zip215",s);const a=e.slice(),c=e[o-1];a[o-1]=-129&c;const u=uu(a),f=s?h:i.ORDER;wu("pointHex.y",u,Wu,f);const p=l(u*u),g=l(p-Gu),y=l(r*p-n);let{isValid:w,value:m}=d(g,y);if(!w)throw new Error("Point.fromHex: invalid y coordinate");const v=(m&Gu)===Gu,E=0!=(128&c);if(!s&&m===Wu&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(m=l(-m)),b.fromAffine({x:m,y:u})}static fromPrivateKey(e){return O(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),s=fu(t,i.BYTES);return s[s.length-1]|=e&Gu?128:0,s}toHex(){return ou(this.toRawBytes())}}b.BASE=new b(t.Gx,t.Gy,Gu,l(t.Gx*t.Gy)),b.ZERO=new b(Wu,Gu,Gu,Wu);const{BASE:v,ZERO:E}=b,x=function(e,t){return{constTimeNegate:Mu,hasPrecomputes:e=>1!==Ku(e),unsafeLadder(t,i,s=e.ZERO){let r=t;for(;i>qu;)i&Du&&(s=s.add(r)),r=r.double(),i>>=Du;return s},precomputeWindow(e,i){const{windows:s,windowSize:r}=ju(i,t),n=[];let o=e,a=o;for(let e=0;e<s;e++){a=o,n.push(a);for(let e=1;e<r;e++)a=a.add(o),n.push(a);o=a.double()}return n},wNAF(i,s,r){const{windows:n,windowSize:o}=ju(i,t);let a=e.ZERO,c=e.BASE;const h=BigInt(2**i-1),l=2**i,u=BigInt(i);for(let e=0;e<n;e++){const t=e*o;let i=Number(r&h);r>>=u,i>o&&(i-=l,r+=Du);const n=t,d=t+Math.abs(i)-1,f=e%2!=0,p=i<0;0===i?c=c.add(Mu(f,s[n])):a=a.add(Mu(p,s[d]))}return{p:a,f:c}},wNAFUnsafe(i,s,r,n=e.ZERO){const{windows:o,windowSize:a}=ju(i,t),c=BigInt(2**i-1),h=2**i,l=BigInt(i);for(let e=0;e<o;e++){const t=e*a;if(r===qu)break;let i=Number(r&c);if(r>>=l,i>a&&(i-=h,r+=Du),0===i)continue;let o=s[t+Math.abs(i)-1];i<0&&(o=o.negate()),n=n.add(o)}return n},getPrecomputes(e,t,i){let s=zu.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&zu.set(t,i(s))),s},wNAFCached(e,t,i){const s=Ku(e);return this.wNAF(s,this.getPrecomputes(s,e,i),t)},wNAFCachedUnsafe(e,t,i,s){const r=Ku(e);return 1===r?this.unsafeLadder(e,t,s):this.wNAFUnsafe(r,this.getPrecomputes(r,e,i),t,s)},setWindowSize(e,i){$u(i,t),Fu.set(e,i),zu.delete(e)}}}(b,8*a);function I(e){return Tu(e,s)}function S(e){return I(uu(e))}function O(e){const t=i.BYTES;e=pu("private key",e,t);const s=pu("hashed private key",n(e),2*t),r=f(s.slice(0,t)),o=s.slice(t,2*t),a=S(r),c=v.multiply(a),h=c.toRawBytes();return{head:r,prefix:o,scalar:a,point:c,pointBytes:h}}function _(e=new Uint8Array,...t){const i=gu(...t);return S(n(p(i,pu("context",e),!!r)))}const A=Xu;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return O(e).pointBytes},sign:function(e,t,n={}){e=pu("message",e),r&&(e=r(e));const{prefix:o,scalar:a,pointBytes:c}=O(t),h=_(n.context,o,e),l=v.multiply(h).toRawBytes(),u=I(h+_(n.context,l,c,e)*a);return wu("signature.s",u,Wu,s),pu("result",gu(l,fu(u,i.BYTES)),2*i.BYTES)},verify:function(e,t,s,n=A){const{context:o,zip215:a}=n,c=i.BYTES;e=pu("signature",e,2*c),t=pu("message",t),s=pu("publicKey",s,c),void 0!==a&&ru("zip215",a),r&&(t=r(t));const h=uu(e.slice(c,2*c));let l,u,d;try{l=b.fromHex(s,a),u=b.fromHex(e.slice(0,c),a),d=v.multiplyUnsafe(h)}catch{return!1}if(!a&&l.isSmallOrder())return!1;const f=_(o,u.toRawBytes(),l.toRawBytes(),t);return u.add(l.multiplyUnsafe(f)).subtract(d).clearCofactor().equals(b.ZERO)},ExtendedPoint:b,utils:{getExtendedPublicKey:O,randomPrivateKey:()=>o(i.BYTES),precompute:(e=8,t=b.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}BigInt(0),BigInt(1);const Qu=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ed=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const td=BigInt(1),id=BigInt(2);BigInt(3);const sd=BigInt(5),rd=BigInt(8);function nd(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function od(e,t){const i=Qu,s=Tu(t*t*t,i),r=function(e){const t=BigInt(10),i=BigInt(20),s=BigInt(40),r=BigInt(80),n=Qu,o=e*e%n*e%n,a=Ru(o,id,n)*o%n,c=Ru(a,td,n)*e%n,h=Ru(c,sd,n)*c%n,l=Ru(h,t,n)*h%n,u=Ru(l,i,n)*l%n,d=Ru(u,s,n)*u%n,f=Ru(d,r,n)*d%n,p=Ru(f,r,n)*d%n,g=Ru(p,t,n)*h%n;return{pow_p_5_8:Ru(g,id,n)*e%n,b2:o}}(e*Tu(s*s*t,i)).pow_p_5_8;let n=Tu(e*s*r,i);const o=Tu(t*n*n,i),a=n,c=Tu(n*ed,i),h=o===e,l=o===Tu(-e,i),u=o===Tu(-e*ed,i);return h&&(n=a),(l||u)&&(n=c),((e,t)=>(Tu(e,t)&Iu)===Iu)(n,i)&&(n=Tu(-n,i)),{isValid:h||l,value:n}}const ad=Lu(Qu,void 0,!0),cd=Ju({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:ad,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:rd,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Jl,randomBytes:jl,adjustScalarBytes:nd,uvRatio:od}),hd=".",ld="base64url",ud="utf8",dd="utf8",fd=":",pd="did",gd="key",yd="base58btc",wd="z",md="K36";function bd(e){return null!=globalThis.Buffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function vd(e=0){return null!=globalThis.Buffer&&null!=globalThis.Buffer.allocUnsafe?bd(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Ed(e,t){t||(t=e.reduce(((e,t)=>e+t.length),0));const i=vd(t);let s=0;for(const t of e)i.set(t,s),s+=t.length;return bd(i)}var xd=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),s=0;s<i.length;s++)i[s]=255;for(var r=0;r<e.length;r++){var n=e.charAt(r),o=n.charCodeAt(0);if(255!==i[o])throw new TypeError(n+" is ambiguous");i[o]=r}var a=e.length,c=e.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var s=0,r=0;e[t]===c;)s++,t++;for(var n=(e.length-t)*h+1>>>0,o=new Uint8Array(n);e[t];){var l=i[e.charCodeAt(t)];if(255===l)return;for(var u=0,d=n-1;(0!==l||u<r)&&-1!==d;d--,u++)l+=a*o[d]>>>0,o[d]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=u,t++}if(" "!==e[t]){for(var f=n-r;f!==n&&0===o[f];)f++;for(var p=new Uint8Array(s+(n-f)),g=s;f!==n;)p[g++]=o[f++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,s=0,r=0,n=t.length;r!==n&&0===t[r];)r++,i++;for(var o=(n-r)*l+1>>>0,h=new Uint8Array(o);r!==n;){for(var u=t[r],d=0,f=o-1;(0!==u||d<s)&&-1!==f;f--,d++)u+=256*h[f]>>>0,h[f]=u%a>>>0,u=u/a>>>0;if(0!==u)throw new Error("Non-zero carry");s=d,r++}for(var p=o-s;p!==o&&0===h[p];)p++;for(var g=c.repeat(i);p<o;++p)g+=e.charAt(h[p]);return g},decodeUnsafe:u,decode:function(e){var i=u(e);if(i)return i;throw new Error(`Non-${t} character`)}}},Id=xd;const Sd=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};class Od{constructor(e,t,i){this.name=e,this.prefix=t,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class _d{constructor(e,t,i){if(this.name=e,this.prefix=t,void 0===t.codePointAt(0))throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=i}decode(e){if("string"==typeof e){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))}throw Error("Can only multibase decode strings")}or(e){return Pd(this,e)}}class Ad{constructor(e){this.decoders=e}or(e){return Pd(this,e)}decode(e){const t=e[0],i=this.decoders[t];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 Pd=(e,t)=>new Ad({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Td{constructor(e,t,i,s){this.name=e,this.prefix=t,this.baseEncode=i,this.baseDecode=s,this.encoder=new Od(e,t,i),this.decoder=new _d(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Bd=({name:e,prefix:t,encode:i,decode:s})=>new Td(e,t,i,s),Rd=({prefix:e,name:t,alphabet:i})=>{const{encode:s,decode:r}=Id(i,t);return Bd({prefix:e,name:t,encode:s,decode:e=>Sd(r(e))})},Nd=({name:e,prefix:t,bitsPerChar:i,alphabet:s})=>Bd({prefix:t,name:e,encode:e=>((e,t,i)=>{const s="="===t[t.length-1],r=(1<<i)-1;let n="",o=0,a=0;for(let s=0;s<e.length;++s)for(a=a<<8|e[s],o+=8;o>i;)o-=i,n+=t[r&a>>o];if(o&&(n+=t[r&a<<i-o]),s)for(;n.length*i&7;)n+="=";return n})(e,s,i),decode:t=>((e,t,i,s)=>{const r={};for(let e=0;e<t.length;++e)r[t[e]]=e;let n=e.length;for(;"="===e[n-1];)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,h=0;for(let t=0;t<n;++t){const n=r[e[t]];if(void 0===n)throw new SyntaxError(`Non-${s} character`);c=c<<i|n,a+=i,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o})(t,s,i,e)}),Cd=Bd({prefix:"\0",name:"identity",encode:e=>(e=>(new TextDecoder).decode(e))(e),decode:e=>(e=>(new TextEncoder).encode(e))(e)});var Ud=Object.freeze({__proto__:null,identity:Cd});const kd=Nd({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ld=Object.freeze({__proto__:null,base2:kd});const qd=Nd({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Dd=Object.freeze({__proto__:null,base8:qd});const Md=Rd({prefix:"9",name:"base10",alphabet:"0123456789"});var $d=Object.freeze({__proto__:null,base10:Md});const jd=Nd({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zd=Nd({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Fd=Object.freeze({__proto__:null,base16:jd,base16upper:zd});const Kd=Nd({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Vd=Nd({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Hd=Nd({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wd=Nd({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gd=Nd({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yd=Nd({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zd=Nd({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Xd=Nd({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jd=Nd({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Qd=Object.freeze({__proto__:null,base32:Kd,base32upper:Vd,base32pad:Hd,base32padupper:Wd,base32hex:Gd,base32hexupper:Yd,base32hexpad:Zd,base32hexpadupper:Xd,base32z:Jd});const ef=Rd({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),tf=Rd({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var sf=Object.freeze({__proto__:null,base36:ef,base36upper:tf});const rf=Rd({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nf=Rd({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var of=Object.freeze({__proto__:null,base58btc:rf,base58flickr:nf});const af=Nd({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cf=Nd({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hf=Nd({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lf=Nd({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var uf=Object.freeze({__proto__:null,base64:af,base64pad:cf,base64url:hf,base64urlpad:lf});const df=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ff=df.reduce(((e,t,i)=>(e[i]=t,e)),[]),pf=df.reduce(((e,t,i)=>(e[t.codePointAt(0)]=i,e)),[]);const gf=Bd({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=ff[t]),"")},decode:function(e){const t=[];for(const i of e){const e=pf[i.codePointAt(0)];if(void 0===e)throw new Error(`Non-base256emoji character: ${i}`);t.push(e)}return new Uint8Array(t)}});var yf=Object.freeze({__proto__:null,base256emoji:gf}),wf=function e(t,i,s){i=i||[];for(var r=s=s||0;t>=vf;)i[s++]=255&t|mf,t/=128;for(;t&bf;)i[s++]=255&t|mf,t>>>=7;return i[s]=0|t,e.bytes=s-r+1,i},mf=128,bf=-128,vf=Math.pow(2,31);var Ef=function e(t,i){var s,r=0,n=(i=i||0,0),o=i,a=t.length;do{if(o>=a)throw e.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=n<28?(s&If)<<n:(s&If)*Math.pow(2,n),n+=7}while(s>=xf);return e.bytes=o-i,r},xf=128,If=127;var Sf=Math.pow(2,7),Of=Math.pow(2,14),_f=Math.pow(2,21),Af=Math.pow(2,28),Pf=Math.pow(2,35),Tf=Math.pow(2,42),Bf=Math.pow(2,49),Rf=Math.pow(2,56),Nf=Math.pow(2,63),Cf={encode:wf,decode:Ef,encodingLength:function(e){return e<Sf?1:e<Of?2:e<_f?3:e<Af?4:e<Pf?5:e<Tf?6:e<Bf?7:e<Rf?8:e<Nf?9:10}};const Uf=(e,t,i=0)=>(Cf.encode(e,t,i),t),kf=e=>Cf.encodingLength(e),Lf=(e,t)=>{const i=t.byteLength,s=kf(e),r=s+kf(i),n=new Uint8Array(r+i);return Uf(e,n,0),Uf(i,n,s),n.set(t,r),new qf(e,i,t,n)};class qf{constructor(e,t,i,s){this.code=e,this.size=t,this.digest=i,this.bytes=s}}const Df=({name:e,code:t,encode:i})=>new Mf(e,t,i);class Mf{constructor(e,t,i){this.name=e,this.code=t,this.encode=i}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?Lf(this.code,t):t.then((e=>Lf(this.code,e)))}throw Error("Unknown type, must be binary type")}}const $f=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),jf=Df({name:"sha2-256",code:18,encode:$f("SHA-256")}),zf=Df({name:"sha2-512",code:19,encode:$f("SHA-512")});Object.freeze({__proto__:null,sha256:jf,sha512:zf});const Ff=Sd,Kf={code:0,name:"identity",encode:Ff,digest:e=>Lf(0,Ff(e))};Object.freeze({__proto__:null,identity:Kf});new TextEncoder,new TextDecoder;const Vf={...Ud,...Ld,...Dd,...$d,...Fd,...Qd,...sf,...of,...uf,...yf};function Hf(e,t,i,s){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:i},decoder:{decode:s}}}const Wf=Hf("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Gf=Hf("ascii","a",(e=>{let t="a";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t}),(e=>{const t=vd((e=e.substring(1)).length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t})),Yf={utf8:Wf,"utf-8":Wf,hex:Vf.base16,latin1:Gf,ascii:Gf,binary:Gf,...Vf};function Zf(e,t="utf8"){const i=Yf[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.encoder.encode(e).substring(1):globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8")}function Xf(e,t="utf8"){const i=Yf[t];if(!i)throw new Error(`Unsupported encoding "${t}"`);return"utf8"!==t&&"utf-8"!==t||null==globalThis.Buffer||null==globalThis.Buffer.from?i.decoder.decode(`${i.prefix}${e}`):bd(globalThis.Buffer.from(e,"utf-8"))}function Jf(e){return Cl(Zf(Xf(e,ld),ud))}function Qf(e){return Zf(Xf(Ul(e),ud),ld)}function ep(e){const t=Xf(md,yd),i=wd+Zf(Ed([t,e]),yd);return[pd,gd,i].join(fd)}function tp(e){return Zf(e,ld)}function ip(e){const t=e.split(hd),i=Jf(t[0]),s=Jf(t[1]),r=function(e){return Xf(e,ld)}(t[2]);return{header:i,payload:s,signature:r,data:Xf(t.slice(0,2).join(hd),dd)}}function sp(e=jl(32)){const t=cd.getPublicKey(e);return{secretKey:Ed([e,t]),publicKey:t}}async function rp(e,t,i,s,r=m.fromMiliseconds(Date.now())){const n={alg:"EdDSA",typ:"JWT"},o={iss:ep(s.publicKey),sub:e,aud:t,iat:r,exp:r+i},a=function(e){return Xf([Qf(e.header),Qf(e.payload)].join(hd),dd)}({header:n,payload:o});return function(e){return[Qf(e.header),Qf(e.payload),tp(e.signature)].join(hd)}({header:n,payload:o,signature:cd.sign(a,s.secretKey.slice(0,32))})}const np={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"}};function op(e){return(4294967296+e).toString(16).substring(1)}var ap={normalizeInput:function(e){let t;if(e instanceof Uint8Array)t=e;else{if("string"!=typeof e)throw new Error("Input must be an string, Buffer or Uint8Array");t=(new TextEncoder).encode(e)}return t},toHex:function(e){return Array.prototype.map.call(e,(function(e){return(e<16?"0":"")+e.toString(16)})).join("")},debugPrint:function(e,t,i){let s="\n"+e+" = ";for(let r=0;r<t.length;r+=2){if(32===i)s+=op(t[r]).toUpperCase(),s+=" ",s+=op(t[r+1]).toUpperCase();else{if(64!==i)throw new Error("Invalid size "+i);s+=op(t[r+1]).toUpperCase(),s+=op(t[r]).toUpperCase()}r%6==4?s+="\n"+new Array(e.length+4).join(" "):r<t.length-2&&(s+=" ")}console.log(s)},testSpeed:function(e,t,i){let s=(new Date).getTime();const r=new Uint8Array(t);for(let e=0;e<t;e++)r[e]=e%256;const n=(new Date).getTime();console.log("Generated random input in "+(n-s)+"ms"),s=n;for(let n=0;n<i;n++){const i=e(r),n=(new Date).getTime(),o=n-s;s=n,console.log("Hashed in "+o+"ms: "+i.substring(0,20)+"..."),console.log(Math.round(t/(1<<20)/(o/1e3)*100)/100+" MB PER SECOND")}}};const cp=ap;function hp(e,t,i){const s=e[t]+e[i];let r=e[t+1]+e[i+1];s>=4294967296&&r++,e[t]=s,e[t+1]=r}function lp(e,t,i,s){let r=e[t]+i;i<0&&(r+=4294967296);let n=e[t+1]+s;r>=4294967296&&n++,e[t]=r,e[t+1]=n}function up(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function dp(e,t,i,s,r,n){const o=yp[r],a=yp[r+1],c=yp[n],h=yp[n+1];hp(gp,e,t),lp(gp,e,o,a);let l=gp[s]^gp[e],u=gp[s+1]^gp[e+1];gp[s]=u,gp[s+1]=l,hp(gp,i,s),l=gp[t]^gp[i],u=gp[t+1]^gp[i+1],gp[t]=l>>>24^u<<8,gp[t+1]=u>>>24^l<<8,hp(gp,e,t),lp(gp,e,c,h),l=gp[s]^gp[e],u=gp[s+1]^gp[e+1],gp[s]=l>>>16^u<<16,gp[s+1]=u>>>16^l<<16,hp(gp,i,s),l=gp[t]^gp[i],u=gp[t+1]^gp[i+1],gp[t]=u>>>31^l<<1,gp[t+1]=l>>>31^u<<1}const fp=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),pp=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3].map((function(e){return 2*e}))),gp=new Uint32Array(32),yp=new Uint32Array(32);function wp(e,t){let i=0;for(i=0;i<16;i++)gp[i]=e.h[i],gp[i+16]=fp[i];for(gp[24]=gp[24]^e.t,gp[25]=gp[25]^e.t/4294967296,t&&(gp[28]=~gp[28],gp[29]=~gp[29]),i=0;i<32;i++)yp[i]=up(e.b,4*i);for(i=0;i<12;i++)dp(0,8,16,24,pp[16*i+0],pp[16*i+1]),dp(2,10,18,26,pp[16*i+2],pp[16*i+3]),dp(4,12,20,28,pp[16*i+4],pp[16*i+5]),dp(6,14,22,30,pp[16*i+6],pp[16*i+7]),dp(0,10,20,30,pp[16*i+8],pp[16*i+9]),dp(2,12,22,24,pp[16*i+10],pp[16*i+11]),dp(4,14,16,26,pp[16*i+12],pp[16*i+13]),dp(6,8,18,28,pp[16*i+14],pp[16*i+15]);for(i=0;i<16;i++)e.h[i]=e.h[i]^gp[i]^gp[i+16]}const mp=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function bp(e,t,i,s){if(0===e||e>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(t&&t.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(i&&16!==i.length)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(s&&16!==s.length)throw new Error("Illegal personal, expected Uint8Array with length is 16");const r={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:e};mp.fill(0),mp[0]=e,t&&(mp[1]=t.length),mp[2]=1,mp[3]=1,i&&mp.set(i,32),s&&mp.set(s,48);for(let e=0;e<16;e++)r.h[e]=fp[e]^up(mp,4*e);return t&&(vp(r,t),r.c=128),r}function vp(e,t){for(let i=0;i<t.length;i++)128===e.c&&(e.t+=e.c,wp(e,!1),e.c=0),e.b[e.c++]=t[i]}function Ep(e){for(e.t+=e.c;e.c<128;)e.b[e.c++]=0;wp(e,!0);const t=new Uint8Array(e.outlen);for(let i=0;i<e.outlen;i++)t[i]=e.h[i>>2]>>8*(3&i);return t}function xp(e,t,i,s,r){i=i||64,e=cp.normalizeInput(e),s&&(s=cp.normalizeInput(s)),r&&(r=cp.normalizeInput(r));const n=bp(i,t,s,r);return vp(n,e),Ep(n)}var Ip={blake2b:xp,blake2bHex:function(e,t,i,s,r){const n=xp(e,t,i,s,r);return cp.toHex(n)},blake2bInit:bp,blake2bUpdate:vp,blake2bFinal:Ep};const Sp=ap;function Op(e,t){return e[t]^e[t+1]<<8^e[t+2]<<16^e[t+3]<<24}function _p(e,t,i,s,r,n){Bp[e]=Bp[e]+Bp[t]+r,Bp[s]=Ap(Bp[s]^Bp[e],16),Bp[i]=Bp[i]+Bp[s],Bp[t]=Ap(Bp[t]^Bp[i],12),Bp[e]=Bp[e]+Bp[t]+n,Bp[s]=Ap(Bp[s]^Bp[e],8),Bp[i]=Bp[i]+Bp[s],Bp[t]=Ap(Bp[t]^Bp[i],7)}function Ap(e,t){return e>>>t^e<<32-t}const Pp=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Tp=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),Bp=new Uint32Array(16),Rp=new Uint32Array(16);function Np(e,t){let i=0;for(i=0;i<8;i++)Bp[i]=e.h[i],Bp[i+8]=Pp[i];for(Bp[12]^=e.t,Bp[13]^=e.t/4294967296,t&&(Bp[14]=~Bp[14]),i=0;i<16;i++)Rp[i]=Op(e.b,4*i);for(i=0;i<10;i++)_p(0,4,8,12,Rp[Tp[16*i+0]],Rp[Tp[16*i+1]]),_p(1,5,9,13,Rp[Tp[16*i+2]],Rp[Tp[16*i+3]]),_p(2,6,10,14,Rp[Tp[16*i+4]],Rp[Tp[16*i+5]]),_p(3,7,11,15,Rp[Tp[16*i+6]],Rp[Tp[16*i+7]]),_p(0,5,10,15,Rp[Tp[16*i+8]],Rp[Tp[16*i+9]]),_p(1,6,11,12,Rp[Tp[16*i+10]],Rp[Tp[16*i+11]]),_p(2,7,8,13,Rp[Tp[16*i+12]],Rp[Tp[16*i+13]]),_p(3,4,9,14,Rp[Tp[16*i+14]],Rp[Tp[16*i+15]]);for(i=0;i<8;i++)e.h[i]^=Bp[i]^Bp[i+8]}function Cp(e,t){if(!(e>0&&e<=32))throw new Error("Incorrect output length, should be in [1, 32]");const i=t?t.length:0;if(t&&!(i>0&&i<=32))throw new Error("Incorrect key length, should be in [1, 32]");const s={h:new Uint32Array(Pp),b:new Uint8Array(64),c:0,t:0,outlen:e};return s.h[0]^=16842752^i<<8^e,i>0&&(Up(s,t),s.c=64),s}function Up(e,t){for(let i=0;i<t.length;i++)64===e.c&&(e.t+=e.c,Np(e,!1),e.c=0),e.b[e.c++]=t[i]}function kp(e){for(e.t+=e.c;e.c<64;)e.b[e.c++]=0;Np(e,!0);const t=new Uint8Array(e.outlen);for(let i=0;i<e.outlen;i++)t[i]=e.h[i>>2]>>8*(3&i)&255;return t}function Lp(e,t,i){i=i||32,e=Sp.normalizeInput(e);const s=Cp(i,t);return Up(s,e),kp(s)}var qp={blake2s:Lp,blake2sHex:function(e,t,i){const s=Lp(e,t,i);return Sp.toHex(s)},blake2sInit:Cp,blake2sUpdate:Up,blake2sFinal:kp};var Dp={blake2b:Ip.blake2b,blake2bHex:Ip.blake2bHex,blake2bInit:Ip.blake2bInit,blake2bUpdate:Ip.blake2bUpdate,blake2bFinal:Ip.blake2bFinal,blake2s:qp.blake2s,blake2sHex:qp.blake2sHex,blake2sInit:qp.blake2sInit,blake2sUpdate:qp.blake2sUpdate,blake2sFinal:qp.blake2sFinal},Mp={exports:{}};function $p(e){try{return JSON.stringify(e)}catch{return'"[Circular]"'}}var jp=function(e,t,i){var s=i&&i.stringify||$p;if("object"==typeof e&&null!==e){var r=t.length+1;if(1===r)return e;var n=new Array(r);n[0]=s(e);for(var o=1;o<r;o++)n[o]=s(t[o]);return n.join(" ")}if("string"!=typeof e)return e;var a=t.length;if(0===a)return e;for(var c="",h=0,l=-1,u=e&&e.length||0,d=0;d<u;){if(37===e.charCodeAt(d)&&d+1<u){switch(l=l>-1?l:0,e.charCodeAt(d+1)){case 100:case 102:if(h>=a||null==t[h])break;l<d&&(c+=e.slice(l,d)),c+=Number(t[h]),l=d+2,d++;break;case 105:if(h>=a||null==t[h])break;l<d&&(c+=e.slice(l,d)),c+=Math.floor(Number(t[h])),l=d+2,d++;break;case 79:case 111:case 106:if(h>=a||void 0===t[h])break;l<d&&(c+=e.slice(l,d));var f=typeof t[h];if("string"===f){c+="'"+t[h]+"'",l=d+2,d++;break}if("function"===f){c+=t[h].name||"<anonymous>",l=d+2,d++;break}c+=s(t[h]),l=d+2,d++;break;case 115:if(h>=a)break;l<d&&(c+=e.slice(l,d)),c+=String(t[h]),l=d+2,d++;break;case 37:l<d&&(c+=e.slice(l,d)),c+="%",l=d+2,d++,h--}++h}++d}return-1===l?e:(l<u&&(c+=e.slice(l)),c)};const zp=jp;Mp.exports=Zp;const Fp=function(){function e(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 e(self)||e(window)||e(this)||{}}}().console||{},Kp={mapHttpRequest:ig,mapHttpResponse:ig,wrapRequestSerializer:sg,wrapResponseSerializer:sg,wrapErrorSerializer:sg,req:ig,res:ig,err:eg,errWithCause:eg};function Vp(e,t){return"silent"===e?1/0:t.levels.values[e]}const Hp=Symbol("pino.logFuncs"),Wp=Symbol("pino.hierarchy"),Gp={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Yp(e,t){const i={logger:t,parent:e[Wp]};t[Wp]=i}function Zp(e){(e=e||{}).browser=e.browser||{};const t=e.browser.transmit;if(t&&"function"!=typeof t.send)throw Error("pino: transmit option must have a send function");const i=e.browser.write||Fp;e.browser.write&&(e.browser.asObject=!0);const s=e.serializers||{},r=function(e,t){return Array.isArray(e)?e.filter((function(e){return"!stdSerializers.err"!==e})):!0===e&&Object.keys(t)}(e.browser.serialize,s);let n=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=Object.keys(e.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);"function"==typeof i&&a.forEach((function(e){i[e]=i})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const c=e.level||"info",h=Object.create(i);h.log||(h.log=rg),function(e,t,i){const s={};t.forEach((e=>{s[e]=i[e]?i[e]:Fp[e]||Fp[Gp[e]||"log"]||rg})),e[Hp]=s}(h,a,i),Yp({},h),Object.defineProperty(h,"levelVal",{get:function(){return Vp(this.level,this)}}),Object.defineProperty(h,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,Xp(this,l,h,"error"),Xp(this,l,h,"fatal"),Xp(this,l,h,"warn"),Xp(this,l,h,"info"),Xp(this,l,h,"debug"),Xp(this,l,h,"trace"),o.forEach((e=>{Xp(this,l,h,e)}))}});const l={transmit:t,serialize:r,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:a,timestamp:tg(e),messageKey:e.messageKey||"msg",onChild:e.onChild||rg};function u(i,n,o){if(!n)throw new Error("missing bindings for child Pino");o=o||{},r&&n.serializers&&(o.serializers=n.serializers);const a=o.serializers;if(r&&a){var c=Object.assign({},s,a),h=!0===e.browser.serialize?Object.keys(c):r;delete n.serializers,Jp([n],h,c,this._stdErrSerialize)}function l(e){this._childLevel=1+(0|e._childLevel),this.bindings=n,c&&(this.serializers=c,this._serialize=h),t&&(this._logEvent=Qp([].concat(e._logEvent.bindings,n)))}l.prototype=this;const d=new l(this);return Yp(this,d),d.child=function(...e){return u.call(this,i,...e)},d.level=o.level||this.level,i.onChild(d),d}return h.levels=function(e){const t=e.customLevels||{},i=Object.assign({},Zp.levels.values,t),s=Object.assign({},Zp.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(i){t[e[i]]=i})),t}(t));return{values:i,labels:s}}(e),h.level=c,h.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]},h.setMaxListeners=h.getMaxListeners=h.emit=h.addListener=h.on=h.prependListener=h.once=h.prependOnceListener=h.removeListener=h.removeAllListeners=h.listeners=h.listenerCount=h.eventNames=h.write=h.flush=rg,h.serializers=s,h._serialize=r,h._stdErrSerialize=n,h.child=function(...e){return u.call(this,l,...e)},t&&(h._logEvent=Qp()),h}function Xp(e,t,i,s){if(Object.defineProperty(e,s,{value:Vp(e.level,i)>Vp(s,i)?rg:i[Hp][s],writable:!0,enumerable:!0,configurable:!0}),e[s]===rg){if(!t.transmit)return;const r=Vp(t.transmit.level||e.level,i);if(Vp(s,i)<r)return}e[s]=function(e,t,i,s){return function(r){return function(){const n=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Fp?Fp:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var h=!1;if(t.serialize&&(Jp(o,this._serialize,this.serializers,this._stdErrSerialize),h=!0),t.asObject||t.formatters?r.call(a,...function(e,t,i,s,r){const{level:n,log:o=(e=>e)}=r.formatters||{},a=i.slice();let c=a[0];const h={};let l=1+(0|e._childLevel);if(l<1&&(l=1),s&&(h.time=s),n){const i=n(t,e.levels.values[t]);Object.assign(h,i)}else h.level=e.levels.values[t];if(r.asObjectBindingsOnly){if(null!==c&&"object"==typeof c)for(;l--&&"object"==typeof a[0];)Object.assign(h,a.shift());return[o(h),...a]}if(null!==c&&"object"==typeof c){for(;l--&&"object"==typeof a[0];)Object.assign(h,a.shift());c=a.length?zp(a.shift(),a):void 0}else"string"==typeof c&&(c=zp(a.shift(),a));return void 0!==c&&(h[r.messageKey]=c),[o(h)]}(this,s,o,n,t)):r.apply(a,o),t.transmit){const r=t.transmit.level||e._level,a=Vp(r,i),c=Vp(s,i);if(c<a)return;!function(e,t,i,s=!1){const r=t.send,n=t.ts,o=t.methodLevel,a=t.methodValue,c=t.val,h=e._logEvent.bindings;s||Jp(i,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize),e._logEvent.ts=n,e._logEvent.messages=i.filter((function(e){return-1===h.indexOf(e)})),e._logEvent.level.label=o,e._logEvent.level.value=a,r(o,e._logEvent,c),e._logEvent=Qp(h)}(this,{ts:n,methodLevel:s,methodValue:c,transmitLevel:r,transmitValue:i.levels.values[t.transmit.level||e._level],send:t.transmit.send,val:Vp(e._level,i)},o,h)}}}(e[Hp][s])}(e,t,i,s);const r=function(e){const t=[];e.bindings&&t.push(e.bindings);let i=e[Wp];for(;i.parent;)i=i.parent,i.logger.bindings&&t.push(i.logger.bindings);return t.reverse()}(e);0!==r.length&&(e[s]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(r,e[s]))}function Jp(e,t,i,s){for(const r in e)if(s&&e[r]instanceof Error)e[r]=Zp.stdSerializers.err(e[r]);else if("object"==typeof e[r]&&!Array.isArray(e[r])&&t)for(const s in e[r])t.indexOf(s)>-1&&s in i&&(e[r][s]=i[s](e[r][s]))}function Qp(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function eg(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const i in e)void 0===t[i]&&(t[i]=e[i]);return t}function tg(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?ng:og}function ig(){return{}}function sg(e){return e}function rg(){}function ng(){return!1}function og(){return Date.now()}Zp.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"}},Zp.stdSerializers=Kp,Zp.stdTimeFunctions=Object.assign({},{nullTime:ng,epochTime:og,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),Mp.exports.default=Zp,Mp.exports.pino=Zp;const ag="info",cg="custom_context",hg=1024e3;var lg=Object.defineProperty,ug=(e,t,i)=>((e,t,i)=>t in e?lg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class dg{constructor(e){ug(this,"nodeValue"),ug(this,"sizeInBytes"),ug(this,"next"),this.nodeValue=e,this.sizeInBytes=(new TextEncoder).encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class fg{constructor(e){ug(this,"lengthInNodes"),ug(this,"sizeInBytes"),ug(this,"head"),ug(this,"tail"),ug(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const t=new dg(e);if(t.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${t.size}`);for(;this.size+t.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=t),this.tail=t):(this.head=t,this.tail=t),this.lengthInNodes++,this.sizeInBytes+=t.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 t=this.head;for(;null!==t;)e.push(t.value),t=t.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 t=e.value;return e=e.next,{done:!1,value:t}}}}}function pg(e){return"string"==typeof e?e:(e=>JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString()+"n":t)))(e)||""}var gg=Object.defineProperty,yg=(e,t,i)=>((e,t,i)=>t in e?gg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class wg{constructor(e,t=hg){yg(this,"logs"),yg(this,"level"),yg(this,"levelValue"),yg(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=Mp.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=t,this.logs=new fg(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,t){t===Mp.exports.levels.values.error?console.error(e):t===Mp.exports.levels.values.warn?console.warn(e):t===Mp.exports.levels.values.debug?console.debug(e):t===Mp.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(pg({timestamp:(new Date).toISOString(),log:e}));const t="string"==typeof e?JSON.parse(e).level:e.level;t>=this.levelValue&&this.forwardToConsole(e,t)}getLogs(){return this.logs}clearLogs(){this.logs=new fg(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const t=this.getLogArray();return t.push(pg({extraMetadata:e})),new Blob(t,{type:"application/json"})}}var mg=Object.defineProperty,bg=(e,t,i)=>((e,t,i)=>t in e?mg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class vg{constructor(e,t=hg){bg(this,"baseChunkLogger"),this.baseChunkLogger=new wg(e,t)}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 t=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=t,i.download=`walletconnect-logs-${(new Date).toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t)}}var Eg=Object.defineProperty,xg=(e,t,i)=>((e,t,i)=>t in e?Eg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Ig{constructor(e,t=hg){xg(this,"baseChunkLogger"),this.baseChunkLogger=new wg(e,t)}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 Sg=Object.defineProperty,Og=Object.defineProperties,_g=Object.getOwnPropertyDescriptors,Ag=Object.getOwnPropertySymbols,Pg=Object.prototype.hasOwnProperty,Tg=Object.prototype.propertyIsEnumerable,Bg=(e,t,i)=>t in e?Sg(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,Rg=(e,t)=>{for(var i in t||(t={}))Pg.call(t,i)&&Bg(e,i,t[i]);if(Ag)for(var i of Ag(t))Tg.call(t,i)&&Bg(e,i,t[i]);return e},Ng=(e,t)=>Og(e,_g(t));function Cg(e,t=cg){return e[t]||""}function Ug(e,t,i=cg){const s=function(e,t,i=cg){const s=Cg(e,i);return s.trim()?`${s}/${t}`:t}(e,t,i);return function(e,t,i=cg){return e[i]=t,e}(e.child({context:s}),s,i)}function kg(e){var t;if(typeof e.loggerOverride<"u"&&"string"!=typeof e.loggerOverride)return{logger:e.loggerOverride,chunkLoggerController:null};const i=Ng(Rg({},e.opts),{level:"string"==typeof e.loggerOverride?e.loggerOverride:null==(t=e.opts)?void 0:t.level});return typeof window<"u"?function(e){var t,i;const s=new vg(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:Mp.exports(Ng(Rg({},e.opts),{level:"trace",browser:Ng(Rg({},null==(i=e.opts)?void 0:i.browser),{write:e=>s.write(e)})})),chunkLoggerController:s}}(Ng(Rg({},e),{opts:i})):function(e){var t,i;const s=new Ig(null==(t=e.opts)?void 0:t.level,e.maxSizeInBytes);return{logger:Mp.exports(Ng(Rg({},e.opts),{level:"trace",browser:Ng(Rg({},null==(i=e.opts)?void 0:i.browser),{write:e=>s.write(e)})}),s),chunkLoggerController:s}}(Ng(Rg({},e),{opts:i}))}const Lg=":";function qg(e){const[t,i]=e.split(Lg);return{namespace:t,reference:i}}function Dg(e,t=[]){const i=[];return Object.keys(e).forEach((s=>{if(t.length&&!t.includes(s))return;const r=e[s];i.push(...r.accounts)})),i}function Mg(e,t){return e.includes(":")?[e]:t.chains||[]}const $g={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}},jg={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 zg(e,t){const{message:i,code:s}=jg[e];return{message:t?`${i} ${t}`:i,code:s}}function Fg(e,t){const{message:i,code:s}=$g[e];return{message:t?`${i} ${t}`:i,code:s}}const Kg="ReactNative",Vg={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Hg="js";function Wg(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Gg(){return!z()&&!!F()&&navigator.product===Kg}function Yg(){return!Wg()&&!!F()&&!!z()}function Zg(){return Gg()?Vg.reactNative:Wg()?Vg.node:Yg()?Vg.browser:Vg.unknown}function Xg(){try{return Gg()&&typeof global<"u"&&typeof global?.Application<"u"?global.Application?.applicationId:void 0}catch{return}}function Jg(){return H()||{name:"",description:"",url:"",icons:[""]}}function Qg(e,t,i){const s=function(){if(Zg()===Vg.reactNative&&typeof global<"u"&&typeof global?.Platform<"u"){const{OS:e,Version:t}=global.Platform;return[e,t].join("-")}const e=g();if(null===e)return"unknown";const t=e.os?e.os.replace(" ","").toLowerCase():"unknown";return"browser"===e.type?[t,e.name,e.version].join("-"):[t,e.version].join("-")}(),r=function(){const e=Zg();return e===Vg.browser?[e,K()?.host||"unknown"].join(":"):e}();return[[e,t].join("-"),[Hg,i].join("-"),s,r].join("/")}function ey({protocol:e,version:t,relayUrl:i,sdkVersion:s,auth:r,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const h=i.split("?"),l={auth:r,ua:Qg(e,t,s),projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},u=function(e,t){const i=new URLSearchParams(e);return Object.entries(t).sort((([e],[t])=>e.localeCompare(t))).forEach((([e,t])=>{null!=t&&i.set(e,String(t))})),i.toString()}(h[1]||"",l);return h[0]+"?"+u}function ty(e,t){return e.filter((e=>t.includes(e))).length===e.length}function iy(e){return Object.fromEntries(e.entries())}function sy(e){return new Map(Object.entries(e))}function ry(e=m.FIVE_MINUTES,t){const i=m.toMiliseconds(e||m.FIVE_MINUTES);let s,r,n,o;return{resolve:e=>{n&&s&&(clearTimeout(n),s(e),o=Promise.resolve(e))},reject:e=>{n&&r&&(clearTimeout(n),r(e))},done:()=>new Promise(((e,a)=>{if(o)return e(o);n=setTimeout((()=>{const e=zg("EXPIRED"),i=new Error(t||e.message);i.code=e.code,a(i)}),i),s=e,r=a}))}}function ny(e,t,i){return new Promise((async(s,r)=>{const n=setTimeout((()=>r(new Error(i))),t);try{s(await e)}catch(e){r(e)}clearTimeout(n)}))}function oy(e,t){if("string"==typeof t&&t.startsWith(`${e}:`))return t;if("topic"===e.toLowerCase()){if("string"!=typeof t)throw new Error('Value must be "string" for expirer target type: topic');return`topic:${t}`}if("id"===e.toLowerCase()){if("number"!=typeof t)throw new Error('Value must be "number" for expirer target type: id');return`id:${t}`}throw new Error(`Unknown expirer target type: ${e}`)}function ay(e){const[t,i]=e.split(":"),s={id:void 0,topic:void 0};if("topic"===t&&"string"==typeof i)s.topic=i;else{if("id"!==t||!Number.isInteger(Number(i)))throw new Error(`Invalid target, expected id:number or topic:string, got ${t}:${i}`);s.id=Number(i)}return s}function cy(e,t){return m.fromMiliseconds((t||Date.now())+m.toMiliseconds(e))}function hy(e){return Date.now()>=m.toMiliseconds(e)}function ly(e,t){return`${e}${t?`:${t}`:""}`}function uy(e=[],t=[]){return[...new Set([...e,...t])]}async function dy({id:e,topic:t,wcDeepLink:i}){try{if(!i)return;const s=("string"==typeof i?JSON.parse(i):i)?.href;if("string"!=typeof s)return;const r=function(e,t,i){const s=`requestId=${t}&sessionTopic=${i}`;e.endsWith("/")&&(e=e.slice(0,-1));let r=`${e}`;if(e.startsWith("https://t.me")){r=`${r}${e.includes("?")?"&startapp=":"?startapp="}${function(e,t=!1){const i=(new TextEncoder).encode(e),s=new Array(i.length);for(let e=0;e<i.length;e++)s[e]=String.fromCharCode(i[e]);const r=btoa(s.join(""));return t?r.replace(/[=]/g,""):r}(s,!0)}`}else r=`${r}/wc?${s}`;return r}(s,e,t),n=Zg();if(n===Vg.browser){if(!z()?.hasFocus())return void console.warn("Document does not have focus, skipping deeplink.");!function(e){let t="_self";!function(){try{return window.self!==window.top}catch{return!1}}()?(typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)||e.startsWith("https://")||e.startsWith("http://"))&&(t="_blank"):t="_top",window.open(e,t,"noreferrer noopener")}(r)}else n===Vg.reactNative&&typeof global?.Linking<"u"&&await global.Linking.openURL(r)}catch(e){console.error(e)}}function fy(e,t){if(!e.includes(t))return null;const i=e.split(/([&,?,=])/),s=i.indexOf(t);return i[s+2]}function py(){return typeof crypto<"u"&&crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function gy(){return typeof process<"u"&&"true"===process.env.IS_VITEST}function yy(e){const t=e+"=".repeat((4-e.length%4)%4),i=atob(t),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return(new TextDecoder).decode(s)}class wy{constructor({limit:e}){this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const e=this.set.values().next().value;e&&this.set.delete(e)}this.set.add(e)}}has(e){return this.set.has(e)}}const my="https://rpc.walletconnect.org/v1";function by(e){const t=e+"=".repeat((4-e.length%4)%4),i=atob(t),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return s}const vy=/^0x[0-9a-fA-F]{64}$/;function Ey(e){const t=`Ethereum Signed Message:\n${e.length}`,i=(new TextEncoder).encode(t+e);return"0x"+Da(tt(i),"base16")}async function xy(e,t,i,s,r,n){switch(i.t){case"eip191":return await function(e,t,i){const s=hr(i);return fr({payload:Ey(t),signature:s}).toLowerCase()===e.toLowerCase()}(e,t,i.s);case"eip1271":return await async function(e,t,i,s,r,n){const o=qg(s);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${s}`);try{const o="0x1626ba7e",a="0000000000000000000000000000000000000000000000000000000000000040",c=i.substring(2),h=(c.length/2).toString(16).padStart(64,"0"),l=(function(e){return vy.test(e)}(t)?t:Ey(t)).substring(2),u=o+l+a+h+c,d=await fetch(`${n||my}/?chainId=${s}&projectId=${r}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Iy(),jsonrpc:"2.0",method:"eth_call",params:[{to:e,data:u},"latest"]})}),{result:f}=await d.json();return!!f&&f.slice(0,o.length).toLowerCase()===o.toLowerCase()}catch(e){return console.error("isValidEip1271Signature: ",e),!1}}(e,t,i.s,s,r,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${i.t}`)}}function Iy(){return Date.now()+Math.floor(1e3*Math.random())}function Sy(e){const t=by(e),i=(new TextEncoder).encode("TransactionData::"),s=new Uint8Array(i.length+t.length);s.set(i),s.set(t,i.length);const r=rn(s,{dkLen:32});return ro.encode(r)}function Oy(e){const t=new Uint8Array(Hr(function(e){if(e instanceof Uint8Array)return e;if(Array.isArray(e))return new Uint8Array(e);if("object"==typeof e&&e?.data)return new Uint8Array(Object.values(e.data));if("object"==typeof e&&e)return new Uint8Array(Object.values(e));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}(e)));return ro.encode(t)}function _y(e){const t=Un(by(e)).txn;if(!t)throw new Error("Invalid signed transaction: missing 'txn' field");const i=xn(t),s=fo([(new TextEncoder).encode("TX"),new Uint8Array(i)]),r=Yr(s);return to.encode(r).replace(/=+$/,"")}function Ay(e){const t=[];let i=BigInt(e);for(;i>=0x80n;)t.push(Number(0x7fn&i|0x80n)),i>>=7n;return t.push(Number(i)),new Uint8Array(t)}function Py(e){const t=by(e.signed.bodyBytes),i=by(e.signed.authInfoBytes),s=by(e.signature.signature),r=[];r.push(new Uint8Array([10])),r.push(Ay(t.length)),r.push(t),r.push(new Uint8Array([18])),r.push(Ay(i.length)),r.push(i),r.push(new Uint8Array([26])),r.push(Ay(s.length)),r.push(s);const n=fo(r);return Da(Hr(n),"base16").toUpperCase()}const Ty={pubnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"},By=72,Ry=64,Ny=20;function Cy(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,!1)}function Uy(e,t){const i=by(e);if(i.length<8)throw new Error("getStellarTransactionHash: envelope too short");const s=Cy(i,0);let r,n;switch(s){case 0:r=2,n=0;break;case 2:r=2,n=4;break;case 5:r=5,n=4;break;default:throw new Error(`getStellarTransactionHash: unsupported envelope type: ${s}`)}const o=function(e){for(let t=Ny;t>=0;t--){const i=e.length-4-By*t;if(i<4||Cy(e,i)!==t)continue;let s=!0;for(let r=0;r<t;r++)if(Cy(e,i+4+By*r+4)!==Ry){s=!1;break}if(s)return i}throw new Error("getStellarTransactionHash: could not locate envelope signature array")}(i),a=t?.split(":").pop()??"pubnet",c=Ty[a];if(!c)throw new Error(`getStellarTransactionHash: unknown Stellar network: ${a}`);const h=fo([Hr((new TextEncoder).encode(c)),new Uint8Array([0,0,0,r]),i.slice(n,o)]);return Da(Hr(h),"base16")}const ky="did:pkh:",Ly={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},qy=e=>e?.split(":"),Dy=e=>{const t=e&&qy(e);if(t)return t[2]+":"+t[3]},My=e=>{const t=e&&qy(e);if(t)return t.pop()};async function $y(e){const{cacao:t,projectId:i}=e,{s:s,p:r}=t;let n;try{n=jy(r,r.iss)}catch{return!1}const o=My(r.iss);return await xy(o,n,s,Dy(r.iss),i)}const jy=(e,t)=>{const i=(e=>{const t=e&&qy(e);if(t)return e.includes(ky)?t[2]:t[0]})(t);if(!i)throw new Error("Invalid issuer: "+t);const s=`${e.domain} wants you to sign in with your ${(e=>e?Ly[e]||e:"")(i)} account:`,r=My(t);if(!e.aud&&!e.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let n=e.statement||void 0;const o=`URI: ${e.aud||e.uri}`,a=`Version: ${e.version}`,c=`Chain ID: ${(e=>{const t=e&&qy(e);if(t)return e.includes(ky)?t[3]:t[1]})(t)}`,h=`Nonce: ${e.nonce}`,l=`Issued At: ${e.iat}`,u=e.exp?`Expiration Time: ${e.exp}`:void 0,d=e.nbf?`Not Before: ${e.nbf}`:void 0,f=e.requestId?`Request ID: ${e.requestId}`:void 0,p=e.resources?`Resources:${e.resources.map((e=>`\n- ${e}`)).join("")}`:void 0,g=Zy(e.resources);if(g){n=function(e="",t){zy(t);const i="I further authorize the stated URI to perform the following actions on my behalf: ";if(e.includes(i))return e;const s=[];let r=0;Object.keys(t.att).forEach((e=>{const i=Object.keys(t.att[e]).map((e=>({ability:e.split("/")[0],action:e.split("/")[1]})));i.sort(((e,t)=>e.action.localeCompare(t.action)));const n={};i.forEach((e=>{n[e.ability]||(n[e.ability]=[]),n[e.ability].push(e.action)}));const o=Object.keys(n).map((t=>(r++,`(${r}) '${t}': '${n[t].join("', '")}' for '${e}'.`)));s.push(o.join(", ").replace(".,","."))}));const n=s.join(" "),o=`${i}${n}`;return`${e?e+" ":""}${o}`}(n,Vy(g))}if(n&&/\r|\n/.test(n))throw new Error("Statement must not contain line breaks (`\\r` or `\\n`)");return[s,r,"",n,"",o,a,c,h,l,u,d,f,p].filter((e=>null!=e)).join("\n")};function zy(e){if(!e)throw new Error("No recap provided, value is undefined");if(!e.att)throw new Error("No `att` property found");const t=Object.keys(e.att);if(!t?.length)throw new Error("No resources found in `att` property");t.forEach((t=>{const i=e.att[t];if(Array.isArray(i))throw new Error(`Resource must be an object: ${t}`);if("object"!=typeof i)throw new Error(`Resource must be an object: ${t}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${t}`);Object.keys(i).forEach((e=>{const t=i[e];if(!Array.isArray(t))throw new Error(`Ability limits ${e} must be an array of objects, found: ${t}`);if(!t.length)throw new Error(`Value of ${e} is empty array, must be an array with objects`);t.forEach((t=>{if("object"!=typeof t)throw new Error(`Ability limits (${e}) must be an array of objects, found: ${t}`)}))}))}))}function Fy(e,t,i={}){t=t?.sort(((e,t)=>e.localeCompare(t)));const s=t.map((t=>({[`${e}/${t}`]:[i]})));return Object.assign({},...s)}function Ky(e){return zy(e),`urn:recap:${function(e){const t=JSON.stringify(e),i=(new TextEncoder).encode(t),s=new Array(i.length);for(let e=0;e<i.length;e++)s[e]=String.fromCharCode(i[e]);return btoa(s.join(""))}(e).replace(/=/g,"")}`}function Vy(e){const t=function(e){const t=e+"=".repeat((4-e.length%4)%4),i=atob(t),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return JSON.parse((new TextDecoder).decode(s))}(e.replace("urn:recap:",""));return zy(t),t}function Hy(e,t,i){const s=function(e,t,i,s={}){return i?.sort(((e,t)=>e.localeCompare(t))),{att:{[e]:Fy(t,i,s)}}}(e,t,i);return Ky(s)}function Wy(e,t){const i=function(e,t){zy(e),zy(t);const i=Object.keys(e.att).concat(Object.keys(t.att)).sort(((e,t)=>e.localeCompare(t))),s={att:{}};return i.forEach((i=>{Object.keys(e.att?.[i]||{}).concat(Object.keys(t.att?.[i]||{})).sort(((e,t)=>e.localeCompare(t))).forEach((r=>{s.att[i]={...s.att[i],[r]:e.att[i]?.[r]||t.att[i]?.[r]}}))})),s}(Vy(e),Vy(t));return Ky(i)}function Gy(e){const t=Vy(e);zy(t);const i=t.att?.eip155;return i?Object.keys(i).map((e=>e.split("/")[1])):[]}function Yy(e){const t=Vy(e);zy(t);const i=[];return Object.values(t.att).forEach((e=>{Object.values(e).forEach((e=>{e?.[0]?.chains&&i.push(e[0].chains)}))})),[...new Set(i.flat())]}function Zy(e){if(!e)return;const t=e?.[e.length-1];return function(e){return e&&e.includes("urn:recap:")}(t)?t:void 0}const Xy="base10",Jy="base16",Qy="base64pad",ew="base64url",tw="utf8",iw=0,sw=1,rw=2,nw=0,ow=1,aw=12,cw=32;function hw(){return Da(Me(cw),Jy)}function lw(e){return Da(fc(qa(e,Jy)),Jy)}function uw(e){return Da(fc(qa(e,tw)),Jy)}function dw(e){return qa(`${e}`,Xy)}function fw(e){return Number(Da(e,Xy))}function pw(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function gw(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4;return t+"=".repeat(i)}function yw(e){if(fw(e.type)===rw)return Da(fo([e.type,e.sealed]),Qy);if(fw(e.type)===sw){if(typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Da(fo([e.type,e.senderPublicKey,e.iv,e.sealed]),Qy)}return Da(fo([e.type,e.iv,e.sealed]),Qy)}function ww(e){const t=qa((e.encoding||Qy)===ew?gw(e.encoded):e.encoded,Qy),i=t.slice(nw,ow),s=ow;if(fw(i)===sw){const e=s+cw,r=e+aw,n=t.slice(s,e),o=t.slice(e,r);return{type:i,sealed:t.slice(r),iv:o,senderPublicKey:n}}if(fw(i)===rw){return{type:i,sealed:t.slice(s),iv:Me(aw)}}const r=s+aw,n=t.slice(s,r);return{type:i,sealed:t.slice(r),iv:n}}function mw(e){const t=e?.type||iw;if(t===sw){if(typeof e?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof e?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:t,senderPublicKey:e?.senderPublicKey,receiverPublicKey:e?.receiverPublicKey}}function bw(e){return e.type===sw&&"string"==typeof e.senderPublicKey&&"string"==typeof e.receiverPublicKey}function vw(e){return e.type===rw}function Ew(e,t){const[i,s,r]=e.split("."),n=qa(gw(r),Qy);if(64!==n.length)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=fc(`${i}.${s}`),h=function(e){const t=qa(gw(e.x),Qy),i=qa(gw(e.y),Qy);return fo([new Uint8Array([4]),t,i])}(t);if(!Bl.verify(fo([o,a]),c,h))throw new Error("Invalid signature");return ip(e).payload}function xw(e){return e?.relay||{protocol:"irn"}}function Iw(e){const t=np[e];if(typeof t>"u")throw new Error(`Relay Protocol not supported: ${e}`);return t}function Sw(e,t="-"){const i={},s="relay"+t;return Object.keys(e).forEach((t=>{if(t.startsWith(s)){const r=t.replace(s,""),n=e[t];i[r]=n}})),i}function Ow(e){if(!e.includes("wc:")){const t=yy(e);t?.includes("wc:")&&(e=t)}const t=(e=(e=e.includes("wc://")?e.replace("wc://",""):e).includes("wc:")?e.replace("wc:",""):e).indexOf(":"),i=-1!==e.indexOf("?")?e.indexOf("?"):void 0,s=e.substring(0,t),r=e.substring(t+1,i).split("@"),n=typeof i<"u"?e.substring(i):"",o=new URLSearchParams(n),a=Object.fromEntries(o.entries()),c="string"==typeof a.methods?a.methods.split(","):void 0;return{protocol:s,topic:_w(r[0]),version:parseInt(r[1],10),symKey:a.symKey,relay:Sw(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function _w(e){return e.startsWith("//")?e.substring(2):e}function Aw(e,t="-"){const i={};return Object.keys(e).forEach((s=>{const r=s,n="relay"+t+r;e[r]&&(i[n]=e[r])})),i}function Pw(e){const t=new URLSearchParams,i={...Aw(e.relay),symKey:e.symKey,...e.expiryTimestamp&&{expiryTimestamp:e.expiryTimestamp.toString()},...e.methods&&{methods:e.methods.join(",")}};return Object.entries(i).sort((([e],[t])=>e.localeCompare(t))).forEach((([e,i])=>{void 0!==i&&t.append(e,String(i))})),`${e.protocol}:${e.topic}@${e.version}?${t}`}function Tw(e,t,i){return`${e}?wc_ev=${i}&topic=${t}`}function Bw(e){const t=[];return e.forEach((e=>{const[i,s]=e.split(":");t.push(`${i}:${s}`)})),t}function Rw(e){const t=[];return Object.values(e).forEach((e=>{t.push(...Bw(e.accounts))})),[...new Set(t)]}function Nw(e){return e.includes(":")}function Cw(e){return Nw(e)?e.split(":")[0]:e}function Uw(e){const t={};if(!qw(e))return t;for(const[i,s]of Object.entries(e)){const e=Nw(i)?[i]:s.chains,r=s.methods||[],n=s.events||[],o=Cw(i);t[o]={...t[o],chains:uy(e,t[o]?.chains),methods:uy(r,t[o]?.methods),events:uy(n,t[o]?.events)}}return t}function kw(e,t){t=t.map((e=>e.replace("did:pkh:","")));const i=function(e){const t={};return e?.forEach((e=>{const[i,s]=e.split(":");t[i]||(t[i]={accounts:[],chains:[],events:[],methods:[]}),t[i].accounts.push(e),t[i].chains?.push(`${i}:${s}`)})),t}(t);for(const[t,s]of Object.entries(i))s.methods?s.methods=uy(s.methods,e):s.methods=e,s.events=["chainChanged","accountsChanged"];return i}function Lw(e,t){return!!Array.isArray(e)&&(!(typeof t<"u"&&e.length)||e.every(t))}function qw(e){return Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length}function Dw(e){return typeof e>"u"}function Mw(e,t){return!(!t||!Dw(e))||"string"==typeof e&&!!e.trim().length}function $w(e,t){return!(!t||!Dw(e))||"number"==typeof e&&!isNaN(e)}function jw(e){return!(!Mw(e,!1)||!e.includes(":"))&&2===e.split(":").length}function zw(e){let t=!0;return Lw(e)?e.length&&(t=e.every((e=>Mw(e,!1)))):t=!1,t}function Fw(e,t,i){let s=null;return Object.entries(e).forEach((([e,r])=>{if(s)return;const n=function(e,t,i){let s=null;return Lw(t)&&t.length?t.forEach((e=>{s||jw(e)||(s=Fg("UNSUPPORTED_CHAINS",`${i}, chain ${e} should be a string and conform to "namespace:chainId" format`))})):jw(e)||(s=Fg("UNSUPPORTED_CHAINS",`${i}, 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"] }`)),s}(e,Mg(e,r),`${t} ${i}`);n&&(s=n)})),s}function Kw(e,t){let i=null;return Lw(e)?e.forEach((e=>{i||function(e){if(Mw(e,!1)&&e.includes(":")){const t=e.split(":");if(3===t.length){const e=t[0]+":"+t[1];return!!t[2]&&jw(e)}}return!1}(e)||(i=Fg("UNSUPPORTED_ACCOUNTS",`${t}, account ${e} should be a string and conform to "namespace:chainId:address" format`))})):i=Fg("UNSUPPORTED_ACCOUNTS",`${t}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),i}function Vw(e,t){let i=null;return Object.values(e).forEach((e=>{if(i)return;const s=function(e,t){let i=null;return zw(e?.methods)?zw(e?.events)||(i=Fg("UNSUPPORTED_EVENTS",`${t}, events should be an array of strings or empty array for no events`)):i=Fg("UNSUPPORTED_METHODS",`${t}, methods should be an array of strings or empty array for no methods`),i}(e,`${t}, namespace`);s&&(i=s)})),i}function Hw(e,t){let i=null;if(e&&qw(e)){const s=Vw(e,t);s&&(i=s);const r=function(e,t){let i=null;return Object.values(e).forEach((e=>{if(i)return;const s=Kw(e?.accounts,`${t} namespace`);s&&(i=s)})),i}(e,t);r&&(i=r)}else i=zg("MISSING_OR_INVALID",`${t}, namespaces should be an object with data`);return i}function Ww(e){return Mw(e.protocol,!0)}function Gw(e){return typeof e<"u"&&null!==typeof e}function Yw(e,t){return!(!jw(t)||!Rw(e).includes(t))}function Zw(e,t,i){return!!Mw(i,!1)&&function(e,t){const i=[];return Object.values(e).forEach((e=>{Bw(e.accounts).includes(t)&&i.push(...e.methods)})),i}(e,t).includes(i)}function Xw(e,t,i){return!!Mw(i,!1)&&function(e,t){const i=[];return Object.values(e).forEach((e=>{Bw(e.accounts).includes(t)&&i.push(...e.events)})),i}(e,t).includes(i)}function Jw(e,t,i){let s=null;const r=function(e){const t={};return Object.keys(e).forEach((i=>{i.includes(":")?t[i]=e[i]:e[i].chains?.forEach((s=>{t[s]={methods:e[i].methods,events:e[i].events}}))})),t}(e),n=function(e){const t={};return Object.keys(e).forEach((i=>{i.includes(":")?t[i]=e[i]:Bw(e[i].accounts)?.forEach((s=>{t[s]={accounts:e[i].accounts.filter((e=>e.includes(`${s}:`))),methods:e[i].methods,events:e[i].events}}))})),t}(t),o=Object.keys(r),a=Object.keys(n),c=Qw(Object.keys(e)),h=Qw(Object.keys(t)),l=c.filter((e=>!h.includes(e)));return l.length&&(s=zg("NON_CONFORMING_NAMESPACES",`${i} namespaces keys don't satisfy requiredNamespaces.\n Required: ${l.toString()}\n Received: ${Object.keys(t).toString()}`)),ty(o,a)||(s=zg("NON_CONFORMING_NAMESPACES",`${i} namespaces chains don't satisfy required namespaces.\n Required: ${o.toString()}\n Approved: ${a.toString()}`)),Object.keys(t).forEach((e=>{if(!e.includes(":")||s)return;const r=Bw(t[e].accounts);r.includes(e)||(s=zg("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${e}\n Required: ${e}\n Approved: ${r.toString()}`))})),o.forEach((e=>{s||(ty(r[e].methods,n[e].methods)?ty(r[e].events,n[e].events)||(s=zg("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${e}`)):s=zg("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${e}`))})),s}function Qw(e){return[...new Set(e.map((e=>e.includes(":")?e.split(":")[0]:e)))]}function em(){const e=Zg();return new Promise((t=>{switch(e){case Vg.browser:t(Yg()&&navigator?.onLine);break;case Vg.reactNative:t(async function(){return!(Gg()&&typeof global<"u"&&global?.NetInfo)||(await(global?.NetInfo.fetch()))?.isConnected}());break;case Vg.node:default:t(!0)}}))}function tm(e){switch(Zg()){case Vg.browser:!function(e){!Gg()&&Yg()&&(window.addEventListener("online",(()=>e(!0))),window.addEventListener("offline",(()=>e(!1))))}(e);break;case Vg.reactNative:!function(e){Gg()&&typeof global<"u"&&global?.NetInfo&&global?.NetInfo.addEventListener((t=>e(t?.isConnected)))}(e)}}const im={};class sm{static get(e){return im[e]}static set(e,t){im[e]=t}static delete(e){delete im[e]}}function rm({publicKey:e,signature:t,payload:i}){const s=nm(i.method),r=128|parseInt(i.version?.toString()||"4"),n=function(e){const t=ro.decode(e)[0];return 42===t?0:60===t?2:1}(i.address),o="00"===i.era?new Uint8Array([0]):nm(i.era);if(1!==o.length&&2!==o.length)throw new Error("Invalid era length");const a=parseInt(i.nonce,16),c=new Uint8Array([255&a,a>>8&255]),h=BigInt(`0x${function(e){return e.startsWith("0x")?e.slice(2):e}(i.tip)}`),l=function(e){if(e<1n<<6n)return new Uint8Array([Number(e<<2n)]);if(e<1n<<14n){const t=e<<2n|0x01n;return new Uint8Array([Number(0xffn&t),Number(t>>8n&0xffn)])}if(e<1n<<30n){const t=e<<2n|0x02n;return new Uint8Array([Number(0xffn&t),Number(t>>8n&0xffn),Number(t>>16n&0xffn),Number(t>>24n&0xffn)])}throw new Error("BigInt compact encoding not supported > 2^30")}(h),u=new Uint8Array([0,...e,n,...t,...o,...c,...l,...s]),d=function(e){if(e<64)return new Uint8Array([e<<2]);if(e<16384){const t=e<<2|1;return new Uint8Array([255&t,t>>8&255])}if(e<1<<30){const t=e<<2|2;return new Uint8Array([255&t,t>>8&255,t>>16&255,t>>24&255])}throw new Error("Compact encoding > 2^30 not supported")}(u.length+1);return new Uint8Array([...d,r,...u])}function nm(e){return new Uint8Array(e.replace(/^0x/,"").match(/.{1,2}/g).map((e=>parseInt(e,16))))}function om(e){const t=nm(e.signature),i=function(e){const t=ro.decode(e);if(t.length<33)throw new Error("Too short to contain a public key");return t.slice(1,33)}(e.transaction.address);return function(e){const t=nm(e);return"0x"+Da(Dp.blake2b(t,void 0,32),"base16")}(Da(rm({publicKey:i,signature:t,payload:e.transaction}),"base16"))}const am=new Set(["TransferFactory_Transfer","DelegateProxy_TransferFactory_Transfer"]);function cm(e,t){const i=t?.payload?.updateId;if(!i)return[];const s=function(e){const t=e?.commands;if(!Array.isArray(t))return[];const i=[];for(const e of t){const t=e?.ExerciseCommand;if(!t||!am.has(t.choice))continue;const s=t.choiceArgument?.transfer;!s?.amount||!s?.instrumentId?.id||i.push({amount:String(s.amount),instrumentId:String(s.instrumentId.id)})}return i}(e);return 0===s.length?[String(i)]:s.map((e=>`${i}:${e.amount}:${e.instrumentId}`))}function hm({logger:e,name:t}){const i="string"==typeof e?kg({opts:{level:e,name:t}}).logger:e;return i.level="string"==typeof e?e:e.level,i}class lm{}class um extends lm{constructor(e){super()}}const dm=m.FIVE_SECONDS,fm="heartbeat_pulse";class pm extends um{constructor(e){super(e),this.events=new t,this.interval=dm,this.interval=e?.interval||dm}static async init(e){const t=new pm(e);return await t.init(),t}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async initialize(){this.intervalRef=setInterval((()=>this.pulse()),m.toMiliseconds(this.interval))}pulse(){this.events.emit(fm)}}const gm=/"(?:_|\\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*:/,ym=/"(?: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*:/,wm=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function mm(e,t){if(!("__proto__"===e||"constructor"===e&&t&&"object"==typeof t&&"prototype"in t))return t;!function(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`)}(e)}function bm(e,t={}){if("string"!=typeof e)return e;const i=e.trim();if('"'===e[0]&&e.endsWith('"')&&!e.includes("\\"))return i.slice(1,-1);if(i.length<=9){const e=i.toLowerCase();if("true"===e)return!0;if("false"===e)return!1;if("undefined"===e)return;if("null"===e)return null;if("nan"===e)return Number.NaN;if("infinity"===e)return Number.POSITIVE_INFINITY;if("-infinity"===e)return Number.NEGATIVE_INFINITY}if(!wm.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(gm.test(e)||ym.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,mm)}return JSON.parse(e)}catch(i){if(t.strict)throw i;return e}}function vm(e,...t){try{return(i=e(...t))&&"function"==typeof i.then?i:Promise.resolve(i)}catch(e){return Promise.reject(e)}var i}function Em(e){if(function(e){const t=typeof e;return null===e||"object"!==t&&"function"!==t}(e))return String(e);if(function(e){const t=Object.getPrototypeOf(e);return!t||t.isPrototypeOf(Object)}(e)||Array.isArray(e))return JSON.stringify(e);if("function"==typeof e.toJSON)return Em(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function xm(){if(void 0===typeof Buffer)throw new TypeError("[unstorage] Buffer is not supported!")}const Im="base64:";function Sm(e){return e?e.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function Om(...e){return Sm(e.join(":"))}function _m(e){return(e=Sm(e))?e+":":""}const Am=()=>{const e=new Map;return{name:"memory",options:{},hasItem:t=>e.has(t),getItem:t=>e.get(t)??null,getItemRaw:t=>e.get(t)??null,setItem(t,i){e.set(t,i)},setItemRaw(t,i){e.set(t,i)},removeItem(t){e.delete(t)},getKeys:()=>Array.from(e.keys()),clear(){e.clear()},dispose(){e.clear()}}};function Pm(e={}){const t={mounts:{"":e.driver||Am()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},i=e=>{for(const i of t.mountpoints)if(e.startsWith(i))return{base:i,relativeKey:e.slice(i.length),driver:t.mounts[i]};return{base:"",relativeKey:e,driver:t.mounts[""]}},s=(e,i)=>t.mountpoints.filter((t=>t.startsWith(e)||i&&e.startsWith(t))).map((i=>({relativeBase:e.length>i.length?e.slice(i.length):void 0,mountpoint:i,driver:t.mounts[i]}))),r=(e,i)=>{if(t.watching){i=Sm(i);for(const s of t.watchListeners)s(e,i)}},n=async()=>{if(t.watching){for(const e in t.unwatch)await t.unwatch[e]();t.unwatch={},t.watching=!1}},o=(e,t,s)=>{const r=new Map,n=e=>{let t=r.get(e.base);return t||(t={driver:e.driver,base:e.base,items:[]},r.set(e.base,t)),t};for(const s of e){const e="string"==typeof s,r=Sm(e?s:s.key),o=e?void 0:s.value,a=e||!s.options?t:{...t,...s.options},c=i(r);n(c).items.push({key:r,value:o,relativeKey:c.relativeKey,options:a})}return Promise.all([...r.values()].map((e=>s(e)))).then((e=>e.flat()))},a={hasItem(e,t={}){e=Sm(e);const{relativeKey:s,driver:r}=i(e);return vm(r.hasItem,s,t)},getItem(e,t={}){e=Sm(e);const{relativeKey:s,driver:r}=i(e);return vm(r.getItem,s,t).then((e=>bm(e)))},getItems:(e,t)=>o(e,t,(e=>e.driver.getItems?vm(e.driver.getItems,e.items.map((e=>({key:e.relativeKey,options:e.options}))),t).then((t=>t.map((t=>({key:Om(e.base,t.key),value:bm(t.value)}))))):Promise.all(e.items.map((t=>vm(e.driver.getItem,t.relativeKey,t.options).then((e=>({key:t.key,value:bm(e)})))))))),getItemRaw(e,t={}){e=Sm(e);const{relativeKey:s,driver:r}=i(e);return r.getItemRaw?vm(r.getItemRaw,s,t):vm(r.getItem,s,t).then((e=>function(e){return"string"!=typeof e?e:e.startsWith(Im)?(xm(),Buffer.from(e.slice(Im.length),"base64")):e}(e)))},async setItem(e,t,s={}){if(void 0===t)return a.removeItem(e);e=Sm(e);const{relativeKey:n,driver:o}=i(e);o.setItem&&(await vm(o.setItem,n,Em(t),s),o.watch||r("update",e))},async setItems(e,t){await o(e,t,(async e=>{e.driver.setItems&&await vm(e.driver.setItems,e.items.map((e=>({key:e.relativeKey,value:Em(e.value),options:e.options}))),t),e.driver.setItem&&await Promise.all(e.items.map((t=>vm(e.driver.setItem,t.relativeKey,Em(t.value),t.options))))}))},async setItemRaw(e,t,s={}){if(void 0===t)return a.removeItem(e,s);e=Sm(e);const{relativeKey:n,driver:o}=i(e);if(o.setItemRaw)await vm(o.setItemRaw,n,t,s);else{if(!o.setItem)return;await vm(o.setItem,n,function(e){if("string"==typeof e)return e;xm();const t=Buffer.from(e).toString("base64");return Im+t}(t),s)}o.watch||r("update",e)},async removeItem(e,t={}){"boolean"==typeof t&&(t={removeMeta:t}),e=Sm(e);const{relativeKey:s,driver:n}=i(e);n.removeItem&&(await vm(n.removeItem,s,t),(t.removeMeta||t.removeMata)&&await vm(n.removeItem,s+"$",t),n.watch||r("remove",e))},async getMeta(e,t={}){"boolean"==typeof t&&(t={nativeOnly:t}),e=Sm(e);const{relativeKey:s,driver:r}=i(e),n=Object.create(null);if(r.getMeta&&Object.assign(n,await vm(r.getMeta,s,t)),!t.nativeOnly){const e=await vm(r.getItem,s+"$",t).then((e=>bm(e)));e&&"object"==typeof e&&("string"==typeof e.atime&&(e.atime=new Date(e.atime)),"string"==typeof e.mtime&&(e.mtime=new Date(e.mtime)),Object.assign(n,e))}return n},setMeta(e,t,i={}){return this.setItem(e+"$",t,i)},removeMeta(e,t={}){return this.removeItem(e+"$",t)},async getKeys(e,t={}){e=_m(e);const i=s(e,!0);let r=[];const n=[];for(const e of i){const i=(await vm(e.driver.getKeys,e.relativeBase,t)).map((t=>e.mountpoint+Sm(t))).filter((e=>!r.some((t=>e.startsWith(t)))));n.push(...i),r=[e.mountpoint,...r.filter((t=>!t.startsWith(e.mountpoint)))]}return e?n.filter((t=>t.startsWith(e)&&!t.endsWith("$"))):n.filter((e=>!e.endsWith("$")))},async clear(e,t={}){e=_m(e),await Promise.all(s(e,!1).map((async e=>{if(e.driver.clear)return vm(e.driver.clear,e.relativeBase,t);if(e.driver.removeItem){const i=await e.driver.getKeys(e.relativeBase||"",t);return Promise.all(i.map((i=>e.driver.removeItem(i,t))))}})))},async dispose(){await Promise.all(Object.values(t.mounts).map((e=>Bm(e))))},watch:async e=>(await(async()=>{if(!t.watching){t.watching=!0;for(const e in t.mounts)t.unwatch[e]=await Tm(t.mounts[e],r,e)}})(),t.watchListeners.push(e),async()=>{t.watchListeners=t.watchListeners.filter((t=>t!==e)),0===t.watchListeners.length&&await n()}),async unwatch(){t.watchListeners=[],await n()},mount(e,i){if((e=_m(e))&&t.mounts[e])throw new Error(`already mounted at ${e}`);return e&&(t.mountpoints.push(e),t.mountpoints.sort(((e,t)=>t.length-e.length))),t.mounts[e]=i,t.watching&&Promise.resolve(Tm(i,r,e)).then((i=>{t.unwatch[e]=i})).catch(console.error),a},async unmount(e,i=!0){(e=_m(e))&&t.mounts[e]&&(t.watching&&e in t.unwatch&&(t.unwatch[e](),delete t.unwatch[e]),i&&await Bm(t.mounts[e]),t.mountpoints=t.mountpoints.filter((t=>t!==e)),delete t.mounts[e])},getMount(e=""){e=Sm(e)+":";const t=i(e);return{driver:t.driver,base:t.base}},getMounts(e="",t={}){e=Sm(e);return s(e,t.parents).map((e=>({driver:e.driver,base:e.mountpoint})))}};return a}function Tm(e,t,i){return e.watch?e.watch(((e,s)=>t(e,i+s))):()=>{}}async function Bm(e){"function"==typeof e.dispose&&await vm(e.dispose)}function Rm(e){return new Promise(((t,i)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>i(e.error)}))}function Nm(e,t){const i=indexedDB.open(e);i.onupgradeneeded=()=>i.result.createObjectStore(t);const s=Rm(i);return(e,i)=>s.then((s=>i(s.transaction(t,e).objectStore(t))))}let Cm;function Um(){return Cm||(Cm=Nm("keyval-store","keyval")),Cm}function km(e,t=Um()){return t("readonly",(t=>Rm(t.get(e))))}function Lm(e=Um()){return e("readonly",(e=>{if(e.getAllKeys)return Rm(e.getAllKeys());const t=[];return function(e,t){return e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},Rm(e.transaction)}(e,(e=>t.push(e.key))).then((()=>t))}))}var qm=(e={})=>{const t=e.base&&e.base.length>0?`${e.base}:`:"",i=e=>t+e;let s;return e.dbName&&e.storeName&&(s=Nm(e.dbName,e.storeName)),{name:"idb-keyval",options:e,hasItem:async e=>!(typeof await km(i(e),s)>"u"),getItem:async e=>await km(i(e),s)??null,setItem:(e,t)=>function(e,t,i=Um()){return i("readwrite",(i=>(i.put(t,e),Rm(i.transaction))))}(i(e),t,s),removeItem:e=>function(e,t=Um()){return t("readwrite",(t=>(t.delete(e),Rm(t.transaction))))}(i(e),s),getKeys:()=>Lm(s),clear:()=>function(e=Um()){return e("readwrite",(e=>(e.clear(),Rm(e.transaction))))}(s)}};class Dm{constructor(){this.indexedDb=Pm({driver:qm({dbName:"WALLET_CONNECT_V2_INDEXED_DB",storeName:"keyvaluestorage"})})}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 t=await this.indexedDb.getItem(e);if(null!==t)return t}async setItem(e,t){await this.indexedDb.setItem(e,Ul(t))}async removeItem(e){await this.indexedDb.removeItem(e)}}var Mm=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$m={exports:{}};function jm(e){var t;return[e[0],Cl(null!=(t=e[1])?t:"")]}!function(){let e;function t(){}e=t,e.prototype.getItem=function(e){return this.hasOwnProperty(e)?String(this[e]):null},e.prototype.setItem=function(e,t){this[e]=String(t)},e.prototype.removeItem=function(e){delete this[e]},e.prototype.clear=function(){const e=this;Object.keys(e).forEach((function(t){e[t]=void 0,delete e[t]}))},e.prototype.key=function(e){return e=e||0,Object.keys(this)[e]},e.prototype.__defineGetter__("length",(function(){return Object.keys(this).length})),typeof Mm<"u"&&Mm.localStorage?$m.exports=Mm.localStorage:typeof window<"u"&&window.localStorage?$m.exports=window.localStorage:$m.exports=new t}();class zm{constructor(){this.localStorage=$m.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(jm)}async getItem(e){const t=this.localStorage.getItem(e);if(null!==t)return Cl(t)}async setItem(e,t){this.localStorage.setItem(e,Ul(t))}async removeItem(e){this.localStorage.removeItem(e)}}const Fm=async(e,t)=>{t.length&&t.forEach((async t=>{await e.removeItem(t)}))};class Km{constructor(){this.initialized=!1,this.setInitialized=e=>{this.storage=e,this.initialized=!0};const e=new zm;this.storage=e;try{(async(e,t,i)=>{const s="wc_storage_version",r=await t.getItem(s);if(r&&r>=1)return void i(t);const n=await e.getKeys();if(!n.length)return void i(t);const o=[];for(;n.length;){const i=n.shift();if(!i)continue;const s=i.toLowerCase();if(s.includes("wc@")||s.includes("walletconnect")||s.includes("wc_")||s.includes("wallet_connect")){const s=await e.getItem(i);await t.setItem(i,s),o.push(i)}}await t.setItem(s,1),i(t),Fm(e,o)})(e,new Dm,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,t){return await this.initialize(),this.storage.setItem(e,t)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise((e=>{const t=setInterval((()=>{this.initialized&&(clearInterval(t),e())}),20)}))}}class Vm extends lm{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class Hm extends lm{constructor(e,t){super(),this.core=e,this.logger=t,this.records=new Map}}class Wm{constructor(e,t){this.logger=e,this.core=t}}class Gm extends lm{constructor(e,t){super(),this.relayer=e,this.logger=t}}class Ym extends lm{constructor(e){super()}}class Zm{constructor(e,t,i,s){this.core=e,this.logger=t,this.name=i}}class Xm extends lm{constructor(e,t){super(),this.relayer=e,this.logger=t}}class Jm extends lm{constructor(e,t){super(),this.core=e,this.logger=t}}class Qm{constructor(e,t,i){this.core=e,this.logger=t,this.store=i}}class eb{constructor(e,t){this.projectId=e,this.logger=t}}class tb{constructor(e,t,i){this.core=e,this.logger=t,this.telemetryEnabled=i}}class ib{constructor(e){this.opts=e,this.protocol="wc",this.version=2}}class sb{constructor(e){this.client=e}}const rb="INTERNAL_ERROR",nb="SERVER_ERROR",ob=[-32700,-32600,-32601,-32602,-32603],ab={PARSE_ERROR:{code:-32700,message:"Parse error"},INVALID_REQUEST:{code:-32600,message:"Invalid Request"},METHOD_NOT_FOUND:{code:-32601,message:"Method not found"},INVALID_PARAMS:{code:-32602,message:"Invalid params"},[rb]:{code:-32603,message:"Internal error"},[nb]:{code:-32e3,message:"Server error"}},cb=nb;function hb(e){return Object.keys(ab).includes(e)?ab[e]:ab[cb]}function lb(e,t,i){return e.message.includes("getaddrinfo ENOTFOUND")||e.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${i} RPC url at ${t}`):e}var ub,db={},fb={};var pb,gb={};function yb(e=3){return Date.now()*Math.pow(10,e)+Math.floor(Math.random()*Math.pow(10,e))}function wb(e=6){return BigInt(yb(e))}function mb(e,t,i){return{id:i||yb(),jsonrpc:"2.0",method:e,params:t}}function bb(e,t){return{id:e,jsonrpc:"2.0",result:t}}function vb(e,t,i){return{id:e,jsonrpc:"2.0",error:Eb(t,i)}}function Eb(e,t){return void 0===e?hb(rb):("string"==typeof e&&(e=Object.assign(Object.assign({},hb(nb)),{message:e})),void 0!==t&&(e.data=t),function(e){return ob.includes(e)}(e.code)&&(e=function(e){const t=Object.values(ab).find((t=>t.code===e));return t||ab[cb]}(e.code)),e)}!function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=i;t.__exportStar(function(){if(ub)return fb;function e(){return(null==s?void 0:s.crypto)||(null==s?void 0:s.msCrypto)||{}}function t(){const t=e();return t.subtle||t.webkitSubtle}return ub=1,Object.defineProperty(fb,"__esModule",{value:!0}),fb.isBrowserCryptoAvailable=fb.getSubtleCrypto=fb.getBrowerCrypto=void 0,fb.getBrowerCrypto=e,fb.getSubtleCrypto=t,fb.isBrowserCryptoAvailable=function(){return!!e()&&!!t()},fb}(),e),t.__exportStar(function(){if(pb)return gb;function e(){return"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product}function t(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node}return pb=1,Object.defineProperty(gb,"__esModule",{value:!0}),gb.isBrowser=gb.isNode=gb.isReactNative=void 0,gb.isReactNative=e,gb.isNode=t,gb.isBrowser=function(){return!e()&&!t()},gb}(),e)}(db);class xb{}class Ib extends xb{constructor(){super()}}class Sb extends Ib{constructor(e){super()}}function Ob(e,t){const i=function(e){const t=e.match(new RegExp(/^\w+:/,"gi"));if(t&&t.length)return t[0]}(e);return void 0!==i&&new RegExp(t).test(i)}function _b(e){return Ob(e,"^https?:")}function Ab(e){return Ob(e,"^wss?:")}function Pb(e){return new RegExp("wss?://localhost(:d{2,5})?").test(e)}function Tb(e){return"object"==typeof e&&"id"in e&&"jsonrpc"in e&&"2.0"===e.jsonrpc}function Bb(e){return Tb(e)&&"method"in e}function Rb(e){return Tb(e)&&(Nb(e)||Cb(e))}function Nb(e){return"result"in e}function Cb(e){return"error"in e}class Ub extends Sb{constructor(e){super(e),this.events=new t,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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async request(e,t){return this.requestStrict(mb(e.method,e.params||[],e.id||wb().toString()),t)}async requestStrict(e,t){return new Promise((async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(e){s(e)}this.events.on(`${e.id}`,(e=>{Cb(e)?s(e.error):i(e.result)}));try{await this.connection.send(e,t)}catch(e){s(e)}}))}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Rb(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&3e3===e.code&&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(),"string"==typeof e&&(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 kb=e=>e.split("?")[0],Lb=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");class qb{constructor(e){if(this.url=e,this.events=new t,this.registering=!1,!Ab(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,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async open(e=this.url){await this.register(e)}async close(){return new Promise(((e,t)=>{typeof this.socket>"u"?t(new Error("Connection already closed")):(this.socket.onclose=t=>{this.onClose(t),e()},this.socket.close())}))}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ul(e))}catch(t){this.onError(e.id,t)}}register(e=this.url){if(!Ab(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise(((e,t)=>{this.events.once("register_error",(e=>{this.resetMaxListeners(),t(e)})),this.events.once("open",(()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return t(new Error("WebSocket connection is missing or invalid"));e(this.socket)}))}))}return this.url=e,this.registering=!0,new Promise(((t,i)=>{const s=db.isReactNative()?void 0:{rejectUnauthorized:!Pb(e)},r=new Lb(e,[],s);typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u"?r.onerror=e=>{const t=e;i(this.emitError(t.error))}:r.on("error",(e=>{i(this.emitError(e))})),r.onopen=()=>{this.onOpen(r),t(r)}}))}onOpen(e){e.onmessage=e=>this.onPayload(e),e.onclose=e=>this.onClose(e),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 t="string"==typeof e.data?Cl(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=vb(e,i.message||i.toString());this.events.emit("payload",s)}parseError(e,t=this.url){return lb(e,kb(t),"WS")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}emitError(e){const t=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${kb(this.url)}`));return this.events.emit("register_error",t),t}}function Db(e){return null!=e&&"function"!=typeof e&&function(e){return Number.isSafeInteger(e)&&e>=0}(e.length)}function Mb(e){return"__proto__"===e}function $b(e){return null==e||"object"!=typeof e&&"function"!=typeof e}function jb(e){return Object.getOwnPropertySymbols(e).filter((t=>Object.prototype.propertyIsEnumerable.call(e,t)))}function zb(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const Fb="[object RegExp]",Kb="[object String]",Vb="[object Number]",Hb="[object Boolean]",Wb="[object Arguments]",Gb="[object Symbol]",Yb="[object Date]",Zb="[object Map]",Xb="[object Set]",Jb="[object Array]",Qb="[object Function]",ev="[object ArrayBuffer]",tv="[object Object]",iv="[object Error]",sv="[object DataView]",rv="[object Uint8Array]",nv="[object Uint8ClampedArray]",ov="[object Uint16Array]",av="[object Uint32Array]",cv="[object BigUint64Array]",hv="[object Int8Array]",lv="[object Int16Array]",uv="[object Int32Array]",dv="[object BigInt64Array]",fv="[object Float32Array]",pv="[object Float64Array]";function gv(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function yv(e,t,i,s=new Map,r=void 0){const n=r?.(e,t,i,s);if(void 0!==n)return n;if($b(e))return e;if(s.has(e))return s.get(e);if(Array.isArray(e)){const t=new Array(e.length);s.set(e,t);for(let n=0;n<e.length;n++)t[n]=yv(e[n],n,i,s,r);return Object.hasOwn(e,"index")&&(t.index=e.index),Object.hasOwn(e,"input")&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){const t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){const t=new Map;s.set(e,t);for(const[n,o]of e)t.set(n,yv(o,n,i,s,r));return t}if(e instanceof Set){const t=new Set;s.set(e,t);for(const n of e)t.add(yv(n,void 0,i,s,r));return t}if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return e.subarray();if(gv(e)){const t=new(Object.getPrototypeOf(e).constructor)(e.length);s.set(e,t);for(let n=0;n<e.length;n++)t[n]=yv(e[n],n,i,s,r);return t}if(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){const t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return s.set(e,t),wv(t,e,i,s,r),t}if("undefined"!=typeof File&&e instanceof File){const t=new File([e],e.name,{type:e.type});return s.set(e,t),wv(t,e,i,s,r),t}if("undefined"!=typeof Blob&&e instanceof Blob){const t=new Blob([e],{type:e.type});return s.set(e,t),wv(t,e,i,s,r),t}if(e instanceof Error){const t=structuredClone(e);return s.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,t.constructor=e.constructor,wv(t,e,i,s,r),t}if(e instanceof Boolean){const t=new Boolean(e.valueOf());return s.set(e,t),wv(t,e,i,s,r),t}if(e instanceof Number){const t=new Number(e.valueOf());return s.set(e,t),wv(t,e,i,s,r),t}if(e instanceof String){const t=new String(e.valueOf());return s.set(e,t),wv(t,e,i,s,r),t}if("object"==typeof e&&function(e){switch(zb(e)){case Wb:case Jb:case ev:case sv:case Hb:case Yb:case fv:case pv:case hv:case lv:case uv:case Zb:case Vb:case tv:case Fb:case Xb:case Kb:case Gb:case rv:case nv:case ov:case av:return!0;default:return!1}}(e)){const t=Object.create(Object.getPrototypeOf(e));return s.set(e,t),wv(t,e,i,s,r),t}return e}function wv(e,t,i=e,s,r){const n=[...Object.keys(t),...jb(t)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(e,a);(null==c||c.writable)&&(e[a]=yv(t[a],a,i,s,r))}}function mv(e,t){return function(e,t){return yv(e,void 0,e,new Map,t)}(e,((i,s,r,n)=>{const o=t?.(i,s,r,n);if(void 0!==o)return o;if("object"==typeof e){if(zb(e)===tv&&"function"!=typeof e.constructor){const t={};return n.set(e,t),wv(t,e,r,n),t}switch(Object.prototype.toString.call(e)){case Vb:case Kb:case Hb:{const t=new e.constructor(e?.valueOf());return wv(t,e),t}case Wb:{const t={};return wv(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}}))}function bv(e){return mv(e)}function vv(e){return null!==e&&"object"==typeof e&&"[object Arguments]"===zb(e)}function Ev(e){return"object"==typeof e&&null!==e}function xv(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t))&&"[object Object]"===Object.prototype.toString.call(e)}function Iv(e,t,i,s,r,n,o){const a=o(e,t,i,s,r,n);if(void 0!==a)return a;if(typeof e==typeof t)switch(typeof e){case"bigint":case"string":case"boolean":case"symbol":case"undefined":case"function":return e===t;case"number":return e===t||Object.is(e,t);case"object":return Sv(e,t,n,o)}return Sv(e,t,n,o)}function Sv(e,t,i,s){if(Object.is(e,t))return!0;let r=zb(e),n=zb(t);if(r===Wb&&(r=tv),n===Wb&&(n=tv),r!==n)return!1;switch(r){case Kb:return e.toString()===t.toString();case Vb:{const i=e.valueOf(),s=t.valueOf();return(o=i)===(a=s)||Number.isNaN(o)&&Number.isNaN(a)}case Hb:case Yb:case Gb:return Object.is(e.valueOf(),t.valueOf());case Fb:return e.source===t.source&&e.flags===t.flags;case Qb:return e===t}var o,a;const c=(i=i??new Map).get(e),h=i.get(t);if(null!=c&&null!=h)return c===t;i.set(e,t),i.set(t,e);try{switch(r){case Zb:if(e.size!==t.size)return!1;for(const[r,n]of e.entries())if(!t.has(r)||!Iv(n,t.get(r),r,e,t,i,s))return!1;return!0;case Xb:{if(e.size!==t.size)return!1;const r=Array.from(e.values()),n=Array.from(t.values());for(let o=0;o<r.length;o++){const a=r[o],c=n.findIndex((r=>Iv(a,r,void 0,e,t,i,s)));if(-1===c)return!1;n.splice(c,1)}return!0}case Jb:case rv:case nv:case ov:case av:case cv:case hv:case lv:case uv:case dv:case fv:case pv:if("undefined"!=typeof Buffer&&Buffer.isBuffer(e)!==Buffer.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Iv(e[r],t[r],r,e,t,i,s))return!1;return!0;case ev:return e.byteLength===t.byteLength&&Sv(new Uint8Array(e),new Uint8Array(t),i,s);case sv:return e.byteLength===t.byteLength&&e.byteOffset===t.byteOffset&&Sv(new Uint8Array(e),new Uint8Array(t),i,s);case iv:return e.name===t.name&&e.message===t.message;case tv:{if(!(Sv(e.constructor,t.constructor,i,s)||xv(e)&&xv(t)))return!1;const r=[...Object.keys(e),...jb(e)],n=[...Object.keys(t),...jb(t)];if(r.length!==n.length)return!1;for(let n=0;n<r.length;n++){const o=r[n],a=e[o];if(!Object.hasOwn(t,o))return!1;if(!Iv(a,t[o],o,e,t,i,s))return!1}return!0}default:return!1}}finally{i.delete(e),i.delete(t)}}function Ov(){}function _v(e,t){return function(e,t,i){return Iv(e,t,void 0,void 0,void 0,void 0,i)}(e,t,Ov)}function Av(e){return gv(e)}function Pv(e){if("object"!=typeof e)return!1;if(null==e)return!1;if(null===Object.getPrototypeOf(e))return!0;if("[object Object]"!==Object.prototype.toString.call(e)){const t=e[Symbol.toStringTag];if(null==t)return!1;return!!Object.getOwnPropertyDescriptor(e,Symbol.toStringTag)?.writable&&e.toString()===`[object ${t}]`}let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Tv(e,t,i,s){if($b(e)&&(e=Object(e)),null==t||"object"!=typeof t)return e;if(s.has(t))return function(e){if($b(e))return e;if(Array.isArray(e)||gv(e)||e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return e.slice(0);const t=Object.getPrototypeOf(e);if(null==t)return Object.assign(Object.create(t),e);const i=t.constructor;if(e instanceof Date||e instanceof Map||e instanceof Set)return new i(e);if(e instanceof RegExp){const t=new i(e);return t.lastIndex=e.lastIndex,t}if(e instanceof DataView)return new i(e.buffer.slice(0));if(e instanceof Error){let t;return t=e instanceof AggregateError?new i(e.errors,e.message,{cause:e.cause}):new i(e.message,{cause:e.cause}),t.stack=e.stack,Object.assign(t,e),t}if("undefined"!=typeof File&&e instanceof File)return new i([e],e.name,{type:e.type,lastModified:e.lastModified});if("object"==typeof e){const i=Object.create(t);return Object.assign(i,e)}return e}(s.get(t));if(s.set(t,e),Array.isArray(t)){t=t.slice();for(let e=0;e<t.length;e++)t[e]=t[e]??void 0}const r=[...Object.keys(t),...jb(t)];for(let o=0;o<r.length;o++){const a=r[o];if(Mb(a))continue;let c=t[a],h=e[a];if(vv(c)&&(c={...c}),vv(h)&&(h={...h}),"undefined"!=typeof Buffer&&Buffer.isBuffer(c)&&(c=bv(c)),Array.isArray(c))if(Array.isArray(h)){const e=[],t=Reflect.ownKeys(h);for(let i=0;i<t.length;i++){const s=t[i];e[s]=h[s]}h=e}else if(Ev(n=h)&&Db(n)){const e=[];for(let t=0;t<h.length;t++)e[t]=h[t];h=e}else h=[];const l=i(h,c,a,e,t,s);void 0!==l?e[a]=l:Array.isArray(c)||Ev(h)&&Ev(c)&&(Pv(h)||Pv(c)||Av(h)||Av(c))?e[a]=Tv(h,c,i,s):null==h&&Pv(c)?e[a]=Tv({},c,i,s):null==h&&Av(c)?e[a]=bv(c):void 0!==h&&void 0===c||(e[a]=c)}var n;return e}function Bv(e,...t){return function(e,...t){const i=t.slice(0,-1),s=t[t.length-1];let r=e;for(let e=0;e<i.length;e++)r=Tv(r,i[e],s,new Map);return r}(e,...t,Ov)}const Rv="core",Nv=`wc@2:${Rv}:`,Cv="error",Uv={database:":memory:"},kv="client_ed25519_seed",Lv=m.ONE_DAY,qv=m.SIX_HOURS,Dv="wss://relay.walletconnect.org",Mv="relayer_message",$v="relayer_message_ack",jv="relayer_connect",zv="relayer_disconnect",Fv="relayer_error",Kv="relayer_connection_stalled",Vv="relayer_publish",Hv="payload",Wv="connect",Gv="disconnect",Yv="error",Zv="2.24.0",Xv={link_mode:"link_mode",relay:"relay"},Jv="inbound",Qv="outbound",eE="WALLETCONNECT_LINK_MODE_APPS",tE="subscription_created",iE="subscription_deleted",sE="subscription_sync",rE="subscription_resubscribed",nE={wc_pairingDelete:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:m.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:m.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:m.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:m.ONE_DAY,prompt:!1,tag:0},res:{ttl:m.ONE_DAY,prompt:!1,tag:0}}},oE="pairing_create",aE="pairing_expire",cE="pairing_delete",hE="pairing_ping",lE="history_created",uE="history_updated",dE="history_deleted",fE="history_sync",pE="expirer_created",gE="expirer_deleted",yE="expirer_expired",wE="expirer_sync",mE="https://verify.walletconnect.org",bE=mE,vE=`${bE}/v3`,EE=["https://verify.walletconnect.com",mE],xE="pairing_started",IE="pairing_uri_validation_success",SE="pairing_uri_not_expired",OE="store_new_pairing",_E="subscribing_pairing_topic",AE="subscribe_pairing_topic_success",PE="existing_pairing",TE="pairing_not_expired",BE="emit_inactive_pairing",RE="emit_session_proposal",NE="no_internet_connection",CE="malformed_pairing_uri",UE="active_pairing_already_exists",kE="subscribe_pairing_topic_failure",LE="pairing_expired",qE="proposal_listener_not_found",DE="session_approve_started",ME="session_namespaces_validation_success",$E="subscribing_session_topic",jE="subscribe_session_topic_success",zE="session_approve_publish_success",FE="store_session",KE="session_request_response_started",VE="session_request_response_validation_success",HE="session_request_response_publish_started",WE="no_internet_connection",GE="proposal_expired",YE="subscribe_session_topic_failure",ZE="session_approve_namespace_validation_failure",XE="proposal_not_found",JE="session_request_response_validation_failure",QE="session_request_response_publish_failure",ex="authenticated_session_approve_started",tx="create_authenticated_session_topic",ix="cacaos_verified",sx="store_authenticated_session",rx="subscribing_authenticated_session_topic",nx="subscribe_authenticated_session_topic_success",ox="publishing_authenticated_session_approve",ax="no_internet_connection",cx="invalid_cacao",hx="subscribe_authenticated_session_topic_failure",lx="authenticated_session_approve_publish_failure",ux="authenticated_session_pending_request_not_found";class dx{constructor(e,t){this.core=e,this.logger=t,this.keychain=new Map,this.name="keychain",this.version="0.3",this.initialized=!1,this.storagePrefix=Nv,this.init=async()=>{if(!this.initialized){const e=await this.getKeyChain();typeof e<"u"&&(this.keychain=e),this.initialized=!0}},this.has=e=>(this.isInitialized(),this.keychain.has(e)),this.set=async(e,t)=>{this.isInitialized(),this.keychain.set(e,t),await this.persist()},this.get=e=>{this.isInitialized();const t=this.keychain.get(e);if(typeof t>"u"){const{message:t}=zg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t},this.del=async e=>{this.isInitialized(),this.keychain.delete(e),await this.persist()},this.core=e,this.logger=Ug(t,this.name)}get context(){return Cg(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,iy(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?sy(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=zg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class fx{constructor(e,t,i){this.core=e,this.logger=t,this.name="crypto",this.randomSessionIdentifier=hw(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=e=>(this.isInitialized(),this.keychain.has(e)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const e=ep(sp(await this.getClientSeed()).publicKey);return this.clientId=e,e},this.generateKeyPair=()=>{this.isInitialized();const e=function(){const e=Wh.utils.randomPrivateKey(),t=Wh.getPublicKey(e);return{privateKey:Da(e,Jy),publicKey:Da(t,Jy)}}();return this.setPrivateKey(e.publicKey,e.privateKey)},this.signJWT=async e=>{this.isInitialized();const t=sp(await this.getClientSeed()),i=this.randomSessionIdentifier,s=Lv;return await rp(i,e,s,t)},this.generateSharedKey=(e,t,i)=>{this.isInitialized();const s=function(e,t){const i=Wh.getSharedSecret(qa(e,Jy),qa(t,Jy));return Da(dc(fc,i,void 0,void 0,cw),Jy)}(this.getPrivateKey(e),t);return this.setSymKey(s,i)},this.setSymKey=async(e,t)=>{this.isInitialized();const i=t||lw(e);return await this.keychain.set(i,e),i},this.deleteKeyPair=async e=>{this.isInitialized(),await this.keychain.del(e)},this.deleteSymKey=async e=>{this.isInitialized(),await this.keychain.del(e)},this.encode=async(e,t,i)=>{this.isInitialized();const s=mw(i),r=Ul(t);if(vw(s))return function(e,t){const i=dw(rw),s=Me(aw),r=yw({type:i,sealed:qa(e,tw),iv:s});return t===ew?pw(r):r}(r,i?.encoding);if(bw(s)){const t=s.senderPublicKey,i=s.receiverPublicKey;e=await this.generateSharedKey(t,i)}const n=this.getSymKey(e),{type:o,senderPublicKey:a}=s;return function(e){const t=dw(typeof e.type<"u"?e.type:iw);if(fw(t)===sw&&typeof e.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const i=typeof e.senderPublicKey<"u"?qa(e.senderPublicKey,Jy):void 0,s=typeof e.iv<"u"?qa(e.iv,Jy):Me(aw),r=qa(e.symKey,Jy),n=yw({type:t,sealed:oc(r,s).encrypt(qa(e.message,tw)),iv:s,senderPublicKey:i});return e.encoding===ew?pw(n):n}({type:o,symKey:n,message:r,senderPublicKey:a,encoding:i?.encoding})},this.decode=async(e,t,i)=>{this.isInitialized();const s=function(e,t){const i=ww({encoded:e,encoding:t?.encoding});return mw({type:fw(i.type),senderPublicKey:typeof i.senderPublicKey<"u"?Da(i.senderPublicKey,Jy):void 0,receiverPublicKey:t?.receiverPublicKey})}(t,i);if(vw(s)){const e=function(e,t){const{sealed:i}=ww({encoded:e,encoding:t});return Da(i,tw)}(t,i?.encoding);return Cl(e)}if(bw(s)){const t=s.receiverPublicKey,i=s.senderPublicKey;e=await this.generateSharedKey(t,i)}try{const s=function(e){const t=qa(e.symKey,Jy),{sealed:i,iv:s}=ww({encoded:e.encoded,encoding:e.encoding}),r=oc(t,s).decrypt(i);if(null===r)throw new Error("Failed to decrypt");return Da(r,tw)}({symKey:this.getSymKey(e),encoded:t,encoding:i?.encoding});return Cl(s)}catch(t){this.logger.error(`Failed to decode message from topic: '${e}', clientId: '${await this.getClientId()}'`),this.logger.error(t)}},this.getPayloadType=(e,t=Qy)=>fw(ww({encoded:e,encoding:t}).type),this.getPayloadSenderPublicKey=(e,t=Qy)=>{const i=ww({encoded:e,encoding:t});return i.senderPublicKey?Da(i.senderPublicKey,Jy):void 0},this.core=e,this.logger=Ug(t,this.name),this.keychain=i||new dx(this.core,this.logger)}get context(){return Cg(this.logger)}async setPrivateKey(e,t){return await this.keychain.set(e,t),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(kv)}catch{e=hw(),await this.keychain.set(kv,e)}return qa(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=zg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class px extends Wm{constructor(e,t){super(e,t),this.logger=e,this.core=t,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name="messages",this.version="0.3",this.initialized=!1,this.storagePrefix=Nv,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const e=await this.getRelayerMessages();typeof e<"u"&&(this.messages=e);const t=await this.getRelayerMessagesWithoutClientAck();typeof t<"u"&&(this.messagesWithoutClientAck=t),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}finally{this.initialized=!0}}},this.set=async(e,t,i)=>{this.isInitialized();const s=uw(t);let r=this.messages.get(e);if(typeof r>"u"&&(r={}),typeof r[s]<"u")return s;if(r[s]=t,this.messages.set(e,r),i===Jv){const i=this.messagesWithoutClientAck.get(e)||{};this.messagesWithoutClientAck.set(e,{...i,[s]:t})}return await this.persist(),s},this.get=e=>{this.isInitialized();let t=this.messages.get(e);return typeof t>"u"&&(t={}),t},this.getWithoutAck=e=>{this.isInitialized();const t={};for(const i of e){const e=this.messagesWithoutClientAck.get(i)||{};t[i]=Object.values(e)}return t},this.has=(e,t)=>{this.isInitialized();return typeof this.get(e)[uw(t)]<"u"},this.ack=async(e,t)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(e);if(typeof i>"u")return;delete i[uw(t)],0===Object.keys(i).length?this.messagesWithoutClientAck.delete(e):this.messagesWithoutClientAck.set(e,i),await this.persist()},this.del=async e=>{this.isInitialized(),this.messages.delete(e),this.messagesWithoutClientAck.delete(e),await this.persist()},this.logger=Ug(e,this.name),this.core=t}get context(){return Cg(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,iy(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,iy(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?sy(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?sy(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=zg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class gx extends Gm{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,this.events=new t,this.name="publisher",this.queue=new Map,this.publishTimeout=m.toMiliseconds(m.ONE_MINUTE),this.initialPublishTimeout=m.toMiliseconds(15*m.ONE_SECOND),this.needsTransportRestart=!1,this.publish=async(e,t,i)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:e,message:t,opts:i}});const s=i?.ttl||qv,r=i?.prompt||!1,n=i?.tag||0,o=i?.id||wb().toString(),a=Iw(xw().protocol),c={id:o,method:i?.publishMethod||a.publish,params:{topic:e,message:t,ttl:s,prompt:r,tag:n,attestation:i?.attestation,...i?.tvf}},h=`Failed to publish payload, please try again. id:${o} tag:${n}`;try{Dw(c.params?.prompt)&&delete c.params?.prompt,Dw(c.params?.tag)&&delete c.params?.tag;const s=new Promise((async e=>{const t=({id:i})=>{c.id?.toString()===i.toString()&&(this.removeRequestFromQueue(i),this.relayer.events.removeListener(Vv,t),e())};this.relayer.events.on(Vv,t);const s=ny(new Promise(((e,t)=>{this.rpcPublish(c,i).then(e).catch((e=>{this.logger.warn(e,e?.message),t(e)}))})),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${o} tag:${n}`);try{await s,this.events.removeListener(Vv,t)}catch(e){this.queue.set(o,{request:c,opts:i,attempt:1}),this.logger.warn(e,e?.message)}}));this.logger.trace({type:"method",method:"publish",params:{id:o,topic:e,message:t,opts:i}}),await ny(s,this.publishTimeout,h)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),i?.internal?.throwOnFailedPublish)throw e}finally{this.queue.delete(o)}},this.publishCustom=async e=>{this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:e});const{payload:t,opts:i={}}=e,{attestation:s,tvf:r,publishMethod:n,prompt:o,tag:a,ttl:c=m.FIVE_MINUTES}=i,h=i.id||wb().toString(),l=Iw(xw().protocol),u=n||l.publish,d={id:h,method:u,params:{...t,ttl:c,prompt:o,tag:a,attestation:s,...r}},f=`Failed to publish custom payload, please try again. id:${h} tag:${a}`;try{Dw(d.params?.prompt)&&delete d.params?.prompt,Dw(d.params?.tag)&&delete d.params?.tag;const e=new Promise((async e=>{const t=({id:i})=>{d.id?.toString()===i.toString()&&(this.removeRequestFromQueue(i),this.relayer.events.removeListener(Vv,t),e())};this.relayer.events.on(Vv,t);const s=ny(new Promise(((e,t)=>{this.rpcPublish(d,i).then(e).catch((e=>{this.logger.warn(e,e?.message),t(e)}))})),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${u} id:${h} tag:${a}`);try{await s,this.events.removeListener(Vv,t)}catch(e){this.queue.set(h,{request:d,opts:i,attempt:1}),this.logger.warn(e,e?.message)}}));this.logger.trace({type:"method",method:"publish",params:{id:h,payload:t,opts:i}}),await ny(e,this.publishTimeout,f)}catch(e){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(e),i?.internal?.throwOnFailedPublish)throw e}finally{this.queue.delete(h)}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.relayer=e,this.logger=Ug(i,this.name),this.registerEventListeners()}get context(){return Cg(this.logger)}async rpcPublish(e,t){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(Vv,{...e,...t}),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach((async(e,t)=>{const i=e.attempt+1;this.queue.set(t,{...e,attempt:i}),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${e.request.params?.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)}))}registerEventListeners(){this.relayer.core.heartbeat.on(fm,(()=>{if(this.needsTransportRestart)return this.needsTransportRestart=!1,void this.relayer.events.emit(Kv);this.checkQueue()})),this.relayer.on($v,(e=>{this.removeRequestFromQueue(e.id.toString())}))}}class yx{constructor(){this.map=new Map,this.set=(e,t)=>{const i=this.get(e);this.exists(e,t)||this.map.set(e,[...i,t])},this.get=e=>this.map.get(e)||[],this.exists=(e,t)=>this.get(e).includes(t),this.delete=(e,t)=>{if(typeof t>"u")return void this.map.delete(e);if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,t))return;const s=i.filter((e=>e!==t));s.length?this.map.set(e,s):this.map.delete(e)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}class wx extends Xm{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,this.subscriptions=new Map,this.topicMap=new yx,this.events=new t,this.name="subscription",this.version="0.3",this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=Nv,this.subscribeTimeout=m.toMiliseconds(m.ONE_MINUTE),this.initialSubscribeTimeout=m.toMiliseconds(15*m.ONE_SECOND),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(e,t)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}});try{const i=xw(t),s={topic:e,relay:i,transportType:t?.transportType};t?.internal?.skipSubscribe||this.pending.set(e,s);const r=await this.rpcSubscribe(e,i,t);return"string"==typeof r&&(this.onSubscribe(r,s),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:e,opts:t}})),r}catch(e){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(e),e}},this.unsubscribe=async(e,t)=>{this.isInitialized(),typeof t?.id<"u"?await this.unsubscribeById(e,t.id,t):await this.unsubscribeByTopic(e,t)},this.isSubscribed=e=>new Promise((t=>{t(this.topicMap.topics.includes(e))})),this.isKnownTopic=e=>new Promise((t=>{t(this.topicMap.topics.includes(e)||this.pending.has(e)||this.cached.some((t=>t.topic===e)))})),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(!(0!==this.pending.size||this.initialized&&this.relayer.connected))return;const e=[];this.pending.forEach((t=>{e.push(t)})),await this.batchSubscribe(e)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(fm,(async()=>{await this.checkPending()})),this.events.on(tE,(async e=>{const t=tE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()})),this.events.on(iE,(async e=>{const t=iE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),await this.persist()}))},this.relayer=e,this.logger=Ug(i,this.name),this.clientId=""}get context(){return Cg(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,t){let i=!1;try{i=this.getSubscription(e).topic===t}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,t){const i=this.topicMap.get(e);await Promise.all(i.map((async i=>await this.unsubscribeById(e,i,t))))}async unsubscribeById(e,t,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}});try{const s=Fg("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,t,s);const r=xw(i);await this.restartToComplete({topic:e,id:t,relay:r}),await this.rpcUnsubscribe(e,t,r),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:t,opts:i}})}catch(e){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(e),e}}async rpcSubscribe(e,t,i){const s=await this.getSubscriptionId(e);if(i?.internal?.skipSubscribe)return s;(!i||i?.transportType===Xv.relay)&&await this.restartToComplete({topic:e,id:e,relay:t});const r={method:Iw(t.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});const n=i?.internal?.throwOnFailedPublish;try{if(i?.transportType===Xv.link_mode)return setTimeout((()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(r).catch((e=>this.logger.warn(e)))}),m.toMiliseconds(m.ONE_SECOND)),s;const t=new Promise((async t=>{const i=s=>{s.topic===e&&(this.events.removeListener(tE,i),t(s.id))};this.events.on(tE,i);try{const s=await ny(new Promise(((e,t)=>{this.relayer.request(r).catch((e=>{this.logger.warn(e,e?.message),t(e)})).then(e)})),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(tE,i),t(s)}catch{}})),o=await ny(t,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!o&&n)throw new Error(`Subscribing to ${e} failed, please try again`);return o?s:null}catch(e){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Kv),n)throw e}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const t={method:Iw(e[0].relay.protocol).batchSubscribe,params:{topics:e.map((e=>e.topic))}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{return await ny(new Promise(((e,i)=>{this.relayer.request(t).then(e).catch((e=>{this.logger.warn(e),i(e)}))})),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(Kv),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const t={method:Iw(e[0].relay.protocol).batchFetchMessages,params:{topics:e.map((e=>e.topic))}};let i;this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:t});try{i=await await ny(new Promise(((e,i)=>{this.relayer.request(t).catch((e=>{this.logger.warn(e),i(e)})).then(e)})),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Kv)}return i}rpcUnsubscribe(e,t,i){const s={method:Iw(i.protocol).unsubscribe,params:{topic:e,id:t}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,t){this.setSubscription(e,{...t,id:e}),this.pending.delete(t.topic)}onBatchSubscribe(e){e.length&&e.forEach((e=>{this.setSubscription(e.id,{...e}),this.pending.delete(e.topic)}))}async onUnsubscribe(e,t,i){this.events.removeAllListeners(t),this.hasSubscription(t,e)&&this.deleteSubscription(t,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,t){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:t}),this.addSubscription(e,t)}addSubscription(e,t){this.subscriptions.set(e,{...t}),this.topicMap.set(t.topic,e),this.events.emit(tE,t)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const t=this.subscriptions.get(e);if(!t){const{message:t}=zg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}deleteSubscription(e,t){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:t});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(iE,{...i,reason:t})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(sE)}async onRestart(){if(this.cached.length){const e=[...this.cached],t=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<t;i++){const t=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(t)}}this.events.emit(rE)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every((e=>e.topic===this.subscriptions.get(e.id)?.topic))){const{message:e}=zg("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(e)}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){if(e.length){if(!await this.rpcBatchSubscribe(e))return this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),void e.forEach((e=>{this.pending.set(e.topic,e)}));this.onBatchSubscribe(await Promise.all(e.map((async e=>({...e,id:await this.getSubscriptionId(e.topic)})))))}}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const t=await this.rpcBatchFetchMessages(e);var i;t&&t.messages&&(await(i=m.toMiliseconds(m.ONE_SECOND),new Promise((e=>setTimeout(e,i)))),await this.relayer.handleBatchMessageEvents(t.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=zg("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 uw(e+await this.getClientId())}}class mx extends Ym{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new t,this.name="relayer",this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=m.toMiliseconds(m.THIRTY_SECONDS+m.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=m.toMiliseconds(15*m.ONE_SECOND),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=m.toMiliseconds(2*m.ONE_SECOND),this.stalledRestartMaxInterval=m.toMiliseconds(m.THIRTY_SECONDS),this.request=async e=>{this.logger.debug("Publishing Request Payload");const t=e.id||wb().toString();await this.toEstablishConnection();try{this.logger.trace({id:t,method:e.method,topic:e.params?.topic},"relayer.request - publishing...");const i=`${t}:${e.params?.tag||""}`;this.requestsInFlight.push(i);const s=await this.provider.request(e);return this.requestsInFlight=this.requestsInFlight.filter((e=>e!==i)),s}catch(e){throw this.logger.debug(`Failed to Publish Request: ${t}`),e}},this.resetPingTimeout=()=>{Wg()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout((()=>{try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),this.provider?.connection?.socket?.terminate?.()}catch(e){this.logger.warn(e,e?.message)}}),this.heartBeatTimeout))},this.onPayloadHandler=e=>{this.onProviderPayload(e),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(jv)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=e=>{this.logger.fatal(`Fatal socket error: ${e.message}`),this.events.emit(Fv,e),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch((e=>this.logger.warn(e)))},this.registerProviderListeners=()=>{this.provider.on(Hv,this.onPayloadHandler),this.provider.on(Wv,this.onConnectHandler),this.provider.on(Gv,this.onDisconnectHandler),this.provider.on(Yv,this.onProviderErrorHandler)},this.core=e.core,this.logger=hm({logger:e.logger??"error",name:this.name}),this.messages=new px(this.logger,e.core),this.subscriber=new wx(this,this.logger),this.publisher=new gx(this,this.logger),this.projectId=e.projectId,this.relayUrl=e.relayUrl||Dv,Gg()&&typeof global<"u"&&typeof global?.Platform<"u"&&"android"===global?.Platform.OS?this.packageName=Xg():Gg()&&typeof global<"u"&&typeof global?.Platform<"u"&&"ios"===global?.Platform.OS&&(this.bundleId=Xg()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch((e=>this.logger.warn(e,e?.message)))}get context(){return Cg(this.logger)}get connected(){return 1===this.provider?.connection?.socket?.readyState}get connecting(){return 0===this.provider?.connection?.socket?.readyState||void 0!==this.connectPromise}async publish(e,t,i){this.isInitialized(),await this.publisher.publish(e,t,i),await this.recordMessageEvent({topic:e,message:t,publishedAt:Date.now(),transportType:Xv.relay},Qv)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,t){this.isInitialized(),(!t?.transportType||"relay"===t?.transportType)&&await this.toEstablishConnection();const i=t?.internal?.throwOnFailedPublish??!0;let s,r=this.subscriber.topicMap.get(e)?.[0]||"";const n=t=>{t.topic===e&&(this.subscriber.off(tE,n),s())};return await Promise.all([new Promise((e=>{s=e,this.subscriber.on(tE,n)})),new Promise(((s,n)=>{this.subscriber.subscribe(e,{internal:{throwOnFailedPublish:i},...t}).then((e=>{r=e||r,s()})).catch((e=>{i?n(e):s()}))}))]),r}async unsubscribe(e,t){this.isInitialized(),await this.subscriber.unsubscribe(e,t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await ny(this.provider.disconnect(),2e3,"provider.disconnect()").catch((()=>this.onProviderDisconnect())):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(e){if(this.subscriber.hasAnyTopics){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=this.connect(e).finally((()=>{this.connectPromise=void 0})),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}else this.logger.info("Starting WS connection skipped because the client has no topics to work with.")}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await em())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(0===e?.length)return void this.logger.trace("Batch message events is empty. Ignoring...");const t=e.sort(((e,t)=>e.publishedAt-t.publishedAt));this.logger.debug(`Batch of ${t.length} message events sorted`);for(const e of t)try{await this.onMessageEvent(e)}catch(e){this.logger.warn(e,"Error while processing batch message event: "+e?.message)}this.logger.trace(`Batch of ${t.length} message events processed`)}async onLinkMessageEvent(e,t){const{topic:i}=e;if(!t.sessionExists){const e={topic:i,expiry:cy(m.FIVE_MINUTES),relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,e)}this.events.emit(Mv,e),await this.recordMessageEvent(e,Jv)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let t=1;try{for(;t<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${t}...`),await this.createProvider(),await new Promise(((e,t)=>{const i=()=>{t(new Error("Connection interrupted while trying to connect"))};this.provider.once(Gv,i),ny(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then((()=>e())).catch(t).finally((()=>{this.provider.off(Gv,i),clearTimeout(this.reconnectTimeout)}))})),await new Promise(((e,t)=>{const i=()=>{t(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Gv,i),this.subscriber.start().then(e).catch(t).finally((()=>{this.provider.off(Gv,i)}))})),this.hasExperiencedNetworkDisruption=!1}catch(e){await this.subscriber.stop();const t=e;this.logger.warn({},t.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${t}`);break}await new Promise((e=>setTimeout(e,m.toMiliseconds(1*t)))),t++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){if(Wg())try{this.provider?.connection?.socket?.on("ping",(()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await ny(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ub(new qb(ey({sdkVersion:Zv,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,t){const{topic:i,message:s}=e;await this.messages.set(i,s,t)}async shouldIgnoreMessageEvent(e){const{topic:t,message:i}=e;if(!i||0===i.length)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(t))return this.logger.warn(`Ignoring message for unknown topic ${t}`),!0;const s=this.messages.has(t,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}),Bb(e)){if(!e.method.endsWith("_subscription"))return;const t=e.params,{topic:i,message:s,publishedAt:r,attestation:n}=t.data,o={topic:i,message:s,publishedAt:r,transportType:Xv.relay,attestation:n};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:t.id,...o}),this.events.emit(t.id,o),await this.acknowledgePayload(e),await this.onMessageEvent(o)}else Rb(e)&&this.events.emit($v,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Jv),this.events.emit(Mv,e))}async acknowledgePayload(e){const t=bb(e.id,!0);await this.provider.connection.send(t)}unregisterProviderListeners(){this.provider.off(Hv,this.onPayloadHandler),this.provider.off(Wv,this.onConnectHandler),this.provider.off(Gv,this.onDisconnectHandler),this.provider.off(Yv,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await em();tm((async t=>{e!==t&&(e=t,t?await this.transportOpen().catch((e=>this.logger.error(e,e?.message))):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))})),this.core.heartbeat.on(fm,(async()=>{if(!(this.transportExplicitlyClosed||this.connected||Yg()&&z()&&"visible"!==z()?.visibilityState))try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}})),this.events.on(Kv,(()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const e=0===this.stalledRestartBackoff?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${e?` in ${e}ms`:""}...`),this.stalledRestartTimeout=setTimeout((async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(e){this.logger.error(e,e?.message)}finally{this.stalledRestartInProgress=!1}}),e)}))}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(zv),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(e){this.logger.warn(e,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed)return void(this.reconnectInProgress=!1);this.reconnectTimeout=setTimeout((async()=>{await this.transportOpen().catch((e=>this.logger.error(e,e?.message))),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}),m.toMiliseconds(.1))}}isInitialized(){if(!this.initialized){const{message:e}=zg("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise)return void await this.connectPromise;this.connectPromise=this.connect().finally((()=>{this.connectPromise=void 0})),await this.connectPromise}}}class bx extends Zm{constructor(e,t,i,s=Nv,r=void 0){super(e,t,i,s),this.core=e,this.logger=t,this.name=i,this.map=new Map,this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Nv,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>{this.getKey&&null!==e&&!Dw(e)?this.map.set(this.getKey(e),e):function(e){return e?.proposer?.publicKey}(e)?this.map.set(e.id,e):function(e){return e?.topic}(e)&&this.map.set(e.topic,e)})),this.cached=[],this.initialized=!0)},this.set=async(e,t)=>{this.isInitialized(),this.map.has(e)?await this.update(e,t):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:e,value:t}),this.map.set(e,t),await this.persist())},this.get=e=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:e}),this.getData(e)),this.getAll=e=>(this.isInitialized(),e?this.values.filter((t=>Object.keys(e).every((i=>_v(t[i],e[i]))))):this.values),this.update=async(e,t)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:e,update:t});const i={...this.getData(e),...t};this.map.set(e,i),await this.persist()},this.delete=async(e,t)=>{this.isInitialized(),this.map.has(e)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:e,reason:t}),this.map.delete(e),this.addToRecentlyDeleted(e),await this.persist())},this.logger=Ug(t,this.name),this.storagePrefix=s,this.getKey=r}get context(){return Cg(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 t=this.map.get(e);if(!t){if(this.recentlyDeleted.includes(e)){const{message:t}=zg("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}const{message:t}=zg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(t),new Error(t)}return t}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:e}=zg("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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}=zg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class vx{constructor(t,i){this.core=t,this.logger=i,this.name="pairing",this.version="0.3",this.events=new e,this.initialized=!1,this.storagePrefix=Nv,this.ignoredPayloadTypes=[sw],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:e})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...e])]},this.create=async e=>{this.isInitialized();const t=hw(),i=await this.core.crypto.setSymKey(t),s=cy(m.FIVE_MINUTES),r={protocol:"irn"},n={topic:i,expiry:s,relay:r,active:!1,methods:e?.methods},o=Pw({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:t,relay:r,expiryTimestamp:s,methods:e?.methods});return this.events.emit(oE,n),this.core.expirer.set(i,s),await this.pairings.set(i,n),await this.core.relayer.subscribe(i,{transportType:e?.transportType,internal:e?.internal}),{topic:i,uri:o}},this.pair=async e=>{this.isInitialized();const t=this.core.eventClient.createEvent({properties:{topic:e?.uri,trace:[xE]}});this.isValidPair(e,t);const{topic:i,symKey:s,relay:r,expiryTimestamp:n,methods:o}=Ow(e.uri);let a;if(t.props.properties.topic=i,t.addTrace(IE),t.addTrace(SE),this.pairings.keys.includes(i)){if(a=this.pairings.get(i),t.addTrace(PE),a.active)throw t.setError(UE),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);t.addTrace(TE)}const c=n||cy(m.FIVE_MINUTES),h={topic:i,relay:r,expiry:c,active:!1,methods:o};this.core.expirer.set(i,c),await this.pairings.set(i,h),t.addTrace(OE),e.activatePairing&&await this.activate({topic:i}),this.events.emit(oE,h),t.addTrace(BE),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(s,i),t.addTrace(_E);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{t.setError(NE)}try{await this.core.relayer.subscribe(i,{relay:r})}catch(e){throw t.setError(kE),e}return t.addTrace(AE),h},this.activate=async({topic:e})=>{this.isInitialized();const t=cy(m.FIVE_MINUTES);this.core.expirer.set(e,t),await this.pairings.update(e,{active:!0,expiry:t})},this.ping=async e=>{this.isInitialized(),await this.isValidPing(e),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:t}=e;if(this.pairings.keys.includes(t)){const e=await this.sendRequest(t,"wc_pairingPing",{}),{done:i,resolve:s,reject:r}=ry();this.events.once(ly("pairing_ping",e),(({error:e})=>{e?r(e):s()})),await i()}},this.updateExpiry=async({topic:e,expiry:t})=>{this.isInitialized(),await this.pairings.update(e,{expiry:t})},this.updateMetadata=async({topic:e,metadata:t})=>{this.isInitialized(),await this.pairings.update(e,{peerMetadata:t})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async e=>{this.isInitialized(),await this.isValidDisconnect(e);const{topic:t}=e;this.pairings.keys.includes(t)&&(await this.sendRequest(t,"wc_pairingDelete",Fg("USER_DISCONNECTED")),await this.deletePairing(t))},this.formatUriFromPairing=e=>{this.isInitialized();const{topic:t,relay:i,expiry:s,methods:r}=e,n=this.core.crypto.keychain.get(t);return Pw({protocol:this.core.protocol,version:this.core.version,topic:t,symKey:n,relay:i,expiryTimestamp:s,methods:r})},this.sendRequest=async(e,t,i)=>{const s=mb(t,i),r=await this.core.crypto.encode(e,s),n=nE[t].req;return this.core.history.set(e,s),this.core.relayer.publish(e,r,n),s.id},this.sendResult=async(e,t,i)=>{const s=bb(e,i),r=await this.core.crypto.encode(t,s),n=(await this.core.history.get(t,e)).request.method,o=nE[n].res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.sendError=async(e,t,i)=>{const s=vb(e,i),r=await this.core.crypto.encode(t,s),n=(await this.core.history.get(t,e)).request.method,o=nE[n]?nE[n].res:nE.unregistered_method.res;await this.core.relayer.publish(t,r,o),await this.core.history.resolve(s)},this.deletePairing=async(e,t)=>{await this.core.relayer.unsubscribe(e),await Promise.all([this.pairings.delete(e,Fg("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(e),t?Promise.resolve():this.core.expirer.del(e)])},this.cleanup=async()=>{const e=this.pairings.getAll().filter((e=>hy(e.expiry)));await Promise.all(e.map((e=>this.deletePairing(e.topic))))},this.onRelayEventRequest=async e=>{const{topic:t,payload:i}=e;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(t,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(t,i);default:return await this.onUnknownRpcMethodRequest(t,i)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:i}=e,s=(await this.core.history.get(t,i.id)).request.method;return"wc_pairingPing"===s?this.onPairingPingResponse(t,i):this.onUnknownRpcMethodResponse(s)},this.onPairingPingRequest=async(e,t)=>{const{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult(i,e,!0),this.events.emit(hE,{id:i,topic:e})}catch(t){await this.sendError(i,e,t),this.logger.error(t)}},this.onPairingPingResponse=(e,t)=>{const{id:i}=t;setTimeout((()=>{Nb(t)?this.events.emit(ly("pairing_ping",i),{}):Cb(t)&&this.events.emit(ly("pairing_ping",i),{error:t.error})}),500)},this.onPairingDeleteRequest=async(e,t)=>{const{id:i}=t;try{this.isValidDisconnect({topic:e}),await this.deletePairing(e),this.events.emit(cE,{id:i,topic:e})}catch(t){await this.sendError(i,e,t),this.logger.error(t)}},this.onUnknownRpcMethodRequest=async(e,t)=>{const{id:i,method:s}=t;try{if(this.registeredMethods.includes(s))return;const t=Fg("WC_METHOD_UNSUPPORTED",s);await this.sendError(i,e,t),this.logger.error(t)}catch(t){await this.sendError(i,e,t),this.logger.error(t)}},this.onUnknownRpcMethodResponse=e=>{this.registeredMethods.includes(e)||this.logger.error(Fg("WC_METHOD_UNSUPPORTED",e))},this.isValidPair=(e,t)=>{if(!Gw(e)){const{message:i}=zg("MISSING_OR_INVALID",`pair() params: ${e}`);throw t.setError(CE),new Error(i)}if(!function(e){function t(e){try{return typeof new URL(e)<"u"}catch{return!1}}try{if(Mw(e,!1))return!!t(e)||t(yy(e))}catch{}return!1}(e.uri)){const{message:i}=zg("MISSING_OR_INVALID",`pair() uri: ${e.uri}`);throw t.setError(CE),new Error(i)}const i=Ow(e?.uri);if(!i?.relay?.protocol){const{message:e}=zg("MISSING_OR_INVALID","pair() uri#relay-protocol");throw t.setError(CE),new Error(e)}if(!i?.symKey){const{message:e}=zg("MISSING_OR_INVALID","pair() uri#symKey");throw t.setError(CE),new Error(e)}if(i?.expiryTimestamp&&m.toMiliseconds(i?.expiryTimestamp)<Date.now()){t.setError(LE);const{message:e}=zg("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(e)}},this.isValidPing=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidDisconnect=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidPairingTopic(t)},this.isValidPairingTopic=async e=>{if(!Mw(e,!1)){const{message:t}=zg("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.pairings.keys.includes(e)){const{message:t}=zg("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(hy(this.pairings.get(e).expiry)){await this.deletePairing(e);const{message:t}=zg("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}},this.core=t,this.logger=Ug(i,this.name),this.pairings=new bx(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Cg(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=zg("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Mv,(async e=>{const{topic:t,message:i,transportType:s}=e;if(this.pairings.keys.includes(t)&&s!==Xv.link_mode){try{if(this.core.crypto.getPayloadType(i,ew)===rw)return void this.logger.warn(`registerRelayerEvents() -> non-link mode TYPE_2 payload ignored: ${i}`)}catch{}if(!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const e=await this.core.crypto.decode(t,i);Bb(e)?(this.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e})):Rb(e)&&(await this.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e}),this.core.history.delete(t,e.id)),await this.core.relayer.messages.ack(t,i)}catch(e){this.logger.error(e)}}}))}registerExpirerEvents(){this.core.expirer.on(yE,(async e=>{const{topic:t}=ay(e.target);t&&this.pairings.keys.includes(t)&&(await this.deletePairing(t,!0),this.events.emit(aE,{topic:t}))}))}}class Ex extends Hm{constructor(e,i){super(e,i),this.core=e,this.logger=i,this.records=new Map,this.events=new t,this.name="history",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Nv,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.records.set(e.id,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.set=(e,t,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:e,request:t,chainId:i}),this.records.has(t.id))return;const s={id:t.id,topic:e,request:{method:t.method,params:t.params||null},chainId:i,expiry:cy(m.THIRTY_DAYS)};this.records.set(s.id,s),this.persist(),this.events.emit(lE,s)},this.resolve=async e=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:e}),!this.records.has(e.id))return;const t=await this.getRecord(e.id);typeof t.response<"u"||(t.response=Cb(e)?{error:e.error}:{result:e.result},this.records.set(t.id,t),this.persist(),this.events.emit(uE,t))},this.get=async(e,t)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:e,id:t}),await this.getRecord(t)),this.delete=(e,t)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:t}),this.values.forEach((i=>{if(i.topic===e){if(typeof t<"u"&&i.id!==t)return;this.records.delete(i.id),this.events.emit(dE,i)}})),this.persist()},this.exists=async(e,t)=>(this.isInitialized(),!!this.records.has(t)&&(await this.getRecord(t)).topic===e),this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=Ug(i,this.name)}get context(){return Cg(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((t=>{if(typeof t.response<"u")return;const i={topic:t.topic,request:mb(t.request.method,t.request.params,t.id),chainId:t.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 t=this.records.get(e);if(!t){const{message:t}=zg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(t)}return t}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(fE)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:e}=zg("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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(lE,(e=>{const t=lE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on(uE,(e=>{const t=uE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.events.on(dE,(e=>{const t=dE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,record:e})})),this.core.heartbeat.on(fm,(()=>{this.cleanup()}))}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach((t=>{m.toMiliseconds(t.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${t.id}`),this.records.delete(t.id),this.events.emit(dE,t,!1),e=!0)})),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=zg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class xx extends Jm{constructor(e,i){super(e,i),this.core=e,this.logger=i,this.expirations=new Map,this.events=new t,this.name="expirer",this.version="0.3",this.cached=[],this.initialized=!1,this.storagePrefix=Nv,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach((e=>this.expirations.set(e.target,e))),this.cached=[],this.registerEventListeners(),this.initialized=!0)},this.has=e=>{try{const t=this.formatTarget(e);return typeof this.getExpiration(t)<"u"}catch{return!1}},this.set=(e,t)=>{this.isInitialized();const i=this.formatTarget(e),s={target:i,expiry:t};this.expirations.set(i,s),this.checkExpiry(i,s),this.events.emit(pE,{target:i,expiration:s})},this.get=e=>{this.isInitialized();const t=this.formatTarget(e);return this.getExpiration(t)},this.del=e=>{if(this.isInitialized(),this.has(e)){const t=this.formatTarget(e),i=this.getExpiration(t);this.expirations.delete(t),this.events.emit(gE,{target:t,expiration:i})}},this.on=(e,t)=>{this.events.on(e,t)},this.once=(e,t)=>{this.events.once(e,t)},this.off=(e,t)=>{this.events.off(e,t)},this.removeListener=(e,t)=>{this.events.removeListener(e,t)},this.logger=Ug(i,this.name)}get context(){return Cg(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("string"==typeof e)return oy("topic",e);if("number"==typeof e)return function(e){return oy("id",e)}(e);const{message:t}=zg("UNKNOWN_TYPE","Target type: "+typeof e);throw new Error(t)}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(wE)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:e}=zg("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(e),new Error(e)}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 t=this.expirations.get(e);if(!t){const{message:t}=zg("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(t),new Error(t)}return t}checkExpiry(e,t){const{expiry:i}=t;m.toMiliseconds(i)-Date.now()<=0&&this.expire(e,t)}expire(e,t){this.expirations.delete(e),this.events.emit(yE,{target:e,expiration:t})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach(((e,t)=>this.checkExpiry(t,e)))}registerEventListeners(){this.core.heartbeat.on(fm,(()=>this.checkExpirations())),this.events.on(pE,(e=>{const t=pE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(yE,(e=>{const t=yE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()})),this.events.on(gE,(e=>{const t=gE;this.logger.info(`Emitting ${t}`),this.logger.debug({type:"event",event:t,data:e}),this.persist()}))}isInitialized(){if(!this.initialized){const{message:e}=zg("NOT_INITIALIZED",this.name);throw new Error(e)}}}class Ix extends Qm{constructor(e,t,i){super(e,t,i),this.core=e,this.logger=t,this.store=i,this.name="verify-api",this.verifyUrlV3=vE,this.storagePrefix=Nv,this.version=2,this.init=async()=>{this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&m.toMiliseconds(this.publicKey?.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async e=>{if(!Yg()||this.isDevEnv)return;const t=window.location.origin,{id:i,decryptedId:s}=e,r=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${t}&id=${i}&decryptedId=${s}`;try{const e=z(),t=this.startAbortTimer(5*m.ONE_SECOND),s=await new Promise(((s,n)=>{const o=()=>{window.removeEventListener("message",c),e.body.removeChild(a),n("attestation aborted")};this.abortController.signal.addEventListener("abort",o);const a=e.createElement("iframe");a.src=r,a.style.display="none",a.addEventListener("error",o,{signal:this.abortController.signal});const c=r=>{if(r.data&&"string"==typeof r.data)try{const n=JSON.parse(r.data);if("verify_attestation"===n.type){if(ip(n.attestation).payload.id!==i)return;clearInterval(t),e.body.removeChild(a),this.abortController.signal.removeEventListener("abort",o),window.removeEventListener("message",c),s(null===n.attestation?"":n.attestation)}}catch(e){this.logger.warn(e)}};e.body.appendChild(a),window.addEventListener("message",c,{signal:this.abortController.signal})}));return this.logger.debug(s,"jwt attestation"),s}catch(e){this.logger.warn(e)}return""},this.resolve=async e=>{if(this.isDevEnv)return"";const{attestationId:t,hash:i,encryptedId:s}=e;if(""===t)return void this.logger.debug("resolve: attestationId is empty, skipping");if(t){if(ip(t).payload.id!==s)return;const e=await this.isValidJwtAttestation(t);if(e)return e.isVerified?e:void this.logger.warn("resolve: jwt attestation: origin url not verified")}if(!i)return;const r=this.getVerifyUrl(e?.verifyUrl);return this.fetchAttestation(i,r)},this.fetchAttestation=async(e,t)=>{this.logger.debug(`resolving attestation: ${e} from url: ${t}`);const i=this.startAbortTimer(5*m.ONE_SECOND),s=await fetch(`${t}/attestation/${e}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(i),200===s.status?await s.json():void 0},this.getVerifyUrl=e=>{let t=e||bE;return EE.includes(t)||(this.logger.info(`verify url: ${t}, not included in trusted list, assigning default: ${bE}`),t=bE),t},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const e=this.startAbortTimer(m.FIVE_SECONDS),t=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(e),await t.json()}catch(e){this.logger.warn(e)}},this.persistPublicKey=async e=>{this.logger.debug(e,"persisting public key to local storage"),await this.store.setItem(this.storeKey,e),this.publicKey=e},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async e=>{const t=await this.getPublicKey();try{if(t)return this.validateAttestation(e,t)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}const i=await this.fetchAndPersistPublicKey();try{if(i)return this.validateAttestation(e,i)}catch(e){this.logger.error(e),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise((async e=>{const t=await this.fetchPublicKey();t&&(await this.persistPublicKey(t),e(t))}));const e=await this.fetchPromise;return this.fetchPromise=void 0,e},this.validateAttestation=(e,t)=>{const i=Ew(e,t.publicKey),s={hasExpired:m.toMiliseconds(i.exp)<Date.now(),payload:i};if(s.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:s.payload.origin,isScam:s.payload.isScam,isVerified:s.payload.isVerified}},this.logger=Ug(t,this.name),this.abortController=new AbortController,this.isDevEnv=gy(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Cg(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout((()=>this.abortController.abort()),m.toMiliseconds(e))}}class Sx extends eb{constructor(e,t){super(e,t),this.projectId=e,this.logger=t,this.context="echo",this.registerDeviceToken=async e=>{const{clientId:t,token:i,notificationType:s,enableEncrypted:r=!1}=e,n=`https://echo.walletconnect.com/${this.projectId}/clients`;await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t,type:s,token:i,always_raw:r})})},this.logger=Ug(t,this.context)}}class Ox extends tb{constructor(e,t,i=!0){super(e,t,i),this.core=e,this.logger=t,this.context="event-client",this.storagePrefix=Nv,this.storageVersion=.1,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!gy())try{const e={eventId:py(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Qg(this.core.relayer.protocol,this.core.relayer.version,Zv)}}};await this.sendEvent([e])}catch(e){this.logger.warn(e)}},this.createEvent=e=>{const{event:t="ERROR",type:i="",properties:{topic:s,trace:r}}=e,n=py(),o=this.core.projectId||"",a={eventId:n,timestamp:Date.now(),props:{event:t,type:i,properties:{topic:s,trace:r}},bundleId:o,domain:this.getAppDomain(),...this.setMethods(n)};return this.telemetryEnabled&&(this.events.set(n,a),this.shouldPersist=!0),a},this.getEvent=e=>{const{eventId:t,topic:i}=e;if(t)return this.events.get(t);const s=Array.from(this.events.values()).find((e=>e.props.properties.topic===i));return s?{...s,...this.setMethods(s.eventId)}:void 0},this.deleteEvent=e=>{const{eventId:t}=e;this.events.delete(t),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(fm,(async()=>{this.shouldPersist&&await this.persist(),this.events.forEach((e=>{m.fromMiliseconds(Date.now())-m.fromMiliseconds(e.timestamp)>86400&&(this.events.delete(e.eventId),this.shouldPersist=!0)}))}))},this.setMethods=e=>({addTrace:t=>this.addTrace(e,t),setError:t=>this.setError(e,t)}),this.addTrace=(e,t)=>{const i=this.events.get(e);i&&(i.props.properties.trace.push(t),this.events.set(e,i),this.shouldPersist=!0)},this.setError=(e,t)=>{const i=this.events.get(e);i&&(i.props.type=t,i.timestamp=Date.now(),this.events.set(e,i),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const e=await this.core.storage.getItem(this.storageKey)||[];if(!e.length)return;e.forEach((e=>{this.events.set(e.eventId,{...e,...this.setMethods(e.eventId)})}))}catch(e){this.logger.warn(e)}},this.submit=async()=>{if(!this.telemetryEnabled||0===this.events.size)return;const e=[];for(const[t,i]of this.events)i.props.type&&e.push(i);if(0!==e.length)try{if((await this.sendEvent(e)).ok)for(const t of e)this.events.delete(t.eventId),this.shouldPersist=!0}catch(e){this.logger.warn(e)}},this.sendEvent=async e=>{const t=this.getAppDomain()?"":"&sp=desktop";return await fetch(`https://pulse.walletconnect.org/batch?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Zv}${t}`,{method:"POST",body:JSON.stringify(e)})},this.getAppDomain=()=>Jg().url,this.logger=Ug(t,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}}const _x=class e extends Vm{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=Rv,this.events=new t,this.initialized=!1,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.dispatchEnvelope=({topic:e,message:t,sessionExists:i})=>{if(!e||!t)return;const s={topic:e,message:t,publishedAt:Date.now(),transportType:Xv.link_mode};this.relayer.onLinkMessageEvent(s,{sessionExists:i})};const i=this.getGlobalCore(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(e){console.warn("Failed to copy global core",e)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Dv,this.customStoragePrefix=e?.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=function(e){return Ng(Rg({},e),{level:e?.level||ag})}({level:"string"==typeof e?.logger&&e.logger?e.logger:Cv,name:Rv}),{logger:r,chunkLoggerController:n}=kg({opts:s,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=n,this.logChunkController?.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{this.logChunkController?.downloadLogsBlobInBrowser&&this.logChunkController?.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()})}),this.logger=Ug(r,this.name),this.heartbeat=new pm,this.crypto=new fx(this,this.logger,e?.keychain),this.history=new Ex(this,this.logger),this.expirer=new xx(this,this.logger),this.storage=e?.storage?e.storage:new Km({...Uv,...e?.storageOptions}),this.relayer=new mx({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new vx(this,this.logger),this.verify=new Ix(this,this.logger,this.storage),this.echoClient=new Sx(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new Ox(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(t){const i=new e(t);await i.initialize();const s=await i.crypto.getClientId();return await i.storage.setItem("WALLETCONNECT_CLIENT_ID",s),i}get context(){return Cg(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){return this.logChunkController?.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(eE,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(eE)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e}`,i=`${t}_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[t]}catch(e){return void console.warn("Failed to get global WalletConnect core",e)}}setGlobalCore(e){try{if(this.isGlobalCoreDisabled())return;const t=`_walletConnectCore_${e.opts?.customStoragePrefix||""}`;globalThis[t]=e}catch(e){console.warn("Failed to set global WalletConnect core",e)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&"true"===process.env.DISABLE_GLOBAL_CORE}catch{return!0}}},Ax="client",Px=`wc@2:${Ax}:`,Tx=Ax,Bx="error",Rx="WALLETCONNECT_DEEPLINK_CHOICE",Nx="Proposal expired",Cx=m.SEVEN_DAYS,Ux={wc_sessionPropose:{req:{ttl:m.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1104},res:{ttl:m.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1106},res:{ttl:m.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:3*m.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:3*m.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:m.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1112},res:{ttl:m.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:m.ONE_DAY,prompt:!1,tag:1114},res:{ttl:m.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:m.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:m.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:m.FIVE_MINUTES,prompt:!1,tag:1119}}},kx={min:m.FIVE_MINUTES,max:m.SEVEN_DAYS},Lx="IDLE",qx="ACTIVE",Dx={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""},canton_prepareSignExecute:{key:""},stellar_signXDR:{key:""},stellar_signAndSubmitXDR:{key:"tx_hash"}},Mx=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],$x="wc@1.5:auth:",jx=`${$x}:PUB_KEY`;class zx extends sb{constructor(t){super(t),this.name="engine",this.events=new e,this.initialized=!1,this.requestQueue={state:Lx,queue:[]},this.sessionRequestQueue={state:Lx,queue:[]},this.emittedSessionRequests=new wy({limit:500}),this.requestQueueDelay=m.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Ux)}),this.initialized=!0,setTimeout((async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()}),m.toMiliseconds(this.requestQueueDelay)))},this.connect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const t={...e,requiredNamespaces:e.requiredNamespaces||{},optionalNamespaces:e.optionalNamespaces||{}};await this.isValidConnect(t),t.optionalNamespaces=function(e,t){const i=Uw(e),s=Uw(t),r={},n=Object.keys(i).concat(Object.keys(s));for(const e of n)r[e]={chains:uy(i[e]?.chains,s[e]?.chains),methods:uy(i[e]?.methods,s[e]?.methods),events:uy(i[e]?.events,s[e]?.events)};return r}(t.requiredNamespaces,t.optionalNamespaces),t.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:r,sessionProperties:n,scopedProperties:o,relays:a,authentication:c,walletPay:h}=t,l=c?.[0]?.ttl||Ux.wc_sessionPropose.req.ttl||m.FIVE_MINUTES;this.validateRequestExpiry(l);let u,d=i,f=!1;try{if(d){const e=this.client.core.pairing.pairings.get(d);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),f=e.active}}catch(e){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),e}if(!d||!f){const{topic:e,uri:t}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});d=e,u=t}if(!d){const{message:e}=zg("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error(e)}const p=await this.client.core.crypto.generateKeyPair(),g=cy(l),y={requiredNamespaces:s,optionalNamespaces:r,relays:a??[{protocol:"irn"}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:d,...n&&{sessionProperties:n},...o&&{scopedProperties:o},id:yb(),...(c||h)&&{requests:{authentication:c?.map((e=>{const{domain:t,chains:i,nonce:s,uri:r,exp:n,nbf:o,type:a,statement:c,requestId:h,resources:l,signatureTypes:u}=e;return{domain:t,chains:i,nonce:s,type:a??"caip122",aud:r,version:"1",iat:(new Date).toISOString(),exp:n,nbf:o,statement:c,requestId:h,resources:l,signatureTypes:u}})),walletPay:h}}},w=ly("session_connect",y.id),{reject:b,resolve:v,done:E}=ry(l,Nx),x=({id:e})=>{if(e===y.id){this.client.events.off("proposal_expire",x);const e=this.pendingSessions.get(y.id);if(e){const{sessionTopic:t,publicKey:i}=e;Promise.all([this.client.core.relayer.unsubscribe(t),this.client.core.crypto.keychain.has(t)?this.client.core.crypto.deleteSymKey(t):Promise.resolve(),this.client.core.crypto.keychain.has(i)?this.client.core.crypto.deleteKeyPair(i):Promise.resolve()]).catch((e=>this.client.logger.warn(e)))}this.pendingSessions.delete(y.id),this.events.emit(w,{error:{message:Nx,code:0}})}};return this.client.events.on("proposal_expire",x),this.events.once(w,(({error:e,session:t})=>{this.client.events.off("proposal_expire",x),e?b(e):t&&v(t)})),await this.setProposal(y.id,y),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}).catch((e=>{throw this.deleteProposal(y.id),e})),{uri:u,approval:E}},this.pair=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(e)}catch(e){throw this.client.logger.error("pair() failed"),e}},this.approve=async e=>{const t=this.client.core.eventClient.createEvent({properties:{topic:e?.id?.toString(),trace:[DE]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(e){throw t.setError(WE),e}try{await this.isValidProposalId(e?.id)}catch(i){throw this.client.logger.error(`approve() -> proposal.get(${e?.id}) failed`),t.setError(XE),i}try{await this.isValidApprove(e)}catch(e){throw this.client.logger.error("approve() -> isValidApprove() failed"),t.setError(ZE),e}const{id:i,relayProtocol:s,namespaces:r,sessionProperties:n,scopedProperties:o,sessionConfig:a,proposalRequestsResponses:c}=e,h=this.client.proposal.get(i);this.client.core.eventClient.deleteEvent({eventId:t.eventId});const{pairingTopic:l,proposer:u,requiredNamespaces:d,optionalNamespaces:f}=h;let p=this.client.core.eventClient?.getEvent({topic:l});p||(p=this.client.core.eventClient?.createEvent({type:DE,properties:{topic:l,trace:[DE,ME]}}));const g=await this.client.core.crypto.generateKeyPair(),y=u.publicKey,w=await this.client.core.crypto.generateSharedKey(g,y),m={relay:{protocol:s??"irn"},namespaces:r,controller:{publicKey:g,metadata:this.client.metadata},expiry:cy(Cx),...n&&{sessionProperties:n},...o&&{scopedProperties:o},...a&&{sessionConfig:a},proposalRequestsResponses:c},b=Xv.relay;p.addTrace($E);try{await this.client.core.relayer.subscribe(w,{transportType:b,internal:{skipSubscribe:!0}})}catch(e){throw p.setError(YE),e}p.addTrace(jE);const v={...m,topic:w,requiredNamespaces:d,optionalNamespaces:f,pairingTopic:l,acknowledged:!1,self:m.controller,peer:{publicKey:u.publicKey,metadata:u.metadata},controller:g,transportType:Xv.relay,authentication:c?.authentication,walletPayResult:c?.walletPay};await this.client.session.set(w,v),p.addTrace(FE);try{await this.sendApproveSession({sessionTopic:w,proposal:h,pairingProposalResponse:{relay:{protocol:s??"irn"},responderPublicKey:g},sessionSettleRequest:m,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:i,...this.getTVFApproveParams(v)}}}),p.addTrace(zE)}catch(e){throw this.client.logger.error(e),this.client.session.delete(w,Fg("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(w),e}return this.client.core.eventClient.deleteEvent({eventId:p.eventId}),await this.client.core.pairing.updateMetadata({topic:l,metadata:u.metadata}),await this.deleteProposal(i),await this.client.core.pairing.activate({topic:l}),await this.setExpiry(w,cy(Cx)),{topic:w,acknowledged:()=>Promise.resolve(this.client.session.get(w))}},this.reject=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(e)}catch(e){throw this.client.logger.error("reject() -> isValidReject() failed"),e}const{id:t,reason:i}=e;let s;try{s=this.client.proposal.get(t).pairingTopic}catch(e){throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`),e}s&&await this.sendError({id:t,topic:s,error:i,rpcOpts:Ux.wc_sessionPropose.reject}),await this.deleteProposal(t)},this.update=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(e)}catch(e){throw this.client.logger.error("update() -> isValidUpdate() failed"),e}const{topic:t,namespaces:i}=e,s=this.client.session.get(t);if(s.self.publicKey!==s.controller){const{message:e}=Fg("UNAUTHORIZED_UPDATE_REQUEST");throw new Error(e)}const{done:r,resolve:n,reject:o}=ry(m.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),a=yb(),c=wb().toString(),h=this.client.session.get(t).namespaces;return this.events.once(ly("session_update",a),(({error:e})=>{e?o(e):n()})),await this.client.session.update(t,{namespaces:i}),await this.sendRequest({topic:t,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:a,relayRpcId:c}).catch((e=>{this.client.logger.error(e),this.client.session.update(t,{namespaces:h}),o(e)})),{acknowledged:r}},this.extend=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(e)}catch(e){throw this.client.logger.error("extend() -> isValidExtend() failed"),e}const{topic:t}=e,i=yb(),{done:s,resolve:r,reject:n}=ry(m.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ly("session_extend",i),(({error:e})=>{e?n(e):r()})),await this.setExpiry(t,cy(Cx)),this.sendRequest({topic:t,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch((e=>{n(e)})),{acknowledged:s}},this.request=async e=>{this.isInitialized();try{await this.isValidRequest(e)}catch(e){throw this.client.logger.error("request() -> isValidRequest() failed"),e}const{chainId:t,request:i,topic:s,expiry:r=Ux.wc_sessionRequest.req.ttl}=e,n=this.client.session.get(s);n?.transportType===Xv.relay&&await this.confirmOnlineStateOrThrow();const o=yb(),a=wb().toString(),{done:c,resolve:h,reject:l}=ry(r,"Request expired. Please try again.");this.events.once(ly("session_request",o),(({error:e,result:t})=>{e?l(e):h(t)}));const u="wc_sessionRequest",d=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);if(d)return await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:s,method:u,params:{request:{...i,expiryTimestamp:cy(r)},chainId:t},expiry:r,throwOnFailedPublish:!0,appLink:d}).catch((e=>l(e))),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:t,id:o}),await c();const f={request:{...i,expiryTimestamp:cy(r)},chainId:t};return await Promise.all([new Promise((async e=>{await this.sendRequest({clientRpcId:o,relayRpcId:a,topic:s,method:u,params:f,expiry:r,throwOnFailedPublish:!0,tvf:this.getTVFParams(o,f)}).catch((e=>l(e))),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:t,id:o}),e()})),new Promise((async e=>{if(!n.sessionConfig?.disableDeepLink){const e=await async function(e,t){let i="";try{if(Yg()&&(i=localStorage.getItem(t),i))return i;i=await e.getItem(t)}catch(e){console.error(e)}return i}(this.client.core.storage,Rx);await dy({id:o,topic:s,wcDeepLink:e})}e()})),c()]).then((e=>e[2]))},this.respond=async e=>{this.isInitialized();const t=this.client.core.eventClient.createEvent({properties:{topic:e?.topic||e?.response?.id?.toString(),trace:[KE]}});try{await this.isValidRespond(e)}catch(e){throw t.addTrace(e?.message),t.setError(JE),e}t.addTrace(VE);const{topic:i,response:s}=e,{id:r}=s,n=this.client.session.get(i);n.transportType===Xv.relay&&await this.confirmOnlineStateOrThrow();const o=this.getAppLinkIfEnabled(n.peer.metadata,n.transportType);try{t.addTrace(HE),Nb(s)?await this.sendResult({id:r,topic:i,result:s.result,throwOnFailedPublish:!0,appLink:o}):Cb(s)&&await this.sendError({id:r,topic:i,error:s.error,appLink:o}),this.cleanupAfterResponse(e)}catch(e){throw t.addTrace(e?.message),t.setError(QE),e}},this.ping=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(e)}catch(e){throw this.client.logger.error("ping() -> isValidPing() failed"),e}const{topic:t}=e;if(this.client.session.keys.includes(t)){const e=yb(),i=wb().toString(),{done:s,resolve:r,reject:n}=ry(m.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ly("session_ping",e),(({error:e})=>{e?n(e):r()})),await Promise.all([this.sendRequest({topic:t,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:e,relayRpcId:i}),s()])}else this.client.core.pairing.pairings.keys.includes(t)&&(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:t}))},this.emit=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(e);const{topic:t,event:i,chainId:s}=e,r=wb().toString(),n=yb();await this.sendRequest({topic:t,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:r,clientRpcId:n})},this.disconnect=async e=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(e);const{topic:t}=e;if(this.client.session.keys.includes(t))await this.sendRequest({topic:t,method:"wc_sessionDelete",params:Fg("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:t,emitEvent:!1});else{if(!this.client.core.pairing.pairings.keys.includes(t)){const{message:e}=zg("MISMATCHED_TOPIC",`Session or pairing topic not found: ${t}`);throw new Error(e)}await this.client.core.pairing.disconnect({topic:t})}},this.find=e=>(this.isInitialized(),this.client.session.getAll().filter((t=>function(e,t){const{requiredNamespaces:i}=t,s=Object.keys(e.namespaces),r=Object.keys(i);let n=!0;return!!ty(r,s)&&(s.forEach((t=>{const{accounts:s,methods:r,events:o}=e.namespaces[t],a=Bw(s),c=i[t];ty(Mg(t,c),a)&&ty(c.methods,r)&&ty(c.events,o)||(n=!1)})),n)}(t,e)))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(e,t)=>{this.isInitialized(),this.isValidAuthenticate(e);const i=t&&this.client.core.linkModeSupportedApps.includes(t)&&this.client.metadata.redirect?.linkMode,s=i?Xv.link_mode:Xv.relay;s===Xv.relay&&await this.confirmOnlineStateOrThrow();const{chains:r,statement:n="",uri:o,domain:a,nonce:c,type:h,exp:l,nbf:u,methods:d=[],expiry:f}=e,p=[...e.resources||[]],{topic:g,uri:y}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:s});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:g,uri:y}}),this.client.auth.authKeys.keys.includes(jx)){const{responseTopic:e,publicKey:t}=this.client.auth.authKeys.get(jx);e&&(await this.client.core.relayer.unsubscribe(e).catch((e=>this.client.logger.warn(e))),await this.client.auth.pairingTopics.delete(e,{message:"replaced",code:0}).catch((e=>this.client.logger.warn(e)))),t&&this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteKeyPair(t)}const w=await this.client.core.crypto.generateKeyPair(),m=lw(w);if(await Promise.all([this.client.auth.authKeys.set(jx,{responseTopic:m,publicKey:w}),this.client.auth.pairingTopics.set(m,{topic:m,pairingTopic:g})]),await this.client.core.relayer.subscribe(m,{transportType:s}),this.client.logger.info(`sending request to new pairing topic: ${g}`),d.length>0){const{namespace:e}=qg(r[0]);let t=Hy(e,"request",d);Zy(p)&&(t=Wy(t,p.pop())),p.push(t)}const b=f&&f>Ux.wc_sessionAuthenticate.req.ttl?f:Ux.wc_sessionAuthenticate.req.ttl,v={authPayload:{type:h??"caip122",chains:r,statement:n,aud:o,domain:a,version:"1",nonce:c,iat:(new Date).toISOString(),exp:l,nbf:u,resources:p},requester:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:cy(b)},E={requiredNamespaces:{},optionalNamespaces:{eip155:{chains:r,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},relays:[{protocol:"irn"}],pairingTopic:g,proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:cy(Ux.wc_sessionPropose.req.ttl),id:yb()},{done:x,resolve:I,reject:S}=ry(b,"Request expired"),O=yb(),_=ly("session_connect",E.id),A=ly("session_request",O),P=async({error:e,session:t})=>{this.events.off(A,T),e?S(e):t&&I({session:t})},T=async e=>{if(await this.deletePendingAuthRequest(O,{message:"fulfilled",code:0}),e.error){const t=Fg("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return e.error.code===t.code?void 0:(this.events.off(_,P),S(e.error.message))}await this.deleteProposal(E.id),this.events.off(_,P);const{cacaos:i,responder:r}=e.result,n=[],o=[];for(const e of i){await $y({cacao:e,projectId:this.client.core.projectId})||(this.client.logger.error(e,"Signature verification failed"),S(Fg("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:t}=e,i=Zy(t.resources),s=[Dy(t.iss)],r=My(t.iss);if(i){const e=Gy(i),t=Yy(i);n.push(...e),s.push(...t)}for(const e of s)o.push(`${e}:${r}`)}const a=await this.client.core.crypto.generateSharedKey(w,r.publicKey);let c;n.length>0&&(c={topic:a,acknowledged:!0,self:{publicKey:w,metadata:this.client.metadata},peer:r,controller:r.publicKey,expiry:cy(Cx),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:g,namespaces:kw([...new Set(n)],[...new Set(o)]),transportType:s},await this.client.core.relayer.subscribe(a,{transportType:s}),await this.client.session.set(a,c),g&&await this.client.core.pairing.updateMetadata({topic:g,metadata:r.metadata}),c=this.client.session.get(a)),this.client.metadata.redirect?.linkMode&&r.metadata.redirect?.linkMode&&r.metadata.redirect?.universal&&t&&(this.client.core.addLinkModeSupportedApp(r.metadata.redirect.universal),this.client.session.update(a,{transportType:Xv.link_mode})),I({auths:i,session:c})};let B;this.events.once(_,P),this.events.once(A,T);try{if(i){const e=mb("wc_sessionAuthenticate",v,O);this.client.core.history.set(g,e);const i=await this.client.core.crypto.encode("",e,{type:rw,encoding:ew});B=Tw(t,g,i)}else await Promise.all([this.sendRequest({topic:g,method:"wc_sessionAuthenticate",params:v,expiry:e.expiry,throwOnFailedPublish:!0,clientRpcId:O}),this.sendRequest({topic:g,method:"wc_sessionPropose",params:E,expiry:Ux.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(e){throw this.events.off(_,P),this.events.off(A,T),e}return await this.setProposal(E.id,E),await this.setAuthRequest(O,{request:{...v,verifyContext:{}},pairingTopic:g,transportType:s}),{uri:B??y,response:x}},this.approveSessionAuthenticate=async e=>{const{id:t,auths:i}=e,s=this.client.core.eventClient.createEvent({properties:{topic:t.toString(),trace:[ex]}});try{this.isInitialized()}catch(e){throw s.setError(ax),e}const r=this.getPendingAuthRequest(t);if(!r)throw s.setError(ux),new Error(`Could not find pending auth request with id ${t}`);const n=r.transportType||Xv.relay;n===Xv.relay&&await this.confirmOnlineStateOrThrow();const o=r.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=lw(o),h={type:sw,receiverPublicKey:o,senderPublicKey:a},l=[],u=[];for(const e of i){if(!await $y({cacao:e,projectId:this.client.core.projectId})){s.setError(cx);const e=Fg("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:t,topic:c,error:e,encodeOpts:h}),new Error(e.message)}s.addTrace(ix);const{p:i}=e,r=Zy(i.resources),n=[Dy(i.iss)],o=My(i.iss);if(r){const e=Gy(r),t=Yy(r);l.push(...e),n.push(...t)}for(const e of n)u.push(`${e}:${o}`)}const d=await this.client.core.crypto.generateSharedKey(a,o);let f;if(s.addTrace(tx),l?.length>0){f={topic:d,acknowledged:!0,self:{publicKey:a,metadata:this.client.metadata},peer:{publicKey:o,metadata:r.requester.metadata},controller:o,expiry:cy(Cx),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:r.pairingTopic,namespaces:kw([...new Set(l)],[...new Set(u)]),transportType:n},s.addTrace(rx);try{await this.client.core.relayer.subscribe(d,{transportType:n})}catch(e){throw s.setError(hx),e}s.addTrace(nx),await this.client.session.set(d,f),s.addTrace(sx),await this.client.core.pairing.updateMetadata({topic:r.pairingTopic,metadata:r.requester.metadata})}s.addTrace(ox);try{await this.sendResult({topic:c,id:t,result:{cacaos:i,responder:{publicKey:a,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(r.requester.metadata,n)})}catch(e){throw s.setError(lx),e}return await this.client.auth.requests.delete(t,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:r.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:f}},this.rejectSessionAuthenticate=async e=>{this.isInitialized();const{id:t,reason:i}=e,s=this.getPendingAuthRequest(t);if(!s)throw new Error(`Could not find pending auth request with id ${t}`);s.transportType===Xv.relay&&await this.confirmOnlineStateOrThrow();const r=s.requester.publicKey,n=await this.client.core.crypto.generateKeyPair(),o=lw(r),a={type:sw,receiverPublicKey:r,senderPublicKey:n};await this.sendError({id:t,topic:o,error:i,encodeOpts:a,rpcOpts:Ux.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(t,{message:"rejected",code:0}),await this.deleteProposal(t)},this.formatAuthMessage=e=>{this.isInitialized();const{request:t,iss:i}=e;return jy(t,i)},this.processRelayMessageCache=()=>{setTimeout((async()=>{if(0!==this.relayMessageCache.length)for(;this.relayMessageCache.length>0;)try{const e=this.relayMessageCache.shift();e&&await this.onRelayMessage(e)}catch(e){this.client.logger.error(e)}}),50)},this.cleanupDuplicatePairings=async e=>{if(e.pairingTopic)try{const t=this.client.core.pairing.pairings.get(e.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter((i=>i.peerMetadata?.url&&i.peerMetadata?.url===e.peer.metadata.url&&i.topic&&i.topic!==t.topic));if(0===i.length)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map((e=>this.client.core.pairing.disconnect({topic:e.topic})))),this.client.logger.info("Duplicate pairings clean up finished")}catch(e){this.client.logger.error(e)}},this.deleteSession=async e=>{const{topic:t,expirerHasDeleted:i=!1,emitEvent:s=!0,id:r=0}=e,{self:n}=this.client.session.get(t);await this.client.core.relayer.unsubscribe(t),await this.client.session.delete(t,Fg("USER_DISCONNECTED")),this.addToRecentlyDeleted(t,"session"),this.client.core.crypto.keychain.has(n.publicKey)&&await this.client.core.crypto.deleteKeyPair(n.publicKey),this.client.core.crypto.keychain.has(t)&&await this.client.core.crypto.deleteSymKey(t),i||this.client.core.expirer.del(t),this.client.core.storage.removeItem(Rx).catch((e=>this.client.logger.warn(e))),t===this.sessionRequestQueue.queue[0]?.topic&&(this.sessionRequestQueue.state=Lx),await Promise.all(this.getPendingSessionRequests().filter((e=>e.topic===t)).map((e=>this.deletePendingSessionRequest(e.id,Fg("USER_DISCONNECTED"))))),s&&this.client.events.emit("session_delete",{id:r,topic:t})},this.deleteProposal=async(e,t)=>{if(t)try{const t=this.client.proposal.get(e);this.client.core.eventClient.getEvent({topic:t.pairingTopic})?.setError(GE)}catch{}await Promise.all([this.client.proposal.delete(e,Fg("USER_DISCONNECTED")),t?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"proposal")},this.deletePendingSessionRequest=async(e,t,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(e,t),i?Promise.resolve():this.client.core.expirer.del(e)]),this.addToRecentlyDeleted(e,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter((t=>t.id!==e)),i&&(this.sessionRequestQueue.state=Lx,this.client.events.emit("session_request_expire",{id:e}))},this.deletePendingAuthRequest=async(e,t,i=!1)=>{await Promise.all([this.client.auth.requests.delete(e,t),i?Promise.resolve():this.client.core.expirer.del(e)])},this.setExpiry=async(e,t)=>{this.client.session.keys.includes(e)&&(this.client.core.expirer.set(e,t),await this.client.session.update(e,{expiry:t}))},this.setProposal=async(e,t)=>{this.client.core.expirer.set(e,cy(Ux.wc_sessionPropose.req.ttl)),await this.client.proposal.set(e,t)},this.setAuthRequest=async(e,t)=>{const{request:i,pairingTopic:s,transportType:r=Xv.relay}=t;this.client.core.expirer.set(e,i.expiryTimestamp),await this.client.auth.requests.set(e,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:e,pairingTopic:s,verifyContext:i.verifyContext,transportType:r})},this.setPendingSessionRequest=async e=>{const{id:t,topic:i,params:s,verifyContext:r}=e,n=s.request.expiryTimestamp||cy(Ux.wc_sessionRequest.req.ttl);this.client.core.expirer.set(t,n),await this.client.pendingRequest.set(t,{id:t,topic:i,params:s,verifyContext:r})},this.sendRequest=async e=>{const{topic:t,method:i,params:s,expiry:r,relayRpcId:n,clientRpcId:o,throwOnFailedPublish:a,appLink:c,tvf:h,publishOpts:l={}}=e,u=mb(i,s,o);let d;const f=!!c;try{const e=f?ew:Qy;d=await this.client.core.crypto.encode(t,u,{encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`),e}let p;if(Mx.includes(i)){const e=uw(JSON.stringify(u)),t=uw(d);p=await this.client.core.verify.register({id:t,decryptedId:e})}const g={...Ux[i].req,...l};if(g.attestation=p,r&&(g.ttl=r),n&&(g.id=n),this.client.core.history.set(t,u),f){const e=Tw(c,t,d);await global.Linking.openURL(e,this.client.name)}else g.tvf={...h,correlationId:u.id},a?(g.internal={...g.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(t,d,g)):this.client.core.relayer.publish(t,d,g).catch((e=>this.client.logger.error(e)));return u.id},this.sendProposeSession=async e=>{const{proposal:t,publishOpts:i}=e,s=mb("wc_sessionPropose",t,t.id);this.client.core.history.set(t.pairingTopic,s);const r=await this.client.core.crypto.encode(t.pairingTopic,s,{encoding:Qy}),n=uw(JSON.stringify(s)),o=uw(r),a=await this.client.core.verify.register({id:o,decryptedId:n});await this.client.core.relayer.publishCustom({payload:{pairingTopic:t.pairingTopic,sessionProposal:r},opts:{...i,publishMethod:"wc_proposeSession",attestation:a}})},this.sendApproveSession=async e=>{const{sessionTopic:t,pairingProposalResponse:i,proposal:s,sessionSettleRequest:r,publishOpts:n}=e,o=bb(s.id,i),a=await this.client.core.crypto.encode(s.pairingTopic,o,{encoding:Qy}),c=mb("wc_sessionSettle",r,n?.id),h=await this.client.core.crypto.encode(t,c,{encoding:Qy});this.client.core.history.set(t,c),await this.client.core.relayer.publishCustom({payload:{sessionTopic:t,pairingTopic:s.pairingTopic,sessionProposalResponse:a,sessionSettlementRequest:h},opts:{...n,publishMethod:"wc_approveSession"}})},this.sendResult=async e=>{const{id:t,topic:i,result:s,throwOnFailedPublish:r,encodeOpts:n,appLink:o}=e,a=bb(t,s);let c;const h=o&&typeof global?.Linking<"u";try{const e=h?ew:Qy;c=await this.client.core.crypto.encode(i,a,{...n||{},encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),e}let l,u;try{l=await this.client.core.history.get(i,t);const e=l.request;try{u=this.getTVFParams(t,e.params,s)}catch(e){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${e?.message}`)}}catch(e){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${t}) failed`),e}if(h){const e=Tw(o,i,c);await global.Linking.openURL(e,this.client.name)}else{const e=l.request.method,s=Ux[e].res;s.tvf={...u,correlationId:t},r?(s.internal={...s.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(i,c,s)):this.client.core.relayer.publish(i,c,s).catch((e=>this.client.logger.error(e)))}await this.client.core.history.resolve(a)},this.sendError=async e=>{const{id:t,topic:i,error:s,encodeOpts:r,rpcOpts:n,appLink:o}=e,a=vb(t,s);let c;const h=o&&typeof global?.Linking<"u";try{const e=h?ew:Qy;c=await this.client.core.crypto.encode(i,a,{...r||{},encoding:e})}catch(e){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),e}let l;try{l=await this.client.core.history.get(i,t)}catch(e){throw this.client.logger.error(`sendError() -> history.get(${i}, ${t}) failed`),e}if(h){const e=Tw(o,i,c);await global.Linking.openURL(e,this.client.name)}else{const e=l.request.method,t=n||Ux[e].res;this.client.core.relayer.publish(i,c,t)}await this.client.core.history.resolve(a)},this.cleanup=async()=>{const e=[],t=[];this.client.session.getAll().forEach((t=>{let i=!1;hy(t.expiry)&&(i=!0),this.client.core.crypto.keychain.has(t.topic)||(i=!0),i&&e.push(t.topic)})),this.client.proposal.getAll().forEach((e=>{hy(e.expiryTimestamp)&&t.push(e.id)})),await Promise.all([...e.map((e=>this.deleteSession({topic:e}))),...t.map((e=>this.deleteProposal(e)))])},this.onProviderMessageEvent=async e=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(e):await this.onRelayMessage(e)},this.onRelayEventRequest=async e=>{this.requestQueue.queue.push(e),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state!==qx){for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=qx;const e=this.requestQueue.queue.shift();if(e)try{await this.processRequest(e)}catch(e){this.client.logger.warn(e)}}this.requestQueue.state=Lx}else this.client.logger.info("Request queue already active, skipping...")},this.processRequest=async e=>{const{topic:t,payload:i,attestation:s,transportType:r,encryptedId:n}=e,o=i.method;if(!this.shouldIgnorePairingRequest({topic:t,requestMethod:o}))switch(o){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:t,payload:i,attestation:s,encryptedId:n});case"wc_sessionSettle":return await this.onSessionSettleRequest(t,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(t,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(t,i);case"wc_sessionPing":return await this.onSessionPingRequest(t,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(t,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:t,payload:i,attestation:s,encryptedId:n,transportType:r});case"wc_sessionEvent":return await this.onSessionEventRequest(t,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:t,payload:i,attestation:s,encryptedId:n,transportType:r});default:return this.client.logger.info(`Unsupported request method ${o}`)}},this.onRelayEventResponse=async e=>{const{topic:t,payload:i,transportType:s}=e,r=(await this.client.core.history.get(t,i.id)).request.method;switch(r){case"wc_sessionPropose":return this.onSessionProposeResponse(t,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(t,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(t,i);case"wc_sessionExtend":return this.onSessionExtendResponse(t,i);case"wc_sessionPing":return this.onSessionPingResponse(t,i);case"wc_sessionRequest":return this.onSessionRequestResponse(t,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(t,i);default:return this.client.logger.info(`Unsupported response method ${r}`)}},this.onRelayEventUnknownPayload=e=>{const{topic:t}=e,{message:i}=zg("MISSING_OR_INVALID",`Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)},this.shouldIgnorePairingRequest=e=>{const{topic:t,requestMethod:i}=e,s=this.expectedPairingMethodMap.get(t);return!(!s||s.includes(i))&&!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async e=>{const{topic:t,payload:i,attestation:s,encryptedId:r}=e,{params:n,id:o}=i;try{const e=this.client.core.eventClient.getEvent({topic:t});0===this.client.events.listenerCount("session_proposal")&&(console.warn("No listener for session_proposal event"),e?.setError(qE)),this.isValidConnect({...i.params});const a={id:o,pairingTopic:t,expiryTimestamp:n.expiryTimestamp||cy(Ux.wc_sessionPropose.req.ttl),attestation:s,encryptedId:r,...n};await this.setProposal(o,a);const c=await this.getVerifyContext({attestationId:s,hash:uw(JSON.stringify(i)),encryptedId:r,metadata:a.proposer.metadata});e?.addTrace(RE),this.client.events.emit("session_proposal",{id:o,params:a,verifyContext:c})}catch(e){await this.sendError({id:o,topic:t,error:e,rpcOpts:Ux.wc_sessionPropose.autoReject}),this.client.logger.error(e)}},this.onSessionProposeResponse=async(e,t,i)=>{const{id:s}=t;if(Nb(t)){const{result:r}=t;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:r});const n=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:n});const o=n.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:o});const a=r.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:a});const c=await this.client.core.crypto.generateSharedKey(o,a);this.pendingSessions.set(s,{sessionTopic:c,pairingTopic:e,proposalId:s,publicKey:o});const h=await this.client.core.relayer.subscribe(c,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:e})}else if(Cb(t)){await this.deleteProposal(s);const e=ly("session_connect",s);if(0===this.events.listenerCount(e))throw new Error(`emitting ${e} without any listeners, 954`);this.events.emit(e,{error:t.error})}},this.onSessionSettleRequest=async(e,t)=>{const{id:i,params:s}=t;try{this.isValidSessionSettleRequest(s);const{relay:i,controller:r,expiry:n,namespaces:o,sessionProperties:a,scopedProperties:c,sessionConfig:h,proposalRequestsResponses:l}=t.params,u=[...this.pendingSessions.values()].find((t=>t.sessionTopic===e));if(!u)return this.client.logger.error(`Pending session not found for topic ${e}`);const d=this.client.proposal.get(u.proposalId),f={topic:e,relay:i,expiry:n,namespaces:o,acknowledged:!0,pairingTopic:u.pairingTopic,requiredNamespaces:d.requiredNamespaces,optionalNamespaces:d.optionalNamespaces,controller:r.publicKey,self:{publicKey:u.publicKey,metadata:this.client.metadata},peer:{publicKey:r.publicKey,metadata:r.metadata},...a&&{sessionProperties:a},...c&&{scopedProperties:c},...h&&{sessionConfig:h},transportType:Xv.relay,authentication:l?.authentication,walletPayResult:l?.walletPay};await this.client.session.set(f.topic,f),await this.setExpiry(f.topic,f.expiry),await this.client.core.pairing.updateMetadata({topic:u.pairingTopic,metadata:f.peer.metadata}),this.pendingSessions.delete(u.proposalId),this.deleteProposal(u.proposalId,!1),this.cleanupDuplicatePairings(f),await this.sendResult({id:t.id,topic:e,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:f}),this.events.emit(ly("session_connect",u.proposalId),{session:f})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionSettleResponse=async(e,t)=>{const{id:i}=t;Nb(t)?(await this.client.session.update(e,{acknowledged:!0}),this.events.emit(ly("session_approve",i),{})):Cb(t)&&(await this.deleteSession({topic:e,emitEvent:!1}),this.events.emit(ly("session_approve",i),{error:t.error}))},this.onSessionUpdateRequest=async(e,t)=>{const{params:i,id:s}=t;try{const t=`${e}_session_update`,r=sm.get(t);if(r&&this.isRequestOutOfSync(r,s))return this.client.logger.warn(`Discarding out of sync request - ${s}`),void this.sendError({id:s,topic:e,error:Fg("INVALID_UPDATE_REQUEST")});await this.isValidUpdate({topic:e,...i});const n=this.client.session.get(e);if(n.peer.publicKey!==n.controller)throw Fg("UNAUTHORIZED_UPDATE_REQUEST");try{sm.set(t,s),await this.client.session.update(e,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:e,result:!0})}catch(e){throw sm.delete(t),e}this.client.events.emit("session_update",{id:s,topic:e,params:i})}catch(t){await this.sendError({id:s,topic:e,error:t}),this.client.logger.error(t)}},this.isRequestOutOfSync=(e,t)=>t.toString().slice(0,-3)<e.toString().slice(0,-3),this.onSessionUpdateResponse=(e,t)=>{const{id:i}=t,s=ly("session_update",i);if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners`);Nb(t)?this.events.emit(ly("session_update",i),{}):Cb(t)&&this.events.emit(ly("session_update",i),{error:t.error})},this.onSessionExtendRequest=async(e,t)=>{const{id:i}=t;try{await this.isValidExtend({topic:e}),await this.setExpiry(e,cy(Cx)),await this.sendResult({id:i,topic:e,result:!0}),this.client.events.emit("session_extend",{id:i,topic:e})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionExtendResponse=(e,t)=>{const{id:i}=t,s=ly("session_extend",i);if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners`);Nb(t)?this.events.emit(ly("session_extend",i),{}):Cb(t)&&this.events.emit(ly("session_extend",i),{error:t.error})},this.onSessionPingRequest=async(e,t)=>{const{id:i}=t;try{this.isValidPing({topic:e}),await this.sendResult({id:i,topic:e,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:e})}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionPingResponse=(e,t)=>{const{id:i}=t,s=ly("session_ping",i);setTimeout((()=>{if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners 2176`);Nb(t)?this.events.emit(ly("session_ping",i),{}):Cb(t)&&this.events.emit(ly("session_ping",i),{error:t.error})}),500)},this.onSessionDeleteRequest=async(e,t)=>{const{id:i}=t;try{await this.isValidDisconnect({topic:e,reason:t.params}),this.cleanupPendingSentRequestsForTopic({topic:e,error:Fg("USER_DISCONNECTED")}),await this.deleteSession({topic:e,id:i})}catch(e){this.client.logger.error(e)}},this.onSessionRequest=async e=>{const{topic:t,payload:i,attestation:s,encryptedId:r,transportType:n}=e,{id:o,params:a}=i;try{await this.isValidRequest({topic:t,...a});const e=this.client.session.get(t),i={id:o,topic:t,params:a,verifyContext:await this.getVerifyContext({attestationId:s,hash:uw(JSON.stringify(mb("wc_sessionRequest",a,o))),encryptedId:r,metadata:e.peer.metadata,transportType:n})};await this.setPendingSessionRequest(i),n===Xv.link_mode&&e.peer.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(e.peer.metadata.redirect?.universal),this.client.signConfig?.disableRequestQueue?this.emitSessionRequest(i):(this.addSessionRequestToSessionRequestQueue(i),this.processSessionRequestQueue())}catch(e){await this.sendError({id:o,topic:t,error:e}),this.client.logger.error(e)}},this.onSessionRequestResponse=(e,t)=>{const{id:i}=t,s=ly("session_request",i);if(0===this.events.listenerCount(s))throw new Error(`emitting ${s} without any listeners`);Nb(t)?this.events.emit(ly("session_request",i),{result:t.result}):Cb(t)&&this.events.emit(ly("session_request",i),{error:t.error})},this.onSessionEventRequest=async(e,t)=>{const{id:i,params:s}=t;try{const t=`${e}_session_event_${s.event.name}`,r=sm.get(t);if(r&&this.isRequestOutOfSync(r,i))return void this.client.logger.info(`Discarding out of sync request - ${i}`);this.isValidEmit({topic:e,...s}),this.client.events.emit("session_event",{id:i,topic:e,params:s}),sm.set(t,i)}catch(t){await this.sendError({id:i,topic:e,error:t}),this.client.logger.error(t)}},this.onSessionAuthenticateResponse=(e,t)=>{const{id:i}=t;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:e,payload:t}),Nb(t)?this.events.emit(ly("session_request",i),{result:t.result}):Cb(t)&&this.events.emit(ly("session_request",i),{error:t.error})},this.onSessionAuthenticateRequest=async e=>{const{topic:t,payload:i,attestation:s,encryptedId:r,transportType:n}=e;try{const{requester:e,authPayload:o,expiryTimestamp:a}=i.params,c=await this.getVerifyContext({attestationId:s,hash:uw(JSON.stringify(i)),encryptedId:r,metadata:e.metadata,transportType:n}),h={requester:e,pairingTopic:t,id:i.id,authPayload:o,verifyContext:c,expiryTimestamp:a};await this.setAuthRequest(i.id,{request:h,pairingTopic:t,transportType:n}),n===Xv.link_mode&&e.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(e.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:t,params:i.params,id:i.id,verifyContext:c})}catch(e){this.client.logger.error(e);const s=i.params.requester.publicKey,r=await this.client.core.crypto.generateKeyPair(),o=this.getAppLinkIfEnabled(i.params.requester.metadata,n),a={type:sw,receiverPublicKey:s,senderPublicKey:r};await this.sendError({id:i.id,topic:t,error:e,encodeOpts:a,rpcOpts:Ux.wc_sessionAuthenticate.autoReject,appLink:o})}},this.addSessionRequestToSessionRequestQueue=e=>{this.sessionRequestQueue.queue.push(e)},this.cleanupAfterResponse=e=>{this.deletePendingSessionRequest(e.response.id,{message:"fulfilled",code:0}),setTimeout((()=>{this.sessionRequestQueue.state=Lx,this.processSessionRequestQueue()}),m.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:e,error:t})=>{const i=this.client.core.history.pending;i.length>0&&i.filter((t=>t.topic===e&&"wc_sessionRequest"===t.request.method)).forEach((e=>{this.events.emit(ly("session_request",e.request.id),{error:t})}))},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===qx)return void this.client.logger.info("session request queue is already active.");const e=this.sessionRequestQueue.queue[0];if(e)try{this.emitSessionRequest(e)}catch(e){this.client.logger.error(e)}else this.client.logger.info("session request queue is empty.")},this.emitSessionRequest=e=>{this.emittedSessionRequests.has(e.id)?this.client.logger.warn({id:e.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${e.id}`):(this.sessionRequestQueue.state=qx,this.emittedSessionRequests.add(e.id),this.client.events.emit("session_request",e))},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{const e=this.client.core.relayer.subscriber.topics;if(0===e.length)return;const t=new Set(this.client.session.keys),i=new Set(this.client.core.pairing.pairings.keys),s=new Set([...this.pendingSessions.values()].map((e=>e.sessionTopic)));let r;if(this.client.auth.authKeys.keys.includes(jx)){const{responseTopic:e}=this.client.auth.authKeys.get(jx);r=e}for(const n of e)if(!t.has(n)&&!i.has(n)&&!s.has(n)&&n!==r){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${n}`);try{await this.client.core.relayer.subscriber.unsubscribe(n)}catch(e){this.client.logger.warn(e,`Failed to clean up orphaned subscription: ${n}`)}}},this.onPairingCreated=e=>{if(e.methods&&this.expectedPairingMethodMap.set(e.topic,e.methods),e.active)return;const t=this.client.proposal.getAll().find((t=>t.pairingTopic===e.topic));t&&this.onSessionProposeRequest({topic:e.topic,payload:mb("wc_sessionPropose",{...t,requiredNamespaces:t.requiredNamespaces,optionalNamespaces:t.optionalNamespaces,relays:t.relays,proposer:t.proposer,sessionProperties:t.sessionProperties,scopedProperties:t.scopedProperties},t.id),attestation:t.attestation,encryptedId:t.encryptedId})},this.isValidConnect=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(e)}`);throw new Error(t)}const{pairingTopic:t,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:r,scopedProperties:n,relays:o}=e;if(Dw(t)||await this.isValidPairingTopic(t),!function(e,t){let i=!1;return t&&!e?i=!0:e&&Lw(e)&&e.length&&e.forEach((e=>{i=Ww(e)})),i}(o,!0)){const{message:e}=zg("MISSING_OR_INVALID",`connect() relays: ${o}`);throw new Error(e)}if(i&&!Dw(i)&&0!==qw(i)){const e="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(e):this.client.logger.warn(e),this.validateNamespaces(i,"requiredNamespaces")}if(s&&!Dw(s)&&0!==qw(s)&&this.validateNamespaces(s,"optionalNamespaces"),r&&!Dw(r)&&this.validateSessionProps(r,"sessionProperties"),n&&!Dw(n)){this.validateSessionProps(n,"scopedProperties");const e=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(n).every((t=>e.includes(t.split(":")[0]))))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(n)}, required/optional namespaces: ${JSON.stringify(e)}`)}},this.validateNamespaces=(e,t)=>{const i=function(e,t,i){let s=null;if(e&&qw(e)){const r=Vw(e,t);r&&(s=r);const n=Fw(e,t,i);n&&(s=n)}else s=zg("MISSING_OR_INVALID",`${t}, ${i} should be an object with data`);return s}(e,"connect()",t);if(i)throw new Error(i.message)},this.isValidApprove=async e=>{if(!Gw(e))throw new Error(zg("MISSING_OR_INVALID",`approve() params: ${e}`).message);const{id:t,namespaces:i,relayProtocol:s,sessionProperties:r,scopedProperties:n}=e;this.checkRecentlyDeleted(t),await this.isValidProposalId(t);const o=this.client.proposal.get(t),a=Hw(i,"approve()");if(a)throw new Error(a.message);const c=Jw(o.requiredNamespaces,i,"approve()");if(c)throw new Error(c.message);if(!Mw(s,!0)){const{message:e}=zg("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(e)}if(r&&!Dw(r)&&this.validateSessionProps(r,"sessionProperties"),n&&!Dw(n)){this.validateSessionProps(n,"scopedProperties");const e=new Set(Object.keys(i));if(!Object.keys(n).every((t=>e.has(t.split(":")[0]))))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(n)}, approved namespaces: ${Array.from(e).join(", ")}`)}},this.isValidReject=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`reject() params: ${e}`);throw new Error(t)}const{id:t,reason:i}=e;if(this.checkRecentlyDeleted(t),await this.isValidProposalId(t),!function(e){return!!(e&&"object"==typeof e&&e.code&&$w(e.code,!1)&&e.message&&Mw(e.message,!1))}(i)){const{message:e}=zg("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidSessionSettleRequest=e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${e}`);throw new Error(t)}const{relay:t,controller:i,namespaces:s,expiry:r}=e;if(!Ww(t)){const{message:e}=zg("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(e)}const n=function(e,t){let i=null;return Mw(e?.publicKey,!1)||(i=zg("MISSING_OR_INVALID",`${t} controller public key should be a string`)),i}(i,"onSessionSettleRequest()");if(n)throw new Error(n.message);const o=Hw(s,"onSessionSettleRequest()");if(o)throw new Error(o.message);if(hy(r)){const{message:e}=zg("EXPIRED","onSessionSettleRequest()");throw new Error(e)}},this.isValidUpdate=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`update() params: ${e}`);throw new Error(t)}const{topic:t,namespaces:i}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const s=this.client.session.get(t),r=Hw(i,"update()");if(r)throw new Error(r.message);const n=Jw(s.requiredNamespaces,i,"update()");if(n)throw new Error(n.message)},this.isValidExtend=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`extend() params: ${e}`);throw new Error(t)}const{topic:t}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t)},this.isValidRequest=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`request() params: ${e}`);throw new Error(t)}const{topic:t,request:i,chainId:s,expiry:r}=e;this.checkRecentlyDeleted(t),await this.isValidSessionTopic(t);const{namespaces:n}=this.client.session.get(t);if(!Yw(n,s)){const{message:e}=zg("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(e)}if(!function(e){return!(Dw(e)||!Mw(e.method,!1))}(i)){const{message:e}=zg("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(e)}if(!Zw(n,s,i.method)){const{message:e}=zg("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(e)}this.validateRequestExpiry(r)},this.isValidRespond=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`respond() params: ${e}`);throw new Error(t)}const{topic:t,response:i}=e;try{await this.isValidSessionTopic(t)}catch(t){throw e?.response?.id&&this.cleanupAfterResponse(e),t}if(!function(e){return!(Dw(e)||Dw(e.result)&&Dw(e.error)||!$w(e.id,!1)||!Mw(e.jsonrpc,!1))}(i)){const{message:e}=zg("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(i)}`);throw new Error(e)}const s=this.client.pendingRequest.get(i.id);if(s.topic!==t){const{message:e}=zg("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${i.id}, expected topic: ${s.topic}, received topic: ${t}`);throw new Error(e)}},this.isValidPing=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`ping() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidEmit=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`emit() params: ${e}`);throw new Error(t)}const{topic:t,event:i,chainId:s}=e;await this.isValidSessionTopic(t);const{namespaces:r}=this.client.session.get(t);if(!Yw(r,s)){const{message:e}=zg("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(e)}if(!function(e){return!(Dw(e)||!Mw(e.name,!1))}(i)){const{message:e}=zg("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(e)}if(!Xw(r,s,i.name)){const{message:e}=zg("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(e)}},this.isValidDisconnect=async e=>{if(!Gw(e)){const{message:t}=zg("MISSING_OR_INVALID",`disconnect() params: ${e}`);throw new Error(t)}const{topic:t}=e;await this.isValidSessionOrPairingTopic(t)},this.isValidAuthenticate=e=>{const{chains:t,uri:i,domain:s,nonce:r}=e;if(!Array.isArray(t)||0===t.length)throw new Error("chains is required and must be a non-empty array");if(!Mw(i,!1))throw new Error("uri is required parameter");if(!Mw(s,!1))throw new Error("domain is required parameter");if(!Mw(r,!1))throw new Error("nonce is required parameter");if([...new Set(t.map((e=>qg(e).namespace)))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:n}=qg(t[0]);if("eip155"!==n)throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async e=>{const{attestationId:t,hash:i,encryptedId:s,metadata:r,transportType:n}=e,o={verified:{verifyUrl:r.verifyUrl||bE,validation:"UNKNOWN",origin:r.url||""}};try{if(n===Xv.link_mode){const e=this.getAppLinkIfEnabled(r,n);return o.verified.validation=e&&new URL(e).origin===new URL(r.url).origin?"VALID":"INVALID",o}const e=await this.client.core.verify.resolve({attestationId:t,hash:i,encryptedId:s,verifyUrl:r.verifyUrl});e&&(o.verified.origin=e.origin,o.verified.isScam=e.isScam,o.verified.validation=e.origin===new URL(r.url).origin?"VALID":"INVALID")}catch(e){this.client.logger.warn(e)}return this.client.logger.debug(`Verify context: ${JSON.stringify(o)}`),o},this.validateSessionProps=(e,t)=>{Object.values(e).forEach(((i,s)=>{if(null==i){const{message:r}=zg("MISSING_OR_INVALID",`${t} must contain an existing value for each key. Received: ${i} for key ${Object.keys(e)[s]}`);throw new Error(r)}}))},this.getPendingAuthRequest=e=>{const t=this.client.auth.requests.get(e);return"object"==typeof t?t:void 0},this.addToRecentlyDeleted=(e,t)=>{if(this.recentlyDeletedMap.set(e,t),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let e=0;const t=this.recentlyDeletedLimit/2;for(const i of this.recentlyDeletedMap.keys()){if(e++>=t)break;this.recentlyDeletedMap.delete(i)}}},this.checkRecentlyDeleted=e=>{const t=this.recentlyDeletedMap.get(e);if(t){const{message:i}=zg("MISSING_OR_INVALID",`Record was recently deleted - ${t}: ${e}`);throw new Error(i)}},this.isLinkModeEnabled=(e,t)=>!(!e||t!==Xv.link_mode)&&(!0===this.client.metadata?.redirect?.linkMode&&void 0!==this.client.metadata?.redirect?.universal&&""!==this.client.metadata?.redirect?.universal&&void 0!==e?.redirect?.universal&&""!==e?.redirect?.universal&&!0===e?.redirect?.linkMode&&this.client.core.linkModeSupportedApps.includes(e.redirect.universal)&&typeof global?.Linking<"u"),this.getAppLinkIfEnabled=(e,t)=>this.isLinkModeEnabled(e,t)?e?.redirect?.universal:void 0,this.handleLinkModeMessage=({url:e})=>{if(!e||!e.includes("wc_ev")||!e.includes("topic"))return;const t=fy(e,"topic")||"",i=decodeURIComponent(fy(e,"wc_ev")||""),s=this.client.session.keys.includes(t);s&&this.client.session.update(t,{transportType:Xv.link_mode}),this.client.core.dispatchEnvelope({topic:t,message:i,sessionExists:s})},this.registerLinkModeListeners=async()=>{if(gy()||Gg()&&this.client.metadata.redirect?.linkMode){const e=global?.Linking;if(typeof e<"u"){e.addEventListener("url",this.handleLinkModeMessage,this.client.name);const t=await e.getInitialURL();t&&setTimeout((()=>{this.handleLinkModeMessage({url:t})}),50)}}},this.getTVFApproveParams=e=>{try{const t=Rw(e.namespaces),i=function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...e.methods)})),[...new Set(t)]}(e.namespaces),s=function(e){const t=[];return Object.values(e).forEach((e=>{t.push(...e.events)})),[...new Set(t)]}(e.namespaces),r=e.sessionProperties;return{approvedChains:t,approvedMethods:i,approvedEvents:s,sessionProperties:r,scopedProperties:e.scopedProperties}}catch(e){return this.client.logger.warn(e,"Error getting TVF approve params"),{}}},this.getTVFParams=(e,t,i)=>{if(!t.request?.method)return{};const s={correlationId:e,rpcMethods:[t.request.method],chainId:t.chainId};try{const e=this.extractTxHashesFromResult(t.request,i);s.txHashes=e,s.contractAddresses=this.isValidContractData(t.request.params)?[t.request.params?.[0]?.to]:[]}catch(e){this.client.logger.warn(e,"Error getting TVF params")}return s},this.isValidContractData=e=>{if(!e)return!1;try{const t=e?.data||e?.[0]?.data;if(!t.startsWith("0x"))return!1;const i=t.slice(2);return!!/^[0-9a-fA-F]*$/.test(i)&&i.length%2==0}catch{}return!1},this.extractTxHashesFromResult=(e,t)=>{try{if(!t)return[];const i=e.method,s=Dx[i];if("sui_signTransaction"===i)return[Sy(t.transactionBytes)];if("near_signTransaction"===i)return[Oy(t)];if("near_signTransactions"===i)return t.map((e=>Oy(e)));if("xrpl_signTransactionFor"===i||"xrpl_signTransaction"===i)return[t.tx_json?.hash];if("polkadot_signTransaction"===i)return[om({transaction:e.params.transactionPayload,signature:t.signature})];if("algo_signTxn"===i)return Lw(t)?t.map((e=>_y(e))):[_y(t)];if("cosmos_signDirect"===i)return[Py(t)];if("stellar_signXDR"===i)return[Uy(t.signedXDR,e.params?.chain)];if("wallet_sendCalls"===i)return function(e){const t=[];try{if("string"==typeof e)return t.push(e),t;if("object"!=typeof e)return t;e?.id&&t.push(e.id);const i=e?.capabilities?.caip345?.transactionHashes;i&&t.push(...i)}catch(e){console.warn("getWalletSendCallsHashes failed: ",e)}return t}(t);if("canton_prepareSignExecute"===i)return cm(e.params,t);if("string"==typeof t)return[t];const r=t[s.key];if(Lw(r))return"solana_signAllTransactions"===i?r.map((e=>function(e){const t=by(e),i=t[0];if(0===i)throw new Error("No signatures found");const s=1+64*i;if(t.length<s)throw new Error("Transaction data too short for claimed signature count");if(t.length<100)throw new Error("Transaction too short");const r=t.slice(1,65);return ro.encode(r)}(e))):r;if("string"==typeof r)return[r]}catch(e){this.client.logger.warn(e,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{const e=this.client.session.keys,t=this.client.core.relayer.messages.getWithoutAck(e);for(const[e,i]of Object.entries(t))for(const t of i)try{await this.onProviderMessageEvent({topic:e,message:t,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${e}, message: ${t}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=zg("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Mv,(e=>{this.onProviderMessageEvent(e)}))}async onRelayMessage(e){const{topic:t,message:i,attestation:s,transportType:r}=e,{publicKey:n}=this.client.auth.authKeys.keys.includes(jx)?this.client.auth.authKeys.get(jx):{publicKey:void 0};try{try{if(r!==Xv.link_mode&&this.client.core.crypto.getPayloadType(i,ew)===rw)return void this.client.logger.warn(`onRelayMessage() -> non-link mode TYPE_2 payload ignored: ${i}`)}catch{}const e=await this.client.core.crypto.decode(t,i,{receiverPublicKey:n,encoding:r===Xv.link_mode?ew:Qy});Bb(e)?(this.client.core.history.set(t,e),await this.onRelayEventRequest({topic:t,payload:e,attestation:s,transportType:r,encryptedId:uw(i)})):Rb(e)?(await this.client.core.history.resolve(e),await this.onRelayEventResponse({topic:t,payload:e,transportType:r}),this.client.core.history.delete(t,e.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(e)}`),await this.onRelayEventUnknownPayload({topic:t,payload:e,transportType:r})),await this.client.core.relayer.messages.ack(t,i)}catch(e){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(e?.message)}}registerExpirerEvents(){this.client.core.expirer.on(yE,(async e=>{const{topic:t,id:i}=ay(e.target);return i&&this.client.pendingRequest.keys.includes(i)?await this.deletePendingSessionRequest(i,zg("EXPIRED"),!0):i&&this.client.auth.requests.keys.includes(i)?await this.deletePendingAuthRequest(i,zg("EXPIRED"),!0):void(t?this.client.session.keys.includes(t)&&(await this.deleteSession({topic:t,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:t})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i})))}))}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",(async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(e){this.client.logger.warn(e)}finally{this.cleanupInProgress=!1}}}))}registerPairingEvents(){this.client.core.pairing.events.on(oE,(e=>this.onPairingCreated(e))),this.client.core.pairing.events.on(cE,(e=>{this.addToRecentlyDeleted(e.topic,"pairing")}))}isValidPairingTopic(e){if(!Mw(e,!1)){const{message:t}=zg("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(t)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:t}=zg("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(t)}if(hy(this.client.core.pairing.pairings.get(e).expiry)){const{message:t}=zg("EXPIRED",`pairing topic: ${e}`);throw new Error(t)}}async isValidSessionTopic(e){if(!Mw(e,!1)){const{message:t}=zg("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(t)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:t}=zg("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(t)}if(hy(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:t}=zg("EXPIRED",`session topic: ${e}`);throw new Error(t)}if(!this.client.core.crypto.keychain.has(e)){const{message:t}=zg("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(t)}}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)){if(Mw(e,!1)){const{message:t}=zg("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(t)}{const{message:t}=zg("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(t)}}this.isValidPairingTopic(e)}}async isValidProposalId(e){if("number"!=typeof e){const{message:t}=zg("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(t)}if(!this.client.proposal.keys.includes(e)){const{message:t}=zg("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(t)}if(hy(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:t}=zg("EXPIRED",`proposal id: ${e}`);throw new Error(t)}}validateRequestExpiry(e){if(e&&(i=kx,!($w(t=e,!1)&&t<=i.max&&t>=i.min))){const{message:t}=zg("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${kx.min} and ${kx.max}`);throw new Error(t)}var t,i}}class Fx extends bx{constructor(e,t){super(e,t,"proposal",Px),this.core=e,this.logger=t}}class Kx extends bx{constructor(e,t){super(e,t,"session",Px),this.core=e,this.logger=t}}class Vx extends bx{constructor(e,t){super(e,t,"request",Px,(e=>e.id)),this.core=e,this.logger=t}}class Hx extends bx{constructor(e,t){super(e,t,"authKeys",$x,(()=>jx)),this.core=e,this.logger=t}}class Wx extends bx{constructor(e,t){super(e,t,"pairingTopics",$x),this.core=e,this.logger=t}}class Gx extends bx{constructor(e,t){super(e,t,"requests",$x,(e=>e.id)),this.core=e,this.logger=t}}class Yx{constructor(e,t){this.core=e,this.logger=t,this.authKeys=new Hx(this.core,this.logger),this.pairingTopics=new Wx(this.core,this.logger),this.requests=new Gx(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}const Zx=class e extends ib{constructor(e){super(e),this.protocol="wc",this.version=2,this.name=Tx,this.events=new t,this.on=(e,t)=>this.events.on(e,t),this.once=(e,t)=>this.events.once(e,t),this.off=(e,t)=>this.events.off(e,t),this.removeListener=(e,t)=>this.events.removeListener(e,t),this.removeAllListeners=e=>this.events.removeAllListeners(e),this.connect=async e=>{try{return await this.engine.connect(e)}catch(e){throw this.logger.error(e.message),e}},this.pair=async e=>{try{return await this.engine.pair(e)}catch(e){throw this.logger.error(e.message),e}},this.approve=async e=>{try{return await this.engine.approve(e)}catch(e){throw this.logger.error(e.message),e}},this.reject=async e=>{try{return await this.engine.reject(e)}catch(e){throw this.logger.error(e.message),e}},this.update=async e=>{try{return await this.engine.update(e)}catch(e){throw this.logger.error(e.message),e}},this.extend=async e=>{try{return await this.engine.extend(e)}catch(e){throw this.logger.error(e.message),e}},this.request=async e=>{try{return await this.engine.request(e)}catch(e){throw this.logger.error(e.message),e}},this.respond=async e=>{try{return await this.engine.respond(e)}catch(e){throw this.logger.error(e.message),e}},this.ping=async e=>{try{return await this.engine.ping(e)}catch(e){throw this.logger.error(e.message),e}},this.emit=async e=>{try{return await this.engine.emit(e)}catch(e){throw this.logger.error(e.message),e}},this.disconnect=async e=>{try{return await this.engine.disconnect(e)}catch(e){throw this.logger.error(e.message),e}},this.find=e=>{try{return this.engine.find(e)}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.authenticate=async(e,t)=>{try{return console.warn("[WalletConnect] `authenticate` is deprecated and will be removed in a future release. Use `connect()`'s `authentication` instead to establish an authenticated session."),await this.engine.authenticate(e,t)}catch(e){throw this.logger.error(e.message),e}},this.formatAuthMessage=e=>{try{return this.engine.formatAuthMessage(e)}catch(e){throw this.logger.error(e.message),e}},this.approveSessionAuthenticate=async e=>{try{return await this.engine.approveSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}},this.rejectSessionAuthenticate=async e=>{try{return await this.engine.rejectSessionAuthenticate(e)}catch(e){throw this.logger.error(e.message),e}},this.name=e?.name||Tx,this.metadata=function(e){const t=Jg();try{return e?.url&&t.url&&new URL(e.url).host!==new URL(t.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${e.url} differs from the actual page url:${t.url}. This is probably unintended and can lead to issues.`),e.url=t.url),e?.icons?.length&&e.icons.length>0&&(e.icons=e.icons.filter((e=>""!==e))),{...t,...e,url:e?.url||t.url,name:e?.name||t.name,description:e?.description||t.description,icons:e?.icons?.length&&e.icons.length>0?e.icons:t.icons}}catch(i){return console.warn("Error populating app metadata",i),e||t}}(e?.metadata),this.signConfig=e?.signConfig;const i=hm({logger:e?.logger||Bx,name:this.name});this.logger=i,this.core=e?.core||new _x(e),this.session=new Kx(this.core,this.logger),this.proposal=new Fx(this.core,this.logger),this.pendingRequest=new Vx(this.core,this.logger),this.engine=new zx(this),this.auth=new Yx(this.core,this.logger)}static async init(t){const i=new e(t);return await i.initialize(),i}get context(){return Cg(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};var Xx=Object.defineProperty,Jx=Object.defineProperties,Qx=Object.getOwnPropertyDescriptors,eI=Object.getOwnPropertySymbols,tI=Object.prototype.hasOwnProperty,iI=Object.prototype.propertyIsEnumerable,sI=(e,t,i)=>t in e?Xx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,rI=(e,t)=>{for(var i in t||(t={}))tI.call(t,i)&&sI(e,i,t[i]);if(eI)for(var i of eI(t))iI.call(t,i)&&sI(e,i,t[i]);return e},nI=(e,t)=>Jx(e,Qx(t));const oI={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST"};class aI{constructor(e,i=!1){if(this.url=e,this.disableProviderPing=i,this.events=new t,this.isAvailable=!1,this.registering=!1,!_b(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=i}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}removeListener(e,t){this.events.removeListener(e,t)}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 t=Ul(e),i=await(await r(this.url,nI(rI({},oI),{body:t}))).json();this.onPayload({data:i})}catch(t){this.onError(e.id,t)}}async register(e=this.url){if(!_b(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const e=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=e||this.events.listenerCount("open")>=e)&&this.events.setMaxListeners(e+1),new Promise(((e,t)=>{this.events.once("register_error",(e=>{this.resetMaxListeners(),t(e)})),this.events.once("open",(()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return t(new Error("HTTP connection is missing or invalid"));e()}))}))}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const t=Ul({id:1,jsonrpc:"2.0",method:"test",params:[]});await r(e,nI(rI({},oI),{body:t}))}this.onOpen()}catch(e){const t=this.parseError(e);throw this.events.emit("register_error",t),this.onClose(),t}}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 t="string"==typeof e.data?Cl(e.data):e.data;this.events.emit("payload",t)}onError(e,t){const i=this.parseError(t),s=vb(e,i.message||i.toString());this.events.emit("payload",s)}parseError(e,t=this.url){return lb(e,t,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>10&&this.events.setMaxListeners(10)}}const cI="error",hI="universal_provider",lI=`wc@2:${hI}:`,uI="https://rpc.walletconnect.org/v1/",dI="generic",fI=`${uI}bundler`,pI="call_status",gI="default_chain_changed";function yI(e,t,i){const s=qg(e);return t.rpcMap?.[s.reference]||`${uI}?chainId=${s.namespace}:${s.reference}&projectId=${i}`}function wI(e){return e.map((e=>`${e.split(":")[0]}:${e.split(":")[1]}`))}function mI(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>t?.chains?.length&&t?.chains?.length>0)))}function bI(e={},t={}){return Bv(mI(vI(e)),mI(vI(t)))}function vI(e){const t={};if(!qw(e))return t;for(const[i,s]of Object.entries(e)){const e=Nw(i)?[i]:s.chains,r=s.methods||[],n=s.events||[],o=s.rpcMap||{},a=Cw(i);t[a]={...t[a],...s,chains:uy(e,t[a]?.chains),methods:uy(r,t[a]?.methods),events:uy(n,t[a]?.events)},(qw(o)||qw(t[a]?.rpcMap||{}))&&(t[a].rpcMap={...o,...t[a]?.rpcMap})}return t}function EI(e){return e.includes(":")?e.split(":")[2]:e}function xI(e){const t={};for(const[i,s]of Object.entries(e)){const e=s.methods||[],r=s.events||[],n=s.accounts||[],o=Nw(i)?[i]:s.chains?s.chains:wI(s.accounts);t[i]={chains:o,methods:e,events:r,accounts:n}}return t}function II(e){return"number"==typeof e?e:e.includes("0x")?parseInt(e,16):(e=e.includes(":")?e.split(":")[1]:e,isNaN(Number(e))?e:Number(e))}const SI={},OI=e=>SI[e],_I=(e,t)=>{SI[e]=t},AI="eip155",PI=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],TI=e=>e&&e.startsWith("0x")?BigInt(e).toString(10):e,BI=e=>e&&e.startsWith("0x")?e:`0x${BigInt(e).toString(16)}`,RI=e=>Object.keys(e).filter((e=>PI.includes(e))).reduce(((t,i)=>(t[i]=NI(e[i]),t)),{}),NI=e=>"string"==typeof e&&function(e){try{const t=JSON.parse(e);return"object"==typeof t&&null!==t&&!Array.isArray(t)}catch{return!1}}(e)?JSON.parse(e):e;let CI;class UI{constructor(e){this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,t){return await this.storage.setItem(e,t)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return CI||(CI=new UI(e)),CI}}async function kI(e,t){const i=qg(e.result.capabilities.caip345.caip2),s=e.result.capabilities.caip345.transactionHashes,r=await Promise.allSettled(s.map((e=>async function(e,t,i){return await i(parseInt(e)).request(mb("eth_getTransactionReceipt",[t]))}(i.reference,e,t)))),n=r.filter((e=>"fulfilled"===e.status)).map((e=>e.value)).filter((e=>e));r.filter((e=>"rejected"===e.status)).forEach((e=>console.warn("Failed to fetch transaction receipt:",e.reason)));const o=!n.length||n.some((e=>!e)),a=n.every((e=>"0x1"===e?.status)),c=n.every((e=>"0x0"===e?.status)),h=n.some((e=>"0x0"===e?.status));let l;return o?l=100:a?l=200:c?l=500:h&&(l=600),{id:e.result.id,version:e.request.version,atomic:e.request.atomicRequired,chainId:e.request.chainId,capabilities:e.result.capabilities,receipts:n,status:l}}async function LI({resultId:e,storage:t}){const i=(await t.getItem(pI))?.[e];if(i&&!hy(i.expiry))return i;await async function({resultId:e,storage:t}){const i=await t.getItem(pI);if(i){delete i[e],await t.setItem(pI,i);for(const e in i)hy(i[e].expiry)&&delete i[e];await t.setItem(pI,i)}}({resultId:e,storage:t})}class qI{constructor(e){this.name="eip155",this.namespace=e.namespace,this.events=OI("events"),this.client=OI("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=UI.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(parseInt(e),t);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(gI,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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,t){const i=t||yI(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ub(new aI(i,OI("disableProviderPing")))}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach((t=>{const i=parseInt(function(e){return e.includes(":")?e.split(":")[1]:e}(t));e[i]=this.createHttpProvider(i,this.namespace.rpcMap?.[t])})),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter((e=>e.split(":")[1]===this.chainId.toString())).map((e=>e.split(":")[2])))]:[]}getHttpProvider(e){const t=e||this.chainId;return this.httpProviders[t]||(this.httpProviders={...this.httpProviders,[t]:this.createHttpProvider(t)},this.httpProviders[t])}async handleSwitchChain(e){let t=e.request.params?e.request.params[0]?.chainId:"0x0";t=t.startsWith("0x")?t:`0x${t}`;const i=parseInt(t,16);if(this.isChainApproved(i))this.setDefaultChain(`${i}`);else{if(!this.namespace.methods.includes("wallet_switchEthereumChain"))throw new Error(`Failed to switch to chain 'eip155:${i}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:t}]},chainId:this.namespace.chains?.[0]}),this.setDefaultChain(`${i}`)}return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){const t=e.request?.params?.[0],i=e.request?.params?.[1]||[];if(!t)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const s=this.client.session.get(e.topic),r=s?.sessionProperties?.capabilities||{},n=`${t}${i.length>0?i.join(","):`0x${this.chainId.toString(16)}`}`,o=r?.[n];if(o)return o;let a;try{a=((e,t,i)=>{const{sessionProperties:s={},scopedProperties:r={}}=e,n={};if(!qw(r)&&!qw(s))return;const o=RI(s);for(const e of i){const i=TI(e);if(!i)continue;n[BI(i)]=o;const s=r?.[`${AI}:${i}`];if(s){const e=s?.[`${AI}:${i}:${t}`];n[BI(i)]={...n[BI(i)],...RI(e||s)}}}for(const[e,t]of Object.entries(n))0===Object.keys(t).length&&delete n[e];return Object.keys(n).length>0?n:void 0})(s,t,i)}catch(e){console.warn("Failed to extract capabilities from session",e)}if(a)return a;const c=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:{...s.sessionProperties||{},capabilities:{...r||{},[n]:c}}})}catch(e){console.warn("Failed to update session with capabilities",e)}return c}async getCallStatus(e){const t=this.client.session.get(e.topic),i=t.sessionProperties?.bundler_name;if(i){const t=this.getBundlerUrl(e.chainId,i);try{return await this.getUserOperationReceipt(t,e)}catch(e){console.warn("Failed to fetch call status from bundler",e,t)}}const s=t.sessionProperties?.bundler_url;if(s)try{return await this.getUserOperationReceipt(s,e)}catch(e){console.warn("Failed to fetch call status from custom bundler",e,s)}const r=await LI({resultId:e.request.params?.[0],storage:this.storage});if(r)try{return await kI(r,this.getHttpProvider.bind(this))}catch(e){console.warn("Failed to fetch call status from stored send calls",e,r)}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,t){const i=new URL(e),s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(mb("eth_getUserOperationReceipt",[t.request.params?.[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,t){return`${fI}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${t}`}async sendCalls(e){const t=await this.client.request(e),i=e.request.params?.[0],s=t?.id,r=t?.capabilities||{},n=r?.caip345?.caip2,o=r?.caip345?.transactionHashes;return!s||!n||!o?.length||await async function({sendCalls:e,storage:t}){const i=await t.getItem(pI);await t.setItem(pI,{...i,[e.result.id]:{request:e.request,result:e.result,expiry:cy(86400)}})}({sendCalls:{request:i,result:t},storage:this.storage}),t}}class DI{constructor(e){this.name=dI,this.namespace=e.namespace,this.events=OI("events"),this.client=OI("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,t){this.httpProviders[e]||this.setHttpProvider(e,t);const i=this.chainId;this.chainId=e,this.events.emit(gI,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return qg(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter((e=>e.split(":")[1]===this.chainId.toString())).map((e=>e.split(":")[2])))]:[]}createHttpProviders(){const e={};return this.namespace?.accounts?.forEach((t=>{const i=qg(t),s=this.namespace?.rpcMap?.[`${i.namespace}:${i.reference}`];e[i.reference]=this.createHttpProvider(t,s)})),e}getHttpProvider(e){const t=qg(e).reference,i=this.httpProviders[t];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,t){const i=this.createHttpProvider(e,t);i&&(this.httpProviders[e]=i)}createHttpProvider(e,t){const i=t||yI(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ub(new aI(i,OI("disableProviderPing")))}}const MI=class t{constructor(t){this.events=new e,this.rpcProviders={},this.disableProviderPing=!1,this.providerOpts=t,this.logger=hm({logger:t.logger??cI,name:this.providerOpts.name??hI}),this.disableProviderPing=t?.disableProviderPing||!1}static async init(e){const i=new t(e);return await i.initialize(),i}async request(e,t,i){const[s,r]=this.validateChain(t);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(s).request({request:{...e},chainId:`${s}:${r}`,topic:this.session.topic,expiry:i})}sendAsync(e,t,i,s){const r=(new Date).getTime();this.request(e,i,s).then((e=>t(null,bb(r,e)))).catch((e=>t(e,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(){if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:this.session?.topic,reason:Fg("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,t){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,t);i&&(this.uri=i,this.events.emit("display_uri",i));const r=await s();if(this.session=r.session,this.session){const e=xI(this.session.namespaces);this.namespaces=bI(this.namespaces,e),await this.persist("namespaces",this.namespaces),this.onConnect()}return r}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}removeListener(e,t){this.events.removeListener(e,t)}off(e,t){this.events.off(e,t)}get isWalletConnect(){return!0}async pair(e){const{uri:t,approval:i}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:this.connectParams?.authentication,walletPay:this.connectParams?.walletPay});t&&(this.uri=t,this.events.emit("display_uri",t));const s=await i();this.session=s;const r=xI(s.namespaces);return this.namespaces=bI(this.namespaces,r),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,t){try{if(!this.session)return;const[i,s]=this.validateChain(e),r=this.getProvider(i);r?r.setDefaultChain(s,t):this.session&&this.logger.warn(`Provider for namespace '${i}' not found in setDefaultChain`)}catch(e){if(!/Please call connect/.test(e.message))throw e}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const t=this.client.pairing.getAll();if(!Lw(t))return;for(const i of t)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: ${t.length}`)}catch(e){this.logger.warn(e,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){if(this.client=this.providerOpts.client||await Zx.init({core:this.providerOpts.core,logger:this.providerOpts.logger||cI,relayUrl:this.providerOpts.relayUrl||"wss://relay.walletconnect.org",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(e){throw this.logger.error(e,"Failed to get session"),new Error(`The provided session: ${this.providerOpts?.session?.topic} doesn't exist in the Sign client`)}else{const e=this.client.session.getAll();this.session=e[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((e=>Cw(e))))];_I("client",this.client),_I("events",this.events),_I("disableProviderPing",this.disableProviderPing),e.forEach((e=>{if(!this.session)return;const t=function(e,t){const i=Object.keys(t.namespaces).filter((t=>t.includes(e)));if(!i.length)return[];const s=[];return i.forEach((e=>{const i=t.namespaces[e].accounts;s.push(...i)})),s}(e,this.session);if(0===t?.length)return;const i=wI(t),s={...bI(this.namespaces,this.optionalNamespaces)[e],accounts:t,chains:i};if("eip155"===e)this.rpcProviders[e]=new qI({namespace:s});else this.rpcProviders[e]=new DI({namespace:s})}))}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",(e=>{const{topic:t}=e;t===this.session?.topic&&this.events.emit("session_ping",e)})),this.client.on("session_event",(e=>{const{params:t,topic:i}=e;if(i!==this.session?.topic)return;const{event:s}=t;if("accountsChanged"===s.name){const e=s.data;e&&Lw(e)&&this.events.emit("accountsChanged",e.map(EI))}else if("chainChanged"===s.name){const e=t.chainId,i=t.event.data,s=Cw(e),r=II(e)!==II(i)?`${s}:${II(i)}`:e;this.onChainChanged({currentCaipChainId:r})}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)})),this.client.on("session_update",(({topic:e,params:t})=>{if(e!==this.session?.topic)return;const{namespaces:i}=t,s=this.client?.session.get(e);this.session={...s,namespaces:i},this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:t})})),this.client.on("session_delete",(async e=>{e.topic===this.session?.topic&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",{...Fg("USER_DISCONNECTED"),data:e.topic}))})),this.on(gI,(e=>{this.onChainChanged({...e,internal:!0})}))}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[dI]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach((e=>{this.getProvider(e).updateNamespace(this.session?.namespaces[e])}))}setNamespaces(e){const{namespaces:t={},optionalNamespaces:i={},sessionProperties:s,scopedProperties:r}=e;this.optionalNamespaces=bI(t,i),this.sessionProperties=s,this.scopedProperties=r}validateChain(e){const[t,i]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[t,i];if(t&&!Object.keys(this.namespaces||{}).map((e=>Cw(e))).includes(t))throw new Error(`Namespace '${t}' is not configured. Please call connect() first with namespace config.`);if(t&&i)return[t,i];const s=Cw(Object.keys(this.namespaces)[0]);return[s,this.rpcProviders[s].getDefaultChain()]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:t,internal:i=!1}){if(!this.namespaces)return;const[s,r]=this.validateChain(e);if(r){if(this.updateNamespaceChain(s,r),i)this.events.emit("chainChanged",r),this.emitAccountsChangedOnChainChange({namespace:s,currentCaipChainId:e,previousCaipChainId:t});else{const e=this.getProvider(s);e?e.setDefaultChain(r):this.session&&this.logger.warn(`Provider for namespace '${s}' not found during chain change`)}await this.persist("namespaces",this.namespaces)}}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:t,previousCaipChainId:i}){try{if(i===t)return;const s=this.session?.namespaces[e]?.accounts;if(!s)return;const r=s.filter((e=>e.includes(`${t}:`))).map(EI);if(!Lw(r))return;this.events.emit("accountsChanged",r)}catch(e){this.logger.warn(e,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,t){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${t}`,s={chains:[],methods:[],events:[],defaultChain:t};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=t):this.namespaces[i]=s}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,t){const i=this.session?.topic||"";await this.client.core.storage.setItem(`${lI}/${e}${i}`,t)}async getFromStore(e){const t=this.session?.topic||"";return await this.client.core.storage.getItem(`${lI}/${e}${t}`)}async deleteFromStore(e){const t=this.session?.topic||"";await this.client.core.storage.removeItem(`${lI}/${e}${t}`)}async cleanupStorage(){try{if(this.client?.session.length>0)return;const e=await this.client.core.storage.getKeys();for(const t of e)t.startsWith(lI)&&await this.client.core.storage.removeItem(t)}catch(e){this.logger.warn(e,"Failed to cleanup storage")}}},$I=["eth_sendTransaction","personal_sign"],jI=["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"],zI=["chainChanged","accountsChanged"],FI=["chainChanged","accountsChanged","message","disconnect","connect"];function KI(e){return Number(e[0].split(":")[1])}function VI(e){return`0x${e.toString(16)}`}let HI=class e{constructor(){this.events=new t,this.namespace="eip155",this.accounts=[],this.chainId=1,this.STORAGE_KEY="wc@2:ethereum_provider:",this.on=(e,t)=>(this.events.on(e,t),this),this.once=(e,t)=>(this.events.once(e,t),this),this.removeListener=(e,t)=>(this.events.removeListener(e,t),this),this.off=(e,t)=>(this.events.off(e,t),this),this.parseAccount=e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e,this.signer={},this.rpc={}}static async init(t){const i=new e;return await i.initialize(t),i}async request(e,t){return await this.signer.request(e,this.formatChainId(this.chainId),t)}sendAsync(e,t,i){this.signer.sendAsync(e,t,this.formatChainId(this.chainId),i)}get connected(){return!!this.signer.client&&this.signer.client.core.relayer.connected}get connecting(){return!!this.signer.client&&this.signer.client.core.relayer.connecting}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:t,optional:i}=function(e){const{chains:t,optionalChains:i,methods:s,optionalMethods:r,events:n,optionalEvents:o,rpcMap:a}=e;if(!Lw(t))throw new Error("Invalid chains");const c={chains:t,methods:s||$I,events:n||zI,rpcMap:{...t.length?{[KI(t)]:a[KI(t)]}:{}}},h=n?.filter((e=>!zI.includes(e))),l=s?.filter((e=>!$I.includes(e)));if(!(i||o||r||h?.length||l?.length))return{required:t.length?c:void 0};const u={chains:[...new Set(h?.length&&l?.length||!i?c.chains.concat(i||[]):i)],methods:[...new Set(c.methods.concat(r?.length?r:jI))],events:[...new Set(c.events.concat(o?.length?o:FI))],rpcMap:a};return{required:t.length?c:void 0,optional:i.length?u:void 0}}(this.rpc);try{const s=await new Promise((async(s,r)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState((e=>{!e.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),r(new Error("Connection request reset. Please try again.")))})));const n=e?.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect({namespaces:{...t&&{[this.namespace]:t}},...i&&{optionalNamespaces:{[this.namespace]:i}},pairingTopic:e?.pairingTopic,scopedProperties:n}).then((e=>{s(e)})).catch((e=>{this.modal?.showErrorMessage("Unable to connect"),r(new Error(e.message))}))}));if(!s)return;const r=Dg(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:r),this.setAccounts(r),this.events.emit("connect",{chainId:VI(this.chainId)})}catch(e){throw this.signer.logger.error(e),e}finally{this.modal?.close()}}async authenticate(e,t){if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e?.chains});try{const i=await new Promise((async(i,s)=>{this.rpc.showQrModal&&(this.modal?.open(),this.modal?.subscribeState((e=>{!e.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),s(new Error("Connection request reset. Please try again.")))}))),await this.signer.authenticate({...e,chains:this.rpc.chains},t).then((e=>{i(e)})).catch((e=>{this.modal?.showErrorMessage("Unable to connect"),s(new Error(e.message))}))})),s=i.session;if(s){const e=Dg(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:e),this.setAccounts(e),this.events.emit("connect",{chainId:VI(this.chainId)})}return i}catch(e){throw this.signer.logger.error(e),e}finally{this.modal?.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:t}=e,{event:i}=t;"accountsChanged"===i.name?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):"chainChanged"===i.name?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 t=parseInt(e);this.chainId=t,this.events.emit("chainChanged",VI(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",{...Fg("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"string"==typeof e&&e.startsWith(`${this.namespace}:`)}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const t=e.filter((e=>this.isCompatibleChainId(e))).map((e=>this.parseChainId(e)));t.length&&(this.chainId=t[0],this.events.emit("chainChanged",VI(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const t=this.parseChainId(e);this.chainId=t,this.switchEthereumChain(t)}}parseAccountId(e){const[t,i,s]=e.split(":");return{chainId:`${t}:${i}`,address:s}}setAccounts(e){this.accounts=e.filter((e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId)).map((e=>this.parseAccountId(e).address)),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){const t=e?.chains??[],i=e?.optionalChains??[],s=t.concat(i);if(!s.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const r=t.length?e?.methods||$I:[],n=t.length?e?.events||zI:[],o=e?.optionalMethods||[],a=e?.optionalEvents||[],c=e?.rpcMap||this.buildRpcMap(s,e.projectId),h=e?.qrModalOptions||void 0;return{chains:t?.map((e=>this.formatChainId(e))),optionalChains:i.map((e=>this.formatChainId(e))),methods:r,events:n,optionalMethods:o,optionalEvents:a,rpcMap:c,showQrModal:!!e?.showQrModal,qrModalOptions:h,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,t){const i={};return e.forEach((e=>{i[e]=this.getRpcUrl(e,t)})),i}async initialize(e){if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?KI(this.rpc.chains):KI(this.rpc.optionalChains),this.signer=await MI.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 e;try{const t=await(async()=>{const{createAppKit:e}=await import("./core-4d7ad6f2.js").then((function(e){return e.ap}));return e})(),{convertWCMToAppKitOptions:i}=await Promise.resolve().then((function(){return XI})),s=i({...this.rpc.qrModalOptions,chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId});if(!s.networks.length)throw new Error("No networks found for WalletConnect");e=t({...s,universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:!0===this.rpc.qrModalOptions?.enableMobileFullScreen})}catch(e){throw console.warn(e),new Error("To use QR modal, please install @reown/appkit package")}if(e)try{this.modal=e}catch(e){throw this.signer.logger.error(e),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:t,optionalChains:i,rpcMap:s}=e;t&&Lw(t)&&(this.rpc.chains=t.map((e=>this.formatChainId(e))),t.forEach((e=>{this.rpc.rpcMap[e]=s?.[e]||this.getRpcUrl(e)}))),i&&Lw(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i?.map((e=>this.formatChainId(e))),i.forEach((e=>{this.rpc.rpcMap[e]=s?.[e]||this.getRpcUrl(e)})))}getRpcUrl(e,t){return this.rpc.rpcMap?.[e]||`https://rpc.walletconnect.org/v1/?chainId=eip155:${e}&projectId=${t||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),t=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:t?.accounts),this.setAccounts(t?.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch((e=>this.signer.logger.warn(e)))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return"string"==typeof e||e instanceof String?[this.parseAccount(e)]:e.map((e=>this.parseAccount(e)))}};const WI=HI;function GI(e){if(e)return{"--w3m-font-family":e["--wcm-font-family"],"--w3m-accent":e["--wcm-accent-color"],"--w3m-color-mix":e["--wcm-background-color"],"--w3m-z-index":e["--wcm-z-index"]?Number(e["--wcm-z-index"]):void 0,"--w3m-qr-color":e["--wcm-accent-color"],"--w3m-font-size-master":e["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":e["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const YI=e=>{const[t,i]=e.split(":");return ZI({id:i,caipNetworkId:e,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function ZI(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}var XI=Object.freeze({__proto__:null,convertWCMToAppKitOptions:function(e){const t=e.chains?.map(YI).filter(Boolean);if(0===t.length)throw new Error("At least one chain must be specified");const i=t.find((t=>t.id===e.defaultChain?.id)),s={projectId:e.projectId,networks:t,themeMode:e.themeMode,themeVariables:GI(e.themeVariables),chainImages:e.chainImages,connectorImages:e.walletImages,defaultNetwork:i,metadata:{...e.metadata,name:e.metadata?.name||"WalletConnect",description:e.metadata?.description||"Connect to WalletConnect-compatible wallets",url:e.metadata?.url||"https://walletconnect.org",icons:e.metadata?.icons||["https://walletconnect.org/walletconnect-logo.png"]},showWallets:!0,featuredWalletIds:"NONE"===e.explorerRecommendedWalletIds?[]:Array.isArray(e.explorerRecommendedWalletIds)?e.explorerRecommendedWalletIds:[],excludeWalletIds:"ALL"===e.explorerExcludedWalletIds?[]:Array.isArray(e.explorerExcludedWalletIds)?e.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if(e.mobileWallets?.length||e.desktopWallets?.length){const t=[...(e.mobileWallets||[]).map((e=>({id:e.id,name:e.name,links:e.links}))),...(e.desktopWallets||[]).map((e=>({id:e.id,name:e.name,links:{native:e.links.native,universal:e.links.universal}})))],i=[...s.featuredWalletIds||[],...s.excludeWalletIds||[]],r=t.filter((e=>!i.includes(e.id)));r.length&&(s.customWallets=r)}return s},defineChain:ZI}),JI=Object.freeze({__proto__:null,EthereumProvider:WI,OPTIONAL_EVENTS:FI,OPTIONAL_METHODS:jI,REQUIRED_EVENTS:zI,REQUIRED_METHODS:$I,default:HI});export{Bb as A,bb as B,Nb as C,yb as D,_b as E,JI as F,lm as I,WI as N,Ul as a,z as b,m as c,F as d,Un as e,qa as f,H as g,xn as h,hr as i,Dp as j,g as k,K as l,fo as m,Sb as n,mb as o,wb as p,Cb as q,fr as r,Cl as s,Da as t,Rb as u,Ab as v,db as w,Pb as x,vb as y,lb as z};