@dcl/landing-site 0.0.1-23657442558.commit-435eab3 → 0.0.1-23658354807.commit-e695ac8

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 (258) hide show
  1. package/assets/{AnimatedBackground-CYvnFuAP.js → AnimatedBackground-BH_AjnqQ.js} +2 -2
  2. package/assets/AnimatedBackground-BH_AjnqQ.js.map +1 -0
  3. package/assets/{CardMedia-Dn_1yf5f.js → CardMedia-CNDmKGwk.js} +1 -1
  4. package/assets/CardMedia-CNDmKGwk.js.map +1 -0
  5. package/assets/{FooterLanding-BYCeCiBr.js → FooterLanding-DYzI4pPY.js} +1 -1
  6. package/assets/FooterLanding-DYzI4pPY.js.map +1 -0
  7. package/assets/{LegalPageLayout-CA-MOUlJ.js → LegalPageLayout-Bmx2f7dQ.js} +1 -1
  8. package/assets/LegalPageLayout-Bmx2f7dQ.js.map +1 -0
  9. package/assets/{SignInRedirect-R0xh4Nh4.js → SignInRedirect-DFPVUUVg.js} +1 -1
  10. package/assets/SignInRedirect-DFPVUUVg.js.map +1 -0
  11. package/assets/{WearablePreview-BYZPTifP.js → WearablePreview-COzbSxYN.js} +1 -1
  12. package/assets/WearablePreview-COzbSxYN.js.map +1 -0
  13. package/assets/{add-DPiWnk4o.js → add-BczYlCv5.js} +1 -1
  14. package/assets/add-BczYlCv5.js.map +1 -0
  15. package/assets/{all-wallets-jWLRFgg8.js → all-wallets-WtFue3fI.js} +1 -1
  16. package/assets/all-wallets-WtFue3fI.js.map +1 -0
  17. package/assets/{app-store-IOQywyCL.js → app-store-BxZb_1M8.js} +1 -1
  18. package/assets/app-store-BxZb_1M8.js.map +1 -0
  19. package/assets/{apple-68JoH_5c.js → apple-CjT7RbME.js} +1 -1
  20. package/assets/apple-CjT7RbME.js.map +1 -0
  21. package/assets/{arrow-bottom-lG7X122r.js → arrow-bottom-4FmcypJQ.js} +1 -1
  22. package/assets/arrow-bottom-4FmcypJQ.js.map +1 -0
  23. package/assets/{arrow-bottom-circle-CRMqfqUN.js → arrow-bottom-circle-CXsF2I3S.js} +1 -1
  24. package/assets/arrow-bottom-circle-CXsF2I3S.js.map +1 -0
  25. package/assets/{arrow-left-Bv2jgvLH.js → arrow-left-BImXYn6U.js} +1 -1
  26. package/assets/arrow-left-BImXYn6U.js.map +1 -0
  27. package/assets/{arrow-right-CMrpY6jW.js → arrow-right-CHJc4WzS.js} +1 -1
  28. package/assets/arrow-right-CHJc4WzS.js.map +1 -0
  29. package/assets/{arrow-top-Cdg0S7uW.js → arrow-top-DovjH58u.js} +1 -1
  30. package/assets/arrow-top-DovjH58u.js.map +1 -0
  31. package/assets/{auto-track-D3wrsf3a.js → auto-track-LCtrzvEp.js} +1 -1
  32. package/assets/auto-track-LCtrzvEp.js.map +1 -0
  33. package/assets/{autoplay-DsVOy--c.js → autoplay-qioRTSgW.js} +1 -1
  34. package/assets/autoplay-qioRTSgW.js.map +1 -0
  35. package/assets/{bank-Y4ICxerj.js → bank-r0C0_RGk.js} +1 -1
  36. package/assets/bank-r0C0_RGk.js.map +1 -0
  37. package/assets/{basic-D7Il4b80.js → basic-DoZtdADf.js} +1 -1
  38. package/assets/basic-DoZtdADf.js.map +1 -0
  39. package/assets/{browser-DfLTrsKv.js → browser-CLFSxwU_.js} +1 -1
  40. package/assets/browser-CLFSxwU_.js.map +1 -0
  41. package/assets/{card-DRPjP4fT.js → card-gjAbVNVg.js} +1 -1
  42. package/assets/card-gjAbVNVg.js.map +1 -0
  43. package/assets/{ccip-BOoASBdu.js → ccip-Cs2-8_ok.js} +1 -1
  44. package/assets/ccip-Cs2-8_ok.js.map +1 -0
  45. package/assets/{checkmark-Cea2zEWd.js → checkmark-CgyA8OA7.js} +1 -1
  46. package/assets/checkmark-CgyA8OA7.js.map +1 -0
  47. package/assets/{checkmark-bold-d4-Fj-F3.js → checkmark-bold-CDzonXTF.js} +1 -1
  48. package/assets/checkmark-bold-CDzonXTF.js.map +1 -0
  49. package/assets/{chevron-bottom-DavJZ7N3.js → chevron-bottom-C5LFXYR3.js} +1 -1
  50. package/assets/chevron-bottom-C5LFXYR3.js.map +1 -0
  51. package/assets/{chevron-left-C_Hw8fus.js → chevron-left-Dl_DSL09.js} +1 -1
  52. package/assets/chevron-left-Dl_DSL09.js.map +1 -0
  53. package/assets/{chevron-right-DcNepqA3.js → chevron-right-B2iMupDM.js} +1 -1
  54. package/assets/chevron-right-B2iMupDM.js.map +1 -0
  55. package/assets/{chevron-top-DOnnhp0P.js → chevron-top-BRQrglLx.js} +1 -1
  56. package/assets/chevron-top-BRQrglLx.js.map +1 -0
  57. package/assets/{chrome-store-CgR-qlQ5.js → chrome-store-j0QHcvz5.js} +1 -1
  58. package/assets/chrome-store-j0QHcvz5.js.map +1 -0
  59. package/assets/{clock-Bo7xT59c.js → clock-DnqFpliA.js} +1 -1
  60. package/assets/clock-DnqFpliA.js.map +1 -0
  61. package/assets/{close-Bas20n3k.js → close-BW8HM0vc.js} +1 -1
  62. package/assets/close-BW8HM0vc.js.map +1 -0
  63. package/assets/{coinPlaceholder-zXo1UIaw.js → coinPlaceholder-D3Q_2Vnz.js} +1 -1
  64. package/assets/coinPlaceholder-D3Q_2Vnz.js.map +1 -0
  65. package/assets/{compass-YAtYlALr.js → compass-DQtQh5Fd.js} +1 -1
  66. package/assets/compass-DQtQh5Fd.js.map +1 -0
  67. package/assets/{copy-D5ojeU-9.js → copy-BqPAHBIq.js} +1 -1
  68. package/assets/copy-BqPAHBIq.js.map +1 -0
  69. package/assets/{core-CyswnR2y.js → core-DoE4v7_w.js} +5 -5
  70. package/assets/core-DoE4v7_w.js.map +1 -0
  71. package/assets/cursor-D7QROIqC.js +3 -0
  72. package/assets/cursor-D7QROIqC.js.map +1 -0
  73. package/assets/{cursor-transparent-BgE7Rtpz.js → cursor-transparent-I9qD1HcU.js} +1 -1
  74. package/assets/cursor-transparent-I9qD1HcU.js.map +1 -0
  75. package/assets/{desktop-BdAB2EC0.js → desktop-D06CYck7.js} +1 -1
  76. package/assets/desktop-D06CYck7.js.map +1 -0
  77. package/assets/{disconnect-DXF_VljU.js → disconnect-DuECek4L.js} +1 -1
  78. package/assets/disconnect-DuECek4L.js.map +1 -0
  79. package/assets/{discord-bfDqUOWC.js → discord-BXYIhoDM.js} +1 -1
  80. package/assets/discord-BXYIhoDM.js.map +1 -0
  81. package/assets/download-CLQcQusq.js +2 -0
  82. package/assets/download-CLQcQusq.js.map +1 -0
  83. package/assets/{download.types-DICgyaKG.js → download.types-DXNjUuQp.js} +1 -1
  84. package/assets/download.types-DXNjUuQp.js.map +1 -0
  85. package/assets/{etherscan-DQkLvBIy.js → etherscan-D8j2p5tH.js} +1 -1
  86. package/assets/etherscan-D8j2p5tH.js.map +1 -0
  87. package/assets/{exclamation-triangle-CUMF0W5Y.js → exclamation-triangle-BDd_YSmu.js} +1 -1
  88. package/assets/exclamation-triangle-BDd_YSmu.js.map +1 -0
  89. package/assets/{extension-DQP1ckZy.js → extension-cnEqQ1yY.js} +1 -1
  90. package/assets/extension-cnEqQ1yY.js.map +1 -0
  91. package/assets/{external-link-9Le-TzHn.js → external-link-CmFlcl7Y.js} +1 -1
  92. package/assets/external-link-CmFlcl7Y.js.map +1 -0
  93. package/assets/{facebook-CllxzjfU.js → facebook-BGz9ceDp.js} +1 -1
  94. package/assets/facebook-BGz9ceDp.js.map +1 -0
  95. package/assets/{farcaster-BFxjUxiI.js → farcaster-D4EbInUC.js} +1 -1
  96. package/assets/farcaster-D4EbInUC.js.map +1 -0
  97. package/assets/{filters-igKN7pRm.js → filters-U9zWe-dv.js} +1 -1
  98. package/assets/filters-U9zWe-dv.js.map +1 -0
  99. package/assets/{github-BuzRyr81.js → github-BwnJ4_Tw.js} +1 -1
  100. package/assets/github-BwnJ4_Tw.js.map +1 -0
  101. package/assets/{google-D536_SRJ.js → google-DFdfOlYV.js} +1 -1
  102. package/assets/google-DFdfOlYV.js.map +1 -0
  103. package/assets/{help-circle-BYUMAxgX.js → help-circle-ClDPGCNM.js} +1 -1
  104. package/assets/help-circle-ClDPGCNM.js.map +1 -0
  105. package/assets/hooks.module-Dz_XB4AG.js.map +1 -0
  106. package/assets/{id-IyoUNIG7.js → id-CVEEV5P3.js} +1 -1
  107. package/assets/id-CVEEV5P3.js.map +1 -0
  108. package/assets/{image-BMkCNBpN.js → image-B4kHWRvO.js} +1 -1
  109. package/assets/image-B4kHWRvO.js.map +1 -0
  110. package/assets/{index-DBS_df1P.js → index-BIiKvkqH.js} +2 -2
  111. package/assets/index-BIiKvkqH.js.map +1 -0
  112. package/assets/{index-DCm0cpWE.js → index-BSKH1f4F.js} +1 -1
  113. package/assets/index-BSKH1f4F.js.map +1 -0
  114. package/assets/{index-Csgvx0UQ.js → index-BwFdAxy9.js} +1 -1
  115. package/assets/index-BwFdAxy9.js.map +1 -0
  116. package/assets/{index-BgkGtQBL.js → index-C58cz8c7.js} +1 -1
  117. package/assets/index-C58cz8c7.js.map +1 -0
  118. package/assets/{index-BNs2v-1T.js → index-C8fM_5WQ.js} +1 -1
  119. package/assets/index-C8fM_5WQ.js.map +1 -0
  120. package/assets/{index-DZ4bDhA1.js → index-CCv7WeLP.js} +1 -1
  121. package/assets/index-CCv7WeLP.js.map +1 -0
  122. package/assets/{index-r18qw1mp.js → index-CEajtogo.js} +1 -1
  123. package/assets/index-CEajtogo.js.map +1 -0
  124. package/assets/{index-CwvhC3XY.js → index-CGCvheGi.js} +79 -79
  125. package/assets/index-CGCvheGi.js.map +1 -0
  126. package/assets/{index-BO3bzd2h.js → index-CP1V7_io.js} +1 -1
  127. package/assets/index-CP1V7_io.js.map +1 -0
  128. package/assets/{index-CSC9n2fJ.js → index-CkUgOBuZ.js} +2 -2
  129. package/assets/index-CkUgOBuZ.js.map +1 -0
  130. package/assets/{index-NgLnxYpy.js → index-Co5o4kNC.js} +2 -2
  131. package/assets/index-Co5o4kNC.js.map +1 -0
  132. package/assets/{index-BBPEbFlT.js → index-CvF9Rb56.js} +1 -1
  133. package/assets/index-CvF9Rb56.js.map +1 -0
  134. package/assets/{index-Bt2jXIjs.js → index-D6KjV6p4.js} +3 -3
  135. package/assets/index-D6KjV6p4.js.map +1 -0
  136. package/assets/index-D6ZMQedT.js.map +1 -0
  137. package/assets/{index-qaZMEqIj.js → index-D6_yiqF_.js} +3 -3
  138. package/assets/index-D6_yiqF_.js.map +1 -0
  139. package/assets/{index-DxORPjmW.js → index-DB4KxUK8.js} +1 -1
  140. package/assets/index-DB4KxUK8.js.map +1 -0
  141. package/assets/{index-D5mTl1Im.js → index-DLbfpB_l.js} +3 -3
  142. package/assets/index-DLbfpB_l.js.map +1 -0
  143. package/assets/{index-DrPYvtVf.js → index-DTEP60Z7.js} +1 -1
  144. package/assets/index-DTEP60Z7.js.map +1 -0
  145. package/assets/{index-CgaXTTOj.js → index-DiFn-Ues.js} +1 -1
  146. package/assets/index-DiFn-Ues.js.map +1 -0
  147. package/assets/{index-DoaGZy-D.js → index-DkC82Qq3.js} +1 -1
  148. package/assets/index-DkC82Qq3.js.map +1 -0
  149. package/assets/{index-DKN-aGC2.js → index-DoJrsvqV.js} +1 -1
  150. package/assets/index-DoJrsvqV.js.map +1 -0
  151. package/assets/index-Dr1-NFn7.js +1 -0
  152. package/assets/index-Dr1-NFn7.js.map +1 -0
  153. package/assets/{index-Bg_-jAf-.js → index-DrYqW_mc.js} +1 -1
  154. package/assets/index-DrYqW_mc.js.map +1 -0
  155. package/assets/{index-D7FErWQ6.js → index-Kl9lqIhB.js} +1 -1
  156. package/assets/index-Kl9lqIhB.js.map +1 -0
  157. package/assets/{index-BvPrP_kb.js → index-Pv7TzXSf.js} +1 -1
  158. package/assets/index-Pv7TzXSf.js.map +1 -0
  159. package/assets/{index-DsLpfqLF.js → index-cY16fPJ9.js} +1 -1
  160. package/assets/index-cY16fPJ9.js.map +1 -0
  161. package/assets/{index-2KYjUKrx.js → index-jmVkAn3V.js} +3 -3
  162. package/assets/index-jmVkAn3V.js.map +1 -0
  163. package/assets/{index-C_XR-pxH.js → index-jopxsqnB.js} +1 -1
  164. package/assets/index-jopxsqnB.js.map +1 -0
  165. package/assets/index-nibyPLVP.js.map +1 -0
  166. package/assets/index-wKfm7r6L.js +1 -0
  167. package/assets/index-wKfm7r6L.js.map +1 -0
  168. package/assets/{index.es-BlIlqooP.js → index.es-D_KVLw0o.js} +5 -5
  169. package/assets/index.es-D_KVLw0o.js.map +1 -0
  170. package/assets/{index.umd-C_QfsPJN.js → index.umd-CSluEYtT.js} +1 -1
  171. package/assets/index.umd-CSluEYtT.js.map +1 -0
  172. package/assets/{info-B9rpc1DX.js → info-D5-ExUNI.js} +1 -1
  173. package/assets/info-D5-ExUNI.js.map +1 -0
  174. package/assets/{info-circle-B44e-8gn.js → info-circle-C2XtIwRV.js} +1 -1
  175. package/assets/info-circle-C2XtIwRV.js.map +1 -0
  176. package/assets/inherits_browser-BlmhoU4v.js.map +1 -0
  177. package/assets/is-plan-event-enabled-DeNtQvA5.js.map +1 -0
  178. package/assets/{lightbulb-D7MIqKO0.js → lightbulb-EP-k9p0L.js} +1 -1
  179. package/assets/lightbulb-EP-k9p0L.js.map +1 -0
  180. package/assets/{mail-CskB2lNI.js → mail-CYWDw7sT.js} +1 -1
  181. package/assets/mail-CYWDw7sT.js.map +1 -0
  182. package/assets/{mobile-w7zP0tUZ.js → mobile-LnBG5WdG.js} +1 -1
  183. package/assets/mobile-LnBG5WdG.js.map +1 -0
  184. package/assets/{more-FviZA2zP.js → more-CUlRnsdE.js} +1 -1
  185. package/assets/more-CUlRnsdE.js.map +1 -0
  186. package/assets/{network-placeholder-CRkXjm2P.js → network-placeholder-DEFOwyXG.js} +1 -1
  187. package/assets/network-placeholder-DEFOwyXG.js.map +1 -0
  188. package/assets/{nftPlaceholder-CeAsWrId.js → nftPlaceholder-y8-2SfHh.js} +1 -1
  189. package/assets/nftPlaceholder-y8-2SfHh.js.map +1 -0
  190. package/assets/{node-CYxnN2Po.js → node-BquF0ZoL.js} +1 -1
  191. package/assets/node-BquF0ZoL.js.map +1 -0
  192. package/assets/{off-B7qKsRMs.js → off-Bmg2DJVN.js} +1 -1
  193. package/assets/off-Bmg2DJVN.js.map +1 -0
  194. package/assets/{play-store-DTGpFHme.js → play-store-BgYnKJZm.js} +1 -1
  195. package/assets/play-store-BgYnKJZm.js.map +1 -0
  196. package/assets/{plus-DEPzfy_x.js → plus-Bj7Zr4nz.js} +1 -1
  197. package/assets/plus-Bj7Zr4nz.js.map +1 -0
  198. package/assets/{qr-code-CB1fNk6g.js → qr-code-Dje5z7AJ.js} +1 -1
  199. package/assets/qr-code-Dje5z7AJ.js.map +1 -0
  200. package/assets/{recycle-horizontal-Czs62o1V.js → recycle-horizontal-L5-CFvVu.js} +1 -1
  201. package/assets/recycle-horizontal-L5-CFvVu.js.map +1 -0
  202. package/assets/{refresh-DP9sjRF6.js → refresh-B5s1b5Xw.js} +1 -1
  203. package/assets/refresh-B5s1b5Xw.js.map +1 -0
  204. package/assets/{reown-logo-Ba08IonY.js → reown-logo-CLdobzFm.js} +1 -1
  205. package/assets/reown-logo-CLdobzFm.js.map +1 -0
  206. package/assets/{search-DaZwjNzO.js → search-Bqfcdrxi.js} +1 -1
  207. package/assets/search-Bqfcdrxi.js.map +1 -0
  208. package/assets/{secp256k1-DBlGGLNL.js → secp256k1-C5qQ4FUv.js} +1 -1
  209. package/assets/secp256k1-C5qQ4FUv.js.map +1 -0
  210. package/assets/{secp256k1-_3IuN8n8.js → secp256k1-D6M1nsfk.js} +1 -1
  211. package/assets/secp256k1-D6M1nsfk.js.map +1 -0
  212. package/assets/{send-dd2TUNiX.js → send-DrmO9HIL.js} +1 -1
  213. package/assets/send-DrmO9HIL.js.map +1 -0
  214. package/assets/{swapHorizontal-DjuTXSNd.js → swapHorizontal-DSVKSSNs.js} +1 -1
  215. package/assets/swapHorizontal-DSVKSSNs.js.map +1 -0
  216. package/assets/{swapHorizontalBold-OeM0eWy3.js → swapHorizontalBold-ozFPFMxq.js} +1 -1
  217. package/assets/swapHorizontalBold-ozFPFMxq.js.map +1 -0
  218. package/assets/{swapHorizontalMedium-Dn43Ura8.js → swapHorizontalMedium-2AClXKVW.js} +1 -1
  219. package/assets/swapHorizontalMedium-2AClXKVW.js.map +1 -0
  220. package/assets/{swapHorizontalRoundedBold-ClMJXV_7.js → swapHorizontalRoundedBold-Dw--6duE.js} +1 -1
  221. package/assets/swapHorizontalRoundedBold-Dw--6duE.js.map +1 -0
  222. package/assets/{swapVertical-C1CBQj4F.js → swapVertical-CxFnK1UF.js} +1 -1
  223. package/assets/swapVertical-CxFnK1UF.js.map +1 -0
  224. package/assets/{swiper-react-DkRXQeaP.js → swiper-react-CrLD22Xk.js} +1 -1
  225. package/assets/swiper-react-CrLD22Xk.js.map +1 -0
  226. package/assets/{telegram-CUHvVcqJ.js → telegram-BmVZEQYk.js} +1 -1
  227. package/assets/telegram-BmVZEQYk.js.map +1 -0
  228. package/assets/{three-dots-B--1f-aJ.js → three-dots-BK6yc88b.js} +1 -1
  229. package/assets/three-dots-BK6yc88b.js.map +1 -0
  230. package/assets/{twitch-D5UR3bH_.js → twitch-CvA0WDHq.js} +1 -1
  231. package/assets/twitch-CvA0WDHq.js.map +1 -0
  232. package/assets/{twitterIcon-C4FaCE6I.js → twitterIcon-DYKNw1tz.js} +1 -1
  233. package/assets/twitterIcon-DYKNw1tz.js.map +1 -0
  234. package/assets/{useFormatMessage-BnXnxCX5.js → useFormatMessage-BfWgOhEa.js} +1 -1
  235. package/assets/useFormatMessage-BfWgOhEa.js.map +1 -0
  236. package/assets/{verify-CX6NFSd9.js → verify-eu0Y2qM8.js} +1 -1
  237. package/assets/verify-eu0Y2qM8.js.map +1 -0
  238. package/assets/{verify-filled-DZnZym2w.js → verify-filled-C_stgx5w.js} +1 -1
  239. package/assets/verify-filled-C_stgx5w.js.map +1 -0
  240. package/assets/{w3m-modal-C_X8MD6y.js → w3m-modal-CH0h68TV.js} +1 -1
  241. package/assets/w3m-modal-CH0h68TV.js.map +1 -0
  242. package/assets/{wallet-DQY7-bL-.js → wallet-Dx1z19Ro.js} +1 -1
  243. package/assets/wallet-Dx1z19Ro.js.map +1 -0
  244. package/assets/{wallet-placeholder-DFLdbuyq.js → wallet-placeholder-C4ASa1lL.js} +1 -1
  245. package/assets/wallet-placeholder-C4ASa1lL.js.map +1 -0
  246. package/assets/{walletconnect-CxDEJ_ge.js → walletconnect-b3lQy-21.js} +1 -1
  247. package/assets/walletconnect-b3lQy-21.js.map +1 -0
  248. package/assets/{warning-circle-CBjKcSTH.js → warning-circle-Byr0mazD.js} +1 -1
  249. package/assets/warning-circle-Byr0mazD.js.map +1 -0
  250. package/assets/{x-DlAP6FIW.js → x-BT7bQigU.js} +1 -1
  251. package/assets/x-BT7bQigU.js.map +1 -0
  252. package/index.html +4 -2
  253. package/landing_hero.webp +0 -0
  254. package/package.json +3 -3
  255. package/robots.txt +4 -0
  256. package/assets/cursor-Cxl4NS77.js +0 -3
  257. package/assets/download-B2bN5wzk.js +0 -2
  258. package/assets/index-D-85M8Ik.js +0 -1
@@ -1,8 +1,8 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-DBlGGLNL.js","assets/index-CwvhC3XY.js","assets/index.es-BlIlqooP.js","assets/index-nibyPLVP.js","assets/node-CYxnN2Po.js","assets/basic-D7Il4b80.js","assets/index-qaZMEqIj.js","assets/w3m-modal-C_X8MD6y.js"])))=>i.map(i=>d[i]);
2
- import{bF as _d,bG as Ad,bH as Sd,b5 as Pd,p as As,a4 as Od,a5 as Ye,g as Q,h as Ro,bb as Qi,aW as qa}from"./index-CwvhC3XY.js";import{d as en,s as wa,a as Pn,I as Yr,g as Td,c as D,f as Rt,t as wt,b as Br,e as pu,C as kd,h as xd,i as $d,j as vi,k as Uo,E as ct,y as At,l as ji,A as fu,m as Rd,B as ya,o as Ut,n as Ud,p as ba,q as va,r as Bn,u as Xr,v as Vs,P as Fa,Q as Dd,w as Ld,x as Tr,z as gu,D as cs,F as Yt,G as fs,H as Ht}from"./index.es-BlIlqooP.js";import{c as Md,g as Wa,s as Bd,d as jd,k as qd,a as Fd}from"./index-nibyPLVP.js";import{E as Wd,f as Hd}from"./node-CYxnN2Po.js";function Ha(t,e={}){const{key:s="fallback",name:r="Fallback",rank:i=!1,shouldThrow:n=zd,retryCount:o,retryDelay:a}=e;return({chain:c,pollingInterval:l=4e3,timeout:u,...h})=>{let d=t,p=()=>{};const w=_d({key:s,name:r,async request({method:m,params:f}){let y;const b=async(v=0)=>{const C=d[v]({...h,chain:c,retryCount:0,timeout:u});try{const S=await C.request({method:m,params:f});return p({method:m,params:f,response:S,transport:C,status:"success"}),S}catch(S){if(p({error:S,method:m,params:f,transport:C,status:"error"}),n(S)||v===d.length-1||(y??=d.slice(v+1).some(_=>{const{include:A,exclude:U}=_({chain:c}).config.methods||{};return A?A.includes(m):U?!U.includes(m):!0}),!y))throw S;return b(v+1)}};return b()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:m=>p=m,transports:d.map(m=>m({chain:c,retryCount:0}))});if(i){const m=typeof i=="object"?i:{};Vd({chain:c,interval:m.interval??l,onTransports:f=>d=f,ping:m.ping,sampleCount:m.sampleCount,timeout:m.timeout,transports:d,weights:m.weights})}return w}}function zd(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===Ad.code||t.code===Sd.code||Wd.nodeMessage.test(t.message)||t.code===5e3))}function Vd({chain:t,interval:e=4e3,onTransports:s,ping:r,sampleCount:i=10,timeout:n=1e3,transports:o,weights:a={}}){const{stability:c=.7,latency:l=.3}=a,u=[],h=async()=>{const d=await Promise.all(o.map(async m=>{const f=m({chain:t,retryCount:0,timeout:n}),y=Date.now();let b,v;try{await(r?r({transport:f}):f.request({method:"net_listening"})),v=1}catch{v=0}finally{b=Date.now()}return{latency:b-y,success:v}}));u.push(d),u.length>i&&u.shift();const p=Math.max(...u.map(m=>Math.max(...m.map(({latency:f})=>f)))),w=o.map((m,f)=>{const y=u.map(_=>_[f].latency),v=1-y.reduce((_,A)=>_+A,0)/y.length/p,C=u.map(_=>_[f].success),S=C.reduce((_,A)=>_+A,0)/C.length;return S===0?[0,f]:[l*v+c*S,f]}).sort((m,f)=>f[0]-m[0]);s(w.map(([,m])=>o[m])),await Pd(e),h()};h()}var za={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23657442558.commit-435eab3"};const j={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof As<"u"&&typeof za<"u"?za.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},mu={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(s=>s.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const s=t.find(i=>i.caipNetworkId===e);if(s)return s.name;const[r]=e.split(":");return j.CHAIN_NAME_MAP?.[r]||void 0}};var Kd=20,Gd=1,Ys=1e6,Va=1e6,Jd=-7,Yd=21,Xd=!1,qi="[big.js] ",rr=qi+"Invalid ",jn=rr+"decimal places",Zd=rr+"rounding mode",wu=qi+"Division by zero",me={},Qt=void 0,Qd=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function yu(){function t(e){var s=this;if(!(s instanceof t))return e===Qt?yu():new t(e);if(e instanceof t)s.s=e.s,s.e=e.e,s.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(rr+"value");e=e===0&&1/e<0?"-0":String(e)}ep(s,e)}s.constructor=t}return t.prototype=me,t.DP=Kd,t.RM=Gd,t.NE=Jd,t.PE=Yd,t.strict=Xd,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function ep(t,e){var s,r,i;if(!Qd.test(e))throw Error(rr+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(s=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(s<0&&(s=r),s+=+e.slice(r+1),e=e.substring(0,r)):s<0&&(s=e.length),i=e.length,r=0;r<i&&e.charAt(r)=="0";)++r;if(r==i)t.c=[t.e=0];else{for(;i>0&&e.charAt(--i)=="0";);for(t.e=s-r-1,t.c=[],s=0;r<=i;)t.c[s++]=+e.charAt(r++)}return t}function ir(t,e,s,r){var i=t.c;if(s===Qt&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(Zd);if(e<1)r=s===3&&(r||!!i[0])||e===0&&(s===1&&i[0]>=5||s===2&&(i[0]>5||i[0]===5&&(r||i[1]!==Qt))),i.length=1,r?(t.e=t.e-e+1,i[0]=1):i[0]=t.e=0;else if(e<i.length){if(r=s===1&&i[e]>=5||s===2&&(i[e]>5||i[e]===5&&(r||i[e+1]!==Qt||i[e-1]&1))||s===3&&(r||!!i[0]),i.length=e,r){for(;++i[--e]>9;)if(i[e]=0,e===0){++t.e,i.unshift(1);break}}for(e=i.length;!i[--e];)i.pop()}return t}function nr(t,e,s){var r=t.e,i=t.c.join(""),n=i.length;if(e)i=i.charAt(0)+(n>1?"."+i.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)i="0"+i;i="0."+i}else if(r>0)if(++r>n)for(r-=n;r--;)i+="0";else r<n&&(i=i.slice(0,r)+"."+i.slice(r));else n>1&&(i=i.charAt(0)+"."+i.slice(1));return t.s<0&&s?"-"+i:i}me.abs=function(){var t=new this.constructor(this);return t.s=1,t};me.cmp=function(t){var e,s=this,r=s.c,i=(t=new s.constructor(t)).c,n=s.s,o=t.s,a=s.e,c=t.e;if(!r[0]||!i[0])return r[0]?n:i[0]?-o:0;if(n!=o)return n;if(e=n<0,a!=c)return a>c^e?1:-1;for(o=(a=r.length)<(c=i.length)?a:c,n=-1;++n<o;)if(r[n]!=i[n])return r[n]>i[n]^e?1:-1;return a==c?0:a>c^e?1:-1};me.div=function(t){var e=this,s=e.constructor,r=e.c,i=(t=new s(t)).c,n=e.s==t.s?1:-1,o=s.DP;if(o!==~~o||o<0||o>Ys)throw Error(jn);if(!i[0])throw Error(wu);if(!r[0])return t.s=n,t.c=[t.e=0],t;var a,c,l,u,h,d=i.slice(),p=a=i.length,w=r.length,m=r.slice(0,a),f=m.length,y=t,b=y.c=[],v=0,C=o+(y.e=e.e-t.e)+1;for(y.s=n,n=C<0?0:C,d.unshift(0);f++<a;)m.push(0);do{for(l=0;l<10;l++){if(a!=(f=m.length))u=a>f?1:-1;else for(h=-1,u=0;++h<a;)if(i[h]!=m[h]){u=i[h]>m[h]?1:-1;break}if(u<0){for(c=f==a?i:d;f;){if(m[--f]<c[f]){for(h=f;h&&!m[--h];)m[h]=9;--m[h],m[f]+=10}m[f]-=c[f]}for(;!m[0];)m.shift()}else break}b[v++]=u?l:++l,m[0]&&u?m[f]=r[p]||0:m=[r[p]]}while((p++<w||m[0]!==Qt)&&n--);return!b[0]&&v!=1&&(b.shift(),y.e--,C--),v>C&&ir(y,C,s.RM,m[0]!==Qt),y};me.eq=function(t){return this.cmp(t)===0};me.gt=function(t){return this.cmp(t)>0};me.gte=function(t){return this.cmp(t)>-1};me.lt=function(t){return this.cmp(t)<0};me.lte=function(t){return this.cmp(t)<1};me.minus=me.sub=function(t){var e,s,r,i,n=this,o=n.constructor,a=n.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,n.plus(t);var l=n.c.slice(),u=n.e,h=t.c,d=t.e;if(!l[0]||!h[0])return h[0]?t.s=-c:l[0]?t=new o(n):t.s=1,t;if(a=u-d){for((i=a<0)?(a=-a,r=l):(d=u,r=h),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(s=((i=l.length<h.length)?l:h).length,a=c=0;c<s;c++)if(l[c]!=h[c]){i=l[c]<h[c];break}if(i&&(r=l,l=h,h=r,t.s=-t.s),(c=(s=h.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;s>a;){if(l[--s]<h[s]){for(e=s;e&&!l[--e];)l[e]=9;--l[e],l[s]+=10}l[s]-=h[s]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--d;return l[0]||(t.s=1,l=[d=0]),t.c=l,t.e=d,t};me.mod=function(t){var e,s=this,r=s.constructor,i=s.s,n=(t=new r(t)).s;if(!t.c[0])throw Error(wu);return s.s=t.s=1,e=t.cmp(s)==1,s.s=i,t.s=n,e?new r(s):(i=r.DP,n=r.RM,r.DP=r.RM=0,s=s.div(t),r.DP=i,r.RM=n,this.minus(s.times(t)))};me.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};me.plus=me.add=function(t){var e,s,r,i=this,n=i.constructor;if(t=new n(t),i.s!=t.s)return t.s=-t.s,i.minus(t);var o=i.e,a=i.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new n(i):t.s=i.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,r=l):(e=-e,r=a),r.reverse();e--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),e=l.length,s=0;e;a[e]%=10)s=(a[--e]=a[e]+l[e]+s)/10|0;for(s&&(a.unshift(s),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t};me.pow=function(t){var e=this,s=new e.constructor("1"),r=s,i=t<0;if(t!==~~t||t<-Va||t>Va)throw Error(rr+"exponent");for(i&&(t=-t);t&1&&(r=r.times(e)),t>>=1,!!t;)e=e.times(e);return i?s.div(r):r};me.prec=function(t,e){if(t!==~~t||t<1||t>Ys)throw Error(rr+"precision");return ir(new this.constructor(this),t,e)};me.round=function(t,e){if(t===Qt)t=0;else if(t!==~~t||t<-Ys||t>Ys)throw Error(jn);return ir(new this.constructor(this),t+this.e+1,e)};me.sqrt=function(){var t,e,s,r=this,i=r.constructor,n=r.s,o=r.e,a=new i("0.5");if(!r.c[0])return new i(r);if(n<0)throw Error(qi+"No square root");n=Math.sqrt(+nr(r,!0,!0)),n===0||n===1/0?(e=r.c.join(""),e.length+o&1||(e+="0"),n=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new i((n==1/0?"5e":(n=n.toExponential()).slice(0,n.indexOf("e")+1))+o)):t=new i(n+""),o=t.e+(i.DP+=4);do s=t,t=a.times(s.plus(r.div(s)));while(s.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return ir(t,(i.DP-=4)+t.e+1,i.RM)};me.times=me.mul=function(t){var e,s=this,r=s.constructor,i=s.c,n=(t=new r(t)).c,o=i.length,a=n.length,c=s.e,l=t.e;if(t.s=s.s==t.s?1:-1,!i[0]||!n[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=i,i=n,n=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+n[c]*i[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t};me.toExponential=function(t,e){var s=this,r=s.c[0];if(t!==Qt){if(t!==~~t||t<0||t>Ys)throw Error(jn);for(s=ir(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return nr(s,!0,!!r)};me.toFixed=function(t,e){var s=this,r=s.c[0];if(t!==Qt){if(t!==~~t||t<0||t>Ys)throw Error(jn);for(s=ir(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return nr(s,!1,!!r)};me[Symbol.for("nodejs.util.inspect.custom")]=me.toJSON=me.toString=function(){var t=this,e=t.constructor;return nr(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};me.toNumber=function(){var t=+nr(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(qi+"Imprecise conversion");return t};me.toPrecision=function(t,e){var s=this,r=s.constructor,i=s.c[0];if(t!==Qt){if(t!==~~t||t<1||t>Ys)throw Error(rr+"precision");for(s=ir(new r(s),t,e);s.c.length<t;)s.c.push(0)}return nr(s,t<=s.e||s.e<=r.NE||s.e>=r.PE,!!i)};me.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(qi+"valueOf disallowed");return nr(t,t.e<=e.NE||t.e>=e.PE,!0)};var ii=yu();const tp={bigNumber(t){return t?new ii(t):new ii(0)},multiply(t,e){if(t===void 0||e===void 0)return new ii(0);const s=new ii(t),r=new ii(e);return s.times(r)},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(t){return t===void 0?0:parseFloat(t.replace(/,/gu,""))}},sp=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],rp=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],ip=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],np={getERC20Abi:t=>j.USDT_CONTRACT_ADDRESSES.includes(t)?ip:sp,getSwapAbi:()=>rp},gs={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,r,i]=e;if(!s||!r||!i)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:r,address:i}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,r]=e;if(!s||!r)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:r}}},te={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections"};function eo(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Z={setItem(t,e){fi()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(fi())return localStorage.getItem(t)||void 0},removeItem(t){fi()&&localStorage.removeItem(t)},clear(){fi()&&localStorage.clear()}};function fi(){return typeof window<"u"&&typeof localStorage<"u"}function Ns(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const op=Symbol(),Ka=Object.getPrototypeOf,Do=new WeakMap,ap=t=>t&&(Do.has(t)?Do.get(t):Ka(t)===Object.prototype||Ka(t)===Array.prototype),cp=t=>ap(t)&&t[op]||null,Ga=(t,e=!0)=>{Do.set(t,e)};var On={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23657442558.commit-435eab3",VITE_REACT_APP_DCL_DEFAULT_ENV:"prod",BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23657442558.commit-435eab3",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const to=t=>typeof t=="object"&&t!==null,vs=new WeakMap,gi=new WeakSet,lp=(t=Object.is,e=(l,u)=>new Proxy(l,u),s=l=>to(l)&&!gi.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),r=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,n=(l,u,h=r)=>{const d=i.get(l);if(d?.[0]===u)return d[1];const p=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return Ga(p,!0),i.set(l,[u,p]),Reflect.ownKeys(l).forEach(w=>{if(Object.getOwnPropertyDescriptor(p,w))return;const m=Reflect.get(l,w),{enumerable:f}=Reflect.getOwnPropertyDescriptor(l,w),y={value:m,enumerable:f,configurable:!0};if(gi.has(m))Ga(m,!1);else if(m instanceof Promise)delete y.value,y.get=()=>h(m);else if(vs.has(m)){const[b,v]=vs.get(m);y.value=n(b,v(),h)}Object.defineProperty(p,w,y)}),Object.preventExtensions(p)},o=new WeakMap,a=[1,1],c=l=>{if(!to(l))throw new Error("object required");const u=o.get(l);if(u)return u;let h=a[0];const d=new Set,p=(E,$=++a[0])=>{h!==$&&(h=$,d.forEach(I=>I(E,$)))};let w=a[1];const m=(E=++a[1])=>(w!==E&&!d.size&&(w=E,y.forEach(([$])=>{const I=$[1](E);I>h&&(h=I)})),h),f=E=>($,I)=>{const L=[...$];L[1]=[E,...L[1]],p(L,I)},y=new Map,b=(E,$)=>{if((On?"production":void 0)!=="production"&&y.has(E))throw new Error("prop listener already exists");if(d.size){const I=$[3](f(E));y.set(E,[$,I])}else y.set(E,[$])},v=E=>{var $;const I=y.get(E);I&&(y.delete(E),($=I[1])==null||$.call(I))},C=E=>(d.add(E),d.size===1&&y.forEach(([I,L],z)=>{if((On?"production":void 0)!=="production"&&L)throw new Error("remove already exists");const N=I[3](f(z));y.set(z,[I,N])}),()=>{d.delete(E),d.size===0&&y.forEach(([I,L],z)=>{L&&(L(),y.set(z,[I]))})}),S=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),A=e(S,{deleteProperty(E,$){const I=Reflect.get(E,$);v($);const L=Reflect.deleteProperty(E,$);return L&&p(["delete",[$],I]),L},set(E,$,I,L){const z=Reflect.has(E,$),N=Reflect.get(E,$,L);if(z&&(t(N,I)||o.has(I)&&t(N,o.get(I))))return!0;v($),to(I)&&(I=cp(I)||I);let k=I;if(I instanceof Promise)I.then(O=>{I.status="fulfilled",I.value=O,p(["resolve",[$],O])}).catch(O=>{I.status="rejected",I.reason=O,p(["reject",[$],O])});else{!vs.has(I)&&s(I)&&(k=c(I));const O=!gi.has(k)&&vs.get(k);O&&b($,O)}return Reflect.set(E,$,k,L),p(["set",[$],I,N]),!0}});o.set(l,A);const U=[S,m,n,C];return vs.set(A,U),Reflect.ownKeys(l).forEach(E=>{const $=Object.getOwnPropertyDescriptor(l,E);"value"in $&&(A[E]=l[E],delete $.value,delete $.writable),Object.defineProperty(S,E,$)}),A})=>[c,vs,gi,t,e,s,r,i,n,o,a],[up]=lp();function Oe(t={}){return up(t)}function it(t,e,s){const r=vs.get(t);(On?"production":void 0)!=="production"&&!r&&console.warn("Please use proxy object");let i;const n=[],o=r[3];let a=!1;const l=o(u=>{n.push(u),i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(n.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Ti(t,e){const s=vs.get(t);(On?"production":void 0)!=="production"&&!s&&console.warn("Please use proxy object");const[r,i,n]=s;return n(r,i(),e)}function Xs(t){return gi.add(t),t}function nt(t,e,s,r){let i=t[e];return it(t,()=>{const n=t[e];Object.is(i,n)||s(i=n)})}function hp(t){const e=Oe({data:Array.from([]),has(s){return this.data.some(r=>r[0]===s)},set(s,r){const i=this.data.find(n=>n[0]===s);return i?i[1]=r:this.data.push([s,r]),this},get(s){var r;return(r=this.data.find(i=>i[0]===s))==null?void 0:r[1]},delete(s){const r=this.data.findIndex(i=>i[0]===s);return r===-1?!1:(this.data.splice(r,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)},forEach(s){this.data.forEach(r=>{s(r[1],r[0],this)})},keys(){return this.data.map(s=>s[0]).values()},values(){return this.data.map(s=>s[1]).values()},entries(){return new Map(this.data).entries()},get[Symbol.toStringTag](){return"Map"},[Symbol.iterator](){return this.entries()}});return Object.defineProperties(e,{data:{enumerable:!1},size:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(e),e}var Ja={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23657442558.commit-435eab3"};const so=(typeof As<"u"&&typeof Ja<"u"?Ja.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",bu=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],dp="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",Ie={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:so,SECURE_SITE_DASHBOARD:`${so}/dashboard`,SECURE_SITE_FAVICON:`${so}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:["eip155","solana"],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["coinbase","meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"}},W={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=W.getActiveNamespace(),e=W.getActiveCaipNetworkId(),s=e?e.split(":")[1]:void 0,r=s?isNaN(Number(s))?s:Number(s):void 0;return{namespace:t,caipNetworkId:e,chainId:r}},setWalletConnectDeepLink({name:t,href:e}){try{Z.setItem(te.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Z.getItem(te.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Z.removeItem(te.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Z.setItem(te.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Z.setItem(te.ACTIVE_CAIP_NETWORK_ID,t),W.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Z.getItem(te.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Z.removeItem(te.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=eo(t);Z.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=W.getRecentWallets();e.find(r=>r.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Z.setItem(te.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Z.getItem(te.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const s=eo(t);Z.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Z.getItem(te.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=eo(t);return Z.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",t)}},setConnectedSocialProvider(t){try{Z.setItem(te.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Z.getItem(te.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Z.removeItem(te.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Z.getItem(te.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Z.getItem(te.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{Z.setItem(te.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Z.getItem(te.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Z.getItem(te.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Z.setItem(te.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=W.getConnectedNamespaces();e.includes(t)||(e.push(t),W.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=W.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),W.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Z.getItem(te.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Z.setItem(te.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Z.removeItem(te.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Z.getItem(te.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=W.getBalanceCache();Z.setItem(te.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=W.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;W.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=W.getBalanceCache();e[t.caipAddress]=t,Z.setItem(te.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Z.getItem(te.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=W.getBalanceCache();Z.setItem(te.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const s=W.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),W.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=W.getNativeBalanceCache();e[t.caipAddress]=t,Z.setItem(te.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Z.getItem(te.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const s=W.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;W.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=W.getEnsCache();e[t.address]=t,Z.setItem(te.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=W.getEnsCache();Z.setItem(te.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Z.getItem(te.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=W.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;W.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=W.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Z.setItem(te.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=W.getIdentityCache();Z.setItem(te.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Z.removeItem(te.PORTFOLIO_CACHE),Z.removeItem(te.NATIVE_BALANCE_CACHE),Z.removeItem(te.ENS_CACHE),Z.removeItem(te.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Z.setItem(te.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Z.getItem(te.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s={...W.getConnections(),[e]:t};Z.setItem(te.CONNECTIONS,JSON.stringify(s))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=Z.getItem(te.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}}},X={isMobile(){return this.isClient()?!!(typeof window?.matchMedia=="function"&&window?.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return X.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=Ie.TEN_SEC_MS:!0},isAllowedRetry(t,e=Ie.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(X.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const s=new URL(t),r=new URL(e);return s.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Ie.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let s;return(...r)=>{function i(){t(...r)}s&&clearTimeout(s),s=setTimeout(i,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(X.isHttpUrl(t))return this.formatUniversalUrl(t,e);let r=t,i=s;r.includes("://")||(r=t.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const n=encodeURIComponent(e);return{redirect:`${r}wc?uri=${n}`,redirectUniversalLink:i?`${i}wc?uri=${n}`:void 0,href:r}},formatUniversalUrl(t,e){if(!X.isHttpUrl(t))return this.formatNativeUrl(t,e);let s=t;s.endsWith("/")||(s=`${s}/`);const r=encodeURIComponent(e);return{redirect:`${s}wc?uri=${r}`,href:s}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?W.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window.matchMedia?.("(display-mode: standalone)")?.matches,e=window?.navigator?.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,r)=>{const i=new Image;i.onload=s,i.onerror=r,i.crossOrigin="anonymous",i.src=t});return Promise.race([e,X.wait(2e3)])},formatBalance(t,e){let s="0.000";if(typeof t=="string"){const r=Number(t);if(r){const i=Math.floor(r*1e3)/1e3;i&&(s=i.toString())}}return`${s}${e?` ${e}`:""}`},formatBalance2(t,e){let s;if(t==="0")s="0";else if(typeof t=="string"){const r=Number(t);r&&(s=r.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}return{value:s??"0",rest:s==="0"?"000":"",symbol:e}},getApiUrl(){return j.W3M_API_URL},getBlockchainApiUrl(){return j.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return j.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const s={};return e&&t&&(t.forEach((r,i)=>{s[r]=i}),e.sort((r,i)=>{const n=s[r.id],o=s[i.id];return n!==void 0&&o!==void 0?n-o:n!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const s of t)e+=s.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[s,r]=e.split(".");return{dollars:s,pennies:r}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const s=new Set;return t.filter(r=>{const i=r[e];return s.has(i)?!1:(s.add(i),!0)})},generateSdkVersion(t,e,s){const i=t.length===0?Ie.ADAPTER_TYPES.UNIVERSAL:t.map(n=>n.adapterType).join(",");return`${e}-${i}-${s}`},createAccount(t,e,s,r,i){return{namespace:t,address:e,type:s,publicKey:r,path:i}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),s=e[0];return e.filter(Boolean).length===3&&s in j.CHAIN_NAME_MAP},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const i="provider_authorization_url=",n=t.substring(t.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(n),s,e);return t.replace(n,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const r=t.indexOf(e);if(r===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const i=t.indexOf("&",r),n=e.length,o=i!==-1?i:t.length,a=t.substring(0,r+n),c=t.substring(r+n,o),l=t.substring(i),u=c+s;return a+u+l}};async function ni(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class Fi{constructor({baseUrl:e,clientId:s}){this.baseUrl=e,this.clientId=s}async get({headers:e,signal:s,cache:r,...i}){const n=this.createUrl(i);return(await ni(n,{method:"GET",headers:e,signal:s,cache:r})).json()}async getBlob({headers:e,signal:s,...r}){const i=this.createUrl(r);return(await ni(i,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await ni(n,{method:"POST",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}async put({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await ni(n,{method:"PUT",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}async delete({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await ni(n,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}createUrl({path:e,params:s}){const r=new URL(e,this.baseUrl);return s&&Object.entries(s).forEach(([i,n])=>{n&&r.searchParams.append(i,n)}),this.clientId&&r.searchParams.append("clientId",this.clientId),r}}const pp={getFeatureValue(t,e){const s=e?.[t];return s===void 0?Ie.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(X.isTelegram()){if(X.isIos())return t.filter(e=>e!=="google");if(X.isMac())return t.filter(e=>e!=="x");if(X.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},K=Oe({features:Ie.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Ie.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),T={state:K,subscribeKey(t,e){return nt(K,t,e)},setOptions(t){Object.assign(K,t)},setRemoteFeatures(t){if(!t)return;const e={...K.remoteFeatures,...t};K.remoteFeatures=e,K.remoteFeatures?.socials&&(K.remoteFeatures.socials=pp.filterSocialsByPlatform(K.remoteFeatures.socials))},setFeatures(t){if(!t)return;K.features||(K.features=Ie.DEFAULT_FEATURES);const e={...K.features,...t};K.features=e},setProjectId(t){K.projectId=t},setCustomRpcUrls(t){K.customRpcUrls=t},setAllWallets(t){K.allWallets=t},setIncludeWalletIds(t){K.includeWalletIds=t},setExcludeWalletIds(t){K.excludeWalletIds=t},setFeaturedWalletIds(t){K.featuredWalletIds=t},setTokens(t){K.tokens=t},setTermsConditionsUrl(t){K.termsConditionsUrl=t},setPrivacyPolicyUrl(t){K.privacyPolicyUrl=t},setCustomWallets(t){K.customWallets=t},setIsSiweEnabled(t){K.isSiweEnabled=t},setIsUniversalProvider(t){K.isUniversalProvider=t},setSdkVersion(t){K.sdkVersion=t},setMetadata(t){K.metadata=t},setDisableAppend(t){K.disableAppend=t},setEIP6963Enabled(t){K.enableEIP6963=t},setDebug(t){K.debug=t},setEnableWalletConnect(t){K.enableWalletConnect=t},setEnableWalletGuide(t){K.enableWalletGuide=t},setEnableAuthLogger(t){K.enableAuthLogger=t},setEnableWallets(t){K.enableWallets=t},setPreferUniversalLinks(t){K.experimental_preferUniversalLinks=t},setHasMultipleAddresses(t){K.hasMultipleAddresses=t},setSIWX(t){K.siwx=t},setConnectMethodsOrder(t){K.features={...K.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){K.features={...K.features,walletFeaturesOrder:t}},setSocialsOrder(t){K.remoteFeatures={...K.remoteFeatures,socials:t}},setCollapseWallets(t){K.features={...K.features,collapseWallets:t}},setEnableEmbedded(t){K.enableEmbedded=t},setAllowUnsupportedChain(t){K.allowUnsupportedChain=t},setManualWCControl(t){K.manualWCControl=t},setEnableNetworkSwitch(t){K.enableNetworkSwitch=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(K.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){K.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return K.universalProviderConfigOverride},getSnapshot(){return Ti(K)}},fp=Object.freeze({enabled:!0,events:[]}),gp=new Fi({baseUrl:X.getAnalyticsUrl(),clientId:null}),mp=5,wp=60*1e3,ms=Oe({...fp}),yp={state:ms,subscribeKey(t,e){return nt(ms,t,e)},async sendError(t,e){if(!ms.enabled)return;const s=Date.now();if(ms.events.filter(n=>{const o=new Date(n.properties.timestamp||"").getTime();return s-o<wp}).length>=mp)return;const i={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};ms.events.push(i);try{if(typeof window>"u")return;const{projectId:n,sdkType:o,sdkVersion:a}=T.state;await gp.post({path:"/e",params:{projectId:n,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:X.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){ms.enabled=!0},disable(){ms.enabled=!1},clearEvents(){ms.events=[]}};class jr extends Error{constructor(e,s,r){super(e),this.name="AppKitError",this.category=s,this.originalError=r,Object.setPrototypeOf(this,jr.prototype);let i=!1;if(r instanceof Error&&typeof r.stack=="string"&&r.stack){const n=r.stack,o=n.indexOf(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/secp256k1-C5qQ4FUv.js","assets/index-CGCvheGi.js","assets/index.es-D_KVLw0o.js","assets/index-nibyPLVP.js","assets/node-BquF0ZoL.js","assets/basic-DoZtdADf.js","assets/index-D6_yiqF_.js","assets/w3m-modal-CH0h68TV.js"])))=>i.map(i=>d[i]);
2
+ import{bO as _d,bP as Ad,bQ as Sd,bh as Pd,p as As,ag as Od,ah as Ye,g as Q,h as Ro,bn as Qi,b6 as qa}from"./index-CGCvheGi.js";import{d as en,s as wa,a as Pn,I as Yr,g as Td,c as D,f as Rt,t as wt,b as Br,e as pu,C as kd,h as xd,i as $d,j as vi,k as Uo,E as ct,y as At,l as ji,A as fu,m as Rd,B as ya,o as Ut,n as Ud,p as ba,q as va,r as Bn,u as Xr,v as Vs,P as Fa,Q as Dd,w as Ld,x as Tr,z as gu,D as cs,F as Yt,G as fs,H as Ht}from"./index.es-D_KVLw0o.js";import{c as Md,g as Wa,s as Bd,d as jd,k as qd,a as Fd}from"./index-nibyPLVP.js";import{E as Wd,f as Hd}from"./node-BquF0ZoL.js";function Ha(t,e={}){const{key:s="fallback",name:r="Fallback",rank:i=!1,shouldThrow:n=zd,retryCount:o,retryDelay:a}=e;return({chain:c,pollingInterval:l=4e3,timeout:u,...h})=>{let d=t,p=()=>{};const w=_d({key:s,name:r,async request({method:m,params:f}){let y;const b=async(v=0)=>{const C=d[v]({...h,chain:c,retryCount:0,timeout:u});try{const S=await C.request({method:m,params:f});return p({method:m,params:f,response:S,transport:C,status:"success"}),S}catch(S){if(p({error:S,method:m,params:f,transport:C,status:"error"}),n(S)||v===d.length-1||(y??=d.slice(v+1).some(_=>{const{include:A,exclude:U}=_({chain:c}).config.methods||{};return A?A.includes(m):U?!U.includes(m):!0}),!y))throw S;return b(v+1)}};return b()},retryCount:o,retryDelay:a,type:"fallback"},{onResponse:m=>p=m,transports:d.map(m=>m({chain:c,retryCount:0}))});if(i){const m=typeof i=="object"?i:{};Vd({chain:c,interval:m.interval??l,onTransports:f=>d=f,ping:m.ping,sampleCount:m.sampleCount,timeout:m.timeout,transports:d,weights:m.weights})}return w}}function zd(t){return!!("code"in t&&typeof t.code=="number"&&(t.code===Ad.code||t.code===Sd.code||Wd.nodeMessage.test(t.message)||t.code===5e3))}function Vd({chain:t,interval:e=4e3,onTransports:s,ping:r,sampleCount:i=10,timeout:n=1e3,transports:o,weights:a={}}){const{stability:c=.7,latency:l=.3}=a,u=[],h=async()=>{const d=await Promise.all(o.map(async m=>{const f=m({chain:t,retryCount:0,timeout:n}),y=Date.now();let b,v;try{await(r?r({transport:f}):f.request({method:"net_listening"})),v=1}catch{v=0}finally{b=Date.now()}return{latency:b-y,success:v}}));u.push(d),u.length>i&&u.shift();const p=Math.max(...u.map(m=>Math.max(...m.map(({latency:f})=>f)))),w=o.map((m,f)=>{const y=u.map(_=>_[f].latency),v=1-y.reduce((_,A)=>_+A,0)/y.length/p,C=u.map(_=>_[f].success),S=C.reduce((_,A)=>_+A,0)/C.length;return S===0?[0,f]:[l*v+c*S,f]}).sort((m,f)=>f[0]-m[0]);s(w.map(([,m])=>o[m])),await Pd(e),h()};h()}var za={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23658354807.commit-e695ac8"};const j={WC_NAME_SUFFIX:".reown.id",WC_NAME_SUFFIX_LEGACY:".wcn.id",BLOCKCHAIN_API_RPC_URL:"https://rpc.walletconnect.org",PULSE_API_URL:"https://pulse.walletconnect.org",W3M_API_URL:"https://api.web3modal.org",CONNECTOR_ID:{WALLET_CONNECT:"walletConnect",INJECTED:"injected",WALLET_STANDARD:"announced",COINBASE:"coinbaseWallet",COINBASE_SDK:"coinbaseWalletSDK",SAFE:"safe",LEDGER:"ledger",OKX:"okx",EIP6963:"eip6963",AUTH:"ID_AUTH"},CONNECTOR_NAMES:{AUTH:"Auth"},AUTH_CONNECTOR_SUPPORTED_CHAINS:["eip155","solana"],LIMITS:{PENDING_TRANSACTIONS:99},CHAIN:{EVM:"eip155",SOLANA:"solana",POLKADOT:"polkadot",BITCOIN:"bip122"},CHAIN_NAME_MAP:{eip155:"EVM Networks",solana:"Solana",polkadot:"Polkadot",bip122:"Bitcoin",cosmos:"Cosmos"},ADAPTER_TYPES:{BITCOIN:"bitcoin",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5"},USDT_CONTRACT_ADDRESSES:["0xdac17f958d2ee523a2206206994597c13d831ec7","0xc2132d05d31c914a87c6611c10748aeb04b58e8f","0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7","0x919C1c267BC06a7039e03fcc2eF738525769109c","0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e","0x55d398326f99059fF775485246999027B3197955","0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9"],HTTP_STATUS_CODES:{SERVICE_UNAVAILABLE:503,FORBIDDEN:403},UNSUPPORTED_NETWORK_NAME:"Unknown Network",SECURE_SITE_SDK_ORIGIN:(typeof As<"u"&&typeof za<"u"?za.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org"},mu={caipNetworkIdToNumber(t){return t?Number(t.split(":")[1]):void 0},parseEvmChainId(t){return typeof t=="string"?this.caipNetworkIdToNumber(t):t},getNetworksByNamespace(t,e){return t?.filter(s=>s.chainNamespace===e)||[]},getFirstNetworkByNamespace(t,e){return this.getNetworksByNamespace(t,e)[0]},getNetworkNameByCaipNetworkId(t,e){if(!e)return;const s=t.find(i=>i.caipNetworkId===e);if(s)return s.name;const[r]=e.split(":");return j.CHAIN_NAME_MAP?.[r]||void 0}};var Kd=20,Gd=1,Ys=1e6,Va=1e6,Jd=-7,Yd=21,Xd=!1,qi="[big.js] ",rr=qi+"Invalid ",jn=rr+"decimal places",Zd=rr+"rounding mode",wu=qi+"Division by zero",me={},Qt=void 0,Qd=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function yu(){function t(e){var s=this;if(!(s instanceof t))return e===Qt?yu():new t(e);if(e instanceof t)s.s=e.s,s.e=e.e,s.c=e.c.slice();else{if(typeof e!="string"){if(t.strict===!0&&typeof e!="bigint")throw TypeError(rr+"value");e=e===0&&1/e<0?"-0":String(e)}ep(s,e)}s.constructor=t}return t.prototype=me,t.DP=Kd,t.RM=Gd,t.NE=Jd,t.PE=Yd,t.strict=Xd,t.roundDown=0,t.roundHalfUp=1,t.roundHalfEven=2,t.roundUp=3,t}function ep(t,e){var s,r,i;if(!Qd.test(e))throw Error(rr+"number");for(t.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(s=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(s<0&&(s=r),s+=+e.slice(r+1),e=e.substring(0,r)):s<0&&(s=e.length),i=e.length,r=0;r<i&&e.charAt(r)=="0";)++r;if(r==i)t.c=[t.e=0];else{for(;i>0&&e.charAt(--i)=="0";);for(t.e=s-r-1,t.c=[],s=0;r<=i;)t.c[s++]=+e.charAt(r++)}return t}function ir(t,e,s,r){var i=t.c;if(s===Qt&&(s=t.constructor.RM),s!==0&&s!==1&&s!==2&&s!==3)throw Error(Zd);if(e<1)r=s===3&&(r||!!i[0])||e===0&&(s===1&&i[0]>=5||s===2&&(i[0]>5||i[0]===5&&(r||i[1]!==Qt))),i.length=1,r?(t.e=t.e-e+1,i[0]=1):i[0]=t.e=0;else if(e<i.length){if(r=s===1&&i[e]>=5||s===2&&(i[e]>5||i[e]===5&&(r||i[e+1]!==Qt||i[e-1]&1))||s===3&&(r||!!i[0]),i.length=e,r){for(;++i[--e]>9;)if(i[e]=0,e===0){++t.e,i.unshift(1);break}}for(e=i.length;!i[--e];)i.pop()}return t}function nr(t,e,s){var r=t.e,i=t.c.join(""),n=i.length;if(e)i=i.charAt(0)+(n>1?"."+i.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)i="0"+i;i="0."+i}else if(r>0)if(++r>n)for(r-=n;r--;)i+="0";else r<n&&(i=i.slice(0,r)+"."+i.slice(r));else n>1&&(i=i.charAt(0)+"."+i.slice(1));return t.s<0&&s?"-"+i:i}me.abs=function(){var t=new this.constructor(this);return t.s=1,t};me.cmp=function(t){var e,s=this,r=s.c,i=(t=new s.constructor(t)).c,n=s.s,o=t.s,a=s.e,c=t.e;if(!r[0]||!i[0])return r[0]?n:i[0]?-o:0;if(n!=o)return n;if(e=n<0,a!=c)return a>c^e?1:-1;for(o=(a=r.length)<(c=i.length)?a:c,n=-1;++n<o;)if(r[n]!=i[n])return r[n]>i[n]^e?1:-1;return a==c?0:a>c^e?1:-1};me.div=function(t){var e=this,s=e.constructor,r=e.c,i=(t=new s(t)).c,n=e.s==t.s?1:-1,o=s.DP;if(o!==~~o||o<0||o>Ys)throw Error(jn);if(!i[0])throw Error(wu);if(!r[0])return t.s=n,t.c=[t.e=0],t;var a,c,l,u,h,d=i.slice(),p=a=i.length,w=r.length,m=r.slice(0,a),f=m.length,y=t,b=y.c=[],v=0,C=o+(y.e=e.e-t.e)+1;for(y.s=n,n=C<0?0:C,d.unshift(0);f++<a;)m.push(0);do{for(l=0;l<10;l++){if(a!=(f=m.length))u=a>f?1:-1;else for(h=-1,u=0;++h<a;)if(i[h]!=m[h]){u=i[h]>m[h]?1:-1;break}if(u<0){for(c=f==a?i:d;f;){if(m[--f]<c[f]){for(h=f;h&&!m[--h];)m[h]=9;--m[h],m[f]+=10}m[f]-=c[f]}for(;!m[0];)m.shift()}else break}b[v++]=u?l:++l,m[0]&&u?m[f]=r[p]||0:m=[r[p]]}while((p++<w||m[0]!==Qt)&&n--);return!b[0]&&v!=1&&(b.shift(),y.e--,C--),v>C&&ir(y,C,s.RM,m[0]!==Qt),y};me.eq=function(t){return this.cmp(t)===0};me.gt=function(t){return this.cmp(t)>0};me.gte=function(t){return this.cmp(t)>-1};me.lt=function(t){return this.cmp(t)<0};me.lte=function(t){return this.cmp(t)<1};me.minus=me.sub=function(t){var e,s,r,i,n=this,o=n.constructor,a=n.s,c=(t=new o(t)).s;if(a!=c)return t.s=-c,n.plus(t);var l=n.c.slice(),u=n.e,h=t.c,d=t.e;if(!l[0]||!h[0])return h[0]?t.s=-c:l[0]?t=new o(n):t.s=1,t;if(a=u-d){for((i=a<0)?(a=-a,r=l):(d=u,r=h),r.reverse(),c=a;c--;)r.push(0);r.reverse()}else for(s=((i=l.length<h.length)?l:h).length,a=c=0;c<s;c++)if(l[c]!=h[c]){i=l[c]<h[c];break}if(i&&(r=l,l=h,h=r,t.s=-t.s),(c=(s=h.length)-(e=l.length))>0)for(;c--;)l[e++]=0;for(c=e;s>a;){if(l[--s]<h[s]){for(e=s;e&&!l[--e];)l[e]=9;--l[e],l[s]+=10}l[s]-=h[s]}for(;l[--c]===0;)l.pop();for(;l[0]===0;)l.shift(),--d;return l[0]||(t.s=1,l=[d=0]),t.c=l,t.e=d,t};me.mod=function(t){var e,s=this,r=s.constructor,i=s.s,n=(t=new r(t)).s;if(!t.c[0])throw Error(wu);return s.s=t.s=1,e=t.cmp(s)==1,s.s=i,t.s=n,e?new r(s):(i=r.DP,n=r.RM,r.DP=r.RM=0,s=s.div(t),r.DP=i,r.RM=n,this.minus(s.times(t)))};me.neg=function(){var t=new this.constructor(this);return t.s=-t.s,t};me.plus=me.add=function(t){var e,s,r,i=this,n=i.constructor;if(t=new n(t),i.s!=t.s)return t.s=-t.s,i.minus(t);var o=i.e,a=i.c,c=t.e,l=t.c;if(!a[0]||!l[0])return l[0]||(a[0]?t=new n(i):t.s=i.s),t;if(a=a.slice(),e=o-c){for(e>0?(c=o,r=l):(e=-e,r=a),r.reverse();e--;)r.push(0);r.reverse()}for(a.length-l.length<0&&(r=l,l=a,a=r),e=l.length,s=0;e;a[e]%=10)s=(a[--e]=a[e]+l[e]+s)/10|0;for(s&&(a.unshift(s),++c),e=a.length;a[--e]===0;)a.pop();return t.c=a,t.e=c,t};me.pow=function(t){var e=this,s=new e.constructor("1"),r=s,i=t<0;if(t!==~~t||t<-Va||t>Va)throw Error(rr+"exponent");for(i&&(t=-t);t&1&&(r=r.times(e)),t>>=1,!!t;)e=e.times(e);return i?s.div(r):r};me.prec=function(t,e){if(t!==~~t||t<1||t>Ys)throw Error(rr+"precision");return ir(new this.constructor(this),t,e)};me.round=function(t,e){if(t===Qt)t=0;else if(t!==~~t||t<-Ys||t>Ys)throw Error(jn);return ir(new this.constructor(this),t+this.e+1,e)};me.sqrt=function(){var t,e,s,r=this,i=r.constructor,n=r.s,o=r.e,a=new i("0.5");if(!r.c[0])return new i(r);if(n<0)throw Error(qi+"No square root");n=Math.sqrt(+nr(r,!0,!0)),n===0||n===1/0?(e=r.c.join(""),e.length+o&1||(e+="0"),n=Math.sqrt(e),o=((o+1)/2|0)-(o<0||o&1),t=new i((n==1/0?"5e":(n=n.toExponential()).slice(0,n.indexOf("e")+1))+o)):t=new i(n+""),o=t.e+(i.DP+=4);do s=t,t=a.times(s.plus(r.div(s)));while(s.c.slice(0,o).join("")!==t.c.slice(0,o).join(""));return ir(t,(i.DP-=4)+t.e+1,i.RM)};me.times=me.mul=function(t){var e,s=this,r=s.constructor,i=s.c,n=(t=new r(t)).c,o=i.length,a=n.length,c=s.e,l=t.e;if(t.s=s.s==t.s?1:-1,!i[0]||!n[0])return t.c=[t.e=0],t;for(t.e=c+l,o<a&&(e=i,i=n,n=e,l=o,o=a,a=l),e=new Array(l=o+a);l--;)e[l]=0;for(c=a;c--;){for(a=0,l=o+c;l>c;)a=e[l]+n[c]*i[l-c-1]+a,e[l--]=a%10,a=a/10|0;e[l]=a}for(a?++t.e:e.shift(),c=e.length;!e[--c];)e.pop();return t.c=e,t};me.toExponential=function(t,e){var s=this,r=s.c[0];if(t!==Qt){if(t!==~~t||t<0||t>Ys)throw Error(jn);for(s=ir(new s.constructor(s),++t,e);s.c.length<t;)s.c.push(0)}return nr(s,!0,!!r)};me.toFixed=function(t,e){var s=this,r=s.c[0];if(t!==Qt){if(t!==~~t||t<0||t>Ys)throw Error(jn);for(s=ir(new s.constructor(s),t+s.e+1,e),t=t+s.e+1;s.c.length<t;)s.c.push(0)}return nr(s,!1,!!r)};me[Symbol.for("nodejs.util.inspect.custom")]=me.toJSON=me.toString=function(){var t=this,e=t.constructor;return nr(t,t.e<=e.NE||t.e>=e.PE,!!t.c[0])};me.toNumber=function(){var t=+nr(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(t.toString()))throw Error(qi+"Imprecise conversion");return t};me.toPrecision=function(t,e){var s=this,r=s.constructor,i=s.c[0];if(t!==Qt){if(t!==~~t||t<1||t>Ys)throw Error(rr+"precision");for(s=ir(new r(s),t,e);s.c.length<t;)s.c.push(0)}return nr(s,t<=s.e||s.e<=r.NE||s.e>=r.PE,!!i)};me.valueOf=function(){var t=this,e=t.constructor;if(e.strict===!0)throw Error(qi+"valueOf disallowed");return nr(t,t.e<=e.NE||t.e>=e.PE,!0)};var ii=yu();const tp={bigNumber(t){return t?new ii(t):new ii(0)},multiply(t,e){if(t===void 0||e===void 0)return new ii(0);const s=new ii(t),r=new ii(e);return s.times(r)},formatNumberToLocalString(t,e=2){return t===void 0?"0.00":typeof t=="number"?t.toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e}):parseFloat(t).toLocaleString("en-US",{maximumFractionDigits:e,minimumFractionDigits:e})},parseLocalStringToNumber(t){return t===void 0?0:parseFloat(t.replace(/,/gu,""))}},sp=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],rp=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{type:"bool"}]}],ip=[{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"sender",type:"address"},{name:"recipient",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]}],np={getERC20Abi:t=>j.USDT_CONTRACT_ADDRESSES.includes(t)?ip:sp,getSwapAbi:()=>rp},gs={validateCaipAddress(t){if(t.split(":")?.length!==3)throw new Error("Invalid CAIP Address");return t},parseCaipAddress(t){const e=t.split(":");if(e.length!==3)throw new Error(`Invalid CAIP-10 address: ${t}`);const[s,r,i]=e;if(!s||!r||!i)throw new Error(`Invalid CAIP-10 address: ${t}`);return{chainNamespace:s,chainId:r,address:i}},parseCaipNetworkId(t){const e=t.split(":");if(e.length!==2)throw new Error(`Invalid CAIP-2 network id: ${t}`);const[s,r]=e;if(!s||!r)throw new Error(`Invalid CAIP-2 network id: ${t}`);return{chainNamespace:s,chainId:r}}},te={WALLET_ID:"@appkit/wallet_id",WALLET_NAME:"@appkit/wallet_name",SOLANA_WALLET:"@appkit/solana_wallet",SOLANA_CAIP_CHAIN:"@appkit/solana_caip_chain",ACTIVE_CAIP_NETWORK_ID:"@appkit/active_caip_network_id",CONNECTED_SOCIAL:"@appkit/connected_social",CONNECTED_SOCIAL_USERNAME:"@appkit-wallet/SOCIAL_USERNAME",RECENT_WALLETS:"@appkit/recent_wallets",DEEPLINK_CHOICE:"WALLETCONNECT_DEEPLINK_CHOICE",ACTIVE_NAMESPACE:"@appkit/active_namespace",CONNECTED_NAMESPACES:"@appkit/connected_namespaces",CONNECTION_STATUS:"@appkit/connection_status",SIWX_AUTH_TOKEN:"@appkit/siwx-auth-token",SIWX_NONCE_TOKEN:"@appkit/siwx-nonce-token",TELEGRAM_SOCIAL_PROVIDER:"@appkit/social_provider",NATIVE_BALANCE_CACHE:"@appkit/native_balance_cache",PORTFOLIO_CACHE:"@appkit/portfolio_cache",ENS_CACHE:"@appkit/ens_cache",IDENTITY_CACHE:"@appkit/identity_cache",PREFERRED_ACCOUNT_TYPES:"@appkit/preferred_account_types",CONNECTIONS:"@appkit/connections"};function eo(t){if(!t)throw new Error("Namespace is required for CONNECTED_CONNECTOR_ID");return`@appkit/${t}:connected_connector_id`}const Z={setItem(t,e){fi()&&e!==void 0&&localStorage.setItem(t,e)},getItem(t){if(fi())return localStorage.getItem(t)||void 0},removeItem(t){fi()&&localStorage.removeItem(t)},clear(){fi()&&localStorage.clear()}};function fi(){return typeof window<"u"&&typeof localStorage<"u"}function Ns(t,e){return e==="light"?{"--w3m-accent":t?.["--w3m-accent"]||"hsla(231, 100%, 70%, 1)","--w3m-background":"#fff"}:{"--w3m-accent":t?.["--w3m-accent"]||"hsla(230, 100%, 67%, 1)","--w3m-background":"#121313"}}const op=Symbol(),Ka=Object.getPrototypeOf,Do=new WeakMap,ap=t=>t&&(Do.has(t)?Do.get(t):Ka(t)===Object.prototype||Ka(t)===Array.prototype),cp=t=>ap(t)&&t[op]||null,Ga=(t,e=!0)=>{Do.set(t,e)};var On={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23658354807.commit-e695ac8",VITE_REACT_APP_DCL_DEFAULT_ENV:"prod",BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23658354807.commit-e695ac8",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const to=t=>typeof t=="object"&&t!==null,vs=new WeakMap,gi=new WeakSet,lp=(t=Object.is,e=(l,u)=>new Proxy(l,u),s=l=>to(l)&&!gi.has(l)&&(Array.isArray(l)||!(Symbol.iterator in l))&&!(l instanceof WeakMap)&&!(l instanceof WeakSet)&&!(l instanceof Error)&&!(l instanceof Number)&&!(l instanceof Date)&&!(l instanceof String)&&!(l instanceof RegExp)&&!(l instanceof ArrayBuffer),r=l=>{switch(l.status){case"fulfilled":return l.value;case"rejected":throw l.reason;default:throw l}},i=new WeakMap,n=(l,u,h=r)=>{const d=i.get(l);if(d?.[0]===u)return d[1];const p=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l));return Ga(p,!0),i.set(l,[u,p]),Reflect.ownKeys(l).forEach(w=>{if(Object.getOwnPropertyDescriptor(p,w))return;const m=Reflect.get(l,w),{enumerable:f}=Reflect.getOwnPropertyDescriptor(l,w),y={value:m,enumerable:f,configurable:!0};if(gi.has(m))Ga(m,!1);else if(m instanceof Promise)delete y.value,y.get=()=>h(m);else if(vs.has(m)){const[b,v]=vs.get(m);y.value=n(b,v(),h)}Object.defineProperty(p,w,y)}),Object.preventExtensions(p)},o=new WeakMap,a=[1,1],c=l=>{if(!to(l))throw new Error("object required");const u=o.get(l);if(u)return u;let h=a[0];const d=new Set,p=(E,$=++a[0])=>{h!==$&&(h=$,d.forEach(I=>I(E,$)))};let w=a[1];const m=(E=++a[1])=>(w!==E&&!d.size&&(w=E,y.forEach(([$])=>{const I=$[1](E);I>h&&(h=I)})),h),f=E=>($,I)=>{const L=[...$];L[1]=[E,...L[1]],p(L,I)},y=new Map,b=(E,$)=>{if((On?"production":void 0)!=="production"&&y.has(E))throw new Error("prop listener already exists");if(d.size){const I=$[3](f(E));y.set(E,[$,I])}else y.set(E,[$])},v=E=>{var $;const I=y.get(E);I&&(y.delete(E),($=I[1])==null||$.call(I))},C=E=>(d.add(E),d.size===1&&y.forEach(([I,L],z)=>{if((On?"production":void 0)!=="production"&&L)throw new Error("remove already exists");const N=I[3](f(z));y.set(z,[I,N])}),()=>{d.delete(E),d.size===0&&y.forEach(([I,L],z)=>{L&&(L(),y.set(z,[I]))})}),S=Array.isArray(l)?[]:Object.create(Object.getPrototypeOf(l)),A=e(S,{deleteProperty(E,$){const I=Reflect.get(E,$);v($);const L=Reflect.deleteProperty(E,$);return L&&p(["delete",[$],I]),L},set(E,$,I,L){const z=Reflect.has(E,$),N=Reflect.get(E,$,L);if(z&&(t(N,I)||o.has(I)&&t(N,o.get(I))))return!0;v($),to(I)&&(I=cp(I)||I);let k=I;if(I instanceof Promise)I.then(O=>{I.status="fulfilled",I.value=O,p(["resolve",[$],O])}).catch(O=>{I.status="rejected",I.reason=O,p(["reject",[$],O])});else{!vs.has(I)&&s(I)&&(k=c(I));const O=!gi.has(k)&&vs.get(k);O&&b($,O)}return Reflect.set(E,$,k,L),p(["set",[$],I,N]),!0}});o.set(l,A);const U=[S,m,n,C];return vs.set(A,U),Reflect.ownKeys(l).forEach(E=>{const $=Object.getOwnPropertyDescriptor(l,E);"value"in $&&(A[E]=l[E],delete $.value,delete $.writable),Object.defineProperty(S,E,$)}),A})=>[c,vs,gi,t,e,s,r,i,n,o,a],[up]=lp();function Oe(t={}){return up(t)}function it(t,e,s){const r=vs.get(t);(On?"production":void 0)!=="production"&&!r&&console.warn("Please use proxy object");let i;const n=[],o=r[3];let a=!1;const l=o(u=>{n.push(u),i||(i=Promise.resolve().then(()=>{i=void 0,a&&e(n.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Ti(t,e){const s=vs.get(t);(On?"production":void 0)!=="production"&&!s&&console.warn("Please use proxy object");const[r,i,n]=s;return n(r,i(),e)}function Xs(t){return gi.add(t),t}function nt(t,e,s,r){let i=t[e];return it(t,()=>{const n=t[e];Object.is(i,n)||s(i=n)})}function hp(t){const e=Oe({data:Array.from([]),has(s){return this.data.some(r=>r[0]===s)},set(s,r){const i=this.data.find(n=>n[0]===s);return i?i[1]=r:this.data.push([s,r]),this},get(s){var r;return(r=this.data.find(i=>i[0]===s))==null?void 0:r[1]},delete(s){const r=this.data.findIndex(i=>i[0]===s);return r===-1?!1:(this.data.splice(r,1),!0)},clear(){this.data.splice(0)},get size(){return this.data.length},toJSON(){return new Map(this.data)},forEach(s){this.data.forEach(r=>{s(r[1],r[0],this)})},keys(){return this.data.map(s=>s[0]).values()},values(){return this.data.map(s=>s[1]).values()},entries(){return new Map(this.data).entries()},get[Symbol.toStringTag](){return"Map"},[Symbol.iterator](){return this.entries()}});return Object.defineProperties(e,{data:{enumerable:!1},size:{enumerable:!1},toJSON:{enumerable:!1}}),Object.seal(e),e}var Ja={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23658354807.commit-e695ac8"};const so=(typeof As<"u"&&typeof Ja<"u"?Ja.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",bu=[{label:"Coinbase",name:"coinbase",feeRange:"1-2%",url:"",supportedChains:["eip155"]},{label:"Meld.io",name:"meld",feeRange:"1-2%",url:"https://meldcrypto.com",supportedChains:["eip155","solana"]}],dp="WXETMuFUQmqqybHuRkSgxv:25B8LJHSfpG6LVjR2ytU5Cwh7Z4Sch2ocoU",Ie={FOUR_MINUTES_MS:24e4,TEN_SEC_MS:1e4,FIVE_SEC_MS:5e3,THREE_SEC_MS:3e3,ONE_SEC_MS:1e3,SECURE_SITE:so,SECURE_SITE_DASHBOARD:`${so}/dashboard`,SECURE_SITE_FAVICON:`${so}/images/favicon.png`,RESTRICTED_TIMEZONES:["ASIA/SHANGHAI","ASIA/URUMQI","ASIA/CHONGQING","ASIA/HARBIN","ASIA/KASHGAR","ASIA/MACAU","ASIA/HONG_KONG","ASIA/MACAO","ASIA/BEIJING","ASIA/HARBIN"],WC_COINBASE_PAY_SDK_CHAINS:["ethereum","arbitrum","polygon","berachain","avalanche-c-chain","optimism","celo","base"],WC_COINBASE_PAY_SDK_FALLBACK_CHAIN:"ethereum",WC_COINBASE_PAY_SDK_CHAIN_NAME_MAP:{Ethereum:"ethereum","Arbitrum One":"arbitrum",Polygon:"polygon",Berachain:"berachain",Avalanche:"avalanche-c-chain","OP Mainnet":"optimism",Celo:"celo",Base:"base"},WC_COINBASE_ONRAMP_APP_ID:"bf18c88d-495a-463b-b249-0b9d3656cf5e",SWAP_SUGGESTED_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP"],SWAP_POPULAR_TOKENS:["ETH","UNI","1INCH","AAVE","SOL","ADA","AVAX","DOT","LINK","NITRO","GAIA","MILK","TRX","NEAR","GNO","WBTC","DAI","WETH","USDC","USDT","ARB","BAL","BICO","CRV","ENS","MATIC","OP","METAL","DAI","CHAMP","WOLF","SALE","BAL","BUSD","MUST","BTCpx","ROUTE","HEX","WELT","amDAI","VSQ","VISION","AURUM","pSP","SNX","VC","LINK","CHP","amUSDT","SPHERE","FOX","GIDDY","GFC","OMEN","OX_OLD","DE","WNT"],BALANCE_SUPPORTED_CHAINS:["eip155","solana"],SWAP_SUPPORTED_NETWORKS:["eip155:1","eip155:42161","eip155:10","eip155:324","eip155:8453","eip155:56","eip155:137","eip155:100","eip155:43114","eip155:250","eip155:8217","eip155:1313161554"],NAMES_SUPPORTED_CHAIN_NAMESPACES:["eip155"],ONRAMP_SUPPORTED_CHAIN_NAMESPACES:["eip155","solana"],ACTIVITY_ENABLED_CHAIN_NAMESPACES:["eip155"],NATIVE_TOKEN_ADDRESS:{eip155:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",solana:"So11111111111111111111111111111111111111111",polkadot:"0x",bip122:"0x",cosmos:"0x"},CONVERT_SLIPPAGE_TOLERANCE:1,CONNECT_LABELS:{MOBILE:"Open and continue in the wallet app",WEB:"Open and continue in the wallet app"},SEND_SUPPORTED_NAMESPACES:["eip155","solana"],DEFAULT_REMOTE_FEATURES:{swaps:["1inch"],onramp:["coinbase","meld"],email:!0,socials:["google","x","discord","farcaster","github","apple","facebook"],activity:!0,reownBranding:!0},DEFAULT_REMOTE_FEATURES_DISABLED:{email:!1,socials:!1,swaps:!1,onramp:!1,activity:!1,reownBranding:!1},DEFAULT_FEATURES:{receive:!0,send:!0,emailShowWallets:!0,connectorTypeOrder:["walletConnect","recent","injected","featured","custom","external","recommended"],analytics:!0,allWallets:!0,legalCheckbox:!1,smartSessions:!1,collapseWallets:!1,walletFeaturesOrder:["onramp","swaps","receive","send"],connectMethodsOrder:void 0,pay:!1},DEFAULT_SOCIALS:["google","x","farcaster","discord","apple","github","facebook"],DEFAULT_ACCOUNT_TYPES:{bip122:"payment",eip155:"smartAccount",polkadot:"eoa",solana:"eoa"},ADAPTER_TYPES:{UNIVERSAL:"universal",SOLANA:"solana",WAGMI:"wagmi",ETHERS:"ethers",ETHERS5:"ethers5",BITCOIN:"bitcoin"}},W={cacheExpiry:{portfolio:3e4,nativeBalance:3e4,ens:3e5,identity:3e5},isCacheExpired(t,e){return Date.now()-t>e},getActiveNetworkProps(){const t=W.getActiveNamespace(),e=W.getActiveCaipNetworkId(),s=e?e.split(":")[1]:void 0,r=s?isNaN(Number(s))?s:Number(s):void 0;return{namespace:t,caipNetworkId:e,chainId:r}},setWalletConnectDeepLink({name:t,href:e}){try{Z.setItem(te.DEEPLINK_CHOICE,JSON.stringify({href:e,name:t}))}catch{console.info("Unable to set WalletConnect deep link")}},getWalletConnectDeepLink(){try{const t=Z.getItem(te.DEEPLINK_CHOICE);if(t)return JSON.parse(t)}catch{console.info("Unable to get WalletConnect deep link")}},deleteWalletConnectDeepLink(){try{Z.removeItem(te.DEEPLINK_CHOICE)}catch{console.info("Unable to delete WalletConnect deep link")}},setActiveNamespace(t){try{Z.setItem(te.ACTIVE_NAMESPACE,t)}catch{console.info("Unable to set active namespace")}},setActiveCaipNetworkId(t){try{Z.setItem(te.ACTIVE_CAIP_NETWORK_ID,t),W.setActiveNamespace(t.split(":")[0])}catch{console.info("Unable to set active caip network id")}},getActiveCaipNetworkId(){try{return Z.getItem(te.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to get active caip network id");return}},deleteActiveCaipNetworkId(){try{Z.removeItem(te.ACTIVE_CAIP_NETWORK_ID)}catch{console.info("Unable to delete active caip network id")}},deleteConnectedConnectorId(t){try{const e=eo(t);Z.removeItem(e)}catch{console.info("Unable to delete connected connector id")}},setAppKitRecent(t){try{const e=W.getRecentWallets();e.find(r=>r.id===t.id)||(e.unshift(t),e.length>2&&e.pop(),Z.setItem(te.RECENT_WALLETS,JSON.stringify(e)))}catch{console.info("Unable to set AppKit recent")}},getRecentWallets(){try{const t=Z.getItem(te.RECENT_WALLETS);return t?JSON.parse(t):[]}catch{console.info("Unable to get AppKit recent")}return[]},setConnectedConnectorId(t,e){try{const s=eo(t);Z.setItem(s,e)}catch{console.info("Unable to set Connected Connector Id")}},getActiveNamespace(){try{return Z.getItem(te.ACTIVE_NAMESPACE)}catch{console.info("Unable to get active namespace")}},getConnectedConnectorId(t){if(t)try{const e=eo(t);return Z.getItem(e)}catch{console.info("Unable to get connected connector id in namespace ",t)}},setConnectedSocialProvider(t){try{Z.setItem(te.CONNECTED_SOCIAL,t)}catch{console.info("Unable to set connected social provider")}},getConnectedSocialProvider(){try{return Z.getItem(te.CONNECTED_SOCIAL)}catch{console.info("Unable to get connected social provider")}},deleteConnectedSocialProvider(){try{Z.removeItem(te.CONNECTED_SOCIAL)}catch{console.info("Unable to delete connected social provider")}},getConnectedSocialUsername(){try{return Z.getItem(te.CONNECTED_SOCIAL_USERNAME)}catch{console.info("Unable to get connected social username")}},getStoredActiveCaipNetworkId(){return Z.getItem(te.ACTIVE_CAIP_NETWORK_ID)?.split(":")?.[1]},setConnectionStatus(t){try{Z.setItem(te.CONNECTION_STATUS,t)}catch{console.info("Unable to set connection status")}},getConnectionStatus(){try{return Z.getItem(te.CONNECTION_STATUS)}catch{return}},getConnectedNamespaces(){try{const t=Z.getItem(te.CONNECTED_NAMESPACES);return t?.length?t.split(","):[]}catch{return[]}},setConnectedNamespaces(t){try{const e=Array.from(new Set(t));Z.setItem(te.CONNECTED_NAMESPACES,e.join(","))}catch{console.info("Unable to set namespaces in storage")}},addConnectedNamespace(t){try{const e=W.getConnectedNamespaces();e.includes(t)||(e.push(t),W.setConnectedNamespaces(e))}catch{console.info("Unable to add connected namespace")}},removeConnectedNamespace(t){try{const e=W.getConnectedNamespaces(),s=e.indexOf(t);s>-1&&(e.splice(s,1),W.setConnectedNamespaces(e))}catch{console.info("Unable to remove connected namespace")}},getTelegramSocialProvider(){try{return Z.getItem(te.TELEGRAM_SOCIAL_PROVIDER)}catch{return console.info("Unable to get telegram social provider"),null}},setTelegramSocialProvider(t){try{Z.setItem(te.TELEGRAM_SOCIAL_PROVIDER,t)}catch{console.info("Unable to set telegram social provider")}},removeTelegramSocialProvider(){try{Z.removeItem(te.TELEGRAM_SOCIAL_PROVIDER)}catch{console.info("Unable to remove telegram social provider")}},getBalanceCache(){let t={};try{const e=Z.getItem(te.PORTFOLIO_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromBalanceCache(t){try{const e=W.getBalanceCache();Z.setItem(te.PORTFOLIO_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getBalanceCacheForCaipAddress(t){try{const s=W.getBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.portfolio))return s.balance;W.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateBalanceCache(t){try{const e=W.getBalanceCache();e[t.caipAddress]=t,Z.setItem(te.PORTFOLIO_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getNativeBalanceCache(){let t={};try{const e=Z.getItem(te.NATIVE_BALANCE_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get balance cache")}return t},removeAddressFromNativeBalanceCache(t){try{const e=W.getBalanceCache();Z.setItem(te.NATIVE_BALANCE_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove address from balance cache",t)}},getNativeBalanceCacheForCaipAddress(t){try{const s=W.getNativeBalanceCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.nativeBalance))return s;console.info("Discarding cache for address",t),W.removeAddressFromBalanceCache(t)}catch{console.info("Unable to get balance cache for address",t)}},updateNativeBalanceCache(t){try{const e=W.getNativeBalanceCache();e[t.caipAddress]=t,Z.setItem(te.NATIVE_BALANCE_CACHE,JSON.stringify(e))}catch{console.info("Unable to update balance cache",t)}},getEnsCache(){let t={};try{const e=Z.getItem(te.ENS_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get ens name cache")}return t},getEnsFromCacheForAddress(t){try{const s=W.getEnsCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.ens))return s.ens;W.removeEnsFromCache(t)}catch{console.info("Unable to get ens name from cache",t)}},updateEnsCache(t){try{const e=W.getEnsCache();e[t.address]=t,Z.setItem(te.ENS_CACHE,JSON.stringify(e))}catch{console.info("Unable to update ens name cache",t)}},removeEnsFromCache(t){try{const e=W.getEnsCache();Z.setItem(te.ENS_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove ens name from cache",t)}},getIdentityCache(){let t={};try{const e=Z.getItem(te.IDENTITY_CACHE);t=e?JSON.parse(e):{}}catch{console.info("Unable to get identity cache")}return t},getIdentityFromCacheForAddress(t){try{const s=W.getIdentityCache()[t];if(s&&!this.isCacheExpired(s.timestamp,this.cacheExpiry.identity))return s.identity;W.removeIdentityFromCache(t)}catch{console.info("Unable to get identity from cache",t)}},updateIdentityCache(t){try{const e=W.getIdentityCache();e[t.address]={identity:t.identity,timestamp:t.timestamp},Z.setItem(te.IDENTITY_CACHE,JSON.stringify(e))}catch{console.info("Unable to update identity cache",t)}},removeIdentityFromCache(t){try{const e=W.getIdentityCache();Z.setItem(te.IDENTITY_CACHE,JSON.stringify({...e,[t]:void 0}))}catch{console.info("Unable to remove identity from cache",t)}},clearAddressCache(){try{Z.removeItem(te.PORTFOLIO_CACHE),Z.removeItem(te.NATIVE_BALANCE_CACHE),Z.removeItem(te.ENS_CACHE),Z.removeItem(te.IDENTITY_CACHE)}catch{console.info("Unable to clear address cache")}},setPreferredAccountTypes(t){try{Z.setItem(te.PREFERRED_ACCOUNT_TYPES,JSON.stringify(t))}catch{console.info("Unable to set preferred account types",t)}},getPreferredAccountTypes(){try{const t=Z.getItem(te.PREFERRED_ACCOUNT_TYPES);return t?JSON.parse(t):{}}catch{console.info("Unable to get preferred account types")}return{}},setConnections(t,e){try{const s={...W.getConnections(),[e]:t};Z.setItem(te.CONNECTIONS,JSON.stringify(s))}catch(s){console.error("Unable to sync connections to storage",s)}},getConnections(){try{const t=Z.getItem(te.CONNECTIONS);return t?JSON.parse(t):{}}catch(t){return console.error("Unable to get connections from storage",t),{}}}},X={isMobile(){return this.isClient()?!!(typeof window?.matchMedia=="function"&&window?.matchMedia("(pointer:coarse)")?.matches||/Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent)):!1},checkCaipNetwork(t,e=""){return t?.caipNetworkId.toLocaleLowerCase().includes(e.toLowerCase())},isAndroid(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return X.isMobile()&&t.includes("android")},isIos(){if(!this.isMobile())return!1;const t=window?.navigator.userAgent.toLowerCase();return t.includes("iphone")||t.includes("ipad")},isSafari(){return this.isClient()?(window?.navigator.userAgent.toLowerCase()).includes("safari"):!1},isClient(){return typeof window<"u"},isPairingExpired(t){return t?t-Date.now()<=Ie.TEN_SEC_MS:!0},isAllowedRetry(t,e=Ie.ONE_SEC_MS){return Date.now()-t>=e},copyToClopboard(t){navigator.clipboard.writeText(t)},isIframe(){try{return window?.self!==window?.top}catch{return!1}},isSafeApp(){if(X.isClient()&&window.self!==window.top)try{const t=window?.location?.ancestorOrigins?.[0],e="https://app.safe.global";if(t){const s=new URL(t),r=new URL(e);return s.hostname===r.hostname}}catch{return!1}return!1},getPairingExpiry(){return Date.now()+Ie.FOUR_MINUTES_MS},getNetworkId(t){return t?.split(":")[1]},getPlainAddress(t){return t?.split(":")[2]},async wait(t){return new Promise(e=>{setTimeout(e,t)})},debounce(t,e=500){let s;return(...r)=>{function i(){t(...r)}s&&clearTimeout(s),s=setTimeout(i,e)}},isHttpUrl(t){return t.startsWith("http://")||t.startsWith("https://")},formatNativeUrl(t,e,s=null){if(X.isHttpUrl(t))return this.formatUniversalUrl(t,e);let r=t,i=s;r.includes("://")||(r=t.replaceAll("/","").replaceAll(":",""),r=`${r}://`),r.endsWith("/")||(r=`${r}/`),i&&!i?.endsWith("/")&&(i=`${i}/`),this.isTelegram()&&this.isAndroid()&&(e=encodeURIComponent(e));const n=encodeURIComponent(e);return{redirect:`${r}wc?uri=${n}`,redirectUniversalLink:i?`${i}wc?uri=${n}`:void 0,href:r}},formatUniversalUrl(t,e){if(!X.isHttpUrl(t))return this.formatNativeUrl(t,e);let s=t;s.endsWith("/")||(s=`${s}/`);const r=encodeURIComponent(e);return{redirect:`${s}wc?uri=${r}`,href:s}},getOpenTargetForPlatform(t){return t==="popupWindow"?t:this.isTelegram()?W.getTelegramSocialProvider()?"_top":"_blank":t},openHref(t,e,s){window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},returnOpenHref(t,e,s){return window?.open(t,this.getOpenTargetForPlatform(e),s||"noreferrer noopener")},isTelegram(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)},isPWA(){if(typeof window>"u")return!1;const t=window.matchMedia?.("(display-mode: standalone)")?.matches,e=window?.navigator?.standalone;return!!(t||e)},async preloadImage(t){const e=new Promise((s,r)=>{const i=new Image;i.onload=s,i.onerror=r,i.crossOrigin="anonymous",i.src=t});return Promise.race([e,X.wait(2e3)])},formatBalance(t,e){let s="0.000";if(typeof t=="string"){const r=Number(t);if(r){const i=Math.floor(r*1e3)/1e3;i&&(s=i.toString())}}return`${s}${e?` ${e}`:""}`},formatBalance2(t,e){let s;if(t==="0")s="0";else if(typeof t=="string"){const r=Number(t);r&&(s=r.toString().match(/^-?\d+(?:\.\d{0,3})?/u)?.[0])}return{value:s??"0",rest:s==="0"?"000":"",symbol:e}},getApiUrl(){return j.W3M_API_URL},getBlockchainApiUrl(){return j.BLOCKCHAIN_API_RPC_URL},getAnalyticsUrl(){return j.PULSE_API_URL},getUUID(){return crypto?.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})},parseError(t){return typeof t=="string"?t:typeof t?.issues?.[0]?.message=="string"?t.issues[0].message:t instanceof Error?t.message:"Unknown error"},sortRequestedNetworks(t,e=[]){const s={};return e&&t&&(t.forEach((r,i)=>{s[r]=i}),e.sort((r,i)=>{const n=s[r.id],o=s[i.id];return n!==void 0&&o!==void 0?n-o:n!==void 0?-1:o!==void 0?1:0})),e},calculateBalance(t){let e=0;for(const s of t)e+=s.value??0;return e},formatTokenBalance(t){const e=t.toFixed(2),[s,r]=e.split(".");return{dollars:s,pennies:r}},isAddress(t,e="eip155"){switch(e){case"eip155":if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)){if(/^(?:0x)?[0-9a-f]{40}$/iu.test(t)||/^(?:0x)?[0-9A-F]{40}$/iu.test(t))return!0}else return!1;return!1;case"solana":return/[1-9A-HJ-NP-Za-km-z]{32,44}$/iu.test(t);default:return!1}},uniqueBy(t,e){const s=new Set;return t.filter(r=>{const i=r[e];return s.has(i)?!1:(s.add(i),!0)})},generateSdkVersion(t,e,s){const i=t.length===0?Ie.ADAPTER_TYPES.UNIVERSAL:t.map(n=>n.adapterType).join(",");return`${e}-${i}-${s}`},createAccount(t,e,s,r,i){return{namespace:t,address:e,type:s,publicKey:r,path:i}},isCaipAddress(t){if(typeof t!="string")return!1;const e=t.split(":"),s=e[0];return e.filter(Boolean).length===3&&s in j.CHAIN_NAME_MAP},isMac(){const t=window?.navigator.userAgent.toLowerCase();return t.includes("macintosh")&&!t.includes("safari")},formatTelegramSocialLoginUrl(t){const e=`--${encodeURIComponent(window?.location.href)}`,s="state=";if(new URL(t).host==="auth.magic.link"){const i="provider_authorization_url=",n=t.substring(t.indexOf(i)+i.length),o=this.injectIntoUrl(decodeURIComponent(n),s,e);return t.replace(n,encodeURIComponent(o))}return this.injectIntoUrl(t,s,e)},injectIntoUrl(t,e,s){const r=t.indexOf(e);if(r===-1)throw new Error(`${e} parameter not found in the URL: ${t}`);const i=t.indexOf("&",r),n=e.length,o=i!==-1?i:t.length,a=t.substring(0,r+n),c=t.substring(r+n,o),l=t.substring(i),u=c+s;return a+u+l}};async function ni(...t){const e=await fetch(...t);if(!e.ok)throw new Error(`HTTP status code: ${e.status}`,{cause:e});return e}class Fi{constructor({baseUrl:e,clientId:s}){this.baseUrl=e,this.clientId=s}async get({headers:e,signal:s,cache:r,...i}){const n=this.createUrl(i);return(await ni(n,{method:"GET",headers:e,signal:s,cache:r})).json()}async getBlob({headers:e,signal:s,...r}){const i=this.createUrl(r);return(await ni(i,{method:"GET",headers:e,signal:s})).blob()}async post({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await ni(n,{method:"POST",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}async put({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await ni(n,{method:"PUT",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}async delete({body:e,headers:s,signal:r,...i}){const n=this.createUrl(i);return(await ni(n,{method:"DELETE",headers:s,body:e?JSON.stringify(e):void 0,signal:r})).json()}createUrl({path:e,params:s}){const r=new URL(e,this.baseUrl);return s&&Object.entries(s).forEach(([i,n])=>{n&&r.searchParams.append(i,n)}),this.clientId&&r.searchParams.append("clientId",this.clientId),r}}const pp={getFeatureValue(t,e){const s=e?.[t];return s===void 0?Ie.DEFAULT_FEATURES[t]:s},filterSocialsByPlatform(t){if(!t||!t.length)return t;if(X.isTelegram()){if(X.isIos())return t.filter(e=>e!=="google");if(X.isMac())return t.filter(e=>e!=="x");if(X.isAndroid())return t.filter(e=>!["facebook","x"].includes(e))}return t}},K=Oe({features:Ie.DEFAULT_FEATURES,projectId:"",sdkType:"appkit",sdkVersion:"html-wagmi-undefined",defaultAccountTypes:Ie.DEFAULT_ACCOUNT_TYPES,enableNetworkSwitch:!0,experimental_preferUniversalLinks:!1,remoteFeatures:{}}),T={state:K,subscribeKey(t,e){return nt(K,t,e)},setOptions(t){Object.assign(K,t)},setRemoteFeatures(t){if(!t)return;const e={...K.remoteFeatures,...t};K.remoteFeatures=e,K.remoteFeatures?.socials&&(K.remoteFeatures.socials=pp.filterSocialsByPlatform(K.remoteFeatures.socials))},setFeatures(t){if(!t)return;K.features||(K.features=Ie.DEFAULT_FEATURES);const e={...K.features,...t};K.features=e},setProjectId(t){K.projectId=t},setCustomRpcUrls(t){K.customRpcUrls=t},setAllWallets(t){K.allWallets=t},setIncludeWalletIds(t){K.includeWalletIds=t},setExcludeWalletIds(t){K.excludeWalletIds=t},setFeaturedWalletIds(t){K.featuredWalletIds=t},setTokens(t){K.tokens=t},setTermsConditionsUrl(t){K.termsConditionsUrl=t},setPrivacyPolicyUrl(t){K.privacyPolicyUrl=t},setCustomWallets(t){K.customWallets=t},setIsSiweEnabled(t){K.isSiweEnabled=t},setIsUniversalProvider(t){K.isUniversalProvider=t},setSdkVersion(t){K.sdkVersion=t},setMetadata(t){K.metadata=t},setDisableAppend(t){K.disableAppend=t},setEIP6963Enabled(t){K.enableEIP6963=t},setDebug(t){K.debug=t},setEnableWalletConnect(t){K.enableWalletConnect=t},setEnableWalletGuide(t){K.enableWalletGuide=t},setEnableAuthLogger(t){K.enableAuthLogger=t},setEnableWallets(t){K.enableWallets=t},setPreferUniversalLinks(t){K.experimental_preferUniversalLinks=t},setHasMultipleAddresses(t){K.hasMultipleAddresses=t},setSIWX(t){K.siwx=t},setConnectMethodsOrder(t){K.features={...K.features,connectMethodsOrder:t}},setWalletFeaturesOrder(t){K.features={...K.features,walletFeaturesOrder:t}},setSocialsOrder(t){K.remoteFeatures={...K.remoteFeatures,socials:t}},setCollapseWallets(t){K.features={...K.features,collapseWallets:t}},setEnableEmbedded(t){K.enableEmbedded=t},setAllowUnsupportedChain(t){K.allowUnsupportedChain=t},setManualWCControl(t){K.manualWCControl=t},setEnableNetworkSwitch(t){K.enableNetworkSwitch=t},setDefaultAccountTypes(t={}){Object.entries(t).forEach(([e,s])=>{s&&(K.defaultAccountTypes[e]=s)})},setUniversalProviderConfigOverride(t){K.universalProviderConfigOverride=t},getUniversalProviderConfigOverride(){return K.universalProviderConfigOverride},getSnapshot(){return Ti(K)}},fp=Object.freeze({enabled:!0,events:[]}),gp=new Fi({baseUrl:X.getAnalyticsUrl(),clientId:null}),mp=5,wp=60*1e3,ms=Oe({...fp}),yp={state:ms,subscribeKey(t,e){return nt(ms,t,e)},async sendError(t,e){if(!ms.enabled)return;const s=Date.now();if(ms.events.filter(n=>{const o=new Date(n.properties.timestamp||"").getTime();return s-o<wp}).length>=mp)return;const i={type:"error",event:e,properties:{errorType:t.name,errorMessage:t.message,stackTrace:t.stack,timestamp:new Date().toISOString()}};ms.events.push(i);try{if(typeof window>"u")return;const{projectId:n,sdkType:o,sdkVersion:a}=T.state;await gp.post({path:"/e",params:{projectId:n,st:o,sv:a||"html-wagmi-4.2.2"},body:{eventId:X.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:new Date().toISOString(),props:{type:"error",event:e,errorType:t.name,errorMessage:t.message,stackTrace:t.stack}}})}catch{}},enable(){ms.enabled=!0},disable(){ms.enabled=!1},clearEvents(){ms.events=[]}};class jr extends Error{constructor(e,s,r){super(e),this.name="AppKitError",this.category=s,this.originalError=r,Object.setPrototypeOf(this,jr.prototype);let i=!1;if(r instanceof Error&&typeof r.stack=="string"&&r.stack){const n=r.stack,o=n.indexOf(`
3
3
  `);if(o>-1){const a=n.substring(o+1);this.stack=`${this.name}: ${this.message}
4
4
  ${a}`,i=!0}}i||(Error.captureStackTrace?Error.captureStackTrace(this,jr):this.stack||(this.stack=`${this.name}: ${this.message}`))}}function Ya(t,e){const s=t instanceof jr?t:new jr(t instanceof Error?t.message:String(t),e,t);throw yp.sendError(s,s.category),s}function St(t,e="INTERNAL_SDK_ERROR"){const s={};return Object.keys(t).forEach(r=>{const i=t[r];if(typeof i=="function"){let n=i;i.constructor.name==="AsyncFunction"?n=async(...o)=>{try{return await i(...o)}catch(a){return Ya(a,e)}}:n=(...o)=>{try{return i(...o)}catch(a){return Ya(a,e)}},s[r]=n}else s[r]=i}),s}const Xt={PHANTOM:{id:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",url:"https://phantom.app"},SOLFLARE:{id:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",url:"https://solflare.com"},COINBASE:{id:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",url:"https://go.cb-w.com"}},bp={handleMobileDeeplinkRedirect(t,e){const s=window.location.href,r=encodeURIComponent(s);if(t===Xt.PHANTOM.id&&!("phantom"in window)){const i=s.startsWith("https")?"https":"http",n=s.split("/")[2],o=encodeURIComponent(`${i}://${n}`);window.location.href=`${Xt.PHANTOM.url}/ul/browse/${r}?ref=${o}`}t===Xt.SOLFLARE.id&&!("solflare"in window)&&(window.location.href=`${Xt.SOLFLARE.url}/ul/v1/browse/${r}?ref=${r}`),e===j.CHAIN.SOLANA&&t===Xt.COINBASE.id&&!("coinbaseSolana"in window)&&(window.location.href=`${Xt.COINBASE.url}/dapp?cb_url=${r}`)}},yt=Oe({walletImages:{},networkImages:{},chainImages:{},connectorImages:{},tokenImages:{},currencyImages:{}}),vp={state:yt,subscribeNetworkImages(t){return it(yt.networkImages,()=>t(yt.networkImages))},subscribeKey(t,e){return nt(yt,t,e)},subscribe(t){return it(yt,()=>t(yt))},setWalletImage(t,e){yt.walletImages[t]=e},setNetworkImage(t,e){yt.networkImages[t]=e},setChainImage(t,e){yt.chainImages[t]=e},setConnectorImage(t,e){yt.connectorImages={...yt.connectorImages,[t]:e}},setTokenImage(t,e){yt.tokenImages[t]=e},setCurrencyImage(t,e){yt.currencyImages[t]=e}},qt=St(vp),Ep={eip155:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",solana:"a1b58899-f671-4276-6a5e-56ca5bd59700",polkadot:"",bip122:"0b4838db-0161-4ffe-022d-532bf03dba00",cosmos:""},ro=Oe({networkImagePromises:{}}),vu={async fetchWalletImage(t){if(t)return await V._fetchWalletImage(t),this.getWalletImageById(t)},async fetchNetworkImage(t){if(!t)return;const e=this.getNetworkImageById(t);return e||(ro.networkImagePromises[t]||(ro.networkImagePromises[t]=V._fetchNetworkImage(t)),await ro.networkImagePromises[t],this.getNetworkImageById(t))},getWalletImageById(t){if(t)return qt.state.walletImages[t]},getWalletImage(t){if(t?.image_url)return t?.image_url;if(t?.image_id)return qt.state.walletImages[t.image_id]},getNetworkImage(t){if(t?.assets?.imageUrl)return t?.assets?.imageUrl;if(t?.assets?.imageId)return qt.state.networkImages[t.assets.imageId]},getNetworkImageById(t){if(t)return qt.state.networkImages[t]},getConnectorImage(t){if(t?.imageUrl)return t.imageUrl;if(t?.imageId)return qt.state.connectorImages[t.imageId]},getChainImage(t){return qt.state.networkImages[Ep[t]]}},ws=Oe({message:"",variant:"info",open:!1}),Cp={state:ws,subscribeKey(t,e){return nt(ws,t,e)},open(t,e){const{debug:s}=T.state,{shortMessage:r,longMessage:i}=t;s&&(ws.message=r,ws.variant=e,ws.open=!0),i&&console.error(typeof i=="function"?i():i)},close(){ws.open=!1,ws.message="",ws.variant="info"}},Fs=St(Cp),Ip=X.getAnalyticsUrl(),Np=new Fi({baseUrl:Ip,clientId:null}),_p=["MODAL_CREATED"],is=Oe({timestamp:Date.now(),reportedErrors:{},data:{type:"track",event:"MODAL_CREATED"}}),ke={state:is,subscribe(t){return it(is,()=>t(is))},getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=T.state;return{projectId:t,st:e,sv:s||"html-wagmi-4.2.2"}},async _sendAnalyticsEvent(t){try{const e=H.state.address;if(_p.includes(t.data.event)||typeof window>"u")return;await Np.post({path:"/e",params:ke.getSdkProperties(),body:{eventId:X.getUUID(),url:window.location.href,domain:window.location.hostname,timestamp:t.timestamp,props:{...t.data,address:e}}}),is.reportedErrors.FORBIDDEN=!1}catch(e){e instanceof Error&&e.cause instanceof Response&&e.cause.status===j.HTTP_STATUS_CODES.FORBIDDEN&&!is.reportedErrors.FORBIDDEN&&(Fs.open({shortMessage:"Invalid App Configuration",longMessage:`Origin ${fi()?window.origin:"uknown"} not found on Allowlist - update configuration on cloud.reown.com`},"error"),is.reportedErrors.FORBIDDEN=!0)}},sendEvent(t){is.timestamp=Date.now(),is.data=t,T.state.features?.analytics&&ke._sendAnalyticsEvent(is)}},Ap=X.getApiUrl(),lt=new Fi({baseUrl:Ap,clientId:null}),Sp=40,Xa=4,Pp=20,se=Oe({promises:{},page:1,count:0,featured:[],allFeatured:[],recommended:[],allRecommended:[],wallets:[],filteredWallets:[],search:[],isAnalyticsEnabled:!1,excludedWallets:[],isFetchingRecommendedWallets:!1}),V={state:se,subscribeKey(t,e){return nt(se,t,e)},_getSdkProperties(){const{projectId:t,sdkType:e,sdkVersion:s}=T.state;return{projectId:t,st:e||"appkit",sv:s||"html-wagmi-4.2.2"}},_filterOutExtensions(t){return T.state.isUniversalProvider?t.filter(e=>!!(e.mobile_link||e.desktop_link||e.webapp_link)):t},async _fetchWalletImage(t){const e=`${lt.baseUrl}/getWalletImage/${t}`,s=await lt.getBlob({path:e,params:V._getSdkProperties()});qt.setWalletImage(t,URL.createObjectURL(s))},async _fetchNetworkImage(t){const e=`${lt.baseUrl}/public/getAssetImage/${t}`,s=await lt.getBlob({path:e,params:V._getSdkProperties()});qt.setNetworkImage(t,URL.createObjectURL(s))},async _fetchConnectorImage(t){const e=`${lt.baseUrl}/public/getAssetImage/${t}`,s=await lt.getBlob({path:e,params:V._getSdkProperties()});qt.setConnectorImage(t,URL.createObjectURL(s))},async _fetchCurrencyImage(t){const e=`${lt.baseUrl}/public/getCurrencyImage/${t}`,s=await lt.getBlob({path:e,params:V._getSdkProperties()});qt.setCurrencyImage(t,URL.createObjectURL(s))},async _fetchTokenImage(t){const e=`${lt.baseUrl}/public/getTokenImage/${t}`,s=await lt.getBlob({path:e,params:V._getSdkProperties()});qt.setTokenImage(t,URL.createObjectURL(s))},_filterWalletsByPlatform(t){return X.isMobile()?t?.filter(s=>s.mobile_link||s.id===Xt.COINBASE.id?!0:g.state.activeChain==="solana"&&(s.id===Xt.SOLFLARE.id||s.id===Xt.PHANTOM.id)):t},async fetchProjectConfig(){return(await lt.get({path:"/appkit/v1/config",params:V._getSdkProperties()})).features},async fetchAllowedOrigins(){try{const{allowedOrigins:t}=await lt.get({path:"/projects/v1/origins",params:V._getSdkProperties()});return t}catch{return[]}},async fetchNetworkImages(){const e=g.getAllRequestedCaipNetworks()?.map(({assets:s})=>s?.imageId).filter(Boolean).filter(s=>!vu.getNetworkImageById(s));e&&await Promise.allSettled(e.map(s=>V._fetchNetworkImage(s)))},async fetchConnectorImages(){const{connectors:t}=q.state,e=t.map(({imageId:s})=>s).filter(Boolean);await Promise.allSettled(e.map(s=>V._fetchConnectorImage(s)))},async fetchCurrencyImages(t=[]){await Promise.allSettled(t.map(e=>V._fetchCurrencyImage(e)))},async fetchTokenImages(t=[]){await Promise.allSettled(t.map(e=>V._fetchTokenImage(e)))},async fetchWallets(t){const e=t.exclude??[];V._getSdkProperties().sv.startsWith("html-core-")&&e.push(...Object.values(Xt).map(n=>n.id));const r=await lt.get({path:"/getWallets",params:{...V._getSdkProperties(),...t,page:String(t.page),entries:String(t.entries),include:t.include?.join(","),exclude:e.join(",")}});return{data:V._filterWalletsByPlatform(r?.data)||[],count:r?.count}},async fetchFeaturedWallets(){const{featuredWalletIds:t}=T.state;if(t?.length){const e={...V._getSdkProperties(),page:1,entries:t?.length??Xa,include:t},{data:s}=await V.fetchWallets(e),r=[...s].sort((n,o)=>t.indexOf(n.id)-t.indexOf(o.id)),i=r.map(n=>n.image_id).filter(Boolean);await Promise.allSettled(i.map(n=>V._fetchWalletImage(n))),se.featured=r,se.allFeatured=r}},async fetchRecommendedWallets(){try{se.isFetchingRecommendedWallets=!0;const{includeWalletIds:t,excludeWalletIds:e,featuredWalletIds:s}=T.state,r=[...e??[],...s??[]].filter(Boolean),i=g.getRequestedCaipNetworkIds().join(","),n={page:1,entries:Xa,include:t,exclude:r,chains:i},{data:o,count:a}=await V.fetchWallets(n),c=W.getRecentWallets(),l=o.map(h=>h.image_id).filter(Boolean),u=c.map(h=>h.image_id).filter(Boolean);await Promise.allSettled([...l,...u].map(h=>V._fetchWalletImage(h))),se.recommended=o,se.allRecommended=o,se.count=a??0}catch{}finally{se.isFetchingRecommendedWallets=!1}},async fetchWalletsByPage({page:t}){const{includeWalletIds:e,excludeWalletIds:s,featuredWalletIds:r}=T.state,i=g.getRequestedCaipNetworkIds().join(","),n=[...se.recommended.map(({id:u})=>u),...s??[],...r??[]].filter(Boolean),o={page:t,entries:Sp,include:e,exclude:n,chains:i},{data:a,count:c}=await V.fetchWallets(o),l=a.slice(0,Pp).map(u=>u.image_id).filter(Boolean);await Promise.allSettled(l.map(u=>V._fetchWalletImage(u))),se.wallets=X.uniqueBy([...se.wallets,...V._filterOutExtensions(a)],"id").filter(u=>u.chains?.some(h=>i.includes(h))),se.count=c>se.count?c:se.count,se.page=t},async initializeExcludedWallets({ids:t}){const e={page:1,entries:t.length,include:t},{data:s}=await V.fetchWallets(e);s&&s.forEach(r=>{se.excludedWallets.push({rdns:r.rdns,name:r.name})})},async searchWallet({search:t,badge:e}){const{includeWalletIds:s,excludeWalletIds:r}=T.state,i=g.getRequestedCaipNetworkIds().join(",");se.search=[];const n={page:1,entries:100,search:t?.trim(),badge_type:e,include:s,exclude:r,chains:i},{data:o}=await V.fetchWallets(n);ke.sendEvent({type:"track",event:"SEARCH_WALLET",properties:{badge:e??"",search:t??""}});const a=o.map(c=>c.image_id).filter(Boolean);await Promise.allSettled([...a.map(c=>V._fetchWalletImage(c)),X.wait(300)]),se.search=V._filterOutExtensions(o)},initPromise(t,e){const s=se.promises[t];return s||(se.promises[t]=e())},prefetch({fetchConnectorImages:t=!0,fetchFeaturedWallets:e=!0,fetchRecommendedWallets:s=!0,fetchNetworkImages:r=!0}={}){const i=[t&&V.initPromise("connectorImages",V.fetchConnectorImages),e&&V.initPromise("featuredWallets",V.fetchFeaturedWallets),s&&V.initPromise("recommendedWallets",V.fetchRecommendedWallets),r&&V.initPromise("networkImages",V.fetchNetworkImages)].filter(Boolean);return Promise.allSettled(i)},prefetchAnalyticsConfig(){T.state.features?.analytics&&V.fetchAnalyticsConfig()},async fetchAnalyticsConfig(){try{const{isAnalyticsEnabled:t}=await lt.get({path:"/getAnalyticsConfig",params:V._getSdkProperties()});T.setFeatures({analytics:t})}catch{T.setFeatures({analytics:!1})}},filterByNamespaces(t){if(!t?.length){se.featured=se.allFeatured,se.recommended=se.allRecommended;return}const e=g.getRequestedCaipNetworkIds().join(",");se.featured=se.allFeatured.filter(s=>s.chains?.some(r=>e.includes(r))),se.recommended=se.allRecommended.filter(s=>s.chains?.some(r=>e.includes(r))),se.filteredWallets=se.wallets.filter(s=>s.chains?.some(r=>e.includes(r)))},clearFilterByNamespaces(){se.filteredWallets=[]},setFilterByNamespace(t){if(!t){se.featured=se.allFeatured,se.recommended=se.allRecommended;return}const e=g.getRequestedCaipNetworkIds().join(",");se.featured=se.allFeatured.filter(s=>s.chains?.some(r=>e.includes(r))),se.recommended=se.allRecommended.filter(s=>s.chains?.some(r=>e.includes(r))),se.filteredWallets=se.wallets.filter(s=>s.chains?.some(r=>e.includes(r)))}},we=Oe({view:"Connect",history:["Connect"],transactionStack:[]}),Op={state:we,subscribeKey(t,e){return nt(we,t,e)},pushTransactionStack(t){we.transactionStack.push(t)},popTransactionStack(t){const e=we.transactionStack.pop();if(!e)return;const{onSuccess:s,onError:r,onCancel:i}=e;switch(t){case"success":s?.();break;case"error":r?.(),ie.goBack();break;case"cancel":i?.(),ie.goBack();break}},push(t,e){t!==we.view&&(we.view=t,we.history.push(t),we.data=e)},reset(t,e){we.view=t,we.history=[t],we.data=e},replace(t,e){we.history.at(-1)===t||(we.view=t,we.history[we.history.length-1]=t,we.data=e)},goBack(){const t=g.state.activeCaipAddress,e=ie.state.view==="ConnectingFarcaster",s=!t&&e;if(we.history.length>1){we.history.pop();const[r]=we.history.slice(-1);r&&(t&&r==="Connect"?we.view="Account":we.view=r)}else Ge.close();we.data?.wallet&&(we.data.wallet=void 0),setTimeout(()=>{if(s){H.setFarcasterUrl(void 0,g.state.activeChain);const r=q.getAuthConnector();r?.provider?.reload();const i=Ti(T.state);r?.provider?.syncDappData?.({metadata:i.metadata,sdkVersion:i.sdkVersion,projectId:i.projectId,sdkType:i.sdkType})}},100)},goBackToIndex(t){if(we.history.length>1){we.history=we.history.slice(0,t+1);const[e]=we.history.slice(-1);e&&(we.view=e)}},goBackOrCloseModal(){ie.state.history.length>1?ie.goBack():Ge.close()}},ie=St(Op),ns=Oe({themeMode:"dark",themeVariables:{},w3mThemeVariables:void 0}),Lo={state:ns,subscribe(t){return it(ns,()=>t(ns))},setThemeMode(t){ns.themeMode=t;try{const e=q.getAuthConnector();if(e){const s=Lo.getSnapshot().themeVariables;e.provider.syncTheme({themeMode:t,themeVariables:s,w3mThemeVariables:Ns(s,t)})}}catch{console.info("Unable to sync theme to auth connector")}},setThemeVariables(t){ns.themeVariables={...ns.themeVariables,...t};try{const e=q.getAuthConnector();if(e){const s=Lo.getSnapshot().themeVariables;e.provider.syncTheme({themeVariables:s,w3mThemeVariables:Ns(ns.themeVariables,ns.themeMode)})}}catch{console.info("Unable to sync theme to auth connector")}},getSnapshot(){return Ti(ns)}},Et=St(Lo),Eu={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},ce=Oe({allConnectors:[],connectors:[],activeConnector:void 0,filterByNamespace:void 0,activeConnectorIds:{...Eu},filterByNamespaceMap:{eip155:!0,solana:!0,polkadot:!0,bip122:!0,cosmos:!0}}),Tp={state:ce,subscribe(t){return it(ce,()=>{t(ce)})},subscribeKey(t,e){return nt(ce,t,e)},initialize(t){t.forEach(e=>{const s=W.getConnectedConnectorId(e);s&&q.setConnectorId(s,e)})},setActiveConnector(t){t&&(ce.activeConnector=Xs(t))},setConnectors(t){t.filter(i=>!ce.allConnectors.some(n=>n.id===i.id&&q.getConnectorName(n.name)===q.getConnectorName(i.name)&&n.chain===i.chain)).forEach(i=>{i.type!=="MULTI_CHAIN"&&ce.allConnectors.push(Xs(i))});const s=q.getEnabledNamespaces(),r=q.getEnabledConnectors(s);ce.connectors=q.mergeMultiChainConnectors(r)},filterByNamespaces(t){Object.keys(ce.filterByNamespaceMap).forEach(e=>{ce.filterByNamespaceMap[e]=!1}),t.forEach(e=>{ce.filterByNamespaceMap[e]=!0}),q.updateConnectorsForEnabledNamespaces()},filterByNamespace(t,e){ce.filterByNamespaceMap[t]=e,q.updateConnectorsForEnabledNamespaces()},updateConnectorsForEnabledNamespaces(){const t=q.getEnabledNamespaces(),e=q.getEnabledConnectors(t),s=q.areAllNamespacesEnabled();ce.connectors=q.mergeMultiChainConnectors(e),s?V.clearFilterByNamespaces():V.filterByNamespaces(t)},getEnabledNamespaces(){return Object.entries(ce.filterByNamespaceMap).filter(([t,e])=>e).map(([t])=>t)},getEnabledConnectors(t){return ce.allConnectors.filter(e=>t.includes(e.chain))},areAllNamespacesEnabled(){return Object.values(ce.filterByNamespaceMap).every(t=>t)},mergeMultiChainConnectors(t){const e=q.generateConnectorMapByName(t),s=[];return e.forEach(r=>{const i=r[0],n=i?.id===j.CONNECTOR_ID.AUTH;r.length>1&&i?s.push({name:i.name,imageUrl:i.imageUrl,imageId:i.imageId,connectors:[...r],type:n?"AUTH":"MULTI_CHAIN",chain:"eip155",id:i?.id||""}):i&&s.push(i)}),s},generateConnectorMapByName(t){const e=new Map;return t.forEach(s=>{const{name:r}=s,i=q.getConnectorName(r);if(!i)return;const n=e.get(i)||[];n.find(a=>a.chain===s.chain)||n.push(s),e.set(i,n)}),e},getConnectorName(t){return t&&({"Trust Wallet":"Trust"}[t]||t)},getUniqueConnectorsByName(t){const e=[];return t.forEach(s=>{e.find(r=>r.chain===s.chain)||e.push(s)}),e},addConnector(t){if(t.id===j.CONNECTOR_ID.AUTH){const e=t,s=Ti(T.state),r=Et.getSnapshot().themeMode,i=Et.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,projectId:s.projectId,sdkType:s.sdkType}),e?.provider?.syncTheme({themeMode:r,themeVariables:i,w3mThemeVariables:Ns(i,r)}),q.setConnectors([t])}else q.setConnectors([t])},getAuthConnector(t){const e=t||g.state.activeChain,s=ce.connectors.find(r=>r.id===j.CONNECTOR_ID.AUTH);if(s)return s?.connectors?.length?s.connectors.find(i=>i.chain===e):s},getAnnouncedConnectorRdns(){return ce.connectors.filter(t=>t.type==="ANNOUNCED").map(t=>t.info?.rdns)},getConnectorById(t){return ce.allConnectors.find(e=>e.id===t)},getConnector(t,e){return ce.allConnectors.filter(r=>r.chain===g.state.activeChain).find(r=>r.explorerId===t||r.info?.rdns===e)},syncIfAuthConnector(t){if(t.id!=="ID_AUTH")return;const e=t,s=Ti(T.state),r=Et.getSnapshot().themeMode,i=Et.getSnapshot().themeVariables;e?.provider?.syncDappData?.({metadata:s.metadata,sdkVersion:s.sdkVersion,sdkType:s.sdkType,projectId:s.projectId}),e.provider.syncTheme({themeMode:r,themeVariables:i,w3mThemeVariables:Ns(i,r)})},getConnectorsByNamespace(t){const e=ce.allConnectors.filter(s=>s.chain===t);return q.mergeMultiChainConnectors(e)},selectWalletConnector(t){const e=q.getConnector(t.id,t.rdns),s=g.state.activeChain;bp.handleMobileDeeplinkRedirect(e?.explorerId||t.id,s),e?ie.push("ConnectingExternal",{connector:e}):ie.push("ConnectingWalletConnect",{wallet:t})},getConnectors(t){return t?q.getConnectorsByNamespace(t):q.mergeMultiChainConnectors(ce.allConnectors)},setFilterByNamespace(t){ce.filterByNamespace=t,ce.connectors=q.getConnectors(t),V.setFilterByNamespace(t)},setConnectorId(t,e){t&&(ce.activeConnectorIds={...ce.activeConnectorIds,[e]:t},W.setConnectedConnectorId(e,t))},removeConnectorId(t){ce.activeConnectorIds={...ce.activeConnectorIds,[t]:void 0},W.deleteConnectedConnectorId(t)},getConnectorId(t){if(t)return ce.activeConnectorIds[t]},isConnected(t){return t?!!ce.activeConnectorIds[t]:Object.values(ce.activeConnectorIds).some(e=>!!e)},resetConnectorIds(){ce.activeConnectorIds={...Eu}}},q=St(Tp),Ei={SAFE_RPC_METHODS:["eth_accounts","eth_blockNumber","eth_call","eth_chainId","eth_estimateGas","eth_feeHistory","eth_gasPrice","eth_getAccount","eth_getBalance","eth_getBlockByHash","eth_getBlockByNumber","eth_getBlockReceipts","eth_getBlockTransactionCountByHash","eth_getBlockTransactionCountByNumber","eth_getCode","eth_getFilterChanges","eth_getFilterLogs","eth_getLogs","eth_getProof","eth_getStorageAt","eth_getTransactionByBlockHashAndIndex","eth_getTransactionByBlockNumberAndIndex","eth_getTransactionByHash","eth_getTransactionCount","eth_getTransactionReceipt","eth_getUncleCountByBlockHash","eth_getUncleCountByBlockNumber","eth_maxPriorityFeePerGas","eth_newBlockFilter","eth_newFilter","eth_newPendingTransactionFilter","eth_sendRawTransaction","eth_syncing","eth_uninstallFilter","wallet_getCapabilities","wallet_getCallsStatus","eth_getUserOperationReceipt","eth_estimateUserOperationGas","eth_getUserOperationByHash","eth_supportedEntryPoints","wallet_getAssets"],NOT_SAFE_RPC_METHODS:["personal_sign","eth_signTypedData_v4","eth_sendTransaction","solana_signMessage","solana_signTransaction","solana_signAllTransactions","solana_signAndSendTransaction","wallet_sendCalls","wallet_grantPermissions","wallet_revokePermissions","eth_sendUserOperation"],GET_CHAIN_ID:"eth_chainId",RPC_METHOD_NOT_ALLOWED_MESSAGE:"Requested RPC call is not allowed",RPC_METHOD_NOT_ALLOWED_UI_MESSAGE:"Action not allowed",ACCOUNT_TYPES:{EOA:"eoa",SMART_ACCOUNT:"smartAccount"}},js=Object.freeze({message:"",variant:"success",svg:void 0,open:!1,autoClose:!0}),Me=Oe({...js}),kp={state:Me,subscribeKey(t,e){return nt(Me,t,e)},showLoading(t,e={}){this._showMessage({message:t,variant:"loading",...e})},showSuccess(t){this._showMessage({message:t,variant:"success"})},showSvg(t,e){this._showMessage({message:t,svg:e})},showError(t){const e=X.parseError(t);this._showMessage({message:e,variant:"error"})},hide(){Me.message=js.message,Me.variant=js.variant,Me.svg=js.svg,Me.open=js.open,Me.autoClose=js.autoClose},_showMessage({message:t,svg:e,variant:s="success",autoClose:r=js.autoClose}){Me.open?(Me.open=!1,setTimeout(()=>{Me.message=t,Me.variant=s,Me.svg=e,Me.open=!0,Me.autoClose=r},150)):(Me.message=t,Me.variant=s,Me.svg=e,Me.open=!0,Me.autoClose=r)}},Ft=kp,_e=Oe({transactions:[],coinbaseTransactions:{},transactionsByYear:{},lastNetworkInView:void 0,loading:!1,empty:!1,next:void 0}),xp={state:_e,subscribe(t){return it(_e,()=>t(_e))},setLastNetworkInView(t){_e.lastNetworkInView=t},async fetchTransactions(t,e){if(!t)throw new Error("Transactions can't be fetched without an accountAddress");_e.loading=!0;try{const s=await J.fetchTransactions({account:t,cursor:_e.next,onramp:e,cache:e==="coinbase"?"no-cache":void 0,chainId:g.state.activeCaipNetwork?.caipNetworkId}),r=mi.filterSpamTransactions(s.data),i=mi.filterByConnectedChain(r),n=[..._e.transactions,...i];_e.loading=!1,e==="coinbase"?_e.coinbaseTransactions=mi.groupTransactionsByYearAndMonth(_e.coinbaseTransactions,s.data):(_e.transactions=n,_e.transactionsByYear=mi.groupTransactionsByYearAndMonth(_e.transactionsByYear,i)),_e.empty=n.length===0,_e.next=s.next?s.next:void 0}catch{const r=g.state.activeChain;ke.sendEvent({type:"track",event:"ERROR_FETCH_TRANSACTIONS",properties:{address:t,projectId:T.state.projectId,cursor:_e.next,isSmartAccount:H.state.preferredAccountTypes?.[r]===Ei.ACCOUNT_TYPES.SMART_ACCOUNT}}),Ft.showError("Failed to fetch transactions"),_e.loading=!1,_e.empty=!0,_e.next=void 0}},groupTransactionsByYearAndMonth(t={},e=[]){const s=t;return e.forEach(r=>{const i=new Date(r.metadata.minedAt).getFullYear(),n=new Date(r.metadata.minedAt).getMonth(),o=s[i]??{},c=(o[n]??[]).filter(l=>l.id!==r.id);s[i]={...o,[n]:[...c,r].sort((l,u)=>new Date(u.metadata.minedAt).getTime()-new Date(l.metadata.minedAt).getTime())}}),s},filterSpamTransactions(t){return t.filter(e=>!e.transfers.every(r=>r.nft_info?.flags.is_spam===!0))},filterByConnectedChain(t){const e=g.state.activeCaipNetwork?.caipNetworkId;return t.filter(r=>r.metadata.chain===e)},clearCursor(){_e.next=void 0},resetTransactions(){_e.transactions=[],_e.transactionsByYear={},_e.lastNetworkInView=void 0,_e.loading=!1,_e.empty=!1,_e.next=void 0}},mi=St(xp,"API_ERROR"),Se=Oe({connections:new Map,wcError:!1,buffering:!1,status:"disconnected"});let Ds;const $p={state:Se,subscribeKey(t,e){return nt(Se,t,e)},_getClient(){return Se._client},setClient(t){Se._client=Xs(t)},async connectWalletConnect(){if(X.isTelegram()||X.isSafari()&&X.isIos()){if(Ds){await Ds,Ds=void 0;return}if(!X.isPairingExpired(Se?.wcPairingExpiry)){const t=Se.wcUri;Se.wcUri=t;return}Ds=Y._getClient()?.connectWalletConnect?.().catch(()=>{}),Y.state.status="connecting",await Ds,Ds=void 0,Se.wcPairingExpiry=void 0,Y.state.status="connected"}else await Y._getClient()?.connectWalletConnect?.()},async connectExternal(t,e,s=!0){await Y._getClient()?.connectExternal?.(t),s&&g.setActiveNamespace(e)},async reconnectExternal(t){await Y._getClient()?.reconnectExternal?.(t);const e=t.chain||g.state.activeChain;e&&q.setConnectorId(t.id,e)},async setPreferredAccountType(t,e){Ge.setLoading(!0,g.state.activeChain);const s=q.getAuthConnector();s&&(H.setPreferredAccountType(t,e),await s.provider.setPreferredAccount(t),W.setPreferredAccountTypes(H.state.preferredAccountTypes??{[e]:t}),await Y.reconnectExternal(s),Ge.setLoading(!1,g.state.activeChain),ke.sendEvent({type:"track",event:"SET_PREFERRED_ACCOUNT_TYPE",properties:{accountType:t,network:g.state.activeCaipNetwork?.caipNetworkId||""}}))},async signMessage(t){return Y._getClient()?.signMessage(t)},parseUnits(t,e){return Y._getClient()?.parseUnits(t,e)},formatUnits(t,e){return Y._getClient()?.formatUnits(t,e)},async sendTransaction(t){return Y._getClient()?.sendTransaction(t)},async getCapabilities(t){return Y._getClient()?.getCapabilities(t)},async grantPermissions(t){return Y._getClient()?.grantPermissions(t)},async walletGetAssets(t){return Y._getClient()?.walletGetAssets(t)??{}},async estimateGas(t){return Y._getClient()?.estimateGas(t)},async writeContract(t){return Y._getClient()?.writeContract(t)},async getEnsAddress(t){return Y._getClient()?.getEnsAddress(t)},async getEnsAvatar(t){return Y._getClient()?.getEnsAvatar(t)},checkInstalled(t){return Y._getClient()?.checkInstalled?.(t)||!1},resetWcConnection(){Se.wcUri=void 0,Se.wcPairingExpiry=void 0,Se.wcLinking=void 0,Se.recentWallet=void 0,Se.status="disconnected",mi.resetTransactions(),W.deleteWalletConnectDeepLink()},resetUri(){Se.wcUri=void 0,Se.wcPairingExpiry=void 0,Ds=void 0},finalizeWcConnection(){const{wcLinking:t,recentWallet:e}=Y.state;t&&W.setWalletConnectDeepLink(t),e&&W.setAppKitRecent(e),ke.sendEvent({type:"track",event:"CONNECT_SUCCESS",properties:{method:t?"mobile":"qrcode",name:ie.state.data?.wallet?.name||"Unknown"}})},setWcBasic(t){Se.wcBasic=t},setUri(t){Se.wcUri=t,Se.wcPairingExpiry=X.getPairingExpiry()},setWcLinking(t){Se.wcLinking=t},setWcError(t){Se.wcError=t,Se.buffering=!1},setRecentWallet(t){Se.recentWallet=t},setBuffering(t){Se.buffering=t},setStatus(t){Se.status=t},async disconnect(t){try{await Y._getClient()?.disconnect(t)}catch(e){throw new jr("Failed to disconnect","INTERNAL_SDK_ERROR",e)}},setConnections(t,e){Se.connections.set(e,t)},switchAccount({connection:t,address:e,namespace:s}){if(q.state.activeConnectorIds[s]===t.connectorId){const n=g.state.activeCaipNetwork;if(n){const o=`${s}:${n.id}:${e}`;H.setCaipAddress(o,s)}else console.warn(`No current network found for namespace "${s}"`)}else{const n=q.getConnector(t.connectorId);n?Y.connectExternal(n,s):console.warn(`No connector found for namespace "${s}"`)}}},Y=St($p),lr=Oe({loading:!1,open:!1,selectedNetworkId:void 0,activeChain:void 0,initialized:!1}),Ss={state:lr,subscribe(t){return it(lr,()=>t(lr))},subscribeOpen(t){return nt(lr,"open",t)},set(t){Object.assign(lr,{...lr,...t})}},io={createBalance(t,e){const s={name:t.metadata.name||"",symbol:t.metadata.symbol||"",decimals:t.metadata.decimals||0,value:t.metadata.value||0,price:t.metadata.price||0,iconUrl:t.metadata.iconUrl||""};return{name:s.name,symbol:s.symbol,chainId:e,address:t.address==="native"?void 0:this.convertAddressToCAIP10Address(t.address,e),value:s.value,price:s.price,quantity:{decimals:s.decimals.toString(),numeric:this.convertHexToBalance({hex:t.balance,decimals:s.decimals})},iconUrl:s.iconUrl}},convertHexToBalance({hex:t,decimals:e}){return Hd(BigInt(t),e)},convertAddressToCAIP10Address(t,e){return`${e}:${t}`},createCAIP2ChainId(t,e){return`${e}:${parseInt(t,16)}`},getChainIdHexFromCAIP2ChainId(t){const e=t.split(":");if(e.length<2||!e[1])return"0x0";const s=e[1],r=parseInt(s,10);return isNaN(r)?"0x0":`0x${r.toString(16)}`},isWalletGetAssetsResponse(t){return typeof t!="object"||t===null?!1:Object.values(t).every(e=>Array.isArray(e)&&e.every(s=>this.isValidAsset(s)))},isValidAsset(t){return typeof t=="object"&&t!==null&&typeof t.address=="string"&&typeof t.balance=="string"&&(t.type==="ERC20"||t.type==="NATIVE")&&typeof t.metadata=="object"&&t.metadata!==null&&typeof t.metadata.name=="string"&&typeof t.metadata.symbol=="string"&&typeof t.metadata.decimals=="number"&&typeof t.metadata.price=="number"&&typeof t.metadata.iconUrl=="string"}},Za={async getMyTokensWithBalance(t){const e=H.state.address,s=g.state.activeCaipNetwork;if(!e||!s)return[];if(s.chainNamespace==="eip155"){const i=await this.getEIP155Balances(e,s);if(i)return this.filterLowQualityTokens(i)}const r=await J.getBalance(e,s.caipNetworkId,t);return this.filterLowQualityTokens(r.balances)},async getEIP155Balances(t,e){try{const s=io.getChainIdHexFromCAIP2ChainId(e.caipNetworkId);if(!(await Y.getCapabilities(t))?.[s]?.assetDiscovery?.supported)return null;const i=await Y.walletGetAssets({account:t,chainFilter:[s]});return io.isWalletGetAssetsResponse(i)?(i[s]||[]).map(o=>io.createBalance(o,e.caipNetworkId)):null}catch{return null}},filterLowQualityTokens(t){return t.filter(e=>e.quantity.decimals!=="0")},mapBalancesToSwapTokens(t){return t?.map(e=>({...e,address:e?.address?e.address:g.getActiveNetworkTokenAddress(),decimals:parseInt(e.quantity.decimals,10),logoUri:e.iconUrl,eip2612:!1}))||[]}},ge=Oe({tokenBalances:[],loading:!1}),Rp={state:ge,subscribe(t){return it(ge,()=>t(ge))},subscribeKey(t,e){return nt(ge,t,e)},setToken(t){t&&(ge.token=Xs(t))},setTokenAmount(t){ge.sendTokenAmount=t},setReceiverAddress(t){ge.receiverAddress=t},setReceiverProfileImageUrl(t){ge.receiverProfileImageUrl=t},setReceiverProfileName(t){ge.receiverProfileName=t},setNetworkBalanceInUsd(t){ge.networkBalanceInUSD=t},setLoading(t){ge.loading=t},async sendToken(){try{switch(de.setLoading(!0),g.state.activeCaipNetwork?.chainNamespace){case"eip155":await de.sendEvmToken();return;case"solana":await de.sendSolanaToken();return;default:throw new Error("Unsupported chain")}}finally{de.setLoading(!1)}},async sendEvmToken(){const t=g.state.activeChain,e=H.state.preferredAccountTypes?.[t];if(!de.state.sendTokenAmount||!de.state.receiverAddress)throw new Error("An amount and receiver address are required");if(!de.state.token)throw new Error("A token is required");de.state.token?.address?(ke.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Ei.ACCOUNT_TYPES.SMART_ACCOUNT,token:de.state.token.address,amount:de.state.sendTokenAmount,network:g.state.activeCaipNetwork?.caipNetworkId||""}}),await de.sendERC20Token({receiverAddress:de.state.receiverAddress,tokenAddress:de.state.token.address,sendTokenAmount:de.state.sendTokenAmount,decimals:de.state.token.quantity.decimals})):(ke.sendEvent({type:"track",event:"SEND_INITIATED",properties:{isSmartAccount:e===Ei.ACCOUNT_TYPES.SMART_ACCOUNT,token:de.state.token.symbol||"",amount:de.state.sendTokenAmount,network:g.state.activeCaipNetwork?.caipNetworkId||""}}),await de.sendNativeToken({receiverAddress:de.state.receiverAddress,sendTokenAmount:de.state.sendTokenAmount,decimals:de.state.token.quantity.decimals}))},async fetchTokenBalance(t){ge.loading=!0;const e=g.state.activeCaipNetwork?.caipNetworkId,s=g.state.activeCaipNetwork?.chainNamespace,r=g.state.activeCaipAddress,i=r?X.getPlainAddress(r):void 0;if(ge.lastRetry&&!X.isAllowedRetry(ge.lastRetry,30*Ie.ONE_SEC_MS))return ge.loading=!1,[];try{if(i&&e&&s){const n=await Za.getMyTokensWithBalance();return ge.tokenBalances=n,ge.lastRetry=void 0,n}}catch(n){ge.lastRetry=Date.now(),t?.(n),Ft.showError("Token Balance Unavailable")}finally{ge.loading=!1}return[]},fetchNetworkBalance(){if(ge.tokenBalances.length===0)return;const t=Za.mapBalancesToSwapTokens(ge.tokenBalances);if(!t)return;const e=t.find(s=>s.address===g.getActiveNetworkTokenAddress());e&&(ge.networkBalanceInUSD=e?tp.multiply(e.quantity.numeric,e.price).toString():"0")},async sendNativeToken(t){ie.pushTransactionStack({});const e=t.receiverAddress,s=H.state.address,r=Y.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));await Y.sendTransaction({chainNamespace:"eip155",to:e,address:s,data:"0x",value:r??BigInt(0)}),ke.sendEvent({type:"track",event:"SEND_SUCCESS",properties:{isSmartAccount:H.state.preferredAccountTypes?.eip155===Ei.ACCOUNT_TYPES.SMART_ACCOUNT,token:de.state.token?.symbol||"",amount:t.sendTokenAmount,network:g.state.activeCaipNetwork?.caipNetworkId||""}}),Y._getClient()?.updateBalance("eip155"),de.resetSend()},async sendERC20Token(t){ie.pushTransactionStack({onSuccess(){ie.replace("Account")}});const e=Y.parseUnits(t.sendTokenAmount.toString(),Number(t.decimals));if(H.state.address&&t.sendTokenAmount&&t.receiverAddress&&t.tokenAddress){const s=X.getPlainAddress(t.tokenAddress);await Y.writeContract({fromAddress:H.state.address,tokenAddress:s,args:[t.receiverAddress,e??BigInt(0)],method:"transfer",abi:np.getERC20Abi(s),chainNamespace:"eip155"}),de.resetSend()}},async sendSolanaToken(){if(!de.state.sendTokenAmount||!de.state.receiverAddress)throw new Error("An amount and receiver address are required");ie.pushTransactionStack({onSuccess(){ie.replace("Account")}}),await Y.sendTransaction({chainNamespace:"solana",to:de.state.receiverAddress,value:de.state.sendTokenAmount}),Y._getClient()?.updateBalance("solana"),de.resetSend()},resetSend(){ge.token=void 0,ge.sendTokenAmount=void 0,ge.receiverAddress=void 0,ge.receiverProfileImageUrl=void 0,ge.receiverProfileName=void 0,ge.loading=!1,ge.tokenBalances=[]}},de=St(Rp),no={currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[],user:void 0},tn={caipNetwork:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]},M=Oe({chains:hp(),activeCaipAddress:void 0,activeChain:void 0,activeCaipNetwork:void 0,noAdapters:!1,universalAdapter:{networkControllerClient:void 0,connectionControllerClient:void 0},isSwitchingNamespace:!1}),Up={state:M,subscribe(t){return it(M,()=>{t(M)})},subscribeKey(t,e){return nt(M,t,e)},subscribeChainProp(t,e,s){let r;return it(M.chains,()=>{const i=s||M.activeChain;if(i){const n=M.chains.get(i)?.[t];r!==n&&(r=n,e(n))}})},initialize(t,e,s){const{chainId:r,namespace:i}=W.getActiveNetworkProps(),n=e?.find(u=>u.id.toString()===r?.toString()),a=t.find(u=>u?.namespace===i)||t?.[0],c=t.map(u=>u.namespace).filter(u=>u!==void 0),l=T.state.enableEmbedded?new Set([...c]):new Set([...e?.map(u=>u.chainNamespace)??[]]);(t?.length===0||!a)&&(M.noAdapters=!0),M.noAdapters||(M.activeChain=a?.namespace,M.activeCaipNetwork=n,g.setChainNetworkData(a?.namespace,{caipNetwork:n}),M.activeChain&&Ss.set({activeChain:a?.namespace})),l.forEach(u=>{const h=e?.filter(d=>d.chainNamespace===u);g.state.chains.set(u,{namespace:u,networkState:Oe({...tn,caipNetwork:h?.[0]}),accountState:Oe(no),caipNetworks:h??[],...s}),g.setRequestedCaipNetworks(h??[],u)})},removeAdapter(t){if(M.activeChain===t){const e=Array.from(M.chains.entries()).find(([s])=>s!==t);if(e){const s=e[1]?.caipNetworks?.[0];s&&g.setActiveCaipNetwork(s)}}M.chains.delete(t)},addAdapter(t,{networkControllerClient:e,connectionControllerClient:s},r){M.chains.set(t.namespace,{namespace:t.namespace,networkState:{...tn,caipNetwork:r[0]},accountState:no,caipNetworks:r,connectionControllerClient:s,networkControllerClient:e}),g.setRequestedCaipNetworks(r?.filter(i=>i.chainNamespace===t.namespace)??[],t.namespace)},addNetwork(t){const e=M.chains.get(t.chainNamespace);if(e){const s=[...e.caipNetworks||[]];e.caipNetworks?.find(r=>r.id===t.id)||s.push(t),M.chains.set(t.chainNamespace,{...e,caipNetworks:s}),g.setRequestedCaipNetworks(s,t.chainNamespace),q.filterByNamespace(t.chainNamespace,!0)}},removeNetwork(t,e){const s=M.chains.get(t);if(s){const r=M.activeCaipNetwork?.id===e,i=[...s.caipNetworks?.filter(n=>n.id!==e)||[]];r&&s?.caipNetworks?.[0]&&g.setActiveCaipNetwork(s.caipNetworks[0]),M.chains.set(t,{...s,caipNetworks:i}),g.setRequestedCaipNetworks(i||[],t),i.length===0&&q.filterByNamespace(t,!1)}},setAdapterNetworkState(t,e){const s=M.chains.get(t);s&&(s.networkState={...s.networkState||tn,...e},M.chains.set(t,s))},setChainAccountData(t,e,s=!0){if(!t)throw new Error("Chain is required to update chain account data");const r=M.chains.get(t);if(r){const i={...r.accountState||no,...e};M.chains.set(t,{...r,accountState:i}),(M.chains.size===1||M.activeChain===t)&&(e.caipAddress&&(M.activeCaipAddress=e.caipAddress),H.replaceState(i))}},setChainNetworkData(t,e){if(!t)return;const s=M.chains.get(t);if(s){const r={...s.networkState||tn,...e};M.chains.set(t,{...s,networkState:r})}},setAccountProp(t,e,s,r=!0){g.setChainAccountData(s,{[t]:e},r),t==="status"&&e==="disconnected"&&s&&q.removeConnectorId(s)},setActiveNamespace(t){M.activeChain=t;const e=t?M.chains.get(t):void 0,s=e?.networkState?.caipNetwork;s?.id&&t&&(M.activeCaipAddress=e?.accountState?.caipAddress,M.activeCaipNetwork=s,g.setChainNetworkData(t,{caipNetwork:s}),W.setActiveCaipNetworkId(s?.caipNetworkId),Ss.set({activeChain:t,selectedNetworkId:s?.caipNetworkId}))},setActiveCaipNetwork(t){if(!t)return;M.activeChain!==t.chainNamespace&&g.setIsSwitchingNamespace(!0);const e=M.chains.get(t.chainNamespace);M.activeChain=t.chainNamespace,M.activeCaipNetwork=t,g.setChainNetworkData(t.chainNamespace,{caipNetwork:t}),e?.accountState?.address?M.activeCaipAddress=`${t.chainNamespace}:${t.id}:${e?.accountState?.address}`:M.activeCaipAddress=void 0,g.setAccountProp("caipAddress",M.activeCaipAddress,t.chainNamespace),e&&H.replaceState(e.accountState),de.resetSend(),Ss.set({activeChain:M.activeChain,selectedNetworkId:M.activeCaipNetwork?.caipNetworkId}),W.setActiveCaipNetworkId(t.caipNetworkId),!g.checkIfSupportedNetwork(t.chainNamespace)&&T.state.enableNetworkSwitch&&!T.state.allowUnsupportedChain&&!Y.state.wcBasic&&g.showUnsupportedChainUI()},addCaipNetwork(t){if(!t)return;const e=M.chains.get(t.chainNamespace);e&&e?.caipNetworks?.push(t)},async switchActiveNamespace(t){if(!t)return;const e=t!==g.state.activeChain,s=g.getNetworkData(t)?.caipNetwork,r=g.getCaipNetworkByNamespace(t,s?.id);e&&r&&await g.switchActiveNetwork(r)},async switchActiveNetwork(t){const s=!g.state.chains.get(g.state.activeChain)?.caipNetworks?.some(i=>i.id===M.activeCaipNetwork?.id),r=g.getNetworkControllerClient(t.chainNamespace);if(r){try{await r.switchCaipNetwork(t),s&&Ge.close()}catch{ie.goBack()}ke.sendEvent({type:"track",event:"SWITCH_NETWORK",properties:{network:t.caipNetworkId}})}},getNetworkControllerClient(t){const e=t||M.activeChain,s=M.chains.get(e);if(!s)throw new Error("Chain adapter not found");if(!s.networkControllerClient)throw new Error("NetworkController client not set");return s.networkControllerClient},getConnectionControllerClient(t){const e=t||M.activeChain;if(!e)throw new Error("Chain is required to get connection controller client");const s=M.chains.get(e);if(!s?.connectionControllerClient)throw new Error("ConnectionController client not set");return s.connectionControllerClient},getAccountProp(t,e){let s=M.activeChain;if(e&&(s=e),!s)return;const r=M.chains.get(s)?.accountState;if(r)return r[t]},getNetworkProp(t,e){const s=M.chains.get(e)?.networkState;if(s)return s[t]},getRequestedCaipNetworks(t){const e=M.chains.get(t),{approvedCaipNetworkIds:s=[],requestedCaipNetworks:r=[]}=e?.networkState||{};return X.sortRequestedNetworks(s,r)},getAllRequestedCaipNetworks(){const t=[];return M.chains.forEach(e=>{const s=g.getRequestedCaipNetworks(e.namespace);t.push(...s)}),t},setRequestedCaipNetworks(t,e){g.setAdapterNetworkState(e,{requestedCaipNetworks:t});const r=g.getAllRequestedCaipNetworks().map(n=>n.chainNamespace),i=Array.from(new Set(r));q.filterByNamespaces(i)},getAllApprovedCaipNetworkIds(){const t=[];return M.chains.forEach(e=>{const s=g.getApprovedCaipNetworkIds(e.namespace);t.push(...s)}),t},getActiveCaipNetwork(){return M.activeCaipNetwork},getActiveCaipAddress(){return M.activeCaipAddress},getApprovedCaipNetworkIds(t){return M.chains.get(t)?.networkState?.approvedCaipNetworkIds||[]},async setApprovedCaipNetworksData(t){const s=await g.getNetworkControllerClient()?.getApprovedCaipNetworksData();g.setAdapterNetworkState(t,{approvedCaipNetworkIds:s?.approvedCaipNetworkIds,supportsAllNetworks:s?.supportsAllNetworks})},checkIfSupportedNetwork(t,e){const s=e||M.activeCaipNetwork,r=g.getRequestedCaipNetworks(t);return r.length?r?.some(i=>i.id===s?.id):!0},checkIfSupportedChainId(t){return M.activeChain?g.getRequestedCaipNetworks(M.activeChain)?.some(s=>s.id===t):!0},setSmartAccountEnabledNetworks(t,e){g.setAdapterNetworkState(e,{smartAccountEnabledNetworks:t})},checkIfSmartAccountEnabled(){const t=mu.caipNetworkIdToNumber(M.activeCaipNetwork?.caipNetworkId),e=M.activeChain;return!e||!t?!1:!!g.getNetworkProp("smartAccountEnabledNetworks",e)?.includes(Number(t))},getActiveNetworkTokenAddress(){const t=M.activeCaipNetwork?.chainNamespace||"eip155",e=M.activeCaipNetwork?.id||1,s=Ie.NATIVE_TOKEN_ADDRESS[t];return`${t}:${e}:${s}`},showUnsupportedChainUI(){Ge.open({view:"UnsupportedChain"})},checkIfNamesSupported(){const t=M.activeCaipNetwork;return!!(t?.chainNamespace&&Ie.NAMES_SUPPORTED_CHAIN_NAMESPACES.includes(t.chainNamespace))},resetNetwork(t){g.setAdapterNetworkState(t,{approvedCaipNetworkIds:void 0,supportsAllNetworks:!0,smartAccountEnabledNetworks:[]})},resetAccount(t){const e=t;if(!e)throw new Error("Chain is required to set account prop");M.activeCaipAddress=void 0,g.setChainAccountData(e,{smartAccountDeployed:!1,currentTab:0,caipAddress:void 0,address:void 0,balance:void 0,balanceSymbol:void 0,profileName:void 0,profileImage:void 0,addressExplorerUrl:void 0,tokenBalance:[],connectedWalletInfo:void 0,preferredAccountTypes:void 0,socialProvider:void 0,socialWindow:void 0,farcasterUrl:void 0,allAccounts:[],user:void 0,status:"disconnected"}),q.removeConnectorId(e)},setIsSwitchingNamespace(t){M.isSwitchingNamespace=t},getFirstCaipNetworkSupportsAuthConnector(){const t=[];let e;if(M.chains.forEach(s=>{j.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(r=>r===s.namespace)&&s.namespace&&t.push(s.namespace)}),t.length>0){const s=t[0];return e=s?M.chains.get(s)?.caipNetworks?.[0]:void 0,e}},getAccountData(t){return t?g.state.chains.get(t)?.accountState:H.state},getNetworkData(t){const e=t||M.activeChain;if(e)return g.state.chains.get(e)?.networkState},getCaipNetworkByNamespace(t,e){if(!t)return;const s=g.state.chains.get(t),r=s?.caipNetworks?.find(i=>i.id===e);return r||s?.networkState?.caipNetwork||s?.caipNetworks?.[0]},getRequestedCaipNetworkIds(){const t=q.state.filterByNamespace;return(t?[M.chains.get(t)]:Array.from(M.chains.values())).flatMap(s=>s?.caipNetworks||[]).map(s=>s.caipNetworkId)},getCaipNetworks(t){return t?g.getRequestedCaipNetworks(t):g.getAllRequestedCaipNetworks()}},g=St(Up),Dp={purchaseCurrencies:[{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},{id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"Ether",symbol:"ETH",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]}],paymentCurrencies:[{id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},{id:"EUR",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]}]},Cu=X.getBlockchainApiUrl(),ut=Oe({clientId:null,api:new Fi({baseUrl:Cu,clientId:null}),supportedChains:{http:[],ws:[]}}),J={state:ut,async get(t){const{st:e,sv:s}=J.getSdkProperties(),r=T.state.projectId,i={...t.params||{},st:e,sv:s,projectId:r};return ut.api.get({...t,params:i})},getSdkProperties(){const{sdkType:t,sdkVersion:e}=T.state;return{st:t||"unknown",sv:e||"unknown"}},async isNetworkSupported(t){if(!t)return!1;try{ut.supportedChains.http.length||await J.getSupportedNetworks()}catch{return!1}return ut.supportedChains.http.includes(t)},async getSupportedNetworks(){try{const t=await J.get({path:"v1/supported-chains"});return ut.supportedChains=t,t}catch{return ut.supportedChains}},async fetchIdentity({address:t,caipNetworkId:e}){if(!await J.isNetworkSupported(e))return{avatar:"",name:""};const r=W.getIdentityFromCacheForAddress(t);if(r)return r;const i=await J.get({path:`/v1/identity/${t}`,params:{sender:g.state.activeCaipAddress?X.getPlainAddress(g.state.activeCaipAddress):void 0}});return W.updateIdentityCache({address:t,identity:i,timestamp:Date.now()}),i},async fetchTransactions({account:t,cursor:e,onramp:s,signal:r,cache:i,chainId:n}){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?J.get({path:`/v1/account/${t}/history`,params:{cursor:e,onramp:s,chainId:n},signal:r,cache:i}):{data:[],next:void 0}},async fetchSwapQuote({amount:t,userAddress:e,from:s,to:r,gasPrice:i}){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?J.get({path:"/v1/convert/quotes",headers:{"Content-Type":"application/json"},params:{amount:t,userAddress:e,from:s,to:r,gasPrice:i}}):{quotes:[]}},async fetchSwapTokens({chainId:t}){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?J.get({path:"/v1/convert/tokens",params:{chainId:t}}):{tokens:[]}},async fetchTokenPrice({addresses:t}){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?ut.api.post({path:"/v1/fungible/price",body:{currency:"usd",addresses:t,projectId:T.state.projectId},headers:{"Content-Type":"application/json"}}):{fungibles:[]}},async fetchSwapAllowance({tokenAddress:t,userAddress:e}){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?J.get({path:"/v1/convert/allowance",params:{tokenAddress:t,userAddress:e},headers:{"Content-Type":"application/json"}}):{allowance:"0"}},async fetchGasPrice({chainId:t}){const{st:e,sv:s}=J.getSdkProperties();if(!await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Gas Price");return J.get({path:"/v1/convert/gas-price",headers:{"Content-Type":"application/json"},params:{chainId:t,st:e,sv:s}})},async generateSwapCalldata({amount:t,from:e,to:s,userAddress:r,disableEstimate:i}){if(!await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return ut.api.post({path:"/v1/convert/build-transaction",headers:{"Content-Type":"application/json"},body:{amount:t,eip155:{slippage:Ie.CONVERT_SLIPPAGE_TOLERANCE},projectId:T.state.projectId,from:e,to:s,userAddress:r,disableEstimate:i}})},async generateApproveCalldata({from:t,to:e,userAddress:s}){const{st:r,sv:i}=J.getSdkProperties();if(!await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId))throw new Error("Network not supported for Swaps");return J.get({path:"/v1/convert/build-approve",headers:{"Content-Type":"application/json"},params:{userAddress:s,from:t,to:e,st:r,sv:i}})},async getBalance(t,e,s){const{st:r,sv:i}=J.getSdkProperties();if(!await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId))return Ft.showError("Token Balance Unavailable"),{balances:[]};const o=`${e}:${t}`,a=W.getBalanceCacheForCaipAddress(o);if(a)return a;const c=await J.get({path:`/v1/account/${t}/balance`,params:{currency:"usd",chainId:e,forceUpdate:s,st:r,sv:i}});return W.updateBalanceCache({caipAddress:o,balance:c,timestamp:Date.now()}),c},async lookupEnsName(t){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?J.get({path:`/v1/profile/account/${t}`,params:{apiVersion:"2"}}):{addresses:{},attributes:[]}},async reverseLookupEnsName({address:t}){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?J.get({path:`/v1/profile/reverse/${t}`,params:{sender:H.state.address,apiVersion:"2"}}):[]},async getEnsNameSuggestions(t){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?J.get({path:`/v1/profile/suggestions/${t}`,params:{zone:"reown.id"}}):{suggestions:[]}},async registerEnsName({coinType:t,address:e,message:s,signature:r}){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?ut.api.post({path:"/v1/profile/account",body:{coin_type:t,address:e,message:s,signature:r},headers:{"Content-Type":"application/json"}}):{success:!1}},async generateOnRampURL({destinationWallets:t,partnerUserId:e,defaultNetwork:s,purchaseAmount:r,paymentAmount:i}){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?(await ut.api.post({path:"/v1/generators/onrampurl",params:{projectId:T.state.projectId},body:{destinationWallets:t,defaultNetwork:s,partnerUserId:e,defaultExperience:"buy",presetCryptoAmount:r,presetFiatAmount:i}})).url:""},async getOnrampOptions(){if(!await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId))return{paymentCurrencies:[],purchaseCurrencies:[]};try{return await J.get({path:"/v1/onramp/options"})}catch{return Dp}},async getOnrampQuote({purchaseCurrency:t,paymentCurrency:e,amount:s,network:r}){try{return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?await ut.api.post({path:"/v1/onramp/quote",params:{projectId:T.state.projectId},body:{purchaseCurrency:t,paymentCurrency:e,amount:s,network:r}}):null}catch{return{coinbaseFee:{amount:s,currency:e.id},networkFee:{amount:s,currency:e.id},paymentSubtotal:{amount:s,currency:e.id},paymentTotal:{amount:s,currency:e.id},purchaseAmount:{amount:s,currency:e.id},quoteId:"mocked-quote-id"}}},async getSmartSessions(t){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?J.get({path:`/v1/sessions/${t}`}):[]},async revokeSmartSession(t,e,s){return await J.isNetworkSupported(g.state.activeCaipNetwork?.caipNetworkId)?ut.api.post({path:`/v1/sessions/${t}/revoke`,params:{projectId:T.state.projectId},body:{pci:e,signature:s}}):{success:!1}},setClientId(t){ut.clientId=t,ut.api=new Fi({baseUrl:Cu,clientId:t})}},Pt=Oe({currentTab:0,tokenBalance:[],smartAccountDeployed:!1,addressLabels:new Map,allAccounts:[]}),Lp={state:Pt,replaceState(t){t&&Object.assign(Pt,Xs(t))},subscribe(t){return g.subscribeChainProp("accountState",e=>{if(e)return t(e)})},subscribeKey(t,e,s){let r;return g.subscribeChainProp("accountState",i=>{if(i){const n=i[t];r!==n&&(r=n,e(n))}},s)},setStatus(t,e){g.setAccountProp("status",t,e)},getCaipAddress(t){return g.getAccountProp("caipAddress",t)},setCaipAddress(t,e){const s=t?X.getPlainAddress(t):void 0;e===g.state.activeChain&&(g.state.activeCaipAddress=t),g.setAccountProp("caipAddress",t,e),g.setAccountProp("address",s,e)},setBalance(t,e,s){g.setAccountProp("balance",t,s),g.setAccountProp("balanceSymbol",e,s)},setProfileName(t,e){g.setAccountProp("profileName",t,e)},setProfileImage(t,e){g.setAccountProp("profileImage",t,e)},setUser(t,e){g.setAccountProp("user",t,e)},setAddressExplorerUrl(t,e){g.setAccountProp("addressExplorerUrl",t,e)},setSmartAccountDeployed(t,e){g.setAccountProp("smartAccountDeployed",t,e)},setCurrentTab(t){g.setAccountProp("currentTab",t,g.state.activeChain)},setTokenBalance(t,e){t&&g.setAccountProp("tokenBalance",t,e)},setShouldUpdateToAddress(t,e){g.setAccountProp("shouldUpdateToAddress",t,e)},setAllAccounts(t,e){g.setAccountProp("allAccounts",t,e)},addAddressLabel(t,e,s){const r=g.getAccountProp("addressLabels",s)||new Map;r.set(t,e),g.setAccountProp("addressLabels",r,s)},removeAddressLabel(t,e){const s=g.getAccountProp("addressLabels",e)||new Map;s.delete(t),g.setAccountProp("addressLabels",s,e)},setConnectedWalletInfo(t,e){g.setAccountProp("connectedWalletInfo",t,e,!1)},setPreferredAccountType(t,e){g.setAccountProp("preferredAccountTypes",{...Pt.preferredAccountTypes,[e]:t},e)},setPreferredAccountTypes(t){Pt.preferredAccountTypes=t},setSocialProvider(t,e){t&&g.setAccountProp("socialProvider",t,e)},setSocialWindow(t,e){g.setAccountProp("socialWindow",t?Xs(t):void 0,e)},setFarcasterUrl(t,e){g.setAccountProp("farcasterUrl",t,e)},async fetchTokenBalance(t){Pt.balanceLoading=!0;const e=g.state.activeCaipNetwork?.caipNetworkId,s=g.state.activeCaipNetwork?.chainNamespace,r=g.state.activeCaipAddress,i=r?X.getPlainAddress(r):void 0;if(Pt.lastRetry&&!X.isAllowedRetry(Pt.lastRetry,30*Ie.ONE_SEC_MS))return Pt.balanceLoading=!1,[];try{if(i&&e&&s){const o=(await J.getBalance(i,e)).balances.filter(a=>a.quantity.decimals!=="0");return H.setTokenBalance(o,s),Pt.lastRetry=void 0,Pt.balanceLoading=!1,o}}catch(n){Pt.lastRetry=Date.now(),t?.(n),Ft.showError("Token Balance Unavailable")}finally{Pt.balanceLoading=!1}return[]},resetAccount(t){g.resetAccount(t)}},H=St(Lp),Mp={onSwitchNetwork({network:t,ignoreSwitchConfirmation:e=!1}){const s=g.state.activeCaipNetwork,r=ie.state.data;if(t.id===s?.id)return;const n=H.getCaipAddress(g.state.activeChain),o=t.chainNamespace!==g.state.activeChain,a=H.getCaipAddress(t.chainNamespace),l=q.getConnectorId(g.state.activeChain)===j.CONNECTOR_ID.AUTH,u=j.AUTH_CONNECTOR_SUPPORTED_CHAINS.find(h=>h===t.chainNamespace);e||l&&u?ie.push("SwitchNetwork",{...r,network:t}):n&&o&&!a?ie.push("SwitchActiveChain",{switchToChain:t.chainNamespace,navigateTo:"Connect",navigateWithReplace:!0,network:t}):ie.push("SwitchNetwork",{...r,network:t})}},ht=Oe({loading:!1,loadingNamespaceMap:new Map,open:!1,shake:!1,namespace:void 0}),Bp={state:ht,subscribe(t){return it(ht,()=>t(ht))},subscribeKey(t,e){return nt(ht,t,e)},async open(t){const e=H.state.status==="connected",s=t?.namespace,r=g.state.activeChain,i=s&&s!==r,n=g.getAccountData(t?.namespace)?.caipAddress;if(Y.state.wcBasic?V.prefetch({fetchNetworkImages:!1,fetchConnectorImages:!1}):await V.prefetch({fetchConnectorImages:!e,fetchFeaturedWallets:!e,fetchRecommendedWallets:!e}),q.setFilterByNamespace(t?.namespace),Ge.setLoading(!0,s),s&&i){const o=g.getNetworkData(s)?.caipNetwork||g.getRequestedCaipNetworks(s)[0];o&&Mp.onSwitchNetwork({network:o,ignoreSwitchConfirmation:!0})}else{const o=g.state.noAdapters;T.state.manualWCControl||o&&!n?X.isMobile()?ie.reset("AllWallets"):ie.reset("ConnectingWalletConnectBasic"):t?.view?ie.reset(t.view,t.data):n?ie.reset("Account"):ie.reset("Connect")}ht.open=!0,Ss.set({open:!0}),ke.sendEvent({type:"track",event:"MODAL_OPEN",properties:{connected:!!n}})},close(){const t=T.state.enableEmbedded,e=!!g.state.activeCaipAddress;ht.open&&ke.sendEvent({type:"track",event:"MODAL_CLOSE",properties:{connected:e}}),ht.open=!1,ie.reset("Connect"),Ge.clearLoading(),t?e?ie.replace("Account"):ie.push("Connect"):Ss.set({open:!1}),Y.resetUri()},setLoading(t,e){e&&ht.loadingNamespaceMap.set(e,t),ht.loading=t,Ss.set({loading:t})},clearLoading(){ht.loadingNamespaceMap.clear(),ht.loading=!1},shake(){ht.shake||(ht.shake=!0,setTimeout(()=>{ht.shake=!1},500))}},Ge=St(Bp),Ci={id:"2b92315d-eab7-5bef-84fa-089a131333f5",name:"USD Coin",symbol:"USDC",networks:[{name:"ethereum-mainnet",display_name:"Ethereum",chain_id:"1",contract_address:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},{name:"polygon-mainnet",display_name:"Polygon",chain_id:"137",contract_address:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"}]},Mo={id:"USD",payment_method_limits:[{id:"card",min:"10.00",max:"7500.00"},{id:"ach_bank_account",min:"10.00",max:"25000.00"}]},jp={providers:bu,selectedProvider:null,error:null,purchaseCurrency:Ci,paymentCurrency:Mo,purchaseCurrencies:[Ci],paymentCurrencies:[],quotesLoading:!1},ae=Oe(jp),qp={state:ae,subscribe(t){return it(ae,()=>t(ae))},subscribeKey(t,e){return nt(ae,t,e)},setSelectedProvider(t){if(t&&t.name==="meld"){const e=g.state.activeChain===j.CHAIN.SOLANA?"SOL":"USDC",s=H.state.address??"",r=new URL(t.url);r.searchParams.append("publicKey",dp),r.searchParams.append("destinationCurrencyCode",e),r.searchParams.append("walletAddress",s),r.searchParams.append("externalCustomerId",T.state.projectId),ae.selectedProvider={...t,url:r.toString()}}else ae.selectedProvider=t},setOnrampProviders(t){if(Array.isArray(t)&&t.every(e=>typeof e=="string")){const e=t,s=bu.filter(r=>e.includes(r.name));ae.providers=s}else ae.providers=[]},setPurchaseCurrency(t){ae.purchaseCurrency=t},setPaymentCurrency(t){ae.paymentCurrency=t},setPurchaseAmount(t){Bo.state.purchaseAmount=t},setPaymentAmount(t){Bo.state.paymentAmount=t},async getAvailableCurrencies(){const t=await J.getOnrampOptions();ae.purchaseCurrencies=t.purchaseCurrencies,ae.paymentCurrencies=t.paymentCurrencies,ae.paymentCurrency=t.paymentCurrencies[0]||Mo,ae.purchaseCurrency=t.purchaseCurrencies[0]||Ci,await V.fetchCurrencyImages(t.paymentCurrencies.map(e=>e.id)),await V.fetchTokenImages(t.purchaseCurrencies.map(e=>e.symbol))},async getQuote(){ae.quotesLoading=!0;try{const t=await J.getOnrampQuote({purchaseCurrency:ae.purchaseCurrency,paymentCurrency:ae.paymentCurrency,amount:ae.paymentAmount?.toString()||"0",network:ae.purchaseCurrency?.symbol});return ae.quotesLoading=!1,ae.purchaseAmount=Number(t?.purchaseAmount.amount),t}catch(t){return ae.error=t.message,ae.quotesLoading=!1,null}finally{ae.quotesLoading=!1}},resetState(){ae.selectedProvider=null,ae.error=null,ae.purchaseCurrency=Ci,ae.paymentCurrency=Mo,ae.purchaseCurrencies=[Ci],ae.paymentCurrencies=[],ae.paymentAmount=void 0,ae.purchaseAmount=void 0,ae.quotesLoading=!1}},Bo=St(qp),Qa=2147483648,Fp={convertEVMChainIdToCoinType(t){if(t>=Qa)throw new Error("Invalid chainId");return(Qa|t)>>>0}},Ot=Oe({suggestions:[],loading:!1}),Wp={state:Ot,subscribe(t){return it(Ot,()=>t(Ot))},subscribeKey(t,e){return nt(Ot,t,e)},async resolveName(t){try{return await J.lookupEnsName(t)}catch(e){const s=e;throw new Error(s?.reasons?.[0]?.description||"Error resolving name")}},async isNameRegistered(t){try{return await J.lookupEnsName(t),!0}catch{return!1}},async getSuggestions(t){try{Ot.loading=!0,Ot.suggestions=[];const e=await J.getEnsNameSuggestions(t);return Ot.suggestions=e.suggestions.map(s=>({...s,name:s.name}))||[],Ot.suggestions}catch(e){const s=Ii.parseEnsApiError(e,"Error fetching name suggestions");throw new Error(s)}finally{Ot.loading=!1}},async getNamesForAddress(t){try{if(!g.state.activeCaipNetwork)return[];const s=W.getEnsFromCacheForAddress(t);if(s)return s;const r=await J.reverseLookupEnsName({address:t});return W.updateEnsCache({address:t,ens:r,timestamp:Date.now()}),r}catch(e){const s=Ii.parseEnsApiError(e,"Error fetching names for address");throw new Error(s)}},async registerName(t){const e=g.state.activeCaipNetwork;if(!e)throw new Error("Network not found");const s=H.state.address,r=q.getAuthConnector();if(!s||!r)throw new Error("Address or auth connector not found");Ot.loading=!0;try{const i=JSON.stringify({name:t,attributes:{},timestamp:Math.floor(Date.now()/1e3)});ie.pushTransactionStack({onCancel(){ie.replace("RegisterAccountName")}});const n=await Y.signMessage(i);Ot.loading=!1;const o=e.id;if(!o)throw new Error("Network not found");const a=Fp.convertEVMChainIdToCoinType(Number(o));await J.registerEnsName({coinType:a,address:s,signature:n,message:i}),H.setProfileName(t,e.chainNamespace),ie.replace("RegisterAccountNameSuccess")}catch(i){const n=Ii.parseEnsApiError(i,`Error registering name ${t}`);throw ie.replace("RegisterAccountName"),new Error(n)}finally{Ot.loading=!1}},validateName(t){return/^[a-zA-Z0-9-]{4,}$/u.test(t)},parseEnsApiError(t,e){return t?.reasons?.[0]?.description||e}},Ii=St(Wp);var Iu={exports:{}},Rr=typeof Reflect=="object"?Reflect:null,ec=Rr&&typeof Rr.apply=="function"?Rr.apply:function(e,s,r){return Function.prototype.apply.call(e,s,r)},mn;Rr&&typeof Rr.ownKeys=="function"?mn=Rr.ownKeys:Object.getOwnPropertySymbols?mn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:mn=function(e){return Object.getOwnPropertyNames(e)};function Hp(t){console&&console.warn&&console.warn(t)}var Nu=Number.isNaN||function(e){return e!==e};function be(){be.init.call(this)}Iu.exports=be;Iu.exports.once=Gp;be.EventEmitter=be;be.prototype._events=void 0;be.prototype._eventsCount=0;be.prototype._maxListeners=void 0;var tc=10;function qn(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(be,"defaultMaxListeners",{enumerable:!0,get:function(){return tc},set:function(t){if(typeof t!="number"||t<0||Nu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");tc=t}});be.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};be.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Nu(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function _u(t){return t._maxListeners===void 0?be.defaultMaxListeners:t._maxListeners}be.prototype.getMaxListeners=function(){return _u(this)};be.prototype.emit=function(e){for(var s=[],r=1;r<arguments.length;r++)s.push(arguments[r]);var i=e==="error",n=this._events;if(n!==void 0)i=i&&n.error===void 0;else if(!i)return!1;if(i){var o;if(s.length>0&&(o=s[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=n[e];if(c===void 0)return!1;if(typeof c=="function")ec(c,this,s);else for(var l=c.length,u=Tu(c,l),r=0;r<l;++r)ec(u[r],this,s);return!0};function Au(t,e,s,r){var i,n,o;if(qn(s),n=t._events,n===void 0?(n=t._events=Object.create(null),t._eventsCount=0):(n.newListener!==void 0&&(t.emit("newListener",e,s.listener?s.listener:s),n=t._events),o=n[e]),o===void 0)o=n[e]=s,++t._eventsCount;else if(typeof o=="function"?o=n[e]=r?[s,o]:[o,s]:r?o.unshift(s):o.push(s),i=_u(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,Hp(a)}return t}be.prototype.addListener=function(e,s){return Au(this,e,s,!1)};be.prototype.on=be.prototype.addListener;be.prototype.prependListener=function(e,s){return Au(this,e,s,!0)};function zp(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Su(t,e,s){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:s},i=zp.bind(r);return i.listener=s,r.wrapFn=i,i}be.prototype.once=function(e,s){return qn(s),this.on(e,Su(this,e,s)),this};be.prototype.prependOnceListener=function(e,s){return qn(s),this.prependListener(e,Su(this,e,s)),this};be.prototype.removeListener=function(e,s){var r,i,n,o,a;if(qn(s),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===s||r.listener===s)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||s));else if(typeof r!="function"){for(n=-1,o=r.length-1;o>=0;o--)if(r[o]===s||r[o].listener===s){a=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():Vp(r,n),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||s)}return this};be.prototype.off=be.prototype.removeListener;be.prototype.removeAllListeners=function(e){var s,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var n=Object.keys(r),o;for(i=0;i<n.length;++i)o=n[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(s=r[e],typeof s=="function")this.removeListener(e,s);else if(s!==void 0)for(i=s.length-1;i>=0;i--)this.removeListener(e,s[i]);return this};function Pu(t,e,s){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?s?[i.listener||i]:[i]:s?Kp(i):Tu(i,i.length)}be.prototype.listeners=function(e){return Pu(this,e,!0)};be.prototype.rawListeners=function(e){return Pu(this,e,!1)};be.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Ou.call(t,e)};be.prototype.listenerCount=Ou;function Ou(t){var e=this._events;if(e!==void 0){var s=e[t];if(typeof s=="function")return 1;if(s!==void 0)return s.length}return 0}be.prototype.eventNames=function(){return this._eventsCount>0?mn(this._events):[]};function Tu(t,e){for(var s=new Array(e),r=0;r<e;++r)s[r]=t[r];return s}function Vp(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Kp(t){for(var e=new Array(t.length),s=0;s<e.length;++s)e[s]=t[s].listener||t[s];return e}function Gp(t,e){return new Promise(function(s,r){function i(o){t.removeListener(e,n),r(o)}function n(){typeof t.removeListener=="function"&&t.removeListener("error",i),s([].slice.call(arguments))}ku(t,e,n,{once:!0}),e!=="error"&&Jp(t,i,{once:!0})})}function Jp(t,e,s){typeof t.on=="function"&&ku(t,"error",e,s)}function ku(t,e,s,r){if(typeof t.on=="function")r.once?t.once(e,s):t.on(e,s);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(n){r.once&&t.removeEventListener(e,i),s(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}const Ni={getSIWX(){return T.state.siwx},async initializeIfEnabled(){const t=T.state.siwx,e=g.getActiveCaipAddress();if(!(t&&e))return;const[s,r,i]=e.split(":");if(g.checkIfSupportedNetwork(s))try{if((await t.getSessions(`${s}:${r}`,i)).length)return;await Ge.open({view:"SIWXSignMessage"})}catch(n){console.error("SIWXUtil:initializeIfEnabled",n),ke.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:this.getSIWXEventProperties()}),await Y._getClient()?.disconnect().catch(console.error),ie.reset("Connect"),Ft.showError("A problem occurred while trying initialize authentication")}},async requestSignMessage(){const t=T.state.siwx,e=X.getPlainAddress(g.getActiveCaipAddress()),s=g.getActiveCaipNetwork(),r=Y._getClient();if(!t)throw new Error("SIWX is not enabled");if(!e)throw new Error("No ActiveCaipAddress found");if(!s)throw new Error("No ActiveCaipNetwork or client found");if(!r)throw new Error("No ConnectionController client found");try{const i=await t.createMessage({chainId:s.caipNetworkId,accountAddress:e}),n=i.toString();q.getConnectorId(s.chainNamespace)===j.CONNECTOR_ID.AUTH&&ie.pushTransactionStack({});const a=await r.signMessage(n);await t.addSession({data:i,message:n,signature:a}),Ge.close(),ke.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:this.getSIWXEventProperties()})}catch(i){const n=this.getSIWXEventProperties();(!Ge.state.open||ie.state.view==="ApproveTransaction")&&await Ge.open({view:"SIWXSignMessage"}),n.isSmartAccount?Ft.showError("This application might not support Smart Accounts"):Ft.showError("Signature declined"),ke.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:n}),console.error("SWIXUtil:requestSignMessage",i)}},async cancelSignMessage(){try{this.getSIWX()?.getRequired?.()?await Y.disconnect():Ge.close(),ie.reset("Connect"),ke.sendEvent({event:"CLICK_CANCEL_SIWX",type:"track",properties:this.getSIWXEventProperties()})}catch(t){console.error("SIWXUtil:cancelSignMessage",t)}},async getSessions(){const t=T.state.siwx,e=X.getPlainAddress(g.getActiveCaipAddress()),s=g.getActiveCaipNetwork();return t&&e&&s?t.getSessions(s.caipNetworkId,e):[]},async isSIWXCloseDisabled(){const t=this.getSIWX();if(t){const e=ie.state.view==="ApproveTransaction",s=ie.state.view==="SIWXSignMessage";if(e||s)return t.getRequired?.()&&(await this.getSessions()).length===0}return!1},async universalProviderAuthenticate({universalProvider:t,chains:e,methods:s}){const r=Ni.getSIWX(),i=new Set(e.map(a=>a.split(":")[0]));if(!r||i.size!==1||!i.has("eip155"))return!1;const n=await r.createMessage({chainId:g.getActiveCaipNetwork()?.caipNetworkId||"",accountAddress:""}),o=await t.authenticate({nonce:n.nonce,domain:n.domain,uri:n.uri,exp:n.expirationTime,iat:n.issuedAt,nbf:n.notBefore,requestId:n.requestId,version:n.version,resources:n.resources,statement:n.statement,chainId:n.chainId,methods:s,chains:[n.chainId,...e.filter(a=>a!==n.chainId)]});if(Ft.showLoading("Authenticating...",{autoClose:!1}),H.setConnectedWalletInfo({...o.session.peer.metadata,name:o.session.peer.metadata.name,icon:o.session.peer.metadata.icons?.[0],type:"WALLET_CONNECT"},Array.from(i)[0]),o?.auths?.length){const a=o.auths.map(c=>{const l=t.client.formatAuthMessage({request:c.p,iss:c.p.iss});return{data:{...c.p,accountAddress:c.p.iss.split(":").slice(-1).join(""),chainId:c.p.iss.split(":").slice(2,4).join(":"),uri:c.p.aud,version:c.p.version||n.version,expirationTime:c.p.exp,issuedAt:c.p.iat,notBefore:c.p.nbf},message:l,signature:c.s.s,cacao:c}});try{await r.setSessions(a),ke.sendEvent({type:"track",event:"SIWX_AUTH_SUCCESS",properties:Ni.getSIWXEventProperties()})}catch(c){throw console.error("SIWX:universalProviderAuth - failed to set sessions",c),ke.sendEvent({type:"track",event:"SIWX_AUTH_ERROR",properties:Ni.getSIWXEventProperties()}),await t.disconnect().catch(console.error),c}finally{Ft.hide()}}return!0},getSIWXEventProperties(){const t=g.state.activeChain;return{network:g.state.activeCaipNetwork?.caipNetworkId||"",isSmartAccount:H.state.preferredAccountTypes?.[t]===Ei.ACCOUNT_TYPES.SMART_ACCOUNT}},async clearSessions(){const t=this.getSIWX();t&&await t.setSessions([])}};var Ea={exports:{}},Ur=typeof Reflect=="object"?Reflect:null,sc=Ur&&typeof Ur.apply=="function"?Ur.apply:function(e,s,r){return Function.prototype.apply.call(e,s,r)},wn;Ur&&typeof Ur.ownKeys=="function"?wn=Ur.ownKeys:Object.getOwnPropertySymbols?wn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:wn=function(e){return Object.getOwnPropertyNames(e)};function Yp(t){console&&console.warn&&console.warn(t)}var xu=Number.isNaN||function(e){return e!==e};function ve(){ve.init.call(this)}Ea.exports=ve;Ea.exports.once=ef;ve.EventEmitter=ve;ve.prototype._events=void 0;ve.prototype._eventsCount=0;ve.prototype._maxListeners=void 0;var rc=10;function Fn(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ve,"defaultMaxListeners",{enumerable:!0,get:function(){return rc},set:function(t){if(typeof t!="number"||t<0||xu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");rc=t}});ve.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ve.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||xu(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function $u(t){return t._maxListeners===void 0?ve.defaultMaxListeners:t._maxListeners}ve.prototype.getMaxListeners=function(){return $u(this)};ve.prototype.emit=function(e){for(var s=[],r=1;r<arguments.length;r++)s.push(arguments[r]);var i=e==="error",n=this._events;if(n!==void 0)i=i&&n.error===void 0;else if(!i)return!1;if(i){var o;if(s.length>0&&(o=s[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=n[e];if(c===void 0)return!1;if(typeof c=="function")sc(c,this,s);else for(var l=c.length,u=Mu(c,l),r=0;r<l;++r)sc(u[r],this,s);return!0};function Ru(t,e,s,r){var i,n,o;if(Fn(s),n=t._events,n===void 0?(n=t._events=Object.create(null),t._eventsCount=0):(n.newListener!==void 0&&(t.emit("newListener",e,s.listener?s.listener:s),n=t._events),o=n[e]),o===void 0)o=n[e]=s,++t._eventsCount;else if(typeof o=="function"?o=n[e]=r?[s,o]:[o,s]:r?o.unshift(s):o.push(s),i=$u(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,Yp(a)}return t}ve.prototype.addListener=function(e,s){return Ru(this,e,s,!1)};ve.prototype.on=ve.prototype.addListener;ve.prototype.prependListener=function(e,s){return Ru(this,e,s,!0)};function Xp(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Uu(t,e,s){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:s},i=Xp.bind(r);return i.listener=s,r.wrapFn=i,i}ve.prototype.once=function(e,s){return Fn(s),this.on(e,Uu(this,e,s)),this};ve.prototype.prependOnceListener=function(e,s){return Fn(s),this.prependListener(e,Uu(this,e,s)),this};ve.prototype.removeListener=function(e,s){var r,i,n,o,a;if(Fn(s),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===s||r.listener===s)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||s));else if(typeof r!="function"){for(n=-1,o=r.length-1;o>=0;o--)if(r[o]===s||r[o].listener===s){a=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():Zp(r,n),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||s)}return this};ve.prototype.off=ve.prototype.removeListener;ve.prototype.removeAllListeners=function(e){var s,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var n=Object.keys(r),o;for(i=0;i<n.length;++i)o=n[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(s=r[e],typeof s=="function")this.removeListener(e,s);else if(s!==void 0)for(i=s.length-1;i>=0;i--)this.removeListener(e,s[i]);return this};function Du(t,e,s){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?s?[i.listener||i]:[i]:s?Qp(i):Mu(i,i.length)}ve.prototype.listeners=function(e){return Du(this,e,!0)};ve.prototype.rawListeners=function(e){return Du(this,e,!1)};ve.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Lu.call(t,e)};ve.prototype.listenerCount=Lu;function Lu(t){var e=this._events;if(e!==void 0){var s=e[t];if(typeof s=="function")return 1;if(s!==void 0)return s.length}return 0}ve.prototype.eventNames=function(){return this._eventsCount>0?wn(this._events):[]};function Mu(t,e){for(var s=new Array(e),r=0;r<e;++r)s[r]=t[r];return s}function Zp(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Qp(t){for(var e=new Array(t.length),s=0;s<e.length;++s)e[s]=t[s].listener||t[s];return e}function ef(t,e){return new Promise(function(s,r){function i(o){t.removeListener(e,n),r(o)}function n(){typeof t.removeListener=="function"&&t.removeListener("error",i),s([].slice.call(arguments))}Bu(t,e,n,{once:!0}),e!=="error"&&tf(t,i,{once:!0})})}function tf(t,e,s){typeof t.on=="function"&&Bu(t,"error",e,s)}function Bu(t,e,s,r){if(typeof t.on=="function")r.once?t.once(e,s):t.on(e,s);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(n){r.once&&t.removeEventListener(e,i),s(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var $s=Ea.exports;const Ca=Od($s);function sf(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function He(t,...e){try{return sf(t(...e))}catch(s){return Promise.reject(s)}}function rf(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function nf(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function yn(t){if(rf(t))return String(t);if(nf(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return yn(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const jo="base64:";function of(t){return typeof t=="string"?t:jo+lf(t)}function af(t){return typeof t!="string"||!t.startsWith(jo)?t:cf(t.slice(jo.length))}function cf(t){return globalThis.Buffer?Ye.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function lf(t){return globalThis.Buffer?Ye.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function ft(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function uf(...t){return ft(t.join(":"))}function sn(t){return t=ft(t),t?t+":":""}function hf(t,e){if(e===void 0)return!0;let s=0,r=t.indexOf(":");for(;r>-1;)s++,r=t.indexOf(":",r+1);return s<=e}function df(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const pf="memory",ff=()=>{const t=new Map;return{name:pf,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,s){t.set(e,s)},setItemRaw(e,s){t.set(e,s)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function gf(t={}){const e={mounts:{"":t.driver||ff()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},s=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},r=(l,u)=>e.mountpoints.filter(h=>h.startsWith(l)||u&&l.startsWith(h)).map(h=>({relativeBase:l.length>h.length?l.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),i=(l,u)=>{if(e.watching){u=ft(u);for(const h of e.watchListeners)h(l,u)}},n=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await ic(e.mounts[l],i,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,h)=>{const d=new Map,p=w=>{let m=d.get(w.base);return m||(m={driver:w.driver,base:w.base,items:[]},d.set(w.base,m)),m};for(const w of l){const m=typeof w=="string",f=ft(m?w:w.key),y=m?void 0:w.value,b=m||!w.options?u:{...u,...w.options},v=s(f);p(v).items.push({key:f,value:y,relativeKey:v.relativeKey,options:b})}return Promise.all([...d.values()].map(w=>h(w))).then(w=>w.flat())},c={hasItem(l,u={}){l=ft(l);const{relativeKey:h,driver:d}=s(l);return He(d.hasItem,h,u)},getItem(l,u={}){l=ft(l);const{relativeKey:h,driver:d}=s(l);return He(d.getItem,h,u).then(p=>en(p))},getItems(l,u={}){return a(l,u,h=>h.driver.getItems?He(h.driver.getItems,h.items.map(d=>({key:d.relativeKey,options:d.options})),u).then(d=>d.map(p=>({key:uf(h.base,p.key),value:en(p.value)}))):Promise.all(h.items.map(d=>He(h.driver.getItem,d.relativeKey,d.options).then(p=>({key:d.key,value:en(p)})))))},getItemRaw(l,u={}){l=ft(l);const{relativeKey:h,driver:d}=s(l);return d.getItemRaw?He(d.getItemRaw,h,u):He(d.getItem,h,u).then(p=>af(p))},async setItem(l,u,h={}){if(u===void 0)return c.removeItem(l);l=ft(l);const{relativeKey:d,driver:p}=s(l);p.setItem&&(await He(p.setItem,d,yn(u),h),p.watch||i("update",l))},async setItems(l,u){await a(l,u,async h=>{if(h.driver.setItems)return He(h.driver.setItems,h.items.map(d=>({key:d.relativeKey,value:yn(d.value),options:d.options})),u);h.driver.setItem&&await Promise.all(h.items.map(d=>He(h.driver.setItem,d.relativeKey,yn(d.value),d.options)))})},async setItemRaw(l,u,h={}){if(u===void 0)return c.removeItem(l,h);l=ft(l);const{relativeKey:d,driver:p}=s(l);if(p.setItemRaw)await He(p.setItemRaw,d,u,h);else if(p.setItem)await He(p.setItem,d,of(u),h);else return;p.watch||i("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=ft(l);const{relativeKey:h,driver:d}=s(l);d.removeItem&&(await He(d.removeItem,h,u),(u.removeMeta||u.removeMata)&&await He(d.removeItem,h+"$",u),d.watch||i("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=ft(l);const{relativeKey:h,driver:d}=s(l),p=Object.create(null);if(d.getMeta&&Object.assign(p,await He(d.getMeta,h,u)),!u.nativeOnly){const w=await He(d.getItem,h+"$",u).then(m=>en(m));w&&typeof w=="object"&&(typeof w.atime=="string"&&(w.atime=new Date(w.atime)),typeof w.mtime=="string"&&(w.mtime=new Date(w.mtime)),Object.assign(p,w))}return p},setMeta(l,u,h={}){return this.setItem(l+"$",u,h)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){l=sn(l);const h=r(l,!0);let d=[];const p=[];let w=!0;for(const f of h){f.driver.flags?.maxDepth||(w=!1);const y=await He(f.driver.getKeys,f.relativeBase,u);for(const b of y){const v=f.mountpoint+ft(b);d.some(C=>v.startsWith(C))||p.push(v)}d=[f.mountpoint,...d.filter(b=>!b.startsWith(f.mountpoint))]}const m=u.maxDepth!==void 0&&!w;return p.filter(f=>(!m||hf(f,u.maxDepth))&&df(f,l))},async clear(l,u={}){l=sn(l),await Promise.all(r(l,!1).map(async h=>{if(h.driver.clear)return He(h.driver.clear,h.relativeBase,u);if(h.driver.removeItem){const d=await h.driver.getKeys(h.relativeBase||"",u);return Promise.all(d.map(p=>h.driver.removeItem(p,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>nc(l)))},async watch(l){return await n(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=sn(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((h,d)=>d.length-h.length)),e.mounts[l]=u,e.watching&&Promise.resolve(ic(u,i,l)).then(h=>{e.unwatch[l]=h}).catch(console.error),c},async unmount(l,u=!0){l=sn(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&(e.unwatch[l]?.(),delete e.unwatch[l]),u&&await nc(e.mounts[l]),e.mountpoints=e.mountpoints.filter(h=>h!==l),delete e.mounts[l])},getMount(l=""){l=ft(l)+":";const u=s(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=ft(l),r(l,u.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,h={})=>c.setItem(l,u,h),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function ic(t,e,s){return t.watch?t.watch((r,i)=>e(r,s+i)):()=>{}}async function nc(t){typeof t.dispose=="function"&&await He(t.dispose)}const mf="idb-keyval";var wf=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",s=i=>e+i;let r;return t.dbName&&t.storeName&&(r=Md(t.dbName,t.storeName)),{name:mf,options:t,async hasItem(i){return!(typeof await Wa(s(i),r)>"u")},async getItem(i){return await Wa(s(i),r)??null},setItem(i,n){return Bd(s(i),n,r)},removeItem(i){return jd(s(i),r)},getKeys(){return qd(r)},clear(){return Fd(r)}}};const yf="WALLET_CONNECT_V2_INDEXED_DB",bf="keyvaluestorage";let vf=class{constructor(){this.indexedDb=gf({driver:wf({dbName:yf,storeName:bf})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const s=await this.indexedDb.getItem(e);if(s!==null)return s}async setItem(e,s){await this.indexedDb.setItem(e,wa(s))}async removeItem(e){await this.indexedDb.removeItem(e)}};var oo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Q<"u"?Q:typeof self<"u"?self:{},bn={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(s){return this.hasOwnProperty(s)?String(this[s]):null},t.prototype.setItem=function(s,r){this[s]=String(r)},t.prototype.removeItem=function(s){delete this[s]},t.prototype.clear=function(){const s=this;Object.keys(s).forEach(function(r){s[r]=void 0,delete s[r]})},t.prototype.key=function(s){return s=s||0,Object.keys(this)[s]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof oo<"u"&&oo.localStorage?bn.exports=oo.localStorage:typeof window<"u"&&window.localStorage?bn.exports=window.localStorage:bn.exports=new e})();function Ef(t){var e;return[t[0],Pn((e=t[1])!=null?e:"")]}let Cf=class{constructor(){this.localStorage=bn.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Ef)}async getItem(e){const s=this.localStorage.getItem(e);if(s!==null)return Pn(s)}async setItem(e,s){this.localStorage.setItem(e,wa(s))}async removeItem(e){this.localStorage.removeItem(e)}};const If="wc_storage_version",oc=1,Nf=async(t,e,s)=>{const r=If,i=await e.getItem(r);if(i&&i>=oc){s(e);return}const n=await t.getKeys();if(!n.length){s(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(r,oc),s(e),_f(t,o)},_f=async(t,e)=>{e.length&&e.forEach(async s=>{await t.removeItem(s)})};let Af=class{constructor(){this.initialized=!1,this.setInitialized=s=>{this.storage=s,this.initialized=!0};const e=new Cf;this.storage=e;try{const s=new vf;Nf(e,s,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,s){return await this.initialize(),this.storage.setItem(e,s)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const s=setInterval(()=>{this.initialized&&(clearInterval(s),e())},20)})}};var Sf=Object.defineProperty,Pf=(t,e,s)=>e in t?Sf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ac=(t,e,s)=>Pf(t,typeof e!="symbol"?e+"":e,s);let Of=class extends Yr{constructor(e){super(),this.opts=e,ac(this,"protocol","wc"),ac(this,"version",2)}};var Tf=Object.defineProperty,kf=(t,e,s)=>e in t?Tf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,xf=(t,e,s)=>kf(t,e+"",s);let $f=class extends Yr{constructor(e,s){super(),this.core=e,this.logger=s,xf(this,"records",new Map)}},Rf=class{constructor(e,s){this.logger=e,this.core=s}},Uf=class extends Yr{constructor(e,s){super(),this.relayer=e,this.logger=s}},Df=class extends Yr{constructor(e){super()}},Lf=class{constructor(e,s,r,i){this.core=e,this.logger=s,this.name=r}},Mf=class extends Yr{constructor(e,s){super(),this.relayer=e,this.logger=s}},Bf=class extends Yr{constructor(e,s){super(),this.core=e,this.logger=s}},jf=class{constructor(e,s,r){this.core=e,this.logger=s,this.store=r}},qf=class{constructor(e,s){this.projectId=e,this.logger=s}},Ff=class{constructor(e,s,r){this.core=e,this.logger=s,this.telemetryEnabled=r}};var Wf=Object.defineProperty,Hf=(t,e,s)=>e in t?Wf(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,cc=(t,e,s)=>Hf(t,typeof e!="symbol"?e+"":e,s);let zf=class{constructor(e){this.opts=e,cc(this,"protocol","wc"),cc(this,"version",2)}},Vf=class{constructor(e){this.client=e}};function ki(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function lc(t){return ki(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const ju="2.23.2";let ao={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:s})=>e?`${t??"https://viem.sh"}${e}${s?`#${s}`:""}`:void 0,version:`viem@${ju}`};class Zs extends Error{constructor(e,s={}){const r=s.cause instanceof Zs?s.cause.details:s.cause?.message?s.cause.message:s.details,i=s.cause instanceof Zs&&s.cause.docsPath||s.docsPath,n=ao.getDocsUrl?.({...s,docsPath:i}),o=[e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...ao.version?[`Version: ${ao.version}`]:[]].join(`
5
- `);super(o,s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=i,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=ju}walk(e){return qu(this,e)}}function qu(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?qu(t.cause,e):e?null:t}class Fu extends Zs{constructor({size:e,targetSize:s,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}}function Zr(t,{dir:e,size:s=32}={}){return typeof t=="string"?Kf(t,{dir:e,size:s}):Gf(t,{dir:e,size:s})}function Kf(t,{dir:e,size:s=32}={}){if(s===null)return t;const r=t.replace("0x","");if(r.length>s*2)throw new Fu({size:Math.ceil(r.length/2),targetSize:s,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function Gf(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new Fu({size:t.length,targetSize:s,type:"bytes"});const r=new Uint8Array(s);for(let i=0;i<s;i++){const n=e==="right";r[n?i:s-i-1]=t[n?i:t.length-i-1]}return r}class Jf extends Zs{constructor({max:e,min:s,signed:r,size:i,value:n}){super(`Number "${n}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${s} to ${e})`:`(above ${s})`}`,{name:"IntegerOutOfRangeError"})}}class Yf extends Zs{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Qr(t,{size:e}){if(lc(t)>e)throw new Yf({givenSize:lc(t),maxSize:e})}function qo(t,e={}){const{signed:s}=e;e.size&&Qr(t,{size:e.size});const r=BigInt(t);if(!s)return r;const i=(t.length-2)/2,n=(1n<<BigInt(i)*8n-1n)-1n;return r<=n?r:r-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function Xf(t,e={}){return Number(qo(t,e))}const Zf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Fo(t,e={}){return typeof t=="number"||typeof t=="bigint"?Hu(t,e):typeof t=="string"?tg(t,e):typeof t=="boolean"?Qf(t,e):Wu(t,e)}function Qf(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(Qr(s,{size:e.size}),Zr(s,{size:e.size})):s}function Wu(t,e={}){let s="";for(let i=0;i<t.length;i++)s+=Zf[t[i]];const r=`0x${s}`;return typeof e.size=="number"?(Qr(r,{size:e.size}),Zr(r,{dir:"right",size:e.size})):r}function Hu(t,e={}){const{signed:s,size:r}=e,i=BigInt(t);let n;r?s?n=(1n<<BigInt(r)*8n-1n)-1n:n=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&s?-n-1n:0;if(n&&i>n||i<o){const c=typeof t=="bigint"?"n":"";throw new Jf({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:s,size:r,value:`${t}${c}`})}const a=`0x${(s&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Zr(a,{size:r}):a}const eg=new TextEncoder;function tg(t,e={}){const s=eg.encode(t);return Wu(s,e)}const sg=new TextEncoder;function rg(t,e={}){return typeof t=="number"||typeof t=="bigint"?ng(t,e):typeof t=="boolean"?ig(t,e):ki(t)?zu(t,e):Vu(t,e)}function ig(t,e={}){const s=new Uint8Array(1);return s[0]=Number(t),typeof e.size=="number"?(Qr(s,{size:e.size}),Zr(s,{size:e.size})):s}const os={zero:48,nine:57,A:65,F:70,a:97,f:102};function uc(t){if(t>=os.zero&&t<=os.nine)return t-os.zero;if(t>=os.A&&t<=os.F)return t-(os.A-10);if(t>=os.a&&t<=os.f)return t-(os.a-10)}function zu(t,e={}){let s=t;e.size&&(Qr(s,{size:e.size}),s=Zr(s,{dir:"right",size:e.size}));let r=s.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,n=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=uc(r.charCodeAt(a++)),l=uc(r.charCodeAt(a++));if(c===void 0||l===void 0)throw new Zs(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);n[o]=c*16+l}return n}function ng(t,e){const s=Hu(t,e);return zu(s)}function Vu(t,e={}){const s=sg.encode(t);return typeof e.size=="number"?(Qr(s,{size:e.size}),Zr(s,{dir:"right",size:e.size})):s}function Tn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function og(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Wn(t,...e){if(!og(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function uN(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Tn(t.outputLen),Tn(t.blockLen)}function hc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ag(t,e){Wn(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const rn=BigInt(2**32-1),dc=BigInt(32);function cg(t,e=!1){return e?{h:Number(t&rn),l:Number(t>>dc&rn)}:{h:Number(t>>dc&rn)|0,l:Number(t&rn)|0}}function lg(t,e=!1){let s=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:n,l:o}=cg(t[i],e);[s[i],r[i]]=[n,o]}return[s,r]}const ug=(t,e,s)=>t<<s|e>>>32-s,hg=(t,e,s)=>e<<s|t>>>32-s,dg=(t,e,s)=>e<<s-32|t>>>64-s,pg=(t,e,s)=>t<<s-32|e>>>64-s,ur=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function fg(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function hN(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function dN(t,e){return t<<32-e|t>>>e}const pc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function gg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function fc(t){for(let e=0;e<t.length;e++)t[e]=gg(t[e])}function mg(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Ku(t){return typeof t=="string"&&(t=mg(t)),Wn(t),t}function pN(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Wn(i),e+=i.length}const s=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const n=t[r];s.set(n,i),i+=n.length}return s}class wg{clone(){return this._cloneInto()}}function yg(t){const e=r=>t().update(Ku(r)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function fN(t=32){if(ur&&typeof ur.getRandomValues=="function")return ur.getRandomValues(new Uint8Array(t));if(ur&&typeof ur.randomBytes=="function")return ur.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Gu=[],Ju=[],Yu=[],bg=BigInt(0),oi=BigInt(1),vg=BigInt(2),Eg=BigInt(7),Cg=BigInt(256),Ig=BigInt(113);for(let t=0,e=oi,s=1,r=0;t<24;t++){[s,r]=[r,(2*s+3*r)%5],Gu.push(2*(5*r+s)),Ju.push((t+1)*(t+2)/2%64);let i=bg;for(let n=0;n<7;n++)e=(e<<oi^(e>>Eg)*Ig)%Cg,e&vg&&(i^=oi<<(oi<<BigInt(n))-oi);Yu.push(i)}const[Ng,_g]=lg(Yu,!0),gc=(t,e,s)=>s>32?dg(t,e,s):ug(t,e,s),mc=(t,e,s)=>s>32?pg(t,e,s):hg(t,e,s);function Ag(t,e=24){const s=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],h=gc(l,u,1)^s[a],d=mc(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=d}let i=t[2],n=t[3];for(let o=0;o<24;o++){const a=Ju[o],c=gc(i,n,a),l=mc(i,n,a),u=Gu[o];i=t[u],n=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=Ng[r],t[1]^=_g[r]}s.fill(0)}class Ia extends wg{constructor(e,s,r,i=!1,n=24){if(super(),this.blockLen=e,this.suffix=s,this.outputLen=r,this.enableXOF=i,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Tn(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=fg(this.state)}keccak(){pc||fc(this.state32),Ag(this.state32,this.rounds),pc||fc(this.state32),this.posOut=0,this.pos=0}update(e){hc(this);const{blockLen:s,state:r}=this;e=Ku(e);const i=e.length;for(let n=0;n<i;){const o=Math.min(s-this.pos,i-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:r,blockLen:i}=this;e[r]^=s,s&128&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){hc(this,!1),Wn(e),this.finish();const s=this.state,{blockLen:r}=this;for(let i=0,n=e.length;i<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-i);e.set(s.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Tn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ag(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:s,suffix:r,outputLen:i,rounds:n,enableXOF:o}=this;return e||(e=new Ia(s,r,i,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Sg=(t,e,s)=>yg(()=>new Ia(e,t,s)),Pg=Sg(1,136,256/8);function Xu(t,e){const s=e||"hex",r=Pg(ki(t,{strict:!1})?rg(t):t);return s==="bytes"?r:Fo(r)}class Og extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const s=super.get(e);return super.has(e)&&s!==void 0&&(this.delete(e),super.set(e,s)),s}set(e,s){if(super.set(e,s),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const co=new Og(8192);function Tg(t,e){if(co.has(`${t}.${e}`))return co.get(`${t}.${e}`);const s=t.substring(2).toLowerCase(),r=Xu(Vu(s),"bytes"),i=s.split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(r[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const n=`0x${i.join("")}`;return co.set(`${t}.${e}`,n),n}function kg(t){const e=Xu(`0x${t.substring(4)}`).substring(26);return Tg(`0x${e}`)}async function xg({hash:t,signature:e}){const s=ki(t)?t:Fo(t),{secp256k1:r}=await Ro(async()=>{const{secp256k1:o}=await import("./secp256k1-DBlGGLNL.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3,4]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:h,yParity:d}=e,p=Number(d??h),w=wc(p);return new r.Signature(qo(l),qo(u)).addRecoveryBit(w)}const o=ki(e)?e:Fo(e),a=Xf(`0x${o.slice(130)}`),c=wc(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(s.substring(2)).toHex(!1)}`}function wc(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function $g({hash:t,signature:e}){return kg(await xg({hash:t,signature:e}))}function Rg(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<t.length;l++){const u=t.charAt(l),h=u.charCodeAt(0);if(e[h]!==255)throw new TypeError(u+" is ambiguous");e[h]=l}const s=t.length,r=t.charAt(0),i=Math.log(s)/Math.log(256),n=Math.log(256)/Math.log(s);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,h=0,d=0;const p=l.length;for(;d!==p&&l[d]===0;)d++,u++;const w=(p-d)*n+1>>>0,m=new Uint8Array(w);for(;d!==p;){let b=l[d],v=0;for(let C=w-1;(b!==0||v<h)&&C!==-1;C--,v++)b+=256*m[C]>>>0,m[C]=b%s>>>0,b=b/s>>>0;if(b!==0)throw new Error("Non-zero carry");h=v,d++}let f=w-h;for(;f!==w&&m[f]===0;)f++;let y=r.repeat(u);for(;f<w;++f)y+=t.charAt(m[f]);return y}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,h=0,d=0;for(;l[u]===r;)h++,u++;const p=(l.length-u)*i+1>>>0,w=new Uint8Array(p);for(;u<l.length;){const b=l.charCodeAt(u);if(b>255)return;let v=e[b];if(v===255)return;let C=0;for(let S=p-1;(v!==0||C<d)&&S!==-1;S--,C++)v+=s*w[S]>>>0,w[S]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");d=C,u++}let m=p-d;for(;m!==p&&w[m]===0;)m++;const f=new Uint8Array(h+(p-m));let y=h;for(;m!==p;)f[y++]=w[m++];return f}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+s+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Ug="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Zu=Rg(Ug);var Dg={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23657442558.commit-435eab3"};const Lg=":";function Dr(t){const[e,s]=t.split(Lg);return{namespace:e,reference:s}}function Qu(t,e){return t.includes(":")?[t]:e.chains||[]}var Mg=Object.defineProperty,Bg=Object.defineProperties,jg=Object.getOwnPropertyDescriptors,yc=Object.getOwnPropertySymbols,qg=Object.prototype.hasOwnProperty,Fg=Object.prototype.propertyIsEnumerable,bc=(t,e,s)=>e in t?Mg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vc=(t,e)=>{for(var s in e||(e={}))qg.call(e,s)&&bc(t,s,e[s]);if(yc)for(var s of yc(e))Fg.call(e,s)&&bc(t,s,e[s]);return t},Wg=(t,e)=>Bg(t,jg(e));const Hg="ReactNative",Nt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},zg="js";function kn(){return typeof As<"u"&&typeof As.versions<"u"&&typeof As.versions.node<"u"}function Rs(){return!Br()&&!!pu()&&navigator.product===Hg}function Vg(){return Rs()&&typeof Q<"u"&&typeof(Q==null?void 0:Q.Platform)<"u"&&(Q==null?void 0:Q.Platform.OS)==="android"}function Kg(){return Rs()&&typeof Q<"u"&&typeof(Q==null?void 0:Q.Platform)<"u"&&(Q==null?void 0:Q.Platform.OS)==="ios"}function ei(){return!kn()&&!!pu()&&!!Br()}function Wi(){return Rs()?Nt.reactNative:kn()?Nt.node:ei()?Nt.browser:Nt.unknown}function Ec(){var t;try{return Rs()&&typeof Q<"u"&&typeof(Q==null?void 0:Q.Application)<"u"?(t=Q.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Gg(t,e){const s=new URLSearchParams(t);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const i=e[r];i!==void 0&&s.set(r,i)}return s.toString()}function Jg(t){var e,s;const r=eh();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),Wg(vc(vc({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(s=t?.icons)!=null&&s.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function eh(){return Td()||{name:"",description:"",url:"",icons:[""]}}function Yg(){if(Wi()===Nt.reactNative&&typeof Q<"u"&&typeof(Q==null?void 0:Q.Platform)<"u"){const{OS:s,Version:r}=Q.Platform;return[s,r].join("-")}const t=xd();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function Xg(){var t;const e=Wi();return e===Nt.browser?[e,((t=$d())==null?void 0:t.host)||"unknown"].join(":"):e}function th(t,e,s){const r=Yg(),i=Xg();return[[t,e].join("-"),[zg,s].join("-"),r,i].join("/")}function Zg({protocol:t,version:e,relayUrl:s,sdkVersion:r,auth:i,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),u=th(t,e,r),h={auth:i,ua:u,projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},d=Gg(l[1]||"",h);return l[0]+"?"+d}function Ks(t,e){return t.filter(s=>e.includes(s)).length===t.length}function Wo(t){return Object.fromEntries(t.entries())}function Ho(t){return new Map(Object.entries(t))}function qs(t=D.FIVE_MINUTES,e){const s=D.toMiliseconds(t||D.FIVE_MINUTES);let r,i,n,o;return{resolve:a=>{n&&r&&(clearTimeout(n),r(a),o=Promise.resolve(a))},reject:a=>{n&&i&&(clearTimeout(n),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),r=a,i=c})}}function _s(t,e,s){return new Promise(async(r,i)=>{const n=setTimeout(()=>i(new Error(s)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(n)})}function sh(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function Qg(t){return sh("topic",t)}function em(t){return sh("id",t)}function rh(t){const[e,s]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")r.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))r.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return r}function Be(t,e){return D.fromMiliseconds(Date.now()+D.toMiliseconds(t))}function Es(t){return Date.now()>=D.toMiliseconds(t)}function fe(t,e){return`${t}${e?`:${e}`:""}`}function es(t=[],e=[]){return[...new Set([...t,...e])]}async function tm({id:t,topic:e,wcDeepLink:s}){var r;try{if(!s)return;const i=typeof s=="string"?JSON.parse(s):s,n=i?.href;if(typeof n!="string")return;const o=sm(n,t,e),a=Wi();if(a===Nt.browser){if(!((r=Br())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}rm(o)}else a===Nt.reactNative&&typeof(Q==null?void 0:Q.Linking)<"u"&&await Q.Linking.openURL(o)}catch(i){console.error(i)}}function sm(t,e,s){const r=`requestId=${e}&sessionTopic=${s}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${n}${am(r,!0)}`}else i=`${i}/wc?${r}`;return i}function rm(t){let e="_self";om()?e="_top":(nm()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function im(t,e){let s="";try{if(ei()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(r){console.error(r)}return s}function Cc(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),r=s.indexOf(e);return s[r+2]}function Ic(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Na(){return typeof As<"u"&&Dg.IS_VITEST==="true"}function nm(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function om(){try{return window.self!==window.top}catch{return!1}}function am(t,e=!1){const s=Ye.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function ih(t){return Ye.from(t,"base64").toString("utf-8")}function cm(t){return new Promise(e=>setTimeout(e,t))}function xi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function lm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Hi(t,...e){if(!lm(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function _a(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");xi(t.outputLen),xi(t.blockLen)}function qr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function nh(t,e){Hi(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const nn=BigInt(2**32-1),Nc=BigInt(32);function um(t,e=!1){return e?{h:Number(t&nn),l:Number(t>>Nc&nn)}:{h:Number(t>>Nc&nn)|0,l:Number(t&nn)|0}}function hm(t,e=!1){let s=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:n,l:o}=um(t[i],e);[s[i],r[i]]=[n,o]}return[s,r]}const dm=(t,e,s)=>t<<s|e>>>32-s,pm=(t,e,s)=>e<<s|t>>>32-s,fm=(t,e,s)=>e<<s-32|t>>>64-s,gm=(t,e,s)=>t<<s-32|e>>>64-s,hr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function mm(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function lo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Vt(t,e){return t<<32-e|t>>>e}const _c=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function wm(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Ac(t){for(let e=0;e<t.length;e++)t[e]=wm(t[e])}function ym(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Fr(t){return typeof t=="string"&&(t=ym(t)),Hi(t),t}function bm(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Hi(i),e+=i.length}const s=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const n=t[r];s.set(n,i),i+=n.length}return s}let Aa=class{clone(){return this._cloneInto()}};function oh(t){const e=r=>t().update(Fr(r)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function ti(t=32){if(hr&&typeof hr.getRandomValues=="function")return hr.getRandomValues(new Uint8Array(t));if(hr&&typeof hr.randomBytes=="function")return hr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const ah=[],ch=[],lh=[],vm=BigInt(0),ai=BigInt(1),Em=BigInt(2),Cm=BigInt(7),Im=BigInt(256),Nm=BigInt(113);for(let t=0,e=ai,s=1,r=0;t<24;t++){[s,r]=[r,(2*s+3*r)%5],ah.push(2*(5*r+s)),ch.push((t+1)*(t+2)/2%64);let i=vm;for(let n=0;n<7;n++)e=(e<<ai^(e>>Cm)*Nm)%Im,e&Em&&(i^=ai<<(ai<<BigInt(n))-ai);lh.push(i)}const[_m,Am]=hm(lh,!0),Sc=(t,e,s)=>s>32?fm(t,e,s):dm(t,e,s),Pc=(t,e,s)=>s>32?gm(t,e,s):pm(t,e,s);function Sm(t,e=24){const s=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],h=Sc(l,u,1)^s[a],d=Pc(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=d}let i=t[2],n=t[3];for(let o=0;o<24;o++){const a=ch[o],c=Sc(i,n,a),l=Pc(i,n,a),u=ah[o];i=t[u],n=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=_m[r],t[1]^=Am[r]}s.fill(0)}let Pm=class uh extends Aa{constructor(e,s,r,i=!1,n=24){if(super(),this.blockLen=e,this.suffix=s,this.outputLen=r,this.enableXOF=i,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,xi(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=mm(this.state)}keccak(){_c||Ac(this.state32),Sm(this.state32,this.rounds),_c||Ac(this.state32),this.posOut=0,this.pos=0}update(e){qr(this);const{blockLen:s,state:r}=this;e=Fr(e);const i=e.length;for(let n=0;n<i;){const o=Math.min(s-this.pos,i-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:r,blockLen:i}=this;e[r]^=s,s&128&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){qr(this,!1),Hi(e),this.finish();const s=this.state,{blockLen:r}=this;for(let i=0,n=e.length;i<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-i);e.set(s.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return xi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(nh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:s,suffix:r,outputLen:i,rounds:n,enableXOF:o}=this;return e||(e=new uh(s,r,i,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Om=(t,e,s)=>oh(()=>new Pm(e,t,s)),Tm=Om(1,136,256/8),km="https://rpc.walletconnect.org/v1";function hh(t){const e=`Ethereum Signed Message:
5
+ `);super(o,s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=i,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=ju}walk(e){return qu(this,e)}}function qu(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?qu(t.cause,e):e?null:t}class Fu extends Zs{constructor({size:e,targetSize:s,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${s}).`,{name:"SizeExceedsPaddingSizeError"})}}function Zr(t,{dir:e,size:s=32}={}){return typeof t=="string"?Kf(t,{dir:e,size:s}):Gf(t,{dir:e,size:s})}function Kf(t,{dir:e,size:s=32}={}){if(s===null)return t;const r=t.replace("0x","");if(r.length>s*2)throw new Fu({size:Math.ceil(r.length/2),targetSize:s,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](s*2,"0")}`}function Gf(t,{dir:e,size:s=32}={}){if(s===null)return t;if(t.length>s)throw new Fu({size:t.length,targetSize:s,type:"bytes"});const r=new Uint8Array(s);for(let i=0;i<s;i++){const n=e==="right";r[n?i:s-i-1]=t[n?i:t.length-i-1]}return r}class Jf extends Zs{constructor({max:e,min:s,signed:r,size:i,value:n}){super(`Number "${n}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${s} to ${e})`:`(above ${s})`}`,{name:"IntegerOutOfRangeError"})}}class Yf extends Zs{constructor({givenSize:e,maxSize:s}){super(`Size cannot exceed ${s} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Qr(t,{size:e}){if(lc(t)>e)throw new Yf({givenSize:lc(t),maxSize:e})}function qo(t,e={}){const{signed:s}=e;e.size&&Qr(t,{size:e.size});const r=BigInt(t);if(!s)return r;const i=(t.length-2)/2,n=(1n<<BigInt(i)*8n-1n)-1n;return r<=n?r:r-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function Xf(t,e={}){return Number(qo(t,e))}const Zf=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Fo(t,e={}){return typeof t=="number"||typeof t=="bigint"?Hu(t,e):typeof t=="string"?tg(t,e):typeof t=="boolean"?Qf(t,e):Wu(t,e)}function Qf(t,e={}){const s=`0x${Number(t)}`;return typeof e.size=="number"?(Qr(s,{size:e.size}),Zr(s,{size:e.size})):s}function Wu(t,e={}){let s="";for(let i=0;i<t.length;i++)s+=Zf[t[i]];const r=`0x${s}`;return typeof e.size=="number"?(Qr(r,{size:e.size}),Zr(r,{dir:"right",size:e.size})):r}function Hu(t,e={}){const{signed:s,size:r}=e,i=BigInt(t);let n;r?s?n=(1n<<BigInt(r)*8n-1n)-1n:n=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&s?-n-1n:0;if(n&&i>n||i<o){const c=typeof t=="bigint"?"n":"";throw new Jf({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:s,size:r,value:`${t}${c}`})}const a=`0x${(s&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Zr(a,{size:r}):a}const eg=new TextEncoder;function tg(t,e={}){const s=eg.encode(t);return Wu(s,e)}const sg=new TextEncoder;function rg(t,e={}){return typeof t=="number"||typeof t=="bigint"?ng(t,e):typeof t=="boolean"?ig(t,e):ki(t)?zu(t,e):Vu(t,e)}function ig(t,e={}){const s=new Uint8Array(1);return s[0]=Number(t),typeof e.size=="number"?(Qr(s,{size:e.size}),Zr(s,{size:e.size})):s}const os={zero:48,nine:57,A:65,F:70,a:97,f:102};function uc(t){if(t>=os.zero&&t<=os.nine)return t-os.zero;if(t>=os.A&&t<=os.F)return t-(os.A-10);if(t>=os.a&&t<=os.f)return t-(os.a-10)}function zu(t,e={}){let s=t;e.size&&(Qr(s,{size:e.size}),s=Zr(s,{dir:"right",size:e.size}));let r=s.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,n=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=uc(r.charCodeAt(a++)),l=uc(r.charCodeAt(a++));if(c===void 0||l===void 0)throw new Zs(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);n[o]=c*16+l}return n}function ng(t,e){const s=Hu(t,e);return zu(s)}function Vu(t,e={}){const s=sg.encode(t);return typeof e.size=="number"?(Qr(s,{size:e.size}),Zr(s,{dir:"right",size:e.size})):s}function Tn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function og(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Wn(t,...e){if(!og(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function uN(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Tn(t.outputLen),Tn(t.blockLen)}function hc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ag(t,e){Wn(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const rn=BigInt(2**32-1),dc=BigInt(32);function cg(t,e=!1){return e?{h:Number(t&rn),l:Number(t>>dc&rn)}:{h:Number(t>>dc&rn)|0,l:Number(t&rn)|0}}function lg(t,e=!1){let s=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:n,l:o}=cg(t[i],e);[s[i],r[i]]=[n,o]}return[s,r]}const ug=(t,e,s)=>t<<s|e>>>32-s,hg=(t,e,s)=>e<<s|t>>>32-s,dg=(t,e,s)=>e<<s-32|t>>>64-s,pg=(t,e,s)=>t<<s-32|e>>>64-s,ur=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function fg(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function hN(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function dN(t,e){return t<<32-e|t>>>e}const pc=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function gg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function fc(t){for(let e=0;e<t.length;e++)t[e]=gg(t[e])}function mg(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Ku(t){return typeof t=="string"&&(t=mg(t)),Wn(t),t}function pN(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Wn(i),e+=i.length}const s=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const n=t[r];s.set(n,i),i+=n.length}return s}class wg{clone(){return this._cloneInto()}}function yg(t){const e=r=>t().update(Ku(r)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function fN(t=32){if(ur&&typeof ur.getRandomValues=="function")return ur.getRandomValues(new Uint8Array(t));if(ur&&typeof ur.randomBytes=="function")return ur.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Gu=[],Ju=[],Yu=[],bg=BigInt(0),oi=BigInt(1),vg=BigInt(2),Eg=BigInt(7),Cg=BigInt(256),Ig=BigInt(113);for(let t=0,e=oi,s=1,r=0;t<24;t++){[s,r]=[r,(2*s+3*r)%5],Gu.push(2*(5*r+s)),Ju.push((t+1)*(t+2)/2%64);let i=bg;for(let n=0;n<7;n++)e=(e<<oi^(e>>Eg)*Ig)%Cg,e&vg&&(i^=oi<<(oi<<BigInt(n))-oi);Yu.push(i)}const[Ng,_g]=lg(Yu,!0),gc=(t,e,s)=>s>32?dg(t,e,s):ug(t,e,s),mc=(t,e,s)=>s>32?pg(t,e,s):hg(t,e,s);function Ag(t,e=24){const s=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],h=gc(l,u,1)^s[a],d=mc(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=d}let i=t[2],n=t[3];for(let o=0;o<24;o++){const a=Ju[o],c=gc(i,n,a),l=mc(i,n,a),u=Gu[o];i=t[u],n=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=Ng[r],t[1]^=_g[r]}s.fill(0)}class Ia extends wg{constructor(e,s,r,i=!1,n=24){if(super(),this.blockLen=e,this.suffix=s,this.outputLen=r,this.enableXOF=i,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Tn(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=fg(this.state)}keccak(){pc||fc(this.state32),Ag(this.state32,this.rounds),pc||fc(this.state32),this.posOut=0,this.pos=0}update(e){hc(this);const{blockLen:s,state:r}=this;e=Ku(e);const i=e.length;for(let n=0;n<i;){const o=Math.min(s-this.pos,i-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:r,blockLen:i}=this;e[r]^=s,s&128&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){hc(this,!1),Wn(e),this.finish();const s=this.state,{blockLen:r}=this;for(let i=0,n=e.length;i<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-i);e.set(s.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Tn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ag(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:s,suffix:r,outputLen:i,rounds:n,enableXOF:o}=this;return e||(e=new Ia(s,r,i,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Sg=(t,e,s)=>yg(()=>new Ia(e,t,s)),Pg=Sg(1,136,256/8);function Xu(t,e){const s=e||"hex",r=Pg(ki(t,{strict:!1})?rg(t):t);return s==="bytes"?r:Fo(r)}class Og extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const s=super.get(e);return super.has(e)&&s!==void 0&&(this.delete(e),super.set(e,s)),s}set(e,s){if(super.set(e,s),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const co=new Og(8192);function Tg(t,e){if(co.has(`${t}.${e}`))return co.get(`${t}.${e}`);const s=t.substring(2).toLowerCase(),r=Xu(Vu(s),"bytes"),i=s.split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(r[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const n=`0x${i.join("")}`;return co.set(`${t}.${e}`,n),n}function kg(t){const e=Xu(`0x${t.substring(4)}`).substring(26);return Tg(`0x${e}`)}async function xg({hash:t,signature:e}){const s=ki(t)?t:Fo(t),{secp256k1:r}=await Ro(async()=>{const{secp256k1:o}=await import("./secp256k1-C5qQ4FUv.js");return{secp256k1:o}},__vite__mapDeps([0,1,2,3,4]));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:l,s:u,v:h,yParity:d}=e,p=Number(d??h),w=wc(p);return new r.Signature(qo(l),qo(u)).addRecoveryBit(w)}const o=ki(e)?e:Fo(e),a=Xf(`0x${o.slice(130)}`),c=wc(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(s.substring(2)).toHex(!1)}`}function wc(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function $g({hash:t,signature:e}){return kg(await xg({hash:t,signature:e}))}function Rg(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<t.length;l++){const u=t.charAt(l),h=u.charCodeAt(0);if(e[h]!==255)throw new TypeError(u+" is ambiguous");e[h]=l}const s=t.length,r=t.charAt(0),i=Math.log(s)/Math.log(256),n=Math.log(256)/Math.log(s);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,h=0,d=0;const p=l.length;for(;d!==p&&l[d]===0;)d++,u++;const w=(p-d)*n+1>>>0,m=new Uint8Array(w);for(;d!==p;){let b=l[d],v=0;for(let C=w-1;(b!==0||v<h)&&C!==-1;C--,v++)b+=256*m[C]>>>0,m[C]=b%s>>>0,b=b/s>>>0;if(b!==0)throw new Error("Non-zero carry");h=v,d++}let f=w-h;for(;f!==w&&m[f]===0;)f++;let y=r.repeat(u);for(;f<w;++f)y+=t.charAt(m[f]);return y}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,h=0,d=0;for(;l[u]===r;)h++,u++;const p=(l.length-u)*i+1>>>0,w=new Uint8Array(p);for(;u<l.length;){const b=l.charCodeAt(u);if(b>255)return;let v=e[b];if(v===255)return;let C=0;for(let S=p-1;(v!==0||C<d)&&S!==-1;S--,C++)v+=s*w[S]>>>0,w[S]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");d=C,u++}let m=p-d;for(;m!==p&&w[m]===0;)m++;const f=new Uint8Array(h+(p-m));let y=h;for(;m!==p;)f[y++]=w[m++];return f}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+s+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Ug="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Zu=Rg(Ug);var Dg={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23658354807.commit-e695ac8"};const Lg=":";function Dr(t){const[e,s]=t.split(Lg);return{namespace:e,reference:s}}function Qu(t,e){return t.includes(":")?[t]:e.chains||[]}var Mg=Object.defineProperty,Bg=Object.defineProperties,jg=Object.getOwnPropertyDescriptors,yc=Object.getOwnPropertySymbols,qg=Object.prototype.hasOwnProperty,Fg=Object.prototype.propertyIsEnumerable,bc=(t,e,s)=>e in t?Mg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vc=(t,e)=>{for(var s in e||(e={}))qg.call(e,s)&&bc(t,s,e[s]);if(yc)for(var s of yc(e))Fg.call(e,s)&&bc(t,s,e[s]);return t},Wg=(t,e)=>Bg(t,jg(e));const Hg="ReactNative",Nt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},zg="js";function kn(){return typeof As<"u"&&typeof As.versions<"u"&&typeof As.versions.node<"u"}function Rs(){return!Br()&&!!pu()&&navigator.product===Hg}function Vg(){return Rs()&&typeof Q<"u"&&typeof(Q==null?void 0:Q.Platform)<"u"&&(Q==null?void 0:Q.Platform.OS)==="android"}function Kg(){return Rs()&&typeof Q<"u"&&typeof(Q==null?void 0:Q.Platform)<"u"&&(Q==null?void 0:Q.Platform.OS)==="ios"}function ei(){return!kn()&&!!pu()&&!!Br()}function Wi(){return Rs()?Nt.reactNative:kn()?Nt.node:ei()?Nt.browser:Nt.unknown}function Ec(){var t;try{return Rs()&&typeof Q<"u"&&typeof(Q==null?void 0:Q.Application)<"u"?(t=Q.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Gg(t,e){const s=new URLSearchParams(t);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const i=e[r];i!==void 0&&s.set(r,i)}return s.toString()}function Jg(t){var e,s;const r=eh();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),Wg(vc(vc({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(s=t?.icons)!=null&&s.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function eh(){return Td()||{name:"",description:"",url:"",icons:[""]}}function Yg(){if(Wi()===Nt.reactNative&&typeof Q<"u"&&typeof(Q==null?void 0:Q.Platform)<"u"){const{OS:s,Version:r}=Q.Platform;return[s,r].join("-")}const t=xd();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function Xg(){var t;const e=Wi();return e===Nt.browser?[e,((t=$d())==null?void 0:t.host)||"unknown"].join(":"):e}function th(t,e,s){const r=Yg(),i=Xg();return[[t,e].join("-"),[zg,s].join("-"),r,i].join("/")}function Zg({protocol:t,version:e,relayUrl:s,sdkVersion:r,auth:i,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=s.split("?"),u=th(t,e,r),h={auth:i,ua:u,projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},d=Gg(l[1]||"",h);return l[0]+"?"+d}function Ks(t,e){return t.filter(s=>e.includes(s)).length===t.length}function Wo(t){return Object.fromEntries(t.entries())}function Ho(t){return new Map(Object.entries(t))}function qs(t=D.FIVE_MINUTES,e){const s=D.toMiliseconds(t||D.FIVE_MINUTES);let r,i,n,o;return{resolve:a=>{n&&r&&(clearTimeout(n),r(a),o=Promise.resolve(a))},reject:a=>{n&&i&&(clearTimeout(n),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},s),r=a,i=c})}}function _s(t,e,s){return new Promise(async(r,i)=>{const n=setTimeout(()=>i(new Error(s)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(n)})}function sh(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function Qg(t){return sh("topic",t)}function em(t){return sh("id",t)}function rh(t){const[e,s]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof s=="string")r.topic=s;else if(e==="id"&&Number.isInteger(Number(s)))r.id=Number(s);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${s}`);return r}function Be(t,e){return D.fromMiliseconds(Date.now()+D.toMiliseconds(t))}function Es(t){return Date.now()>=D.toMiliseconds(t)}function fe(t,e){return`${t}${e?`:${e}`:""}`}function es(t=[],e=[]){return[...new Set([...t,...e])]}async function tm({id:t,topic:e,wcDeepLink:s}){var r;try{if(!s)return;const i=typeof s=="string"?JSON.parse(s):s,n=i?.href;if(typeof n!="string")return;const o=sm(n,t,e),a=Wi();if(a===Nt.browser){if(!((r=Br())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}rm(o)}else a===Nt.reactNative&&typeof(Q==null?void 0:Q.Linking)<"u"&&await Q.Linking.openURL(o)}catch(i){console.error(i)}}function sm(t,e,s){const r=`requestId=${e}&sessionTopic=${s}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${n}${am(r,!0)}`}else i=`${i}/wc?${r}`;return i}function rm(t){let e="_self";om()?e="_top":(nm()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function im(t,e){let s="";try{if(ei()&&(s=localStorage.getItem(e),s))return s;s=await t.getItem(e)}catch(r){console.error(r)}return s}function Cc(t,e){if(!t.includes(e))return null;const s=t.split(/([&,?,=])/),r=s.indexOf(e);return s[r+2]}function Ic(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function Na(){return typeof As<"u"&&Dg.IS_VITEST==="true"}function nm(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function om(){try{return window.self!==window.top}catch{return!1}}function am(t,e=!1){const s=Ye.from(t).toString("base64");return e?s.replace(/[=]/g,""):s}function ih(t){return Ye.from(t,"base64").toString("utf-8")}function cm(t){return new Promise(e=>setTimeout(e,t))}function xi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function lm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Hi(t,...e){if(!lm(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function _a(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");xi(t.outputLen),xi(t.blockLen)}function qr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function nh(t,e){Hi(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}const nn=BigInt(2**32-1),Nc=BigInt(32);function um(t,e=!1){return e?{h:Number(t&nn),l:Number(t>>Nc&nn)}:{h:Number(t>>Nc&nn)|0,l:Number(t&nn)|0}}function hm(t,e=!1){let s=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:n,l:o}=um(t[i],e);[s[i],r[i]]=[n,o]}return[s,r]}const dm=(t,e,s)=>t<<s|e>>>32-s,pm=(t,e,s)=>e<<s|t>>>32-s,fm=(t,e,s)=>e<<s-32|t>>>64-s,gm=(t,e,s)=>t<<s-32|e>>>64-s,hr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function mm(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function lo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Vt(t,e){return t<<32-e|t>>>e}const _c=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function wm(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Ac(t){for(let e=0;e<t.length;e++)t[e]=wm(t[e])}function ym(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Fr(t){return typeof t=="string"&&(t=ym(t)),Hi(t),t}function bm(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Hi(i),e+=i.length}const s=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const n=t[r];s.set(n,i),i+=n.length}return s}let Aa=class{clone(){return this._cloneInto()}};function oh(t){const e=r=>t().update(Fr(r)).digest(),s=t();return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=()=>t(),e}function ti(t=32){if(hr&&typeof hr.getRandomValues=="function")return hr.getRandomValues(new Uint8Array(t));if(hr&&typeof hr.randomBytes=="function")return hr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const ah=[],ch=[],lh=[],vm=BigInt(0),ai=BigInt(1),Em=BigInt(2),Cm=BigInt(7),Im=BigInt(256),Nm=BigInt(113);for(let t=0,e=ai,s=1,r=0;t<24;t++){[s,r]=[r,(2*s+3*r)%5],ah.push(2*(5*r+s)),ch.push((t+1)*(t+2)/2%64);let i=vm;for(let n=0;n<7;n++)e=(e<<ai^(e>>Cm)*Nm)%Im,e&Em&&(i^=ai<<(ai<<BigInt(n))-ai);lh.push(i)}const[_m,Am]=hm(lh,!0),Sc=(t,e,s)=>s>32?fm(t,e,s):dm(t,e,s),Pc=(t,e,s)=>s>32?gm(t,e,s):pm(t,e,s);function Sm(t,e=24){const s=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)s[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],h=Sc(l,u,1)^s[a],d=Pc(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=d}let i=t[2],n=t[3];for(let o=0;o<24;o++){const a=ch[o],c=Sc(i,n,a),l=Pc(i,n,a),u=ah[o];i=t[u],n=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}t[0]^=_m[r],t[1]^=Am[r]}s.fill(0)}let Pm=class uh extends Aa{constructor(e,s,r,i=!1,n=24){if(super(),this.blockLen=e,this.suffix=s,this.outputLen=r,this.enableXOF=i,this.rounds=n,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,xi(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=mm(this.state)}keccak(){_c||Ac(this.state32),Sm(this.state32,this.rounds),_c||Ac(this.state32),this.posOut=0,this.pos=0}update(e){qr(this);const{blockLen:s,state:r}=this;e=Fr(e);const i=e.length;for(let n=0;n<i;){const o=Math.min(s-this.pos,i-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:r,blockLen:i}=this;e[r]^=s,s&128&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){qr(this,!1),Hi(e),this.finish();const s=this.state,{blockLen:r}=this;for(let i=0,n=e.length;i<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-i);e.set(s.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return xi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(nh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:s,suffix:r,outputLen:i,rounds:n,enableXOF:o}=this;return e||(e=new uh(s,r,i,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Om=(t,e,s)=>oh(()=>new Pm(e,t,s)),Tm=Om(1,136,256/8),km="https://rpc.walletconnect.org/v1";function hh(t){const e=`Ethereum Signed Message:
6
6
  ${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Ye.from(Tm(s)).toString("hex")}async function xm(t,e,s,r,i,n){switch(s.t){case"eip191":return await $m(t,e,s.s);case"eip1271":return await Rm(t,e,s.s,r,i,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${s.t}`)}}async function $m(t,e,s){return(await $g({hash:hh(e),signature:s})).toLowerCase()===t.toLowerCase()}async function Rm(t,e,s,r,i,n){const o=Dr(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l="0000000000000000000000000000000000000000000000000000000000000041",u=s.substring(2),h=hh(e).substring(2),d=a+h+c+l+u,p=await fetch(`${n||km}/?chainId=${r}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:Um(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:w}=await p.json();return w?w.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Um(){return Date.now()+Math.floor(Math.random()*1e3)}function Dm(t){const e=atob(t),s=new Uint8Array(e.length);for(let o=0;o<e.length;o++)s[o]=e.charCodeAt(o);const r=s[0];if(r===0)throw new Error("No signatures found");const i=1+r*64;if(s.length<i)throw new Error("Transaction data too short for claimed signature count");if(s.length<100)throw new Error("Transaction too short");const n=Ye.from(t,"base64").slice(1,65);return Zu.encode(n)}var Lm=Object.defineProperty,Mm=Object.defineProperties,Bm=Object.getOwnPropertyDescriptors,Oc=Object.getOwnPropertySymbols,jm=Object.prototype.hasOwnProperty,qm=Object.prototype.propertyIsEnumerable,Tc=(t,e,s)=>e in t?Lm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Fm=(t,e)=>{for(var s in e||(e={}))jm.call(e,s)&&Tc(t,s,e[s]);if(Oc)for(var s of Oc(e))qm.call(e,s)&&Tc(t,s,e[s]);return t},Wm=(t,e)=>Mm(t,Bm(e));const Hm="did:pkh:",Sa=t=>t?.split(":"),zm=t=>{const e=t&&Sa(t);if(e)return t.includes(Hm)?e[3]:e[1]},zo=t=>{const e=t&&Sa(t);if(e)return e[2]+":"+e[3]},xn=t=>{const e=t&&Sa(t);if(e)return e.pop()};async function kc(t){const{cacao:e,projectId:s}=t,{s:r,p:i}=e,n=dh(i,i.iss),o=xn(i.iss);return await xm(o,n,r,zo(i.iss),s)}const dh=(t,e)=>{const s=`${t.domain} wants you to sign in with your Ethereum account:`,r=xn(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0;const n=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${zm(e)}`,c=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,u=t.exp?`Expiration Time: ${t.exp}`:void 0,h=t.nbf?`Not Before: ${t.nbf}`:void 0,d=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(m=>`
7
7
  - ${m}`).join("")}`:void 0,w=vn(t.resources);if(w){const m=$i(w);i=ew(i,m)}return[s,r,"",i,"",n,o,a,c,l,u,h,d,p].filter(m=>m!=null).join(`
8
8
  `)};function Vm(t){return Ye.from(JSON.stringify(t)).toString("base64")}function Km(t){return JSON.parse(Ye.from(t,"base64").toString("utf-8"))}function Qs(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(s=>{const r=t.att[s];if(Array.isArray(r))throw new Error(`Resource must be an object: ${s}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${s}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${s}`);Object.keys(r).forEach(i=>{const n=r[i];if(!Array.isArray(n))throw new Error(`Ability limits ${i} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function Gm(t,e,s,r={}){return s?.sort((i,n)=>i.localeCompare(n)),{att:{[t]:Jm(e,s,r)}}}function Jm(t,e,s={}){e=e?.sort((i,n)=>i.localeCompare(n));const r=e.map(i=>({[`${t}/${i}`]:[s]}));return Object.assign({},...r)}function ph(t){return Qs(t),`urn:recap:${Vm(t).replace(/=/g,"")}`}function $i(t){const e=Km(t.replace("urn:recap:",""));return Qs(e),e}function Ym(t,e,s){const r=Gm(t,e,s);return ph(r)}function Xm(t){return t&&t.includes("urn:recap:")}function Zm(t,e){const s=$i(t),r=$i(e),i=Qm(s,r);return ph(i)}function Qm(t,e){Qs(t),Qs(e);const s=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,n)=>i.localeCompare(n)),r={att:{}};return s.forEach(i=>{var n,o;Object.keys(((n=t.att)==null?void 0:n[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;r.att[i]=Wm(Fm({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((l=e.att[i])==null?void 0:l[a])})})}),r}function ew(t="",e){Qs(e);const s="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(s))return t;const r=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,d)=>h.action.localeCompare(d.action));const l={};c.forEach(h=>{l[h.ability]||(l[h.ability]=[]),l[h.ability].push(h.action)});const u=Object.keys(l).map(h=>(i++,`(${i}) '${h}': '${l[h].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const n=r.join(" "),o=`${s}${n}`;return`${t?t+" ":""}${o}`}function xc(t){var e;const s=$i(t);Qs(s);const r=(e=s.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function $c(t){const e=$i(t);Qs(e);const s=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(i=>{var n;(n=i?.[0])!=null&&n.chains&&s.push(i[0].chains)})}),[...new Set(s.flat())]}function vn(t){if(!t)return;const e=t?.[t.length-1];return Xm(e)?e:void 0}function uo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function fh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function It(t,...e){if(!fh(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Rc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function tw(t,e){It(t);const s=e.outputLen;if(t.length<s)throw new Error("digestInto() expects output buffer of length at least "+s)}function Uc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const Ps=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),sw=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),rw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!rw)throw new Error("Non little-endian hardware is not supported");function iw(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Vo(t){if(typeof t=="string")t=iw(t);else if(fh(t))t=Ko(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function nw(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function ow(t,e){if(t.length!==e.length)return!1;let s=0;for(let r=0;r<t.length;r++)s|=t[r]^e[r];return s===0}const aw=(t,e)=>{function s(r,...i){if(It(r),t.nonceLength!==void 0){const l=i[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?It(l):It(l,t.nonceLength)}const n=t.tagLength;n&&i[1]!==void 0&&It(i[1]);const o=e(r,...i),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");It(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,It(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(It(l),n&&l.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(s,t),s};function Dc(t,e,s=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(s&&!cw(e))throw new Error("invalid output, must be aligned");return e}function Lc(t,e,s,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,r);const i=BigInt(32),n=BigInt(4294967295),o=Number(s>>i&n),a=Number(s&n);t.setUint32(e+4,o,r),t.setUint32(e+0,a,r)}function cw(t){return t.byteOffset%4===0}function Ko(t){return Uint8Array.from(t)}function Wr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const gh=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),lw=gh("expand 16-byte k"),uw=gh("expand 32-byte k"),hw=Ps(lw),dw=Ps(uw);function le(t,e){return t<<e|t>>>32-e}function Go(t){return t.byteOffset%4===0}const on=64,pw=16,mh=2**32-1,Mc=new Uint32Array;function fw(t,e,s,r,i,n,o,a){const c=i.length,l=new Uint8Array(on),u=Ps(l),h=Go(i)&&Go(n),d=h?Ps(i):Mc,p=h?Ps(n):Mc;for(let w=0;w<c;o++){if(t(e,s,r,u,o,a),o>=mh)throw new Error("arx: counter overflow");const m=Math.min(on,c-w);if(h&&m===on){const f=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let y=0,b;y<pw;y++)b=f+y,p[b]=d[b]^u[y];w+=on;continue}for(let f=0,y;f<m;f++)y=w+f,n[y]=i[y]^l[f];w+=m}}function gw(t,e){const{allowShortKeys:s,extendNonceFn:r,counterLength:i,counterRight:n,rounds:o}=nw({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return uo(i),uo(o),Uc(n),Uc(s),(a,c,l,u,h=0)=>{It(a),It(c),It(l);const d=l.length;if(u===void 0&&(u=new Uint8Array(d)),It(u),uo(h),h<0||h>=mh)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);const p=[];let w=a.length,m,f;if(w===32)p.push(m=Ko(a)),f=dw;else if(w===16&&s)m=new Uint8Array(32),m.set(a),m.set(a,16),f=hw,p.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);Go(c)||p.push(c=Ko(c));const y=Ps(m);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(f,y,Ps(c.subarray(0,16)),y),c=c.subarray(16)}const b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){const C=new Uint8Array(12);C.set(c,n?0:12-c.length),c=C,p.push(c)}const v=Ps(c);return fw(t,f,y,v,l,u,h,o),Wr(...p),u}}const Xe=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class mw{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=Vo(e),It(e,32);const s=Xe(e,0),r=Xe(e,2),i=Xe(e,4),n=Xe(e,6),o=Xe(e,8),a=Xe(e,10),c=Xe(e,12),l=Xe(e,14);this.r[0]=s&8191,this.r[1]=(s>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Xe(e,16+2*u)}process(e,s,r=!1){const i=r?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],h=o[4],d=o[5],p=o[6],w=o[7],m=o[8],f=o[9],y=Xe(e,s+0),b=Xe(e,s+2),v=Xe(e,s+4),C=Xe(e,s+6),S=Xe(e,s+8),_=Xe(e,s+10),A=Xe(e,s+12),U=Xe(e,s+14);let E=n[0]+(y&8191),$=n[1]+((y>>>13|b<<3)&8191),I=n[2]+((b>>>10|v<<6)&8191),L=n[3]+((v>>>7|C<<9)&8191),z=n[4]+((C>>>4|S<<12)&8191),N=n[5]+(S>>>1&8191),k=n[6]+((S>>>14|_<<2)&8191),O=n[7]+((_>>>11|A<<5)&8191),B=n[8]+((A>>>8|U<<8)&8191),F=n[9]+(U>>>5|i),x=0,G=x+E*a+$*(5*f)+I*(5*m)+L*(5*w)+z*(5*p);x=G>>>13,G&=8191,G+=N*(5*d)+k*(5*h)+O*(5*u)+B*(5*l)+F*(5*c),x+=G>>>13,G&=8191;let ee=x+E*c+$*a+I*(5*f)+L*(5*m)+z*(5*w);x=ee>>>13,ee&=8191,ee+=N*(5*p)+k*(5*d)+O*(5*h)+B*(5*u)+F*(5*l),x+=ee>>>13,ee&=8191;let re=x+E*l+$*c+I*a+L*(5*f)+z*(5*m);x=re>>>13,re&=8191,re+=N*(5*w)+k*(5*p)+O*(5*d)+B*(5*h)+F*(5*u),x+=re>>>13,re&=8191;let Ne=x+E*u+$*l+I*c+L*a+z*(5*f);x=Ne>>>13,Ne&=8191,Ne+=N*(5*m)+k*(5*w)+O*(5*p)+B*(5*d)+F*(5*h),x+=Ne>>>13,Ne&=8191;let pe=x+E*h+$*u+I*l+L*c+z*a;x=pe>>>13,pe&=8191,pe+=N*(5*f)+k*(5*m)+O*(5*w)+B*(5*p)+F*(5*d),x+=pe>>>13,pe&=8191;let $e=x+E*d+$*h+I*u+L*l+z*c;x=$e>>>13,$e&=8191,$e+=N*a+k*(5*f)+O*(5*m)+B*(5*w)+F*(5*p),x+=$e>>>13,$e&=8191;let qe=x+E*p+$*d+I*h+L*u+z*l;x=qe>>>13,qe&=8191,qe+=N*c+k*a+O*(5*f)+B*(5*m)+F*(5*w),x+=qe>>>13,qe&=8191;let tt=x+E*w+$*p+I*d+L*h+z*u;x=tt>>>13,tt&=8191,tt+=N*l+k*c+O*a+B*(5*f)+F*(5*m),x+=tt>>>13,tt&=8191;let De=x+E*m+$*w+I*p+L*d+z*h;x=De>>>13,De&=8191,De+=N*u+k*l+O*c+B*a+F*(5*f),x+=De>>>13,De&=8191;let Le=x+E*f+$*m+I*w+L*p+z*d;x=Le>>>13,Le&=8191,Le+=N*h+k*u+O*l+B*c+F*a,x+=Le>>>13,Le&=8191,x=(x<<2)+x|0,x=x+G|0,G=x&8191,x=x>>>13,ee+=x,n[0]=G,n[1]=ee,n[2]=re,n[3]=Ne,n[4]=pe,n[5]=$e,n[6]=qe,n[7]=tt,n[8]=De,n[9]=Le}finalize(){const{h:e,pad:s}=this,r=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let n=(i^1)-1;for(let a=0;a<10;a++)r[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+s[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+s[a]|0)+(o>>>16)|0,e[a]=o&65535;Wr(r)}update(e){Rc(this);const{buffer:s,blockLen:r}=this;e=Vo(e);const i=e.length;for(let n=0;n<i;){const o=Math.min(r-this.pos,i-n);if(o===r){for(;r<=i-n;n+=r)this.process(e,n);continue}s.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===r&&(this.process(s,0,!1),this.pos=0)}return this}destroy(){Wr(this.h,this.r,this.buffer,this.pad)}digestInto(e){Rc(this),tw(e,this),this.finished=!0;const{buffer:s,h:r}=this;let{pos:i}=this;if(i){for(s[i++]=1;i<16;i++)s[i]=0;this.process(s,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=r[o]>>>0,e[n++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const r=e.slice(0,s);return this.destroy(),r}}function ww(t){const e=(r,i)=>t(i).update(Vo(r)).digest(),s=t(new Uint8Array(32));return e.outputLen=s.outputLen,e.blockLen=s.blockLen,e.create=r=>t(r),e}const yw=ww(t=>new mw(t));function bw(t,e,s,r,i,n=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],h=e[1],d=e[2],p=e[3],w=e[4],m=e[5],f=e[6],y=e[7],b=i,v=s[0],C=s[1],S=s[2],_=o,A=a,U=c,E=l,$=u,I=h,L=d,z=p,N=w,k=m,O=f,B=y,F=b,x=v,G=C,ee=S;for(let Ne=0;Ne<n;Ne+=2)_=_+$|0,F=le(F^_,16),N=N+F|0,$=le($^N,12),_=_+$|0,F=le(F^_,8),N=N+F|0,$=le($^N,7),A=A+I|0,x=le(x^A,16),k=k+x|0,I=le(I^k,12),A=A+I|0,x=le(x^A,8),k=k+x|0,I=le(I^k,7),U=U+L|0,G=le(G^U,16),O=O+G|0,L=le(L^O,12),U=U+L|0,G=le(G^U,8),O=O+G|0,L=le(L^O,7),E=E+z|0,ee=le(ee^E,16),B=B+ee|0,z=le(z^B,12),E=E+z|0,ee=le(ee^E,8),B=B+ee|0,z=le(z^B,7),_=_+I|0,ee=le(ee^_,16),O=O+ee|0,I=le(I^O,12),_=_+I|0,ee=le(ee^_,8),O=O+ee|0,I=le(I^O,7),A=A+L|0,F=le(F^A,16),B=B+F|0,L=le(L^B,12),A=A+L|0,F=le(F^A,8),B=B+F|0,L=le(L^B,7),U=U+z|0,x=le(x^U,16),N=N+x|0,z=le(z^N,12),U=U+z|0,x=le(x^U,8),N=N+x|0,z=le(z^N,7),E=E+$|0,G=le(G^E,16),k=k+G|0,$=le($^k,12),E=E+$|0,G=le(G^E,8),k=k+G|0,$=le($^k,7);let re=0;r[re++]=o+_|0,r[re++]=a+A|0,r[re++]=c+U|0,r[re++]=l+E|0,r[re++]=u+$|0,r[re++]=h+I|0,r[re++]=d+L|0,r[re++]=p+z|0,r[re++]=w+N|0,r[re++]=m+k|0,r[re++]=f+O|0,r[re++]=y+B|0,r[re++]=b+F|0,r[re++]=v+x|0,r[re++]=C+G|0,r[re++]=S+ee|0}const vw=gw(bw,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Ew=new Uint8Array(16),Bc=(t,e)=>{t.update(e);const s=e.length%16;s&&t.update(Ew.subarray(s))},Cw=new Uint8Array(32);function jc(t,e,s,r,i){const n=t(e,s,Cw),o=yw.create(n);i&&Bc(o,i),Bc(o,r);const a=new Uint8Array(16),c=sw(a);Lc(c,0,BigInt(i?i.length:0),!0),Lc(c,8,BigInt(r.length),!0),o.update(a);const l=o.digest();return Wr(n,a),l}const Iw=t=>(e,s,r)=>({encrypt(i,n){const o=i.length;n=Dc(o+16,n,!1),n.set(i);const a=n.subarray(0,-16);t(e,s,a,a,1);const c=jc(t,e,s,a,r);return n.set(c,o),Wr(c),n},decrypt(i,n){n=Dc(i.length-16,n,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=jc(t,e,s,o,r);if(!ow(a,c))throw new Error("invalid tag");return n.set(i.subarray(0,-16)),t(e,s,n,n,1),Wr(c),n}}),wh=aw({blockSize:64,nonceLength:12,tagLength:16},Iw(vw));let yh=class extends Aa{constructor(e,s){super(),this.finished=!1,this.destroyed=!1,_a(e);const r=Fr(s);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,n=new Uint8Array(i);n.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),n.fill(0)}update(e){return qr(this),this.iHash.update(e),this}digestInto(e){qr(this),Hi(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:r,finished:i,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Hn=(t,e,s)=>new yh(t,e).update(s).digest();Hn.create=(t,e)=>new yh(t,e);function Nw(t,e,s){return _a(t),s===void 0&&(s=new Uint8Array(t.outputLen)),Hn(t,Fr(s),Fr(e))}const ho=new Uint8Array([0]),qc=new Uint8Array;function _w(t,e,s,r=32){if(_a(t),xi(r),r>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/t.outputLen);s===void 0&&(s=qc);const n=new Uint8Array(i*t.outputLen),o=Hn.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let l=0;l<i;l++)ho[0]=l+1,a.update(l===0?qc:c).update(s).update(ho).digestInto(c),n.set(c,t.outputLen*l),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),ho.fill(0),n.slice(0,r)}const Aw=(t,e,s,r,i)=>_w(t,Nw(t,e,s),r,i);function Sw(t,e,s,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,s,r);const i=BigInt(32),n=BigInt(4294967295),o=Number(s>>i&n),a=Number(s&n),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function Pw(t,e,s){return t&e^~t&s}function Ow(t,e,s){return t&e^t&s^e&s}let Tw=class extends Aa{constructor(e,s,r,i){super(),this.blockLen=e,this.outputLen=s,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=lo(this.buffer)}update(e){qr(this);const{view:s,buffer:r,blockLen:i}=this;e=Fr(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(i-this.pos,n-o);if(a===i){const c=lo(e);for(;i<=n-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){qr(this),nh(e,this),this.finished=!0;const{buffer:s,view:r,blockLen:i,isLE:n}=this;let{pos:o}=this;s[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let h=o;h<i;h++)s[h]=0;Sw(r,i-8,BigInt(this.length*8),n),this.process(r,0);const a=lo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],n)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const r=e.slice(0,s);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:r,length:i,finished:n,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=n,e.destroyed=o,i%s&&e.buffer.set(r),e}};const kw=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ys=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),bs=new Uint32Array(64);class xw extends Tw{constructor(){super(64,32,8,!1),this.A=ys[0]|0,this.B=ys[1]|0,this.C=ys[2]|0,this.D=ys[3]|0,this.E=ys[4]|0,this.F=ys[5]|0,this.G=ys[6]|0,this.H=ys[7]|0}get(){const{A:e,B:s,C:r,D:i,E:n,F:o,G:a,H:c}=this;return[e,s,r,i,n,o,a,c]}set(e,s,r,i,n,o,a,c){this.A=e|0,this.B=s|0,this.C=r|0,this.D=i|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let h=0;h<16;h++,s+=4)bs[h]=e.getUint32(s,!1);for(let h=16;h<64;h++){const d=bs[h-15],p=bs[h-2],w=Vt(d,7)^Vt(d,18)^d>>>3,m=Vt(p,17)^Vt(p,19)^p>>>10;bs[h]=m+bs[h-7]+w+bs[h-16]|0}let{A:r,B:i,C:n,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const d=Vt(a,6)^Vt(a,11)^Vt(a,25),p=u+d+Pw(a,c,l)+kw[h]+bs[h]|0,w=(Vt(r,2)^Vt(r,13)^Vt(r,22))+Ow(r,i,n)|0;u=l,l=c,c=a,a=o+p|0,o=n,n=i,i=r,r=p+w|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,i,n,o,a,c,l,u)}roundClean(){bs.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const zi=oh(()=>new xw);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const zn=BigInt(0),Vn=BigInt(1),$w=BigInt(2);function er(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Vi(t){if(!er(t))throw new Error("Uint8Array expected")}function Hr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Rw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function zr(t){Vi(t);let e="";for(let s=0;s<t.length;s++)e+=Rw[t[s]];return e}function kr(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Pa(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?zn:BigInt("0x"+t)}const as={_0:48,_9:57,A:65,F:70,a:97,f:102};function Fc(t){if(t>=as._0&&t<=as._9)return t-as._0;if(t>=as.A&&t<=as.F)return t-(as.A-10);if(t>=as.a&&t<=as.f)return t-(as.a-10)}function Vr(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(s);for(let i=0,n=0;i<s;i++,n+=2){const o=Fc(t.charCodeAt(n)),a=Fc(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}r[i]=o*16+a}return r}function Js(t){return Pa(zr(t))}function Ri(t){return Vi(t),Pa(zr(Uint8Array.from(t).reverse()))}function Kr(t,e){return Vr(t.toString(16).padStart(e*2,"0"))}function Kn(t,e){return Kr(t,e).reverse()}function Uw(t){return Vr(kr(t))}function Ct(t,e,s){let r;if(typeof e=="string")try{r=Vr(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(er(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof s=="number"&&i!==s)throw new Error(t+" of length "+s+" expected, got "+i);return r}function Ui(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Vi(i),e+=i.length}const s=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const n=t[r];s.set(n,i),i+=n.length}return s}function Dw(t,e){if(t.length!==e.length)return!1;let s=0;for(let r=0;r<t.length;r++)s|=t[r]^e[r];return s===0}function Lw(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const po=t=>typeof t=="bigint"&&zn<=t;function Gn(t,e,s){return po(t)&&po(e)&&po(s)&&e<=t&&t<s}function ds(t,e,s,r){if(!Gn(e,s,r))throw new Error("expected valid "+t+": "+s+" <= n < "+r+", got "+e)}function bh(t){let e;for(e=0;t>zn;t>>=Vn,e+=1);return e}function Mw(t,e){return t>>BigInt(e)&Vn}function Bw(t,e,s){return t|(s?Vn:zn)<<BigInt(e)}const Oa=t=>($w<<BigInt(t-1))-Vn,fo=t=>new Uint8Array(t),Wc=t=>Uint8Array.from(t);function vh(t,e,s){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof s!="function")throw new Error("hmacFn must be a function");let r=fo(t),i=fo(t),n=0;const o=()=>{r.fill(1),i.fill(0),n=0},a=(...u)=>s(i,r,...u),c=(u=fo())=>{i=a(Wc([0]),u),r=a(),u.length!==0&&(i=a(Wc([1]),u),r=a())},l=()=>{if(n++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const h=[];for(;u<e;){r=a();const d=r.slice();h.push(d),u+=r.length}return Ui(...h)};return(u,h)=>{o(),c(u);let d;for(;!(d=h(l()));)c();return o(),d}}const jw={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||er(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function si(t,e,s={}){const r=(i,n,o)=>{const a=jw[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+n+", got "+c)};for(const[i,n]of Object.entries(e))r(i,n,!1);for(const[i,n]of Object.entries(s))r(i,n,!0);return t}const qw=()=>{throw new Error("not implemented")};function Jo(t){const e=new WeakMap;return(s,...r)=>{const i=e.get(s);if(i!==void 0)return i;const n=t(s,...r);return e.set(s,n),n}}var Fw=Object.freeze({__proto__:null,isBytes:er,abytes:Vi,abool:Hr,bytesToHex:zr,numberToHexUnpadded:kr,hexToNumber:Pa,hexToBytes:Vr,bytesToNumberBE:Js,bytesToNumberLE:Ri,numberToBytesBE:Kr,numberToBytesLE:Kn,numberToVarBytesBE:Uw,ensureBytes:Ct,concatBytes:Ui,equalBytes:Dw,utf8ToBytes:Lw,inRange:Gn,aInRange:ds,bitLen:bh,bitGet:Mw,bitSet:Bw,bitMask:Oa,createHmacDrbg:vh,validateObject:si,notImplemented:qw,memoized:Jo});const Je=BigInt(0),xe=BigInt(1),Ws=BigInt(2),Ww=BigInt(3),Yo=BigInt(4),Hc=BigInt(5),zc=BigInt(8);function mt(t,e){const s=t%e;return s>=Je?s:e+s}function Eh(t,e,s){if(e<Je)throw new Error("invalid exponent, negatives unsupported");if(s<=Je)throw new Error("invalid modulus");if(s===xe)return Je;let r=xe;for(;e>Je;)e&xe&&(r=r*t%s),t=t*t%s,e>>=xe;return r}function jt(t,e,s){let r=t;for(;e-- >Je;)r*=r,r%=s;return r}function Xo(t,e){if(t===Je)throw new Error("invert: expected non-zero number");if(e<=Je)throw new Error("invert: expected positive modulus, got "+e);let s=mt(t,e),r=e,i=Je,n=xe;for(;s!==Je;){const o=r/s,a=r%s,c=i-n*o;r=s,s=a,i=n,n=c}if(r!==xe)throw new Error("invert: does not exist");return mt(i,e)}function Hw(t){const e=(t-xe)/Ws;let s,r,i;for(s=t-xe,r=0;s%Ws===Je;s/=Ws,r++);for(i=Ws;i<t&&Eh(i,e,t)!==t-xe;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+xe)/Yo;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const n=(s+xe)/Ws;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,l=o.pow(o.mul(o.ONE,i),s),u=o.pow(a,n),h=o.pow(a,s);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let d=1;for(let w=o.sqr(h);d<c&&!o.eql(w,o.ONE);d++)w=o.sqr(w);const p=o.pow(l,xe<<BigInt(c-d-1));l=o.sqr(p),u=o.mul(u,p),h=o.mul(h,l),c=d}return u}}function zw(t){if(t%Yo===Ww){const e=(t+xe)/Yo;return function(s,r){const i=s.pow(r,e);if(!s.eql(s.sqr(i),r))throw new Error("Cannot find square root");return i}}if(t%zc===Hc){const e=(t-Hc)/zc;return function(s,r){const i=s.mul(r,Ws),n=s.pow(i,e),o=s.mul(r,n),a=s.mul(s.mul(o,Ws),n),c=s.mul(o,s.sub(a,s.ONE));if(!s.eql(s.sqr(c),r))throw new Error("Cannot find square root");return c}}return Hw(t)}const Vw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},s=Vw.reduce((r,i)=>(r[i]="function",r),e);return si(t,s)}function Gw(t,e,s){if(s<Je)throw new Error("invalid exponent, negatives unsupported");if(s===Je)return t.ONE;if(s===xe)return e;let r=t.ONE,i=e;for(;s>Je;)s&xe&&(r=t.mul(r,i)),i=t.sqr(i),s>>=xe;return r}function Jw(t,e){const s=new Array(e.length),r=e.reduce((n,o,a)=>t.is0(o)?n:(s[a]=n,t.mul(n,o)),t.ONE),i=t.inv(r);return e.reduceRight((n,o,a)=>t.is0(o)?n:(s[a]=t.mul(n,s[a]),t.mul(n,o)),i),s}function Ch(t,e){const s=e!==void 0?e:t.toString(2).length,r=Math.ceil(s/8);return{nBitLength:s,nByteLength:r}}function Ih(t,e,s=!1,r={}){if(t<=Je)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:n}=Ch(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:s,BITS:i,BYTES:n,MASK:Oa(i),ZERO:Je,ONE:xe,create:c=>mt(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Je<=c&&c<t},is0:c=>c===Je,isOdd:c=>(c&xe)===xe,neg:c=>mt(-c,t),eql:(c,l)=>c===l,sqr:c=>mt(c*c,t),add:(c,l)=>mt(c+l,t),sub:(c,l)=>mt(c-l,t),mul:(c,l)=>mt(c*l,t),pow:(c,l)=>Gw(a,c,l),div:(c,l)=>mt(c*Xo(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Xo(c,t),sqrt:r.sqrt||(c=>(o||(o=zw(t)),o(a,c))),invertBatch:c=>Jw(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>s?Kn(c,n):Kr(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return s?Ri(c):Js(c)}});return Object.freeze(a)}function Nh(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function _h(t){const e=Nh(t);return e+Math.ceil(e/2)}function Yw(t,e,s=!1){const r=t.length,i=Nh(e),n=_h(e);if(r<16||r<n||r>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+r);const o=s?Ri(t):Js(t),a=mt(o,e-xe)+xe;return s?Kn(a,i):Kr(a,i)}const Vc=BigInt(0),an=BigInt(1);function go(t,e){const s=e.negate();return t?s:e}function Ah(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function mo(t,e){Ah(t,e);const s=Math.ceil(e/t)+1,r=2**(t-1);return{windows:s,windowSize:r}}function Xw(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((s,r)=>{if(!(s instanceof e))throw new Error("invalid point at index "+r)})}function Zw(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((s,r)=>{if(!e.isValid(s))throw new Error("invalid scalar at index "+r)})}const wo=new WeakMap,Sh=new WeakMap;function yo(t){return Sh.get(t)||1}function Qw(t,e){return{constTimeNegate:go,hasPrecomputes(s){return yo(s)!==1},unsafeLadder(s,r,i=t.ZERO){let n=s;for(;r>Vc;)r&an&&(i=i.add(n)),n=n.double(),r>>=an;return i},precomputeWindow(s,r){const{windows:i,windowSize:n}=mo(r,e),o=[];let a=s,c=a;for(let l=0;l<i;l++){c=a,o.push(c);for(let u=1;u<n;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(s,r,i){const{windows:n,windowSize:o}=mo(s,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**s-1),u=2**s,h=BigInt(s);for(let d=0;d<n;d++){const p=d*o;let w=Number(i&l);i>>=h,w>o&&(w-=u,i+=an);const m=p,f=p+Math.abs(w)-1,y=d%2!==0,b=w<0;w===0?c=c.add(go(y,r[m])):a=a.add(go(b,r[f]))}return{p:a,f:c}},wNAFUnsafe(s,r,i,n=t.ZERO){const{windows:o,windowSize:a}=mo(s,e),c=BigInt(2**s-1),l=2**s,u=BigInt(s);for(let h=0;h<o;h++){const d=h*a;if(i===Vc)break;let p=Number(i&c);if(i>>=u,p>a&&(p-=l,i+=an),p===0)continue;let w=r[d+Math.abs(p)-1];p<0&&(w=w.negate()),n=n.add(w)}return n},getPrecomputes(s,r,i){let n=wo.get(r);return n||(n=this.precomputeWindow(r,s),s!==1&&wo.set(r,i(n))),n},wNAFCached(s,r,i){const n=yo(s);return this.wNAF(n,this.getPrecomputes(n,s,i),r)},wNAFCachedUnsafe(s,r,i,n){const o=yo(s);return o===1?this.unsafeLadder(s,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,s,i),r,n)},setWindowSize(s,r){Ah(r,e),Sh.set(s,r),wo.delete(s)}}}function ey(t,e,s,r){if(Xw(s,t),Zw(r,e),s.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,n=bh(BigInt(s.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),l=Math.floor((e.BITS-1)/o)*o;let u=i;for(let h=l;h>=0;h-=o){c.fill(i);for(let p=0;p<r.length;p++){const w=r[p],m=Number(w>>BigInt(h)&BigInt(a));c[m]=c[m].add(s[p])}let d=i;for(let p=c.length-1,w=i;p>0;p--)w=w.add(c[p]),d=d.add(w);if(u=u.add(d),h!==0)for(let p=0;p<o;p++)u=u.double()}return u}function Ph(t){return Kw(t.Fp),si(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ch(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const dr=BigInt(0),bo=BigInt(1);function ty(t){return si(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function sy(t){const e=ty(t),{P:s}=e,r=b=>mt(b,s),i=e.montgomeryBits,n=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(b=>b),c=e.powPminus2||(b=>Eh(b,s-BigInt(2),s));function l(b,v,C){const S=r(b*(v-C));return v=r(v-S),C=r(C+S),[v,C]}const u=(e.a-BigInt(2))/BigInt(4);function h(b,v){ds("u",b,dr,s),ds("scalar",v,dr,s);const C=v,S=b;let _=bo,A=dr,U=b,E=bo,$=dr,I;for(let z=BigInt(i-1);z>=dr;z--){const N=C>>z&bo;$^=N,I=l($,_,U),_=I[0],U=I[1],I=l($,A,E),A=I[0],E=I[1],$=N;const k=_+A,O=r(k*k),B=_-A,F=r(B*B),x=O-F,G=U+E,ee=U-E,re=r(ee*k),Ne=r(G*B),pe=re+Ne,$e=re-Ne;U=r(pe*pe),E=r(S*r($e*$e)),_=r(O*F),A=r(x*(O+r(u*x)))}I=l($,_,U),_=I[0],U=I[1],I=l($,A,E),A=I[0],E=I[1];const L=c(A);return r(_*L)}function d(b){return Kn(r(b),n)}function p(b){const v=Ct("u coordinate",b,n);return o===32&&(v[31]&=127),Ri(v)}function w(b){const v=Ct("scalar",b),C=v.length;if(C!==n&&C!==o){let S=""+n+" or "+o;throw new Error("invalid scalar, expected "+S+" bytes, got "+C)}return Ri(a(v))}function m(b,v){const C=p(v),S=w(b),_=h(C,S);if(_===dr)throw new Error("invalid private or public key received");return d(_)}const f=d(e.Gu);function y(b){return m(b,f)}return{scalarMult:m,scalarMultBase:y,getSharedSecret:(b,v)=>m(b,v),getPublicKey:b=>y(b),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:f}}const Zo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const ry=BigInt(1),Kc=BigInt(2),iy=BigInt(3),ny=BigInt(5);BigInt(8);function oy(t){const e=BigInt(10),s=BigInt(20),r=BigInt(40),i=BigInt(80),n=Zo,o=t*t%n*t%n,a=jt(o,Kc,n)*o%n,c=jt(a,ry,n)*t%n,l=jt(c,ny,n)*c%n,u=jt(l,e,n)*l%n,h=jt(u,s,n)*u%n,d=jt(h,r,n)*h%n,p=jt(d,i,n)*d%n,w=jt(p,i,n)*d%n,m=jt(w,e,n)*l%n;return{pow_p_5_8:jt(m,Kc,n)*t%n,b2:o}}function ay(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Qo=sy({P:Zo,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=Zo,{pow_p_5_8:s,b2:r}=oy(t);return mt(jt(s,iy,e)*r,e)},adjustScalarBytes:ay,randomBytes:ti});function Gc(t){t.lowS!==void 0&&Hr("lowS",t.lowS),t.prehash!==void 0&&Hr("prehash",t.prehash)}function cy(t){const e=Ph(t);si(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:s,Fp:r,a:i}=e;if(s){if(!r.eql(i,r.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof s!="object"||typeof s.beta!="bigint"||typeof s.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:ly,hexToBytes:uy}=Fw;class hy extends Error{constructor(e=""){super(e)}}const us={Err:hy,_tlv:{encode:(t,e)=>{const{Err:s}=us;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const r=e.length/2,i=kr(r);if(i.length/2&128)throw new s("tlv.encode: long form length too big");const n=r>127?kr(i.length/2|128):"";return kr(t)+n+i+e},decode(t,e){const{Err:s}=us;let r=0;if(t<0||t>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new s("tlv.decode: wrong tlv");const i=e[r++],n=!!(i&128);let o=0;if(!n)o=i;else{const c=i&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=us;if(t<hs)throw new e("integer: negative integers are not allowed");let s=kr(t);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(t){const{Err:e}=us;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ly(t)}},toSig(t){const{Err:e,_int:s,_tlv:r}=us,i=typeof t=="string"?uy(t):t;Vi(i);const{v:n,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,n),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(t){const{_tlv:e,_int:s}=us,r=e.encode(2,s.encode(t.r)),i=e.encode(2,s.encode(t.s)),n=r+i;return e.encode(48,n)}},hs=BigInt(0),ze=BigInt(1);BigInt(2);const Jc=BigInt(3);BigInt(4);function dy(t){const e=cy(t),{Fp:s}=e,r=Ih(e.n,e.nBitLength),i=e.toBytes||((m,f,y)=>{const b=f.toAffine();return Ui(Uint8Array.from([4]),s.toBytes(b.x),s.toBytes(b.y))}),n=e.fromBytes||(m=>{const f=m.subarray(1),y=s.fromBytes(f.subarray(0,s.BYTES)),b=s.fromBytes(f.subarray(s.BYTES,2*s.BYTES));return{x:y,y:b}});function o(m){const{a:f,b:y}=e,b=s.sqr(m),v=s.mul(b,m);return s.add(s.add(v,s.mul(m,f)),y)}if(!s.eql(s.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Gn(m,ze,e.n)}function c(m){const{allowedPrivateKeyLengths:f,nByteLength:y,wrapPrivateKey:b,n:v}=e;if(f&&typeof m!="bigint"){if(er(m)&&(m=zr(m)),typeof m!="string"||!f.includes(m.length))throw new Error("invalid private key");m=m.padStart(y*2,"0")}let C;try{C=typeof m=="bigint"?m:Js(Ct("private key",m,y))}catch{throw new Error("invalid private key, expected hex or "+y+" bytes, got "+typeof m)}return b&&(C=mt(C,v)),ds("private key",C,ze,v),C}function l(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}const u=Jo((m,f)=>{const{px:y,py:b,pz:v}=m;if(s.eql(v,s.ONE))return{x:y,y:b};const C=m.is0();f==null&&(f=C?s.ONE:s.inv(v));const S=s.mul(y,f),_=s.mul(b,f),A=s.mul(v,f);if(C)return{x:s.ZERO,y:s.ZERO};if(!s.eql(A,s.ONE))throw new Error("invZ was invalid");return{x:S,y:_}}),h=Jo(m=>{if(m.is0()){if(e.allowInfinityPoint&&!s.is0(m.py))return;throw new Error("bad point: ZERO")}const{x:f,y}=m.toAffine();if(!s.isValid(f)||!s.isValid(y))throw new Error("bad point: x or y not FE");const b=s.sqr(y),v=o(f);if(!s.eql(b,v))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(f,y,b){if(this.px=f,this.py=y,this.pz=b,f==null||!s.isValid(f))throw new Error("x required");if(y==null||!s.isValid(y))throw new Error("y required");if(b==null||!s.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(f){const{x:y,y:b}=f||{};if(!f||!s.isValid(y)||!s.isValid(b))throw new Error("invalid affine point");if(f instanceof d)throw new Error("projective point not allowed");const v=C=>s.eql(C,s.ZERO);return v(y)&&v(b)?d.ZERO:new d(y,b,s.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(f){const y=s.invertBatch(f.map(b=>b.pz));return f.map((b,v)=>b.toAffine(y[v])).map(d.fromAffine)}static fromHex(f){const y=d.fromAffine(n(Ct("pointHex",f)));return y.assertValidity(),y}static fromPrivateKey(f){return d.BASE.multiply(c(f))}static msm(f,y){return ey(d,r,f,y)}_setWindowSize(f){w.setWindowSize(this,f)}assertValidity(){h(this)}hasEvenY(){const{y:f}=this.toAffine();if(s.isOdd)return!s.isOdd(f);throw new Error("Field doesn't support isOdd")}equals(f){l(f);const{px:y,py:b,pz:v}=this,{px:C,py:S,pz:_}=f,A=s.eql(s.mul(y,_),s.mul(C,v)),U=s.eql(s.mul(b,_),s.mul(S,v));return A&&U}negate(){return new d(this.px,s.neg(this.py),this.pz)}double(){const{a:f,b:y}=e,b=s.mul(y,Jc),{px:v,py:C,pz:S}=this;let _=s.ZERO,A=s.ZERO,U=s.ZERO,E=s.mul(v,v),$=s.mul(C,C),I=s.mul(S,S),L=s.mul(v,C);return L=s.add(L,L),U=s.mul(v,S),U=s.add(U,U),_=s.mul(f,U),A=s.mul(b,I),A=s.add(_,A),_=s.sub($,A),A=s.add($,A),A=s.mul(_,A),_=s.mul(L,_),U=s.mul(b,U),I=s.mul(f,I),L=s.sub(E,I),L=s.mul(f,L),L=s.add(L,U),U=s.add(E,E),E=s.add(U,E),E=s.add(E,I),E=s.mul(E,L),A=s.add(A,E),I=s.mul(C,S),I=s.add(I,I),E=s.mul(I,L),_=s.sub(_,E),U=s.mul(I,$),U=s.add(U,U),U=s.add(U,U),new d(_,A,U)}add(f){l(f);const{px:y,py:b,pz:v}=this,{px:C,py:S,pz:_}=f;let A=s.ZERO,U=s.ZERO,E=s.ZERO;const $=e.a,I=s.mul(e.b,Jc);let L=s.mul(y,C),z=s.mul(b,S),N=s.mul(v,_),k=s.add(y,b),O=s.add(C,S);k=s.mul(k,O),O=s.add(L,z),k=s.sub(k,O),O=s.add(y,v);let B=s.add(C,_);return O=s.mul(O,B),B=s.add(L,N),O=s.sub(O,B),B=s.add(b,v),A=s.add(S,_),B=s.mul(B,A),A=s.add(z,N),B=s.sub(B,A),E=s.mul($,O),A=s.mul(I,N),E=s.add(A,E),A=s.sub(z,E),E=s.add(z,E),U=s.mul(A,E),z=s.add(L,L),z=s.add(z,L),N=s.mul($,N),O=s.mul(I,O),z=s.add(z,N),N=s.sub(L,N),N=s.mul($,N),O=s.add(O,N),L=s.mul(z,O),U=s.add(U,L),L=s.mul(B,O),A=s.mul(k,A),A=s.sub(A,L),L=s.mul(k,z),E=s.mul(B,E),E=s.add(E,L),new d(A,U,E)}subtract(f){return this.add(f.negate())}is0(){return this.equals(d.ZERO)}wNAF(f){return w.wNAFCached(this,f,d.normalizeZ)}multiplyUnsafe(f){const{endo:y,n:b}=e;ds("scalar",f,hs,b);const v=d.ZERO;if(f===hs)return v;if(this.is0()||f===ze)return this;if(!y||w.hasPrecomputes(this))return w.wNAFCachedUnsafe(this,f,d.normalizeZ);let{k1neg:C,k1:S,k2neg:_,k2:A}=y.splitScalar(f),U=v,E=v,$=this;for(;S>hs||A>hs;)S&ze&&(U=U.add($)),A&ze&&(E=E.add($)),$=$.double(),S>>=ze,A>>=ze;return C&&(U=U.negate()),_&&(E=E.negate()),E=new d(s.mul(E.px,y.beta),E.py,E.pz),U.add(E)}multiply(f){const{endo:y,n:b}=e;ds("scalar",f,ze,b);let v,C;if(y){const{k1neg:S,k1:_,k2neg:A,k2:U}=y.splitScalar(f);let{p:E,f:$}=this.wNAF(_),{p:I,f:L}=this.wNAF(U);E=w.constTimeNegate(S,E),I=w.constTimeNegate(A,I),I=new d(s.mul(I.px,y.beta),I.py,I.pz),v=E.add(I),C=$.add(L)}else{const{p:S,f:_}=this.wNAF(f);v=S,C=_}return d.normalizeZ([v,C])[0]}multiplyAndAddUnsafe(f,y,b){const v=d.BASE,C=(_,A)=>A===hs||A===ze||!_.equals(v)?_.multiplyUnsafe(A):_.multiply(A),S=C(this,y).add(C(f,b));return S.is0()?void 0:S}toAffine(f){return u(this,f)}isTorsionFree(){const{h:f,isTorsionFree:y}=e;if(f===ze)return!0;if(y)return y(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:f,clearCofactor:y}=e;return f===ze?this:y?y(d,this):this.multiplyUnsafe(e.h)}toRawBytes(f=!0){return Hr("isCompressed",f),this.assertValidity(),i(d,this,f)}toHex(f=!0){return Hr("isCompressed",f),zr(this.toRawBytes(f))}}d.BASE=new d(e.Gx,e.Gy,s.ONE),d.ZERO=new d(s.ZERO,s.ONE,s.ZERO);const p=e.nBitLength,w=Qw(d,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function py(t){const e=Ph(t);return si(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function fy(t){const e=py(t),{Fp:s,n:r}=e,i=s.BYTES+1,n=2*s.BYTES+1;function o(N){return mt(N,r)}function a(N){return Xo(N,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=dy({...e,toBytes(N,k,O){const B=k.toAffine(),F=s.toBytes(B.x),x=Ui;return Hr("isCompressed",O),O?x(Uint8Array.from([k.hasEvenY()?2:3]),F):x(Uint8Array.from([4]),F,s.toBytes(B.y))},fromBytes(N){const k=N.length,O=N[0],B=N.subarray(1);if(k===i&&(O===2||O===3)){const F=Js(B);if(!Gn(F,ze,s.ORDER))throw new Error("Point is not on curve");const x=u(F);let G;try{G=s.sqrt(x)}catch(re){const Ne=re instanceof Error?": "+re.message:"";throw new Error("Point is not on curve"+Ne)}const ee=(G&ze)===ze;return(O&1)===1!==ee&&(G=s.neg(G)),{x:F,y:G}}else if(k===n&&O===4){const F=s.fromBytes(B.subarray(0,s.BYTES)),x=s.fromBytes(B.subarray(s.BYTES,2*s.BYTES));return{x:F,y:x}}else{const F=i,x=n;throw new Error("invalid Point, expected length of "+F+", or uncompressed "+x+", got "+k)}}}),d=N=>zr(Kr(N,e.nByteLength));function p(N){const k=r>>ze;return N>k}function w(N){return p(N)?o(-N):N}const m=(N,k,O)=>Js(N.slice(k,O));class f{constructor(k,O,B){this.r=k,this.s=O,this.recovery=B,this.assertValidity()}static fromCompact(k){const O=e.nByteLength;return k=Ct("compactSignature",k,O*2),new f(m(k,0,O),m(k,O,2*O))}static fromDER(k){const{r:O,s:B}=us.toSig(Ct("DER",k));return new f(O,B)}assertValidity(){ds("r",this.r,ze,r),ds("s",this.s,ze,r)}addRecoveryBit(k){return new f(this.r,this.s,k)}recoverPublicKey(k){const{r:O,s:B,recovery:F}=this,x=_(Ct("msgHash",k));if(F==null||![0,1,2,3].includes(F))throw new Error("recovery id invalid");const G=F===2||F===3?O+e.n:O;if(G>=s.ORDER)throw new Error("recovery id 2 or 3 invalid");const ee=F&1?"03":"02",re=c.fromHex(ee+d(G)),Ne=a(G),pe=o(-x*Ne),$e=o(B*Ne),qe=c.BASE.multiplyAndAddUnsafe(re,pe,$e);if(!qe)throw new Error("point at infinify");return qe.assertValidity(),qe}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Vr(this.toDERHex())}toDERHex(){return us.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Vr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const y={isValidPrivateKey(N){try{return l(N),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const N=_h(e.n);return Yw(e.randomBytes(N),e.n)},precompute(N=8,k=c.BASE){return k._setWindowSize(N),k.multiply(BigInt(3)),k}};function b(N,k=!0){return c.fromPrivateKey(N).toRawBytes(k)}function v(N){const k=er(N),O=typeof N=="string",B=(k||O)&&N.length;return k?B===i||B===n:O?B===2*i||B===2*n:N instanceof c}function C(N,k,O=!0){if(v(N))throw new Error("first arg must be private key");if(!v(k))throw new Error("second arg must be public key");return c.fromHex(k).multiply(l(N)).toRawBytes(O)}const S=e.bits2int||function(N){if(N.length>8192)throw new Error("input is too large");const k=Js(N),O=N.length*8-e.nBitLength;return O>0?k>>BigInt(O):k},_=e.bits2int_modN||function(N){return o(S(N))},A=Oa(e.nBitLength);function U(N){return ds("num < 2^"+e.nBitLength,N,hs,A),Kr(N,e.nByteLength)}function E(N,k,O=$){if(["recovered","canonical"].some(De=>De in O))throw new Error("sign() legacy options not supported");const{hash:B,randomBytes:F}=e;let{lowS:x,prehash:G,extraEntropy:ee}=O;x==null&&(x=!0),N=Ct("msgHash",N),Gc(O),G&&(N=Ct("prehashed msgHash",B(N)));const re=_(N),Ne=l(k),pe=[U(Ne),U(re)];if(ee!=null&&ee!==!1){const De=ee===!0?F(s.BYTES):ee;pe.push(Ct("extraEntropy",De))}const $e=Ui(...pe),qe=re;function tt(De){const Le=S(De);if(!h(Le))return;const Us=a(Le),ss=c.BASE.multiply(Le).toAffine(),zt=o(ss.x);if(zt===hs)return;const rs=o(Us*o(qe+zt*Ne));if(rs===hs)return;let cr=(ss.x===zt?0:2)|Number(ss.y&ze),Zi=rs;return x&&p(rs)&&(Zi=w(rs),cr^=1),new f(zt,Zi,cr)}return{seed:$e,k2sig:tt}}const $={lowS:e.lowS,prehash:!1},I={lowS:e.lowS,prehash:!1};function L(N,k,O=$){const{seed:B,k2sig:F}=E(N,k,O),x=e;return vh(x.hash.outputLen,x.nByteLength,x.hmac)(B,F)}c.BASE._setWindowSize(8);function z(N,k,O,B=I){const F=N;k=Ct("msgHash",k),O=Ct("publicKey",O);const{lowS:x,prehash:G,format:ee}=B;if(Gc(B),"strict"in B)throw new Error("options.strict was renamed to lowS");if(ee!==void 0&&ee!=="compact"&&ee!=="der")throw new Error("format must be compact or der");const re=typeof F=="string"||er(F),Ne=!re&&!ee&&typeof F=="object"&&F!==null&&typeof F.r=="bigint"&&typeof F.s=="bigint";if(!re&&!Ne)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let pe,$e;try{if(Ne&&(pe=new f(F.r,F.s)),re){try{ee!=="compact"&&(pe=f.fromDER(F))}catch(rs){if(!(rs instanceof us.Err))throw rs}!pe&&ee!=="der"&&(pe=f.fromCompact(F))}$e=c.fromHex(O)}catch{return!1}if(!pe||x&&pe.hasHighS())return!1;G&&(k=e.hash(k));const{r:qe,s:tt}=pe,De=_(k),Le=a(tt),Us=o(De*Le),ss=o(qe*Le),zt=c.BASE.multiplyAndAddUnsafe($e,Us,ss)?.toAffine();return zt?o(zt.x)===qe:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:C,sign:L,verify:z,ProjectivePoint:c,Signature:f,utils:y}}function gy(t){return{hash:t,hmac:(e,...s)=>Hn(t,e,bm(...s)),randomBytes:ti}}function my(t,e){const s=r=>fy({...t,...gy(r)});return{...s(e),create:s}}const Oh=Ih(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),wy=Oh.create(BigInt("-3")),yy=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),by=my({a:wy,b:yy,Fp:Oh,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},zi),Th="base10",at="base16",Wt="base64pad",Cs="base64url",Ki="utf8",kh=0,ps=1,Gi=2,vy=0,Yc=1,_i=12,Ta=32;function Ey(){const t=Qo.utils.randomPrivateKey(),e=Qo.getPublicKey(t);return{privateKey:wt(t,at),publicKey:wt(e,at)}}function ea(){const t=ti(Ta);return wt(t,at)}function Cy(t,e){const s=Qo.getSharedSecret(Rt(t,at),Rt(e,at)),r=Aw(zi,s,void 0,void 0,Ta);return wt(r,at)}function En(t){const e=zi(Rt(t,at));return wt(e,at)}function Zt(t){const e=zi(Rt(t,Ki));return wt(e,at)}function xh(t){return Rt(`${t}`,Th)}function tr(t){return Number(wt(t,Th))}function $h(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Rh(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),s=(4-e.length%4)%4;return e+"=".repeat(s)}function Iy(t){const e=xh(typeof t.type<"u"?t.type:kh);if(tr(e)===ps&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const s=typeof t.senderPublicKey<"u"?Rt(t.senderPublicKey,at):void 0,r=typeof t.iv<"u"?Rt(t.iv,at):ti(_i),i=Rt(t.symKey,at),n=wh(i,r).encrypt(Rt(t.message,Ki)),o=Uh({type:e,sealed:n,iv:r,senderPublicKey:s});return t.encoding===Cs?$h(o):o}function Ny(t){const e=Rt(t.symKey,at),{sealed:s,iv:r}=Di({encoded:t.encoded,encoding:t.encoding}),i=wh(e,r).decrypt(s);if(i===null)throw new Error("Failed to decrypt");return wt(i,Ki)}function _y(t,e){const s=xh(Gi),r=ti(_i),i=Rt(t,Ki),n=Uh({type:s,sealed:i,iv:r});return e===Cs?$h(n):n}function Ay(t,e){const{sealed:s}=Di({encoded:t,encoding:e});return wt(s,Ki)}function Uh(t){if(tr(t.type)===Gi)return wt(vi([t.type,t.sealed]),Wt);if(tr(t.type)===ps){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return wt(vi([t.type,t.senderPublicKey,t.iv,t.sealed]),Wt)}return wt(vi([t.type,t.iv,t.sealed]),Wt)}function Di(t){const e=(t.encoding||Wt)===Cs?Rh(t.encoded):t.encoded,s=Rt(e,Wt),r=s.slice(vy,Yc),i=Yc;if(tr(r)===ps){const c=i+Ta,l=c+_i,u=s.slice(i,c),h=s.slice(c,l),d=s.slice(l);return{type:r,sealed:d,iv:h,senderPublicKey:u}}if(tr(r)===Gi){const c=s.slice(i),l=ti(_i);return{type:r,sealed:c,iv:l}}const n=i+_i,o=s.slice(i,n),a=s.slice(n);return{type:r,sealed:a,iv:o}}function Sy(t,e){const s=Di({encoded:t,encoding:e?.encoding});return Dh({type:tr(s.type),senderPublicKey:typeof s.senderPublicKey<"u"?wt(s.senderPublicKey,at):void 0,receiverPublicKey:e?.receiverPublicKey})}function Dh(t){const e=t?.type||kh;if(e===ps){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function Xc(t){return t.type===ps&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Zc(t){return t.type===Gi}function Py(t){const e=Ye.from(t.x,"base64"),s=Ye.from(t.y,"base64");return vi([new Uint8Array([4]),e,s])}function Oy(t,e){const[s,r,i]=t.split("."),n=Ye.from(Rh(i),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${s}.${r}`,l=zi(c),u=Py(e);if(!by.verify(vi([o,a]),l,u))throw new Error("Invalid signature");return Uo(t).payload}const Ty="irn";function $n(t){return t?.relay||{protocol:Ty}}function wi(t){const e=kd[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function ky(t,e="-"){const s={},r="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(r)){const n=i.replace(r,""),o=t[i];s[n]=o}}),s}function Qc(t){if(!t.includes("wc:")){const l=ih(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),s=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),i=t.substring(e+1,s).split("@"),n=typeof s<"u"?t.substring(s):"",o=new URLSearchParams(n),a={};o.forEach((l,u)=>{a[u]=l});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:xy(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:ky(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function xy(t){return t.startsWith("//")?t.substring(2):t}function $y(t,e="-"){const s="relay",r={};return Object.keys(t).forEach(i=>{const n=i,o=s+e+n;t[n]&&(r[o]=t[n])}),r}function el(t){const e=new URLSearchParams,s=$y(t.relay);Object.keys(s).sort().forEach(i=>{e.set(i,s[i])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const r=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${r}`}function cn(t,e,s){return`${t}?wc_ev=${s}&topic=${e}`}var Ry=Object.defineProperty,Uy=Object.defineProperties,Dy=Object.getOwnPropertyDescriptors,tl=Object.getOwnPropertySymbols,Ly=Object.prototype.hasOwnProperty,My=Object.prototype.propertyIsEnumerable,sl=(t,e,s)=>e in t?Ry(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,By=(t,e)=>{for(var s in e||(e={}))Ly.call(e,s)&&sl(t,s,e[s]);if(tl)for(var s of tl(e))My.call(e,s)&&sl(t,s,e[s]);return t},jy=(t,e)=>Uy(t,Dy(e));function ri(t){const e=[];return t.forEach(s=>{const[r,i]=s.split(":");e.push(`${r}:${i}`)}),e}function qy(t){const e=[];return Object.values(t).forEach(s=>{e.push(...ri(s.accounts))}),e}function Fy(t,e){const s=[];return Object.values(t).forEach(r=>{ri(r.accounts).includes(e)&&s.push(...r.methods)}),s}function Wy(t,e){const s=[];return Object.values(t).forEach(r=>{ri(r.accounts).includes(e)&&s.push(...r.events)}),s}function Jn(t){return t.includes(":")}function xr(t){return Jn(t)?t.split(":")[0]:t}function rl(t){var e,s,r;const i={};if(!Ts(t))return i;for(const[n,o]of Object.entries(t)){const a=Jn(n)?[n]:o.chains,c=o.methods||[],l=o.events||[],u=xr(n);i[u]=jy(By({},i[u]),{chains:es(a,(e=i[u])==null?void 0:e.chains),methods:es(c,(s=i[u])==null?void 0:s.methods),events:es(l,(r=i[u])==null?void 0:r.events)})}return i}function Hy(t){const e={};return t?.forEach(s=>{var r;const[i,n]=s.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(s),(r=e[i].chains)==null||r.push(`${i}:${n}`)}),e}function il(t,e){e=e.map(r=>r.replace("did:pkh:",""));const s=Hy(e);for(const[r,i]of Object.entries(s))i.methods?i.methods=es(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return s}function zy(t,e){var s,r,i,n,o,a;const c=rl(t),l=rl(e),u={},h=Object.keys(c).concat(Object.keys(l));for(const d of h)u[d]={chains:es((s=c[d])==null?void 0:s.chains,(r=l[d])==null?void 0:r.chains),methods:es((i=c[d])==null?void 0:i.methods,(n=l[d])==null?void 0:n.methods),events:es((o=c[d])==null?void 0:o.events,(a=l[d])==null?void 0:a.events)};return u}const Vy={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}},Ky={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 R(t,e){const{message:s,code:r}=Ky[t];return{message:e?`${s} ${e}`:s,code:r}}function ye(t,e){const{message:s,code:r}=Vy[t];return{message:e?`${s} ${e}`:s,code:r}}function Os(t,e){return!!Array.isArray(t)}function Ts(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function rt(t){return typeof t>"u"}function Ue(t,e){return e&&rt(t)?!0:typeof t=="string"&&!!t.trim().length}function ka(t,e){return typeof t=="number"&&!isNaN(t)}function Gy(t,e){const{requiredNamespaces:s}=e,r=Object.keys(t.namespaces),i=Object.keys(s);let n=!0;return Ks(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=ri(a),h=s[o];(!Ks(Qu(o,h),u)||!Ks(h.methods,c)||!Ks(h.events,l))&&(n=!1)}),n):!1}function Rn(t){return Ue(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function Jy(t){if(Ue(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const s=e[0]+":"+e[1];return!!e[2]&&Rn(s)}}return!1}function Yy(t){function e(s){try{return typeof new URL(s)<"u"}catch{return!1}}try{if(Ue(t,!1)){if(e(t))return!0;const s=ih(t);return e(s)}}catch{}return!1}function Xy(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function Zy(t){return t?.topic}function Qy(t,e){let s=null;return Ue(t?.publicKey,!1)||(s=R("MISSING_OR_INVALID",`${e} controller public key should be a string`)),s}function nl(t){let e=!0;return Os(t)?t.length&&(e=t.every(s=>Ue(s,!1))):e=!1,e}function eb(t,e,s){let r=null;return Os(e)&&e.length?e.forEach(i=>{r||Rn(i)||(r=ye("UNSUPPORTED_CHAINS",`${s}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Rn(t)||(r=ye("UNSUPPORTED_CHAINS",`${s}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function tb(t,e,s){let r=null;return Object.entries(t).forEach(([i,n])=>{if(r)return;const o=eb(i,Qu(i,n),`${e} ${s}`);o&&(r=o)}),r}function sb(t,e){let s=null;return Os(t)?t.forEach(r=>{s||Jy(r)||(s=ye("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):s=ye("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),s}function rb(t,e){let s=null;return Object.values(t).forEach(r=>{if(s)return;const i=sb(r?.accounts,`${e} namespace`);i&&(s=i)}),s}function ib(t,e){let s=null;return nl(t?.methods)?nl(t?.events)||(s=ye("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):s=ye("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),s}function Lh(t,e){let s=null;return Object.values(t).forEach(r=>{if(s)return;const i=ib(r,`${e}, namespace`);i&&(s=i)}),s}function nb(t,e,s){let r=null;if(t&&Ts(t)){const i=Lh(t,e);i&&(r=i);const n=tb(t,e,s);n&&(r=n)}else r=R("MISSING_OR_INVALID",`${e}, ${s} should be an object with data`);return r}function vo(t,e){let s=null;if(t&&Ts(t)){const r=Lh(t,e);r&&(s=r);const i=rb(t,e);i&&(s=i)}else s=R("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return s}function Mh(t){return Ue(t.protocol,!0)}function ob(t,e){let s=!1;return t?t&&Os(t)&&t.length&&t.forEach(r=>{s=Mh(r)}):s=!0,s}function ab(t){return typeof t=="number"}function gt(t){return typeof t<"u"&&typeof t!==null}function cb(t){return!(!t||typeof t!="object"||!t.code||!ka(t.code)||!t.message||!Ue(t.message,!1))}function lb(t){return!(rt(t)||!Ue(t.method,!1))}function ub(t){return!(rt(t)||rt(t.result)&&rt(t.error)||!ka(t.id)||!Ue(t.jsonrpc,!1))}function hb(t){return!(rt(t)||!Ue(t.name,!1))}function ol(t,e){return!(!Rn(e)||!qy(t).includes(e))}function db(t,e,s){return Ue(s,!1)?Fy(t,e).includes(s):!1}function pb(t,e,s){return Ue(s,!1)?Wy(t,e).includes(s):!1}function al(t,e,s){let r=null;const i=fb(t),n=gb(e),o=Object.keys(i),a=Object.keys(n),c=cl(Object.keys(t)),l=cl(Object.keys(e)),u=c.filter(h=>!l.includes(h));return u.length&&(r=R("NON_CONFORMING_NAMESPACES",`${s} namespaces keys don't satisfy requiredNamespaces.
@@ -11,7 +11,7 @@ ${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Ye.from(Tm(s)).toString(
11
11
  Required: ${o.toString()}
12
12
  Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||r)return;const d=ri(e[h].accounts);d.includes(h)||(r=R("NON_CONFORMING_NAMESPACES",`${s} namespaces accounts don't satisfy namespace accounts for ${h}
13
13
  Required: ${h}
14
- Approved: ${d.toString()}`))}),o.forEach(h=>{r||(Ks(i[h].methods,n[h].methods)?Ks(i[h].events,n[h].events)||(r=R("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${h}`)):r=R("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${h}`))}),r}function fb(t){const e={};return Object.keys(t).forEach(s=>{var r;s.includes(":")?e[s]=t[s]:(r=t[s].chains)==null||r.forEach(i=>{e[i]={methods:t[s].methods,events:t[s].events}})}),e}function cl(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function gb(t){const e={};return Object.keys(t).forEach(s=>{s.includes(":")?e[s]=t[s]:ri(t[s].accounts)?.forEach(i=>{e[i]={accounts:t[s].accounts.filter(n=>n.includes(`${i}:`)),methods:t[s].methods,events:t[s].events}})}),e}function mb(t,e){return ka(t)&&t<=e.max&&t>=e.min}function ll(){const t=Wi();return new Promise(e=>{switch(t){case Nt.browser:e(wb());break;case Nt.reactNative:e(yb());break;case Nt.node:e(bb());break;default:e(!0)}})}function wb(){return ei()&&navigator?.onLine}async function yb(){return Rs()&&typeof Q<"u"&&Q!=null&&Q.NetInfo?(await(Q==null?void 0:Q.NetInfo.fetch()))?.isConnected:!0}function bb(){return!0}function vb(t){switch(Wi()){case Nt.browser:Eb(t);break;case Nt.reactNative:Cb(t);break}}function Eb(t){!Rs()&&ei()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function Cb(t){Rs()&&typeof Q<"u"&&Q!=null&&Q.NetInfo&&Q?.NetInfo.addEventListener(e=>t(e?.isConnected))}function Ib(){var t;return ei()&&Br()?((t=Br())==null?void 0:t.visibilityState)==="visible":!0}const Eo={};class ci{static get(e){return Eo[e]}static set(e,s){Eo[e]=s}static delete(e){delete Eo[e]}}var Nb={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23657442558.commit-435eab3"};const Bh="wc",jh=2,Un="core",ts=`${Bh}@2:${Un}:`,_b={name:Un,logger:"error"},Ab={database:":memory:"},Sb="crypto",ul="client_ed25519_seed",Pb=D.ONE_DAY,Ob="keychain",Tb="0.3",kb="messages",xb="0.3",hl=D.SIX_HOURS,$b="publisher",qh="irn",Rb="error",Fh="wss://relay.walletconnect.org",Ub="relayer",Ve={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},Db="_subscription",Tt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Lb=.1,ta="2.21.0",Pe={link_mode:"link_mode",relay:"relay"},Cn={inbound:"inbound",outbound:"outbound"},Mb="0.3",Bb="WALLETCONNECT_CLIENT_ID",dl="WALLETCONNECT_LINK_MODE_APPS",vt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},jb="subscription",qb="0.3",Fb="pairing",Wb="0.3",li={wc_pairingDelete:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:D.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:D.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:D.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:D.ONE_DAY,prompt:!1,tag:0},res:{ttl:D.ONE_DAY,prompt:!1,tag:0}}},Hs={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Lt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Hb="history",zb="0.3",Vb="expirer",$t={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Kb="0.3",Gb="verify-api",Jb="https://verify.walletconnect.com",Wh="https://verify.walletconnect.org",Ai=Wh,Yb=`${Ai}/v3`,Xb=[Jb,Wh],Zb="echo",Qb="https://echo.walletconnect.com",Jt={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},ls={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Mt={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Ls={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Ms={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},ui={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},ev=.1,tv="event-client",sv=86400,rv="https://pulse.walletconnect.org/batch";function iv(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),r=0;r<s.length;r++)s[r]=255;for(var i=0;i<t.length;i++){var n=t.charAt(i),o=n.charCodeAt(0);if(s[o]!==255)throw new TypeError(n+" is ambiguous");s[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var m=0,f=0,y=0,b=w.length;y!==b&&w[y]===0;)y++,m++;for(var v=(b-y)*u+1>>>0,C=new Uint8Array(v);y!==b;){for(var S=w[y],_=0,A=v-1;(S!==0||_<f)&&A!==-1;A--,_++)S+=256*C[A]>>>0,C[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");f=_,y++}for(var U=v-f;U!==v&&C[U]===0;)U++;for(var E=c.repeat(m);U<v;++U)E+=t.charAt(C[U]);return E}function d(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var m=0;if(w[m]!==" "){for(var f=0,y=0;w[m]===c;)f++,m++;for(var b=(w.length-m)*l+1>>>0,v=new Uint8Array(b);w[m];){var C=s[w.charCodeAt(m)];if(C===255)return;for(var S=0,_=b-1;(C!==0||S<y)&&_!==-1;_--,S++)C+=a*v[_]>>>0,v[_]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");y=S,m++}if(w[m]!==" "){for(var A=b-y;A!==b&&v[A]===0;)A++;for(var U=new Uint8Array(f+(b-A)),E=f;A!==b;)U[E++]=v[A++];return U}}}function p(w){var m=d(w);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var nv=iv,ov=nv;const Hh=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},av=t=>new TextEncoder().encode(t),cv=t=>new TextDecoder().decode(t);class lv{constructor(e,s,r){this.name=e,this.prefix=s,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class uv{constructor(e,s,r){if(this.name=e,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return zh(this,e)}}class hv{constructor(e){this.decoders=e}or(e){return zh(this,e)}decode(e){const s=e[0],r=this.decoders[s];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const zh=(t,e)=>new hv({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class dv{constructor(e,s,r,i){this.name=e,this.prefix=s,this.baseEncode=r,this.baseDecode=i,this.encoder=new lv(e,s,r),this.decoder=new uv(e,s,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Yn=({name:t,prefix:e,encode:s,decode:r})=>new dv(t,e,s,r),Ji=({prefix:t,name:e,alphabet:s})=>{const{encode:r,decode:i}=ov(s,e);return Yn({prefix:t,name:e,encode:r,decode:n=>Hh(i(n))})},pv=(t,e,s,r)=>{const i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*s/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const h=i[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<s|h,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},fv=(t,e,s)=>{const r=e[e.length-1]==="=",i=(1<<s)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,n+=e[i&a>>o];if(o&&(n+=e[i&a<<s-o]),r)for(;n.length*s&7;)n+="=";return n},et=({name:t,prefix:e,bitsPerChar:s,alphabet:r})=>Yn({prefix:e,name:t,encode(i){return fv(i,r,s)},decode(i){return pv(i,r,s,t)}}),gv=Yn({prefix:"\0",name:"identity",encode:t=>cv(t),decode:t=>av(t)});var mv=Object.freeze({__proto__:null,identity:gv});const wv=et({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var yv=Object.freeze({__proto__:null,base2:wv});const bv=et({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vv=Object.freeze({__proto__:null,base8:bv});const Ev=Ji({prefix:"9",name:"base10",alphabet:"0123456789"});var Cv=Object.freeze({__proto__:null,base10:Ev});const Iv=et({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Nv=et({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var _v=Object.freeze({__proto__:null,base16:Iv,base16upper:Nv});const Av=et({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sv=et({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Pv=et({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ov=et({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Tv=et({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kv=et({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xv=et({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$v=et({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Rv=et({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Uv=Object.freeze({__proto__:null,base32:Av,base32upper:Sv,base32pad:Pv,base32padupper:Ov,base32hex:Tv,base32hexupper:kv,base32hexpad:xv,base32hexpadupper:$v,base32z:Rv});const Dv=Ji({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Lv=Ji({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Mv=Object.freeze({__proto__:null,base36:Dv,base36upper:Lv});const Bv=Ji({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jv=Ji({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qv=Object.freeze({__proto__:null,base58btc:Bv,base58flickr:jv});const Fv=et({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Wv=et({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Hv=et({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zv=et({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Vv=Object.freeze({__proto__:null,base64:Fv,base64pad:Wv,base64url:Hv,base64urlpad:zv});const Vh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Kv=Vh.reduce((t,e,s)=>(t[s]=e,t),[]),Gv=Vh.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function Jv(t){return t.reduce((e,s)=>(e+=Kv[s],e),"")}function Yv(t){const e=[];for(const s of t){const r=Gv[s.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(r)}return new Uint8Array(e)}const Xv=Yn({prefix:"🚀",name:"base256emoji",encode:Jv,decode:Yv});var Zv=Object.freeze({__proto__:null,base256emoji:Xv}),Qv=Kh,pl=128,e0=127,t0=~e0,s0=Math.pow(2,31);function Kh(t,e,s){e=e||[],s=s||0;for(var r=s;t>=s0;)e[s++]=t&255|pl,t/=128;for(;t&t0;)e[s++]=t&255|pl,t>>>=7;return e[s]=t|0,Kh.bytes=s-r+1,e}var r0=sa,i0=128,fl=127;function sa(t,r){var s=0,r=r||0,i=0,n=r,o,a=t.length;do{if(n>=a)throw sa.bytes=0,new RangeError("Could not decode varint");o=t[n++],s+=i<28?(o&fl)<<i:(o&fl)*Math.pow(2,i),i+=7}while(o>=i0);return sa.bytes=n-r,s}var n0=Math.pow(2,7),o0=Math.pow(2,14),a0=Math.pow(2,21),c0=Math.pow(2,28),l0=Math.pow(2,35),u0=Math.pow(2,42),h0=Math.pow(2,49),d0=Math.pow(2,56),p0=Math.pow(2,63),f0=function(t){return t<n0?1:t<o0?2:t<a0?3:t<c0?4:t<l0?5:t<u0?6:t<h0?7:t<d0?8:t<p0?9:10},g0={encode:Qv,decode:r0,encodingLength:f0},Gh=g0;const gl=(t,e,s=0)=>(Gh.encode(t,e,s),e),ml=t=>Gh.encodingLength(t),ra=(t,e)=>{const s=e.byteLength,r=ml(t),i=r+ml(s),n=new Uint8Array(i+s);return gl(t,n,0),gl(s,n,r),n.set(e,i),new m0(t,s,e,n)};class m0{constructor(e,s,r,i){this.code=e,this.size=s,this.digest=r,this.bytes=i}}const Jh=({name:t,code:e,encode:s})=>new w0(t,e,s);class w0{constructor(e,s,r){this.name=e,this.code=s,this.encode=r}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?ra(this.code,s):s.then(r=>ra(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Yh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),y0=Jh({name:"sha2-256",code:18,encode:Yh("SHA-256")}),b0=Jh({name:"sha2-512",code:19,encode:Yh("SHA-512")});var v0=Object.freeze({__proto__:null,sha256:y0,sha512:b0});const Xh=0,E0="identity",Zh=Hh,C0=t=>ra(Xh,Zh(t)),I0={code:Xh,name:E0,encode:Zh,digest:C0};var N0=Object.freeze({__proto__:null,identity:I0});new TextEncoder,new TextDecoder;const wl={...mv,...yv,...vv,...Cv,..._v,...Uv,...Mv,...qv,...Vv,...Zv};({...v0,...N0});function _0(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Qh(t,e,s,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:r}}}const yl=Qh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Co=Qh("ascii","a",t=>{let e="a";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return e},t=>{t=t.substring(1);const e=_0(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),A0={utf8:yl,"utf-8":yl,hex:wl.base16,latin1:Co,ascii:Co,binary:Co,...wl};function S0(t,e="utf8"){const s=A0[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):s.decoder.decode(`${s.prefix}${t}`)}var P0=Object.defineProperty,O0=(t,e,s)=>e in t?P0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Kt=(t,e,s)=>O0(t,typeof e!="symbol"?e+"":e,s);class T0{constructor(e,s){this.core=e,this.logger=s,Kt(this,"keychain",new Map),Kt(this,"name",Ob),Kt(this,"version",Tb),Kt(this,"initialized",!1),Kt(this,"storagePrefix",ts),Kt(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Kt(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Kt(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),Kt(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:n}=R("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(n)}return i}),Kt(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=ct(s,this.name)}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Wo(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ho(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var k0=Object.defineProperty,x0=(t,e,s)=>e in t?k0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ze=(t,e,s)=>x0(t,typeof e!="symbol"?e+"":e,s);class $0{constructor(e,s,r){this.core=e,this.logger=s,Ze(this,"name",Sb),Ze(this,"keychain"),Ze(this,"randomSessionIdentifier",ea()),Ze(this,"initialized",!1),Ze(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ze(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Ze(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),n=Fa(i);return Dd(n.publicKey)}),Ze(this,"generateKeyPair",()=>{this.isInitialized();const i=Ey();return this.setPrivateKey(i.publicKey,i.privateKey)}),Ze(this,"signJWT",async i=>{this.isInitialized();const n=await this.getClientSeed(),o=Fa(n),a=this.randomSessionIdentifier;return await Ld(a,i,Pb,o)}),Ze(this,"generateSharedKey",(i,n,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=Cy(a,n);return this.setSymKey(c,o)}),Ze(this,"setSymKey",async(i,n)=>{this.isInitialized();const o=n||En(i);return await this.keychain.set(o,i),o}),Ze(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ze(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ze(this,"encode",async(i,n,o)=>{this.isInitialized();const a=Dh(o),c=wa(n);if(Zc(a))return _y(c,o?.encoding);if(Xc(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(d,p)}const l=this.getSymKey(i),{type:u,senderPublicKey:h}=a;return Iy({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o?.encoding})}),Ze(this,"decode",async(i,n,o)=>{this.isInitialized();const a=Sy(n,o);if(Zc(a)){const c=Ay(n,o?.encoding);return Pn(c)}if(Xc(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=Ny({symKey:c,encoded:n,encoding:o?.encoding});return Pn(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ze(this,"getPayloadType",(i,n=Wt)=>{const o=Di({encoded:i,encoding:n});return tr(o.type)}),Ze(this,"getPayloadSenderPublicKey",(i,n=Wt)=>{const o=Di({encoded:i,encoding:n});return o.senderPublicKey?wt(o.senderPublicKey,at):void 0}),this.core=e,this.logger=ct(s,this.name),this.keychain=r||new T0(this.core,this.logger)}get context(){return At(this.logger)}async setPrivateKey(e,s){return await this.keychain.set(e,s),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ul)}catch{e=ea(),await this.keychain.set(ul,e)}return S0(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var R0=Object.defineProperty,U0=Object.defineProperties,D0=Object.getOwnPropertyDescriptors,bl=Object.getOwnPropertySymbols,L0=Object.prototype.hasOwnProperty,M0=Object.prototype.propertyIsEnumerable,ia=(t,e,s)=>e in t?R0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,B0=(t,e)=>{for(var s in e||(e={}))L0.call(e,s)&&ia(t,s,e[s]);if(bl)for(var s of bl(e))M0.call(e,s)&&ia(t,s,e[s]);return t},j0=(t,e)=>U0(t,D0(e)),bt=(t,e,s)=>ia(t,typeof e!="symbol"?e+"":e,s);class q0 extends Rf{constructor(e,s){super(e,s),this.logger=e,this.core=s,bt(this,"messages",new Map),bt(this,"messagesWithoutClientAck",new Map),bt(this,"name",kb),bt(this,"version",xb),bt(this,"initialized",!1),bt(this,"storagePrefix",ts),bt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),bt(this,"set",async(r,i,n)=>{this.isInitialized();const o=Zt(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),n===Cn.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,j0(B0({},c),{[o]:i}))}return await this.persist(),o}),bt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),bt(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const n of r){const o=this.messagesWithoutClientAck.get(n)||{};i[n]=Object.values(o)}return i}),bt(this,"has",(r,i)=>{this.isInitialized();const n=this.get(r),o=Zt(i);return typeof n[o]<"u"}),bt(this,"ack",async(r,i)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(r);if(typeof n>"u")return;const o=Zt(i);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,n),await this.persist()}),bt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=ct(e,this.name),this.core=s}get context(){return At(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,Wo(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Wo(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ho(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Ho(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var F0=Object.defineProperty,W0=Object.defineProperties,H0=Object.getOwnPropertyDescriptors,vl=Object.getOwnPropertySymbols,z0=Object.prototype.hasOwnProperty,V0=Object.prototype.propertyIsEnumerable,na=(t,e,s)=>e in t?F0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ln=(t,e)=>{for(var s in e||(e={}))z0.call(e,s)&&na(t,s,e[s]);if(vl)for(var s of vl(e))V0.call(e,s)&&na(t,s,e[s]);return t},Io=(t,e)=>W0(t,H0(e)),Bt=(t,e,s)=>na(t,typeof e!="symbol"?e+"":e,s);class K0 extends Uf{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Bt(this,"events",new $s.EventEmitter),Bt(this,"name",$b),Bt(this,"queue",new Map),Bt(this,"publishTimeout",D.toMiliseconds(D.ONE_MINUTE)),Bt(this,"initialPublishTimeout",D.toMiliseconds(D.ONE_SECOND*15)),Bt(this,"needsTransportRestart",!1),Bt(this,"publish",async(r,i,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:n}});const a=n?.ttl||hl,c=$n(n),l=n?.prompt||!1,u=n?.tag||0,h=n?.id||Tr().toString(),d={topic:r,message:i,opts:{ttl:a,relay:c,prompt:l,tag:u,id:h,attestation:n?.attestation,tvf:n?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${u}`;try{const w=new Promise(async m=>{const f=({id:b})=>{d.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(Ve.publish,f),m(d))};this.relayer.events.on(Ve.publish,f);const y=_s(new Promise((b,v)=>{this.rpcPublish({topic:r,message:i,ttl:a,prompt:l,tag:u,id:h,attestation:n?.attestation,tvf:n?.tvf}).then(b).catch(C=>{this.logger.warn(C,C?.message),v(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${u}`);try{await y,this.events.removeListener(Ve.publish,f)}catch(b){this.queue.set(h,Io(ln({},d),{attempt:1})),this.logger.warn(b,b?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:r,message:i,opts:n}}),await _s(w,this.publishTimeout,p)}catch(w){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(w),(o=n?.internal)!=null&&o.throwOnFailedPublish)throw w}finally{this.queue.delete(h)}}),Bt(this,"on",(r,i)=>{this.events.on(r,i)}),Bt(this,"once",(r,i)=>{this.events.once(r,i)}),Bt(this,"off",(r,i)=>{this.events.off(r,i)}),Bt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=ct(s,this.name),this.registerEventListeners()}get context(){return At(this.logger)}async rpcPublish(e){var s,r,i,n;const{topic:o,message:a,ttl:c=hl,prompt:l,tag:u,id:h,attestation:d,tvf:p}=e,w={method:wi($n().protocol).publish,params:ln({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:d},p),id:h};rt((s=w.params)==null?void 0:s.prompt)&&((r=w.params)==null||delete r.prompt),rt((i=w.params)==null?void 0:i.tag)&&((n=w.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w});const m=await this.relayer.request(w);return this.relayer.events.emit(Ve.publish,e),this.logger.debug("Successfully Published Payload"),m}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{const r=e.attempt+1;this.queue.set(s,Io(ln({},e),{attempt:r}));const{topic:i,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${r}`),await this.rpcPublish(Io(ln({},e),{topic:i,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Xr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ve.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ve.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var G0=Object.defineProperty,J0=(t,e,s)=>e in t?G0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pr=(t,e,s)=>J0(t,typeof e!="symbol"?e+"":e,s);class Y0{constructor(){pr(this,"map",new Map),pr(this,"set",(e,s)=>{const r=this.get(e);this.exists(e,s)||this.map.set(e,[...r,s])}),pr(this,"get",e=>this.map.get(e)||[]),pr(this,"exists",(e,s)=>this.get(e).includes(s)),pr(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,s))return;const i=r.filter(n=>n!==s);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),pr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var X0=Object.defineProperty,Z0=Object.defineProperties,Q0=Object.getOwnPropertyDescriptors,El=Object.getOwnPropertySymbols,eE=Object.prototype.hasOwnProperty,tE=Object.prototype.propertyIsEnumerable,oa=(t,e,s)=>e in t?X0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,hi=(t,e)=>{for(var s in e||(e={}))eE.call(e,s)&&oa(t,s,e[s]);if(El)for(var s of El(e))tE.call(e,s)&&oa(t,s,e[s]);return t},No=(t,e)=>Z0(t,Q0(e)),Ee=(t,e,s)=>oa(t,typeof e!="symbol"?e+"":e,s);class sE extends Mf{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Ee(this,"subscriptions",new Map),Ee(this,"topicMap",new Y0),Ee(this,"events",new $s.EventEmitter),Ee(this,"name",jb),Ee(this,"version",qb),Ee(this,"pending",new Map),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",ts),Ee(this,"subscribeTimeout",D.toMiliseconds(D.ONE_MINUTE)),Ee(this,"initialSubscribeTimeout",D.toMiliseconds(D.ONE_SECOND*15)),Ee(this,"clientId"),Ee(this,"batchSubscribeTopicsLimit",500),Ee(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Ee(this,"subscribe",async(r,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const n=$n(i),o={topic:r,relay:n,transportType:i?.transportType};this.pending.set(r,o);const a=await this.rpcSubscribe(r,n,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),Ee(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),Ee(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),Ee(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(n=>n.topic===r))})),Ee(this,"on",(r,i)=>{this.events.on(r,i)}),Ee(this,"once",(r,i)=>{this.events.once(r,i)}),Ee(this,"off",(r,i)=>{this.events.off(r,i)}),Ee(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),Ee(this,"start",async()=>{await this.onConnect()}),Ee(this,"stop",async()=>{await this.onDisconnect()}),Ee(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Ee(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),Ee(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Xr.pulse,async()=>{await this.checkPending()}),this.events.on(vt.created,async r=>{const i=vt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(vt.deleted,async r=>{const i=vt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=ct(s,this.name),this.clientId=""}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,s){let r=!1;try{r=this.getSubscription(e).topic===s}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,s){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,s)))}async unsubscribeById(e,s,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:r}});try{const i=$n(r);await this.restartToComplete({topic:e,id:s,relay:i}),await this.rpcUnsubscribe(e,s,i);const n=ye("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,s,r){var i;(!r||r?.transportType===Pe.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const n={method:wi(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(i=r?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(r?.transportType===Pe.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(u=>this.logger.warn(u))},D.toMiliseconds(D.ONE_SECOND)),a;const c=new Promise(async u=>{const h=d=>{d.topic===e&&(this.events.removeListener(vt.created,h),u(d.id))};this.events.on(vt.created,h);try{const d=await _s(new Promise((p,w)=>{this.relayer.request(n).catch(m=>{this.logger.warn(m,m?.message),w(m)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(vt.created,h),u(d)}catch{}}),l=await _s(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ve.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,r={method:wi(s.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await _s(new Promise(i=>{this.relayer.request(r).catch(n=>this.logger.warn(n)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Ve.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,r={method:wi(s.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await _s(new Promise((n,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Ve.connection_stalled)}return i}rpcUnsubscribe(e,s,r){const i={method:wi(r.protocol).unsubscribe,params:{topic:e,id:s}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,s){this.setSubscription(e,No(hi({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,hi({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,r){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,s){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:s}),this.addSubscription(e,s)}addSubscription(e,s){this.subscriptions.set(e,hi({},s)),this.topicMap.set(s.topic,e),this.events.emit(vt.created,s)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const s=this.subscriptions.get(e);if(!s){const{message:r}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(vt.deleted,No(hi({},r),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(vt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<s;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(vt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:s}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async s=>No(hi({},s),{id:await this.getSubscriptionId(s.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const s=await this.rpcBatchFetchMessages(e);s&&s.messages&&(await cm(D.toMiliseconds(D.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(s.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=R("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 Zt(e+await this.getClientId())}}var rE=Object.defineProperty,Cl=Object.getOwnPropertySymbols,iE=Object.prototype.hasOwnProperty,nE=Object.prototype.propertyIsEnumerable,aa=(t,e,s)=>e in t?rE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Il=(t,e)=>{for(var s in e||(e={}))iE.call(e,s)&&aa(t,s,e[s]);if(Cl)for(var s of Cl(e))nE.call(e,s)&&aa(t,s,e[s]);return t},ue=(t,e,s)=>aa(t,typeof e!="symbol"?e+"":e,s);class oE extends Df{constructor(e){super(e),ue(this,"protocol","wc"),ue(this,"version",2),ue(this,"core"),ue(this,"logger"),ue(this,"events",new $s.EventEmitter),ue(this,"provider"),ue(this,"messages"),ue(this,"subscriber"),ue(this,"publisher"),ue(this,"name",Ub),ue(this,"transportExplicitlyClosed",!1),ue(this,"initialized",!1),ue(this,"connectionAttemptInProgress",!1),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"packageName"),ue(this,"bundleId"),ue(this,"hasExperiencedNetworkDisruption",!1),ue(this,"pingTimeout"),ue(this,"heartBeatTimeout",D.toMiliseconds(D.THIRTY_SECONDS+D.FIVE_SECONDS)),ue(this,"reconnectTimeout"),ue(this,"connectPromise"),ue(this,"reconnectInProgress",!1),ue(this,"requestsInFlight",[]),ue(this,"connectTimeout",D.toMiliseconds(D.ONE_SECOND*15)),ue(this,"request",async s=>{var r,i;this.logger.debug("Publishing Request Payload");const n=s.id||Tr().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:s.method,topic:(r=s.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${n}:${((i=s.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(s);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),ue(this,"resetPingTimeout",()=>{kn()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var s,r,i,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(i=(r=(s=this.provider)==null?void 0:s.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||n.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),ue(this,"onPayloadHandler",s=>{this.onProviderPayload(s),this.resetPingTimeout()}),ue(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Ve.connect)}),ue(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ue(this,"onProviderErrorHandler",s=>{this.logger.fatal(`Fatal socket error: ${s.message}`),this.events.emit(Ve.error,s),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ue(this,"registerProviderListeners",()=>{this.provider.on(Tt.payload,this.onPayloadHandler),this.provider.on(Tt.connect,this.onConnectHandler),this.provider.on(Tt.disconnect,this.onDisconnectHandler),this.provider.on(Tt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ct(e.logger,this.name):ya(ji({level:e.logger||Rb})),this.messages=new q0(this.logger,e.core),this.subscriber=new sE(this,this.logger),this.publisher=new K0(this,this.logger),this.relayUrl=e?.relayUrl||Fh,this.projectId=e.projectId,Vg()?this.packageName=Ec():Kg()&&(this.bundleId=Ec()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return At(this.logger)}get connected(){var e,s,r;return((r=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,s,r;return((r=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,r){this.isInitialized(),await this.publisher.publish(e,s,r),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:Pe.relay},Cn.outbound)}async subscribe(e,s){var r,i,n;this.isInitialized(),(!(s!=null&&s.transportType)||s?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=s?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=s?.internal)==null?void 0:i.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(vt.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(vt.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,Il({internal:{throwOnFailedPublish:o}},s)).catch(d=>{o&&h(d)})||a,u()})]),a}async unsubscribe(e,s){this.isInitialized(),await this.subscriber.unsubscribe(e,s)}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}off(e,s){this.events.off(e,s)}removeListener(e,s){this.events.removeListener(e,s)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await _s(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(s,r)=>{await this.connect(e).then(s).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ll())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const s=e.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const r of s)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:r}=e;if(!s.sessionExists){const i=Be(D.FIVE_MINUTES),n={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,n)}this.events.emit(Ve.message,e),await this.recordMessageEvent(e,Cn.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let s=1;for(;s<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${s}...`),await this.createProvider(),await new Promise(async(r,i)=>{const n=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Tt.disconnect,n),await _s(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(Tt.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Tt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Tt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${s}`);break}await new Promise(r=>setTimeout(r,D.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,r,i,n;if(kn())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((n=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ut(new Ud(Zg({sdkVersion:ta,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,s){const{topic:r,message:i}=e;await this.messages.set(r,i,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const i=this.messages.has(s,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),ba(e)){if(!e.method.endsWith(Db))return;const s=e.params,{topic:r,message:i,publishedAt:n,attestation:o}=s.data,a={topic:r,message:i,publishedAt:n,transportType:Pe.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Il({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else va(e)&&this.events.emit(Ve.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Cn.inbound),this.events.emit(Ve.message,e))}async acknowledgePayload(e){const s=Bn(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Tt.payload,this.onPayloadHandler),this.provider.off(Tt.connect,this.onConnectHandler),this.provider.off(Tt.disconnect,this.onDisconnectHandler),this.provider.off(Tt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await ll();vb(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Xr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Ib())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Ve.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},D.toMiliseconds(Lb)))))}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function aE(){}function Nl(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function _l(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Al(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const cE="[object RegExp]",lE="[object String]",uE="[object Number]",hE="[object Boolean]",Sl="[object Arguments]",dE="[object Symbol]",pE="[object Date]",fE="[object Map]",gE="[object Set]",mE="[object Array]",wE="[object Function]",yE="[object ArrayBuffer]",_o="[object Object]",bE="[object Error]",vE="[object DataView]",EE="[object Uint8Array]",CE="[object Uint8ClampedArray]",IE="[object Uint16Array]",NE="[object Uint32Array]",_E="[object BigUint64Array]",AE="[object Int8Array]",SE="[object Int16Array]",PE="[object Int32Array]",OE="[object BigInt64Array]",TE="[object Float32Array]",kE="[object Float64Array]";function xE(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function $E(t,e,s){return yi(t,e,void 0,void 0,void 0,void 0,s)}function yi(t,e,s,r,i,n,o){const a=o(t,e,s,r,i,n);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Si(t,e,n,o)}return Si(t,e,n,o)}function Si(t,e,s,r){if(Object.is(t,e))return!0;let i=Al(t),n=Al(e);if(i===Sl&&(i=_o),n===Sl&&(n=_o),i!==n)return!1;switch(i){case lE:return t.toString()===e.toString();case uE:{const c=t.valueOf(),l=e.valueOf();return xE(c,l)}case hE:case pE:case dE:return Object.is(t.valueOf(),e.valueOf());case cE:return t.source===e.source&&t.flags===e.flags;case wE:return t===e}s=s??new Map;const o=s.get(t),a=s.get(e);if(o!=null&&a!=null)return o===e;s.set(t,e),s.set(e,t);try{switch(i){case fE:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!yi(l,e.get(c),c,t,e,s,r))return!1;return!0}case gE:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],d=l.findIndex(p=>yi(h,p,void 0,t,e,s,r));if(d===-1)return!1;l.splice(d,1)}return!0}case mE:case EE:case CE:case IE:case NE:case _E:case AE:case SE:case PE:case OE:case TE:case kE:{if(typeof Ye<"u"&&Ye.isBuffer(t)!==Ye.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!yi(t[c],e[c],c,t,e,s,r))return!1;return!0}case yE:return t.byteLength!==e.byteLength?!1:Si(new Uint8Array(t),new Uint8Array(e),s,r);case vE:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Si(new Uint8Array(t),new Uint8Array(e),s,r);case bE:return t.name===e.name&&t.message===e.message;case _o:{if(!(Si(t.constructor,e.constructor,s,r)||Nl(t)&&Nl(e)))return!1;const c=[...Object.keys(t),..._l(t)],l=[...Object.keys(e),..._l(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],d=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!yi(d,p,h,t,e,s,r))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function RE(t,e){return $E(t,e,aE)}var UE=Object.defineProperty,Pl=Object.getOwnPropertySymbols,DE=Object.prototype.hasOwnProperty,LE=Object.prototype.propertyIsEnumerable,ca=(t,e,s)=>e in t?UE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ol=(t,e)=>{for(var s in e||(e={}))DE.call(e,s)&&ca(t,s,e[s]);if(Pl)for(var s of Pl(e))LE.call(e,s)&&ca(t,s,e[s]);return t},dt=(t,e,s)=>ca(t,typeof e!="symbol"?e+"":e,s);class or extends Lf{constructor(e,s,r,i=ts,n=void 0){super(e,s,r,i),this.core=e,this.logger=s,this.name=r,dt(this,"map",new Map),dt(this,"version",Mb),dt(this,"cached",[]),dt(this,"initialized",!1),dt(this,"getKey"),dt(this,"storagePrefix",ts),dt(this,"recentlyDeleted",[]),dt(this,"recentlyDeletedLimit",200),dt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!rt(o)?this.map.set(this.getKey(o),o):Xy(o)?this.map.set(o.id,o):Zy(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),dt(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),dt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),dt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>RE(a[c],o[c]))):this.values)),dt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Ol(Ol({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),dt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=ct(s,this.name),this.storagePrefix=i,this.getKey=n}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const s=this.map.get(e);if(!s){if(this.recentlyDeleted.includes(e)){const{message:i}=R("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return s}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:s}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ME=Object.defineProperty,BE=(t,e,s)=>e in t?ME(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ne=(t,e,s)=>BE(t,typeof e!="symbol"?e+"":e,s);class jE{constructor(e,s){this.core=e,this.logger=s,ne(this,"name",Fb),ne(this,"version",Wb),ne(this,"events",new Ca),ne(this,"pairings"),ne(this,"initialized",!1),ne(this,"storagePrefix",ts),ne(this,"ignoredPayloadTypes",[ps]),ne(this,"registeredMethods",[]),ne(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ne(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),ne(this,"create",async r=>{this.isInitialized();const i=ea(),n=await this.core.crypto.setSymKey(i),o=Be(D.FIVE_MINUTES),a={protocol:qh},c={topic:n,expiry:o,relay:a,active:!1,methods:r?.methods},l=el({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(Hs.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:r?.transportType}),{topic:n,uri:l}}),ne(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[Jt.pairing_started]}});this.isValidPair(r,i);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Qc(r.uri);i.props.properties.topic=n,i.addTrace(Jt.pairing_uri_validation_success),i.addTrace(Jt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),i.addTrace(Jt.existing_pairing),u.active)throw i.setError(ls.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);i.addTrace(Jt.pairing_not_expired)}const h=c||Be(D.FIVE_MINUTES),d={topic:n,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(n,h),await this.pairings.set(n,d),i.addTrace(Jt.store_new_pairing),r.activatePairing&&await this.activate({topic:n}),this.events.emit(Hs.create,d),i.addTrace(Jt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),i.addTrace(Jt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(ls.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw i.setError(ls.subscribe_pairing_topic_failure),p}return i.addTrace(Jt.subscribe_pairing_topic_success),d}),ne(this,"activate",async({topic:r})=>{this.isInitialized();const i=Be(D.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),ne(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const n=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=qs();this.events.once(fe("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),ne(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),ne(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),ne(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ne(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",ye("USER_DISCONNECTED")),await this.deletePairing(i))}),ne(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:n,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return el({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),ne(this,"sendRequest",async(r,i,n)=>{const o=Vs(i,n),a=await this.core.crypto.encode(r,o),c=li[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),ne(this,"sendResult",async(r,i,n)=>{const o=Bn(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=li[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ne(this,"sendError",async(r,i,n)=>{const o=gu(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=li[c]?li[c].res:li.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ne(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,ye("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),ne(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>Es(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),ne(this,"onRelayEventRequest",async r=>{const{topic:i,payload:n}=r;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,n);default:return await this.onUnknownRpcMethodRequest(i,n)}}),ne(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n}=r,o=(await this.core.history.get(i,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,n);default:return this.onUnknownRpcMethodResponse(o)}}),ne(this,"onPairingPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult(n,r,!0),this.events.emit(Hs.ping,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),ne(this,"onPairingPingResponse",(r,i)=>{const{id:n}=i;setTimeout(()=>{cs(i)?this.events.emit(fe("pairing_ping",n),{}):Yt(i)&&this.events.emit(fe("pairing_ping",n),{error:i.error})},500)}),ne(this,"onPairingDeleteRequest",async(r,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Hs.delete,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),ne(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:n,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=ye("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,r,a),this.logger.error(a)}catch(a){await this.sendError(n,r,a),this.logger.error(a)}}),ne(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(ye("WC_METHOD_UNSUPPORTED",r))}),ne(this,"isValidPair",(r,i)=>{var n;if(!gt(r)){const{message:a}=R("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(ls.malformed_pairing_uri),new Error(a)}if(!Yy(r.uri)){const{message:a}=R("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(ls.malformed_pairing_uri),new Error(a)}const o=Qc(r?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(ls.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(ls.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&D.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(ls.pairing_expired);const{message:a}=R("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ne(this,"isValidPing",async r=>{if(!gt(r)){const{message:n}=R("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),ne(this,"isValidDisconnect",async r=>{if(!gt(r)){const{message:n}=R("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),ne(this,"isValidPairingTopic",async r=>{if(!Ue(r,!1)){const{message:i}=R("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(Es(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=R("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=ct(s,this.name),this.pairings=new or(this.core,this.logger,this.name,this.storagePrefix)}get context(){return At(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ve.message,async e=>{const{topic:s,message:r,transportType:i}=e;if(this.pairings.keys.includes(s)&&i!==Pe.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const n=await this.core.crypto.decode(s,r);ba(n)?(this.core.history.set(s,n),await this.onRelayEventRequest({topic:s,payload:n})):va(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:s,payload:n}),this.core.history.delete(s,n.id)),await this.core.relayer.messages.ack(s,r)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on($t.expired,async e=>{const{topic:s}=rh(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(Hs.expire,{topic:s}))})}}var qE=Object.defineProperty,FE=(t,e,s)=>e in t?qE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qe=(t,e,s)=>FE(t,typeof e!="symbol"?e+"":e,s);class WE extends $f{constructor(e,s){super(e,s),this.core=e,this.logger=s,Qe(this,"records",new Map),Qe(this,"events",new $s.EventEmitter),Qe(this,"name",Hb),Qe(this,"version",zb),Qe(this,"cached",[]),Qe(this,"initialized",!1),Qe(this,"storagePrefix",ts),Qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Qe(this,"set",(r,i,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:n}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:n,expiry:Be(D.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Lt.created,o)}),Qe(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=Yt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(Lt.updated,i))}),Qe(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Qe(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(n=>{if(n.topic===r){if(typeof i<"u"&&n.id!==i)return;this.records.delete(n.id),this.events.emit(Lt.deleted,n)}}),this.persist()}),Qe(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Qe(this,"on",(r,i)=>{this.events.on(r,i)}),Qe(this,"once",(r,i)=>{this.events.once(r,i)}),Qe(this,"off",(r,i)=>{this.events.off(r,i)}),Qe(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=ct(s,this.name)}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(s=>{if(typeof s.response<"u")return;const r={topic:s.topic,request:Vs(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const s=this.records.get(e);if(!s){const{message:r}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Lt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Lt.created,e=>{const s=Lt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Lt.updated,e=>{const s=Lt.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Lt.deleted,e=>{const s=Lt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(Xr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{D.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(Lt.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var HE=Object.defineProperty,zE=(t,e,s)=>e in t?HE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,st=(t,e,s)=>zE(t,typeof e!="symbol"?e+"":e,s);class VE extends Bf{constructor(e,s){super(e,s),this.core=e,this.logger=s,st(this,"expirations",new Map),st(this,"events",new $s.EventEmitter),st(this,"name",Vb),st(this,"version",Kb),st(this,"cached",[]),st(this,"initialized",!1),st(this,"storagePrefix",ts),st(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),st(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),st(this,"set",(r,i)=>{this.isInitialized();const n=this.formatTarget(r),o={target:n,expiry:i};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit($t.created,{target:n,expiration:o})}),st(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),st(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),n=this.getExpiration(i);this.expirations.delete(i),this.events.emit($t.deleted,{target:i,expiration:n})}}),st(this,"on",(r,i)=>{this.events.on(r,i)}),st(this,"once",(r,i)=>{this.events.once(r,i)}),st(this,"off",(r,i)=>{this.events.off(r,i)}),st(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=ct(s,this.name)}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Qg(e);if(typeof e=="number")return em(e);const{message:s}=R("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(s)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit($t.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const s=this.expirations.get(e);if(!s){const{message:r}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return s}checkExpiry(e,s){const{expiry:r}=s;D.toMiliseconds(r)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit($t.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(Xr.pulse,()=>this.checkExpirations()),this.events.on($t.created,e=>{const s=$t.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on($t.expired,e=>{const s=$t.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on($t.deleted,e=>{const s=$t.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var KE=Object.defineProperty,GE=(t,e,s)=>e in t?KE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Re=(t,e,s)=>GE(t,typeof e!="symbol"?e+"":e,s);class JE extends jf{constructor(e,s,r){super(e,s,r),this.core=e,this.logger=s,this.store=r,Re(this,"name",Gb),Re(this,"abortController"),Re(this,"isDevEnv"),Re(this,"verifyUrlV3",Yb),Re(this,"storagePrefix",ts),Re(this,"version",jh),Re(this,"publicKey"),Re(this,"fetchPromise"),Re(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&D.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Re(this,"register",async i=>{if(!ei()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=Br(),u=this.startAbortTimer(D.ONE_SECOND*5),h=await new Promise((d,p)=>{const w=()=>{window.removeEventListener("message",f),l.body.removeChild(m),p("attestation aborted")};this.abortController.signal.addEventListener("abort",w);const m=l.createElement("iframe");m.src=c,m.style.display="none",m.addEventListener("error",w,{signal:this.abortController.signal});const f=y=>{if(y.data&&typeof y.data=="string")try{const b=JSON.parse(y.data);if(b.type==="verify_attestation"){if(Uo(b.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(m),this.abortController.signal.removeEventListener("abort",w),window.removeEventListener("message",f),d(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};l.body.appendChild(m),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(l){this.logger.warn(l)}return""}),Re(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=i;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(Uo(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),Re(this,"fetchAttestation",async(i,n)=>{this.logger.debug(`resolving attestation: ${i} from url: ${n}`);const o=this.startAbortTimer(D.ONE_SECOND*5),a=await fetch(`${n}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),Re(this,"getVerifyUrl",i=>{let n=i||Ai;return Xb.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ai}`),n=Ai),n}),Re(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(D.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await n.json()}catch(i){this.logger.warn(i)}}),Re(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Re(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Re(this,"isValidJwtAttestation",async i=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(i,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Re(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Re(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),Re(this,"validateAttestation",(i,n)=>{const o=Oy(i,n.publicKey),a={hasExpired:D.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=ct(s,this.name),this.abortController=new AbortController,this.isDevEnv=Na(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return At(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),D.toMiliseconds(e))}}var YE=Object.defineProperty,XE=(t,e,s)=>e in t?YE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Tl=(t,e,s)=>XE(t,typeof e!="symbol"?e+"":e,s);class ZE extends qf{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,Tl(this,"context",Zb),Tl(this,"registerDeviceToken",async r=>{const{clientId:i,token:n,notificationType:o,enableEncrypted:a=!1}=r,c=`${Qb}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:n,always_raw:a})})}),this.logger=ct(s,this.context)}}var QE=Object.defineProperty,kl=Object.getOwnPropertySymbols,eC=Object.prototype.hasOwnProperty,tC=Object.prototype.propertyIsEnumerable,la=(t,e,s)=>e in t?QE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,di=(t,e)=>{for(var s in e||(e={}))eC.call(e,s)&&la(t,s,e[s]);if(kl)for(var s of kl(e))tC.call(e,s)&&la(t,s,e[s]);return t},Fe=(t,e,s)=>la(t,typeof e!="symbol"?e+"":e,s);class sC extends Ff{constructor(e,s,r=!0){super(e,s,r),this.core=e,this.logger=s,Fe(this,"context",tv),Fe(this,"storagePrefix",ts),Fe(this,"storageVersion",ev),Fe(this,"events",new Map),Fe(this,"shouldPersist",!1),Fe(this,"init",async()=>{if(!Na())try{const i={eventId:Ic(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:th(this.core.relayer.protocol,this.core.relayer.version,ta)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Fe(this,"createEvent",i=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=Ic(),u=this.core.projectId||"",h=Date.now(),d=di({eventId:l,timestamp:h,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,d),this.shouldPersist=!0),d}),Fe(this,"getEvent",i=>{const{eventId:n,topic:o}=i;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return di(di({},a),this.setMethods(a.eventId))}),Fe(this,"deleteEvent",i=>{const{eventId:n}=i;this.events.delete(n),this.shouldPersist=!0}),Fe(this,"setEventListeners",()=>{this.core.heartbeat.on(Xr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{D.fromMiliseconds(Date.now())-D.fromMiliseconds(i.timestamp)>sv&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Fe(this,"setMethods",i=>({addTrace:n=>this.addTrace(i,n),setError:n=>this.setError(i,n)})),Fe(this,"addTrace",(i,n)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(n),this.events.set(i,o),this.shouldPersist=!0)}),Fe(this,"setError",(i,n)=>{const o=this.events.get(i);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Fe(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Fe(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(n=>{this.events.set(n.eventId,di(di({},n),this.setMethods(n.eventId)))})}catch(i){this.logger.warn(i)}}),Fe(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[n,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const n of i)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),Fe(this,"sendEvent",async i=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${rv}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${ta}${n}`,{method:"POST",body:JSON.stringify(i)})}),Fe(this,"getAppDomain",()=>eh().url),this.logger=ct(s,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var rC=Object.defineProperty,xl=Object.getOwnPropertySymbols,iC=Object.prototype.hasOwnProperty,nC=Object.prototype.propertyIsEnumerable,ua=(t,e,s)=>e in t?rC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$l=(t,e)=>{for(var s in e||(e={}))iC.call(e,s)&&ua(t,s,e[s]);if(xl)for(var s of xl(e))nC.call(e,s)&&ua(t,s,e[s]);return t},Ae=(t,e,s)=>ua(t,typeof e!="symbol"?e+"":e,s);let oC=class ed extends Of{constructor(e){var s;super(e),Ae(this,"protocol",Bh),Ae(this,"version",jh),Ae(this,"name",Un),Ae(this,"relayUrl"),Ae(this,"projectId"),Ae(this,"customStoragePrefix"),Ae(this,"events",new $s.EventEmitter),Ae(this,"logger"),Ae(this,"heartbeat"),Ae(this,"relayer"),Ae(this,"crypto"),Ae(this,"storage"),Ae(this,"history"),Ae(this,"expirer"),Ae(this,"pairing"),Ae(this,"verify"),Ae(this,"echoClient"),Ae(this,"linkModeSupportedApps"),Ae(this,"eventClient"),Ae(this,"initialized",!1),Ae(this,"logChunkController"),Ae(this,"on",(a,c)=>this.events.on(a,c)),Ae(this,"once",(a,c)=>this.events.once(a,c)),Ae(this,"off",(a,c)=>this.events.off(a,c)),Ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Pe.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Fh,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=ji({level:typeof e?.logger=="string"&&e.logger?e.logger:_b.logger,name:Un}),{logger:n,chunkLoggerController:o}=fu({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(s=this.logChunkController)!=null&&s.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ct(n,this.name),this.heartbeat=new Rd,this.crypto=new $0(this,this.logger,e?.keychain),this.history=new WE(this,this.logger),this.expirer=new VE(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Af($l($l({},Ab),e?.storageOptions)),this.relayer=new oE({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new jE(this,this.logger),this.verify=new JE(this,this.logger,this.storage),this.echoClient=new ZE(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new sC(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new ed(e);await s.initialize();const r=await s.crypto.getClientId();return await s.storage.setItem(Bb,r),s}get context(){return At(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(dl,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(dl)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${e}`,r=`${s}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[s]}catch(s){console.warn("Failed to get global WalletConnect core",s);return}}setGlobalCore(e){var s;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof As<"u"&&Nb.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const aC=oC,td="wc",sd=2,rd="client",xa=`${td}@${sd}:${rd}:`,Ao={name:rd,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Rl="WALLETCONNECT_DEEPLINK_CHOICE",cC="proposal",Ul="Proposal expired",lC="session",fr=D.SEVEN_DAYS,uC="engine",We={wc_sessionPropose:{req:{ttl:D.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1104},res:{ttl:D.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1106},res:{ttl:D.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:D.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:D.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1112},res:{ttl:D.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1114},res:{ttl:D.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:D.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:D.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1119}}},So={min:D.FIVE_MINUTES,max:D.SEVEN_DAYS},Gt={idle:"IDLE",active:"ACTIVE"},Dl={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},hC="request",dC=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],pC="wc",fC="auth",gC="authKeys",mC="pairingTopics",wC="requests",Xn=`${pC}@${1.5}:${fC}:`,In=`${Xn}:PUB_KEY`;var yC=Object.defineProperty,bC=Object.defineProperties,vC=Object.getOwnPropertyDescriptors,Ll=Object.getOwnPropertySymbols,EC=Object.prototype.hasOwnProperty,CC=Object.prototype.propertyIsEnumerable,ha=(t,e,s)=>e in t?yC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ce=(t,e)=>{for(var s in e||(e={}))EC.call(e,s)&&ha(t,s,e[s]);if(Ll)for(var s of Ll(e))CC.call(e,s)&&ha(t,s,e[s]);return t},ot=(t,e)=>bC(t,vC(e)),P=(t,e,s)=>ha(t,typeof e!="symbol"?e+"":e,s);class IC extends Vf{constructor(e){super(e),P(this,"name",uC),P(this,"events",new Ca),P(this,"initialized",!1),P(this,"requestQueue",{state:Gt.idle,queue:[]}),P(this,"sessionRequestQueue",{state:Gt.idle,queue:[]}),P(this,"requestQueueDelay",D.ONE_SECOND),P(this,"expectedPairingMethodMap",new Map),P(this,"recentlyDeletedMap",new Map),P(this,"recentlyDeletedLimit",200),P(this,"relayMessageCache",[]),P(this,"pendingSessions",new Map),P(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(We)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},D.toMiliseconds(this.requestQueueDelay)))}),P(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=ot(Ce({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=zy(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=r;let u=i,h,d=!1;try{if(u){const _=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=_.active}}catch(_){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),_}if(!u||!d){const{topic:_,uri:A}=await this.client.core.pairing.create();u=_,h=A}if(!u){const{message:_}=R("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(_)}const p=await this.client.core.crypto.generateKeyPair(),w=We.wc_sessionPropose.req.ttl||D.FIVE_MINUTES,m=Be(w),f=ot(Ce(Ce({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:qh}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:fs()}),y=fe("session_connect",f.id),{reject:b,resolve:v,done:C}=qs(w,Ul),S=({id:_})=>{_===f.id&&(this.client.events.off("proposal_expire",S),this.pendingSessions.delete(f.id),this.events.emit(y,{error:{message:Ul,code:0}}))};return this.client.events.on("proposal_expire",S),this.events.once(y,({error:_,session:A})=>{this.client.events.off("proposal_expire",S),_?b(_):A&&v(A)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:h,approval:C}}),P(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(r){throw this.client.logger.error("pair() failed"),r}}),P(this,"approve",async s=>{var r,i,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=s?.id)==null?void 0:r.toString(),trace:[Mt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(E){throw o.setError(Ls.no_internet_connection),E}try{await this.isValidProposalId(s?.id)}catch(E){throw this.client.logger.error(`approve() -> proposal.get(${s?.id}) failed`),o.setError(Ls.proposal_not_found),E}try{await this.isValidApprove(s)}catch(E){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Ls.session_approve_namespace_validation_failure),E}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:d}=s,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:w,proposer:m,requiredNamespaces:f,optionalNamespaces:y}=p;let b=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:w});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Mt.session_approve_started,properties:{topic:w,trace:[Mt.session_approve_started,Mt.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),C=m.publicKey,S=await this.client.core.crypto.generateSharedKey(v,C),_=Ce(Ce(Ce({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:Be(fr)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),A=Pe.relay;b.addTrace(Mt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(S,{transportType:A})}catch(E){throw b.setError(Ls.subscribe_session_topic_failure),E}b.addTrace(Mt.subscribe_session_topic_success);const U=ot(Ce({},_),{topic:S,requiredNamespaces:f,optionalNamespaces:y,pairingTopic:w,acknowledged:!1,self:_.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:v,transportType:Pe.relay});await this.client.session.set(S,U),b.addTrace(Mt.store_session);try{b.addTrace(Mt.publishing_session_settle),await this.sendRequest({topic:S,method:"wc_sessionSettle",params:_,throwOnFailedPublish:!0}).catch(E=>{throw b?.setError(Ls.session_settle_publish_failure),E}),b.addTrace(Mt.session_settle_publish_success),b.addTrace(Mt.publishing_session_approve),await this.sendResult({id:a,topic:w,result:{relay:{protocol:c??"irn"},responderPublicKey:v},throwOnFailedPublish:!0}).catch(E=>{throw b?.setError(Ls.session_approve_publish_failure),E}),b.addTrace(Mt.session_approve_publish_success)}catch(E){throw this.client.logger.error(E),this.client.session.delete(S,ye("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(S),E}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:m.metadata}),await this.client.proposal.delete(a,ye("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(S,Be(fr)),{topic:S,acknowledged:()=>Promise.resolve(this.client.session.get(S))}}),P(this,"reject",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(s)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=s;let n;try{n=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}n&&(await this.sendError({id:r,topic:n,error:i,rpcOpts:We.wc_sessionPropose.reject}),await this.client.proposal.delete(r,ye("USER_DISCONNECTED")))}),P(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:r,namespaces:i}=s,{done:n,resolve:o,reject:a}=qs(),c=fs(),l=Tr().toString(),u=this.client.session.get(r).namespaces;return this.events.once(fe("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(r,{namespaces:u}),a(h)}),{acknowledged:n}}),P(this,"extend",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(s)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=s,i=fs(),{done:n,resolve:o,reject:a}=qs();return this.events.once(fe("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,Be(fr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),P(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:i,topic:n,expiry:o=We.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(n);a?.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const c=fs(),l=Tr().toString(),{done:u,resolve:h,reject:d}=qs(o,"Request expired. Please try again.");this.events.once(fe("session_request",c),({error:y,result:b})=>{y?d(y):h(b)});const p="wc_sessionRequest",w=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(w)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:p,params:{request:ot(Ce({},i),{expiryTimestamp:Be(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:w}).catch(y=>d(y)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),await u();const m={request:ot(Ce({},i),{expiryTimestamp:Be(o)}),chainId:r},f=this.shouldSetTVF(p,m);return await Promise.all([new Promise(async y=>{await this.sendRequest(Ce({clientRpcId:c,relayRpcId:l,topic:n,method:p,params:m,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,m)})).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const v=await im(this.client.core.storage,Rl);await tm({id:c,topic:n,wcDeepLink:v})}y()}),u()]).then(y=>y[2])}),P(this,"respond",async s=>{this.isInitialized(),await this.isValidRespond(s);const{topic:r,response:i}=s,{id:n}=i,o=this.client.session.get(r);o.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);cs(i)?await this.sendResult({id:n,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:a}):Yt(i)&&await this.sendError({id:n,topic:r,error:i.error,appLink:a}),this.cleanupAfterResponse(s)}),P(this,"ping",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(s)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=s;if(this.client.session.keys.includes(r)){const i=fs(),n=Tr().toString(),{done:o,resolve:a,reject:c}=qs();this.events.once(fe("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(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:r}))}),P(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:r,event:i,chainId:n}=s,o=Tr().toString(),a=fs();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),P(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:r}=s;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:ye("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=R("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),P(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(r=>Gy(r,s)))),P(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),P(this,"authenticate",async(s,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(s);const n=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=n?Pe.link_mode:Pe.relay;o===Pe.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:d,exp:p,nbf:w,methods:m=[],expiry:f}=s,y=[...s.resources||[]],{topic:b,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:v}});const C=await this.client.core.crypto.generateKeyPair(),S=En(C);if(await Promise.all([this.client.auth.authKeys.set(In,{responseTopic:S,publicKey:C}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:b})]),await this.client.core.relayer.subscribe(S,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),m.length>0){const{namespace:x}=Dr(a[0]);let G=Ym(x,"request",m);vn(y)&&(G=Zm(G,y.pop())),y.push(G)}const _=f&&f>We.wc_sessionAuthenticate.req.ttl?f:We.wc_sessionAuthenticate.req.ttl,A={authPayload:{type:d??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:w,resources:y},requester:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Be(_)},U={eip155:{chains:a,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},E={requiredNamespaces:{},optionalNamespaces:U,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Be(We.wc_sessionPropose.req.ttl),id:fs()},{done:$,resolve:I,reject:L}=qs(_,"Request expired"),z=fs(),N=fe("session_connect",E.id),k=fe("session_request",z),O=async({error:x,session:G})=>{this.events.off(k,B),x?L(x):G&&I({session:G})},B=async x=>{var G,ee,re;if(await this.deletePendingAuthRequest(z,{message:"fulfilled",code:0}),x.error){const Le=ye("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===Le.code?void 0:(this.events.off(N,O),L(x.error.message))}await this.deleteProposal(E.id),this.events.off(N,O);const{cacaos:Ne,responder:pe}=x.result,$e=[],qe=[];for(const Le of Ne){await kc({cacao:Le,projectId:this.client.core.projectId})||(this.client.logger.error(Le,"Signature verification failed"),L(ye("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Us}=Le,ss=vn(Us.resources),zt=[zo(Us.iss)],rs=xn(Us.iss);if(ss){const cr=xc(ss),Zi=$c(ss);$e.push(...cr),zt.push(...Zi)}for(const cr of zt)qe.push(`${cr}:${rs}`)}const tt=await this.client.core.crypto.generateSharedKey(C,pe.publicKey);let De;$e.length>0&&(De={topic:tt,acknowledged:!0,self:{publicKey:C,metadata:this.client.metadata},peer:pe,controller:pe.publicKey,expiry:Be(fr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:il([...new Set($e)],[...new Set(qe)]),transportType:o},await this.client.core.relayer.subscribe(tt,{transportType:o}),await this.client.session.set(tt,De),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:pe.metadata}),De=this.client.session.get(tt)),(G=this.client.metadata.redirect)!=null&&G.linkMode&&(ee=pe.metadata.redirect)!=null&&ee.linkMode&&(re=pe.metadata.redirect)!=null&&re.universal&&r&&(this.client.core.addLinkModeSupportedApp(pe.metadata.redirect.universal),this.client.session.update(tt,{transportType:Pe.link_mode})),I({auths:Ne,session:De})};this.events.once(N,O),this.events.once(k,B);let F;try{if(n){const x=Vs("wc_sessionAuthenticate",A,z);this.client.core.history.set(b,x);const G=await this.client.core.crypto.encode("",x,{type:Gi,encoding:Cs});F=cn(r,b,G)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:A,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:z}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:E,expiry:We.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(x){throw this.events.off(N,O),this.events.off(k,B),x}return await this.setProposal(E.id,E),await this.setAuthRequest(z,{request:ot(Ce({},A),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:F??v,response:$}}),P(this,"approveSessionAuthenticate",async s=>{const{id:r,auths:i}=s,n=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Ms.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(ui.no_internet_connection),f}const o=this.getPendingAuthRequest(r);if(!o)throw n.setError(ui.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Pe.relay;a===Pe.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=En(c),h={type:ps,receiverPublicKey:c,senderPublicKey:l},d=[],p=[];for(const f of i){if(!await kc({cacao:f,projectId:this.client.core.projectId})){n.setError(ui.invalid_cacao);const S=ye("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:S,encodeOpts:h}),new Error(S.message)}n.addTrace(Ms.cacaos_verified);const{p:y}=f,b=vn(y.resources),v=[zo(y.iss)],C=xn(y.iss);if(b){const S=xc(b),_=$c(b);d.push(...S),v.push(..._)}for(const S of v)p.push(`${S}:${C}`)}const w=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Ms.create_authenticated_session_topic);let m;if(d?.length>0){m={topic:w,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Be(fr),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:il([...new Set(d)],[...new Set(p)]),transportType:a},n.addTrace(Ms.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:a})}catch(f){throw n.setError(ui.subscribe_authenticated_session_topic_failure),f}n.addTrace(Ms.subscribe_authenticated_session_topic_success),await this.client.session.set(w,m),n.addTrace(Ms.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Ms.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(f){throw n.setError(ui.authenticated_session_approve_publish_failure),f}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:m}}),P(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:r,reason:i}=s,n=this.getPendingAuthRequest(r);if(!n)throw new Error(`Could not find pending auth request with id ${r}`);n.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=En(o),l={type:ps,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:l,rpcOpts:We.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.client.proposal.delete(r,ye("USER_DISCONNECTED"))}),P(this,"formatAuthMessage",s=>{this.isInitialized();const{request:r,iss:i}=s;return dh(r,i)}),P(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const s=this.relayMessageCache.shift();s&&await this.onRelayMessage(s)}catch(s){this.client.logger.error(s)}},50)}),P(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const r=this.client.core.pairing.pairings.get(s.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&n.topic&&n.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),P(this,"deleteSession",async s=>{var r;const{topic:i,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=s,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,ye("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),n||this.client.core.expirer.del(i),this.client.core.storage.removeItem(Rl).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,ye("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=Gt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),P(this,"deleteProposal",async(s,r)=>{if(r)try{const i=this.client.proposal.get(s);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(Ls.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,ye("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),P(this,"deletePendingSessionRequest",async(s,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(s,r),i?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==s),i&&(this.sessionRequestQueue.state=Gt.idle,this.client.events.emit("session_request_expire",{id:s}))}),P(this,"deletePendingAuthRequest",async(s,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(s,r),i?Promise.resolve():this.client.core.expirer.del(s)])}),P(this,"setExpiry",async(s,r)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,r),await this.client.session.update(s,{expiry:r}))}),P(this,"setProposal",async(s,r)=>{this.client.core.expirer.set(s,Be(We.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,r)}),P(this,"setAuthRequest",async(s,r)=>{const{request:i,pairingTopic:n,transportType:o=Pe.relay}=r;this.client.core.expirer.set(s,i.expiryTimestamp),await this.client.auth.requests.set(s,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:s,pairingTopic:n,verifyContext:i.verifyContext,transportType:o})}),P(this,"setPendingSessionRequest",async s=>{const{id:r,topic:i,params:n,verifyContext:o}=s,a=n.request.expiryTimestamp||Be(We.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:n,verifyContext:o})}),P(this,"sendRequest",async s=>{const{topic:r,method:i,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h}=s,d=Vs(i,n,c);let p;const w=!!u;try{const y=w?Cs:Wt;p=await this.client.core.crypto.encode(r,d,{encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),y}let m;if(dC.includes(i)){const y=Zt(JSON.stringify(d)),b=Zt(p);m=await this.client.core.verify.register({id:b,decryptedId:y})}const f=We[i].req;if(f.attestation=m,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(r,d),w){const y=cn(u,r,p);await Q.Linking.openURL(y,this.client.name)}else{const y=We[i].req;o&&(y.ttl=o),a&&(y.id=a),y.tvf=ot(Ce({},h),{correlationId:d.id}),l?(y.internal=ot(Ce({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,y)):this.client.core.relayer.publish(r,p,y).catch(b=>this.client.logger.error(b))}return d.id}),P(this,"sendResult",async s=>{const{id:r,topic:i,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=Bn(r,n);let u;const h=c&&typeof(Q==null?void 0:Q.Linking)<"u";try{const w=h?Cs:Wt;u=await this.client.core.crypto.encode(i,l,ot(Ce({},a||{}),{encoding:w}))}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),w}let d,p;try{d=await this.client.core.history.get(i,r);const w=d.request;try{this.shouldSetTVF(w.method,w.params)&&(p=this.getTVFParams(r,w.params,n))}catch(m){this.client.logger.warn("sendResult() -> getTVFParams() failed",m)}}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),w}if(h){const w=cn(c,i,u);await Q.Linking.openURL(w,this.client.name)}else{const w=d.request.method,m=We[w].res;m.tvf=ot(Ce({},p),{correlationId:r}),o?(m.internal=ot(Ce({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,m)):this.client.core.relayer.publish(i,u,m).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(l)}),P(this,"sendError",async s=>{const{id:r,topic:i,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=gu(r,n);let u;const h=c&&typeof(Q==null?void 0:Q.Linking)<"u";try{const p=h?Cs:Wt;u=await this.client.core.crypto.encode(i,l,ot(Ce({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let d;try{d=await this.client.core.history.get(i,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),p}if(h){const p=cn(c,i,u);await Q.Linking.openURL(p,this.client.name)}else{const p=d.request.method,w=a||We[p].res;this.client.core.relayer.publish(i,u,w)}await this.client.core.history.resolve(l)}),P(this,"cleanup",async()=>{const s=[],r=[];this.client.session.getAll().forEach(i=>{let n=!1;Es(i.expiry)&&(n=!0),this.client.core.crypto.keychain.has(i.topic)||(n=!0),n&&s.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Es(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...s.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),P(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),P(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),P(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Gt.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Gt.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=Gt.idle}),P(this,"processRequest",async s=>{const{topic:r,payload:i,attestation:n,transportType:o,encryptedId:a}=s,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),P(this,"onRelayEventResponse",async s=>{const{topic:r,payload:i,transportType:n}=s,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,n);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),P(this,"onRelayEventUnknownPayload",s=>{const{topic:r}=s,{message:i}=R("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),P(this,"shouldIgnorePairingRequest",s=>{const{topic:r,requestMethod:i}=s,n=this.expectedPairingMethodMap.get(r);return!n||n.includes(i)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),P(this,"onSessionProposeRequest",async s=>{const{topic:r,payload:i,attestation:n,encryptedId:o}=s,{params:a,id:c}=i;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(ls.proposal_listener_not_found)),this.isValidConnect(Ce({},i.params));const u=a.expiryTimestamp||Be(We.wc_sessionPropose.req.ttl),h=Ce({id:c,pairingTopic:r,expiryTimestamp:u},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:n,hash:Zt(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});l?.addTrace(Jt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:We.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),P(this,"onSessionProposeResponse",async(s,r,i)=>{const{id:n}=r;if(cs(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:s,proposalId:n,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:s})}else if(Yt(r)){await this.client.proposal.delete(n,ye("USER_DISCONNECTED"));const o=fe("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),P(this,"onSessionSettleRequest",async(s,r)=>{const{id:i,params:n}=r;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:d}=r.params,p=[...this.pendingSessions.values()].find(f=>f.sessionTopic===s);if(!p)return this.client.logger.error(`Pending session not found for topic ${s}`);const w=this.client.proposal.get(p.proposalId),m=ot(Ce(Ce(Ce({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),{transportType:Pe.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(fe("session_connect",p.proposalId),{session:m}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:r.id,topic:s,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),P(this,"onSessionSettleResponse",async(s,r)=>{const{id:i}=r;cs(r)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(fe("session_approve",i),{})):Yt(r)&&(await this.client.session.delete(s,ye("USER_DISCONNECTED")),this.events.emit(fe("session_approve",i),{error:r.error}))}),P(this,"onSessionUpdateRequest",async(s,r)=>{const{params:i,id:n}=r;try{const o=`${s}_session_update`,a=ci.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:s,error:ye("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ce({topic:s},i));try{ci.set(o,n),await this.client.session.update(s,{namespaces:i.namespaces}),await this.sendResult({id:n,topic:s,result:!0,throwOnFailedPublish:!0})}catch(c){throw ci.delete(o),c}this.client.events.emit("session_update",{id:n,topic:s,params:i})}catch(o){await this.sendError({id:n,topic:s,error:o}),this.client.logger.error(o)}}),P(this,"isRequestOutOfSync",(s,r)=>r.toString().slice(0,-3)<s.toString().slice(0,-3)),P(this,"onSessionUpdateResponse",(s,r)=>{const{id:i}=r,n=fe("session_update",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);cs(r)?this.events.emit(fe("session_update",i),{}):Yt(r)&&this.events.emit(fe("session_update",i),{error:r.error})}),P(this,"onSessionExtendRequest",async(s,r)=>{const{id:i}=r;try{this.isValidExtend({topic:s}),await this.setExpiry(s,Be(fr)),await this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:s})}catch(n){await this.sendError({id:i,topic:s,error:n}),this.client.logger.error(n)}}),P(this,"onSessionExtendResponse",(s,r)=>{const{id:i}=r,n=fe("session_extend",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);cs(r)?this.events.emit(fe("session_extend",i),{}):Yt(r)&&this.events.emit(fe("session_extend",i),{error:r.error})}),P(this,"onSessionPingRequest",async(s,r)=>{const{id:i}=r;try{this.isValidPing({topic:s}),await this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:s})}catch(n){await this.sendError({id:i,topic:s,error:n}),this.client.logger.error(n)}}),P(this,"onSessionPingResponse",(s,r)=>{const{id:i}=r,n=fe("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);cs(r)?this.events.emit(fe("session_ping",i),{}):Yt(r)&&this.events.emit(fe("session_ping",i),{error:r.error})},500)}),P(this,"onSessionDeleteRequest",async(s,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:s,reason:r.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(Ve.publish,async()=>{n(await this.deleteSession({topic:s,id:i}))})}),this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:ye("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),P(this,"onSessionRequest",async s=>{var r,i,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=s,{id:h,params:d}=a;try{await this.isValidRequest(Ce({topic:o},d));const p=this.client.session.get(o),w=await this.getVerifyContext({attestationId:c,hash:Zt(JSON.stringify(Vs("wc_sessionRequest",d,h))),encryptedId:l,metadata:p.peer.metadata,transportType:u}),m={id:h,topic:o,params:d,verifyContext:w};await this.setPendingSessionRequest(m),u===Pe.link_mode&&(r=p.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),P(this,"onSessionRequestResponse",(s,r)=>{const{id:i}=r,n=fe("session_request",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);cs(r)?this.events.emit(fe("session_request",i),{result:r.result}):Yt(r)&&this.events.emit(fe("session_request",i),{error:r.error})}),P(this,"onSessionEventRequest",async(s,r)=>{const{id:i,params:n}=r;try{const o=`${s}_session_event_${n.event.name}`,a=ci.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Ce({topic:s},n)),this.client.events.emit("session_event",{id:i,topic:s,params:n}),ci.set(o,i)}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),P(this,"onSessionAuthenticateResponse",(s,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:r}),cs(r)?this.events.emit(fe("session_request",i),{result:r.result}):Yt(r)&&this.events.emit(fe("session_request",i),{error:r.error})}),P(this,"onSessionAuthenticateRequest",async s=>{var r;const{topic:i,payload:n,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:u,expiryTimestamp:h}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Zt(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:i,id:n.id,authPayload:u,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(n.id,{request:p,pairingTopic:i,transportType:c}),c===Pe.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:n.params,id:n.id,verifyContext:d})}catch(l){this.client.logger.error(l);const u=n.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),p={type:ps,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:n.id,topic:i,error:l,encodeOpts:p,rpcOpts:We.wc_sessionAuthenticate.autoReject,appLink:d})}}),P(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),P(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Gt.idle,this.processSessionRequestQueue()},D.toMiliseconds(this.requestQueueDelay))}),P(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(n=>n.topic===s&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=fe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(fe("session_request",n.request.id),{error:r})})}),P(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Gt.active){this.client.logger.info("session request queue is already active.");return}const s=this.sessionRequestQueue.queue[0];if(!s){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Gt.active,this.emitSessionRequest(s)}catch(r){this.client.logger.error(r)}}),P(this,"emitSessionRequest",s=>{this.client.events.emit("session_request",s)}),P(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===s.topic);r&&this.onSessionProposeRequest({topic:s.topic,payload:Vs("wc_sessionPropose",ot(Ce({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id)})}),P(this,"isValidConnect",async s=>{if(!gt(s)){const{message:l}=R("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=s;if(rt(r)||await this.isValidPairingTopic(r),!ob(c)){const{message:l}=R("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!rt(i)&&Ts(i)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(i,"requiredNamespaces")}if(!rt(n)&&Ts(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),rt(o)||this.validateSessionProps(o,"sessionProperties"),!rt(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(u=>l.includes(u)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),P(this,"validateNamespaces",(s,r)=>{const i=nb(s,"connect()",r);if(i)throw new Error(i.message)}),P(this,"isValidApprove",async s=>{if(!gt(s))throw new Error(R("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:r,namespaces:i,relayProtocol:n,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=vo(i,"approve()");if(l)throw new Error(l.message);const u=al(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!Ue(n,!0)){const{message:h}=R("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}if(rt(o)||this.validateSessionProps(o,"sessionProperties"),!rt(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),P(this,"isValidReject",async s=>{if(!gt(s)){const{message:n}=R("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(n)}const{id:r,reason:i}=s;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!cb(i)){const{message:n}=R("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(n)}}),P(this,"isValidSessionSettleRequest",s=>{if(!gt(s)){const{message:l}=R("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:r,controller:i,namespaces:n,expiry:o}=s;if(!Mh(r)){const{message:l}=R("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Qy(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=vo(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Es(o)){const{message:l}=R("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),P(this,"isValidUpdate",async s=>{if(!gt(s)){const{message:c}=R("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:r,namespaces:i}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const n=this.client.session.get(r),o=vo(i,"update()");if(o)throw new Error(o.message);const a=al(n.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),P(this,"isValidExtend",async s=>{if(!gt(s)){const{message:i}=R("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(i)}const{topic:r}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),P(this,"isValidRequest",async s=>{if(!gt(s)){const{message:c}=R("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:r,request:i,chainId:n,expiry:o}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!ol(a,n)){const{message:c}=R("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!lb(i)){const{message:c}=R("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!db(a,n,i.method)){const{message:c}=R("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!mb(o,So)){const{message:c}=R("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${So.min} and ${So.max}`);throw new Error(c)}}),P(this,"isValidRespond",async s=>{var r;if(!gt(s)){const{message:o}=R("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(o)}const{topic:i,response:n}=s;try{await this.isValidSessionTopic(i)}catch(o){throw(r=s?.response)!=null&&r.id&&this.cleanupAfterResponse(s),o}if(!ub(n)){const{message:o}=R("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),P(this,"isValidPing",async s=>{if(!gt(s)){const{message:i}=R("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(i)}const{topic:r}=s;await this.isValidSessionOrPairingTopic(r)}),P(this,"isValidEmit",async s=>{if(!gt(s)){const{message:a}=R("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}const{topic:r,event:i,chainId:n}=s;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!ol(o,n)){const{message:a}=R("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!hb(i)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!pb(o,n,i.name)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),P(this,"isValidDisconnect",async s=>{if(!gt(s)){const{message:i}=R("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(i)}const{topic:r}=s;await this.isValidSessionOrPairingTopic(r)}),P(this,"isValidAuthenticate",s=>{const{chains:r,uri:i,domain:n,nonce:o}=s;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!Ue(i,!1))throw new Error("uri is required parameter");if(!Ue(n,!1))throw new Error("domain is required parameter");if(!Ue(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Dr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Dr(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),P(this,"getVerifyContext",async s=>{const{attestationId:r,hash:i,encryptedId:n,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||Ai,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Pe.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:n,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),P(this,"validateSessionProps",(s,r)=>{Object.values(s).forEach((i,n)=>{if(i==null){const{message:o}=R("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(s)[n]}`);throw new Error(o)}})}),P(this,"getPendingAuthRequest",s=>{const r=this.client.auth.requests.get(s);return typeof r=="object"?r:void 0}),P(this,"addToRecentlyDeleted",(s,r)=>{if(this.recentlyDeletedMap.set(s,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=n)break;this.recentlyDeletedMap.delete(o)}}}),P(this,"checkRecentlyDeleted",s=>{const r=this.recentlyDeletedMap.get(s);if(r){const{message:i}=R("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${s}`);throw new Error(i)}}),P(this,"isLinkModeEnabled",(s,r)=>{var i,n,o,a,c,l,u,h,d;return!s||r!==Pe.link_mode?!1:((n=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=s?.redirect)==null?void 0:u.universal)!==void 0&&((h=s?.redirect)==null?void 0:h.universal)!==""&&((d=s?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(Q==null?void 0:Q.Linking)<"u"}),P(this,"getAppLinkIfEnabled",(s,r)=>{var i;return this.isLinkModeEnabled(s,r)?(i=s?.redirect)==null?void 0:i.universal:void 0}),P(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const r=Cc(s,"topic")||"",i=decodeURIComponent(Cc(s,"wc_ev")||""),n=this.client.session.keys.includes(r);n&&this.client.session.update(r,{transportType:Pe.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:n})}),P(this,"registerLinkModeListeners",async()=>{var s;if(Na()||Rs()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const r=Q==null?void 0:Q.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),P(this,"shouldSetTVF",(s,r)=>{if(!r||s!=="wc_sessionRequest")return!1;const{request:i}=r;return Object.keys(Dl).includes(i.method)}),P(this,"getTVFParams",(s,r,i)=>{var n,o;try{const a=r.request.method,c=this.extractTxHashesFromResult(a,i);return ot(Ce({correlationId:s,rpcMethods:[a],chainId:r.chainId},this.isValidContractData(r.request.params)&&{contractAddresses:[(o=(n=r.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),P(this,"isValidContractData",s=>{var r;if(!s)return!1;try{const i=s?.data||((r=s?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const n=i.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),P(this,"extractTxHashesFromResult",(s,r)=>{try{const i=Dl[s];if(typeof r=="string")return[r];const n=r[i.key];if(Os(n))return s==="solana_signAllTransactions"?n.map(o=>Dm(o)):n;if(typeof n=="string")return[n]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,s=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,i]of Object.entries(s))for(const n of i)try{await this.onProviderMessageEvent({topic:r,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ve.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:r,attestation:i,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(In)?this.client.auth.authKeys.get(In):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,r,{receiverPublicKey:o,encoding:n===Pe.link_mode?Cs:Wt});ba(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:i,transportType:n,encryptedId:Zt(r)})):va(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:n}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(s,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on($t.expired,async e=>{const{topic:s,id:r}=rh(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,R("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,R("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(Hs.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Hs.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ue(e,!1)){const{message:s}=R("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(s)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:s}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(Es(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=R("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!Ue(e,!1)){const{message:s}=R("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(s)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:s}=R("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(Es(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=R("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=R("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(s)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(Ue(e,!1)){const{message:s}=R("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=R("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!ab(e)){const{message:s}=R("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=R("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(Es(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=R("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class NC extends or{constructor(e,s){super(e,s,cC,xa),this.core=e,this.logger=s}}let _C=class extends or{constructor(e,s){super(e,s,lC,xa),this.core=e,this.logger=s}};class AC extends or{constructor(e,s){super(e,s,hC,xa,r=>r.id),this.core=e,this.logger=s}}class SC extends or{constructor(e,s){super(e,s,gC,Xn,()=>In),this.core=e,this.logger=s}}class PC extends or{constructor(e,s){super(e,s,mC,Xn),this.core=e,this.logger=s}}class OC extends or{constructor(e,s){super(e,s,wC,Xn,r=>r.id),this.core=e,this.logger=s}}var TC=Object.defineProperty,kC=(t,e,s)=>e in t?TC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Po=(t,e,s)=>kC(t,typeof e!="symbol"?e+"":e,s);class xC{constructor(e,s){this.core=e,this.logger=s,Po(this,"authKeys"),Po(this,"pairingTopics"),Po(this,"requests"),this.authKeys=new SC(this.core,this.logger),this.pairingTopics=new PC(this.core,this.logger),this.requests=new OC(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var $C=Object.defineProperty,RC=(t,e,s)=>e in t?$C(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oe=(t,e,s)=>RC(t,typeof e!="symbol"?e+"":e,s);let UC=class id extends zf{constructor(e){super(e),oe(this,"protocol",td),oe(this,"version",sd),oe(this,"name",Ao.name),oe(this,"metadata"),oe(this,"core"),oe(this,"logger"),oe(this,"events",new $s.EventEmitter),oe(this,"engine"),oe(this,"session"),oe(this,"proposal"),oe(this,"pendingRequest"),oe(this,"auth"),oe(this,"signConfig"),oe(this,"on",(r,i)=>this.events.on(r,i)),oe(this,"once",(r,i)=>this.events.once(r,i)),oe(this,"off",(r,i)=>this.events.off(r,i)),oe(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),oe(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),oe(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),oe(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(n){throw this.logger.error(n.message),n}}),oe(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ao.name,this.metadata=Jg(e?.metadata),this.signConfig=e?.signConfig;const s=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ya(ji({level:e?.logger||Ao.logger}));this.core=e?.core||new aC(e),this.logger=ct(s,this.name),this.session=new _C(this.core,this.logger),this.proposal=new NC(this.core,this.logger),this.pendingRequest=new AC(this.core,this.logger),this.engine=new IC(this),this.auth=new xC(this.core,this.logger)}static async init(e){const s=new id(e);return await s.initialize(),s}get context(){return At(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},D.toMiliseconds(D.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Ml="error",DC="wss://relay.walletconnect.org",LC="wc",MC="universal_provider",un=`${LC}@2:${MC}:`,nd="https://rpc.walletconnect.org/v1/",Sr="generic",BC=`${nd}bundler`,Dt={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function jC(){}function $a(t){return t==null||typeof t!="object"&&typeof t!="function"}function Ra(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function qC(t){if($a(t))return t;if(Array.isArray(t)||Ra(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),s=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new s(t);if(t instanceof RegExp){const r=new s(t);return r.lastIndex=t.lastIndex,r}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const r=new s(t.message);return r.stack=t.stack,r.name=t.name,r.cause=t.cause,r}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const r=Object.create(e);return Object.assign(r,t)}return t}function Bl(t){return typeof t=="object"&&t!==null}function od(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ad(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const FC="[object RegExp]",cd="[object String]",ld="[object Number]",ud="[object Boolean]",hd="[object Arguments]",WC="[object Symbol]",HC="[object Date]",zC="[object Map]",VC="[object Set]",KC="[object Array]",GC="[object ArrayBuffer]",JC="[object Object]",YC="[object DataView]",XC="[object Uint8Array]",ZC="[object Uint8ClampedArray]",QC="[object Uint16Array]",e1="[object Uint32Array]",t1="[object Int8Array]",s1="[object Int16Array]",r1="[object Int32Array]",i1="[object Float32Array]",n1="[object Float64Array]";function o1(t,e){return $r(t,void 0,t,new Map,e)}function $r(t,e,s,r=new Map,i=void 0){const n=i?.(t,e,s,r);if(n!=null)return n;if($a(t))return t;if(r.has(t))return r.get(t);if(Array.isArray(t)){const o=new Array(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=$r(t[a],a,s,r,i);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;r.set(t,o);for(const[a,c]of t)o.set(a,$r(c,a,s,r,i));return o}if(t instanceof Set){const o=new Set;r.set(t,o);for(const a of t)o.add($r(a,void 0,s,r,i));return o}if(typeof Ye<"u"&&Ye.isBuffer(t))return t.subarray();if(Ra(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=$r(t[a],a,s,r,i);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return r.set(t,o),zs(o,t,s,r,i),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return r.set(t,o),zs(o,t,s,r,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return r.set(t,o),zs(o,t,s,r,i),o}if(t instanceof Error){const o=new t.constructor;return r.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,zs(o,t,s,r,i),o}if(typeof t=="object"&&a1(t)){const o=Object.create(Object.getPrototypeOf(t));return r.set(t,o),zs(o,t,s,r,i),o}return t}function zs(t,e,s=t,r,i){const n=[...Object.keys(e),...od(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=$r(e[a],a,s,r,i))}}function a1(t){switch(ad(t)){case hd:case KC:case GC:case YC:case ud:case HC:case i1:case n1:case t1:case s1:case r1:case zC:case ld:case JC:case FC:case VC:case cd:case WC:case XC:case ZC:case QC:case e1:return!0;default:return!1}}function c1(t,e){return o1(t,(s,r,i,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case ld:case cd:case ud:{const o=new t.constructor(t?.valueOf());return zs(o,t),o}case hd:{const o={};return zs(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function jl(t){return c1(t)}function ql(t){return t!==null&&typeof t=="object"&&ad(t)==="[object Arguments]"}function l1(t){return Ra(t)}function u1(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const s=t[Symbol.toStringTag];return s==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${s}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function h1(t,...e){const s=e.slice(0,-1),r=e[e.length-1];let i=t;for(let n=0;n<s.length;n++){const o=s[n];i=da(i,o,r,new Map)}return i}function da(t,e,s,r){if($a(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(r.has(e))return qC(r.get(e));if(r.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const i=[...Object.keys(e),...od(e)];for(let n=0;n<i.length;n++){const o=i[n];let a=e[o],c=t[o];if(ql(a)&&(a={...a}),ql(c)&&(c={...c}),typeof Ye<"u"&&Ye.isBuffer(a)&&(a=jl(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let d=0;d<h.length;d++){const p=h[d];u[p]=c[p]}c=u}else c=[];const l=s(c,a,o,t,e,r);l!=null?t[o]=l:Array.isArray(a)||Bl(c)&&Bl(a)?t[o]=da(c,a,s,r):c==null&&u1(a)?t[o]=da({},a,s,r):c==null&&l1(a)?t[o]=jl(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function d1(t,...e){return h1(t,...e,jC)}var p1=Object.defineProperty,f1=Object.defineProperties,g1=Object.getOwnPropertyDescriptors,Fl=Object.getOwnPropertySymbols,m1=Object.prototype.hasOwnProperty,w1=Object.prototype.propertyIsEnumerable,Wl=(t,e,s)=>e in t?p1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,hn=(t,e)=>{for(var s in e||(e={}))m1.call(e,s)&&Wl(t,s,e[s]);if(Fl)for(var s of Fl(e))w1.call(e,s)&&Wl(t,s,e[s]);return t},y1=(t,e)=>f1(t,g1(e));function _t(t,e,s){var r;const i=Dr(t);return((r=e.rpcMap)==null?void 0:r[i.reference])||`${nd}?chainId=${i.namespace}:${i.reference}&projectId=${s}`}function ar(t){return t.includes(":")?t.split(":")[1]:t}function dd(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function b1(t,e){const s=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!s.length)return[];const r=[];return s.forEach(i=>{const n=e.namespaces[i].accounts;r.push(...n)}),r}function dn(t={},e={}){const s=Hl(t),r=Hl(e);return d1(s,r)}function Hl(t){var e,s,r,i,n;const o={};if(!Ts(t))return o;for(const[a,c]of Object.entries(t)){const l=Jn(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],d=c.rpcMap||{},p=xr(a);o[p]=y1(hn(hn({},o[p]),c),{chains:es(l,(e=o[p])==null?void 0:e.chains),methods:es(u,(s=o[p])==null?void 0:s.methods),events:es(h,(r=o[p])==null?void 0:r.events)}),(Ts(d)||Ts(((i=o[p])==null?void 0:i.rpcMap)||{}))&&(o[p].rpcMap=hn(hn({},d),(n=o[p])==null?void 0:n.rpcMap))}return o}function zl(t){return t.includes(":")?t.split(":")[2]:t}function Vl(t){const e={};for(const[s,r]of Object.entries(t)){const i=r.methods||[],n=r.events||[],o=r.accounts||[],a=Jn(s)?[s]:r.chains?r.chains:dd(r.accounts);e[s]={chains:a,methods:i,events:n,accounts:o}}return e}function Oo(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const pd={},he=t=>pd[t],To=(t,e)=>{pd[t]=e};var v1=Object.defineProperty,E1=(t,e,s)=>e in t?v1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,gr=(t,e,s)=>E1(t,typeof e!="symbol"?e+"":e,s);class C1{constructor(e){gr(this,"name","polkadot"),gr(this,"client"),gr(this,"httpProviders"),gr(this,"events"),gr(this,"namespace"),gr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var I1=Object.defineProperty,N1=Object.defineProperties,_1=Object.getOwnPropertyDescriptors,Kl=Object.getOwnPropertySymbols,A1=Object.prototype.hasOwnProperty,S1=Object.prototype.propertyIsEnumerable,pa=(t,e,s)=>e in t?I1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Gl=(t,e)=>{for(var s in e||(e={}))A1.call(e,s)&&pa(t,s,e[s]);if(Kl)for(var s of Kl(e))S1.call(e,s)&&pa(t,s,e[s]);return t},Jl=(t,e)=>N1(t,_1(e)),mr=(t,e,s)=>pa(t,typeof e!="symbol"?e+"":e,s);class P1{constructor(e){mr(this,"name","eip155"),mr(this,"client"),mr(this,"chainId"),mr(this,"namespace"),mr(this,"httpProviders"),mr(this,"events"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s),this.chainId=parseInt(e),this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,s){const r=s||_t(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=parseInt(ar(s));e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}async handleSwitchChain(e){var s,r;let i=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const n=parseInt(i,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,r,i,n,o;const a=(r=(s=e.request)==null?void 0:s.params)==null?void 0:r[0],c=((n=(i=e.request)==null?void 0:i.params)==null?void 0:n[1])||[],l=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const u=this.client.session.get(e.topic),h=((o=u?.sessionProperties)==null?void 0:o.capabilities)||{};if(h!=null&&h[l])return h?.[l];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Jl(Gl({},u.sessionProperties||{}),{capabilities:Jl(Gl({},h||{}),{[l]:d})})})}catch(p){console.warn("Failed to update session with capabilities",p)}return d}async getCallStatus(e){var s,r;const i=this.client.session.get(e.topic),n=(s=i.sessionProperties)==null?void 0:s.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(r=i.sessionProperties)==null?void 0:r.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,s){var r;const i=new URL(e),n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Vs("eth_getUserOperationReceipt",[(r=s.request.params)==null?void 0:r[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,s){return`${BC}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}}var O1=Object.defineProperty,T1=(t,e,s)=>e in t?O1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,wr=(t,e,s)=>T1(t,typeof e!="symbol"?e+"":e,s);class k1{constructor(e){wr(this,"name","solana"),wr(this,"client"),wr(this,"httpProviders"),wr(this,"events"),wr(this,"namespace"),wr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var x1=Object.defineProperty,$1=(t,e,s)=>e in t?x1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yr=(t,e,s)=>$1(t,typeof e!="symbol"?e+"":e,s);class R1{constructor(e){yr(this,"name","cosmos"),yr(this,"client"),yr(this,"httpProviders"),yr(this,"events"),yr(this,"namespace"),yr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var U1=Object.defineProperty,D1=(t,e,s)=>e in t?U1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,br=(t,e,s)=>D1(t,typeof e!="symbol"?e+"":e,s);class L1{constructor(e){br(this,"name","algorand"),br(this,"client"),br(this,"httpProviders"),br(this,"events"),br(this,"namespace"),br(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(!this.httpProviders[e]){const r=s||_t(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);return typeof r>"u"?void 0:new Ut(new Ht(r,he("disableProviderPing")))}}var M1=Object.defineProperty,B1=(t,e,s)=>e in t?M1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vr=(t,e,s)=>B1(t,typeof e!="symbol"?e+"":e,s);class j1{constructor(e){vr(this,"name","cip34"),vr(this,"client"),vr(this,"httpProviders"),vr(this,"events"),vr(this,"namespace"),vr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{const r=this.getCardanoRPCUrl(s),i=ar(s);e[i]=this.createHttpProvider(i,r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}getCardanoRPCUrl(e){const s=this.namespace.rpcMap;if(s)return s[e]}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||this.getCardanoRPCUrl(e);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var q1=Object.defineProperty,F1=(t,e,s)=>e in t?q1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Er=(t,e,s)=>F1(t,typeof e!="symbol"?e+"":e,s);class W1{constructor(e){Er(this,"name","elrond"),Er(this,"client"),Er(this,"httpProviders"),Er(this,"events"),Er(this,"namespace"),Er(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var H1=Object.defineProperty,z1=(t,e,s)=>e in t?H1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Cr=(t,e,s)=>z1(t,typeof e!="symbol"?e+"":e,s);class V1{constructor(e){Cr(this,"name","multiversx"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var K1=Object.defineProperty,G1=(t,e,s)=>e in t?K1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ir=(t,e,s)=>G1(t,typeof e!="symbol"?e+"":e,s);class J1{constructor(e){Ir(this,"name","near"),Ir(this,"client"),Ir(this,"httpProviders"),Ir(this,"events"),Ir(this,"namespace"),Ir(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||_t(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace);return typeof r>"u"?void 0:new Ut(new Ht(r,he("disableProviderPing")))}}var Y1=Object.defineProperty,X1=(t,e,s)=>e in t?Y1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Nr=(t,e,s)=>X1(t,typeof e!="symbol"?e+"":e,s);class Z1{constructor(e){Nr(this,"name","tezos"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||_t(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{e[s]=this.createHttpProvider(s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace);return typeof r>"u"?void 0:new Ut(new Ht(r))}}var Q1=Object.defineProperty,eI=(t,e,s)=>e in t?Q1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_r=(t,e,s)=>eI(t,typeof e!="symbol"?e+"":e,s);class tI{constructor(e){_r(this,"name",Sr),_r(this,"client"),_r(this,"httpProviders"),_r(this,"events"),_r(this,"namespace"),_r(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){var e,s;const r={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(i=>{const n=Dr(i);r[`${n.namespace}:${n.reference}`]=this.createHttpProvider(i)}),r}getHttpProvider(e){const s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var sI=Object.defineProperty,rI=Object.defineProperties,iI=Object.getOwnPropertyDescriptors,Yl=Object.getOwnPropertySymbols,nI=Object.prototype.hasOwnProperty,oI=Object.prototype.propertyIsEnumerable,fa=(t,e,s)=>e in t?sI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pn=(t,e)=>{for(var s in e||(e={}))nI.call(e,s)&&fa(t,s,e[s]);if(Yl)for(var s of Yl(e))oI.call(e,s)&&fa(t,s,e[s]);return t},ko=(t,e)=>rI(t,iI(e)),kt=(t,e,s)=>fa(t,typeof e!="symbol"?e+"":e,s);let aI=class fd{constructor(e){kt(this,"client"),kt(this,"namespaces"),kt(this,"optionalNamespaces"),kt(this,"sessionProperties"),kt(this,"scopedProperties"),kt(this,"events",new Ca),kt(this,"rpcProviders",{}),kt(this,"session"),kt(this,"providerOpts"),kt(this,"logger"),kt(this,"uri"),kt(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ya(ji({level:e?.logger||Ml})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const s=new fd(e);return await s.initialize(),s}async request(e,s,r){const[i,n]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:pn({},e),chainId:`${i}:${n}`,topic:this.session.topic,expiry:r})}sendAsync(e,s,r,i){const n=new Date().getTime();this.request(e,r,i).then(o=>s(null,Bn(n,o))).catch(o=>s(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:ye("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,s){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:i}=await this.client.authenticate(e,s);r&&(this.uri=r,this.events.emit("display_uri",r));const n=await i();if(this.session=n.session,this.session){const o=Vl(this.session.namespaces);this.namespaces=dn(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}removeListener(e,s){this.events.removeListener(e,s)}off(e,s){this.events.off(e,s)}get isWalletConnect(){return!0}async pair(e){const{uri:s,approval:r}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});s&&(this.uri=s,this.events.emit("display_uri",s));const i=await r();this.session=i;const n=Vl(i.namespaces);return this.namespaces=dn(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,s){try{if(!this.session)return;const[r,i]=this.validateChain(e),n=this.getProvider(r);n.name===Sr?n.setDefaultChain(`${r}:${i}`,s):n.setDefaultChain(i,s)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(Os(s)){for(const r of s)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,s;if(this.client=this.providerOpts.client||await UC.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Ml,relayUrl:this.providerOpts.relayUrl||DC,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(r){throw this.logger.error("Failed to get session",r),new Error(`The provided session: ${(s=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:s.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(s=>xr(s)))];To("client",this.client),To("events",this.events),To("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const r=b1(s,this.session),i=dd(r),n=dn(this.namespaces,this.optionalNamespaces),o=ko(pn({},n[s]),{accounts:r,chains:i});switch(s){case"eip155":this.rpcProviders[s]=new P1({namespace:o});break;case"algorand":this.rpcProviders[s]=new L1({namespace:o});break;case"solana":this.rpcProviders[s]=new k1({namespace:o});break;case"cosmos":this.rpcProviders[s]=new R1({namespace:o});break;case"polkadot":this.rpcProviders[s]=new C1({namespace:o});break;case"cip34":this.rpcProviders[s]=new j1({namespace:o});break;case"elrond":this.rpcProviders[s]=new W1({namespace:o});break;case"multiversx":this.rpcProviders[s]=new V1({namespace:o});break;case"near":this.rpcProviders[s]=new J1({namespace:o});break;case"tezos":this.rpcProviders[s]=new Z1({namespace:o});break;default:this.rpcProviders[Sr]?this.rpcProviders[Sr].updateNamespace(o):this.rpcProviders[Sr]=new tI({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var s;const{topic:r}=e;r===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:r,topic:i}=e;if(i!==((s=this.session)==null?void 0:s.topic))return;const{event:n}=r;if(n.name==="accountsChanged"){const o=n.data;o&&Os(o)&&this.events.emit("accountsChanged",o.map(zl))}else if(n.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=xr(o),l=Oo(o)!==Oo(a)?`${c}:${Oo(a)}`:o;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var r,i;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:n}=s,o=(i=this.client)==null?void 0:i.session.get(e);this.session=ko(pn({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:s})}),this.client.on("session_delete",async e=>{var s;e.topic===((s=this.session)==null?void 0:s.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",ko(pn({},ye("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Dt.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Sr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var s;this.getProvider(e).updateNamespace((s=this.session)==null?void 0:s.namespaces[e])})}setNamespaces(e){const{namespaces:s={},optionalNamespaces:r={},sessionProperties:i,scopedProperties:n}=e;this.optionalNamespaces=dn(s,r),this.sessionProperties=i,this.scopedProperties=n}validateChain(e){const[s,r]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,r];if(s&&!Object.keys(this.namespaces||{}).map(o=>xr(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&r)return[s,r];const i=xr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[i].getDefaultChain();return[i,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,s=!1){if(!this.namespaces)return;const[r,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(r,i),this.events.emit("chainChanged",i);const n=this.getProvider(r).getDefaultChain();s||this.getProvider(r).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:r,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:s,newChainId:r}){var i,n;try{if(s===r)return;const o=(n=(i=this.session)==null?void 0:i.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(zl);if(!Os(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,s){if(!this.namespaces)return;const r=this.namespaces[e]?e:`${e}:${s}`,i={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=s):this.namespaces[r]=i}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,s){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${un}/${e}${i}`,s)}async getFromStore(e){var s;const r=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${un}/${e}${r}`)}async deleteFromStore(e){var s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${un}/${e}${r}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const s=await this.client.core.storage.getKeys();for(const r of s)r.startsWith(un)&&await this.client.core.storage.removeItem(r)}catch(s){this.logger.warn("Failed to cleanup storage",s)}}};function fn(t,e){return q.getConnectorId(t)===e}function cI(t){const e=Array.from(g.state.chains.keys());let s=[];return t?(s.push([t,g.state.chains.get(t)]),fn(t,j.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(r=>{r!==t&&fn(r,j.CONNECTOR_ID.WALLET_CONNECT)&&s.push([r,g.state.chains.get(r)])}):fn(t,j.CONNECTOR_ID.AUTH)&&e.forEach(r=>{r!==t&&fn(r,j.CONNECTOR_ID.AUTH)&&s.push([r,g.state.chains.get(r)])})):s=Array.from(g.state.chains.entries()),s}const je={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"ID_AUTH"},Dn={ConnectorExplorerIds:{[j.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[j.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[j.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[j.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[j.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[je.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[je.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[je.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[je.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[je.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[je.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[je.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[je.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[je.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[je.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[je.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200"},ConnectorImageIds:{[j.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[j.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[j.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[j.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[j.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[j.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[j.CONNECTOR_ID.INJECTED]:"Browser Wallet",[j.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[j.CONNECTOR_ID.COINBASE]:"Coinbase",[j.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[j.CONNECTOR_ID.LEDGER]:"Ledger",[j.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[j.CONNECTOR_ID.INJECTED]:"INJECTED",[j.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[j.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[j.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]},Ua={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,r])=>{e[`${je.EIP155}:${s}`]=r}),e},isLowerCaseMatch(t,e){return t?.toLowerCase()===e?.toLowerCase()}},lI=new AbortController,Ar={EmbeddedWalletAbortController:lI,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"INVALID_APP_CONFIGURATION"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{shortMessage:"Network Not Found",longMessage:"Network not found - please make sure it is included in 'networks' array in createAppKit function"},INVALID_APP_CONFIGURATION:{shortMessage:"Invalid App Configuration",longMessage:()=>`Origin ${uI()?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},IFRAME_LOAD_FAILED:{shortMessage:"Network Error - Could not load embedded wallet",longMessage:()=>"There was an issue loading the embedded wallet. Please try again later."},IFRAME_REQUEST_TIMEOUT:{shortMessage:"Embedded Wallet Request Timed Out",longMessage:()=>"There was an issue doing the request to the embedded wallet. Please try again later."},UNVERIFIED_DOMAIN:{shortMessage:"Invalid App Configuration",longMessage:()=>"There was an issue loading the embedded wallet. Please verify that your domain is allowed at cloud.reown.com"},JWT_TOKEN_NOT_VALID:{shortMessage:"Session Expired",longMessage:"Invalid session found on UniversalProvider - please check your time settings and connect again"},INVALID_PROJECT_ID:{shortMessage:"Invalid App Configuration",longMessage:"Invalid Project ID - update configuration"},PROJECT_ID_NOT_CONFIGURED:{shortMessage:"Project ID Not Configured",longMessage:"Project ID Not Configured - update configuration on cloud.reown.com"}}};function uI(){return typeof window<"u"}const hI={createLogger(t,e="error"){const s=ji({level:e}),{logger:r}=fu({opts:s});return r.error=(...i)=>{for(const n of i)if(n instanceof Error){t(n,...i);return}t(void 0,...i)},r}},dI="rpc.walletconnect.org";function Xl(t,e){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",t),s.searchParams.set("projectId",e),s.toString()}const xo=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],Pr={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===dI}catch{s=!1}if(s){const r=new URL(t);return r.searchParams.has("projectId")||r.searchParams.set("projectId",e),r.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:j.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${j.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){const r=t.rpcUrls?.default?.http?.[0];return xo.includes(e)?Xl(e,s):r||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:r}){const i=this.getChainNamespace(t),n=this.getCaipNetworkId(t),o=t.rpcUrls.default.http?.[0],a=this.getDefaultRpcUrl(t,n,s),c=t?.rpcUrls?.chainDefault?.http?.[0]||o,l=r?.[n]?.map(d=>d.url)||[],u=[...l,a],h=[...l];return c&&!h.includes(c)&&h.push(c),{...t,chainNamespace:i,caipNetworkId:n,assets:{imageId:Dn.NetworkImageIds[t.id],imageUrl:e?.[t.id]},rpcUrls:{...t.rpcUrls,default:{http:u},chainDefault:{http:h}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:r}){return t.map(i=>Pr.extendCaipNetwork(i,{customNetworkImageUrls:e,customRpcUrls:r,projectId:s}))},getViemTransport(t,e,s){const r=[];return s?.forEach(i=>{r.push(Qi(i.url,i.config))}),xo.includes(t.caipNetworkId)&&r.push(Qi(Xl(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),t?.rpcUrls?.default?.http?.forEach(i=>{r.push(Qi(i))}),Ha(r)},extendWagmiTransports(t,e,s){if(xo.includes(t.caipNetworkId)){const r=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return Ha([s,Qi(r)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:j.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){const e=W.getActiveCaipNetworkId(),s=g.getAllRequestedCaipNetworks(),r=Array.from(g.state.chains?.keys()||[]),i=e?.split(":")[0],n=i?r.includes(i):!1,o=s?.find(c=>c.caipNetworkId===e);return n&&!o&&e?this.getUnsupportedNetwork(e):o||t||s?.[0]}},Ln={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},pt=Oe({providers:{...Ln},providerIds:{...Ln}}),Te={state:pt,subscribeKey(t,e){return nt(pt,t,e)},subscribe(t){return it(pt,()=>{t(pt)})},subscribeProviders(t){return it(pt.providers,()=>t(pt.providers))},setProvider(t,e){e&&(pt.providers[t]=Xs(e))},getProvider(t){return pt.providers[t]},setProviderId(t,e){e&&(pt.providerIds[t]=e)},getProviderId(t){if(t)return pt.providerIds[t]},reset(){pt.providers={...Ln},pt.providerIds={...Ln}},resetChain(t){pt.providers[t]=void 0,pt.providerIds[t]=void 0}};var Zl={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23657442558.commit-435eab3"};const pI={ACCOUNT_TABS:[{label:"Tokens"},{label:"NFTs"},{label:"Activity"}],SECURE_SITE_ORIGIN:(typeof As<"u"&&typeof Zl<"u"?Zl.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},ga={filterOutDuplicatesByRDNS(t){const e=T.state.enableEIP6963?q.state.connectors:[],s=W.getRecentWallets(),r=e.map(a=>a.info?.rdns).filter(Boolean),i=s.map(a=>a.rdns).filter(Boolean),n=r.concat(i);if(n.includes("io.metamask.mobile")&&X.isMobile()){const a=n.indexOf("io.metamask.mobile");n[a]="io.metamask"}return t.filter(a=>!n.includes(String(a?.rdns)))},filterOutDuplicatesByIds(t){const e=q.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=W.getRecentWallets(),r=e.map(a=>a.explorerId),i=s.map(a=>a.id),n=r.concat(i);return t.filter(a=>!n.includes(a?.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=q.state,{featuredWalletIds:s}=T.state,r=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>(a.info?.rdns&&(o[a.info.rdns]=!0),o),{});return t.map(o=>({...o,installed:!!o.rdns&&!!r[o.rdns??""]})).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(s?.length){const l=s.indexOf(o.id),u=s.indexOf(a.id);if(l!==-1&&u!==-1)return l-u;if(l!==-1)return-1;if(u!==-1)return 1}return 0})},getConnectOrderMethod(t,e){const s=t?.connectMethodsOrder||T.state.features?.connectMethodsOrder,r=e||q.state.connectors;if(s)return s;const{injected:i,announced:n}=Nn.getConnectorsByType(r,V.state.recommended,V.state.featured),o=i.filter(Nn.showConnector),a=n.filter(Nn.showConnector);return o.length||a.length?["wallet","email","social"]:pI.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&V.state.excludedWallets.some(r=>r.rdns===t.rdns),s=!!t.name&&V.state.excludedWallets.some(r=>Ua.isLowerCaseMatch(r.name,t.name));return e||s}},Nn={getConnectorsByType(t,e,s){const{customWallets:r}=T.state,i=W.getRecentWallets(),n=ga.filterOutDuplicateWallets(e),o=ga.filterOutDuplicateWallets(s),a=t.filter(h=>h.type==="MULTI_CHAIN"),c=t.filter(h=>h.type==="ANNOUNCED"),l=t.filter(h=>h.type==="INJECTED"),u=t.filter(h=>h.type==="EXTERNAL");return{custom:r,recent:i,external:u,multiChain:a,announced:c,injected:l,recommended:n,featured:o}},showConnector(t){const e=t.info?.rdns,s=!!e&&V.state.excludedWallets.some(i=>!!i.rdns&&i.rdns===e),r=!!t.name&&V.state.excludedWallets.some(i=>Ua.isLowerCaseMatch(i.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!X.isMobile()||X.isMobile()&&!e&&!Y.checkInstalled())||s||r)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||r))},getIsConnectedWithWC(){return Array.from(g.state.chains.values()).some(s=>q.getConnectorId(s.namespace)===j.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:r,announced:i,injected:n,multiChain:o,external:a,overriddenConnectors:c=T.state.features?.connectorTypeOrder??[]}){const l=Nn.getIsConnectedWithWC(),d=[{type:"walletConnect",isEnabled:T.state.enableWalletConnect&&!l},{type:"recent",isEnabled:r.length>0},{type:"injected",isEnabled:[...n,...i,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(f=>f.isEnabled),p=new Set(d.map(f=>f.type)),w=c.filter(f=>p.has(f)).map(f=>({type:f,isEnabled:!0})),m=d.filter(({type:f})=>!w.some(({type:b})=>b===f));return Array.from(new Set([...w,...m].map(({type:f})=>f)))}};/**
14
+ Approved: ${d.toString()}`))}),o.forEach(h=>{r||(Ks(i[h].methods,n[h].methods)?Ks(i[h].events,n[h].events)||(r=R("NON_CONFORMING_NAMESPACES",`${s} namespaces events don't satisfy namespace events for ${h}`)):r=R("NON_CONFORMING_NAMESPACES",`${s} namespaces methods don't satisfy namespace methods for ${h}`))}),r}function fb(t){const e={};return Object.keys(t).forEach(s=>{var r;s.includes(":")?e[s]=t[s]:(r=t[s].chains)==null||r.forEach(i=>{e[i]={methods:t[s].methods,events:t[s].events}})}),e}function cl(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function gb(t){const e={};return Object.keys(t).forEach(s=>{s.includes(":")?e[s]=t[s]:ri(t[s].accounts)?.forEach(i=>{e[i]={accounts:t[s].accounts.filter(n=>n.includes(`${i}:`)),methods:t[s].methods,events:t[s].events}})}),e}function mb(t,e){return ka(t)&&t<=e.max&&t>=e.min}function ll(){const t=Wi();return new Promise(e=>{switch(t){case Nt.browser:e(wb());break;case Nt.reactNative:e(yb());break;case Nt.node:e(bb());break;default:e(!0)}})}function wb(){return ei()&&navigator?.onLine}async function yb(){return Rs()&&typeof Q<"u"&&Q!=null&&Q.NetInfo?(await(Q==null?void 0:Q.NetInfo.fetch()))?.isConnected:!0}function bb(){return!0}function vb(t){switch(Wi()){case Nt.browser:Eb(t);break;case Nt.reactNative:Cb(t);break}}function Eb(t){!Rs()&&ei()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function Cb(t){Rs()&&typeof Q<"u"&&Q!=null&&Q.NetInfo&&Q?.NetInfo.addEventListener(e=>t(e?.isConnected))}function Ib(){var t;return ei()&&Br()?((t=Br())==null?void 0:t.visibilityState)==="visible":!0}const Eo={};class ci{static get(e){return Eo[e]}static set(e,s){Eo[e]=s}static delete(e){delete Eo[e]}}var Nb={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23658354807.commit-e695ac8"};const Bh="wc",jh=2,Un="core",ts=`${Bh}@2:${Un}:`,_b={name:Un,logger:"error"},Ab={database:":memory:"},Sb="crypto",ul="client_ed25519_seed",Pb=D.ONE_DAY,Ob="keychain",Tb="0.3",kb="messages",xb="0.3",hl=D.SIX_HOURS,$b="publisher",qh="irn",Rb="error",Fh="wss://relay.walletconnect.org",Ub="relayer",Ve={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},Db="_subscription",Tt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Lb=.1,ta="2.21.0",Pe={link_mode:"link_mode",relay:"relay"},Cn={inbound:"inbound",outbound:"outbound"},Mb="0.3",Bb="WALLETCONNECT_CLIENT_ID",dl="WALLETCONNECT_LINK_MODE_APPS",vt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},jb="subscription",qb="0.3",Fb="pairing",Wb="0.3",li={wc_pairingDelete:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:D.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:D.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:D.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:D.ONE_DAY,prompt:!1,tag:0},res:{ttl:D.ONE_DAY,prompt:!1,tag:0}}},Hs={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Lt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Hb="history",zb="0.3",Vb="expirer",$t={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Kb="0.3",Gb="verify-api",Jb="https://verify.walletconnect.com",Wh="https://verify.walletconnect.org",Ai=Wh,Yb=`${Ai}/v3`,Xb=[Jb,Wh],Zb="echo",Qb="https://echo.walletconnect.com",Jt={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},ls={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Mt={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Ls={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},Ms={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},ui={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},ev=.1,tv="event-client",sv=86400,rv="https://pulse.walletconnect.org/batch";function iv(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),r=0;r<s.length;r++)s[r]=255;for(var i=0;i<t.length;i++){var n=t.charAt(i),o=n.charCodeAt(0);if(s[o]!==255)throw new TypeError(n+" is ambiguous");s[o]=i}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var m=0,f=0,y=0,b=w.length;y!==b&&w[y]===0;)y++,m++;for(var v=(b-y)*u+1>>>0,C=new Uint8Array(v);y!==b;){for(var S=w[y],_=0,A=v-1;(S!==0||_<f)&&A!==-1;A--,_++)S+=256*C[A]>>>0,C[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");f=_,y++}for(var U=v-f;U!==v&&C[U]===0;)U++;for(var E=c.repeat(m);U<v;++U)E+=t.charAt(C[U]);return E}function d(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var m=0;if(w[m]!==" "){for(var f=0,y=0;w[m]===c;)f++,m++;for(var b=(w.length-m)*l+1>>>0,v=new Uint8Array(b);w[m];){var C=s[w.charCodeAt(m)];if(C===255)return;for(var S=0,_=b-1;(C!==0||S<y)&&_!==-1;_--,S++)C+=a*v[_]>>>0,v[_]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");y=S,m++}if(w[m]!==" "){for(var A=b-y;A!==b&&v[A]===0;)A++;for(var U=new Uint8Array(f+(b-A)),E=f;A!==b;)U[E++]=v[A++];return U}}}function p(w){var m=d(w);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var nv=iv,ov=nv;const Hh=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},av=t=>new TextEncoder().encode(t),cv=t=>new TextDecoder().decode(t);class lv{constructor(e,s,r){this.name=e,this.prefix=s,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class uv{constructor(e,s,r){if(this.name=e,this.prefix=s,s.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return zh(this,e)}}class hv{constructor(e){this.decoders=e}or(e){return zh(this,e)}decode(e){const s=e[0],r=this.decoders[s];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const zh=(t,e)=>new hv({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class dv{constructor(e,s,r,i){this.name=e,this.prefix=s,this.baseEncode=r,this.baseDecode=i,this.encoder=new lv(e,s,r),this.decoder=new uv(e,s,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Yn=({name:t,prefix:e,encode:s,decode:r})=>new dv(t,e,s,r),Ji=({prefix:t,name:e,alphabet:s})=>{const{encode:r,decode:i}=ov(s,e);return Yn({prefix:t,name:e,encode:r,decode:n=>Hh(i(n))})},pv=(t,e,s,r)=>{const i={};for(let u=0;u<e.length;++u)i[e[u]]=u;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*s/8|0);let a=0,c=0,l=0;for(let u=0;u<n;++u){const h=i[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<s|h,a+=s,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=s||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},fv=(t,e,s)=>{const r=e[e.length-1]==="=",i=(1<<s)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>s;)o-=s,n+=e[i&a>>o];if(o&&(n+=e[i&a<<s-o]),r)for(;n.length*s&7;)n+="=";return n},et=({name:t,prefix:e,bitsPerChar:s,alphabet:r})=>Yn({prefix:e,name:t,encode(i){return fv(i,r,s)},decode(i){return pv(i,r,s,t)}}),gv=Yn({prefix:"\0",name:"identity",encode:t=>cv(t),decode:t=>av(t)});var mv=Object.freeze({__proto__:null,identity:gv});const wv=et({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var yv=Object.freeze({__proto__:null,base2:wv});const bv=et({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vv=Object.freeze({__proto__:null,base8:bv});const Ev=Ji({prefix:"9",name:"base10",alphabet:"0123456789"});var Cv=Object.freeze({__proto__:null,base10:Ev});const Iv=et({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Nv=et({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var _v=Object.freeze({__proto__:null,base16:Iv,base16upper:Nv});const Av=et({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sv=et({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Pv=et({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ov=et({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Tv=et({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kv=et({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xv=et({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$v=et({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Rv=et({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Uv=Object.freeze({__proto__:null,base32:Av,base32upper:Sv,base32pad:Pv,base32padupper:Ov,base32hex:Tv,base32hexupper:kv,base32hexpad:xv,base32hexpadupper:$v,base32z:Rv});const Dv=Ji({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Lv=Ji({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Mv=Object.freeze({__proto__:null,base36:Dv,base36upper:Lv});const Bv=Ji({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jv=Ji({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var qv=Object.freeze({__proto__:null,base58btc:Bv,base58flickr:jv});const Fv=et({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Wv=et({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Hv=et({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zv=et({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Vv=Object.freeze({__proto__:null,base64:Fv,base64pad:Wv,base64url:Hv,base64urlpad:zv});const Vh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Kv=Vh.reduce((t,e,s)=>(t[s]=e,t),[]),Gv=Vh.reduce((t,e,s)=>(t[e.codePointAt(0)]=s,t),[]);function Jv(t){return t.reduce((e,s)=>(e+=Kv[s],e),"")}function Yv(t){const e=[];for(const s of t){const r=Gv[s.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${s}`);e.push(r)}return new Uint8Array(e)}const Xv=Yn({prefix:"🚀",name:"base256emoji",encode:Jv,decode:Yv});var Zv=Object.freeze({__proto__:null,base256emoji:Xv}),Qv=Kh,pl=128,e0=127,t0=~e0,s0=Math.pow(2,31);function Kh(t,e,s){e=e||[],s=s||0;for(var r=s;t>=s0;)e[s++]=t&255|pl,t/=128;for(;t&t0;)e[s++]=t&255|pl,t>>>=7;return e[s]=t|0,Kh.bytes=s-r+1,e}var r0=sa,i0=128,fl=127;function sa(t,r){var s=0,r=r||0,i=0,n=r,o,a=t.length;do{if(n>=a)throw sa.bytes=0,new RangeError("Could not decode varint");o=t[n++],s+=i<28?(o&fl)<<i:(o&fl)*Math.pow(2,i),i+=7}while(o>=i0);return sa.bytes=n-r,s}var n0=Math.pow(2,7),o0=Math.pow(2,14),a0=Math.pow(2,21),c0=Math.pow(2,28),l0=Math.pow(2,35),u0=Math.pow(2,42),h0=Math.pow(2,49),d0=Math.pow(2,56),p0=Math.pow(2,63),f0=function(t){return t<n0?1:t<o0?2:t<a0?3:t<c0?4:t<l0?5:t<u0?6:t<h0?7:t<d0?8:t<p0?9:10},g0={encode:Qv,decode:r0,encodingLength:f0},Gh=g0;const gl=(t,e,s=0)=>(Gh.encode(t,e,s),e),ml=t=>Gh.encodingLength(t),ra=(t,e)=>{const s=e.byteLength,r=ml(t),i=r+ml(s),n=new Uint8Array(i+s);return gl(t,n,0),gl(s,n,r),n.set(e,i),new m0(t,s,e,n)};class m0{constructor(e,s,r,i){this.code=e,this.size=s,this.digest=r,this.bytes=i}}const Jh=({name:t,code:e,encode:s})=>new w0(t,e,s);class w0{constructor(e,s,r){this.name=e,this.code=s,this.encode=r}digest(e){if(e instanceof Uint8Array){const s=this.encode(e);return s instanceof Uint8Array?ra(this.code,s):s.then(r=>ra(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Yh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),y0=Jh({name:"sha2-256",code:18,encode:Yh("SHA-256")}),b0=Jh({name:"sha2-512",code:19,encode:Yh("SHA-512")});var v0=Object.freeze({__proto__:null,sha256:y0,sha512:b0});const Xh=0,E0="identity",Zh=Hh,C0=t=>ra(Xh,Zh(t)),I0={code:Xh,name:E0,encode:Zh,digest:C0};var N0=Object.freeze({__proto__:null,identity:I0});new TextEncoder,new TextDecoder;const wl={...mv,...yv,...vv,...Cv,..._v,...Uv,...Mv,...qv,...Vv,...Zv};({...v0,...N0});function _0(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Qh(t,e,s,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:s},decoder:{decode:r}}}const yl=Qh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Co=Qh("ascii","a",t=>{let e="a";for(let s=0;s<t.length;s++)e+=String.fromCharCode(t[s]);return e},t=>{t=t.substring(1);const e=_0(t.length);for(let s=0;s<t.length;s++)e[s]=t.charCodeAt(s);return e}),A0={utf8:yl,"utf-8":yl,hex:wl.base16,latin1:Co,ascii:Co,binary:Co,...wl};function S0(t,e="utf8"){const s=A0[e];if(!s)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t,"utf8"):s.decoder.decode(`${s.prefix}${t}`)}var P0=Object.defineProperty,O0=(t,e,s)=>e in t?P0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Kt=(t,e,s)=>O0(t,typeof e!="symbol"?e+"":e,s);class T0{constructor(e,s){this.core=e,this.logger=s,Kt(this,"keychain",new Map),Kt(this,"name",Ob),Kt(this,"version",Tb),Kt(this,"initialized",!1),Kt(this,"storagePrefix",ts),Kt(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Kt(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Kt(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),Kt(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:n}=R("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(n)}return i}),Kt(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=ct(s,this.name)}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Wo(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ho(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var k0=Object.defineProperty,x0=(t,e,s)=>e in t?k0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ze=(t,e,s)=>x0(t,typeof e!="symbol"?e+"":e,s);class $0{constructor(e,s,r){this.core=e,this.logger=s,Ze(this,"name",Sb),Ze(this,"keychain"),Ze(this,"randomSessionIdentifier",ea()),Ze(this,"initialized",!1),Ze(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ze(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Ze(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),n=Fa(i);return Dd(n.publicKey)}),Ze(this,"generateKeyPair",()=>{this.isInitialized();const i=Ey();return this.setPrivateKey(i.publicKey,i.privateKey)}),Ze(this,"signJWT",async i=>{this.isInitialized();const n=await this.getClientSeed(),o=Fa(n),a=this.randomSessionIdentifier;return await Ld(a,i,Pb,o)}),Ze(this,"generateSharedKey",(i,n,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=Cy(a,n);return this.setSymKey(c,o)}),Ze(this,"setSymKey",async(i,n)=>{this.isInitialized();const o=n||En(i);return await this.keychain.set(o,i),o}),Ze(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ze(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ze(this,"encode",async(i,n,o)=>{this.isInitialized();const a=Dh(o),c=wa(n);if(Zc(a))return _y(c,o?.encoding);if(Xc(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(d,p)}const l=this.getSymKey(i),{type:u,senderPublicKey:h}=a;return Iy({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o?.encoding})}),Ze(this,"decode",async(i,n,o)=>{this.isInitialized();const a=Sy(n,o);if(Zc(a)){const c=Ay(n,o?.encoding);return Pn(c)}if(Xc(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;i=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(i),l=Ny({symKey:c,encoded:n,encoding:o?.encoding});return Pn(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ze(this,"getPayloadType",(i,n=Wt)=>{const o=Di({encoded:i,encoding:n});return tr(o.type)}),Ze(this,"getPayloadSenderPublicKey",(i,n=Wt)=>{const o=Di({encoded:i,encoding:n});return o.senderPublicKey?wt(o.senderPublicKey,at):void 0}),this.core=e,this.logger=ct(s,this.name),this.keychain=r||new T0(this.core,this.logger)}get context(){return At(this.logger)}async setPrivateKey(e,s){return await this.keychain.set(e,s),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(ul)}catch{e=ea(),await this.keychain.set(ul,e)}return S0(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var R0=Object.defineProperty,U0=Object.defineProperties,D0=Object.getOwnPropertyDescriptors,bl=Object.getOwnPropertySymbols,L0=Object.prototype.hasOwnProperty,M0=Object.prototype.propertyIsEnumerable,ia=(t,e,s)=>e in t?R0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,B0=(t,e)=>{for(var s in e||(e={}))L0.call(e,s)&&ia(t,s,e[s]);if(bl)for(var s of bl(e))M0.call(e,s)&&ia(t,s,e[s]);return t},j0=(t,e)=>U0(t,D0(e)),bt=(t,e,s)=>ia(t,typeof e!="symbol"?e+"":e,s);class q0 extends Rf{constructor(e,s){super(e,s),this.logger=e,this.core=s,bt(this,"messages",new Map),bt(this,"messagesWithoutClientAck",new Map),bt(this,"name",kb),bt(this,"version",xb),bt(this,"initialized",!1),bt(this,"storagePrefix",ts),bt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),bt(this,"set",async(r,i,n)=>{this.isInitialized();const o=Zt(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),n===Cn.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,j0(B0({},c),{[o]:i}))}return await this.persist(),o}),bt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),bt(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const n of r){const o=this.messagesWithoutClientAck.get(n)||{};i[n]=Object.values(o)}return i}),bt(this,"has",(r,i)=>{this.isInitialized();const n=this.get(r),o=Zt(i);return typeof n[o]<"u"}),bt(this,"ack",async(r,i)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(r);if(typeof n>"u")return;const o=Zt(i);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,n),await this.persist()}),bt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=ct(e,this.name),this.core=s}get context(){return At(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,Wo(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Wo(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ho(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Ho(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var F0=Object.defineProperty,W0=Object.defineProperties,H0=Object.getOwnPropertyDescriptors,vl=Object.getOwnPropertySymbols,z0=Object.prototype.hasOwnProperty,V0=Object.prototype.propertyIsEnumerable,na=(t,e,s)=>e in t?F0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ln=(t,e)=>{for(var s in e||(e={}))z0.call(e,s)&&na(t,s,e[s]);if(vl)for(var s of vl(e))V0.call(e,s)&&na(t,s,e[s]);return t},Io=(t,e)=>W0(t,H0(e)),Bt=(t,e,s)=>na(t,typeof e!="symbol"?e+"":e,s);class K0 extends Uf{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Bt(this,"events",new $s.EventEmitter),Bt(this,"name",$b),Bt(this,"queue",new Map),Bt(this,"publishTimeout",D.toMiliseconds(D.ONE_MINUTE)),Bt(this,"initialPublishTimeout",D.toMiliseconds(D.ONE_SECOND*15)),Bt(this,"needsTransportRestart",!1),Bt(this,"publish",async(r,i,n)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:n}});const a=n?.ttl||hl,c=$n(n),l=n?.prompt||!1,u=n?.tag||0,h=n?.id||Tr().toString(),d={topic:r,message:i,opts:{ttl:a,relay:c,prompt:l,tag:u,id:h,attestation:n?.attestation,tvf:n?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${u}`;try{const w=new Promise(async m=>{const f=({id:b})=>{d.opts.id===b&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(Ve.publish,f),m(d))};this.relayer.events.on(Ve.publish,f);const y=_s(new Promise((b,v)=>{this.rpcPublish({topic:r,message:i,ttl:a,prompt:l,tag:u,id:h,attestation:n?.attestation,tvf:n?.tvf}).then(b).catch(C=>{this.logger.warn(C,C?.message),v(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${u}`);try{await y,this.events.removeListener(Ve.publish,f)}catch(b){this.queue.set(h,Io(ln({},d),{attempt:1})),this.logger.warn(b,b?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:r,message:i,opts:n}}),await _s(w,this.publishTimeout,p)}catch(w){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(w),(o=n?.internal)!=null&&o.throwOnFailedPublish)throw w}finally{this.queue.delete(h)}}),Bt(this,"on",(r,i)=>{this.events.on(r,i)}),Bt(this,"once",(r,i)=>{this.events.once(r,i)}),Bt(this,"off",(r,i)=>{this.events.off(r,i)}),Bt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=ct(s,this.name),this.registerEventListeners()}get context(){return At(this.logger)}async rpcPublish(e){var s,r,i,n;const{topic:o,message:a,ttl:c=hl,prompt:l,tag:u,id:h,attestation:d,tvf:p}=e,w={method:wi($n().protocol).publish,params:ln({topic:o,message:a,ttl:c,prompt:l,tag:u,attestation:d},p),id:h};rt((s=w.params)==null?void 0:s.prompt)&&((r=w.params)==null||delete r.prompt),rt((i=w.params)==null?void 0:i.tag)&&((n=w.params)==null||delete n.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:w});const m=await this.relayer.request(w);return this.relayer.events.emit(Ve.publish,e),this.logger.debug("Successfully Published Payload"),m}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,s)=>{const r=e.attempt+1;this.queue.set(s,Io(ln({},e),{attempt:r}));const{topic:i,message:n,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${r}`),await this.rpcPublish(Io(ln({},e),{topic:i,message:n,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Xr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ve.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ve.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var G0=Object.defineProperty,J0=(t,e,s)=>e in t?G0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pr=(t,e,s)=>J0(t,typeof e!="symbol"?e+"":e,s);class Y0{constructor(){pr(this,"map",new Map),pr(this,"set",(e,s)=>{const r=this.get(e);this.exists(e,s)||this.map.set(e,[...r,s])}),pr(this,"get",e=>this.map.get(e)||[]),pr(this,"exists",(e,s)=>this.get(e).includes(s)),pr(this,"delete",(e,s)=>{if(typeof s>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,s))return;const i=r.filter(n=>n!==s);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),pr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var X0=Object.defineProperty,Z0=Object.defineProperties,Q0=Object.getOwnPropertyDescriptors,El=Object.getOwnPropertySymbols,eE=Object.prototype.hasOwnProperty,tE=Object.prototype.propertyIsEnumerable,oa=(t,e,s)=>e in t?X0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,hi=(t,e)=>{for(var s in e||(e={}))eE.call(e,s)&&oa(t,s,e[s]);if(El)for(var s of El(e))tE.call(e,s)&&oa(t,s,e[s]);return t},No=(t,e)=>Z0(t,Q0(e)),Ee=(t,e,s)=>oa(t,typeof e!="symbol"?e+"":e,s);class sE extends Mf{constructor(e,s){super(e,s),this.relayer=e,this.logger=s,Ee(this,"subscriptions",new Map),Ee(this,"topicMap",new Y0),Ee(this,"events",new $s.EventEmitter),Ee(this,"name",jb),Ee(this,"version",qb),Ee(this,"pending",new Map),Ee(this,"cached",[]),Ee(this,"initialized",!1),Ee(this,"storagePrefix",ts),Ee(this,"subscribeTimeout",D.toMiliseconds(D.ONE_MINUTE)),Ee(this,"initialSubscribeTimeout",D.toMiliseconds(D.ONE_SECOND*15)),Ee(this,"clientId"),Ee(this,"batchSubscribeTopicsLimit",500),Ee(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),Ee(this,"subscribe",async(r,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const n=$n(i),o={topic:r,relay:n,transportType:i?.transportType};this.pending.set(r,o);const a=await this.rpcSubscribe(r,n,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),a}catch(n){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(n),n}}),Ee(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),Ee(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),Ee(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(n=>n.topic===r))})),Ee(this,"on",(r,i)=>{this.events.on(r,i)}),Ee(this,"once",(r,i)=>{this.events.once(r,i)}),Ee(this,"off",(r,i)=>{this.events.off(r,i)}),Ee(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),Ee(this,"start",async()=>{await this.onConnect()}),Ee(this,"stop",async()=>{await this.onDisconnect()}),Ee(this,"restart",async()=>{await this.restore(),await this.onRestart()}),Ee(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),Ee(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Xr.pulse,async()=>{await this.checkPending()}),this.events.on(vt.created,async r=>{const i=vt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(vt.deleted,async r=>{const i=vt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=ct(s,this.name),this.clientId=""}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,s){let r=!1;try{r=this.getSubscription(e).topic===s}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,s){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,s)))}async unsubscribeById(e,s,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:r}});try{const i=$n(r);await this.restartToComplete({topic:e,id:s,relay:i}),await this.rpcUnsubscribe(e,s,i);const n=ye("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,s,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:s,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,s,r){var i;(!r||r?.transportType===Pe.relay)&&await this.restartToComplete({topic:e,id:e,relay:s});const n={method:wi(s.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});const o=(i=r?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(r?.transportType===Pe.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(n).catch(u=>this.logger.warn(u))},D.toMiliseconds(D.ONE_SECOND)),a;const c=new Promise(async u=>{const h=d=>{d.topic===e&&(this.events.removeListener(vt.created,h),u(d.id))};this.events.on(vt.created,h);try{const d=await _s(new Promise((p,w)=>{this.relayer.request(n).catch(m=>{this.logger.warn(m,m?.message),w(m)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(vt.created,h),u(d)}catch{}}),l=await _s(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return l?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ve.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const s=e[0].relay,r={method:wi(s.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await _s(new Promise(i=>{this.relayer.request(r).catch(n=>this.logger.warn(n)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Ve.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const s=e[0].relay,r={method:wi(s.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await _s(new Promise((n,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Ve.connection_stalled)}return i}rpcUnsubscribe(e,s,r){const i={method:wi(r.protocol).unsubscribe,params:{topic:e,id:s}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,s){this.setSubscription(e,No(hi({},s),{id:e})),this.pending.delete(s.topic)}onBatchSubscribe(e){e.length&&e.forEach(s=>{this.setSubscription(s.id,hi({},s)),this.pending.delete(s.topic)})}async onUnsubscribe(e,s,r){this.events.removeAllListeners(s),this.hasSubscription(s,e)&&this.deleteSubscription(s,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,s){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:s}),this.addSubscription(e,s)}addSubscription(e,s){this.subscriptions.set(e,hi({},s)),this.topicMap.set(s.topic,e),this.events.emit(vt.created,s)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const s=this.subscriptions.get(e);if(!s){const{message:r}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return s}deleteSubscription(e,s){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:s});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(vt.deleted,No(hi({},r),{reason:s}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(vt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],s=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<s;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(vt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:s}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async s=>No(hi({},s),{id:await this.getSubscriptionId(s.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const s=await this.rpcBatchFetchMessages(e);s&&s.messages&&(await cm(D.toMiliseconds(D.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(s.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=R("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 Zt(e+await this.getClientId())}}var rE=Object.defineProperty,Cl=Object.getOwnPropertySymbols,iE=Object.prototype.hasOwnProperty,nE=Object.prototype.propertyIsEnumerable,aa=(t,e,s)=>e in t?rE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Il=(t,e)=>{for(var s in e||(e={}))iE.call(e,s)&&aa(t,s,e[s]);if(Cl)for(var s of Cl(e))nE.call(e,s)&&aa(t,s,e[s]);return t},ue=(t,e,s)=>aa(t,typeof e!="symbol"?e+"":e,s);class oE extends Df{constructor(e){super(e),ue(this,"protocol","wc"),ue(this,"version",2),ue(this,"core"),ue(this,"logger"),ue(this,"events",new $s.EventEmitter),ue(this,"provider"),ue(this,"messages"),ue(this,"subscriber"),ue(this,"publisher"),ue(this,"name",Ub),ue(this,"transportExplicitlyClosed",!1),ue(this,"initialized",!1),ue(this,"connectionAttemptInProgress",!1),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"packageName"),ue(this,"bundleId"),ue(this,"hasExperiencedNetworkDisruption",!1),ue(this,"pingTimeout"),ue(this,"heartBeatTimeout",D.toMiliseconds(D.THIRTY_SECONDS+D.FIVE_SECONDS)),ue(this,"reconnectTimeout"),ue(this,"connectPromise"),ue(this,"reconnectInProgress",!1),ue(this,"requestsInFlight",[]),ue(this,"connectTimeout",D.toMiliseconds(D.ONE_SECOND*15)),ue(this,"request",async s=>{var r,i;this.logger.debug("Publishing Request Payload");const n=s.id||Tr().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:s.method,topic:(r=s.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${n}:${((i=s.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(s);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),ue(this,"resetPingTimeout",()=>{kn()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var s,r,i,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(i=(r=(s=this.provider)==null?void 0:s.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||n.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),ue(this,"onPayloadHandler",s=>{this.onProviderPayload(s),this.resetPingTimeout()}),ue(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(Ve.connect)}),ue(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ue(this,"onProviderErrorHandler",s=>{this.logger.fatal(`Fatal socket error: ${s.message}`),this.events.emit(Ve.error,s),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ue(this,"registerProviderListeners",()=>{this.provider.on(Tt.payload,this.onPayloadHandler),this.provider.on(Tt.connect,this.onConnectHandler),this.provider.on(Tt.disconnect,this.onDisconnectHandler),this.provider.on(Tt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?ct(e.logger,this.name):ya(ji({level:e.logger||Rb})),this.messages=new q0(this.logger,e.core),this.subscriber=new sE(this,this.logger),this.publisher=new K0(this,this.logger),this.relayUrl=e?.relayUrl||Fh,this.projectId=e.projectId,Vg()?this.packageName=Ec():Kg()&&(this.bundleId=Ec()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return At(this.logger)}get connected(){var e,s,r;return((r=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,s,r;return((r=(s=(e=this.provider)==null?void 0:e.connection)==null?void 0:s.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,s,r){this.isInitialized(),await this.publisher.publish(e,s,r),await this.recordMessageEvent({topic:e,message:s,publishedAt:Date.now(),transportType:Pe.relay},Cn.outbound)}async subscribe(e,s){var r,i,n;this.isInitialized(),(!(s!=null&&s.transportType)||s?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=s?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=s?.internal)==null?void 0:i.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(vt.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(vt.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,Il({internal:{throwOnFailedPublish:o}},s)).catch(d=>{o&&h(d)})||a,u()})]),a}async unsubscribe(e,s){this.isInitialized(),await this.subscriber.unsubscribe(e,s)}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}off(e,s){this.events.off(e,s)}removeListener(e,s){this.events.removeListener(e,s)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await _s(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.warn("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(s,r)=>{await this.connect(e).then(s).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await ll())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const s=e.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${s.length} message events sorted`);for(const r of s)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${s.length} message events processed`)}async onLinkMessageEvent(e,s){const{topic:r}=e;if(!s.sessionExists){const i=Be(D.FIVE_MINUTES),n={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,n)}this.events.emit(Ve.message,e),await this.recordMessageEvent(e,Cn.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let s=1;for(;s<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${s}...`),await this.createProvider(),await new Promise(async(r,i)=>{const n=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Tt.disconnect,n),await _s(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(Tt.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Tt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(Tt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${s}`);break}await new Promise(r=>setTimeout(r,D.toMiliseconds(s*1))),s++}}startPingTimeout(){var e,s,r,i,n;if(kn())try{(s=(e=this.provider)==null?void 0:e.connection)!=null&&s.socket&&((n=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Ut(new Ud(Zg({sdkVersion:ta,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,s){const{topic:r,message:i}=e;await this.messages.set(r,i,s)}async shouldIgnoreMessageEvent(e){const{topic:s,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(s))return this.logger.warn(`Ignoring message for unknown topic ${s}`),!0;const i=this.messages.has(s,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),ba(e)){if(!e.method.endsWith(Db))return;const s=e.params,{topic:r,message:i,publishedAt:n,attestation:o}=s.data,a={topic:r,message:i,publishedAt:n,transportType:Pe.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Il({type:"event",event:s.id},a)),this.events.emit(s.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else va(e)&&this.events.emit(Ve.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Cn.inbound),this.events.emit(Ve.message,e))}async acknowledgePayload(e){const s=Bn(e.id,!0);await this.provider.connection.send(s)}unregisterProviderListeners(){this.provider.off(Tt.payload,this.onPayloadHandler),this.provider.off(Tt.connect,this.onConnectHandler),this.provider.off(Tt.disconnect,this.onDisconnectHandler),this.provider.off(Tt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await ll();vb(async s=>{e!==s&&(e=s,s?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Xr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Ib())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(s){this.logger.warn(s,s?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Ve.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},D.toMiliseconds(Lb)))))}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function aE(){}function Nl(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function _l(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Al(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const cE="[object RegExp]",lE="[object String]",uE="[object Number]",hE="[object Boolean]",Sl="[object Arguments]",dE="[object Symbol]",pE="[object Date]",fE="[object Map]",gE="[object Set]",mE="[object Array]",wE="[object Function]",yE="[object ArrayBuffer]",_o="[object Object]",bE="[object Error]",vE="[object DataView]",EE="[object Uint8Array]",CE="[object Uint8ClampedArray]",IE="[object Uint16Array]",NE="[object Uint32Array]",_E="[object BigUint64Array]",AE="[object Int8Array]",SE="[object Int16Array]",PE="[object Int32Array]",OE="[object BigInt64Array]",TE="[object Float32Array]",kE="[object Float64Array]";function xE(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function $E(t,e,s){return yi(t,e,void 0,void 0,void 0,void 0,s)}function yi(t,e,s,r,i,n,o){const a=o(t,e,s,r,i,n);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Si(t,e,n,o)}return Si(t,e,n,o)}function Si(t,e,s,r){if(Object.is(t,e))return!0;let i=Al(t),n=Al(e);if(i===Sl&&(i=_o),n===Sl&&(n=_o),i!==n)return!1;switch(i){case lE:return t.toString()===e.toString();case uE:{const c=t.valueOf(),l=e.valueOf();return xE(c,l)}case hE:case pE:case dE:return Object.is(t.valueOf(),e.valueOf());case cE:return t.source===e.source&&t.flags===e.flags;case wE:return t===e}s=s??new Map;const o=s.get(t),a=s.get(e);if(o!=null&&a!=null)return o===e;s.set(t,e),s.set(e,t);try{switch(i){case fE:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!yi(l,e.get(c),c,t,e,s,r))return!1;return!0}case gE:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],d=l.findIndex(p=>yi(h,p,void 0,t,e,s,r));if(d===-1)return!1;l.splice(d,1)}return!0}case mE:case EE:case CE:case IE:case NE:case _E:case AE:case SE:case PE:case OE:case TE:case kE:{if(typeof Ye<"u"&&Ye.isBuffer(t)!==Ye.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!yi(t[c],e[c],c,t,e,s,r))return!1;return!0}case yE:return t.byteLength!==e.byteLength?!1:Si(new Uint8Array(t),new Uint8Array(e),s,r);case vE:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Si(new Uint8Array(t),new Uint8Array(e),s,r);case bE:return t.name===e.name&&t.message===e.message;case _o:{if(!(Si(t.constructor,e.constructor,s,r)||Nl(t)&&Nl(e)))return!1;const c=[...Object.keys(t),..._l(t)],l=[...Object.keys(e),..._l(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],d=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!yi(d,p,h,t,e,s,r))return!1}return!0}default:return!1}}finally{s.delete(t),s.delete(e)}}function RE(t,e){return $E(t,e,aE)}var UE=Object.defineProperty,Pl=Object.getOwnPropertySymbols,DE=Object.prototype.hasOwnProperty,LE=Object.prototype.propertyIsEnumerable,ca=(t,e,s)=>e in t?UE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ol=(t,e)=>{for(var s in e||(e={}))DE.call(e,s)&&ca(t,s,e[s]);if(Pl)for(var s of Pl(e))LE.call(e,s)&&ca(t,s,e[s]);return t},dt=(t,e,s)=>ca(t,typeof e!="symbol"?e+"":e,s);class or extends Lf{constructor(e,s,r,i=ts,n=void 0){super(e,s,r,i),this.core=e,this.logger=s,this.name=r,dt(this,"map",new Map),dt(this,"version",Mb),dt(this,"cached",[]),dt(this,"initialized",!1),dt(this,"getKey"),dt(this,"storagePrefix",ts),dt(this,"recentlyDeleted",[]),dt(this,"recentlyDeletedLimit",200),dt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!rt(o)?this.map.set(this.getKey(o),o):Xy(o)?this.map.set(o.id,o):Zy(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),dt(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),dt(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),dt(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>RE(a[c],o[c]))):this.values)),dt(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=Ol(Ol({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),dt(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=ct(s,this.name),this.storagePrefix=i,this.getKey=n}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const s=this.map.get(e);if(!s){if(this.recentlyDeleted.includes(e)){const{message:i}=R("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return s}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:s}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var ME=Object.defineProperty,BE=(t,e,s)=>e in t?ME(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ne=(t,e,s)=>BE(t,typeof e!="symbol"?e+"":e,s);class jE{constructor(e,s){this.core=e,this.logger=s,ne(this,"name",Fb),ne(this,"version",Wb),ne(this,"events",new Ca),ne(this,"pairings"),ne(this,"initialized",!1),ne(this,"storagePrefix",ts),ne(this,"ignoredPayloadTypes",[ps]),ne(this,"registeredMethods",[]),ne(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ne(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),ne(this,"create",async r=>{this.isInitialized();const i=ea(),n=await this.core.crypto.setSymKey(i),o=Be(D.FIVE_MINUTES),a={protocol:qh},c={topic:n,expiry:o,relay:a,active:!1,methods:r?.methods},l=el({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(Hs.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:r?.transportType}),{topic:n,uri:l}}),ne(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[Jt.pairing_started]}});this.isValidPair(r,i);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Qc(r.uri);i.props.properties.topic=n,i.addTrace(Jt.pairing_uri_validation_success),i.addTrace(Jt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(n)){if(u=this.pairings.get(n),i.addTrace(Jt.existing_pairing),u.active)throw i.setError(ls.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);i.addTrace(Jt.pairing_not_expired)}const h=c||Be(D.FIVE_MINUTES),d={topic:n,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(n,h),await this.pairings.set(n,d),i.addTrace(Jt.store_new_pairing),r.activatePairing&&await this.activate({topic:n}),this.events.emit(Hs.create,d),i.addTrace(Jt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),i.addTrace(Jt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(ls.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw i.setError(ls.subscribe_pairing_topic_failure),p}return i.addTrace(Jt.subscribe_pairing_topic_success),d}),ne(this,"activate",async({topic:r})=>{this.isInitialized();const i=Be(D.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),ne(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const n=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=qs();this.events.once(fe("pairing_ping",n),({error:l})=>{l?c(l):a()}),await o()}}),ne(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),ne(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),ne(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ne(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",ye("USER_DISCONNECTED")),await this.deletePairing(i))}),ne(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:n,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return el({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),ne(this,"sendRequest",async(r,i,n)=>{const o=Vs(i,n),a=await this.core.crypto.encode(r,o),c=li[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),ne(this,"sendResult",async(r,i,n)=>{const o=Bn(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=li[c].res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ne(this,"sendError",async(r,i,n)=>{const o=gu(r,n),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,l=li[c]?li[c].res:li.unregistered_method.res;await this.core.relayer.publish(i,a,l),await this.core.history.resolve(o)}),ne(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,ye("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),ne(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>Es(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),ne(this,"onRelayEventRequest",async r=>{const{topic:i,payload:n}=r;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,n);default:return await this.onUnknownRpcMethodRequest(i,n)}}),ne(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n}=r,o=(await this.core.history.get(i,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,n);default:return this.onUnknownRpcMethodResponse(o)}}),ne(this,"onPairingPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult(n,r,!0),this.events.emit(Hs.ping,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),ne(this,"onPairingPingResponse",(r,i)=>{const{id:n}=i;setTimeout(()=>{cs(i)?this.events.emit(fe("pairing_ping",n),{}):Yt(i)&&this.events.emit(fe("pairing_ping",n),{error:i.error})},500)}),ne(this,"onPairingDeleteRequest",async(r,i)=>{const{id:n}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Hs.delete,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),ne(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:n,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=ye("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,r,a),this.logger.error(a)}catch(a){await this.sendError(n,r,a),this.logger.error(a)}}),ne(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(ye("WC_METHOD_UNSUPPORTED",r))}),ne(this,"isValidPair",(r,i)=>{var n;if(!gt(r)){const{message:a}=R("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(ls.malformed_pairing_uri),new Error(a)}if(!Yy(r.uri)){const{message:a}=R("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(ls.malformed_pairing_uri),new Error(a)}const o=Qc(r?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(ls.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=R("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(ls.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&D.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(ls.pairing_expired);const{message:a}=R("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ne(this,"isValidPing",async r=>{if(!gt(r)){const{message:n}=R("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),ne(this,"isValidDisconnect",async r=>{if(!gt(r)){const{message:n}=R("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidPairingTopic(i)}),ne(this,"isValidPairingTopic",async r=>{if(!Ue(r,!1)){const{message:i}=R("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(Es(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=R("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=ct(s,this.name),this.pairings=new or(this.core,this.logger,this.name,this.storagePrefix)}get context(){return At(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ve.message,async e=>{const{topic:s,message:r,transportType:i}=e;if(this.pairings.keys.includes(s)&&i!==Pe.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const n=await this.core.crypto.decode(s,r);ba(n)?(this.core.history.set(s,n),await this.onRelayEventRequest({topic:s,payload:n})):va(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:s,payload:n}),this.core.history.delete(s,n.id)),await this.core.relayer.messages.ack(s,r)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on($t.expired,async e=>{const{topic:s}=rh(e.target);s&&this.pairings.keys.includes(s)&&(await this.deletePairing(s,!0),this.events.emit(Hs.expire,{topic:s}))})}}var qE=Object.defineProperty,FE=(t,e,s)=>e in t?qE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Qe=(t,e,s)=>FE(t,typeof e!="symbol"?e+"":e,s);class WE extends $f{constructor(e,s){super(e,s),this.core=e,this.logger=s,Qe(this,"records",new Map),Qe(this,"events",new $s.EventEmitter),Qe(this,"name",Hb),Qe(this,"version",zb),Qe(this,"cached",[]),Qe(this,"initialized",!1),Qe(this,"storagePrefix",ts),Qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Qe(this,"set",(r,i,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:n}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:n,expiry:Be(D.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Lt.created,o)}),Qe(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=Yt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(Lt.updated,i))}),Qe(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Qe(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(n=>{if(n.topic===r){if(typeof i<"u"&&n.id!==i)return;this.records.delete(n.id),this.events.emit(Lt.deleted,n)}}),this.persist()}),Qe(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Qe(this,"on",(r,i)=>{this.events.on(r,i)}),Qe(this,"once",(r,i)=>{this.events.once(r,i)}),Qe(this,"off",(r,i)=>{this.events.off(r,i)}),Qe(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=ct(s,this.name)}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(s=>{if(typeof s.response<"u")return;const r={topic:s.topic,request:Vs(s.request.method,s.request.params,s.id),chainId:s.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const s=this.records.get(e);if(!s){const{message:r}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return s}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Lt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:s}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Lt.created,e=>{const s=Lt.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Lt.updated,e=>{const s=Lt.updated;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.events.on(Lt.deleted,e=>{const s=Lt.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,record:e})}),this.core.heartbeat.on(Xr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(s=>{D.toMiliseconds(s.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${s.id}`),this.records.delete(s.id),this.events.emit(Lt.deleted,s,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var HE=Object.defineProperty,zE=(t,e,s)=>e in t?HE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,st=(t,e,s)=>zE(t,typeof e!="symbol"?e+"":e,s);class VE extends Bf{constructor(e,s){super(e,s),this.core=e,this.logger=s,st(this,"expirations",new Map),st(this,"events",new $s.EventEmitter),st(this,"name",Vb),st(this,"version",Kb),st(this,"cached",[]),st(this,"initialized",!1),st(this,"storagePrefix",ts),st(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),st(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),st(this,"set",(r,i)=>{this.isInitialized();const n=this.formatTarget(r),o={target:n,expiry:i};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit($t.created,{target:n,expiration:o})}),st(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),st(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),n=this.getExpiration(i);this.expirations.delete(i),this.events.emit($t.deleted,{target:i,expiration:n})}}),st(this,"on",(r,i)=>{this.events.on(r,i)}),st(this,"once",(r,i)=>{this.events.once(r,i)}),st(this,"off",(r,i)=>{this.events.off(r,i)}),st(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=ct(s,this.name)}get context(){return At(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Qg(e);if(typeof e=="number")return em(e);const{message:s}=R("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(s)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit($t.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:s}=R("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(s),new Error(s)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const s=this.expirations.get(e);if(!s){const{message:r}=R("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return s}checkExpiry(e,s){const{expiry:r}=s;D.toMiliseconds(r)-Date.now()<=0&&this.expire(e,s)}expire(e,s){this.expirations.delete(e),this.events.emit($t.expired,{target:e,expiration:s})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,s)=>this.checkExpiry(s,e))}registerEventListeners(){this.core.heartbeat.on(Xr.pulse,()=>this.checkExpirations()),this.events.on($t.created,e=>{const s=$t.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on($t.expired,e=>{const s=$t.expired;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()}),this.events.on($t.deleted,e=>{const s=$t.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}}var KE=Object.defineProperty,GE=(t,e,s)=>e in t?KE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Re=(t,e,s)=>GE(t,typeof e!="symbol"?e+"":e,s);class JE extends jf{constructor(e,s,r){super(e,s,r),this.core=e,this.logger=s,this.store=r,Re(this,"name",Gb),Re(this,"abortController"),Re(this,"isDevEnv"),Re(this,"verifyUrlV3",Yb),Re(this,"storagePrefix",ts),Re(this,"version",jh),Re(this,"publicKey"),Re(this,"fetchPromise"),Re(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&D.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Re(this,"register",async i=>{if(!ei()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const l=Br(),u=this.startAbortTimer(D.ONE_SECOND*5),h=await new Promise((d,p)=>{const w=()=>{window.removeEventListener("message",f),l.body.removeChild(m),p("attestation aborted")};this.abortController.signal.addEventListener("abort",w);const m=l.createElement("iframe");m.src=c,m.style.display="none",m.addEventListener("error",w,{signal:this.abortController.signal});const f=y=>{if(y.data&&typeof y.data=="string")try{const b=JSON.parse(y.data);if(b.type==="verify_attestation"){if(Uo(b.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(m),this.abortController.signal.removeEventListener("abort",w),window.removeEventListener("message",f),d(b.attestation===null?"":b.attestation)}}catch(b){this.logger.warn(b)}};l.body.appendChild(m),window.addEventListener("message",f,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(l){this.logger.warn(l)}return""}),Re(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=i;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(Uo(n).payload.id!==a)return;const l=await this.isValidJwtAttestation(n);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),Re(this,"fetchAttestation",async(i,n)=>{this.logger.debug(`resolving attestation: ${i} from url: ${n}`);const o=this.startAbortTimer(D.ONE_SECOND*5),a=await fetch(`${n}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),Re(this,"getVerifyUrl",i=>{let n=i||Ai;return Xb.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ai}`),n=Ai),n}),Re(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(D.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await n.json()}catch(i){this.logger.warn(i)}}),Re(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Re(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Re(this,"isValidJwtAttestation",async i=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(i,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),Re(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Re(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),Re(this,"validateAttestation",(i,n)=>{const o=Oy(i,n.publicKey),a={hasExpired:D.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=ct(s,this.name),this.abortController=new AbortController,this.isDevEnv=Na(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return At(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),D.toMiliseconds(e))}}var YE=Object.defineProperty,XE=(t,e,s)=>e in t?YE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Tl=(t,e,s)=>XE(t,typeof e!="symbol"?e+"":e,s);class ZE extends qf{constructor(e,s){super(e,s),this.projectId=e,this.logger=s,Tl(this,"context",Zb),Tl(this,"registerDeviceToken",async r=>{const{clientId:i,token:n,notificationType:o,enableEncrypted:a=!1}=r,c=`${Qb}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:n,always_raw:a})})}),this.logger=ct(s,this.context)}}var QE=Object.defineProperty,kl=Object.getOwnPropertySymbols,eC=Object.prototype.hasOwnProperty,tC=Object.prototype.propertyIsEnumerable,la=(t,e,s)=>e in t?QE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,di=(t,e)=>{for(var s in e||(e={}))eC.call(e,s)&&la(t,s,e[s]);if(kl)for(var s of kl(e))tC.call(e,s)&&la(t,s,e[s]);return t},Fe=(t,e,s)=>la(t,typeof e!="symbol"?e+"":e,s);class sC extends Ff{constructor(e,s,r=!0){super(e,s,r),this.core=e,this.logger=s,Fe(this,"context",tv),Fe(this,"storagePrefix",ts),Fe(this,"storageVersion",ev),Fe(this,"events",new Map),Fe(this,"shouldPersist",!1),Fe(this,"init",async()=>{if(!Na())try{const i={eventId:Ic(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:th(this.core.relayer.protocol,this.core.relayer.version,ta)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Fe(this,"createEvent",i=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=i,l=Ic(),u=this.core.projectId||"",h=Date.now(),d=di({eventId:l,timestamp:h,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,d),this.shouldPersist=!0),d}),Fe(this,"getEvent",i=>{const{eventId:n,topic:o}=i;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return di(di({},a),this.setMethods(a.eventId))}),Fe(this,"deleteEvent",i=>{const{eventId:n}=i;this.events.delete(n),this.shouldPersist=!0}),Fe(this,"setEventListeners",()=>{this.core.heartbeat.on(Xr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{D.fromMiliseconds(Date.now())-D.fromMiliseconds(i.timestamp)>sv&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Fe(this,"setMethods",i=>({addTrace:n=>this.addTrace(i,n),setError:n=>this.setError(i,n)})),Fe(this,"addTrace",(i,n)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(n),this.events.set(i,o),this.shouldPersist=!0)}),Fe(this,"setError",(i,n)=>{const o=this.events.get(i);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Fe(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Fe(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(n=>{this.events.set(n.eventId,di(di({},n),this.setMethods(n.eventId)))})}catch(i){this.logger.warn(i)}}),Fe(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[n,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const n of i)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),Fe(this,"sendEvent",async i=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${rv}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${ta}${n}`,{method:"POST",body:JSON.stringify(i)})}),Fe(this,"getAppDomain",()=>eh().url),this.logger=ct(s,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var rC=Object.defineProperty,xl=Object.getOwnPropertySymbols,iC=Object.prototype.hasOwnProperty,nC=Object.prototype.propertyIsEnumerable,ua=(t,e,s)=>e in t?rC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,$l=(t,e)=>{for(var s in e||(e={}))iC.call(e,s)&&ua(t,s,e[s]);if(xl)for(var s of xl(e))nC.call(e,s)&&ua(t,s,e[s]);return t},Ae=(t,e,s)=>ua(t,typeof e!="symbol"?e+"":e,s);let oC=class ed extends Of{constructor(e){var s;super(e),Ae(this,"protocol",Bh),Ae(this,"version",jh),Ae(this,"name",Un),Ae(this,"relayUrl"),Ae(this,"projectId"),Ae(this,"customStoragePrefix"),Ae(this,"events",new $s.EventEmitter),Ae(this,"logger"),Ae(this,"heartbeat"),Ae(this,"relayer"),Ae(this,"crypto"),Ae(this,"storage"),Ae(this,"history"),Ae(this,"expirer"),Ae(this,"pairing"),Ae(this,"verify"),Ae(this,"echoClient"),Ae(this,"linkModeSupportedApps"),Ae(this,"eventClient"),Ae(this,"initialized",!1),Ae(this,"logChunkController"),Ae(this,"on",(a,c)=>this.events.on(a,c)),Ae(this,"once",(a,c)=>this.events.once(a,c)),Ae(this,"off",(a,c)=>this.events.off(a,c)),Ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),Ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:Pe.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Fh,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=ji({level:typeof e?.logger=="string"&&e.logger?e.logger:_b.logger,name:Un}),{logger:n,chunkLoggerController:o}=fu({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(s=this.logChunkController)!=null&&s.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=ct(n,this.name),this.heartbeat=new Rd,this.crypto=new $0(this,this.logger,e?.keychain),this.history=new WE(this,this.logger),this.expirer=new VE(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Af($l($l({},Ab),e?.storageOptions)),this.relayer=new oE({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new jE(this,this.logger),this.verify=new JE(this,this.logger,this.storage),this.echoClient=new ZE(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new sC(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const s=new ed(e);await s.initialize();const r=await s.crypto.getClientId();return await s.storage.setItem(Bb,r),s}get context(){return At(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(dl,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(dl)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const s=`_walletConnectCore_${e}`,r=`${s}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[s]}catch(s){console.warn("Failed to get global WalletConnect core",s);return}}setGlobalCore(e){var s;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((s=e.opts)==null?void 0:s.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof As<"u"&&Nb.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const aC=oC,td="wc",sd=2,rd="client",xa=`${td}@${sd}:${rd}:`,Ao={name:rd,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Rl="WALLETCONNECT_DEEPLINK_CHOICE",cC="proposal",Ul="Proposal expired",lC="session",fr=D.SEVEN_DAYS,uC="engine",We={wc_sessionPropose:{req:{ttl:D.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1104},res:{ttl:D.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1106},res:{ttl:D.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:D.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:D.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1112},res:{ttl:D.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:D.ONE_DAY,prompt:!1,tag:1114},res:{ttl:D.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:D.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:D.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:D.FIVE_MINUTES,prompt:!1,tag:1119}}},So={min:D.FIVE_MINUTES,max:D.SEVEN_DAYS},Gt={idle:"IDLE",active:"ACTIVE"},Dl={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},hC="request",dC=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],pC="wc",fC="auth",gC="authKeys",mC="pairingTopics",wC="requests",Xn=`${pC}@${1.5}:${fC}:`,In=`${Xn}:PUB_KEY`;var yC=Object.defineProperty,bC=Object.defineProperties,vC=Object.getOwnPropertyDescriptors,Ll=Object.getOwnPropertySymbols,EC=Object.prototype.hasOwnProperty,CC=Object.prototype.propertyIsEnumerable,ha=(t,e,s)=>e in t?yC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ce=(t,e)=>{for(var s in e||(e={}))EC.call(e,s)&&ha(t,s,e[s]);if(Ll)for(var s of Ll(e))CC.call(e,s)&&ha(t,s,e[s]);return t},ot=(t,e)=>bC(t,vC(e)),P=(t,e,s)=>ha(t,typeof e!="symbol"?e+"":e,s);class IC extends Vf{constructor(e){super(e),P(this,"name",uC),P(this,"events",new Ca),P(this,"initialized",!1),P(this,"requestQueue",{state:Gt.idle,queue:[]}),P(this,"sessionRequestQueue",{state:Gt.idle,queue:[]}),P(this,"requestQueueDelay",D.ONE_SECOND),P(this,"expectedPairingMethodMap",new Map),P(this,"recentlyDeletedMap",new Map),P(this,"recentlyDeletedLimit",200),P(this,"relayMessageCache",[]),P(this,"pendingSessions",new Map),P(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(We)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},D.toMiliseconds(this.requestQueueDelay)))}),P(this,"connect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=ot(Ce({},s),{requiredNamespaces:s.requiredNamespaces||{},optionalNamespaces:s.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=zy(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l}=r;let u=i,h,d=!1;try{if(u){const _=this.client.core.pairing.pairings.get(u);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),d=_.active}}catch(_){throw this.client.logger.error(`connect() -> pairing.get(${u}) failed`),_}if(!u||!d){const{topic:_,uri:A}=await this.client.core.pairing.create();u=_,h=A}if(!u){const{message:_}=R("NO_MATCHING_KEY",`connect() pairing topic: ${u}`);throw new Error(_)}const p=await this.client.core.crypto.generateKeyPair(),w=We.wc_sessionPropose.req.ttl||D.FIVE_MINUTES,m=Be(w),f=ot(Ce(Ce({requiredNamespaces:n,optionalNamespaces:o,relays:l??[{protocol:qh}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:u},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:fs()}),y=fe("session_connect",f.id),{reject:b,resolve:v,done:C}=qs(w,Ul),S=({id:_})=>{_===f.id&&(this.client.events.off("proposal_expire",S),this.pendingSessions.delete(f.id),this.events.emit(y,{error:{message:Ul,code:0}}))};return this.client.events.on("proposal_expire",S),this.events.once(y,({error:_,session:A})=>{this.client.events.off("proposal_expire",S),_?b(_):A&&v(A)}),await this.sendRequest({topic:u,method:"wc_sessionPropose",params:f,throwOnFailedPublish:!0,clientRpcId:f.id}),await this.setProposal(f.id,f),{uri:h,approval:C}}),P(this,"pair",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(s)}catch(r){throw this.client.logger.error("pair() failed"),r}}),P(this,"approve",async s=>{var r,i,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=s?.id)==null?void 0:r.toString(),trace:[Mt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(E){throw o.setError(Ls.no_internet_connection),E}try{await this.isValidProposalId(s?.id)}catch(E){throw this.client.logger.error(`approve() -> proposal.get(${s?.id}) failed`),o.setError(Ls.proposal_not_found),E}try{await this.isValidApprove(s)}catch(E){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Ls.session_approve_namespace_validation_failure),E}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:d}=s,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:w,proposer:m,requiredNamespaces:f,optionalNamespaces:y}=p;let b=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:w});b||(b=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:Mt.session_approve_started,properties:{topic:w,trace:[Mt.session_approve_started,Mt.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),C=m.publicKey,S=await this.client.core.crypto.generateSharedKey(v,C),_=Ce(Ce(Ce({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:Be(fr)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),A=Pe.relay;b.addTrace(Mt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(S,{transportType:A})}catch(E){throw b.setError(Ls.subscribe_session_topic_failure),E}b.addTrace(Mt.subscribe_session_topic_success);const U=ot(Ce({},_),{topic:S,requiredNamespaces:f,optionalNamespaces:y,pairingTopic:w,acknowledged:!1,self:_.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:v,transportType:Pe.relay});await this.client.session.set(S,U),b.addTrace(Mt.store_session);try{b.addTrace(Mt.publishing_session_settle),await this.sendRequest({topic:S,method:"wc_sessionSettle",params:_,throwOnFailedPublish:!0}).catch(E=>{throw b?.setError(Ls.session_settle_publish_failure),E}),b.addTrace(Mt.session_settle_publish_success),b.addTrace(Mt.publishing_session_approve),await this.sendResult({id:a,topic:w,result:{relay:{protocol:c??"irn"},responderPublicKey:v},throwOnFailedPublish:!0}).catch(E=>{throw b?.setError(Ls.session_approve_publish_failure),E}),b.addTrace(Mt.session_approve_publish_success)}catch(E){throw this.client.logger.error(E),this.client.session.delete(S,ye("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(S),E}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:w,metadata:m.metadata}),await this.client.proposal.delete(a,ye("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:w}),await this.setExpiry(S,Be(fr)),{topic:S,acknowledged:()=>Promise.resolve(this.client.session.get(S))}}),P(this,"reject",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(s)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=s;let n;try{n=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}n&&(await this.sendError({id:r,topic:n,error:i,rpcOpts:We.wc_sessionPropose.reject}),await this.client.proposal.delete(r,ye("USER_DISCONNECTED")))}),P(this,"update",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(s)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:r,namespaces:i}=s,{done:n,resolve:o,reject:a}=qs(),c=fs(),l=Tr().toString(),u=this.client.session.get(r).namespaces;return this.events.once(fe("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(r,{namespaces:u}),a(h)}),{acknowledged:n}}),P(this,"extend",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(s)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=s,i=fs(),{done:n,resolve:o,reject:a}=qs();return this.events.once(fe("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,Be(fr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),P(this,"request",async s=>{this.isInitialized();try{await this.isValidRequest(s)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:i,topic:n,expiry:o=We.wc_sessionRequest.req.ttl}=s,a=this.client.session.get(n);a?.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const c=fs(),l=Tr().toString(),{done:u,resolve:h,reject:d}=qs(o,"Request expired. Please try again.");this.events.once(fe("session_request",c),({error:y,result:b})=>{y?d(y):h(b)});const p="wc_sessionRequest",w=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(w)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:n,method:p,params:{request:ot(Ce({},i),{expiryTimestamp:Be(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:w}).catch(y=>d(y)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),await u();const m={request:ot(Ce({},i),{expiryTimestamp:Be(o)}),chainId:r},f=this.shouldSetTVF(p,m);return await Promise.all([new Promise(async y=>{await this.sendRequest(Ce({clientRpcId:c,relayRpcId:l,topic:n,method:p,params:m,expiry:o,throwOnFailedPublish:!0},f&&{tvf:this.getTVFParams(c,m)})).catch(b=>d(b)),this.client.events.emit("session_request_sent",{topic:n,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const v=await im(this.client.core.storage,Rl);await tm({id:c,topic:n,wcDeepLink:v})}y()}),u()]).then(y=>y[2])}),P(this,"respond",async s=>{this.isInitialized(),await this.isValidRespond(s);const{topic:r,response:i}=s,{id:n}=i,o=this.client.session.get(r);o.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);cs(i)?await this.sendResult({id:n,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:a}):Yt(i)&&await this.sendError({id:n,topic:r,error:i.error,appLink:a}),this.cleanupAfterResponse(s)}),P(this,"ping",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(s)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=s;if(this.client.session.keys.includes(r)){const i=fs(),n=Tr().toString(),{done:o,resolve:a,reject:c}=qs();this.events.once(fe("session_ping",i),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(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:r}))}),P(this,"emit",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(s);const{topic:r,event:i,chainId:n}=s,o=Tr().toString(),a=fs();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),P(this,"disconnect",async s=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(s);const{topic:r}=s;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:ye("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=R("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),P(this,"find",s=>(this.isInitialized(),this.client.session.getAll().filter(r=>Gy(r,s)))),P(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),P(this,"authenticate",async(s,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(s);const n=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=n?Pe.link_mode:Pe.relay;o===Pe.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:d,exp:p,nbf:w,methods:m=[],expiry:f}=s,y=[...s.resources||[]],{topic:b,uri:v}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:v}});const C=await this.client.core.crypto.generateKeyPair(),S=En(C);if(await Promise.all([this.client.auth.authKeys.set(In,{responseTopic:S,publicKey:C}),this.client.auth.pairingTopics.set(S,{topic:S,pairingTopic:b})]),await this.client.core.relayer.subscribe(S,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${b}`),m.length>0){const{namespace:x}=Dr(a[0]);let G=Ym(x,"request",m);vn(y)&&(G=Zm(G,y.pop())),y.push(G)}const _=f&&f>We.wc_sessionAuthenticate.req.ttl?f:We.wc_sessionAuthenticate.req.ttl,A={authPayload:{type:d??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:w,resources:y},requester:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Be(_)},U={eip155:{chains:a,methods:[...new Set(["personal_sign",...m])],events:["chainChanged","accountsChanged"]}},E={requiredNamespaces:{},optionalNamespaces:U,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:C,metadata:this.client.metadata},expiryTimestamp:Be(We.wc_sessionPropose.req.ttl),id:fs()},{done:$,resolve:I,reject:L}=qs(_,"Request expired"),z=fs(),N=fe("session_connect",E.id),k=fe("session_request",z),O=async({error:x,session:G})=>{this.events.off(k,B),x?L(x):G&&I({session:G})},B=async x=>{var G,ee,re;if(await this.deletePendingAuthRequest(z,{message:"fulfilled",code:0}),x.error){const Le=ye("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===Le.code?void 0:(this.events.off(N,O),L(x.error.message))}await this.deleteProposal(E.id),this.events.off(N,O);const{cacaos:Ne,responder:pe}=x.result,$e=[],qe=[];for(const Le of Ne){await kc({cacao:Le,projectId:this.client.core.projectId})||(this.client.logger.error(Le,"Signature verification failed"),L(ye("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Us}=Le,ss=vn(Us.resources),zt=[zo(Us.iss)],rs=xn(Us.iss);if(ss){const cr=xc(ss),Zi=$c(ss);$e.push(...cr),zt.push(...Zi)}for(const cr of zt)qe.push(`${cr}:${rs}`)}const tt=await this.client.core.crypto.generateSharedKey(C,pe.publicKey);let De;$e.length>0&&(De={topic:tt,acknowledged:!0,self:{publicKey:C,metadata:this.client.metadata},peer:pe,controller:pe.publicKey,expiry:Be(fr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:il([...new Set($e)],[...new Set(qe)]),transportType:o},await this.client.core.relayer.subscribe(tt,{transportType:o}),await this.client.session.set(tt,De),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:pe.metadata}),De=this.client.session.get(tt)),(G=this.client.metadata.redirect)!=null&&G.linkMode&&(ee=pe.metadata.redirect)!=null&&ee.linkMode&&(re=pe.metadata.redirect)!=null&&re.universal&&r&&(this.client.core.addLinkModeSupportedApp(pe.metadata.redirect.universal),this.client.session.update(tt,{transportType:Pe.link_mode})),I({auths:Ne,session:De})};this.events.once(N,O),this.events.once(k,B);let F;try{if(n){const x=Vs("wc_sessionAuthenticate",A,z);this.client.core.history.set(b,x);const G=await this.client.core.crypto.encode("",x,{type:Gi,encoding:Cs});F=cn(r,b,G)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:A,expiry:s.expiry,throwOnFailedPublish:!0,clientRpcId:z}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:E,expiry:We.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:E.id})])}catch(x){throw this.events.off(N,O),this.events.off(k,B),x}return await this.setProposal(E.id,E),await this.setAuthRequest(z,{request:ot(Ce({},A),{verifyContext:{}}),pairingTopic:b,transportType:o}),{uri:F??v,response:$}}),P(this,"approveSessionAuthenticate",async s=>{const{id:r,auths:i}=s,n=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Ms.authenticated_session_approve_started]}});try{this.isInitialized()}catch(f){throw n.setError(ui.no_internet_connection),f}const o=this.getPendingAuthRequest(r);if(!o)throw n.setError(ui.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||Pe.relay;a===Pe.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=En(c),h={type:ps,receiverPublicKey:c,senderPublicKey:l},d=[],p=[];for(const f of i){if(!await kc({cacao:f,projectId:this.client.core.projectId})){n.setError(ui.invalid_cacao);const S=ye("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:S,encodeOpts:h}),new Error(S.message)}n.addTrace(Ms.cacaos_verified);const{p:y}=f,b=vn(y.resources),v=[zo(y.iss)],C=xn(y.iss);if(b){const S=xc(b),_=$c(b);d.push(...S),v.push(..._)}for(const S of v)p.push(`${S}:${C}`)}const w=await this.client.core.crypto.generateSharedKey(l,c);n.addTrace(Ms.create_authenticated_session_topic);let m;if(d?.length>0){m={topic:w,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Be(fr),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:il([...new Set(d)],[...new Set(p)]),transportType:a},n.addTrace(Ms.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:a})}catch(f){throw n.setError(ui.subscribe_authenticated_session_topic_failure),f}n.addTrace(Ms.subscribe_authenticated_session_topic_success),await this.client.session.set(w,m),n.addTrace(Ms.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Ms.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:i,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(f){throw n.setError(ui.authenticated_session_approve_publish_failure),f}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:m}}),P(this,"rejectSessionAuthenticate",async s=>{this.isInitialized();const{id:r,reason:i}=s,n=this.getPendingAuthRequest(r);if(!n)throw new Error(`Could not find pending auth request with id ${r}`);n.transportType===Pe.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=En(o),l={type:ps,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:l,rpcOpts:We.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.client.proposal.delete(r,ye("USER_DISCONNECTED"))}),P(this,"formatAuthMessage",s=>{this.isInitialized();const{request:r,iss:i}=s;return dh(r,i)}),P(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const s=this.relayMessageCache.shift();s&&await this.onRelayMessage(s)}catch(s){this.client.logger.error(s)}},50)}),P(this,"cleanupDuplicatePairings",async s=>{if(s.pairingTopic)try{const r=this.client.core.pairing.pairings.get(s.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===s.peer.metadata.url&&n.topic&&n.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),P(this,"deleteSession",async s=>{var r;const{topic:i,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=s,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,ye("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),n||this.client.core.expirer.del(i),this.client.core.storage.removeItem(Rl).catch(l=>this.client.logger.warn(l)),this.getPendingSessionRequests().forEach(l=>{l.topic===i&&this.deletePendingSessionRequest(l.id,ye("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=Gt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),P(this,"deleteProposal",async(s,r)=>{if(r)try{const i=this.client.proposal.get(s);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(Ls.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(s,ye("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"proposal")}),P(this,"deletePendingSessionRequest",async(s,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(s,r),i?Promise.resolve():this.client.core.expirer.del(s)]),this.addToRecentlyDeleted(s,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==s),i&&(this.sessionRequestQueue.state=Gt.idle,this.client.events.emit("session_request_expire",{id:s}))}),P(this,"deletePendingAuthRequest",async(s,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(s,r),i?Promise.resolve():this.client.core.expirer.del(s)])}),P(this,"setExpiry",async(s,r)=>{this.client.session.keys.includes(s)&&(this.client.core.expirer.set(s,r),await this.client.session.update(s,{expiry:r}))}),P(this,"setProposal",async(s,r)=>{this.client.core.expirer.set(s,Be(We.wc_sessionPropose.req.ttl)),await this.client.proposal.set(s,r)}),P(this,"setAuthRequest",async(s,r)=>{const{request:i,pairingTopic:n,transportType:o=Pe.relay}=r;this.client.core.expirer.set(s,i.expiryTimestamp),await this.client.auth.requests.set(s,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:s,pairingTopic:n,verifyContext:i.verifyContext,transportType:o})}),P(this,"setPendingSessionRequest",async s=>{const{id:r,topic:i,params:n,verifyContext:o}=s,a=n.request.expiryTimestamp||Be(We.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:n,verifyContext:o})}),P(this,"sendRequest",async s=>{const{topic:r,method:i,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h}=s,d=Vs(i,n,c);let p;const w=!!u;try{const y=w?Cs:Wt;p=await this.client.core.crypto.encode(r,d,{encoding:y})}catch(y){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),y}let m;if(dC.includes(i)){const y=Zt(JSON.stringify(d)),b=Zt(p);m=await this.client.core.verify.register({id:b,decryptedId:y})}const f=We[i].req;if(f.attestation=m,o&&(f.ttl=o),a&&(f.id=a),this.client.core.history.set(r,d),w){const y=cn(u,r,p);await Q.Linking.openURL(y,this.client.name)}else{const y=We[i].req;o&&(y.ttl=o),a&&(y.id=a),y.tvf=ot(Ce({},h),{correlationId:d.id}),l?(y.internal=ot(Ce({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,y)):this.client.core.relayer.publish(r,p,y).catch(b=>this.client.logger.error(b))}return d.id}),P(this,"sendResult",async s=>{const{id:r,topic:i,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=s,l=Bn(r,n);let u;const h=c&&typeof(Q==null?void 0:Q.Linking)<"u";try{const w=h?Cs:Wt;u=await this.client.core.crypto.encode(i,l,ot(Ce({},a||{}),{encoding:w}))}catch(w){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),w}let d,p;try{d=await this.client.core.history.get(i,r);const w=d.request;try{this.shouldSetTVF(w.method,w.params)&&(p=this.getTVFParams(r,w.params,n))}catch(m){this.client.logger.warn("sendResult() -> getTVFParams() failed",m)}}catch(w){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),w}if(h){const w=cn(c,i,u);await Q.Linking.openURL(w,this.client.name)}else{const w=d.request.method,m=We[w].res;m.tvf=ot(Ce({},p),{correlationId:r}),o?(m.internal=ot(Ce({},m.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,u,m)):this.client.core.relayer.publish(i,u,m).catch(f=>this.client.logger.error(f))}await this.client.core.history.resolve(l)}),P(this,"sendError",async s=>{const{id:r,topic:i,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=s,l=gu(r,n);let u;const h=c&&typeof(Q==null?void 0:Q.Linking)<"u";try{const p=h?Cs:Wt;u=await this.client.core.crypto.encode(i,l,ot(Ce({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let d;try{d=await this.client.core.history.get(i,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),p}if(h){const p=cn(c,i,u);await Q.Linking.openURL(p,this.client.name)}else{const p=d.request.method,w=a||We[p].res;this.client.core.relayer.publish(i,u,w)}await this.client.core.history.resolve(l)}),P(this,"cleanup",async()=>{const s=[],r=[];this.client.session.getAll().forEach(i=>{let n=!1;Es(i.expiry)&&(n=!0),this.client.core.crypto.keychain.has(i.topic)||(n=!0),n&&s.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Es(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...s.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),P(this,"onProviderMessageEvent",async s=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(s):await this.onRelayMessage(s)}),P(this,"onRelayEventRequest",async s=>{this.requestQueue.queue.push(s),await this.processRequestsQueue()}),P(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Gt.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Gt.active;const s=this.requestQueue.queue.shift();if(s)try{await this.processRequest(s)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=Gt.idle}),P(this,"processRequest",async s=>{const{topic:r,payload:i,attestation:n,transportType:o,encryptedId:a}=s,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),P(this,"onRelayEventResponse",async s=>{const{topic:r,payload:i,transportType:n}=s,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,n);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),P(this,"onRelayEventUnknownPayload",s=>{const{topic:r}=s,{message:i}=R("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),P(this,"shouldIgnorePairingRequest",s=>{const{topic:r,requestMethod:i}=s,n=this.expectedPairingMethodMap.get(r);return!n||n.includes(i)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),P(this,"onSessionProposeRequest",async s=>{const{topic:r,payload:i,attestation:n,encryptedId:o}=s,{params:a,id:c}=i;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(ls.proposal_listener_not_found)),this.isValidConnect(Ce({},i.params));const u=a.expiryTimestamp||Be(We.wc_sessionPropose.req.ttl),h=Ce({id:c,pairingTopic:r,expiryTimestamp:u},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:n,hash:Zt(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});l?.addTrace(Jt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:We.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),P(this,"onSessionProposeResponse",async(s,r,i)=>{const{id:n}=r;if(cs(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(n,{sessionTopic:u,pairingTopic:s,proposalId:n,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:s})}else if(Yt(r)){await this.client.proposal.delete(n,ye("USER_DISCONNECTED"));const o=fe("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),P(this,"onSessionSettleRequest",async(s,r)=>{const{id:i,params:n}=r;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:d}=r.params,p=[...this.pendingSessions.values()].find(f=>f.sessionTopic===s);if(!p)return this.client.logger.error(`Pending session not found for topic ${s}`);const w=this.client.proposal.get(p.proposalId),m=ot(Ce(Ce(Ce({topic:s,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:w.requiredNamespaces,optionalNamespaces:w.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),{transportType:Pe.relay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.client.events.emit("session_connect",{session:m}),this.events.emit(fe("session_connect",p.proposalId),{session:m}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:r.id,topic:s,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),P(this,"onSessionSettleResponse",async(s,r)=>{const{id:i}=r;cs(r)?(await this.client.session.update(s,{acknowledged:!0}),this.events.emit(fe("session_approve",i),{})):Yt(r)&&(await this.client.session.delete(s,ye("USER_DISCONNECTED")),this.events.emit(fe("session_approve",i),{error:r.error}))}),P(this,"onSessionUpdateRequest",async(s,r)=>{const{params:i,id:n}=r;try{const o=`${s}_session_update`,a=ci.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:s,error:ye("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(Ce({topic:s},i));try{ci.set(o,n),await this.client.session.update(s,{namespaces:i.namespaces}),await this.sendResult({id:n,topic:s,result:!0,throwOnFailedPublish:!0})}catch(c){throw ci.delete(o),c}this.client.events.emit("session_update",{id:n,topic:s,params:i})}catch(o){await this.sendError({id:n,topic:s,error:o}),this.client.logger.error(o)}}),P(this,"isRequestOutOfSync",(s,r)=>r.toString().slice(0,-3)<s.toString().slice(0,-3)),P(this,"onSessionUpdateResponse",(s,r)=>{const{id:i}=r,n=fe("session_update",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);cs(r)?this.events.emit(fe("session_update",i),{}):Yt(r)&&this.events.emit(fe("session_update",i),{error:r.error})}),P(this,"onSessionExtendRequest",async(s,r)=>{const{id:i}=r;try{this.isValidExtend({topic:s}),await this.setExpiry(s,Be(fr)),await this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_extend",{id:i,topic:s})}catch(n){await this.sendError({id:i,topic:s,error:n}),this.client.logger.error(n)}}),P(this,"onSessionExtendResponse",(s,r)=>{const{id:i}=r,n=fe("session_extend",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);cs(r)?this.events.emit(fe("session_extend",i),{}):Yt(r)&&this.events.emit(fe("session_extend",i),{error:r.error})}),P(this,"onSessionPingRequest",async(s,r)=>{const{id:i}=r;try{this.isValidPing({topic:s}),await this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:s})}catch(n){await this.sendError({id:i,topic:s,error:n}),this.client.logger.error(n)}}),P(this,"onSessionPingResponse",(s,r)=>{const{id:i}=r,n=fe("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);cs(r)?this.events.emit(fe("session_ping",i),{}):Yt(r)&&this.events.emit(fe("session_ping",i),{error:r.error})},500)}),P(this,"onSessionDeleteRequest",async(s,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:s,reason:r.params}),Promise.all([new Promise(n=>{this.client.core.relayer.once(Ve.publish,async()=>{n(await this.deleteSession({topic:s,id:i}))})}),this.sendResult({id:i,topic:s,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:s,error:ye("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),P(this,"onSessionRequest",async s=>{var r,i,n;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=s,{id:h,params:d}=a;try{await this.isValidRequest(Ce({topic:o},d));const p=this.client.session.get(o),w=await this.getVerifyContext({attestationId:c,hash:Zt(JSON.stringify(Vs("wc_sessionRequest",d,h))),encryptedId:l,metadata:p.peer.metadata,transportType:u}),m={id:h,topic:o,params:d,verifyContext:w};await this.setPendingSessionRequest(m),u===Pe.link_mode&&(r=p.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(m):(this.addSessionRequestToSessionRequestQueue(m),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),P(this,"onSessionRequestResponse",(s,r)=>{const{id:i}=r,n=fe("session_request",i);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);cs(r)?this.events.emit(fe("session_request",i),{result:r.result}):Yt(r)&&this.events.emit(fe("session_request",i),{error:r.error})}),P(this,"onSessionEventRequest",async(s,r)=>{const{id:i,params:n}=r;try{const o=`${s}_session_event_${n.event.name}`,a=ci.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(Ce({topic:s},n)),this.client.events.emit("session_event",{id:i,topic:s,params:n}),ci.set(o,i)}catch(o){await this.sendError({id:i,topic:s,error:o}),this.client.logger.error(o)}}),P(this,"onSessionAuthenticateResponse",(s,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:s,payload:r}),cs(r)?this.events.emit(fe("session_request",i),{result:r.result}):Yt(r)&&this.events.emit(fe("session_request",i),{error:r.error})}),P(this,"onSessionAuthenticateRequest",async s=>{var r;const{topic:i,payload:n,attestation:o,encryptedId:a,transportType:c}=s;try{const{requester:l,authPayload:u,expiryTimestamp:h}=n.params,d=await this.getVerifyContext({attestationId:o,hash:Zt(JSON.stringify(n)),encryptedId:a,metadata:l.metadata,transportType:c}),p={requester:l,pairingTopic:i,id:n.id,authPayload:u,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(n.id,{request:p,pairingTopic:i,transportType:c}),c===Pe.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:n.params,id:n.id,verifyContext:d})}catch(l){this.client.logger.error(l);const u=n.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(n.params.requester.metadata,c),p={type:ps,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:n.id,topic:i,error:l,encodeOpts:p,rpcOpts:We.wc_sessionAuthenticate.autoReject,appLink:d})}}),P(this,"addSessionRequestToSessionRequestQueue",s=>{this.sessionRequestQueue.queue.push(s)}),P(this,"cleanupAfterResponse",s=>{this.deletePendingSessionRequest(s.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Gt.idle,this.processSessionRequestQueue()},D.toMiliseconds(this.requestQueueDelay))}),P(this,"cleanupPendingSentRequestsForTopic",({topic:s,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(n=>n.topic===s&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=fe("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(fe("session_request",n.request.id),{error:r})})}),P(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Gt.active){this.client.logger.info("session request queue is already active.");return}const s=this.sessionRequestQueue.queue[0];if(!s){this.client.logger.info("session request queue is empty.");return}try{this.sessionRequestQueue.state=Gt.active,this.emitSessionRequest(s)}catch(r){this.client.logger.error(r)}}),P(this,"emitSessionRequest",s=>{this.client.events.emit("session_request",s)}),P(this,"onPairingCreated",s=>{if(s.methods&&this.expectedPairingMethodMap.set(s.topic,s.methods),s.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===s.topic);r&&this.onSessionProposeRequest({topic:s.topic,payload:Vs("wc_sessionPropose",ot(Ce({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id)})}),P(this,"isValidConnect",async s=>{if(!gt(s)){const{message:l}=R("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(s)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=s;if(rt(r)||await this.isValidPairingTopic(r),!ob(c)){const{message:l}=R("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(!rt(i)&&Ts(i)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(i,"requiredNamespaces")}if(!rt(n)&&Ts(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),rt(o)||this.validateSessionProps(o,"sessionProperties"),!rt(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(i||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(u=>l.includes(u)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),P(this,"validateNamespaces",(s,r)=>{const i=nb(s,"connect()",r);if(i)throw new Error(i.message)}),P(this,"isValidApprove",async s=>{if(!gt(s))throw new Error(R("MISSING_OR_INVALID",`approve() params: ${s}`).message);const{id:r,namespaces:i,relayProtocol:n,sessionProperties:o,scopedProperties:a}=s;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=vo(i,"approve()");if(l)throw new Error(l.message);const u=al(c.requiredNamespaces,i,"approve()");if(u)throw new Error(u.message);if(!Ue(n,!0)){const{message:h}=R("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}if(rt(o)||this.validateSessionProps(o,"sessionProperties"),!rt(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),P(this,"isValidReject",async s=>{if(!gt(s)){const{message:n}=R("MISSING_OR_INVALID",`reject() params: ${s}`);throw new Error(n)}const{id:r,reason:i}=s;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!cb(i)){const{message:n}=R("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(n)}}),P(this,"isValidSessionSettleRequest",s=>{if(!gt(s)){const{message:l}=R("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${s}`);throw new Error(l)}const{relay:r,controller:i,namespaces:n,expiry:o}=s;if(!Mh(r)){const{message:l}=R("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Qy(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=vo(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Es(o)){const{message:l}=R("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),P(this,"isValidUpdate",async s=>{if(!gt(s)){const{message:c}=R("MISSING_OR_INVALID",`update() params: ${s}`);throw new Error(c)}const{topic:r,namespaces:i}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const n=this.client.session.get(r),o=vo(i,"update()");if(o)throw new Error(o.message);const a=al(n.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),P(this,"isValidExtend",async s=>{if(!gt(s)){const{message:i}=R("MISSING_OR_INVALID",`extend() params: ${s}`);throw new Error(i)}const{topic:r}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),P(this,"isValidRequest",async s=>{if(!gt(s)){const{message:c}=R("MISSING_OR_INVALID",`request() params: ${s}`);throw new Error(c)}const{topic:r,request:i,chainId:n,expiry:o}=s;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!ol(a,n)){const{message:c}=R("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!lb(i)){const{message:c}=R("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!db(a,n,i.method)){const{message:c}=R("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!mb(o,So)){const{message:c}=R("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${So.min} and ${So.max}`);throw new Error(c)}}),P(this,"isValidRespond",async s=>{var r;if(!gt(s)){const{message:o}=R("MISSING_OR_INVALID",`respond() params: ${s}`);throw new Error(o)}const{topic:i,response:n}=s;try{await this.isValidSessionTopic(i)}catch(o){throw(r=s?.response)!=null&&r.id&&this.cleanupAfterResponse(s),o}if(!ub(n)){const{message:o}=R("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),P(this,"isValidPing",async s=>{if(!gt(s)){const{message:i}=R("MISSING_OR_INVALID",`ping() params: ${s}`);throw new Error(i)}const{topic:r}=s;await this.isValidSessionOrPairingTopic(r)}),P(this,"isValidEmit",async s=>{if(!gt(s)){const{message:a}=R("MISSING_OR_INVALID",`emit() params: ${s}`);throw new Error(a)}const{topic:r,event:i,chainId:n}=s;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!ol(o,n)){const{message:a}=R("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!hb(i)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!pb(o,n,i.name)){const{message:a}=R("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),P(this,"isValidDisconnect",async s=>{if(!gt(s)){const{message:i}=R("MISSING_OR_INVALID",`disconnect() params: ${s}`);throw new Error(i)}const{topic:r}=s;await this.isValidSessionOrPairingTopic(r)}),P(this,"isValidAuthenticate",s=>{const{chains:r,uri:i,domain:n,nonce:o}=s;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!Ue(i,!1))throw new Error("uri is required parameter");if(!Ue(n,!1))throw new Error("domain is required parameter");if(!Ue(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Dr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Dr(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),P(this,"getVerifyContext",async s=>{const{attestationId:r,hash:i,encryptedId:n,metadata:o,transportType:a}=s,c={verified:{verifyUrl:o.verifyUrl||Ai,validation:"UNKNOWN",origin:o.url||""}};try{if(a===Pe.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:n,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),P(this,"validateSessionProps",(s,r)=>{Object.values(s).forEach((i,n)=>{if(i==null){const{message:o}=R("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(s)[n]}`);throw new Error(o)}})}),P(this,"getPendingAuthRequest",s=>{const r=this.client.auth.requests.get(s);return typeof r=="object"?r:void 0}),P(this,"addToRecentlyDeleted",(s,r)=>{if(this.recentlyDeletedMap.set(s,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=n)break;this.recentlyDeletedMap.delete(o)}}}),P(this,"checkRecentlyDeleted",s=>{const r=this.recentlyDeletedMap.get(s);if(r){const{message:i}=R("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${s}`);throw new Error(i)}}),P(this,"isLinkModeEnabled",(s,r)=>{var i,n,o,a,c,l,u,h,d;return!s||r!==Pe.link_mode?!1:((n=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=s?.redirect)==null?void 0:u.universal)!==void 0&&((h=s?.redirect)==null?void 0:h.universal)!==""&&((d=s?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(s.redirect.universal)&&typeof(Q==null?void 0:Q.Linking)<"u"}),P(this,"getAppLinkIfEnabled",(s,r)=>{var i;return this.isLinkModeEnabled(s,r)?(i=s?.redirect)==null?void 0:i.universal:void 0}),P(this,"handleLinkModeMessage",({url:s})=>{if(!s||!s.includes("wc_ev")||!s.includes("topic"))return;const r=Cc(s,"topic")||"",i=decodeURIComponent(Cc(s,"wc_ev")||""),n=this.client.session.keys.includes(r);n&&this.client.session.update(r,{transportType:Pe.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:n})}),P(this,"registerLinkModeListeners",async()=>{var s;if(Na()||Rs()&&(s=this.client.metadata.redirect)!=null&&s.linkMode){const r=Q==null?void 0:Q.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),P(this,"shouldSetTVF",(s,r)=>{if(!r||s!=="wc_sessionRequest")return!1;const{request:i}=r;return Object.keys(Dl).includes(i.method)}),P(this,"getTVFParams",(s,r,i)=>{var n,o;try{const a=r.request.method,c=this.extractTxHashesFromResult(a,i);return ot(Ce({correlationId:s,rpcMethods:[a],chainId:r.chainId},this.isValidContractData(r.request.params)&&{contractAddresses:[(o=(n=r.request.params)==null?void 0:n[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),P(this,"isValidContractData",s=>{var r;if(!s)return!1;try{const i=s?.data||((r=s?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const n=i.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),P(this,"extractTxHashesFromResult",(s,r)=>{try{const i=Dl[s];if(typeof r=="string")return[r];const n=r[i.key];if(Os(n))return s==="solana_signAllTransactions"?n.map(o=>Dm(o)):n;if(typeof n=="string")return[n]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,s=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,i]of Object.entries(s))for(const n of i)try{await this.onProviderMessageEvent({topic:r,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=R("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ve.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:s,message:r,attestation:i,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(In)?this.client.auth.authKeys.get(In):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(s,r,{receiverPublicKey:o,encoding:n===Pe.link_mode?Cs:Wt});ba(a)?(this.client.core.history.set(s,a),await this.onRelayEventRequest({topic:s,payload:a,attestation:i,transportType:n,encryptedId:Zt(r)})):va(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:s,payload:a,transportType:n}),this.client.core.history.delete(s,a.id)):await this.onRelayEventUnknownPayload({topic:s,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(s,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on($t.expired,async e=>{const{topic:s,id:r}=rh(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,R("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,R("EXPIRED"),!0);s?this.client.session.keys.includes(s)&&(await this.deleteSession({topic:s,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:s})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(Hs.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Hs.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ue(e,!1)){const{message:s}=R("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(s)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:s}=R("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(s)}if(Es(this.client.core.pairing.pairings.get(e).expiry)){const{message:s}=R("EXPIRED",`pairing topic: ${e}`);throw new Error(s)}}async isValidSessionTopic(e){if(!Ue(e,!1)){const{message:s}=R("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(s)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:s}=R("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(s)}if(Es(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:s}=R("EXPIRED",`session topic: ${e}`);throw new Error(s)}if(!this.client.core.crypto.keychain.has(e)){const{message:s}=R("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(s)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(Ue(e,!1)){const{message:s}=R("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(s)}else{const{message:s}=R("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(s)}}async isValidProposalId(e){if(!ab(e)){const{message:s}=R("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(s)}if(!this.client.proposal.keys.includes(e)){const{message:s}=R("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(s)}if(Es(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:s}=R("EXPIRED",`proposal id: ${e}`);throw new Error(s)}}}class NC extends or{constructor(e,s){super(e,s,cC,xa),this.core=e,this.logger=s}}let _C=class extends or{constructor(e,s){super(e,s,lC,xa),this.core=e,this.logger=s}};class AC extends or{constructor(e,s){super(e,s,hC,xa,r=>r.id),this.core=e,this.logger=s}}class SC extends or{constructor(e,s){super(e,s,gC,Xn,()=>In),this.core=e,this.logger=s}}class PC extends or{constructor(e,s){super(e,s,mC,Xn),this.core=e,this.logger=s}}class OC extends or{constructor(e,s){super(e,s,wC,Xn,r=>r.id),this.core=e,this.logger=s}}var TC=Object.defineProperty,kC=(t,e,s)=>e in t?TC(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Po=(t,e,s)=>kC(t,typeof e!="symbol"?e+"":e,s);class xC{constructor(e,s){this.core=e,this.logger=s,Po(this,"authKeys"),Po(this,"pairingTopics"),Po(this,"requests"),this.authKeys=new SC(this.core,this.logger),this.pairingTopics=new PC(this.core,this.logger),this.requests=new OC(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var $C=Object.defineProperty,RC=(t,e,s)=>e in t?$C(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oe=(t,e,s)=>RC(t,typeof e!="symbol"?e+"":e,s);let UC=class id extends zf{constructor(e){super(e),oe(this,"protocol",td),oe(this,"version",sd),oe(this,"name",Ao.name),oe(this,"metadata"),oe(this,"core"),oe(this,"logger"),oe(this,"events",new $s.EventEmitter),oe(this,"engine"),oe(this,"session"),oe(this,"proposal"),oe(this,"pendingRequest"),oe(this,"auth"),oe(this,"signConfig"),oe(this,"on",(r,i)=>this.events.on(r,i)),oe(this,"once",(r,i)=>this.events.once(r,i)),oe(this,"off",(r,i)=>this.events.off(r,i)),oe(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),oe(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),oe(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),oe(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(n){throw this.logger.error(n.message),n}}),oe(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ao.name,this.metadata=Jg(e?.metadata),this.signConfig=e?.signConfig;const s=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ya(ji({level:e?.logger||Ao.logger}));this.core=e?.core||new aC(e),this.logger=ct(s,this.name),this.session=new _C(this.core,this.logger),this.proposal=new NC(this.core,this.logger),this.pendingRequest=new AC(this.core,this.logger),this.engine=new IC(this),this.auth=new xC(this.core,this.logger)}static async init(e){const s=new id(e);return await s.initialize(),s}get context(){return At(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success"),setTimeout(()=>{this.engine.processRelayMessageCache()},D.toMiliseconds(D.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}};const Ml="error",DC="wss://relay.walletconnect.org",LC="wc",MC="universal_provider",un=`${LC}@2:${MC}:`,nd="https://rpc.walletconnect.org/v1/",Sr="generic",BC=`${nd}bundler`,Dt={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};function jC(){}function $a(t){return t==null||typeof t!="object"&&typeof t!="function"}function Ra(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function qC(t){if($a(t))return t;if(Array.isArray(t)||Ra(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),s=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new s(t);if(t instanceof RegExp){const r=new s(t);return r.lastIndex=t.lastIndex,r}if(t instanceof DataView)return new s(t.buffer.slice(0));if(t instanceof Error){const r=new s(t.message);return r.stack=t.stack,r.name=t.name,r.cause=t.cause,r}if(typeof File<"u"&&t instanceof File)return new s([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const r=Object.create(e);return Object.assign(r,t)}return t}function Bl(t){return typeof t=="object"&&t!==null}function od(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ad(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const FC="[object RegExp]",cd="[object String]",ld="[object Number]",ud="[object Boolean]",hd="[object Arguments]",WC="[object Symbol]",HC="[object Date]",zC="[object Map]",VC="[object Set]",KC="[object Array]",GC="[object ArrayBuffer]",JC="[object Object]",YC="[object DataView]",XC="[object Uint8Array]",ZC="[object Uint8ClampedArray]",QC="[object Uint16Array]",e1="[object Uint32Array]",t1="[object Int8Array]",s1="[object Int16Array]",r1="[object Int32Array]",i1="[object Float32Array]",n1="[object Float64Array]";function o1(t,e){return $r(t,void 0,t,new Map,e)}function $r(t,e,s,r=new Map,i=void 0){const n=i?.(t,e,s,r);if(n!=null)return n;if($a(t))return t;if(r.has(t))return r.get(t);if(Array.isArray(t)){const o=new Array(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=$r(t[a],a,s,r,i);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;r.set(t,o);for(const[a,c]of t)o.set(a,$r(c,a,s,r,i));return o}if(t instanceof Set){const o=new Set;r.set(t,o);for(const a of t)o.add($r(a,void 0,s,r,i));return o}if(typeof Ye<"u"&&Ye.isBuffer(t))return t.subarray();if(Ra(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=$r(t[a],a,s,r,i);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return r.set(t,o),zs(o,t,s,r,i),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return r.set(t,o),zs(o,t,s,r,i),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return r.set(t,o),zs(o,t,s,r,i),o}if(t instanceof Error){const o=new t.constructor;return r.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,zs(o,t,s,r,i),o}if(typeof t=="object"&&a1(t)){const o=Object.create(Object.getPrototypeOf(t));return r.set(t,o),zs(o,t,s,r,i),o}return t}function zs(t,e,s=t,r,i){const n=[...Object.keys(e),...od(e)];for(let o=0;o<n.length;o++){const a=n[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=$r(e[a],a,s,r,i))}}function a1(t){switch(ad(t)){case hd:case KC:case GC:case YC:case ud:case HC:case i1:case n1:case t1:case s1:case r1:case zC:case ld:case JC:case FC:case VC:case cd:case WC:case XC:case ZC:case QC:case e1:return!0;default:return!1}}function c1(t,e){return o1(t,(s,r,i,n)=>{if(typeof t=="object")switch(Object.prototype.toString.call(t)){case ld:case cd:case ud:{const o=new t.constructor(t?.valueOf());return zs(o,t),o}case hd:{const o={};return zs(o,t),o.length=t.length,o[Symbol.iterator]=t[Symbol.iterator],o}default:return}})}function jl(t){return c1(t)}function ql(t){return t!==null&&typeof t=="object"&&ad(t)==="[object Arguments]"}function l1(t){return Ra(t)}function u1(t){if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const s=t[Symbol.toStringTag];return s==null||!Object.getOwnPropertyDescriptor(t,Symbol.toStringTag)?.writable?!1:t.toString()===`[object ${s}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function h1(t,...e){const s=e.slice(0,-1),r=e[e.length-1];let i=t;for(let n=0;n<s.length;n++){const o=s[n];i=da(i,o,r,new Map)}return i}function da(t,e,s,r){if($a(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(r.has(e))return qC(r.get(e));if(r.set(e,t),Array.isArray(e)){e=e.slice();for(let n=0;n<e.length;n++)e[n]=e[n]??void 0}const i=[...Object.keys(e),...od(e)];for(let n=0;n<i.length;n++){const o=i[n];let a=e[o],c=t[o];if(ql(a)&&(a={...a}),ql(c)&&(c={...c}),typeof Ye<"u"&&Ye.isBuffer(a)&&(a=jl(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let d=0;d<h.length;d++){const p=h[d];u[p]=c[p]}c=u}else c=[];const l=s(c,a,o,t,e,r);l!=null?t[o]=l:Array.isArray(a)||Bl(c)&&Bl(a)?t[o]=da(c,a,s,r):c==null&&u1(a)?t[o]=da({},a,s,r):c==null&&l1(a)?t[o]=jl(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function d1(t,...e){return h1(t,...e,jC)}var p1=Object.defineProperty,f1=Object.defineProperties,g1=Object.getOwnPropertyDescriptors,Fl=Object.getOwnPropertySymbols,m1=Object.prototype.hasOwnProperty,w1=Object.prototype.propertyIsEnumerable,Wl=(t,e,s)=>e in t?p1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,hn=(t,e)=>{for(var s in e||(e={}))m1.call(e,s)&&Wl(t,s,e[s]);if(Fl)for(var s of Fl(e))w1.call(e,s)&&Wl(t,s,e[s]);return t},y1=(t,e)=>f1(t,g1(e));function _t(t,e,s){var r;const i=Dr(t);return((r=e.rpcMap)==null?void 0:r[i.reference])||`${nd}?chainId=${i.namespace}:${i.reference}&projectId=${s}`}function ar(t){return t.includes(":")?t.split(":")[1]:t}function dd(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function b1(t,e){const s=Object.keys(e.namespaces).filter(i=>i.includes(t));if(!s.length)return[];const r=[];return s.forEach(i=>{const n=e.namespaces[i].accounts;r.push(...n)}),r}function dn(t={},e={}){const s=Hl(t),r=Hl(e);return d1(s,r)}function Hl(t){var e,s,r,i,n;const o={};if(!Ts(t))return o;for(const[a,c]of Object.entries(t)){const l=Jn(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],d=c.rpcMap||{},p=xr(a);o[p]=y1(hn(hn({},o[p]),c),{chains:es(l,(e=o[p])==null?void 0:e.chains),methods:es(u,(s=o[p])==null?void 0:s.methods),events:es(h,(r=o[p])==null?void 0:r.events)}),(Ts(d)||Ts(((i=o[p])==null?void 0:i.rpcMap)||{}))&&(o[p].rpcMap=hn(hn({},d),(n=o[p])==null?void 0:n.rpcMap))}return o}function zl(t){return t.includes(":")?t.split(":")[2]:t}function Vl(t){const e={};for(const[s,r]of Object.entries(t)){const i=r.methods||[],n=r.events||[],o=r.accounts||[],a=Jn(s)?[s]:r.chains?r.chains:dd(r.accounts);e[s]={chains:a,methods:i,events:n,accounts:o}}return e}function Oo(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}const pd={},he=t=>pd[t],To=(t,e)=>{pd[t]=e};var v1=Object.defineProperty,E1=(t,e,s)=>e in t?v1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,gr=(t,e,s)=>E1(t,typeof e!="symbol"?e+"":e,s);class C1{constructor(e){gr(this,"name","polkadot"),gr(this,"client"),gr(this,"httpProviders"),gr(this,"events"),gr(this,"namespace"),gr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var I1=Object.defineProperty,N1=Object.defineProperties,_1=Object.getOwnPropertyDescriptors,Kl=Object.getOwnPropertySymbols,A1=Object.prototype.hasOwnProperty,S1=Object.prototype.propertyIsEnumerable,pa=(t,e,s)=>e in t?I1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Gl=(t,e)=>{for(var s in e||(e={}))A1.call(e,s)&&pa(t,s,e[s]);if(Kl)for(var s of Kl(e))S1.call(e,s)&&pa(t,s,e[s]);return t},Jl=(t,e)=>N1(t,_1(e)),mr=(t,e,s)=>pa(t,typeof e!="symbol"?e+"":e,s);class P1{constructor(e){mr(this,"name","eip155"),mr(this,"client"),mr(this,"chainId"),mr(this,"namespace"),mr(this,"httpProviders"),mr(this,"events"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain())}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(parseInt(e),s),this.chainId=parseInt(e),this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,s){const r=s||_t(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=parseInt(ar(s));e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}getHttpProvider(){const e=this.chainId,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}async handleSwitchChain(e){var s,r;let i=e.request.params?(s=e.request.params[0])==null?void 0:s.chainId:"0x0";i=i.startsWith("0x")?i:`0x${i}`;const n=parseInt(i,16);if(this.isChainApproved(n))this.setDefaultChain(`${n}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:i}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${n}`);else throw new Error(`Failed to switch to chain 'eip155:${n}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var s,r,i,n,o;const a=(r=(s=e.request)==null?void 0:s.params)==null?void 0:r[0],c=((n=(i=e.request)==null?void 0:i.params)==null?void 0:n[1])||[],l=`${a}${c.join(",")}`;if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const u=this.client.session.get(e.topic),h=((o=u?.sessionProperties)==null?void 0:o.capabilities)||{};if(h!=null&&h[l])return h?.[l];const d=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:Jl(Gl({},u.sessionProperties||{}),{capabilities:Jl(Gl({},h||{}),{[l]:d})})})}catch(p){console.warn("Failed to update session with capabilities",p)}return d}async getCallStatus(e){var s,r;const i=this.client.session.get(e.topic),n=(s=i.sessionProperties)==null?void 0:s.bundler_name;if(n){const a=this.getBundlerUrl(e.chainId,n);try{return await this.getUserOperationReceipt(a,e)}catch(c){console.warn("Failed to fetch call status from bundler",c,a)}}const o=(r=i.sessionProperties)==null?void 0:r.bundler_url;if(o)try{return await this.getUserOperationReceipt(o,e)}catch(a){console.warn("Failed to fetch call status from custom bundler",a,o)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,s){var r;const i=new URL(e),n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Vs("eth_getUserOperationReceipt",[(r=s.request.params)==null?void 0:r[0]]))});if(!n.ok)throw new Error(`Failed to fetch user operation receipt - ${n.status}`);return await n.json()}getBundlerUrl(e,s){return`${BC}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${s}`}}var O1=Object.defineProperty,T1=(t,e,s)=>e in t?O1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,wr=(t,e,s)=>T1(t,typeof e!="symbol"?e+"":e,s);class k1{constructor(e){wr(this,"name","solana"),wr(this,"client"),wr(this,"httpProviders"),wr(this,"events"),wr(this,"namespace"),wr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var x1=Object.defineProperty,$1=(t,e,s)=>e in t?x1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,yr=(t,e,s)=>$1(t,typeof e!="symbol"?e+"":e,s);class R1{constructor(e){yr(this,"name","cosmos"),yr(this,"client"),yr(this,"httpProviders"),yr(this,"events"),yr(this,"namespace"),yr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var U1=Object.defineProperty,D1=(t,e,s)=>e in t?U1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,br=(t,e,s)=>D1(t,typeof e!="symbol"?e+"":e,s);class L1{constructor(e){br(this,"name","algorand"),br(this,"client"),br(this,"httpProviders"),br(this,"events"),br(this,"namespace"),br(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(!this.httpProviders[e]){const r=s||_t(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);return typeof r>"u"?void 0:new Ut(new Ht(r,he("disableProviderPing")))}}var M1=Object.defineProperty,B1=(t,e,s)=>e in t?M1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,vr=(t,e,s)=>B1(t,typeof e!="symbol"?e+"":e,s);class j1{constructor(e){vr(this,"name","cip34"),vr(this,"client"),vr(this,"httpProviders"),vr(this,"events"),vr(this,"namespace"),vr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{const r=this.getCardanoRPCUrl(s),i=ar(s);e[i]=this.createHttpProvider(i,r)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}getCardanoRPCUrl(e){const s=this.namespace.rpcMap;if(s)return s[e]}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||this.getCardanoRPCUrl(e);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var q1=Object.defineProperty,F1=(t,e,s)=>e in t?q1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Er=(t,e,s)=>F1(t,typeof e!="symbol"?e+"":e,s);class W1{constructor(e){Er(this,"name","elrond"),Er(this,"client"),Er(this,"httpProviders"),Er(this,"events"),Er(this,"namespace"),Er(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var H1=Object.defineProperty,z1=(t,e,s)=>e in t?H1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Cr=(t,e,s)=>z1(t,typeof e!="symbol"?e+"":e,s);class V1{constructor(e){Cr(this,"name","multiversx"),Cr(this,"client"),Cr(this,"httpProviders"),Cr(this,"events"),Cr(this,"namespace"),Cr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;const i=ar(s);e[i]=this.createHttpProvider(i,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var K1=Object.defineProperty,G1=(t,e,s)=>e in t?K1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ir=(t,e,s)=>G1(t,typeof e!="symbol"?e+"":e,s);class J1{constructor(e){Ir(this,"name","near"),Ir(this,"client"),Ir(this,"httpProviders"),Ir(this,"events"),Ir(this,"namespace"),Ir(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||_t(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{var r;e[s]=this.createHttpProvider(s,(r=this.namespace.rpcMap)==null?void 0:r[s])}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace);return typeof r>"u"?void 0:new Ut(new Ht(r,he("disableProviderPing")))}}var Y1=Object.defineProperty,X1=(t,e,s)=>e in t?Y1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Nr=(t,e,s)=>X1(t,typeof e!="symbol"?e+"":e,s);class Z1{constructor(e){Nr(this,"name","tezos"),Nr(this,"client"),Nr(this,"httpProviders"),Nr(this,"events"),Nr(this,"namespace"),Nr(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider().request(e.request)}setDefaultChain(e,s){if(this.chainId=e,!this.httpProviders[e]){const r=s||_t(`${this.name}:${e}`,this.namespace);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);this.setHttpProvider(e,r)}this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${this.chainId}`)}getAccounts(){const e=this.namespace.accounts;return e?e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2])||[]:[]}createHttpProviders(){const e={};return this.namespace.chains.forEach(s=>{e[s]=this.createHttpProvider(s)}),e}getHttpProvider(){const e=`${this.name}:${this.chainId}`,s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace);return typeof r>"u"?void 0:new Ut(new Ht(r))}}var Q1=Object.defineProperty,eI=(t,e,s)=>e in t?Q1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,_r=(t,e,s)=>eI(t,typeof e!="symbol"?e+"":e,s);class tI{constructor(e){_r(this,"name",Sr),_r(this,"client"),_r(this,"httpProviders"),_r(this,"events"),_r(this,"namespace"),_r(this,"chainId"),this.namespace=e.namespace,this.events=he("events"),this.client=he("client"),this.chainId=this.getDefaultChain(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,s){this.httpProviders[e]||this.setHttpProvider(e,s),this.chainId=e,this.events.emit(Dt.DEFAULT_CHAIN_CHANGED,`${this.name}:${e}`)}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(s=>s.split(":")[1]===this.chainId.toString()).map(s=>s.split(":")[2]))]:[]}createHttpProviders(){var e,s;const r={};return(s=(e=this.namespace)==null?void 0:e.accounts)==null||s.forEach(i=>{const n=Dr(i);r[`${n.namespace}:${n.reference}`]=this.createHttpProvider(i)}),r}getHttpProvider(e){const s=this.httpProviders[e];if(typeof s>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return s}setHttpProvider(e,s){const r=this.createHttpProvider(e,s);r&&(this.httpProviders[e]=r)}createHttpProvider(e,s){const r=s||_t(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Ut(new Ht(r,he("disableProviderPing")))}}var sI=Object.defineProperty,rI=Object.defineProperties,iI=Object.getOwnPropertyDescriptors,Yl=Object.getOwnPropertySymbols,nI=Object.prototype.hasOwnProperty,oI=Object.prototype.propertyIsEnumerable,fa=(t,e,s)=>e in t?sI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,pn=(t,e)=>{for(var s in e||(e={}))nI.call(e,s)&&fa(t,s,e[s]);if(Yl)for(var s of Yl(e))oI.call(e,s)&&fa(t,s,e[s]);return t},ko=(t,e)=>rI(t,iI(e)),kt=(t,e,s)=>fa(t,typeof e!="symbol"?e+"":e,s);let aI=class fd{constructor(e){kt(this,"client"),kt(this,"namespaces"),kt(this,"optionalNamespaces"),kt(this,"sessionProperties"),kt(this,"scopedProperties"),kt(this,"events",new Ca),kt(this,"rpcProviders",{}),kt(this,"session"),kt(this,"providerOpts"),kt(this,"logger"),kt(this,"uri"),kt(this,"disableProviderPing",!1),this.providerOpts=e,this.logger=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:ya(ji({level:e?.logger||Ml})),this.disableProviderPing=e?.disableProviderPing||!1}static async init(e){const s=new fd(e);return await s.initialize(),s}async request(e,s,r){const[i,n]=this.validateChain(s);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(i).request({request:pn({},e),chainId:`${i}:${n}`,topic:this.session.topic,expiry:r})}sendAsync(e,s,r,i){const n=new Date().getTime();this.request(e,r,i).then(o=>s(null,Bn(n,o))).catch(o=>s(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:ye("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.setNamespaces(e),await this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,s){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:i}=await this.client.authenticate(e,s);r&&(this.uri=r,this.events.emit("display_uri",r));const n=await i();if(this.session=n.session,this.session){const o=Vl(this.session.namespaces);this.namespaces=dn(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return n}on(e,s){this.events.on(e,s)}once(e,s){this.events.once(e,s)}removeListener(e,s){this.events.removeListener(e,s)}off(e,s){this.events.off(e,s)}get isWalletConnect(){return!0}async pair(e){const{uri:s,approval:r}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties});s&&(this.uri=s,this.events.emit("display_uri",s));const i=await r();this.session=i;const n=Vl(i.namespaces);return this.namespaces=dn(this.namespaces,n),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,s){try{if(!this.session)return;const[r,i]=this.validateChain(e),n=this.getProvider(r);n.name===Sr?n.setDefaultChain(`${r}:${i}`,s):n.setDefaultChain(i,s)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){this.logger.info("Cleaning up inactive pairings...");const s=this.client.pairing.getAll();if(Os(s)){for(const r of s)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${s.length}`)}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,s;if(this.client=this.providerOpts.client||await UC.init({core:this.providerOpts.core,logger:this.providerOpts.logger||Ml,relayUrl:this.providerOpts.relayUrl||DC,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(r){throw this.logger.error("Failed to get session",r),new Error(`The provided session: ${(s=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:s.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(s=>xr(s)))];To("client",this.client),To("events",this.events),To("disableProviderPing",this.disableProviderPing),e.forEach(s=>{if(!this.session)return;const r=b1(s,this.session),i=dd(r),n=dn(this.namespaces,this.optionalNamespaces),o=ko(pn({},n[s]),{accounts:r,chains:i});switch(s){case"eip155":this.rpcProviders[s]=new P1({namespace:o});break;case"algorand":this.rpcProviders[s]=new L1({namespace:o});break;case"solana":this.rpcProviders[s]=new k1({namespace:o});break;case"cosmos":this.rpcProviders[s]=new R1({namespace:o});break;case"polkadot":this.rpcProviders[s]=new C1({namespace:o});break;case"cip34":this.rpcProviders[s]=new j1({namespace:o});break;case"elrond":this.rpcProviders[s]=new W1({namespace:o});break;case"multiversx":this.rpcProviders[s]=new V1({namespace:o});break;case"near":this.rpcProviders[s]=new J1({namespace:o});break;case"tezos":this.rpcProviders[s]=new Z1({namespace:o});break;default:this.rpcProviders[Sr]?this.rpcProviders[Sr].updateNamespace(o):this.rpcProviders[Sr]=new tI({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var s;const{topic:r}=e;r===((s=this.session)==null?void 0:s.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var s;const{params:r,topic:i}=e;if(i!==((s=this.session)==null?void 0:s.topic))return;const{event:n}=r;if(n.name==="accountsChanged"){const o=n.data;o&&Os(o)&&this.events.emit("accountsChanged",o.map(zl))}else if(n.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=xr(o),l=Oo(o)!==Oo(a)?`${c}:${Oo(a)}`:o;this.onChainChanged(l)}else this.events.emit(n.name,n.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:s})=>{var r,i;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:n}=s,o=(i=this.client)==null?void 0:i.session.get(e);this.session=ko(pn({},o),{namespaces:n}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:s})}),this.client.on("session_delete",async e=>{var s;e.topic===((s=this.session)==null?void 0:s.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",ko(pn({},ye("USER_DISCONNECTED")),{data:e.topic})))}),this.on(Dt.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(e,!0)})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[Sr]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var s;this.getProvider(e).updateNamespace((s=this.session)==null?void 0:s.namespaces[e])})}setNamespaces(e){const{namespaces:s={},optionalNamespaces:r={},sessionProperties:i,scopedProperties:n}=e;this.optionalNamespaces=dn(s,r),this.sessionProperties=i,this.scopedProperties=n}validateChain(e){const[s,r]=e?.split(":")||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[s,r];if(s&&!Object.keys(this.namespaces||{}).map(o=>xr(o)).includes(s))throw new Error(`Namespace '${s}' is not configured. Please call connect() first with namespace config.`);if(s&&r)return[s,r];const i=xr(Object.keys(this.namespaces)[0]),n=this.rpcProviders[i].getDefaultChain();return[i,n]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged(e,s=!1){if(!this.namespaces)return;const[r,i]=this.validateChain(e);if(!i)return;this.updateNamespaceChain(r,i),this.events.emit("chainChanged",i);const n=this.getProvider(r).getDefaultChain();s||this.getProvider(r).setDefaultChain(i),this.emitAccountsChangedOnChainChange({namespace:r,previousChainId:n,newChainId:e}),await this.persist("namespaces",this.namespaces)}emitAccountsChangedOnChainChange({namespace:e,previousChainId:s,newChainId:r}){var i,n;try{if(s===r)return;const o=(n=(i=this.session)==null?void 0:i.namespaces[e])==null?void 0:n.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${r}:`)).map(zl);if(!Os(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn("Failed to emit accountsChanged on chain change",o)}}updateNamespaceChain(e,s){if(!this.namespaces)return;const r=this.namespaces[e]?e:`${e}:${s}`,i={chains:[],methods:[],events:[],defaultChain:s};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=s):this.namespaces[r]=i}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,await this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,s){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${un}/${e}${i}`,s)}async getFromStore(e){var s;const r=((s=this.session)==null?void 0:s.topic)||"";return await this.client.core.storage.getItem(`${un}/${e}${r}`)}async deleteFromStore(e){var s;const r=((s=this.session)==null?void 0:s.topic)||"";await this.client.core.storage.removeItem(`${un}/${e}${r}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const s=await this.client.core.storage.getKeys();for(const r of s)r.startsWith(un)&&await this.client.core.storage.removeItem(r)}catch(s){this.logger.warn("Failed to cleanup storage",s)}}};function fn(t,e){return q.getConnectorId(t)===e}function cI(t){const e=Array.from(g.state.chains.keys());let s=[];return t?(s.push([t,g.state.chains.get(t)]),fn(t,j.CONNECTOR_ID.WALLET_CONNECT)?e.forEach(r=>{r!==t&&fn(r,j.CONNECTOR_ID.WALLET_CONNECT)&&s.push([r,g.state.chains.get(r)])}):fn(t,j.CONNECTOR_ID.AUTH)&&e.forEach(r=>{r!==t&&fn(r,j.CONNECTOR_ID.AUTH)&&s.push([r,g.state.chains.get(r)])})):s=Array.from(g.state.chains.entries()),s}const je={METMASK_CONNECTOR_NAME:"MetaMask",TRUST_CONNECTOR_NAME:"Trust Wallet",SOLFLARE_CONNECTOR_NAME:"Solflare",PHANTOM_CONNECTOR_NAME:"Phantom",COIN98_CONNECTOR_NAME:"Coin98",MAGIC_EDEN_CONNECTOR_NAME:"Magic Eden",BACKPACK_CONNECTOR_NAME:"Backpack",BITGET_CONNECTOR_NAME:"Bitget Wallet",FRONTIER_CONNECTOR_NAME:"Frontier",XVERSE_CONNECTOR_NAME:"Xverse Wallet",LEATHER_CONNECTOR_NAME:"Leather",EIP155:"eip155",ADD_CHAIN_METHOD:"wallet_addEthereumChain",EIP6963_ANNOUNCE_EVENT:"eip6963:announceProvider",EIP6963_REQUEST_EVENT:"eip6963:requestProvider",CONNECTOR_RDNS_MAP:{coinbaseWallet:"com.coinbase.wallet",coinbaseWalletSDK:"com.coinbase.wallet"},CONNECTOR_TYPE_EXTERNAL:"EXTERNAL",CONNECTOR_TYPE_WALLET_CONNECT:"WALLET_CONNECT",CONNECTOR_TYPE_INJECTED:"INJECTED",CONNECTOR_TYPE_ANNOUNCED:"ANNOUNCED",CONNECTOR_TYPE_AUTH:"AUTH",CONNECTOR_TYPE_MULTI_CHAIN:"MULTI_CHAIN",CONNECTOR_TYPE_W3M_AUTH:"ID_AUTH"},Dn={ConnectorExplorerIds:{[j.CONNECTOR_ID.COINBASE]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[j.CONNECTOR_ID.COINBASE_SDK]:"fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa",[j.CONNECTOR_ID.SAFE]:"225affb176778569276e484e1b92637ad061b01e13a048b35a9d280c3b58970f",[j.CONNECTOR_ID.LEDGER]:"19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927",[j.CONNECTOR_ID.OKX]:"971e689d0a5be527bac79629b4ee9b925e82208e5168b733496a09c0faed0709",[je.METMASK_CONNECTOR_NAME]:"c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96",[je.TRUST_CONNECTOR_NAME]:"4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0",[je.SOLFLARE_CONNECTOR_NAME]:"1ca0bdd4747578705b1939af023d120677c64fe6ca76add81fda36e350605e79",[je.PHANTOM_CONNECTOR_NAME]:"a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393",[je.COIN98_CONNECTOR_NAME]:"2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01",[je.MAGIC_EDEN_CONNECTOR_NAME]:"8b830a2b724a9c3fbab63af6f55ed29c9dfa8a55e732dc88c80a196a2ba136c6",[je.BACKPACK_CONNECTOR_NAME]:"2bd8c14e035c2d48f184aaa168559e86b0e3433228d3c4075900a221785019b0",[je.BITGET_CONNECTOR_NAME]:"38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662",[je.FRONTIER_CONNECTOR_NAME]:"85db431492aa2e8672e93f4ea7acf10c88b97b867b0d373107af63dc4880f041",[je.XVERSE_CONNECTOR_NAME]:"2a87d74ae02e10bdd1f51f7ce6c4e1cc53cd5f2c0b6b5ad0d7b3007d2b13de7b",[je.LEATHER_CONNECTOR_NAME]:"483afe1df1df63daf313109971ff3ef8356ddf1cc4e45877d205eee0b7893a13"},NetworkImageIds:{1:"ba0ba0cd-17c6-4806-ad93-f9d174f17900",42161:"3bff954d-5cb0-47a0-9a23-d20192e74600",43114:"30c46e53-e989-45fb-4549-be3bd4eb3b00",56:"93564157-2e8e-4ce7-81df-b264dbee9b00",250:"06b26297-fe0c-4733-5d6b-ffa5498aac00",10:"ab9c186a-c52f-464b-2906-ca59d760a400",137:"41d04d42-da3b-4453-8506-668cc0727900",5e3:"e86fae9b-b770-4eea-e520-150e12c81100",295:"6a97d510-cac8-4e58-c7ce-e8681b044c00",11155111:"e909ea0a-f92a-4512-c8fc-748044ea6800",84532:"a18a7ecd-e307-4360-4746-283182228e00",1301:"4eeea7ef-0014-4649-5d1d-07271a80f600",130:"2257980a-3463-48c6-cbac-a42d2a956e00",10143:"0a728e83-bacb-46db-7844-948f05434900",100:"02b53f6a-e3d4-479e-1cb4-21178987d100",9001:"f926ff41-260d-4028-635e-91913fc28e00",324:"b310f07f-4ef7-49f3-7073-2a0a39685800",314:"5a73b3dd-af74-424e-cae0-0de859ee9400",4689:"34e68754-e536-40da-c153-6ef2e7188a00",1088:"3897a66d-40b9-4833-162f-a2c90531c900",1284:"161038da-44ae-4ec7-1208-0ea569454b00",1285:"f1d73bb6-5450-4e18-38f7-fb6484264a00",7777777:"845c60df-d429-4991-e687-91ae45791600",42220:"ab781bbc-ccc6-418d-d32d-789b15da1f00",8453:"7289c336-3981-4081-c5f4-efc26ac64a00",1313161554:"3ff73439-a619-4894-9262-4470c773a100",2020:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",2021:"b8101fc0-9c19-4b6f-ec65-f6dfff106e00",80094:"e329c2c9-59b0-4a02-83e4-212ff3779900",2741:"fc2427d1-5af9-4a9c-8da5-6f94627cd900","5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp":"a1b58899-f671-4276-6a5e-56ca5bd59700","4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z":"a1b58899-f671-4276-6a5e-56ca5bd59700",EtWTRABZaYq6iMfeYKouRu166VU2xqa1:"a1b58899-f671-4276-6a5e-56ca5bd59700","000000000019d6689c085ae165831e93":"0b4838db-0161-4ffe-022d-532bf03dba00","000000000933ea01ad0ee984209779ba":"39354064-d79b-420b-065d-f980c4b78200"},ConnectorImageIds:{[j.CONNECTOR_ID.COINBASE]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[j.CONNECTOR_ID.COINBASE_SDK]:"0c2840c3-5b04-4c44-9661-fbd4b49e1800",[j.CONNECTOR_ID.SAFE]:"461db637-8616-43ce-035a-d89b8a1d5800",[j.CONNECTOR_ID.LEDGER]:"54a1aa77-d202-4f8d-0fb2-5d2bb6db0300",[j.CONNECTOR_ID.WALLET_CONNECT]:"ef1a1fcf-7fe8-4d69-bd6d-fda1345b4400",[j.CONNECTOR_ID.INJECTED]:"07ba87ed-43aa-4adf-4540-9e6a2b9cae00"},ConnectorNamesMap:{[j.CONNECTOR_ID.INJECTED]:"Browser Wallet",[j.CONNECTOR_ID.WALLET_CONNECT]:"WalletConnect",[j.CONNECTOR_ID.COINBASE]:"Coinbase",[j.CONNECTOR_ID.COINBASE_SDK]:"Coinbase",[j.CONNECTOR_ID.LEDGER]:"Ledger",[j.CONNECTOR_ID.SAFE]:"Safe"},ConnectorTypesMap:{[j.CONNECTOR_ID.INJECTED]:"INJECTED",[j.CONNECTOR_ID.WALLET_CONNECT]:"WALLET_CONNECT",[j.CONNECTOR_ID.EIP6963]:"ANNOUNCED",[j.CONNECTOR_ID.AUTH]:"AUTH"},WalletConnectRpcChainIds:[1,5,11155111,10,420,42161,421613,137,80001,42220,1313161554,1313161555,56,97,43114,43113,100,8453,84531,7777777,999,324,280]},Ua={getCaipTokens(t){if(!t)return;const e={};return Object.entries(t).forEach(([s,r])=>{e[`${je.EIP155}:${s}`]=r}),e},isLowerCaseMatch(t,e){return t?.toLowerCase()===e?.toLowerCase()}},lI=new AbortController,Ar={EmbeddedWalletAbortController:lI,UniversalProviderErrors:{UNAUTHORIZED_DOMAIN_NOT_ALLOWED:{message:"Unauthorized: origin not allowed",alertErrorKey:"INVALID_APP_CONFIGURATION"},JWT_VALIDATION_ERROR:{message:"JWT validation error: JWT Token is not yet valid",alertErrorKey:"JWT_TOKEN_NOT_VALID"},INVALID_KEY:{message:"Unauthorized: invalid key",alertErrorKey:"INVALID_PROJECT_ID"}},ALERT_ERRORS:{SWITCH_NETWORK_NOT_FOUND:{shortMessage:"Network Not Found",longMessage:"Network not found - please make sure it is included in 'networks' array in createAppKit function"},INVALID_APP_CONFIGURATION:{shortMessage:"Invalid App Configuration",longMessage:()=>`Origin ${uI()?window.origin:"unknown"} not found on Allowlist - update configuration on cloud.reown.com`},IFRAME_LOAD_FAILED:{shortMessage:"Network Error - Could not load embedded wallet",longMessage:()=>"There was an issue loading the embedded wallet. Please try again later."},IFRAME_REQUEST_TIMEOUT:{shortMessage:"Embedded Wallet Request Timed Out",longMessage:()=>"There was an issue doing the request to the embedded wallet. Please try again later."},UNVERIFIED_DOMAIN:{shortMessage:"Invalid App Configuration",longMessage:()=>"There was an issue loading the embedded wallet. Please verify that your domain is allowed at cloud.reown.com"},JWT_TOKEN_NOT_VALID:{shortMessage:"Session Expired",longMessage:"Invalid session found on UniversalProvider - please check your time settings and connect again"},INVALID_PROJECT_ID:{shortMessage:"Invalid App Configuration",longMessage:"Invalid Project ID - update configuration"},PROJECT_ID_NOT_CONFIGURED:{shortMessage:"Project ID Not Configured",longMessage:"Project ID Not Configured - update configuration on cloud.reown.com"}}};function uI(){return typeof window<"u"}const hI={createLogger(t,e="error"){const s=ji({level:e}),{logger:r}=fu({opts:s});return r.error=(...i)=>{for(const n of i)if(n instanceof Error){t(n,...i);return}t(void 0,...i)},r}},dI="rpc.walletconnect.org";function Xl(t,e){const s=new URL("https://rpc.walletconnect.org/v1/");return s.searchParams.set("chainId",t),s.searchParams.set("projectId",e),s.toString()}const xo=["near:mainnet","solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","eip155:1101","eip155:56","eip155:42161","eip155:7777777","eip155:59144","eip155:324","solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1","eip155:5000","solana:4sgjmw1sunhzsxgspuhpqldx6wiyjntz","eip155:80084","eip155:5003","eip155:100","eip155:8453","eip155:42220","eip155:1313161555","eip155:17000","eip155:1","eip155:300","eip155:1313161554","eip155:1329","eip155:84532","eip155:421614","eip155:11155111","eip155:8217","eip155:43114","solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z","eip155:999999999","eip155:11155420","eip155:80002","eip155:97","eip155:43113","eip155:137","eip155:10","eip155:1301","bip122:000000000019d6689c085ae165831e93","bip122:000000000933ea01ad0ee984209779ba"],Pr={extendRpcUrlWithProjectId(t,e){let s=!1;try{s=new URL(t).host===dI}catch{s=!1}if(s){const r=new URL(t);return r.searchParams.has("projectId")||r.searchParams.set("projectId",e),r.toString()}return t},isCaipNetwork(t){return"chainNamespace"in t&&"caipNetworkId"in t},getChainNamespace(t){return this.isCaipNetwork(t)?t.chainNamespace:j.CHAIN.EVM},getCaipNetworkId(t){return this.isCaipNetwork(t)?t.caipNetworkId:`${j.CHAIN.EVM}:${t.id}`},getDefaultRpcUrl(t,e,s){const r=t.rpcUrls?.default?.http?.[0];return xo.includes(e)?Xl(e,s):r||""},extendCaipNetwork(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:r}){const i=this.getChainNamespace(t),n=this.getCaipNetworkId(t),o=t.rpcUrls.default.http?.[0],a=this.getDefaultRpcUrl(t,n,s),c=t?.rpcUrls?.chainDefault?.http?.[0]||o,l=r?.[n]?.map(d=>d.url)||[],u=[...l,a],h=[...l];return c&&!h.includes(c)&&h.push(c),{...t,chainNamespace:i,caipNetworkId:n,assets:{imageId:Dn.NetworkImageIds[t.id],imageUrl:e?.[t.id]},rpcUrls:{...t.rpcUrls,default:{http:u},chainDefault:{http:h}}}},extendCaipNetworks(t,{customNetworkImageUrls:e,projectId:s,customRpcUrls:r}){return t.map(i=>Pr.extendCaipNetwork(i,{customNetworkImageUrls:e,customRpcUrls:r,projectId:s}))},getViemTransport(t,e,s){const r=[];return s?.forEach(i=>{r.push(Qi(i.url,i.config))}),xo.includes(t.caipNetworkId)&&r.push(Qi(Xl(t.caipNetworkId,e),{fetchOptions:{headers:{"Content-Type":"text/plain"}}})),t?.rpcUrls?.default?.http?.forEach(i=>{r.push(Qi(i))}),Ha(r)},extendWagmiTransports(t,e,s){if(xo.includes(t.caipNetworkId)){const r=this.getDefaultRpcUrl(t,t.caipNetworkId,e);return Ha([s,Qi(r)])}return s},getUnsupportedNetwork(t){return{id:t.split(":")[1],caipNetworkId:t,name:j.UNSUPPORTED_NETWORK_NAME,chainNamespace:t.split(":")[0],nativeCurrency:{name:"",decimals:0,symbol:""},rpcUrls:{default:{http:[]}}}},getCaipNetworkFromStorage(t){const e=W.getActiveCaipNetworkId(),s=g.getAllRequestedCaipNetworks(),r=Array.from(g.state.chains?.keys()||[]),i=e?.split(":")[0],n=i?r.includes(i):!1,o=s?.find(c=>c.caipNetworkId===e);return n&&!o&&e?this.getUnsupportedNetwork(e):o||t||s?.[0]}},Ln={eip155:void 0,solana:void 0,polkadot:void 0,bip122:void 0,cosmos:void 0},pt=Oe({providers:{...Ln},providerIds:{...Ln}}),Te={state:pt,subscribeKey(t,e){return nt(pt,t,e)},subscribe(t){return it(pt,()=>{t(pt)})},subscribeProviders(t){return it(pt.providers,()=>t(pt.providers))},setProvider(t,e){e&&(pt.providers[t]=Xs(e))},getProvider(t){return pt.providers[t]},setProviderId(t,e){e&&(pt.providerIds[t]=e)},getProviderId(t){if(t)return pt.providerIds[t]},reset(){pt.providers={...Ln},pt.providerIds={...Ln}},resetChain(t){pt.providers[t]=void 0,pt.providerIds[t]=void 0}};var Zl={VITE_BASE_URL:"https://cdn.decentraland.org/@dcl/landing-site/0.0.1-23658354807.commit-e695ac8"};const pI={ACCOUNT_TABS:[{label:"Tokens"},{label:"NFTs"},{label:"Activity"}],SECURE_SITE_ORIGIN:(typeof As<"u"&&typeof Zl<"u"?Zl.NEXT_PUBLIC_SECURE_SITE_ORIGIN:void 0)||"https://secure.walletconnect.org",VIEW_DIRECTION:{Next:"next",Prev:"prev"},DEFAULT_CONNECT_METHOD_ORDER:["email","social","wallet"],ANIMATION_DURATIONS:{HeaderText:120,ModalHeight:150,ViewTransition:150}},ga={filterOutDuplicatesByRDNS(t){const e=T.state.enableEIP6963?q.state.connectors:[],s=W.getRecentWallets(),r=e.map(a=>a.info?.rdns).filter(Boolean),i=s.map(a=>a.rdns).filter(Boolean),n=r.concat(i);if(n.includes("io.metamask.mobile")&&X.isMobile()){const a=n.indexOf("io.metamask.mobile");n[a]="io.metamask"}return t.filter(a=>!n.includes(String(a?.rdns)))},filterOutDuplicatesByIds(t){const e=q.state.connectors.filter(a=>a.type==="ANNOUNCED"||a.type==="INJECTED"),s=W.getRecentWallets(),r=e.map(a=>a.explorerId),i=s.map(a=>a.id),n=r.concat(i);return t.filter(a=>!n.includes(a?.id))},filterOutDuplicateWallets(t){const e=this.filterOutDuplicatesByRDNS(t);return this.filterOutDuplicatesByIds(e)},markWalletsAsInstalled(t){const{connectors:e}=q.state,{featuredWalletIds:s}=T.state,r=e.filter(o=>o.type==="ANNOUNCED").reduce((o,a)=>(a.info?.rdns&&(o[a.info.rdns]=!0),o),{});return t.map(o=>({...o,installed:!!o.rdns&&!!r[o.rdns??""]})).sort((o,a)=>{const c=Number(a.installed)-Number(o.installed);if(c!==0)return c;if(s?.length){const l=s.indexOf(o.id),u=s.indexOf(a.id);if(l!==-1&&u!==-1)return l-u;if(l!==-1)return-1;if(u!==-1)return 1}return 0})},getConnectOrderMethod(t,e){const s=t?.connectMethodsOrder||T.state.features?.connectMethodsOrder,r=e||q.state.connectors;if(s)return s;const{injected:i,announced:n}=Nn.getConnectorsByType(r,V.state.recommended,V.state.featured),o=i.filter(Nn.showConnector),a=n.filter(Nn.showConnector);return o.length||a.length?["wallet","email","social"]:pI.DEFAULT_CONNECT_METHOD_ORDER},isExcluded(t){const e=!!t.rdns&&V.state.excludedWallets.some(r=>r.rdns===t.rdns),s=!!t.name&&V.state.excludedWallets.some(r=>Ua.isLowerCaseMatch(r.name,t.name));return e||s}},Nn={getConnectorsByType(t,e,s){const{customWallets:r}=T.state,i=W.getRecentWallets(),n=ga.filterOutDuplicateWallets(e),o=ga.filterOutDuplicateWallets(s),a=t.filter(h=>h.type==="MULTI_CHAIN"),c=t.filter(h=>h.type==="ANNOUNCED"),l=t.filter(h=>h.type==="INJECTED"),u=t.filter(h=>h.type==="EXTERNAL");return{custom:r,recent:i,external:u,multiChain:a,announced:c,injected:l,recommended:n,featured:o}},showConnector(t){const e=t.info?.rdns,s=!!e&&V.state.excludedWallets.some(i=>!!i.rdns&&i.rdns===e),r=!!t.name&&V.state.excludedWallets.some(i=>Ua.isLowerCaseMatch(i.name,t.name));return!(t.type==="INJECTED"&&(t.name==="Browser Wallet"&&(!X.isMobile()||X.isMobile()&&!e&&!Y.checkInstalled())||s||r)||(t.type==="ANNOUNCED"||t.type==="EXTERNAL")&&(s||r))},getIsConnectedWithWC(){return Array.from(g.state.chains.values()).some(s=>q.getConnectorId(s.namespace)===j.CONNECTOR_ID.WALLET_CONNECT)},getConnectorTypeOrder({recommended:t,featured:e,custom:s,recent:r,announced:i,injected:n,multiChain:o,external:a,overriddenConnectors:c=T.state.features?.connectorTypeOrder??[]}){const l=Nn.getIsConnectedWithWC(),d=[{type:"walletConnect",isEnabled:T.state.enableWalletConnect&&!l},{type:"recent",isEnabled:r.length>0},{type:"injected",isEnabled:[...n,...i,...o].length>0},{type:"featured",isEnabled:e.length>0},{type:"custom",isEnabled:s&&s.length>0},{type:"external",isEnabled:a.length>0},{type:"recommended",isEnabled:t.length>0}].filter(f=>f.isEnabled),p=new Set(d.map(f=>f.type)),w=c.filter(f=>p.has(f)).map(f=>({type:f,isEnabled:!0})),m=d.filter(({type:f})=>!w.some(({type:b})=>b===f));return Array.from(new Set([...w,...m].map(({type:f})=>f)))}};/**
15
15
  * @license
16
16
  * Copyright 2019 Google LLC
17
17
  * SPDX-License-Identifier: BSD-3-Clause
@@ -905,4 +905,4 @@ ${t.length}`,s=new TextEncoder().encode(e+t);return"0x"+Ye.from(Tm(s)).toString(
905
905
  .wui-color-fg-350 {
906
906
  background-color: var(--wui-color-fg-350);
907
907
  }
908
- `,bi={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]};function Xi(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const uu=Xi({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"}),hu=Xi({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"});Xi({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"});Xi({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Xi({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const UI={solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},Sn={getMethodsByChainNamespace(t){return UI[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const s={...t},r=new Set;if(e.methods&&Object.keys(e.methods).forEach(i=>r.add(i)),e.chains&&Object.keys(e.chains).forEach(i=>r.add(i)),e.events&&Object.keys(e.events).forEach(i=>r.add(i)),e.rpcMap&&Object.keys(e.rpcMap).forEach(i=>{const[n]=i.split(":");n&&r.add(n)}),r.forEach(i=>{s[i]||(s[i]=this.createDefaultNamespace(i))}),e.methods&&Object.entries(e.methods).forEach(([i,n])=>{s[i]&&(s[i].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([i,n])=>{s[i]&&(s[i].chains=n)}),e.events&&Object.entries(e.events).forEach(([i,n])=>{s[i]&&(s[i].events=n)}),e.rpcMap){const i=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,c]=n.split(":");!a||!c||!s[a]||(s[a].rpcMap||(s[a].rpcMap={}),i.has(a)||(s[a].rpcMap={},i.add(a)),s[a].rpcMap[c]=o)})}return s},createNamespaces(t,e){const s=t.reduce((r,i)=>{const{id:n,chainNamespace:o,rpcUrls:a}=i,c=a.default.http[0];r[o]||(r[o]=this.createDefaultNamespace(o));const l=`${o}:${n}`,u=r[o];switch(u.chains.push(l),l){case uu.caipNetworkId:u.chains.push(uu.deprecatedCaipNetworkId);break;case hu.caipNetworkId:u.chains.push(hu.deprecatedCaipNetworkId);break}return u?.rpcMap&&c&&(u.rpcMap[n]=c),r},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{const e=await Ii.resolveName(t);return(Object.values(e?.addresses)||[])[0]?.address||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],r=e.accounts.map(i=>{const[n,o]=i.split(":");return`${n}:${o}`});return Array.from(new Set([...s,...r]))})},isSessionEventData(t){return typeof t=="object"&&t!==null&&"id"in t&&"topic"in t&&"params"in t&&typeof t.params=="object"&&t.params!==null&&"chainId"in t.params&&"event"in t.params&&typeof t.params.event=="object"&&t.params.event!==null},isOriginAllowed(t,e,s){for(const r of[...e,...s])if(r.includes("*")){const n=`^${r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(n,"u").test(t))return!0}else try{if(new URL(r).origin===t)return!0}catch{if(r===t)return!0}return!1}};class Id{constructor({provider:e,namespace:s}){this.id=j.CONNECTOR_ID.WALLET_CONNECT,this.name=Dn.ConnectorNamesMap[j.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Dn.ConnectorImageIds[j.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=g.getCaipNetworks.bind(g),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=s}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const s=this.getCaipNetworks(),r=T.state.universalProviderConfigOverride,i=Sn.createNamespaces(s,r);await this.provider.connect({optionalNamespaces:i})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(s=>s.caipNetworkId);return Ni.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:DI})}}const DI=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"];class LI{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=s=>g.getCaipNetworks(s),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.getCaipNetworks(this.namespace)}setAuthProvider(e){this.addConnector({id:j.CONNECTOR_ID.AUTH,type:"AUTH",name:j.CONNECTOR_NAMES.AUTH,provider:e,imageId:Dn.ConnectorImageIds[j.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const s=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(r=>s.has(r.id)?!1:(s.add(r.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,s){H.setStatus(e,s)}on(e,s){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(s)}off(e,s){const r=this.eventListeners.get(e);r&&r.delete(s)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const r=this.eventListeners.get(e);r&&r.forEach(i=>i(s))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:s,providerType:r}=e;if(!e.provider)return;const i="provider"in e.provider?e.provider.provider:e.provider;if(r==="WALLET_CONNECT"){i.setDefaultChain(s.caipNetworkId);return}if(i&&r==="AUTH"){const n=i,o=H.state.preferredAccountTypes?.[s.chainNamespace];await n.switchNetwork(s.caipNetworkId);const a=await n.getUser({chainId:s.caipNetworkId,preferredAccountType:o});this.emit("switchNetwork",a)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s instanceof Id);if(!e)throw new Error("WalletConnectConnector not found");return e}}class MI extends LI{setUniversalProvider(e){this.addConnector(new Id({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){const r=this.provider?.session?.namespaces?.[e]?.accounts?.map(i=>{const[,,n]=i.split(":");return n}).filter((i,n,o)=>o.indexOf(i)===n)||[];return Promise.resolve({accounts:r.map(i=>X.createAccount(e,i,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&Ie.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(H.state.balanceLoading&&e.chainId===g.state.activeCaipNetwork?.id)return{balance:H.state.balance||"0.00",symbol:H.state.balanceSymbol||""};const i=(await H.fetchTokenBalance()).find(n=>n.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&n.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:i?.quantity.numeric||"0.00",symbol:i?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:s,message:r,address:i}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return g.state.activeCaipNetwork?.chainNamespace===j.CHAIN.SOLANA?n=(await s.request({method:"solana_signMessage",params:{message:Zu.encode(new TextEncoder().encode(r)),pubkey:i}},g.state.activeCaipNetwork?.caipNetworkId)).signature:n=await s.request({method:"personal_sign",params:[r,i]},g.state.activeCaipNetwork?.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:s}=e,r=this.getWalletConnectConnector();if(s.chainNamespace===j.CHAIN.EVM)try{await r.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:qa(s.id)}]})}catch(i){if(i.code===bi.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||i.code===bi.ERROR_INVALID_CHAIN_ID||i.code===bi.ERROR_CODE_DEFAULT||i?.data?.originalError?.code===bi.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await r.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:qa(s.id),rpcUrls:[s?.rpcUrls.chainDefault?.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[s.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}r.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(r=>r.type==="WALLET_CONNECT")?.provider}}const BI=["email","socials","swaps","onramp","activity","reownBranding"],gn={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(s=>s!=="email"):!1},processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?Ie.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?Ie.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?Ie.DEFAULT_REMOTE_FEATURES.onramp:!1:t},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.activity:!!t},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.reownBranding:!!t}},jI={localSettingsOverridden:new Set,getApiConfig(t,e){return e?.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=gn[e],r=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(r)}},processFeature(t,e,s,r,i){const n=gn[t],o=e[n.localFeatureName];if(i&&!n.isAvailableOnBasic)return!1;if(r){const a=this.getApiConfig(n.apiFeatureName,s);return a?.config===null?this.processFallbackFeature(t,o):a?.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return gn[t].processApi(e)},processFallbackFeature(t,e){return gn[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let r=null,i=!1;try{r=await V.fetchProjectConfig(),i=r!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const n=i&&!e?Ie.DEFAULT_REMOTE_FEATURES:Ie.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of BI){const a=this.processFeature(o,s,r,i,e);Object.assign(n,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),Ie.DEFAULT_REMOTE_FEATURES}if(i&&this.localSettingsOverridden.size>0){const o=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;Fs.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${o}`},"warning")}return n}};class qI{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,r)=>{if(s){const i=g.getNetworkData(s)?.requestedCaipNetworks?.find(a=>a.id===r);if(i)return i;const n=g.getNetworkData(s)?.caipNetwork;return n||g.getRequestedCaipNetworks(s).filter(a=>a.chainNamespace===s)?.[0]}return g.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>g.getCaipNetworks(s),this.getActiveChainNamespace=()=>g.state.activeChain,this.setRequestedCaipNetworks=(s,r)=>{g.setRequestedCaipNetworks(s,r)},this.getApprovedCaipNetworkIds=()=>g.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>g.state.activeChain===s||!s?g.state.activeCaipAddress:g.getAccountProp("caipAddress",s),this.setClientId=s=>{J.setClientId(s)},this.getProvider=s=>Te.getProvider(s),this.getProviderType=s=>Te.getProviderId(s),this.getPreferredAccountType=s=>H.state.preferredAccountTypes?.[s],this.setCaipAddress=(s,r)=>{H.setCaipAddress(s,r),s&&T.state.enableEmbedded&&this.close()},this.setBalance=(s,r,i)=>{H.setBalance(s,r,i)},this.setProfileName=(s,r)=>{H.setProfileName(s,r)},this.setProfileImage=(s,r)=>{H.setProfileImage(s,r)},this.setUser=(s,r)=>{H.setUser(s,r)},this.resetAccount=s=>{H.resetAccount(s)},this.setCaipNetwork=s=>{g.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,r)=>{g.setChainNetworkData(r,{caipNetwork:s})},this.setAllAccounts=(s,r)=>{H.setAllAccounts(s,r),T.setHasMultipleAddresses(s?.length>1)},this.setStatus=(s,r)=>{H.setStatus(s,r),q.isConnected()?W.setConnectionStatus("connected"):W.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>g.getAccountProp("address",s),this.setConnectors=s=>{const r=[...q.state.allConnectors,...s];q.setConnectors(r)},this.setConnections=(s,r)=>{Y.setConnections(s,r)},this.fetchIdentity=s=>J.fetchIdentity(s),this.getReownName=s=>Ii.getNamesForAddress(s),this.getConnectors=()=>q.getConnectors(),this.getConnectorImage=s=>vu.getConnectorImage(s),this.setConnectedWalletInfo=(s,r)=>{const i=Te.getProviderId(r),n=s?{...s,type:i}:void 0;H.setConnectedWalletInfo(n,r)},this.getIsConnectedState=()=>!!g.state.activeCaipAddress,this.addAddressLabel=(s,r,i)=>{H.addAddressLabel(s,r,i)},this.removeAddressLabel=(s,r)=>{H.removeAddressLabel(s,r)},this.getAddress=s=>g.state.activeChain===s||!s?H.state.address:g.getAccountProp("address",s),this.setApprovedCaipNetworksData=s=>g.setApprovedCaipNetworksData(s),this.resetNetwork=s=>{g.resetNetwork(s)},this.addConnector=s=>{q.addConnector(s)},this.resetWcConnection=()=>{Y.resetWcConnection()},this.setAddressExplorerUrl=(s,r)=>{H.setAddressExplorerUrl(s,r)},this.setSmartAccountDeployed=(s,r)=>{H.setSmartAccountDeployed(s,r)},this.setSmartAccountEnabledNetworks=(s,r)=>{g.setSmartAccountEnabledNetworks(s,r)},this.setPreferredAccountType=(s,r)=>{H.setPreferredAccountType(s,r)},this.setEIP6963Enabled=s=>{T.setEIP6963Enabled(s)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,s){const r=e?.map(n=>n.namespace).filter(n=>!!n);if(r?.length)return[...new Set(r)];const i=s?.map(n=>n.chainNamespace);return[...new Set(i)]}async initialize(e){this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),await this.syncExistingConnection(),this.remoteFeatures=await jI.fetchRemoteFeatures(e),T.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&Bo.setOnrampProviders(this.remoteFeatures.onramp),(T.state.remoteFeatures?.email||Array.isArray(T.state.remoteFeatures?.socials)&&T.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await V.fetchAllowedOrigins();if(e&&X.isClient()){const s=window.location.origin;Sn.isOriginAllowed(s,e,bi.DEFAULT_ALLOWED_ANCESTORS)||Fs.open(Ar.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else Fs.open(Ar.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){const{...s}=e;delete s.adapters,delete s.universalProvider,ke.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(r=>r.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&Et.setThemeMode(e.themeMode),e.themeVariables&&Et.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");g.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const s=this.getDefaultNetwork();s&&g.setActiveCaipNetwork(s)}initializeConnectionController(e){Y.setWcBasic(e.basic??!1)}initializeConnectorController(){q.initialize(this.chainNamespaces)}initializeProjectSettings(e){T.setProjectId(e.projectId),T.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){T.setDebug(e.debug!==!1),T.setEnableWalletConnect(e.enableWalletConnect!==!1),T.setEnableWalletGuide(e.enableWalletGuide!==!1),T.setEnableWallets(e.enableWallets!==!1),T.setEIP6963Enabled(e.enableEIP6963!==!1),T.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),T.setEnableAuthLogger(e.enableAuthLogger!==!1),T.setCustomRpcUrls(e.customRpcUrls),T.setEnableEmbedded(e.enableEmbedded),T.setAllWallets(e.allWallets),T.setIncludeWalletIds(e.includeWalletIds),T.setExcludeWalletIds(e.excludeWalletIds),T.setFeaturedWalletIds(e.featuredWalletIds),T.setTokens(e.tokens),T.setTermsConditionsUrl(e.termsConditionsUrl),T.setPrivacyPolicyUrl(e.privacyPolicyUrl),T.setCustomWallets(e.customWallets),T.setFeatures(e.features),T.setAllowUnsupportedChain(e.allowUnsupportedChain),T.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),T.setPreferUniversalLinks(e.experimental_preferUniversalLinks),T.setDefaultAccountTypes(e.defaultAccountTypes);const s=W.getPreferredAccountTypes()||{},r={...T.state.defaultAccountTypes,...s};H.setPreferredAccountTypes(r);const i=this.getDefaultMetaData();if(!e.metadata&&i&&(e.metadata=i),T.setMetadata(e.metadata),T.setDisableAppend(e.disableAppend),T.setEnableEmbedded(e.enableEmbedded),T.setSIWX(e.siwx),!e.projectId){Fs.open(Ar.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(o=>o.namespace===j.CHAIN.EVM)&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");T.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return X.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const r=Pr.getUnsupportedNetwork(`${s}:${e}`);g.setActiveCaipNetwork(r)}}getDefaultNetwork(){return Pr.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,s){return Pr.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return Pr.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(i=>i.id===e.defaultNetwork?.id);return s?Pr.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e){try{const s=this.getAdapter(e),r=Te.getProvider(e),i=Te.getProviderId(e),{caipAddress:n}=g.getAccountData(e)||{};this.setLoading(!0,e),n&&s?.disconnect&&await s.disconnect({provider:r,providerType:i}),W.removeConnectedNamespace(e),Te.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),q.removeConnectorId(e),g.resetAccount(e),g.resetNetwork(e),this.setLoading(!1,e)}catch(s){throw this.setLoading(!1,e),new Error(`Failed to disconnect chain ${e}: ${s.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=g.state.activeChain,s=this.getAdapter(e),r=this.getCaipNetwork(e)?.id;if(!s)throw new Error("Adapter not found");const i=await s.connectWalletConnect(r);this.close(),this.setClientId(i?.clientId||null),W.setConnectedNamespaces([...g.state.chains.keys()]),this.chainNamespaces.forEach(n=>{q.setConnectorId(je.CONNECTOR_TYPE_WALLET_CONNECT,n)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:s,type:r,provider:i,chain:n,caipNetwork:o,socialUri:a})=>{const c=g.state.activeChain,l=n||c,u=this.getAdapter(l);if(n&&n!==c&&!o){const m=this.getCaipNetworks().find(f=>f.chainNamespace===n);m&&this.setCaipNetwork(m)}if(!u)throw new Error("Adapter not found");const h=this.getCaipNetwork(l),d=await u.connect({id:e,info:s,type:r,provider:i,socialUri:a,chainId:o?.id||h?.id,rpcUrl:o?.rpcUrls?.default?.http?.[0]||h?.rpcUrls?.default?.http?.[0]});if(!d)return;W.addConnectedNamespace(l),this.syncProvider({...d,chainNamespace:l});const p=H.state.allAccounts,{accounts:w}=p?.length>0?{accounts:[...p]}:await u.getAccounts({namespace:l,id:e});this.setAllAccounts(w,l),this.setStatus("connected",l),this.syncConnectedWalletInfo(l)},reconnectExternal:async({id:e,info:s,type:r,provider:i})=>{const n=g.state.activeChain,o=this.getAdapter(n);o?.reconnect&&(await o?.reconnect({id:e,info:s,type:r,provider:i,chainId:this.getCaipNetwork()?.id}),W.addConnectedNamespace(n),this.syncConnectedWalletInfo(n))},disconnect:async e=>{const s=cI(e);try{const r=await Promise.allSettled(s.map(async([n])=>this.disconnectNamespace(n)));de.resetSend(),Y.resetWcConnection(),await Ni.clearSessions(),q.setFilterByNamespace(void 0);const i=r.filter(n=>n.status==="rejected");if(i.length>0)throw new Error(i.map(n=>n.reason.message).join(", "));W.deleteConnectedSocialProvider(),ke.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:e||"all"}})}catch(r){throw new Error(`Failed to disconnect chains: ${r.message}`)}},checkInstalled:e=>e?e.some(s=>!!window.ethereum?.[String(s)]):!!window.ethereum,signMessage:async e=>(await this.getAdapter(g.state.activeChain)?.signMessage({message:e,address:H.state.address,provider:Te.getProvider(g.state.activeChain)}))?.signature||"",sendTransaction:async e=>{const s=e.chainNamespace;if(Ie.SEND_SUPPORTED_NAMESPACES.includes(s)){const r=this.getAdapter(g.state.activeChain),i=Te.getProvider(s);return(await r?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}))?.hash||""}return""},estimateGas:async e=>{if(e.chainNamespace===j.CHAIN.EVM){const s=this.getAdapter(g.state.activeChain),r=Te.getProvider(g.state.activeChain),i=this.getCaipNetwork();if(!i)throw new Error("CaipNetwork is undefined");return(await s?.estimateGas({...e,provider:r,caipNetwork:i}))?.gas||0n}return 0n},getEnsAvatar:async()=>(await this.syncIdentity({address:H.state.address,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:g.state.activeChain}),H.state.profileImage||!1),getEnsAddress:async e=>await Sn.resolveReownName(e),writeContract:async e=>{const s=this.getAdapter(g.state.activeChain),r=this.getCaipNetwork(),i=this.getCaipAddress(),n=Te.getProvider(g.state.activeChain);if(!r||!i)throw new Error("CaipNetwork or CaipAddress is undefined");return(await s?.writeContract({...e,caipNetwork:r,provider:n,caipAddress:i}))?.hash},parseUnits:(e,s)=>this.getAdapter(g.state.activeChain)?.parseUnits({value:e,decimals:s})??0n,formatUnits:(e,s)=>this.getAdapter(g.state.activeChain)?.formatUnits({value:e,decimals:s})??"0",getCapabilities:async e=>await this.getAdapter(g.state.activeChain)?.getCapabilities(e),grantPermissions:async e=>await this.getAdapter(g.state.activeChain)?.grantPermissions(e),revokePermissions:async e=>{const s=this.getAdapter(g.state.activeChain);return s?.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>await this.getAdapter(g.state.activeChain)?.walletGetAssets(e)??{},updateBalance:e=>{const s=this.getCaipNetwork(e);!s||!H.state.address||this.updateNativeBalance(H.state.address,s?.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Y.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){if(Te.getProviderId(g.state.activeChain)===je.CONNECTOR_TYPE_WALLET_CONNECT){const s=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(s)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const i=Te.getProvider(s),n=Te.getProviderId(s);if(e.chainNamespace===g.state.activeChain)await this.getAdapter(s)?.switchNetwork({caipNetwork:e,provider:i,providerType:n});else if(this.setCaipNetwork(e),n===je.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(s);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:s})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(s=>{const r=s.chains||[],i=s.accounts.map(n=>{const{chainId:o,chainNamespace:a}=gs.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...r,...i]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,r)=>{const i=e?.find(n=>n.namespace===r);return i?(i.construct({namespace:r,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),s[r]=i):s[r]=new MI({namespace:r,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e),await this.chainAdapters?.[e].syncConnectors(this.options,this),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){this.getAdapter(e)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const r=W.getConnectionStatus();r==="connected"?this.setStatus("connecting",e):r==="disconnected"?(W.clearAddressCache(),this.setStatus(r,e)):this.setStatus(r,e),s.on("switchNetwork",({address:i,chainId:n})=>{const o=this.getCaipNetworks().find(l=>l.id===n||l.caipNetworkId===n),a=g.state.activeChain===e,c=g.getAccountProp("address",e);if(o){const l=a&&i?i:c;l&&this.syncAccount({address:l,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),s.on("disconnect",this.disconnect.bind(this,e)),s.on("connections",i=>{this.setConnections(i,e)}),s.on("pendingTransactions",()=>{const i=H.state.address,n=g.state.activeCaipNetwork;!i||!n?.id||this.updateNativeBalance(i,n.id,n.chainNamespace)}),s.on("accountChanged",({address:i,chainId:n})=>{const o=g.state.activeChain===e;o&&n?this.syncAccount({address:i,chainId:n,chainNamespace:e}):o&&g.state.activeCaipNetwork?.id?this.syncAccount({address:i,chainId:g.state.activeCaipNetwork?.id,chainNamespace:e}):this.syncAccountInfo(i,n,e),this.syncAllAccounts(e)})}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{e===j.CHAIN.EVM&&X.isSafeApp()&&q.setConnectorId(j.CONNECTOR_ID.SAFE,e);const s=q.getConnectorId(e);switch(this.setStatus("connecting",e),s){case j.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case j.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){const s=this.getAdapter(e),r=q.getConnectorId(e),i=this.getCaipNetwork(e),o=q.getConnectors(e).find(a=>a.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!i?.id)throw new Error("CaipNetwork not found");const a=await s?.syncConnection({namespace:e,id:o.id,chainId:i.id,rpcUrl:i?.rpcUrls?.default?.http?.[0]});if(a){const c=await s?.getAccounts({namespace:e,id:o.id});c&&c.accounts.length>0?this.setAllAccounts(c.accounts,e):this.setAllAccounts([X.createAccount(e,a.address,"eoa")],e),this.syncProvider({...a,chainNamespace:e}),await this.syncAccount({...a,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async s=>{const r=this.getAdapter(s),i=this.universalProvider?.session?.namespaces?.[s]?.accounts||[],n=g.state.activeCaipNetwork?.id,o=i.find(a=>{const{chainId:c}=gs.parseCaipAddress(a);return c===n?.toString()})||i[0];if(o){const a=gs.validateCaipAddress(o),{chainId:c,address:l}=gs.parseCaipAddress(a);if(Te.setProviderId(s,je.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&g.state.activeCaipNetwork&&r?.namespace!==j.CHAIN.EVM){const u=r?.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:g.state.activeCaipNetwork});Te.setProvider(s,u)}else Te.setProvider(s,this.universalProvider);q.setConnectorId(j.CONNECTOR_ID.WALLET_CONNECT,s),W.addConnectedNamespace(s),this.syncWalletConnectAccounts(s),await this.syncAccount({address:l,chainId:c,chainNamespace:s})}else this.setStatus("disconnected",s);this.syncConnectedWalletInfo(s),await g.setApprovedCaipNetworksData(s)});await Promise.all(e)}syncWalletConnectAccounts(e){const s=this.universalProvider?.session?.namespaces?.[e]?.accounts?.map(r=>{const{address:i}=gs.parseCaipAddress(r);return i}).filter((r,i,n)=>n.indexOf(r)===i);s&&this.setAllAccounts(s.map(r=>X.createAccount(e,r,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:s,id:r,chainNamespace:i}){Te.setProviderId(i,e),Te.setProvider(i,s),q.setConnectorId(r,i)}async syncAllAccounts(e){const s=q.getConnectorId(e);if(!s)return;const i=await this.getAdapter(e)?.getAccounts({namespace:e,id:s});i&&i.accounts.length>0&&this.setAllAccounts(i.accounts,e)}async syncAccount(e){const s=e.chainNamespace===g.state.activeChain,r=g.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:i,chainId:n,chainNamespace:o}=e,{chainId:a}=W.getActiveNetworkProps(),c=n||a,l=g.state.activeCaipNetwork?.name===j.UNSUPPORTED_NETWORK_NAME,u=g.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!u)&&c){let h=this.getCaipNetworks().find(w=>w.id.toString()===c.toString()),d=this.getCaipNetworks().find(w=>w.chainNamespace===o);if(!u&&!h&&!d){const w=this.getApprovedCaipNetworkIds()||[],m=w.find(y=>gs.parseCaipNetworkId(y)?.chainId===c.toString()),f=w.find(y=>gs.parseCaipNetworkId(y)?.chainNamespace===o);h=this.getCaipNetworks().find(y=>y.caipNetworkId===m),d=this.getCaipNetworks().find(y=>y.caipNetworkId===f||"deprecatedCaipNetworkId"in y&&y.deprecatedCaipNetworkId===f)}const p=h||d;p?.chainNamespace===g.state.activeChain?T.state.enableNetworkSwitch&&!T.state.allowUnsupportedChain&&g.state.activeCaipNetwork?.name===j.UNSUPPORTED_NETWORK_NAME?g.showUnsupportedChainUI():this.setCaipNetwork(p):s||r&&this.setCaipNetworkOfNamespace(r,o),this.syncConnectedWalletInfo(o),Ua.isLowerCaseMatch(i,H.state.address)||this.syncAccountInfo(i,p?.id,o),s?await this.syncBalance({address:i,chainId:p?.id,chainNamespace:o}):await this.syncBalance({address:i,chainId:r?.id,chainNamespace:o})}}async syncAccountInfo(e,s,r){const i=this.getCaipAddress(r),n=s||i?.split(":")[1];if(!n)return;const o=`${r}:${n}:${e}`;this.setCaipAddress(o,r),await this.syncIdentity({address:e,chainId:n,chainNamespace:r})}async syncReownName(e,s){try{const r=await this.getReownName(e);if(r[0]){const i=r[0];this.setProfileName(i.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){const s=q.getConnectorId(e),r=Te.getProviderId(e);if(r===je.CONNECTOR_TYPE_ANNOUNCED||r===je.CONNECTOR_TYPE_INJECTED){if(s){const i=this.getConnectors().find(n=>n.id===s);if(i){const{info:n,name:o,imageUrl:a}=i,c=a||this.getConnectorImage(i);this.setConnectedWalletInfo({name:o,icon:c,...n},e)}}}else if(r===je.CONNECTOR_TYPE_WALLET_CONNECT){const i=Te.getProvider(e);i?.session&&this.setConnectedWalletInfo({...i.session.peer.metadata,name:i.session.peer.metadata.name,icon:i.session.peer.metadata.icons?.[0]},e)}else if(s&&s===j.CONNECTOR_ID.COINBASE){const i=this.getConnectors().find(n=>n.id===j.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(i)},e)}}async syncBalance(e){!mu.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(r=>r.id.toString()===e.chainId?.toString())||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,r){const i=this.getAdapter(r),n=g.getCaipNetworkByNamespace(r,s);if(i){const o=await i.getBalance({address:e,chainId:s,caipNetwork:n,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,r),o}}async initializeUniversalAdapter(){const e=hI.createLogger((r,...i)=>{r&&this.handleAlertError(r),console.error(...i)}),s={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};T.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await aI.init(s),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Y.setUri(e)}),this.universalProvider.on("connect",Y.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Y.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const s=this.getCaipNetworks().find(i=>i.id==e),r=this.getCaipNetwork();if(!s){this.setUnsupportedNetwork(e);return}r?.id!==s?.id&&this.setCaipNetwork(s)}),this.universalProvider.on("session_event",e=>{if(Sn.isSessionEventData(e)){const{name:s,data:r}=e.params.event;s==="accountsChanged"&&Array.isArray(r)&&X.isCaipAddress(r[0])&&this.syncAccount(gs.parseCaipAddress(r[0]))}}))}createUniversalProvider(){return!this.universalProviderInitPromise&&X.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){ke.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const s=Object.entries(Ar.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[r,i]=s??[],{message:n,alertErrorKey:o}=i??{};if(r&&n&&!this.reportedAlertErrors[r]){const a=Ar.ALERT_ERRORS[o];a&&(Fs.open(a,"error"),this.reportedAlertErrors[r]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const r=e;r.namespace=s,r.construct({namespace:s,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=r)}async open(e){if(await this.injectModalUi(),e?.uri&&Y.setUri(e.uri),e?.arguments)switch(e?.view){case"Swap":return Ge.open({...e,data:{swap:e.arguments}})}return Ge.open(e)}async close(){await this.injectModalUi(),Ge.close()}setLoading(e,s){Ge.setLoading(e,s)}async disconnect(e){await Y.disconnect(e)}getSIWX(){return T.state.siwx}getError(){return""}getChainId(){return g.state.activeCaipNetwork?.id}async switchNetwork(e){const s=this.getCaipNetworks().find(r=>r.id===e.id);if(!s){Fs.open(Ar.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await g.switchActiveNetwork(s)}getWalletProvider(){return g.state.activeChain?Te.state.providers[g.state.activeChain]:null}getWalletProviderType(){return Te.getProviderId(g.state.activeChain)}subscribeProviders(e){return Te.subscribeProviders(e)}getThemeMode(){return Et.state.themeMode}getThemeVariables(){return Et.state.themeVariables}setThemeMode(e){Et.setThemeMode(e),Cd(Et.state.themeMode)}setTermsConditionsUrl(e){T.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){T.setPrivacyPolicyUrl(e)}setThemeVariables(e){Et.setThemeVariables(e),RI(Et.state.themeVariables)}subscribeTheme(e){return Et.subscribe(e)}getWalletInfo(){return H.state.connectedWalletInfo}getAccount(e){const s=q.getAuthConnector(e),r=g.getAccountData(e),i=g.state.activeChain,n=W.getConnectedConnectorId(e||i);if(r)return{allAccounts:r.allAccounts,caipAddress:r.caipAddress,address:X.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:s&&n===j.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:W.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:r.preferredAccountTypes?.[e||i],isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const r=()=>{const i=this.getAccount(s);i&&e(i)};s?g.subscribeChainProp("accountState",r,s):g.subscribe(r),q.subscribe(r)}subscribeNetwork(e){return g.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s?.id,caipNetworkId:s?.caipNetworkId})})}subscribeWalletInfo(e){return H.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){H.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){g.subscribeKey("activeCaipNetwork",e)}getState(){return Ss.state}subscribeState(e){return Ss.subscribe(e)}showErrorMessage(e){Ft.showError(e)}showSuccessMessage(e){Ft.showSuccess(e)}getEvent(){return{...ke.state}}subscribeEvents(e){return ke.subscribe(e)}replace(e){ie.replace(e)}redirect(e){ie.push(e)}popTransactionStack(e){ie.popTransactionStack(e)}isOpen(){return Ge.state.open}isTransactionStackEmpty(){return ie.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){T.setFeatures(e)}updateRemoteFeatures(e){T.setRemoteFeatures(e)}updateOptions(e){const r={...T.state||{},...e};T.setOptions(r)}setConnectMethodsOrder(e){T.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){T.setWalletFeaturesOrder(e)}setCollapseWallets(e){T.setCollapseWallets(e)}setSocialsOrder(e){T.setSocialsOrder(e)}getConnectMethodsOrder(){return ga.getConnectOrderMethod(T.state.features,q.getConnectors())}addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const r=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(i=>i.id===r.id)||g.addNetwork(r)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(i=>i.id===s)&&g.removeNetwork(e,s)}}let du=!1;class Nd extends qI{async open(e){q.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Y.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!du&&X.isClient()){if(await Ro(()=>import("./basic-D7Il4b80.js"),__vite__mapDeps([5,6,1,2,3,4])),await Ro(()=>import("./w3m-modal-C_X8MD6y.js"),__vite__mapDeps([7,6,1,2,3,4])),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!T.state.disableAppend&&!T.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}du=!0}}}const FI="1.7.8";function WI(t){return new Nd({...t,basic:!0,sdkVersion:`html-core-${FI}`})}const SN=Object.freeze(Object.defineProperty({__proto__:null,AppKit:Nd,createAppKit:WI},Symbol.toStringTag,{value:"Module"}));export{V as A,pI as B,q as C,H as D,ke as E,IN as F,hN as G,wg as H,hc as I,Ku as J,ag as K,yg as L,Ge as M,dN as N,T as O,uN as P,Wn as Q,ie as R,W as S,Et as T,pN as U,fN as V,ga as W,SN as X,An as a,EN as b,X as c,Nn as d,_N as e,vu as f,Y as g,j as h,Lr as i,g as j,qt as k,Ft as l,Ie as m,Ke as n,AN as o,md as p,Gr as q,NN as r,Oe as s,St as t,ma as u,it as v,CN as w,nt as x,Ni as y,Fs as z};
908
+ `,bi={ERROR_CODE_UNRECOGNIZED_CHAIN_ID:4902,ERROR_CODE_DEFAULT:5e3,ERROR_INVALID_CHAIN_ID:32603,DEFAULT_ALLOWED_ANCESTORS:["http://localhost:*","https://*.pages.dev","https://*.vercel.app","https://*.ngrok-free.app","https://secure-mobile.walletconnect.com","https://secure-mobile.walletconnect.org"]};function Xi(t){return{formatters:void 0,fees:void 0,serializers:void 0,...t}}const uu=Xi({id:"5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",name:"Solana",network:"solana-mainnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!1,chainNamespace:"solana",caipNetworkId:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",deprecatedCaipNetworkId:"solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"}),hu=Xi({id:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1",name:"Solana Devnet",network:"solana-devnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",deprecatedCaipNetworkId:"solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K"});Xi({id:"4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",name:"Solana Testnet",network:"solana-testnet",nativeCurrency:{name:"Solana",symbol:"SOL",decimals:9},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},blockExplorers:{default:{name:"Solscan",url:"https://solscan.io"}},testnet:!0,chainNamespace:"solana",caipNetworkId:"solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z"});Xi({id:"000000000019d6689c085ae165831e93",caipNetworkId:"bip122:000000000019d6689c085ae165831e93",chainNamespace:"bip122",name:"Bitcoin",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}});Xi({id:"000000000933ea01ad0ee984209779ba",caipNetworkId:"bip122:000000000933ea01ad0ee984209779ba",chainNamespace:"bip122",name:"Bitcoin Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}},testnet:!0});const UI={solana:["solana_signMessage","solana_signTransaction","solana_requestAccounts","solana_getAccounts","solana_signAllTransactions","solana_signAndSendTransaction"],eip155:["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_showCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"],bip122:["sendTransfer","signMessage","signPsbt","getAccountAddresses"]},Sn={getMethodsByChainNamespace(t){return UI[t]||[]},createDefaultNamespace(t){return{methods:this.getMethodsByChainNamespace(t),events:["accountsChanged","chainChanged"],chains:[],rpcMap:{}}},applyNamespaceOverrides(t,e){if(!e)return{...t};const s={...t},r=new Set;if(e.methods&&Object.keys(e.methods).forEach(i=>r.add(i)),e.chains&&Object.keys(e.chains).forEach(i=>r.add(i)),e.events&&Object.keys(e.events).forEach(i=>r.add(i)),e.rpcMap&&Object.keys(e.rpcMap).forEach(i=>{const[n]=i.split(":");n&&r.add(n)}),r.forEach(i=>{s[i]||(s[i]=this.createDefaultNamespace(i))}),e.methods&&Object.entries(e.methods).forEach(([i,n])=>{s[i]&&(s[i].methods=n)}),e.chains&&Object.entries(e.chains).forEach(([i,n])=>{s[i]&&(s[i].chains=n)}),e.events&&Object.entries(e.events).forEach(([i,n])=>{s[i]&&(s[i].events=n)}),e.rpcMap){const i=new Set;Object.entries(e.rpcMap).forEach(([n,o])=>{const[a,c]=n.split(":");!a||!c||!s[a]||(s[a].rpcMap||(s[a].rpcMap={}),i.has(a)||(s[a].rpcMap={},i.add(a)),s[a].rpcMap[c]=o)})}return s},createNamespaces(t,e){const s=t.reduce((r,i)=>{const{id:n,chainNamespace:o,rpcUrls:a}=i,c=a.default.http[0];r[o]||(r[o]=this.createDefaultNamespace(o));const l=`${o}:${n}`,u=r[o];switch(u.chains.push(l),l){case uu.caipNetworkId:u.chains.push(uu.deprecatedCaipNetworkId);break;case hu.caipNetworkId:u.chains.push(hu.deprecatedCaipNetworkId);break}return u?.rpcMap&&c&&(u.rpcMap[n]=c),r},{});return this.applyNamespaceOverrides(s,e)},resolveReownName:async t=>{const e=await Ii.resolveName(t);return(Object.values(e?.addresses)||[])[0]?.address||!1},getChainsFromNamespaces(t={}){return Object.values(t).flatMap(e=>{const s=e.chains||[],r=e.accounts.map(i=>{const[n,o]=i.split(":");return`${n}:${o}`});return Array.from(new Set([...s,...r]))})},isSessionEventData(t){return typeof t=="object"&&t!==null&&"id"in t&&"topic"in t&&"params"in t&&typeof t.params=="object"&&t.params!==null&&"chainId"in t.params&&"event"in t.params&&typeof t.params.event=="object"&&t.params.event!==null},isOriginAllowed(t,e,s){for(const r of[...e,...s])if(r.includes("*")){const n=`^${r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replace(/\\\*/gu,".*")}$`;if(new RegExp(n,"u").test(t))return!0}else try{if(new URL(r).origin===t)return!0}catch{if(r===t)return!0}return!1}};class Id{constructor({provider:e,namespace:s}){this.id=j.CONNECTOR_ID.WALLET_CONNECT,this.name=Dn.ConnectorNamesMap[j.CONNECTOR_ID.WALLET_CONNECT],this.type="WALLET_CONNECT",this.imageId=Dn.ConnectorImageIds[j.CONNECTOR_ID.WALLET_CONNECT],this.getCaipNetworks=g.getCaipNetworks.bind(g),this.caipNetworks=this.getCaipNetworks(),this.provider=e,this.chain=s}get chains(){return this.getCaipNetworks()}async connectWalletConnect(){if(!await this.authenticate()){const s=this.getCaipNetworks(),r=T.state.universalProviderConfigOverride,i=Sn.createNamespaces(s,r);await this.provider.connect({optionalNamespaces:i})}return{clientId:await this.provider.client.core.crypto.getClientId(),session:this.provider.session}}async disconnect(){await this.provider.disconnect()}async authenticate(){const e=this.chains.map(s=>s.caipNetworkId);return Ni.universalProviderAuthenticate({universalProvider:this.provider,chains:e,methods:DI})}}const DI=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_getCallsStatus","wallet_sendCalls","wallet_getCapabilities","wallet_grantPermissions","wallet_revokePermissions","wallet_getAssets"];class LI{constructor(e){this.availableConnectors=[],this.eventListeners=new Map,this.getCaipNetworks=s=>g.getCaipNetworks(s),e&&this.construct(e)}construct(e){this.projectId=e.projectId,this.namespace=e.namespace,this.adapterType=e.adapterType}get connectors(){return this.availableConnectors}get networks(){return this.getCaipNetworks(this.namespace)}setAuthProvider(e){this.addConnector({id:j.CONNECTOR_ID.AUTH,type:"AUTH",name:j.CONNECTOR_NAMES.AUTH,provider:e,imageId:Dn.ConnectorImageIds[j.CONNECTOR_ID.AUTH],chain:this.namespace,chains:[]})}addConnector(...e){const s=new Set;this.availableConnectors=[...e,...this.availableConnectors].filter(r=>s.has(r.id)?!1:(s.add(r.id),!0)),this.emit("connectors",this.availableConnectors)}setStatus(e,s){H.setStatus(e,s)}on(e,s){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e)?.add(s)}off(e,s){const r=this.eventListeners.get(e);r&&r.delete(s)}removeAllEventListeners(){this.eventListeners.forEach(e=>{e.clear()})}emit(e,s){const r=this.eventListeners.get(e);r&&r.forEach(i=>i(s))}async connectWalletConnect(e){return{clientId:(await this.getWalletConnectConnector().connectWalletConnect()).clientId}}async switchNetwork(e){const{caipNetwork:s,providerType:r}=e;if(!e.provider)return;const i="provider"in e.provider?e.provider.provider:e.provider;if(r==="WALLET_CONNECT"){i.setDefaultChain(s.caipNetworkId);return}if(i&&r==="AUTH"){const n=i,o=H.state.preferredAccountTypes?.[s.chainNamespace];await n.switchNetwork(s.caipNetworkId);const a=await n.getUser({chainId:s.caipNetworkId,preferredAccountType:o});this.emit("switchNetwork",a)}}getWalletConnectConnector(){const e=this.connectors.find(s=>s instanceof Id);if(!e)throw new Error("WalletConnectConnector not found");return e}}class MI extends LI{setUniversalProvider(e){this.addConnector(new Id({provider:e,caipNetworks:this.getCaipNetworks(),namespace:this.namespace}))}async connect(e){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:Number(e.chainId),provider:this.provider,address:""})}async disconnect(){try{await this.getWalletConnectConnector().disconnect()}catch(e){console.warn("UniversalAdapter:disconnect - error",e)}}async getAccounts({namespace:e}){const r=this.provider?.session?.namespaces?.[e]?.accounts?.map(i=>{const[,,n]=i.split(":");return n}).filter((i,n,o)=>o.indexOf(i)===n)||[];return Promise.resolve({accounts:r.map(i=>X.createAccount(e,i,e==="bip122"?"payment":"eoa"))})}async syncConnectors(){return Promise.resolve()}async getBalance(e){if(!(e.caipNetwork&&Ie.BALANCE_SUPPORTED_CHAINS.includes(e.caipNetwork?.chainNamespace))||e.caipNetwork?.testnet)return{balance:"0.00",symbol:e.caipNetwork?.nativeCurrency.symbol||""};if(H.state.balanceLoading&&e.chainId===g.state.activeCaipNetwork?.id)return{balance:H.state.balance||"0.00",symbol:H.state.balanceSymbol||""};const i=(await H.fetchTokenBalance()).find(n=>n.chainId===`${e.caipNetwork?.chainNamespace}:${e.chainId}`&&n.symbol===e.caipNetwork?.nativeCurrency.symbol);return{balance:i?.quantity.numeric||"0.00",symbol:i?.symbol||e.caipNetwork?.nativeCurrency.symbol||""}}async signMessage(e){const{provider:s,message:r,address:i}=e;if(!s)throw new Error("UniversalAdapter:signMessage - provider is undefined");let n="";return g.state.activeCaipNetwork?.chainNamespace===j.CHAIN.SOLANA?n=(await s.request({method:"solana_signMessage",params:{message:Zu.encode(new TextEncoder().encode(r)),pubkey:i}},g.state.activeCaipNetwork?.caipNetworkId)).signature:n=await s.request({method:"personal_sign",params:[r,i]},g.state.activeCaipNetwork?.caipNetworkId),{signature:n}}async estimateGas(){return Promise.resolve({gas:BigInt(0)})}async sendTransaction(){return Promise.resolve({hash:""})}walletGetAssets(e){return Promise.resolve({})}async writeContract(){return Promise.resolve({hash:""})}parseUnits(){return 0n}formatUnits(){return"0"}async getCapabilities(){return Promise.resolve({})}async grantPermissions(){return Promise.resolve({})}async revokePermissions(){return Promise.resolve("0x")}async syncConnection(){return Promise.resolve({id:"WALLET_CONNECT",type:"WALLET_CONNECT",chainId:1,provider:this.provider,address:""})}async switchNetwork(e){const{caipNetwork:s}=e,r=this.getWalletConnectConnector();if(s.chainNamespace===j.CHAIN.EVM)try{await r.provider?.request({method:"wallet_switchEthereumChain",params:[{chainId:qa(s.id)}]})}catch(i){if(i.code===bi.ERROR_CODE_UNRECOGNIZED_CHAIN_ID||i.code===bi.ERROR_INVALID_CHAIN_ID||i.code===bi.ERROR_CODE_DEFAULT||i?.data?.originalError?.code===bi.ERROR_CODE_UNRECOGNIZED_CHAIN_ID)try{await r.provider?.request({method:"wallet_addEthereumChain",params:[{chainId:qa(s.id),rpcUrls:[s?.rpcUrls.chainDefault?.http],chainName:s.name,nativeCurrency:s.nativeCurrency,blockExplorerUrls:[s.blockExplorers?.default.url]}]})}catch{throw new Error("Chain is not supported")}}r.provider.setDefaultChain(s.caipNetworkId)}getWalletConnectProvider(){return this.connectors.find(r=>r.type==="WALLET_CONNECT")?.provider}}const BI=["email","socials","swaps","onramp","activity","reownBranding"],gn={email:{apiFeatureName:"social_login",localFeatureName:"email",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return!!t.isEnabled&&e.includes("email")},processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.email:!!t},socials:{apiFeatureName:"social_login",localFeatureName:"socials",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e.filter(s=>s!=="email"):!1},processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.socials:typeof t=="boolean"?t?Ie.DEFAULT_REMOTE_FEATURES.socials:!1:t},swaps:{apiFeatureName:"swap",localFeatureName:"swaps",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.swaps:typeof t=="boolean"?t?Ie.DEFAULT_REMOTE_FEATURES.swaps:!1:t},onramp:{apiFeatureName:"onramp",localFeatureName:"onramp",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>{if(!t?.config)return!1;const e=t.config;return t.isEnabled&&e.length>0?e:!1},processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.onramp:typeof t=="boolean"?t?Ie.DEFAULT_REMOTE_FEATURES.onramp:!1:t},activity:{apiFeatureName:"activity",localFeatureName:"history",returnType:!1,isLegacy:!0,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.activity:!!t},reownBranding:{apiFeatureName:"reown_branding",localFeatureName:"reownBranding",returnType:!1,isLegacy:!1,isAvailableOnBasic:!1,processApi:t=>!!t.isEnabled,processFallback:t=>t===void 0?Ie.DEFAULT_REMOTE_FEATURES.reownBranding:!!t}},jI={localSettingsOverridden:new Set,getApiConfig(t,e){return e?.find(s=>s.id===t)},addWarning(t,e){if(t!==void 0){const s=gn[e],r=s.isLegacy?`"features.${s.localFeatureName}" (now "${e}")`:`"features.${e}"`;this.localSettingsOverridden.add(r)}},processFeature(t,e,s,r,i){const n=gn[t],o=e[n.localFeatureName];if(i&&!n.isAvailableOnBasic)return!1;if(r){const a=this.getApiConfig(n.apiFeatureName,s);return a?.config===null?this.processFallbackFeature(t,o):a?.config?(o!==void 0&&this.addWarning(o,t),this.processApiFeature(t,a)):!1}return this.processFallbackFeature(t,o)},processApiFeature(t,e){return gn[t].processApi(e)},processFallbackFeature(t,e){return gn[t].processFallback(e)},async fetchRemoteFeatures(t){const e=t.basic??!1,s=t.features||{};this.localSettingsOverridden.clear();let r=null,i=!1;try{r=await V.fetchProjectConfig(),i=r!=null}catch(o){console.warn("[Reown Config] Failed to fetch remote project configuration. Using local/default values.",o)}const n=i&&!e?Ie.DEFAULT_REMOTE_FEATURES:Ie.DEFAULT_REMOTE_FEATURES_DISABLED;try{for(const o of BI){const a=this.processFeature(o,s,r,i,e);Object.assign(n,{[o]:a})}}catch(o){return console.warn("[Reown Config] Failed to process the configuration from Cloud. Using default values.",o),Ie.DEFAULT_REMOTE_FEATURES}if(i&&this.localSettingsOverridden.size>0){const o=`Your local configuration for ${Array.from(this.localSettingsOverridden).join(", ")} was ignored because a remote configuration was successfully fetched. Please manage these features via your project dashboard on dashboard.reown.com.`;Fs.open({shortMessage:"Local configuration ignored",longMessage:`[Reown Config Notice] ${o}`},"warning")}return n}};class qI{constructor(e){this.chainNamespaces=[],this.remoteFeatures={},this.reportedAlertErrors={},this.getCaipNetwork=(s,r)=>{if(s){const i=g.getNetworkData(s)?.requestedCaipNetworks?.find(a=>a.id===r);if(i)return i;const n=g.getNetworkData(s)?.caipNetwork;return n||g.getRequestedCaipNetworks(s).filter(a=>a.chainNamespace===s)?.[0]}return g.state.activeCaipNetwork||this.defaultCaipNetwork},this.getCaipNetworkId=()=>{const s=this.getCaipNetwork();if(s)return s.id},this.getCaipNetworks=s=>g.getCaipNetworks(s),this.getActiveChainNamespace=()=>g.state.activeChain,this.setRequestedCaipNetworks=(s,r)=>{g.setRequestedCaipNetworks(s,r)},this.getApprovedCaipNetworkIds=()=>g.getAllApprovedCaipNetworkIds(),this.getCaipAddress=s=>g.state.activeChain===s||!s?g.state.activeCaipAddress:g.getAccountProp("caipAddress",s),this.setClientId=s=>{J.setClientId(s)},this.getProvider=s=>Te.getProvider(s),this.getProviderType=s=>Te.getProviderId(s),this.getPreferredAccountType=s=>H.state.preferredAccountTypes?.[s],this.setCaipAddress=(s,r)=>{H.setCaipAddress(s,r),s&&T.state.enableEmbedded&&this.close()},this.setBalance=(s,r,i)=>{H.setBalance(s,r,i)},this.setProfileName=(s,r)=>{H.setProfileName(s,r)},this.setProfileImage=(s,r)=>{H.setProfileImage(s,r)},this.setUser=(s,r)=>{H.setUser(s,r)},this.resetAccount=s=>{H.resetAccount(s)},this.setCaipNetwork=s=>{g.setActiveCaipNetwork(s)},this.setCaipNetworkOfNamespace=(s,r)=>{g.setChainNetworkData(r,{caipNetwork:s})},this.setAllAccounts=(s,r)=>{H.setAllAccounts(s,r),T.setHasMultipleAddresses(s?.length>1)},this.setStatus=(s,r)=>{H.setStatus(s,r),q.isConnected()?W.setConnectionStatus("connected"):W.setConnectionStatus("disconnected")},this.getAddressByChainNamespace=s=>g.getAccountProp("address",s),this.setConnectors=s=>{const r=[...q.state.allConnectors,...s];q.setConnectors(r)},this.setConnections=(s,r)=>{Y.setConnections(s,r)},this.fetchIdentity=s=>J.fetchIdentity(s),this.getReownName=s=>Ii.getNamesForAddress(s),this.getConnectors=()=>q.getConnectors(),this.getConnectorImage=s=>vu.getConnectorImage(s),this.setConnectedWalletInfo=(s,r)=>{const i=Te.getProviderId(r),n=s?{...s,type:i}:void 0;H.setConnectedWalletInfo(n,r)},this.getIsConnectedState=()=>!!g.state.activeCaipAddress,this.addAddressLabel=(s,r,i)=>{H.addAddressLabel(s,r,i)},this.removeAddressLabel=(s,r)=>{H.removeAddressLabel(s,r)},this.getAddress=s=>g.state.activeChain===s||!s?H.state.address:g.getAccountProp("address",s),this.setApprovedCaipNetworksData=s=>g.setApprovedCaipNetworksData(s),this.resetNetwork=s=>{g.resetNetwork(s)},this.addConnector=s=>{q.addConnector(s)},this.resetWcConnection=()=>{Y.resetWcConnection()},this.setAddressExplorerUrl=(s,r)=>{H.setAddressExplorerUrl(s,r)},this.setSmartAccountDeployed=(s,r)=>{H.setSmartAccountDeployed(s,r)},this.setSmartAccountEnabledNetworks=(s,r)=>{g.setSmartAccountEnabledNetworks(s,r)},this.setPreferredAccountType=(s,r)=>{H.setPreferredAccountType(s,r)},this.setEIP6963Enabled=s=>{T.setEIP6963Enabled(s)},this.handleUnsafeRPCRequest=()=>{if(this.isOpen()){if(this.isTransactionStackEmpty())return;this.redirect("ApproveTransaction")}else this.open({view:"ApproveTransaction"})},this.options=e,this.version=e.sdkVersion,this.caipNetworks=this.extendCaipNetworks(e),this.chainNamespaces=this.getChainNamespacesSet(e.adapters,this.caipNetworks),this.defaultCaipNetwork=this.extendDefaultCaipNetwork(e),this.chainAdapters=this.createAdapters(e.adapters),this.readyPromise=this.initialize(e)}getChainNamespacesSet(e,s){const r=e?.map(n=>n.namespace).filter(n=>!!n);if(r?.length)return[...new Set(r)];const i=s?.map(n=>n.chainNamespace);return[...new Set(i)]}async initialize(e){this.initializeProjectSettings(e),this.initControllers(e),await this.initChainAdapters(),this.sendInitializeEvent(e),await this.syncExistingConnection(),this.remoteFeatures=await jI.fetchRemoteFeatures(e),T.setRemoteFeatures(this.remoteFeatures),this.remoteFeatures.onramp&&Bo.setOnrampProviders(this.remoteFeatures.onramp),(T.state.remoteFeatures?.email||Array.isArray(T.state.remoteFeatures?.socials)&&T.state.remoteFeatures?.socials.length>0)&&await this.checkAllowedOrigins()}async checkAllowedOrigins(){const e=await V.fetchAllowedOrigins();if(e&&X.isClient()){const s=window.location.origin;Sn.isOriginAllowed(s,e,bi.DEFAULT_ALLOWED_ANCESTORS)||Fs.open(Ar.ALERT_ERRORS.INVALID_APP_CONFIGURATION,"error")}else Fs.open(Ar.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error")}sendInitializeEvent(e){const{...s}=e;delete s.adapters,delete s.universalProvider,ke.sendEvent({type:"track",event:"INITIALIZE",properties:{...s,networks:e.networks.map(r=>r.id),siweConfig:{options:e.siweConfig?.options||{}}}})}initControllers(e){this.initializeOptionsController(e),this.initializeChainController(e),this.initializeThemeController(e),this.initializeConnectionController(e),this.initializeConnectorController()}initializeThemeController(e){e.themeMode&&Et.setThemeMode(e.themeMode),e.themeVariables&&Et.setThemeVariables(e.themeVariables)}initializeChainController(e){if(!this.connectionControllerClient||!this.networkControllerClient)throw new Error("ConnectionControllerClient and NetworkControllerClient must be set");g.initialize(e.adapters??[],this.caipNetworks,{connectionControllerClient:this.connectionControllerClient,networkControllerClient:this.networkControllerClient});const s=this.getDefaultNetwork();s&&g.setActiveCaipNetwork(s)}initializeConnectionController(e){Y.setWcBasic(e.basic??!1)}initializeConnectorController(){q.initialize(this.chainNamespaces)}initializeProjectSettings(e){T.setProjectId(e.projectId),T.setSdkVersion(e.sdkVersion)}initializeOptionsController(e){T.setDebug(e.debug!==!1),T.setEnableWalletConnect(e.enableWalletConnect!==!1),T.setEnableWalletGuide(e.enableWalletGuide!==!1),T.setEnableWallets(e.enableWallets!==!1),T.setEIP6963Enabled(e.enableEIP6963!==!1),T.setEnableNetworkSwitch(e.enableNetworkSwitch!==!1),T.setEnableAuthLogger(e.enableAuthLogger!==!1),T.setCustomRpcUrls(e.customRpcUrls),T.setEnableEmbedded(e.enableEmbedded),T.setAllWallets(e.allWallets),T.setIncludeWalletIds(e.includeWalletIds),T.setExcludeWalletIds(e.excludeWalletIds),T.setFeaturedWalletIds(e.featuredWalletIds),T.setTokens(e.tokens),T.setTermsConditionsUrl(e.termsConditionsUrl),T.setPrivacyPolicyUrl(e.privacyPolicyUrl),T.setCustomWallets(e.customWallets),T.setFeatures(e.features),T.setAllowUnsupportedChain(e.allowUnsupportedChain),T.setUniversalProviderConfigOverride(e.universalProviderConfigOverride),T.setPreferUniversalLinks(e.experimental_preferUniversalLinks),T.setDefaultAccountTypes(e.defaultAccountTypes);const s=W.getPreferredAccountTypes()||{},r={...T.state.defaultAccountTypes,...s};H.setPreferredAccountTypes(r);const i=this.getDefaultMetaData();if(!e.metadata&&i&&(e.metadata=i),T.setMetadata(e.metadata),T.setDisableAppend(e.disableAppend),T.setEnableEmbedded(e.enableEmbedded),T.setSIWX(e.siwx),!e.projectId){Fs.open(Ar.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED,"error");return}if(e.adapters?.find(o=>o.namespace===j.CHAIN.EVM)&&e.siweConfig){if(e.siwx)throw new Error("Cannot set both `siweConfig` and `siwx` options");T.setSIWX(e.siweConfig.mapToSIWX())}}getDefaultMetaData(){return X.isClient()?{name:document.getElementsByTagName("title")?.[0]?.textContent||"",description:document.querySelector('meta[property="og:description"]')?.content||"",url:window.location.origin,icons:[document.querySelector('link[rel~="icon"]')?.href||""]}:null}setUnsupportedNetwork(e){const s=this.getActiveChainNamespace();if(s){const r=Pr.getUnsupportedNetwork(`${s}:${e}`);g.setActiveCaipNetwork(r)}}getDefaultNetwork(){return Pr.getCaipNetworkFromStorage(this.defaultCaipNetwork)}extendCaipNetwork(e,s){return Pr.extendCaipNetwork(e,{customNetworkImageUrls:s.chainImages,projectId:s.projectId})}extendCaipNetworks(e){return Pr.extendCaipNetworks(e.networks,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId})}extendDefaultCaipNetwork(e){const s=e.networks.find(i=>i.id===e.defaultNetwork?.id);return s?Pr.extendCaipNetwork(s,{customNetworkImageUrls:e.chainImages,customRpcUrls:e.customRpcUrls,projectId:e.projectId}):void 0}async disconnectNamespace(e){try{const s=this.getAdapter(e),r=Te.getProvider(e),i=Te.getProviderId(e),{caipAddress:n}=g.getAccountData(e)||{};this.setLoading(!0,e),n&&s?.disconnect&&await s.disconnect({provider:r,providerType:i}),W.removeConnectedNamespace(e),Te.resetChain(e),this.setUser(void 0,e),this.setStatus("disconnected",e),this.setConnectedWalletInfo(void 0,e),q.removeConnectorId(e),g.resetAccount(e),g.resetNetwork(e),this.setLoading(!1,e)}catch(s){throw this.setLoading(!1,e),new Error(`Failed to disconnect chain ${e}: ${s.message}`)}}createClients(){this.connectionControllerClient={connectWalletConnect:async()=>{const e=g.state.activeChain,s=this.getAdapter(e),r=this.getCaipNetwork(e)?.id;if(!s)throw new Error("Adapter not found");const i=await s.connectWalletConnect(r);this.close(),this.setClientId(i?.clientId||null),W.setConnectedNamespaces([...g.state.chains.keys()]),this.chainNamespaces.forEach(n=>{q.setConnectorId(je.CONNECTOR_TYPE_WALLET_CONNECT,n)}),await this.syncWalletConnectAccount()},connectExternal:async({id:e,info:s,type:r,provider:i,chain:n,caipNetwork:o,socialUri:a})=>{const c=g.state.activeChain,l=n||c,u=this.getAdapter(l);if(n&&n!==c&&!o){const m=this.getCaipNetworks().find(f=>f.chainNamespace===n);m&&this.setCaipNetwork(m)}if(!u)throw new Error("Adapter not found");const h=this.getCaipNetwork(l),d=await u.connect({id:e,info:s,type:r,provider:i,socialUri:a,chainId:o?.id||h?.id,rpcUrl:o?.rpcUrls?.default?.http?.[0]||h?.rpcUrls?.default?.http?.[0]});if(!d)return;W.addConnectedNamespace(l),this.syncProvider({...d,chainNamespace:l});const p=H.state.allAccounts,{accounts:w}=p?.length>0?{accounts:[...p]}:await u.getAccounts({namespace:l,id:e});this.setAllAccounts(w,l),this.setStatus("connected",l),this.syncConnectedWalletInfo(l)},reconnectExternal:async({id:e,info:s,type:r,provider:i})=>{const n=g.state.activeChain,o=this.getAdapter(n);o?.reconnect&&(await o?.reconnect({id:e,info:s,type:r,provider:i,chainId:this.getCaipNetwork()?.id}),W.addConnectedNamespace(n),this.syncConnectedWalletInfo(n))},disconnect:async e=>{const s=cI(e);try{const r=await Promise.allSettled(s.map(async([n])=>this.disconnectNamespace(n)));de.resetSend(),Y.resetWcConnection(),await Ni.clearSessions(),q.setFilterByNamespace(void 0);const i=r.filter(n=>n.status==="rejected");if(i.length>0)throw new Error(i.map(n=>n.reason.message).join(", "));W.deleteConnectedSocialProvider(),ke.sendEvent({type:"track",event:"DISCONNECT_SUCCESS",properties:{namespace:e||"all"}})}catch(r){throw new Error(`Failed to disconnect chains: ${r.message}`)}},checkInstalled:e=>e?e.some(s=>!!window.ethereum?.[String(s)]):!!window.ethereum,signMessage:async e=>(await this.getAdapter(g.state.activeChain)?.signMessage({message:e,address:H.state.address,provider:Te.getProvider(g.state.activeChain)}))?.signature||"",sendTransaction:async e=>{const s=e.chainNamespace;if(Ie.SEND_SUPPORTED_NAMESPACES.includes(s)){const r=this.getAdapter(g.state.activeChain),i=Te.getProvider(s);return(await r?.sendTransaction({...e,caipNetwork:this.getCaipNetwork(),provider:i}))?.hash||""}return""},estimateGas:async e=>{if(e.chainNamespace===j.CHAIN.EVM){const s=this.getAdapter(g.state.activeChain),r=Te.getProvider(g.state.activeChain),i=this.getCaipNetwork();if(!i)throw new Error("CaipNetwork is undefined");return(await s?.estimateGas({...e,provider:r,caipNetwork:i}))?.gas||0n}return 0n},getEnsAvatar:async()=>(await this.syncIdentity({address:H.state.address,chainId:Number(this.getCaipNetwork()?.id),chainNamespace:g.state.activeChain}),H.state.profileImage||!1),getEnsAddress:async e=>await Sn.resolveReownName(e),writeContract:async e=>{const s=this.getAdapter(g.state.activeChain),r=this.getCaipNetwork(),i=this.getCaipAddress(),n=Te.getProvider(g.state.activeChain);if(!r||!i)throw new Error("CaipNetwork or CaipAddress is undefined");return(await s?.writeContract({...e,caipNetwork:r,provider:n,caipAddress:i}))?.hash},parseUnits:(e,s)=>this.getAdapter(g.state.activeChain)?.parseUnits({value:e,decimals:s})??0n,formatUnits:(e,s)=>this.getAdapter(g.state.activeChain)?.formatUnits({value:e,decimals:s})??"0",getCapabilities:async e=>await this.getAdapter(g.state.activeChain)?.getCapabilities(e),grantPermissions:async e=>await this.getAdapter(g.state.activeChain)?.grantPermissions(e),revokePermissions:async e=>{const s=this.getAdapter(g.state.activeChain);return s?.revokePermissions?await s.revokePermissions(e):"0x"},walletGetAssets:async e=>await this.getAdapter(g.state.activeChain)?.walletGetAssets(e)??{},updateBalance:e=>{const s=this.getCaipNetwork(e);!s||!H.state.address||this.updateNativeBalance(H.state.address,s?.id,e)}},this.networkControllerClient={switchCaipNetwork:async e=>await this.switchCaipNetwork(e),getApprovedCaipNetworksData:async()=>this.getApprovedCaipNetworksData()},Y.setClient(this.connectionControllerClient)}getApprovedCaipNetworksData(){if(Te.getProviderId(g.state.activeChain)===je.CONNECTOR_TYPE_WALLET_CONNECT){const s=this.universalProvider?.session?.namespaces;return{supportsAllNetworks:this.universalProvider?.session?.peer?.metadata.name==="MetaMask Wallet",approvedCaipNetworkIds:this.getChainsFromNamespaces(s)}}return{supportsAllNetworks:!0,approvedCaipNetworkIds:[]}}async switchCaipNetwork(e){if(!e)return;const s=e.chainNamespace;if(this.getAddressByChainNamespace(e.chainNamespace)){const i=Te.getProvider(s),n=Te.getProviderId(s);if(e.chainNamespace===g.state.activeChain)await this.getAdapter(s)?.switchNetwork({caipNetwork:e,provider:i,providerType:n});else if(this.setCaipNetwork(e),n===je.CONNECTOR_TYPE_WALLET_CONNECT)this.syncWalletConnectAccount();else{const o=this.getAddressByChainNamespace(s);o&&this.syncAccount({address:o,chainId:e.id,chainNamespace:s})}}else this.setCaipNetwork(e)}getChainsFromNamespaces(e={}){return Object.values(e).flatMap(s=>{const r=s.chains||[],i=s.accounts.map(n=>{const{chainId:o,chainNamespace:a}=gs.parseCaipAddress(n);return`${a}:${o}`});return Array.from(new Set([...r,...i]))})}createAdapters(e){return this.createClients(),this.chainNamespaces.reduce((s,r)=>{const i=e?.find(n=>n.namespace===r);return i?(i.construct({namespace:r,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),s[r]=i):s[r]=new MI({namespace:r,networks:this.getCaipNetworks()}),s},{})}async initChainAdapter(e){this.onConnectors(e),this.listenAdapter(e),await this.chainAdapters?.[e].syncConnectors(this.options,this),await this.createUniversalProviderForAdapter(e)}async initChainAdapters(){await Promise.all(this.chainNamespaces.map(async e=>{await this.initChainAdapter(e)}))}onConnectors(e){this.getAdapter(e)?.on("connectors",this.setConnectors.bind(this))}listenAdapter(e){const s=this.getAdapter(e);if(!s)return;const r=W.getConnectionStatus();r==="connected"?this.setStatus("connecting",e):r==="disconnected"?(W.clearAddressCache(),this.setStatus(r,e)):this.setStatus(r,e),s.on("switchNetwork",({address:i,chainId:n})=>{const o=this.getCaipNetworks().find(l=>l.id===n||l.caipNetworkId===n),a=g.state.activeChain===e,c=g.getAccountProp("address",e);if(o){const l=a&&i?i:c;l&&this.syncAccount({address:l,chainId:o.id,chainNamespace:e})}else this.setUnsupportedNetwork(n)}),s.on("disconnect",this.disconnect.bind(this,e)),s.on("connections",i=>{this.setConnections(i,e)}),s.on("pendingTransactions",()=>{const i=H.state.address,n=g.state.activeCaipNetwork;!i||!n?.id||this.updateNativeBalance(i,n.id,n.chainNamespace)}),s.on("accountChanged",({address:i,chainId:n})=>{const o=g.state.activeChain===e;o&&n?this.syncAccount({address:i,chainId:n,chainNamespace:e}):o&&g.state.activeCaipNetwork?.id?this.syncAccount({address:i,chainId:g.state.activeCaipNetwork?.id,chainNamespace:e}):this.syncAccountInfo(i,n,e),this.syncAllAccounts(e)})}async createUniversalProviderForAdapter(e){await this.getUniversalProvider(),this.universalProvider&&this.chainAdapters?.[e]?.setUniversalProvider?.(this.universalProvider)}async syncExistingConnection(){await Promise.allSettled(this.chainNamespaces.map(e=>this.syncNamespaceConnection(e)))}async syncNamespaceConnection(e){try{e===j.CHAIN.EVM&&X.isSafeApp()&&q.setConnectorId(j.CONNECTOR_ID.SAFE,e);const s=q.getConnectorId(e);switch(this.setStatus("connecting",e),s){case j.CONNECTOR_ID.WALLET_CONNECT:await this.syncWalletConnectAccount();break;case j.CONNECTOR_ID.AUTH:break;default:await this.syncAdapterConnection(e)}}catch(s){console.warn("AppKit couldn't sync existing connection",s),this.setStatus("disconnected",e)}}async syncAdapterConnection(e){const s=this.getAdapter(e),r=q.getConnectorId(e),i=this.getCaipNetwork(e),o=q.getConnectors(e).find(a=>a.id===r);try{if(!s||!o)throw new Error(`Adapter or connector not found for namespace ${e}`);if(!i?.id)throw new Error("CaipNetwork not found");const a=await s?.syncConnection({namespace:e,id:o.id,chainId:i.id,rpcUrl:i?.rpcUrls?.default?.http?.[0]});if(a){const c=await s?.getAccounts({namespace:e,id:o.id});c&&c.accounts.length>0?this.setAllAccounts(c.accounts,e):this.setAllAccounts([X.createAccount(e,a.address,"eoa")],e),this.syncProvider({...a,chainNamespace:e}),await this.syncAccount({...a,chainNamespace:e}),this.setStatus("connected",e)}else this.setStatus("disconnected",e)}catch{this.setStatus("disconnected",e)}}async syncWalletConnectAccount(){const e=this.chainNamespaces.map(async s=>{const r=this.getAdapter(s),i=this.universalProvider?.session?.namespaces?.[s]?.accounts||[],n=g.state.activeCaipNetwork?.id,o=i.find(a=>{const{chainId:c}=gs.parseCaipAddress(a);return c===n?.toString()})||i[0];if(o){const a=gs.validateCaipAddress(o),{chainId:c,address:l}=gs.parseCaipAddress(a);if(Te.setProviderId(s,je.CONNECTOR_TYPE_WALLET_CONNECT),this.caipNetworks&&g.state.activeCaipNetwork&&r?.namespace!==j.CHAIN.EVM){const u=r?.getWalletConnectProvider({caipNetworks:this.getCaipNetworks(),provider:this.universalProvider,activeCaipNetwork:g.state.activeCaipNetwork});Te.setProvider(s,u)}else Te.setProvider(s,this.universalProvider);q.setConnectorId(j.CONNECTOR_ID.WALLET_CONNECT,s),W.addConnectedNamespace(s),this.syncWalletConnectAccounts(s),await this.syncAccount({address:l,chainId:c,chainNamespace:s})}else this.setStatus("disconnected",s);this.syncConnectedWalletInfo(s),await g.setApprovedCaipNetworksData(s)});await Promise.all(e)}syncWalletConnectAccounts(e){const s=this.universalProvider?.session?.namespaces?.[e]?.accounts?.map(r=>{const{address:i}=gs.parseCaipAddress(r);return i}).filter((r,i,n)=>n.indexOf(r)===i);s&&this.setAllAccounts(s.map(r=>X.createAccount(e,r,e==="bip122"?"payment":"eoa")),e)}syncProvider({type:e,provider:s,id:r,chainNamespace:i}){Te.setProviderId(i,e),Te.setProvider(i,s),q.setConnectorId(r,i)}async syncAllAccounts(e){const s=q.getConnectorId(e);if(!s)return;const i=await this.getAdapter(e)?.getAccounts({namespace:e,id:s});i&&i.accounts.length>0&&this.setAllAccounts(i.accounts,e)}async syncAccount(e){const s=e.chainNamespace===g.state.activeChain,r=g.getCaipNetworkByNamespace(e.chainNamespace,e.chainId),{address:i,chainId:n,chainNamespace:o}=e,{chainId:a}=W.getActiveNetworkProps(),c=n||a,l=g.state.activeCaipNetwork?.name===j.UNSUPPORTED_NETWORK_NAME,u=g.getNetworkProp("supportsAllNetworks",o);if(this.setStatus("connected",o),!(l&&!u)&&c){let h=this.getCaipNetworks().find(w=>w.id.toString()===c.toString()),d=this.getCaipNetworks().find(w=>w.chainNamespace===o);if(!u&&!h&&!d){const w=this.getApprovedCaipNetworkIds()||[],m=w.find(y=>gs.parseCaipNetworkId(y)?.chainId===c.toString()),f=w.find(y=>gs.parseCaipNetworkId(y)?.chainNamespace===o);h=this.getCaipNetworks().find(y=>y.caipNetworkId===m),d=this.getCaipNetworks().find(y=>y.caipNetworkId===f||"deprecatedCaipNetworkId"in y&&y.deprecatedCaipNetworkId===f)}const p=h||d;p?.chainNamespace===g.state.activeChain?T.state.enableNetworkSwitch&&!T.state.allowUnsupportedChain&&g.state.activeCaipNetwork?.name===j.UNSUPPORTED_NETWORK_NAME?g.showUnsupportedChainUI():this.setCaipNetwork(p):s||r&&this.setCaipNetworkOfNamespace(r,o),this.syncConnectedWalletInfo(o),Ua.isLowerCaseMatch(i,H.state.address)||this.syncAccountInfo(i,p?.id,o),s?await this.syncBalance({address:i,chainId:p?.id,chainNamespace:o}):await this.syncBalance({address:i,chainId:r?.id,chainNamespace:o})}}async syncAccountInfo(e,s,r){const i=this.getCaipAddress(r),n=s||i?.split(":")[1];if(!n)return;const o=`${r}:${n}:${e}`;this.setCaipAddress(o,r),await this.syncIdentity({address:e,chainId:n,chainNamespace:r})}async syncReownName(e,s){try{const r=await this.getReownName(e);if(r[0]){const i=r[0];this.setProfileName(i.name,s)}else this.setProfileName(null,s)}catch{this.setProfileName(null,s)}}syncConnectedWalletInfo(e){const s=q.getConnectorId(e),r=Te.getProviderId(e);if(r===je.CONNECTOR_TYPE_ANNOUNCED||r===je.CONNECTOR_TYPE_INJECTED){if(s){const i=this.getConnectors().find(n=>n.id===s);if(i){const{info:n,name:o,imageUrl:a}=i,c=a||this.getConnectorImage(i);this.setConnectedWalletInfo({name:o,icon:c,...n},e)}}}else if(r===je.CONNECTOR_TYPE_WALLET_CONNECT){const i=Te.getProvider(e);i?.session&&this.setConnectedWalletInfo({...i.session.peer.metadata,name:i.session.peer.metadata.name,icon:i.session.peer.metadata.icons?.[0]},e)}else if(s&&s===j.CONNECTOR_ID.COINBASE){const i=this.getConnectors().find(n=>n.id===j.CONNECTOR_ID.COINBASE);this.setConnectedWalletInfo({name:"Coinbase Wallet",icon:this.getConnectorImage(i)},e)}}async syncBalance(e){!mu.getNetworksByNamespace(this.getCaipNetworks(),e.chainNamespace).find(r=>r.id.toString()===e.chainId?.toString())||!e.chainId||await this.updateNativeBalance(e.address,e.chainId,e.chainNamespace)}async ready(){await this.readyPromise}async updateNativeBalance(e,s,r){const i=this.getAdapter(r),n=g.getCaipNetworkByNamespace(r,s);if(i){const o=await i.getBalance({address:e,chainId:s,caipNetwork:n,tokens:this.options.tokens});return this.setBalance(o.balance,o.symbol,r),o}}async initializeUniversalAdapter(){const e=hI.createLogger((r,...i)=>{r&&this.handleAlertError(r),console.error(...i)}),s={projectId:this.options?.projectId,metadata:{name:this.options?.metadata?this.options?.metadata.name:"",description:this.options?.metadata?this.options?.metadata.description:"",url:this.options?.metadata?this.options?.metadata.url:"",icons:this.options?.metadata?this.options?.metadata.icons:[""]},logger:e};T.setManualWCControl(!!this.options?.manualWCControl),this.universalProvider=this.options.universalProvider??await aI.init(s),this.listenWalletConnect()}listenWalletConnect(){this.universalProvider&&(this.universalProvider.on("display_uri",e=>{Y.setUri(e)}),this.universalProvider.on("connect",Y.finalizeWcConnection),this.universalProvider.on("disconnect",()=>{this.chainNamespaces.forEach(e=>{this.resetAccount(e)}),Y.resetWcConnection()}),this.universalProvider.on("chainChanged",e=>{const s=this.getCaipNetworks().find(i=>i.id==e),r=this.getCaipNetwork();if(!s){this.setUnsupportedNetwork(e);return}r?.id!==s?.id&&this.setCaipNetwork(s)}),this.universalProvider.on("session_event",e=>{if(Sn.isSessionEventData(e)){const{name:s,data:r}=e.params.event;s==="accountsChanged"&&Array.isArray(r)&&X.isCaipAddress(r[0])&&this.syncAccount(gs.parseCaipAddress(r[0]))}}))}createUniversalProvider(){return!this.universalProviderInitPromise&&X.isClient()&&this.options?.projectId&&(this.universalProviderInitPromise=this.initializeUniversalAdapter()),this.universalProviderInitPromise}async getUniversalProvider(){if(!this.universalProvider)try{await this.createUniversalProvider()}catch(e){ke.sendEvent({type:"error",event:"INTERNAL_SDK_ERROR",properties:{errorType:"UniversalProviderInitError",errorMessage:e instanceof Error?e.message:"Unknown",uncaught:!1}}),console.error("AppKit:getUniversalProvider - Cannot create provider",e)}return this.universalProvider}handleAlertError(e){const s=Object.entries(Ar.UniversalProviderErrors).find(([,{message:a}])=>e.message.includes(a)),[r,i]=s??[],{message:n,alertErrorKey:o}=i??{};if(r&&n&&!this.reportedAlertErrors[r]){const a=Ar.ALERT_ERRORS[o];a&&(Fs.open(a,"error"),this.reportedAlertErrors[r]=!0)}}getAdapter(e){if(e)return this.chainAdapters?.[e]}createAdapter(e){if(!e)return;const s=e.namespace;if(!s)return;this.createClients();const r=e;r.namespace=s,r.construct({namespace:s,projectId:this.options?.projectId,networks:this.getCaipNetworks()}),this.chainNamespaces.includes(s)||this.chainNamespaces.push(s),this.chainAdapters&&(this.chainAdapters[s]=r)}async open(e){if(await this.injectModalUi(),e?.uri&&Y.setUri(e.uri),e?.arguments)switch(e?.view){case"Swap":return Ge.open({...e,data:{swap:e.arguments}})}return Ge.open(e)}async close(){await this.injectModalUi(),Ge.close()}setLoading(e,s){Ge.setLoading(e,s)}async disconnect(e){await Y.disconnect(e)}getSIWX(){return T.state.siwx}getError(){return""}getChainId(){return g.state.activeCaipNetwork?.id}async switchNetwork(e){const s=this.getCaipNetworks().find(r=>r.id===e.id);if(!s){Fs.open(Ar.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND,"error");return}await g.switchActiveNetwork(s)}getWalletProvider(){return g.state.activeChain?Te.state.providers[g.state.activeChain]:null}getWalletProviderType(){return Te.getProviderId(g.state.activeChain)}subscribeProviders(e){return Te.subscribeProviders(e)}getThemeMode(){return Et.state.themeMode}getThemeVariables(){return Et.state.themeVariables}setThemeMode(e){Et.setThemeMode(e),Cd(Et.state.themeMode)}setTermsConditionsUrl(e){T.setTermsConditionsUrl(e)}setPrivacyPolicyUrl(e){T.setPrivacyPolicyUrl(e)}setThemeVariables(e){Et.setThemeVariables(e),RI(Et.state.themeVariables)}subscribeTheme(e){return Et.subscribe(e)}getWalletInfo(){return H.state.connectedWalletInfo}getAccount(e){const s=q.getAuthConnector(e),r=g.getAccountData(e),i=g.state.activeChain,n=W.getConnectedConnectorId(e||i);if(r)return{allAccounts:r.allAccounts,caipAddress:r.caipAddress,address:X.getPlainAddress(r.caipAddress),isConnected:!!r.caipAddress,status:r.status,embeddedWalletInfo:s&&n===j.CONNECTOR_ID.AUTH?{user:r.user?{...r.user,username:W.getConnectedSocialUsername()}:void 0,authProvider:r.socialProvider||"email",accountType:r.preferredAccountTypes?.[e||i],isSmartAccountDeployed:!!r.smartAccountDeployed}:void 0}}subscribeAccount(e,s){const r=()=>{const i=this.getAccount(s);i&&e(i)};s?g.subscribeChainProp("accountState",r,s):g.subscribe(r),q.subscribe(r)}subscribeNetwork(e){return g.subscribe(({activeCaipNetwork:s})=>{e({caipNetwork:s,chainId:s?.id,caipNetworkId:s?.caipNetworkId})})}subscribeWalletInfo(e){return H.subscribeKey("connectedWalletInfo",e)}subscribeShouldUpdateToAddress(e){H.subscribeKey("shouldUpdateToAddress",e)}subscribeCaipNetworkChange(e){g.subscribeKey("activeCaipNetwork",e)}getState(){return Ss.state}subscribeState(e){return Ss.subscribe(e)}showErrorMessage(e){Ft.showError(e)}showSuccessMessage(e){Ft.showSuccess(e)}getEvent(){return{...ke.state}}subscribeEvents(e){return ke.subscribe(e)}replace(e){ie.replace(e)}redirect(e){ie.push(e)}popTransactionStack(e){ie.popTransactionStack(e)}isOpen(){return Ge.state.open}isTransactionStackEmpty(){return ie.state.transactionStack.length===0}static getInstance(){return this.instance}updateFeatures(e){T.setFeatures(e)}updateRemoteFeatures(e){T.setRemoteFeatures(e)}updateOptions(e){const r={...T.state||{},...e};T.setOptions(r)}setConnectMethodsOrder(e){T.setConnectMethodsOrder(e)}setWalletFeaturesOrder(e){T.setWalletFeaturesOrder(e)}setCollapseWallets(e){T.setCollapseWallets(e)}setSocialsOrder(e){T.setSocialsOrder(e)}getConnectMethodsOrder(){return ga.getConnectOrderMethod(T.state.features,q.getConnectors())}addNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);const r=this.extendCaipNetwork(s,this.options);this.getCaipNetworks().find(i=>i.id===r.id)||g.addNetwork(r)}removeNetwork(e,s){if(this.chainAdapters&&!this.chainAdapters[e])throw new Error(`Adapter for namespace ${e} doesn't exist`);this.getCaipNetworks().find(i=>i.id===s)&&g.removeNetwork(e,s)}}let du=!1;class Nd extends qI{async open(e){q.isConnected()||await super.open(e)}async close(){await super.close(),this.options.manualWCControl&&Y.finalizeWcConnection()}async syncIdentity(e){return Promise.resolve()}async syncBalance(e){return Promise.resolve()}async injectModalUi(){if(!du&&X.isClient()){if(await Ro(()=>import("./basic-DoZtdADf.js"),__vite__mapDeps([5,6,1,2,3,4])),await Ro(()=>import("./w3m-modal-CH0h68TV.js"),__vite__mapDeps([7,6,1,2,3,4])),!document.querySelector("w3m-modal")){const s=document.createElement("w3m-modal");!T.state.disableAppend&&!T.state.enableEmbedded&&document.body.insertAdjacentElement("beforeend",s)}du=!0}}}const FI="1.7.8";function WI(t){return new Nd({...t,basic:!0,sdkVersion:`html-core-${FI}`})}const SN=Object.freeze(Object.defineProperty({__proto__:null,AppKit:Nd,createAppKit:WI},Symbol.toStringTag,{value:"Module"}));export{V as A,pI as B,q as C,H as D,ke as E,IN as F,hN as G,wg as H,hc as I,Ku as J,ag as K,yg as L,Ge as M,dN as N,T as O,uN as P,Wn as Q,ie as R,W as S,Et as T,pN as U,fN as V,ga as W,SN as X,An as a,EN as b,X as c,Nn as d,_N as e,vu as f,Y as g,j as h,Lr as i,g as j,qt as k,Ft as l,Ie as m,Ke as n,AN as o,md as p,Gr as q,NN as r,Oe as s,St as t,ma as u,it as v,CN as w,nt as x,Ni as y,Fs as z};